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

推荐订阅源

D
Docker
爱范儿
爱范儿
人人都是产品经理
人人都是产品经理
博客园 - 司徒正美
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
量子位
罗磊的独立博客
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
小众软件
小众软件
C
Cybersecurity and Infrastructure Security Agency CISA
Cyberwarzone
Cyberwarzone
大猫的无限游戏
大猫的无限游戏
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
雷峰网
雷峰网
Simon Willison's Weblog
Simon Willison's Weblog
The Cloudflare Blog
博客园 - 三生石上(FineUI控件)
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园_首页
博客园 - 叶小钗
V
Vulnerabilities – Threatpost
T
The Exploit Database - CXSecurity.com
T
Tailwind CSS Blog
IT之家
IT之家
博客园 - 聂微东
Spread Privacy
Spread Privacy
V2EX - 技术
V2EX - 技术
S
Security Affairs
宝玉的分享
宝玉的分享
V
V2EX
C
Cisco Blogs
博客园 - Franky
美团技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
S
Securelist
J
Java Code Geeks
Webroot Blog
Webroot Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Proofpoint News Feed
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
NISL@THU
NISL@THU
WordPress大学
WordPress大学
W
WeLiveSecurity
T
Threatpost
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志

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
Prompts for AI Commits in HagiCode: Design Rationale and Implementation Breakdown
Hagicode · 2026-06-20 · via DEV Community

Prompts for AI Commits in HagiCode: Design Rationale and Implementation Breakdown

When you dump a bunch of messy changes to AI and ask it to help you commit, what exactly is the prompt being sent to the model behind the scenes? Why is the prompt written that way? This article breaks down the actual prompt that drives "AI commits" in HagiCode for you to see.

Background

Using AI to assist with development—after a full day of coding, it can be quite exhausting. You've accumulated a pile of uncommitted changes: config files, documentation, business logic, test cases all mixed together—just looking at it gives you a headache. Manually grouping them, hand-writing commit messages that conform to standards, then switching branches and pushing—these "cleanup tasks" alone can eat up half an hour.

Naturally, this gives rise to a demand—can we just throw all uncommitted changes at AI at once, let it analyze, group, write messages, and even directly commit + push?

The idea is good, but there are plenty of pitfalls along the way. AI might only change --author without changing Committer, resulting in the correct author but wrong committer in commit history—a jarring inconsistency. It might write flashy messages that don't align with your repository's style at all. It might arbitrarily switch to the main branch and mess things up. It might miss Co-Authored-By or recklessly add Signed-off-by, triggering compliance issues.

These pitfalls are lessons learned the hard way. To address these pain points, we've made "AI commit" a parameterized Agent task contract. What this contract looks like and why it's designed this way is what this article aims to clarify.

About HagiCode

The solution shared in this article comes from our practice in the HagiCode project. HagiCode is an AI code assistant focused on developer workflows, turning daily tasks like Git commits, code reviews, and build deployments into AI-participated tasks. The prompt system broken down below is the one actually running in HagiCode's backend. Ultimately, it's just about handing off those tedious "cleanup tasks" to AI.

The True Form of Prompts: Templates Plus Metadata, Not a Hardcoded String

Many people think "prompts" are just a piece of hardcoded natural language to throw at a model. But HagiCode's approach is completely different.

The actual prompt driving "AI commits" is called auto-compose-commit, corresponding to PromptScenario.AutoComposeCommit in the code. It's located under repos/hagicode-core/src/PCode.Web/Resources/Prompts/ with this structure:

Resources/Prompts/
├── auto-compose-commit.en-US.hbs     # English Handlebars template
├── auto-compose-commit.en-US.json    # English metadata (parameter schema, version, tags)
├── auto-compose-commit.zh-CN.hbs     # Chinese template
└── auto-compose-commit.zh-CN.json    # Chinese metadata

In other words, a prompt is a combination of one Handlebars template + one JSON metadata, flattened into multiple sets by locale.

Why split it this way? There are several considerations behind it.

First, metadata decoupled from prompt body. JSON describes the parameter schema—parameter names, types, whether required, default values. .hbs only handles "how to say it." This way, the frontend can automatically render the correct input form based on JSON without knowing the template content: Git identity selector, Co-Authored-By mode, target branch strategy, whether to push... these controls are all driven by JSON.

Second, multi-language flattened, not using i18n keys for translation. Each locale has a complete set of .hbs + .json, avoiding "translation key drift." Different languages don't just substitute words—grouping examples and command examples can also be localized. Commit habits in Chinese and English repositories are inherently different; forcing them into one template then translating feels awkward.

Third, migrating from Scriban to Handlebars was for performance. HandlebarsTemplateRenderer chose Handlebars.Net because it can "compile templates directly to IL bytecode," which is much faster than interpretation. During migration, an interesting compatibility fix was made: replacing True/False with true/false in render results to match old Scriban boolean output habits—without paying attention to such details, old tests would all fail.

Five Key Decisions Behind This Prompt Structure

Looking at auto-compose-commit.zh-CN.hbs, the skeleton roughly is:

Non-interactive mode instructions
├── <task>            Task definition: analyze changes, intelligent grouping, multiple commits
├── <context>         Context: projectPath + push control + target branch control
├── <working_directory>
├── <git_profile>     Identity: Author plus Committer dual-write
├── <tools>           Tool whitelist
├── <requirements>    Hard requirements (branch, grouping, Co-Authored-By, Signed-off-by, Conventional Commits)
├── <historical_format_analysis>  Historical consistency
├── <constraints>     Constraints (prohibit reset, ignore .gitignore)
├── <workflow>        Step-by-step execution flow
├── <output_format>   Strict `---` separated output
└── <final_instruction>

Below, let's expand on five points that best reflect the design intent.

Decision One: Execute Directly, Don't Just Generate a Plan

The prompt repeatedly emphasizes one sentence: Use Git commands directly to execute each commit, don't return a plan, operate directly.

This is the fundamental difference between "Auto Compose Commit" and earlier solutions. The early ai-git-commit-message-generator (corresponding to the ai-commit-message-generation spec in OpenSpec) only did one thing: call a POST /api/git/generate-commit-message, return a commit message string, and let the user manually commit the rest.

But auto-compose-commit is different. It's an Agent automated task. The model must call Bash(git:*) tools itself and run the full chain of add → commit → push. This difference determines the tone of the entire prompt—it can't just describe "what kind of message to write," but also specify "what workflow to follow, what tools to use, and what to do when errors occur."

Decision Two: Why Git Identity is So Verbose

There's a large section in <git_profile> and <requirements> explaining Author versus Committer, which looks redundant at first glance:

- `--author="Name <email>"` only modifies Author
- `git -c user.name="Name" -c user.email="email" commit ...` only modifies Committer for this command
- For each generated commit, you must set both Author and Committer to the selected identity
- Preferred command form:
  git -c user.name="..." -c user.email="..." commit --author="... <...>" ...

This actually comes from real pitfalls learned. Git commits have two identity fields. Models easily only change --author, leaving Committer as the global config identity. In commit history, "author is correct but committer is wrong"—visually jarring. So the prompt directly provides the preferred command template and requires the model to self-check using git log --format=fuller -1.

By analogy, this is like shipping a package—"sender" and "actual handler" are two different forms. You only write your name on one form, the other still has the company name printed—the package ships, but records don't match, ultimately feeling awkward.

Decision Three: Grouping Decision Tree Plus Historical Consistency

Models excel at "free improvisation," but in commit grouping, this is often a disaster. So the prompt provides a clear decision tree: config files as one group, docs as another, same-module code changes merged, cross-module changes handled case-by-case. It also includes positive examples, like src/auth/login.ts plus auth.service.ts should go into the same commit.

More critical is the <historical_format_analysis> section. It requires the model to:

  1. Use git log -n 15 --pretty=format:"%H|%s|%b%n---%n" to get recent commit history
  2. Analyze structural patterns, language patterns, common types, special formats
  3. Generate commit messages following detected patterns

In other words, the model can't write however it wants—it must align with the target repository's existing style first. HagiCode Mono main repo uses English + Conventional Commits, certain sub-repos use Chinese paragraph style—AI must follow local customs. This capability corresponds to archived proposal 2026-02-23-auto-commit-compose-history-consistency-optimization, an optimization added later. After all, nobody wants their commit history to look like a hodgepodge.

Decision Four: Conditional Rendering for Co-Authored-By and Signed-off-by

The prompt has many nested {{#if}} statements, deciding whether to add trailers based on runtime parameters:

  • When coAuthoredByIsNone, don't add Co-Authored-By at all
  • When coAuthoredByIsCustom, use the user-provided custom trailer
  • When signedOffByEnabled plus gitProfileName, add Signed-off-by; missing identity must error, not fabricate one

Trailers involve attribution and compliance (DCO sign-off), must be explicitly controlled by users, never left to model discretion. HagiCode has implemented proposals like git-commit-coauthor-standardization and ai-commit-consent-management to draw these boundaries clearly. Such things are better strict than vague.

Decision Five: --- Separated Output Contract

<output_format> specifies that each return must use --- to separate multiple commit blocks, with hard-coded format:

---
Commit 1: {hash}
{message}
---
Commit 2: {hash}
{message}
---

This isn't for looks. A model might produce N commits in one task—the backend relies on this separator to parse each commit's hash and message, then pass them back to frontend for display. Once the output protocol loosens, backend parsing crashes. So the --- rule is emphasized twice in <output_format> and <final_instruction>—important things should indeed be said three times.

How Prompts Are Assembled and Delivered

Looking at templates isn't enough; we need to know how they run.

Loading and Rendering

The backend registers two singletons in PCodeClaudeHelperModule:

// Register prompt loader: find corresponding .json and .hbs by scenario + locale
context.Services.AddSingleton<IPromptLoader, FilePromptLoaderV2>();
// Register Handlebars renderer: compile templates to IL and cache
context.Services.AddSingleton<HandlebarsTemplateRenderer>(...);

FilePromptLoaderV2 gets the template body, then hands it to HandlebarsTemplateRenderer.Render(template, parameters) for rendering. The renderer's core logic roughly is:

public string Render(string template, IDictionary<string, object> parameters)
{
    // Cache by SHA256 of template content, avoid recompiling each commit
    var compiledTemplate = GetOrCompileTemplate(template);
    var rendered = compiledTemplate(parameters ?? new Dictionary<string, object>());
    // Compatible with old Scriban boolean output habit
    rendered = rendered.Replace("True", "true").Replace("False", "false");
    return rendered;
}

Compilation results cached by content hash is key for performance. Commit operations can trigger frequently—recompiling IL each time is unbearable.

Where Do Parameters Come From

JSON metadata declares a dozen parameters: projectPath, needPush, targetBranchMode, gitProfileName, gitProfileEmail, signedOffByEnabled, coAuthoredBy*, etc. These parameters are collected by the frontend "AI commit drawer," injected into backend via AutoTask channel, then routed by FilePromptProvider to this template set via PromptScenario.AutoComposeCommit.

Three-State Handling for Branch Strategy

targetBranchMode determines whether the model touches branches before commit, a three-state:

Mode Behavior
current Commit in place, don't touch branches
new-custom Create new branch from current branch using user-provided targetBranchName
ai-generated-new Model generates kebab-case branch name based on changes, add stable suffix if conflicts

The prompt explicitly says "don't switch to any other existing branch," preventing the model from arbitrarily switching to main branch to commit. This capability corresponds to the auto-branch-switch-on-commit proposal. After all, once main branch is messed up, rolling back is a messy affair.

A Complete Rendering Example

Suppose the user selects in frontend: stay on current branch, need push, enable Signed-off-by, disable Co-Authored-By, Git identity is newbe <newbe@newbe.pro>.

Then the <git_profile> section renders to:

<git_profile>
Use the following Git identity in all generated commits:
- Selected name: newbe
- Selected email: newbe@newbe.pro
...
- This run also requires Git standard sign-off trailer, so prefer using `git ... commit --author=... --signoff ...`
</git_profile>

<requirements> keeps only the "Co-Authored-By disabled for this run" branch, and <workflow> gives commands like:

# Note -c sets Committer, --author sets Author, --signoff adds DCO trailer
git -c user.name="newbe" -c user.email="newbe@newbe.pro" commit \
    --author="newbe <newbe@newbe.pro>" --signoff -m "type(scope): subject"

Engineering Practices for Template Maintenance

HagiCode provides a full set of engineering safeguards for these .hbs templates—not just writing them and calling it done.

First, snapshot tests. Test directory has BuildMessage_enUS.verified.txt, BuildMessage_zhCN.verified.txt and other verified snapshots—any rendering difference in templates is caught by tests. Change one character and you must update snapshots, preventing prompts from silently drifting.

Second, formatting scripts. cleanup-prompts.py --fix cleans trailing whitespace, collapses excess blank lines—CI check fails and blocks PR directly if not passing.

Third, parameter validation. Each scenario's required parameters, default values, types have dedicated test coverage—if template uses {{newParam}} but JSON doesn't declare it, tests fail.

Fourth, snapshot layering: Snapshots/Rendered/ stores render results, Snapshots/Scenarios/ stores scenario metadata, ensuring consistency between templates, metadata, and render products.

Here's a practical pitfall reminder. If you want to add new parameters or branches to this prompt system, four things must be done synchronously:

  1. Use {{newParam}} in template (.hbs)
  2. Declare schema in parameters array in metadata (.json)
  3. Update corresponding .verified.txt in snapshot tests
  4. Frontend form generates input controls based on new JSON parameters and passes through API

Missing any link either means empty parameters during rendering, red snapshot tests, or frontend unable to configure. This "four-way sync" constraint looks annoying, but for maintainability, it must be so.

Why Prompts Are So "Verbose"

Looking back at this prompt, you'll find it unusually verbose—identity, trailers, output format repeatedly emphasized. This is actually deliberate.

Models in Agent mode are particularly prone to "acting on their own," so hard constraints must be scattered and repeatedly declared across <requirements>, <workflow>, <final_instruction> to reduce probability of missed execution. This is like onboarding new people—say important things three times, not because they're slow, but because too many things compete for attention.

In non-interactive mode (CI/CD, automation), models can't ask users questions, so the prompt explicitly states at the start "prohibit using AskUserQuestion, use defaults for missing info and record assumptions," ensuring it runs unattended.

Once output contract loosens, backend parsing crashes—so --- separation rule is emphasized twice. Important things do indeed need to be said three times.

References

Summary

Returning to the theme "Prompts for AI Commits in HagiCode: Design Rationale and Implementation Breakdown," what's worth repeatedly confirming isn't scattered techniques, but whether constraints, implementation boundaries, and engineering trade-offs are clearly seen.

Once you distill the judgment basis in this article into stable checklist items, you can make reliable decisions faster when facing similar problems.

Original Article & License

Thanks for reading. If this article helped, consider liking, bookmarking, or sharing it.
This article was created with AI assistance and reviewed by the author before publication.