1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
|
import {
getAnthropic,
MODEL_HAIKU,
MODEL_SONNET,
extractText,
parseJsonResponse,
isAiAvailable,
} from "./ai-client";
export type CommitStyle = "conventional" | "plain";
export interface CommitMessage {
subject: string;
body: string;
}
export interface GenerateOptions {
style?: CommitStyle;
}
export const DIFF_BYTE_CAP = 50_000;
const TRUNCATE_MARKER = "\n... (more)";
const CONVENTIONAL_TYPES = [
"feat",
"fix",
"docs",
"style",
"refactor",
"perf",
"test",
"build",
"ci",
"chore",
"revert",
] as const;
type ConventionalType = (typeof CONVENTIONAL_TYPES)[number];
export function truncateDiff(diff: string, cap = DIFF_BYTE_CAP): string {
if (diff.length <= cap) return diff;
return diff.slice(0, cap - TRUNCATE_MARKER.length) + TRUNCATE_MARKER;
}
export function heuristicMessage(
diff: string,
style: CommitStyle = "conventional"
): CommitMessage {
const trimmed = diff.trim();
if (!trimmed) {
return {
subject: style === "conventional" ? "chore: update" : "Update",
body: "",
};
}
const paths: string[] = [];
let added = 0;
let removed = 0;
let newFiles = 0;
for (const line of trimmed.split("\n")) {
if (line.startsWith("+++ b/")) {
const p = line.slice("+++ b/".length).trim();
if (p && p !== "/dev/null") paths.push(p);
} else if (line.startsWith("new file mode")) {
newFiles++;
} else if (line.startsWith("+") && !line.startsWith("+++")) {
added++;
} else if (line.startsWith("-") && !line.startsWith("---")) {
removed++;
}
}
const onlyDocs =
paths.length > 0 &&
paths.every((p) => /\.(md|mdx|rst|txt)$/i.test(p) || /readme/i.test(p));
const onlyTests =
paths.length > 0 && paths.every((p) => /(^|\/)(__tests__|tests?)\//.test(p) || /\.test\.[tj]sx?$/.test(p));
const allNew = newFiles > 0 && newFiles === paths.length;
let type: ConventionalType = "chore";
if (onlyDocs) type = "docs";
else if (onlyTests) type = "test";
else if (allNew) type = "feat";
else if (removed > added * 2) type = "refactor";
else type = "chore";
const tops = new Set(paths.map((p) => p.split("/")[0]).filter(Boolean));
const scope = tops.size === 1 ? [...tops][0] : "";
const fileWord = paths.length === 1 ? "file" : "files";
const subjectRaw =
paths.length === 0
? "update files"
: `update ${paths.length} ${fileWord}`;
const subject =
style === "conventional"
? `${type}${scope ? `(${scope})` : ""}: ${subjectRaw}`
: subjectRaw.charAt(0).toUpperCase() + subjectRaw.slice(1);
const cappedSubject =
subject.length > 72 ? subject.slice(0, 69) + "..." : subject;
const topPaths = paths.slice(0, 3);
const body =
paths.length === 0
? ""
: `Touched files:\n${topPaths.map((p) => `- ${p}`).join("\n")}` +
(paths.length > topPaths.length
? `\n- ...and ${paths.length - topPaths.length} more`
: "");
return { subject: cappedSubject, body };
}
export function parseModelOutput(
text: string,
style: CommitStyle = "conventional"
): CommitMessage {
const cleaned = text.replace(/^```[a-zA-Z]*\n|\n```$/g, "").trim();
const parsed = parseJsonResponse<{ subject?: string; body?: string }>(
cleaned
);
let subject = "";
let body = "";
if (parsed && typeof parsed.subject === "string") {
subject = parsed.subject.trim();
body = typeof parsed.body === "string" ? parsed.body.trim() : "";
} else {
const lines = cleaned.split("\n");
subject = (lines[0] || "").trim();
body = lines.slice(1).join("\n").trim();
if (body.startsWith("\n")) body = body.slice(1);
}
subject = subject.replace(/^["'`]+|["'`]+$/g, "").trim();
if (subject.length > 72) {
subject = subject.slice(0, 69) + "...";
}
if (!subject) {
return { subject: style === "conventional" ? "chore: update" : "Update", body: "" };
}
if (style === "conventional" && !/^[a-z]+(\([^)]+\))?(!?):/.test(subject)) {
subject = `chore: ${subject.charAt(0).toLowerCase()}${subject.slice(1)}`;
if (subject.length > 72) subject = subject.slice(0, 69) + "...";
}
return { subject, body };
}
export function buildPrompt(diff: string, style: CommitStyle): string {
const styleInstruction =
style === "conventional"
? `Use Conventional Commits style — the subject MUST start with one of: ${CONVENTIONAL_TYPES.join(", ")}, optionally followed by (scope), then ": ", then a lowercase imperative summary. Example: "feat(auth): add passkey login".`
: `Write a plain-English subject in imperative mood (e.g. "Add passkey login"). No type prefix.`;
return `You are writing a git commit message for the following staged diff.
${styleInstruction}
Rules:
- Subject MUST be 72 characters or fewer.
- Subject is one line. No trailing period.
- Body explains WHY the change was made when it is non-obvious. Skip the body for trivial changes.
- Body lines wrap at ~72 chars. Use blank lines between paragraphs.
- Do NOT describe what every file does — the diff already shows that. Focus on intent.
- Do NOT include code fences, markdown, or extra commentary.
Respond ONLY with JSON in this exact shape:
{"subject": "...", "body": "..."}
If the change is trivial enough that no body is needed, return body as "".
Diff:
\`\`\`diff
${diff}
\`\`\``;
}
export async function generateCommitMessage(
diff: string,
opts: GenerateOptions = {}
): Promise<CommitMessage> {
const style: CommitStyle = opts.style === "plain" ? "plain" : "conventional";
const trimmed = diff.trim();
if (!trimmed) {
return {
subject: style === "conventional" ? "chore: empty commit" : "Empty commit",
body: "",
};
}
if (!isAiAvailable()) {
return heuristicMessage(trimmed, style);
}
const truncated = truncateDiff(trimmed);
try {
const client = getAnthropic();
const message = await client.messages.create({
model: MODEL_SONNET,
max_tokens: 512,
messages: [
{
role: "user",
content: buildPrompt(truncated, style),
},
],
});
try {
const { recordAiCost, extractUsage } = await import("./ai-cost-tracker");
const usage = extractUsage(message);
await recordAiCost({
model: MODEL_SONNET,
inputTokens: usage.input,
outputTokens: usage.output,
category: "other",
sourceKind: "commit_message",
});
} catch {
}
const text = extractText(message);
if (!text.trim()) {
return heuristicMessage(trimmed, style);
}
return parseModelOutput(text, style);
} catch {
return heuristicMessage(trimmed, style);
}
}
export const __test = {
truncateDiff,
heuristicMessage,
parseModelOutput,
buildPrompt,
CONVENTIONAL_TYPES,
};
|