gitCommitMessageGenerator.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import type {
  2. GitCommitMessageConversationContext,
  3. GitDiffResult,
  4. GitFileChange,
  5. Locale,
  6. ZCodeWorkspaceGenerateTextParams,
  7. } from "@zcode/shared";
  8. import type { ServiceLogger } from "#src/logger/serviceLogger.js";
  9. const MAX_PROMPT_FILES = 20;
  10. const MAX_DIFF_FILES = 8;
  11. const MAX_DIFF_CHARS = 12_000;
  12. const MAX_DIFF_CHARS_PER_FILE = 2_000;
  13. const MAX_CONVERSATION_CONTEXT_MESSAGES = 12;
  14. const MAX_CONVERSATION_CONTEXT_CHARS = 4_000;
  15. const MAX_CONVERSATION_CONTEXT_CHARS_PER_MESSAGE = 600;
  16. const MAX_COMMIT_MESSAGE_CHARS = 1_000;
  17. const COMMIT_MESSAGE_QUERY_SOURCE = "git_commit_message";
  18. const CONVENTIONAL_COMMIT_RE =
  19. /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([^)]+\))?!?: .{1,100}$/;
  20. export interface GitCommitMessageCurrentModelProvider {
  21. readCurrentModel(params: {
  22. workspacePath: string;
  23. workspaceIdentity?: string;
  24. }): Promise<ZCodeWorkspaceGenerateTextParams["selection"] | null>;
  25. }
  26. export interface GitCommitMessageTextGenerator {
  27. generateText(params: {
  28. workspacePath: string;
  29. workspaceIdentity?: string;
  30. selection: ZCodeWorkspaceGenerateTextParams["selection"];
  31. prompt: string;
  32. querySource: string;
  33. }): Promise<{ text: string; selection: ZCodeWorkspaceGenerateTextParams["selection"] }>;
  34. }
  35. export interface GitCommitMessageGeneratorOptions {
  36. currentModelProvider: GitCommitMessageCurrentModelProvider;
  37. textGenerator: GitCommitMessageTextGenerator;
  38. logger?: ServiceLogger;
  39. }
  40. export class GitCommitMessageGenerationError extends Error {
  41. constructor(
  42. message: string,
  43. readonly reason: "model-unavailable" | "request-failed" | "invalid-output",
  44. readonly detail?: string,
  45. ) {
  46. super(message);
  47. this.name = "GitCommitMessageGenerationError";
  48. }
  49. }
  50. export class GitCommitMessageGenerator {
  51. constructor(private readonly options: GitCommitMessageGeneratorOptions) {}
  52. async generate(params: {
  53. workspacePath: string;
  54. workspaceIdentity?: string;
  55. branchName: string | null;
  56. locale?: Locale;
  57. files: readonly GitFileChange[];
  58. diffs: readonly GitDiffResult[];
  59. conversationContext?: GitCommitMessageConversationContext;
  60. }): Promise<{ message: string; providerId: string; model: string }> {
  61. const selection = await this.resolveCurrentModel(params);
  62. const prompt = buildGitCommitMessageGenerationPrompt({
  63. branchName: params.branchName,
  64. locale: params.locale,
  65. files: params.files,
  66. diffs: params.diffs,
  67. conversationContext: params.conversationContext,
  68. });
  69. this.options.logger?.info(undefined, "开始生成 Git 提交消息", {
  70. workspacePath: params.workspacePath,
  71. workspaceIdentity: params.workspaceIdentity,
  72. providerId: selection.providerId,
  73. model: selection.modelId,
  74. fileCount: params.files.length,
  75. diffCount: params.diffs.length,
  76. conversationMessageCount: params.conversationContext?.messages.length ?? 0,
  77. conversationOmittedMessageCount: params.conversationContext?.omittedMessageCount ?? 0,
  78. });
  79. const rawMessage = await this.complete({
  80. workspacePath: params.workspacePath,
  81. workspaceIdentity: params.workspaceIdentity,
  82. selection,
  83. prompt,
  84. });
  85. const validation = validateGeneratedGitCommitMessage(rawMessage);
  86. if (!validation.ok) {
  87. // 模型可能重复 prompt 或返回解释性长文本,直接塞给 UI 会让错误提示失控。
  88. // 这里只保留短 preview 给用户,完整模型调用细节由 agent runtime 的模型日志记录。
  89. this.options.logger?.debug(undefined, "模型生成的 Git 提交消息不合规", {
  90. workspacePath: params.workspacePath,
  91. providerId: selection.providerId,
  92. model: selection.modelId,
  93. reason: validation.reason,
  94. preview: validation.preview,
  95. });
  96. throw new GitCommitMessageGenerationError(
  97. "模型没有返回可用的 Conventional Commit 提交消息。",
  98. "invalid-output",
  99. validation.preview,
  100. );
  101. }
  102. return {
  103. message: validation.message,
  104. providerId: selection.providerId,
  105. model: selection.modelId,
  106. };
  107. }
  108. private async resolveCurrentModel(params: {
  109. workspacePath: string;
  110. workspaceIdentity?: string;
  111. }): Promise<ZCodeWorkspaceGenerateTextParams["selection"]> {
  112. const currentModel = await this.options.currentModelProvider.readCurrentModel({
  113. workspacePath: params.workspacePath,
  114. workspaceIdentity: params.workspaceIdentity,
  115. });
  116. const modelId = currentModel?.modelId?.trim();
  117. const providerId = currentModel?.providerId?.trim();
  118. const options = currentModel?.options;
  119. if (!providerId || !modelId) {
  120. throw new GitCommitMessageGenerationError("未读取到当前模型。", "model-unavailable");
  121. }
  122. return {
  123. providerId,
  124. modelId,
  125. ...(options
  126. ? {
  127. options: {
  128. ...options,
  129. },
  130. }
  131. : {}),
  132. };
  133. }
  134. private async complete(params: {
  135. workspacePath: string;
  136. workspaceIdentity?: string;
  137. selection: ZCodeWorkspaceGenerateTextParams["selection"];
  138. prompt: string;
  139. }): Promise<string> {
  140. try {
  141. const result = await this.options.textGenerator.generateText({
  142. workspacePath: params.workspacePath,
  143. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  144. selection: params.selection,
  145. prompt: params.prompt,
  146. querySource: COMMIT_MESSAGE_QUERY_SOURCE,
  147. });
  148. return normalizeModelText(result.text);
  149. } catch (error) {
  150. if (error instanceof GitCommitMessageGenerationError) {
  151. throw error;
  152. }
  153. throw new GitCommitMessageGenerationError(
  154. "模型请求失败。",
  155. "request-failed",
  156. error instanceof Error ? error.message : String(error),
  157. );
  158. }
  159. }
  160. }
  161. function buildGitCommitMessageGenerationPrompt(params: {
  162. branchName: string | null;
  163. locale?: Locale;
  164. files: readonly GitFileChange[];
  165. diffs: readonly GitDiffResult[];
  166. conversationContext?: GitCommitMessageConversationContext;
  167. }): string {
  168. const normalizedBranchName = params.branchName?.trim() || "(detached or unknown)";
  169. const language = resolveCommitMessageLanguage(params.locale);
  170. const visibleFiles = params.files.slice(0, MAX_PROMPT_FILES);
  171. const omittedFileCount = Math.max(0, params.files.length - visibleFiles.length);
  172. const fileSummary = visibleFiles
  173. .map((file) => `- ${file.kind} ${file.repoRelativePath} (+${file.added}/-${file.removed})`)
  174. .join("\n");
  175. const diffSummary = buildDiffSummary(params.diffs);
  176. const conversationSummary = buildConversationContextSummary(params.conversationContext);
  177. return [
  178. "Write exactly one Git commit message for the workspace changes below.",
  179. "Return only the commit message text.",
  180. "",
  181. "Hard requirements:",
  182. "- The first line must be a valid Conventional Commit subject.",
  183. "- Use one of: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert.",
  184. "- Keep the Conventional Commit type and optional scope in English.",
  185. "- Write the subject and any body in the current language.",
  186. "- Keep the subject under 72 characters.",
  187. "- Use the current session conversation context only to infer user intent.",
  188. "- Do not mention the conversation, chat, prompt, or user request explicitly.",
  189. "- Do not explain your reasoning.",
  190. "- Do not repeat these instructions.",
  191. "",
  192. `Current branch: ${normalizedBranchName}`,
  193. `Current language: ${language}`,
  194. "",
  195. "Current session conversation context:",
  196. conversationSummary || "(not provided)",
  197. "",
  198. "Changed files:",
  199. fileSummary || "- (no file summary available)",
  200. omittedFileCount > 0 ? `- ... ${omittedFileCount} more files` : "",
  201. "",
  202. "Diff excerpts:",
  203. diffSummary || "(diff unavailable; infer only from the changed file summary)",
  204. ]
  205. .filter((line) => line !== "")
  206. .join("\n");
  207. }
  208. function resolveCommitMessageLanguage(locale?: Locale): "Chinese" | "English" {
  209. const candidate = locale ?? readRuntimeLocale();
  210. return candidate?.toLowerCase().startsWith("zh") ? "Chinese" : "English";
  211. }
  212. function readRuntimeLocale(): string | undefined {
  213. try {
  214. // 系统默认语言没有从 UI 显式传入时,服务层只能读取当前运行时的 Intl locale。
  215. // 这里仍只接受 zh 为中文,其它未知或读取失败都按英文处理,避免误生成第三种语言。
  216. return Intl.DateTimeFormat().resolvedOptions().locale;
  217. } catch {
  218. return undefined;
  219. }
  220. }
  221. function validateGeneratedGitCommitMessage(
  222. rawMessage: string,
  223. ): { ok: true; message: string } | { ok: false; reason: "empty" | "invalid"; preview?: string } {
  224. const message = stripGeneratedCommitMessageDecorations(rawMessage)
  225. .trim()
  226. .slice(0, MAX_COMMIT_MESSAGE_CHARS)
  227. .trim();
  228. if (!message) {
  229. return { ok: false, reason: "empty" };
  230. }
  231. const subject = message.split(/\r?\n/, 1)[0]?.trim() ?? "";
  232. if (!CONVENTIONAL_COMMIT_RE.test(subject)) {
  233. return { ok: false, reason: "invalid", preview: subject || message.slice(0, 120) };
  234. }
  235. return { ok: true, message };
  236. }
  237. function buildDiffSummary(diffs: readonly GitDiffResult[]): string {
  238. let totalChars = 0;
  239. const chunks: string[] = [];
  240. for (const diff of diffs.slice(0, MAX_DIFF_FILES)) {
  241. const header = `--- ${diff.path}`;
  242. const body = diff.patch?.trim() || diff.summary?.trim() || "(diff unavailable)";
  243. const remainingChars = MAX_DIFF_CHARS - totalChars;
  244. if (remainingChars <= 0) {
  245. break;
  246. }
  247. const clippedBody = clipText(
  248. body,
  249. Math.min(MAX_DIFF_CHARS_PER_FILE, remainingChars),
  250. "...diff truncated...",
  251. );
  252. const chunk = `${header}\n${clippedBody}`;
  253. chunks.push(chunk);
  254. totalChars += chunk.length;
  255. }
  256. return chunks.join("\n\n");
  257. }
  258. function buildConversationContextSummary(
  259. context: GitCommitMessageConversationContext | undefined,
  260. ): string {
  261. const messages = context?.messages ?? [];
  262. if (messages.length === 0) {
  263. return "";
  264. }
  265. const chunks: string[] = [];
  266. let totalChars = 0;
  267. const omittedMessageCount =
  268. (context?.omittedMessageCount ?? 0) +
  269. Math.max(0, messages.length - MAX_CONVERSATION_CONTEXT_MESSAGES);
  270. if (omittedMessageCount > 0) {
  271. chunks.push(`- ${omittedMessageCount} earlier messages omitted`);
  272. }
  273. for (const message of messages.slice(-MAX_CONVERSATION_CONTEXT_MESSAGES)) {
  274. const content = normalizeConversationContextText(message.content);
  275. if (!content) {
  276. continue;
  277. }
  278. const role = message.role === "assistant" ? "Assistant" : "User";
  279. const clippedContent = clipText(
  280. content,
  281. MAX_CONVERSATION_CONTEXT_CHARS_PER_MESSAGE,
  282. "...message truncated...",
  283. );
  284. const nextChunk = `${role}: ${clippedContent}`;
  285. const remainingChars = MAX_CONVERSATION_CONTEXT_CHARS - totalChars;
  286. if (remainingChars <= 0) {
  287. break;
  288. }
  289. const clippedChunk = clipText(nextChunk, remainingChars, "...conversation truncated...");
  290. chunks.push(clippedChunk);
  291. totalChars += clippedChunk.length + 1;
  292. }
  293. return chunks.join("\n");
  294. }
  295. function normalizeConversationContextText(value: string): string {
  296. return value
  297. .replace(/\r\n?/gu, "\n")
  298. .replace(/[ \t]+\n/gu, "\n")
  299. .replace(/\n{3,}/gu, "\n\n")
  300. .trim();
  301. }
  302. function clipText(value: string, maxChars: number, marker: string): string {
  303. if (value.length <= maxChars) {
  304. return value;
  305. }
  306. return `${value.slice(0, Math.max(0, maxChars - marker.length - 1)).trimEnd()}\n${marker}`;
  307. }
  308. function stripGeneratedCommitMessageDecorations(value: string): string {
  309. const trimmed = value.trim();
  310. const fenced = /^```(?:[a-zA-Z0-9_-]+)?\s*([\s\S]*?)\s*```$/.exec(trimmed);
  311. const withoutFence = fenced?.[1] ?? trimmed;
  312. const withoutPrefix = withoutFence.replace(/^commit message:\s*/i, "").trim();
  313. if (
  314. (withoutPrefix.startsWith('"') && withoutPrefix.endsWith('"')) ||
  315. (withoutPrefix.startsWith("'") && withoutPrefix.endsWith("'"))
  316. ) {
  317. return withoutPrefix.slice(1, -1);
  318. }
  319. return withoutPrefix;
  320. }
  321. function normalizeModelText(value: unknown): string {
  322. if (typeof value !== "string" || !value.trim()) {
  323. throw new Error("模型响应缺少文本内容。");
  324. }
  325. return value.trim();
  326. }