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

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

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
Build a Git Commit Analyzer with Gemma 4 31B and a 256K Context Window
Jubin Soni · 2026-05-09 · via DEV Community

This is a submission for the Gemma 4 Challenge: Build with Gemma 4

Most developers reach for an LLM when they need code completion or a chatbot. This article is about something more useful and less obvious: feeding your entire sprint's git history to Gemma 4 31B — diffs, commit messages, authors and all — and getting back structured, actionable analysis of what actually changed and why it might matter.

The 31B Dense model's 256K context window is the key enabler here. It means you can pass tens of thousands of lines of patch output in a single prompt and ask the model to reason across the whole thing — not chunk-and-summarize, but genuinely cross-reference commits, spot patterns, and flag risk. That's a qualitatively different capability from what a smaller model or an older Gemma generation could provide.

By the end of this guide you'll have a working Python CLI tool that:

  • Shells out to git log --patch to collect a commit range
  • Sends the full diff to Gemma 4 31B via the Gemini API (free tier in Google AI Studio)
  • Returns a structured JSON report with change summaries, risk flags, and a draft changelog
  • Optionally writes a Markdown changelog file

Why Gemma 4 31B Is the Right Model for This

Three specific properties make the 31B Dense the correct pick here — not the 26B MoE, not the edge models.

256K context window. A week's worth of commits on a mid-size codebase generates 20,000–80,000 tokens of patch text. The 31B handles that in a single pass. Chunking and summarizing separately loses cross-commit signal: the model can't notice that a refactor in commit 3 introduced the same variable name collision that commit 7 later fixed.

Maximum quality per query. The 31B Dense is the highest-accuracy model in the Gemma 4 family. For code analysis you care about precision — a false positive risk flag wastes a senior engineer's time, and a false negative ships a bug. You're making one expensive call per analysis run, so raw quality beats throughput.

Native structured output. Gemma 4 has first-class support for function calling and structured JSON output. The analyzer requests a strict JSON schema and the model reliably returns it — no fragile string parsing required.

The 26B MoE is the right choice if you're building something that calls the model thousands of times per day and want cost efficiency. This tool calls it once per analysis run and prioritizes signal quality, so the Dense wins.


Prerequisites

  • Python 3.10+
  • A Google AI Studio API key (free — get one here)
  • A git repository to analyze
  • The google-generativeai Python SDK
pip install google-generativeai

Enter fullscreen mode Exit fullscreen mode

Set your API key as an environment variable:

export GEMINI_API_KEY="your-key-here"

Enter fullscreen mode Exit fullscreen mode


Step 1: Collect the Git Diff

The first job is gathering the raw patch data. We use git log --patch with a commit range and pipe the output to a string. We also collect structured commit metadata separately so the model has author and timestamp context alongside the diff.

import subprocess
import sys

def collect_git_history(repo_path: str, since: str = "1 week ago", until: str = "HEAD") -> tuple[str, list[dict]]:
    """
    Returns (full_patch_text, list_of_commit_metadata).
    `since` accepts anything git understands: '7 days ago', 'v1.2.3', a SHA, etc.
    """
    # Collect the full unified diff
    patch_result = subprocess.run(
        ["git", "log", "--patch", "--no-merges", f"--since={since}", f"--until={until}",
         "--pretty=format:COMMIT: %H%nAuthor: %an <%ae>%nDate: %ci%nMessage: %s%n"],
        cwd=repo_path,
        capture_output=True,
        text=True,
        check=True
    )

    # Collect lightweight metadata for the summary header
    meta_result = subprocess.run(
        ["git", "log", "--no-merges", f"--since={since}", f"--until={until}",
         "--pretty=format:%H|%an|%ci|%s"],
        cwd=repo_path,
        capture_output=True,
        text=True,
        check=True
    )

    commits = []
    for line in meta_result.stdout.strip().splitlines():
        if not line:
            continue
        sha, author, date, *msg_parts = line.split("|")
        commits.append({
            "sha": sha[:8],
            "author": author,
            "date": date,
            "message": "|".join(msg_parts)
        })

    return patch_result.stdout, commits

Enter fullscreen mode Exit fullscreen mode

A week of commits on a real codebase might be 40,000–100,000 tokens. We'll let the model handle the full text — that's exactly what the 256K window is for.


Step 2: Build the Prompt

The prompt does three things: gives the model its role and output contract, defines the JSON schema it must return, and passes the raw git history.

SYSTEM_PROMPT = """You are a senior staff engineer performing a structured code review
of a git commit history. Your job is to analyse the provided patch text and return a
single JSON object — nothing else, no markdown fences, no explanation outside the JSON.

The JSON object must match this schema exactly:

{
  "summary": "2-3 sentence plain-English summary of the overall change set",
  "changed_areas": [
    {
      "path": "path/to/file_or_directory",
      "change_type": "added | modified | deleted | renamed",
      "description": "what changed and why it likely changed"
    }
  ],
  "risk_flags": [
    {
      "severity": "low | medium | high",
      "area": "file or component",
      "reason": "specific, concrete reason this change carries risk"
    }
  ],
  "patterns": [
    "notable cross-commit pattern, refactor theme, or repeated change"
  ],
  "changelog_entry": "A polished, user-facing changelog entry in Markdown. Use ## [Unreleased] as the heading. Group under Added, Changed, Fixed, Removed as appropriate."
}

Be specific. Do not flag risk without a concrete reason tied to the actual diff.
Do not invent changes that are not present in the patch text."""


def build_prompt(patch_text: str, commits: list[dict]) -> str:
    commit_count = len(commits)
    authors = list({c["author"] for c in commits})
    date_range = f"{commits[-1]['date'][:10]} to {commits[0]['date'][:10]}" if commits else "unknown"

    header = (
        f"ANALYSIS REQUEST\n"
        f"Commits: {commit_count}\n"
        f"Authors: {', '.join(authors)}\n"
        f"Date range: {date_range}\n\n"
        f"FULL PATCH TEXT FOLLOWS\n"
        f"{'='*60}\n"
    )

    return header + patch_text

Enter fullscreen mode Exit fullscreen mode

The system prompt enforces a strict schema so we can parse the response with json.loads — no regex, no fallbacks. One of Gemma 4's standout improvements over Gemma 3 is how reliably it follows structured output instructions at this schema complexity.


Step 3: Call Gemma 4 31B

We use the google-generativeai SDK with gemma-4-31b-it (the instruction-tuned variant — always use IT for structured task completion).

import google.generativeai as genai
import json
import os

def analyze_with_gemma(patch_text: str, commits: list[dict]) -> dict:
    genai.configure(api_key=os.environ["GEMINI_API_KEY"])

    model = genai.GenerativeModel(
        model_name="gemma-4-31b-it",
        system_instruction=SYSTEM_PROMPT,
        generation_config=genai.GenerationConfig(
            temperature=0.2,      # Low temperature for consistent structured output
            top_p=0.9,
            max_output_tokens=4096,
        )
    )

    prompt = build_prompt(patch_text, commits)

    print(f"Sending {len(prompt.split()):,} words to Gemma 4 31B...", file=sys.stderr)

    response = model.generate_content(prompt)

    raw = response.text.strip()

    # Strip markdown fences if the model adds them despite instructions
    if raw.startswith("```

"):
        raw = raw.split("

```")[1]
        if raw.startswith("json"):
            raw = raw[4:]

    return json.loads(raw)

Enter fullscreen mode Exit fullscreen mode

Temperature at 0.2 keeps the output deterministic and schema-compliant. For creative changelog prose you could nudge it to 0.4 — but for risk flags you want the model to be conservative and consistent.


Step 4: Format and Output the Report

from datetime import datetime

def print_report(analysis: dict, commits: list[dict]) -> None:
    print("\n" + "="*60)
    print("GIT HISTORY ANALYSIS — Gemma 4 31B")
    print("="*60)
    print(f"\nCommits analysed: {len(commits)}")
    print(f"\nSUMMARY\n{analysis['summary']}\n")

    if analysis.get("risk_flags"):
        print("RISK FLAGS")
        for flag in sorted(analysis["risk_flags"], key=lambda f: {"high": 0, "medium": 1, "low": 2}[f["severity"]]):
            icon = {"high": "🔴", "medium": "🟡", "low": "🟢"}[flag["severity"]]
            print(f"  {icon} [{flag['severity'].upper()}] {flag['area']}")
            print(f"     {flag['reason']}")
        print()

    if analysis.get("patterns"):
        print("PATTERNS DETECTED")
        for p in analysis["patterns"]:
            print(f"{p}")
        print()

    print("CHANGED AREAS")
    for area in analysis.get("changed_areas", []):
        print(f"  [{area['change_type'].upper():8}] {area['path']}")
        print(f"             {area['description']}")
    print()


def write_changelog(analysis: dict, output_path: str) -> None:
    entry = analysis.get("changelog_entry", "")
    if not entry:
        return

    # Inject today's date if the entry has a placeholder
    entry = entry.replace("[Unreleased]", f"[Unreleased] — {datetime.today().strftime('%Y-%m-%d')}")

    with open(output_path, "w") as f:
        f.write(entry + "\n")

    print(f"Changelog written to {output_path}", file=sys.stderr)

Enter fullscreen mode Exit fullscreen mode


Step 5: Wire It Together as a CLI

import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Analyse a git commit range with Gemma 4 31B"
    )
    parser.add_argument("repo", help="Path to git repository")
    parser.add_argument("--since", default="1 week ago",
                        help="Start of range (default: '1 week ago'). Accepts any git date or ref.")
    parser.add_argument("--until", default="HEAD",
                        help="End of range (default: HEAD)")
    parser.add_argument("--changelog", default=None,
                        help="Write changelog entry to this file")
    parser.add_argument("--json", dest="json_out", default=None,
                        help="Write full JSON report to this file")
    args = parser.parse_args()

    patch_text, commits = collect_git_history(args.repo, args.since, args.until)

    if not commits:
        print("No commits found in the specified range.", file=sys.stderr)
        sys.exit(0)

    analysis = analyze_with_gemma(patch_text, commits)
    print_report(analysis, commits)

    if args.changelog:
        write_changelog(analysis, args.changelog)

    if args.json_out:
        with open(args.json_out, "w") as f:
            json.dump(analysis, f, indent=2)
        print(f"Full JSON report written to {args.json_out}", file=sys.stderr)


if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode


Running It

Analyse the last week of commits in the current repo:

python git_analyzer.py . --since "1 week ago"

Enter fullscreen mode Exit fullscreen mode

Analyse a specific SHA range and write a changelog:

python git_analyzer.py /path/to/repo \
  --since v1.4.0 \
  --until v1.5.0 \
  --changelog CHANGELOG.md \
  --json report.json

Enter fullscreen mode Exit fullscreen mode

Analyse a single sprint (two-week window):

python git_analyzer.py . --since "14 days ago" --changelog CHANGELOG.md

Enter fullscreen mode Exit fullscreen mode


Sample Output

Here's an abbreviated example of what the tool produces on a real project:

============================================================
GIT HISTORY ANALYSIS — Gemma 4 31B
============================================================

Commits analysed: 23

SUMMARY
This sprint focused on migrating the authentication layer from session
cookies to JWTs, with supporting changes to the user model and API
middleware. Three unrelated bug fixes were included. No database
migrations were added despite schema-adjacent changes in user.py.

RISK FLAGS
  🔴 [HIGH]  src/auth/middleware.py
             Token expiry is set to 0 in the new JWT config, which
             disables expiry entirely. This appears unintentional given
             the surrounding comments referencing a 24h TTL.
  🟡 [MEDIUM] src/models/user.py
             The `last_login` field is now written in two places with
             different timezone handling (UTC in the old path, local
             time in the new one). Cross-commit inconsistency introduced
             in commits a3f1cc and 9d02bb.

PATTERNS DETECTED
  • JWT migration touched 11 files across 8 commits — no single
    atomic commit, suggesting iterative discovery during implementation
  • Four separate commits add logging statements then remove them,
    indicating debug churn that could have been a feature branch

CHANGED AREAS
  [MODIFIED ] src/auth/middleware.py
               Core auth middleware rewritten to validate Bearer tokens
               instead of reading from session. Old session path removed.
  [MODIFIED ] src/models/user.py
               Added jwt_secret field; last_login timezone handling changed
  [ADDED    ] src/auth/token.py
               New module for JWT encode/decode with HS256
  ...

Enter fullscreen mode Exit fullscreen mode

The risk flag about token expiry being set to 0 is real — this is the kind of thing that slips through human PR review precisely because it looks like a config value, not a bug. The cross-commit inconsistency flag is only possible because the model reasoned across all 23 commits simultaneously rather than reviewing each in isolation.


Context Window Headroom

The 256K window on Gemma 4 31B means you have significant headroom. At roughly 3 characters per token, the practical limits look like this:

Scenario Approx. tokens Fits in 256K?
1 day of commits, small team ~5,000
1 sprint (2 weeks), small team ~40,000
Full quarter, mid-size team ~180,000
1 year of active development ~500,000+ ❌ use --since to segment

For very large repos, segment by component directory using git log -- path/to/subdir rather than trying to fit everything.


Where to Take This Next

GitHub Action. Trigger the analyzer on each PR, post the risk flags as a PR comment, and block merge if any high severity flags are found. One YAML file and a secrets entry gets you there.

Slack/Teams digest. Run on a cron, pipe the changelog entry to a webhook. Engineering managers get a plain-English weekly summary without reading git.

Fine-tuning. If your team consistently disagrees with certain risk classifications, collect those corrections as a small labeled dataset and fine-tune the model on Vertex AI or Colab. Gemma 4's Apache 2.0 license means there are no restrictions on using it as a fine-tuning base for internal tools.

Multi-repo analysis. Pass diffs from multiple services in the same prompt window. The 256K context means you can compare what changed across your backend, frontend, and infra repos in the same analysis run.


Why This Matters

The git history is one of the most information-dense artifacts a software team produces, and it's almost entirely ignored outside of git blame. Gemma 4 31B's context window is large enough to treat a sprint's history as a single document rather than a stream of individual events.

That shift in granularity changes what the model can do: it can notice that a change made on Tuesday was partially reverted on Thursday, that two different authors independently touched the same configuration key, or that a "refactor" commit introduced a subtle behavioral change buried in 400 lines of renames.

None of that is possible when each commit is reviewed in isolation.


Resources