Auto-generate PR Description Golang CI: AI from Spec and Diff
Automate the creation of informative PR descriptions with AI. Generate from spec, git diff, and commit messages for a Go project in GitHub Actions.
Auto-generating PR descriptions with AI is one of the automations whose ROI is felt fastest on a Golang team. A poor PR description is a silent productivity killer: reviewers don’t know the context, so reviews become slow, and future developers don’t understand why a change was made, so debugging takes longer. By leveraging the git diff, commit messages, and spec files as context, AI can write an informative PR description in 30 seconds β without the developer typing a single word.
In this article we build a complete pipeline in GitHub Actions for a Go project: from the anatomy of a good PR description, to the generator script, the automated workflow, and finally the rollout strategy to the team.
10.1 Anatomy of a Good PR Description
Before we tell the AI to write, we first need to know what a decent PR description looks like. The structure below is the skeleton that lets a reviewer immediately understand the change without asking questions.
1An ideal PR description contains:
2
31. SUMMARY (1-2 sentences)
4 What changed and why, in non-technical language.
5 "Implement the cancel order feature that allows customers to cancel a
6 PENDING order within 30 minutes after it was created."
7
82. CHANGES (bullet list)
9 Technical changes made.
10 - Add CancelOrderUseCase with business rule validation
11 - Add repository method CancelWithStockRestore
12 - Add HTTP DELETE /orders/:id endpoint
13 - Add unit tests covering 4 ACs from the spec
14
153. SPEC COMPLIANCE (if using Spec Kit)
16 Which ACs are addressed.
17 - AC1: Cancel PENDING order within window β β
18 - AC2: Non-PENDING β 409 β β
19
204. TESTING
21 How to test this change.
22 - Unit tests: go test ./internal/usecase/order/...
23 - Manual: DELETE /orders/{pending-order-id}
24
255. NOTES (optional)
26 Things the reviewer should be aware of.
27
28A bad PR description:
29 "fix order cancel"
30 β this is 97% of PR descriptions in the real worldThese five blocks are what we’ll target as the AI’s output. Note one important separation: sections 1β5 can be generated from the code, but verification (the checklist) remains the developer’s responsibility β a separation we’ll preserve throughout the article.
10.2 Generator Architecture
So it’s clear what goes into and out of the generator, the diagram below maps the input, processing, and output along with a cost estimate.
1Input:
2 1. Git diff (what changed in the code)
3 2. Commit messages (context from the developer)
4 3. Spec files (which ACs are addressed, if any)
5 4. PR template (the desired format)
6
7Processing:
8 Claude Haiku β parse all input β generate structured description
9
10Output:
11 Markdown PR description posted to the GitHub PR body
12
13Cost per PR generation:
14 Input: ~1,500 tokens (diff + spec + template)
15 Output: ~400 tokens (description)
16 Haiku cost: (1500 Γ $0.80 + 400 Γ $4.00) / 1,000,000 = $0.0028
17 = less than a few cents per PRA cost of a few cents per PR is a figure you never need to think about again β its value far exceeds the developer time it saves. Now let’s implement the processor in the middle of that diagram.
10.3 Implementation: Node.js Script
The core of the system is a single Node.js script that gathers all the input from the repository and then calls Claude. The script below executes seven steps β from fetching the diff to printing the description β with graceful degradation at every failure point.
1// scripts/generate-pr-description.js
2// Called from GitHub Actions
3
4const { execSync } = require('child_process');
5const fs = require('fs');
6
7async function generatePRDescription() {
8 const baseBranch = process.env.BASE_BRANCH || 'main';
9 const apiKey = process.env.ANTHROPIC_API_KEY;
10
11 if (!apiKey) {
12 console.log('No ANTHROPIC_API_KEY, skip PR description generation');
13 process.exit(0);
14 }
15
16 // 1. Get git diff (Go files only, max 300 lines)
17 let diff = '';
18 try {
19 diff = execSync(
20 `git diff origin/${baseBranch}...HEAD -- '*.go' | head -300`,
21 { encoding: 'utf-8' }
22 );
23 } catch (e) {
24 console.log('Could not get diff:', e.message);
25 }
26
27 if (!diff.trim()) {
28 console.log('No Go changes detected');
29 process.exit(0);
30 }
31
32 // 2. Get commit messages
33 let commits = '';
34 try {
35 commits = execSync(
36 `git log --oneline --no-merges origin/${baseBranch}..HEAD | head -10`,
37 { encoding: 'utf-8' }
38 );
39 } catch (e) {}
40
41 // 3. Find relevant spec files
42 let specContent = '';
43 try {
44 const changedFiles = execSync(
45 `git diff origin/${baseBranch}...HEAD --name-only -- 'internal/usecase/**'`,
46 { encoding: 'utf-8' }
47 ).trim().split('\n');
48
49 const features = [...new Set(changedFiles
50 .map(f => f.replace('internal/usecase/', '').split('/')[0])
51 .filter(Boolean)
52 )];
53
54 for (const feature of features) {
55 const specPath = `.specify/features/${feature}/spec.md`;
56 if (fs.existsSync(specPath)) {
57 const specText = fs.readFileSync(specPath, 'utf-8');
58 specContent += `\n### Spec: ${feature}\n${specText.slice(0, 500)}\n`;
59 }
60 }
61 } catch (e) {}
62
63 // 4. Load PR template
64 let template = '';
65 if (fs.existsSync('.github/pull_request_template.md')) {
66 template = fs.readFileSync('.github/pull_request_template.md', 'utf-8');
67 }
68
69 // 5. Build prompt
70 const prompt = `Generate an informative PR description for this Go code change.
71
72COMMIT MESSAGES:
73${commits || 'No commits found'}
74
75${specContent ? `RELATED SPEC:\n${specContent}` : ''}
76
77CODE DIFF (first 300 lines):
78${diff}
79
80${template ? `PR TEMPLATE (follow this structure):\n${template}` : ''}
81
82Generate a PR description in English that includes:
831. ## Summary β 1-2 sentences on what changed and why
842. ## Changes β bullet list of technical changes
85${specContent ? '3. ## Spec Compliance β which ACs are addressed' : ''}
864. ## Testing β how to test this change
875. ## Notes β important things for the reviewer (if any)
88
89Be specific and technical. Mention function names, packages, patterns used.
90Do NOT include checklist items from the template (leave those for the developer).
91Output: markdown only, no preamble.`;
92
93 // 6. Call Claude API
94 const response = await fetch('https://api.anthropic.com/v1/messages', {
95 method: 'POST',
96 headers: {
97 'x-api-key': apiKey,
98 'anthropic-version': '2023-06-01',
99 'content-type': 'application/json',
100 },
101 body: JSON.stringify({
102 model: 'claude-haiku-4-5-20251001',
103 max_tokens: 800,
104 messages: [{ role: 'user', content: prompt }],
105 }),
106 });
107
108 if (!response.ok) {
109 console.error('Claude API error:', response.status);
110 process.exit(0); // graceful β do not fail the pipeline
111 }
112
113 const data = await response.json();
114 const description = data.content[0].text;
115
116 // 7. Output description (will be posted by the caller)
117 console.log(description);
118}
119
120generatePRDescription().catch(err => {
121 console.error('Error:', err);
122 process.exit(0); // graceful degradation
123});Note three important design decisions: the diff is capped at 300 lines so the output isn’t generic, the spec is linked automatically from the internal/usecase/** path, and every failure calls process.exit(0) so the pipeline never fails because of a description-generation problem. This script is what the following workflow will invoke.
10.4 GitHub Actions Workflow
The script above needs to run automatically when a new PR is opened. The workflow below triggers only for new PRs (opened) that touch Go files, first checks whether the body is already filled, and only then generates and updates the PR.
1# .github/workflows/pr-description.yml
2name: Auto PR Description
3
4on:
5 pull_request:
6 types: [opened] # only for new PRs, not updates
7 paths: ['**.go']
8
9jobs:
10 generate-description:
11 name: Generate PR Description
12 runs-on: ubuntu-latest
13 if: "!github.event.pull_request.draft"
14 permissions:
15 pull-requests: write
16 contents: read
17 env:
18 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
19
20 steps:
21 - uses: actions/checkout@v4
22 with:
23 fetch-depth: 0
24
25 - uses: actions/setup-node@v4
26 with:
27 node-version: '20'
28
29 - name: Check if PR already has description
30 id: check_desc
31 run: |
32 BODY='${{ github.event.pull_request.body }}'
33 if [ ${#BODY} -gt 50 ]; then
34 echo "has_description=true" >> $GITHUB_OUTPUT
35 echo "PR already has description, skip generation"
36 else
37 echo "has_description=false" >> $GITHUB_OUTPUT
38 fi
39
40 - name: Generate PR description
41 id: generate
42 if: steps.check_desc.outputs.has_description == 'false'
43 env:
44 BASE_BRANCH: ${{ github.base_ref }}
45 run: |
46 node scripts/generate-pr-description.js > /tmp/pr-description.txt 2>&1
47 if [ -s /tmp/pr-description.txt ]; then
48 echo "generated=true" >> $GITHUB_OUTPUT
49 else
50 echo "generated=false" >> $GITHUB_OUTPUT
51 fi
52
53 - name: Update PR with generated description
54 if: |
55 steps.check_desc.outputs.has_description == 'false' &&
56 steps.generate.outputs.generated == 'true'
57 uses: actions/github-script@v7
58 with:
59 script: |
60 const fs = require('fs');
61 const generatedDesc = fs.readFileSync('/tmp/pr-description.txt', 'utf8').trim();
62
63 if (!generatedDesc || generatedDesc.length < 50) {
64 console.log('Generated description too short, skip');
65 return;
66 }
67
68 // Manual checklist that the developer still must fill in
69 const templateChecklist = [
70 '', '---', '## Checklist',
71 '- [ ] Tests added/updated',
72 '- [ ] go test -race ./... β
',
73 '- [ ] CLAUDE.md rules followed',
74 '- [ ] Spec updated (if behavior changed)',
75 '', '*PR description auto-generated by AI | Edit if incorrect*',
76 ].join('\n');
77
78 await github.rest.pulls.update({
79 owner: context.repo.owner,
80 repo: context.repo.repo,
81 pull_number: context.issue.number,
82 body: generatedDesc + templateChecklist,
83 });
84
85 console.log('PR description updated successfully');Two guards in this workflow are crucial: types: [opened] prevents the AI from overriding a description the developer already wrote on a subsequent push, and the body-length check ensures we don’t overwrite a manual description. The generated part and the manual checklist are deliberately kept separate β let’s look at the template next.
10.5 The Optimal PR Template
So that both the AI and the developer fill in the right sections, the PR template separates the AI-generated area from the manually-required area. The template below marks both with HTML comments.
1<!-- .github/pull_request_template.md -->
2
3## Summary
4<!-- AI will generate this -->
5
6## Changes
7<!-- AI will generate this -->
8
9## Spec Compliance
10<!-- AI will generate this if spec files exist -->
11
12## Testing
13<!-- AI will generate this -->
14
15## Notes
16<!-- AI will generate this if relevant -->
17
18---
19## Developer Checklist (fill in manually)
20- [ ] `go test -race ./...` β
21- [ ] Spec updated (if behavior changed)
22- [ ] CLAUDE.md rules followed
23- [ ] Breaking changes? (bump API version if any)
24
25## Reviewer Focus
26<!-- Developer: write what needs the reviewer's attention most -->With this template, the AI fills in the context (Summary through Notes) while the developer remains responsible for verification (the checklist) and reviewer guidance β an honest division of labor, because the AI cannot know whether the tests actually ran.
10.6 Example of Generated Output
To make it concrete, here is a real example of a PR description generated for a cancel-order feature implementation, complete with a spec compliance section because the spec file was available.
1## Summary
2Implement the cancel order feature that lets customers cancel a PENDING
3order within a 30-minute window. This feature implements an atomic stock
4restore via a database transaction.
5
6## Changes
7- **Domain:** Add `Order.ValidateCancellation()` in
8 `internal/domain/order/entity.go`
9- **UseCase:** Implement `CancelOrderUseCase.Execute()` in
10 `internal/usecase/order/cancel_order.go` with full error handling
11- **Repository:** Add `CancelWithStockRestore()` β a single DB transaction
12 to update the order status + restore product stock
13- **Handler:** Add `DELETE /orders/:id` with JWT auth
14- **Tests:** Unit tests β 5 test cases via testify/suite
15
16## Spec Compliance
17Based on `.specify/features/cancel-order/spec.md`:
18- β
AC1: PENDING order + < 30 min β cancel β 204 No Content
19- β
AC2: Non-PENDING order β 409 `{"error": "ORDER_NOT_CANCELLABLE"}`
20- β
AC3: PENDING order + > 30 min β 409 `{"error": "CANCEL_WINDOW_EXPIRED"}`
21- β
AC4: Order not found β 404 `{"error": "ORDER_NOT_FOUND"}`
22
23## Testing
24go test -race ./internal/usecase/order/... -run TestCancelOrder
25
26## Notes
27- `CancelWithStockRestore` uses `pgx.ReadCommitted` to prevent a
28 dirty read on the stock quantity
29- The Kafka event `ORDER_CANCELLED` is published after the DB commit (async)Compare this output with the “fix order cancel” PR description we usually encounter β here the reviewer can start reviewing immediately because every AC, file, and design decision is already documented. The key to this quality is the spec context, which we’ll enrich further.
10.7 Enrichment: Add Context from Jira/Linear
The description becomes richer with added context from the issue tracker. The function below extracts the issue key from the branch name, then fetches the summary and priority from Jira to inject into the prompt.
1// Extend generate-pr-description.js with Jira integration
2async function getJiraContext(branchName) {
3 const match = branchName.match(/([A-Z]+-\d+)/);
4 if (!match) return '';
5
6 const issueKey = match[1];
7 const jiraUrl = process.env.JIRA_URL;
8 const jiraToken = process.env.JIRA_TOKEN;
9 if (!jiraUrl || !jiraToken) return '';
10
11 try {
12 const response = await fetch(
13 `${jiraUrl}/rest/api/3/issue/${issueKey}?fields=summary,priority`,
14 { headers: { 'Authorization': `Bearer ${jiraToken}`, 'Accept': 'application/json' } }
15 );
16 if (!response.ok) return '';
17
18 const data = await response.json();
19 return `\nJIRA ISSUE: ${issueKey}\nTitle: ${data.fields.summary}\nPriority: ${data.fields.priority.name}\n`;
20 } catch (e) {
21 return '';
22 }
23}Note the same graceful pattern: if the branch has no issue key or the Jira credentials are absent, the function returns an empty string and generation still proceeds. This issue context lets the AI explain why a change was made, not just what changed.
10.8 Quality Check for the Generated Description
AI output isn’t always perfect, so we need to validate before posting. The function below checks the minimum length, the presence of required sections, and whether the description actually contains Go-specific content.
1function validateDescription(description) {
2 const issues = [];
3
4 if (description.length < 200)
5 issues.push(`Too short (${description.length} chars, min 200)`);
6
7 ['Summary', 'Changes', 'Testing'].forEach(section => {
8 if (!description.includes(`## ${section}`))
9 issues.push(`Missing section: ## ${section}`);
10 });
11
12 const goTerms = ['func', 'struct', 'usecase', 'repository', 'handler'];
13 if (!goTerms.some(t => description.toLowerCase().includes(t)))
14 issues.push('No Go-specific content detected');
15
16 return { valid: issues.length === 0, issues };
17}This lightweight validation catches the two most common failures: an AI that produces a description that’s too short/generic, and output that’s missing an important section. If quality scores are consistently low, that’s a signal to retune the prompt β not to disable the feature.
10.9 Handling Large PRs with Chunking
A very large diff produces a generic description and wastes tokens. For big PRs, we split the diff per file, summarize each in parallel, then combine them into one cohesive description.
1// For PRs > 300 lines of diff: chunk per file
2async function generateForLargePR(diff) {
3 const files = diff.split('diff --git');
4
5 // Parallel summary per file (max 10 files)
6 const summaries = await Promise.all(
7 files.slice(1, 11).map(async chunk => {
8 const file = chunk.split('\n')[0].replace(' a/', '').split(' ')[0];
9 const summary = await callClaude(
10 `Summarize changes to ${file} in 1-2 sentences: ${chunk.slice(0, 200)}`, 80
11 );
12 return `- **${file.split('/').pop()}:** ${summary}`;
13 })
14 );
15
16 return await callClaude(
17 `Write PR description from these summaries:\n${summaries.join('\n')}`, 600
18 );
19}This map-reduce strategy preserves quality for gigantic PRs without flooding the context window: per-file summaries first, then a final synthesis. A firmer alternative: for PRs over 50 files, suggest the developer split the PR.
10.10 Multi-language Support
Santekno writes in Indonesian, but another team might need English. The small function below picks the target language based on the repository’s organization.
1function detectLanguage(orgName) {
2 if (orgName === 'santekno') return 'Bahasa Indonesia';
3 return 'English'; // default for other organizations
4}
5
6const lang = detectLanguage(process.env.GITHUB_REPOSITORY_OWNER);
7const prompt = `Generate PR description in ${lang}.\n...`;With a single language variable injected into the prompt, the same pipeline can serve multilingual teams without duplicating the script. Now let’s measure whether this automation truly has an impact.
10.11 PR Description Analytics
To prove the value of the automation, we need data. The step below records metrics for each PR β body length, whether it’s AI-generated, and section completeness β for a monthly comparison.
1- name: Track PR description quality
2 if: always()
3 uses: actions/github-script@v7
4 with:
5 script: |
6 const pr = context.payload.pull_request;
7 const hasAILabel = pr.labels?.some(l => l.name === 'ai-generated-description');
8 const hasSections = ['Summary', 'Changes', 'Testing']
9 .filter(s => pr.body?.includes(`## ${s}`)).length;
10
11 console.log(JSON.stringify({
12 pr_number: pr.number,
13 body_length: pr.body?.length || 0,
14 ai_generated: hasAILabel,
15 sections_count: hasSections,
16 timestamp: new Date().toISOString(),
17 }));This data answers an important question objectively: are AI-generated descriptions longer and more structured than manual ones? Usually the answer is yes β and that figure is what convinces the skeptical members of a team.
10.12 Before and After Auto PR Description
The impact is felt most when we compare the reviewer’s experience before and after the automation is enabled. The illustration below summarizes the difference.
1BEFORE:
2 Title: "fix cancel order"
3 Body: "" (empty or "wip")
4 Reviewer: "What was fixed? Why? What context?"
5 β Back and forth for 30-60 minutes before the review can start
6
7AFTER:
8 Title: "feat(order): implement cancel order feature"
9 Body: [AI-generated: Summary, Changes, Spec ACs, Testing, Notes]
10 Reviewer: can start reviewing immediately because the context is clear
11 β Review cycle -20%, reviewer satisfaction upNote that what’s lost isn’t just time β it’s also the social friction of the back-and-forth questioning. To spread this benefit evenly across the team, we need a gradual rollout strategy.
10.13 Rollout Strategy
Even good automation can be rejected by a team if it’s forced all at once. The roadmap below introduces it gradually: from a soft launch that only logs, to a full launch as the standard.
1WEEK 1: Soft launch
2 - Enable the workflow but output to the log (don't update the PR body)
3 - Review the output: is it accurate and useful? Adjust the prompt.
4
5WEEK 2-3: Opt-in
6 - Enable for all new PRs
7 - Developers can manually edit if the AI output isn't quite right
8 - Track: how many are edited?
9
10MONTH 2: Full launch
11 - Part of the standard workflow
12 - The checklist template still must be filled in manuallyThis gradual pattern builds trust: the team sees the AI output first before it actually touches their PRs. With a feedback loop at every phase, the prompt can be tuned before full adoption.
10.14 Tips & Gotchas
Before we wrap up, a few practical lessons from real-world adoption that will save you debugging time.
π‘ Tip 1: Generate only for new PRs (the opened action). If you generate on every push, a developer who has already written a description will get overridden.
π‘ Tip 2: Still ask the developer to fill in the checklist. The AI can’t know whether the tests actually ran or the spec was actually updated.
π‘ Tip 3: Limit the diff size. A very large diff (1000+ lines) produces a generic description. 300 lines is the sweet spot.
π‘ Tip 4: Spec context dramatically improves quality. A PR description with spec ACs is far more useful than one based only on the diff.
β οΈ Gotcha 1: AI that’s too verbose. Haiku is sometimes too long. Add to the prompt: “Be concise, maximum 400 words.”
β οΈ Gotcha 2: Race condition with fork branches. PRs from a fork don’t have access to secrets. Handle this by checking github.event.pull_request.head.repo.full_name.
The point most often forgotten is Gotcha 2 β PRs from external contributors will fail silently if not handled, so make sure the pipeline skips forks gracefully.
10.15 Summary
Auto-generating PR descriptions is an automation with immediate value because it doesn’t require much setup and is instantly useful for the whole team.
Key numbers:
- Cost: a few cents per PR
- Time saved per developer: 5-15 minutes (writing the PR description)
- Quality: more consistent and informative descriptions
Key rules: generate only for new PRs (types: [opened]), check first whether the body already exists, degrade gracefully if the API fails, and always preserve the manual checklist.
In the next article, we raise the automation to a higher level: changelogs and release notes generated automatically from commit messages.