import { Arguments } from 'yargs' import { SimpleGit } from 'simple-git' import { loadConfig } from '../../lib/config/utils/loadConfig' import { getApiKeyForModel, getModelAndProviderFromConfig, } from '../../lib/langchain/utils' import { resolveDynamicService } from '../../lib/langchain/utils/dynamicModels' import { LangChainCancelledError } from '../../lib/langchain/errors' import { executeChainStreaming } from '../../lib/langchain/utils/executeChainStreaming' import { executeChainWithSchema } from '../../lib/langchain/utils/executeChainWithSchema' import { createSchemaParser } from '../../lib/langchain/utils/createSchemaParser' import { DEFAULT_RESPONSE_TOKEN_RESERVE, enforcePromptBudget, } from '../../lib/langchain/utils/enforcePromptBudget' import { formatCommitMessage } from '../../lib/langchain/utils/formatCommitMessage' import { getLlm } from '../../lib/langchain/utils/getLlm' import { getPrompt } from '../../lib/langchain/utils/getPrompt' import { getLanguageContext } from '../../lib/langchain/utils/languageContext' import { LLMModel } from '../../lib/langchain/types' import type { LlmUsageSurface } from '../../lib/langchain/utils/observability' import { FileChange } from '../../lib/types' import { fileChangeParser } from '../../lib/parsers/default' import { createFileChangeParserOptions } from '../../lib/parsers/default/utils/createFileChangeParserOptions' import { extractTicketIdFromBranchName } from '../../lib/simple-git/extractTicketIdFromBranchName' import { getChanges } from '../../lib/simple-git/getChanges' import { getCurrentBranchName } from '../../lib/simple-git/getCurrentBranchName' import { getPreviousCommits } from '../../lib/simple-git/getPreviousCommits' import { Logger } from '../../lib/utils/logger' import { getTokenCounterForProvider } from '../../lib/utils/tokenizer' import { hasCommitlintConfig } from '../../lib/utils/hasCommitlintConfig' import { resolveUseConventional } from './resolveUseConventional' import { CommitArgv, CommitMessageResponseSchema, CommitOptions, ConventionalCommitMessageResponseSchema, } from './config' import { COMMIT_PROMPT, CONVENTIONAL_COMMIT_PROMPT } from './prompt' import { salvageCommitMessageFromText } from './salvageCommitMessage' export type CommitDraftInput = { git: SimpleGit argv: Arguments /** * Repository root to resolve cwd-relative config sources (project config, * `.gitignore`/`.ignore`) against. Interactive `coco commit` already * `chdir`'d via `applyRepoFlag` so it can omit this; agent/MCP callers * resolve a repo root without mutating cwd and must pass it explicitly, or * the repository's `.coco.json` is silently skipped. */ cwd?: string logger?: Logger /** * Optional streaming callback (#881 phase 2). When provided AND * `config.service.streaming.enabled` is true, the first generation * attempt uses `executeChainStreaming` and fires this callback with * each text fragment as it arrives. The handler is intended for * live-preview rendering only; the final returned draft still goes * through the same fallback parser + commitlint validation as the * non-streaming path, so output behaviour is unchanged for the * caller. * * When the streaming attempt's accumulated text can't be parsed * into a valid commit message even by the fallback parser, the * function falls back to the existing non-streaming * `executeChainWithSchema` flow (which has its own LLM-level retry). * Net effect: streaming adds a UX preview without removing the * resilience of the schema-validated path. */ onStreamChunk?: (text: string, accumulated: string) => void /** * Optional `AbortSignal` for user-initiated cancellation. Forwarded to both * streaming and schema-validated generation paths. Cancellation returns a * `CommitDraftResult` with `cancelled: true` instead of being retried. */ signal?: AbortSignal /** * Override the change set the draft is generated from (#0.67 `coco amend`). * When provided, the staged-changes lookup is skipped and these changes are * summarized instead — letting `amend` draft a message from the last commit's * diff rather than the working-tree staging area. `commitRef` is the label * passed to the diff parser (e.g. `'HEAD'`). */ changeSource?: { changes: FileChange[]; commitRef: string } /** * Pre-consolidated context supplied by an agent or another trusted caller. * When present, skip staged-change discovery and fileChangeParser entirely. * The caller remains responsible for describing the intended repository * state and for surfacing whether that context was repository-derived or * externally supplied. */ preparedSummary?: string /** * Permit repository-defined prompt and commitlint configuration. Agent and * MCP callers leave this disabled unless the repository is explicitly * trusted, preventing executable commitlint config from running implicitly. */ trustRepositoryConfig?: boolean /** * Pre-resolved `conventions_context` prompt variable (#1956), e.g. from * `getConventionsContext`. Only the agent layer reads convention files * from disk -- this function never reads them itself, so interactive * `coco commit` callers that omit this stay unaffected. */ conventionsContext?: string /** Override the invocation surface stored in metadata-only local usage records. */ usageSurface?: LlmUsageSurface /** Disable persistent usage-ledger writes when a caller requires it. */ recordUsage?: boolean } export type CommitDraftMessage = { title: string body: string formatted: string } export type CommitDraftResult = { ok: boolean draft: string message?: CommitDraftMessage warnings: string[] validationErrors: string[] /** * Set when the call was aborted via an `AbortSignal` (#881 phase * 3). Callers should treat this as user intent, not an error — * the status line should reflect "cancelled" not "failed," and no * retry should fire. `draft` may carry partial accumulated text * from the streamed prefix; today the workstation discards it. */ cancelled?: boolean } const FORMAT_INSTRUCTIONS_TEMPLATE = (schemaDescription: string): string => ( `CRITICAL: You must return ONLY a valid JSON object with no additional text, explanations, or markdown formatting. REQUIRED JSON FORMAT: ${schemaDescription} EXAMPLE (follow this EXACT format - compact JSON on a single line or minimal whitespace): {"title": "feat(auth): add user authentication system", "body": "Implement JWT-based authentication with login and logout functionality. Includes password hashing and session management."} IMPORTANT RULES: - Return ONLY the JSON object - NO markdown code blocks, NO backticks, NO extra text - ALL string values MUST be enclosed in double quotes - Use compact JSON format (minimal whitespace) for best compatibility - NO trailing commas - NO comments or additional text outside the JSON - The "title" and "body" values must be properly quoted strings` ) function structuredDraft(formatted: string): CommitDraftMessage { const separatorIndex = formatted.indexOf('\n\n') return { title: separatorIndex === -1 ? formatted : formatted.slice(0, separatorIndex), body: separatorIndex === -1 ? '' : formatted.slice(separatorIndex + 2), formatted, } } /** * Word-wrap a single text line to the given max column width. * Preserves leading whitespace (e.g. indent for list items). * Lines that have no word-break opportunity (a single token longer than * maxLen) are left intact rather than broken mid-token. */ function wrapLine(line: string, maxLen: number): string { if (line.length <= maxLen) return line // Detect and preserve leading whitespace const leadMatch = line.match(/^(\s*)/) const indent = leadMatch ? leadMatch[1] : '' const words = line.trimStart().split(/\s+/) const lines: string[] = [] let current = indent for (const word of words) { if (current === indent) { // First word on this visual line — always place it even if it overflows current += word } else if ((current + ' ' + word).length <= maxLen) { current += ' ' + word } else { lines.push(current) current = indent + word } } if (current) lines.push(current) return lines.join('\n') } /** * Truncate a single-line header to the given max column width at the last * word boundary that fits, so the conventional `type(scope):` prefix is * never cut into. Falls back to a hard cut if there is no word boundary * (e.g. a single very long token) — the word-boundary search is restricted * to the subject (after the `type(scope): ` prefix) so a long single-word * subject can never be collapsed down to just the prefix. */ function truncateHeader(header: string, maxLen: number): string { if (header.length <= maxLen) return header const prefixMatch = header.match(/^[a-z]+(?:\([^)]*\))?!?:\s*/) const subjectStart = prefixMatch ? prefixMatch[0].length : 0 const truncated = header.slice(0, maxLen) const lastSpace = truncated.lastIndexOf(' ') const cut = lastSpace >= subjectStart ? truncated.slice(0, lastSpace) : truncated return cut.trimEnd() } /** * Attempt to mechanically repair a commit message to satisfy commitlint rules * that coco itself chose and generated text for. Handles the three most * common self-inflicted violations: * * 1. `body-max-line-length` — hard-wraps over-length body lines at word * boundaries using the limit extracted from the error message (defaults * to 100 if no number is found). * 2. `subject-case` — lower-cases the first character of the subject (the * part after `type(scope):`) whenever it's uppercase, without checking * which cases a repository's own rule actually allows. Safe because the * repaired draft is always re-validated before being accepted, so a * wrong-direction fix just falls through to the original failure. * 3. `header-max-length` — truncates the title at the last word boundary * that fits within the limit extracted from the error message (defaults * to 72 if no number is found). * * Returns the repaired message string, or the original when no repair rule * applies (so callers can always call this unconditionally). */ export function repairDraftAgainstValidationErrors( draft: string, validationErrors: string[], ): string { if (!draft || validationErrors.length === 0) return draft const separatorIndex = draft.indexOf('\n\n') let title = separatorIndex === -1 ? draft : draft.slice(0, separatorIndex) let body = separatorIndex === -1 ? '' : draft.slice(separatorIndex + 2) for (const error of validationErrors) { // --- header-max-length --- if (/header.{0,30}longer than/i.test(error) || /header-max-length/i.test(error)) { const limitMatch = error.match(/\b(\d+)\b/) const limit = limitMatch ? parseInt(limitMatch[1], 10) : 72 title = truncateHeader(title, limit) } // --- body-max-line-length --- if (/body.{0,30}lines?.{0,30}longer than/i.test(error) || /body-max-line-length/i.test(error)) { const limitMatch = error.match(/\b(\d+)\b/) const limit = limitMatch ? parseInt(limitMatch[1], 10) : 100 if (body) { body = body .split('\n') .map((line) => wrapLine(line, limit)) .join('\n') } } // --- subject-case (lower-case / sentence-case violations) --- // Lower-cases just the first character of the subject whenever it's // uppercase — the most common violation (capitalised first word), and // the one that satisfies both `sentence-case` and `lower-case`. This is // applied unconditionally on any subject-case error, without checking // which cases a repository's own rule actually allows (e.g. a rule // restricted to `start-case`/`pascal-case` would want the capital kept). // That's safe because the repaired draft is always re-validated below // before being accepted — a wrong-direction fix just fails re-validation // and falls through to the original `ok: false` result, never a silently // broken success. if (/subject.{0,30}(must be|case)/i.test(error) || /subject-case/i.test(error)) { // Extract subject from conventional title: "type(scope): Subject text" const conventionalMatch = title.match(/^([a-z]+(?:\([^)]*\))?!?):\s*(.*)$/) if (conventionalMatch) { const prefix = conventionalMatch[1] const subject = conventionalMatch[2] if (subject && subject[0] === subject[0].toUpperCase() && subject[0] !== subject[0].toLowerCase()) { // Lower-case the first character of the subject title = `${prefix}: ${subject[0].toLowerCase()}${subject.slice(1)}` } } } } return body ? `${title}\n\n${body}` : title } /** * Generate a commit message draft with no UI side effects. * * Mirrors the LLM-chain logic from `commit/handler.ts`'s agent callback but * skips the review loop, ora spinners, Inquirer prompts, and stdout writes * that would corrupt the surrounding Ink TUI alt screen. Validation failures * are surfaced as `validationErrors`/`warnings` rather than driving an * interactive retry flow — the TUI can re-invoke or let the user edit. */ export async function generateCommitDraft({ git, argv, cwd, logger = new Logger({ silent: true }), onStreamChunk, signal, changeSource, preparedSummary, trustRepositoryConfig = true, conventionsContext, usageSurface, recordUsage, }: CommitDraftInput): Promise { const config = loadConfig(argv as Arguments, { cwd }) const key = getApiKeyForModel(config) const { provider } = getModelAndProviderFromConfig(config) const commitService = resolveDynamicService(config, 'commit') const summaryService = resolveDynamicService(config, 'summarize') const model = commitService.model if (config.service.authentication.type !== 'None' && !key) { return { ok: false, draft: '', warnings: [], validationErrors: ['No API key configured for the commit service.'], } } const tokenizer = await getTokenCounterForProvider(provider, String(model)) const llm = await getLlm(provider, model as LLMModel, { ...config, service: commitService }) const summaryLlm = await getLlm(provider, summaryService.model as LLMModel, { ...config, service: summaryService, }) const useConventional = await resolveUseConventional({ argvConventional: argv.conventional, configConventional: trustRepositoryConfig ? config.conventionalCommits : undefined, detectCommitlint: trustRepositoryConfig, }) // `coco amend` passes an explicit change set (the last commit's diff). The // default path summarizes the staged working tree. Agent callers may pass a // pre-consolidated summary and bypass both discovery and summarization. const diffLabel = changeSource?.commitRef ?? '--staged' const changes = preparedSummary ? [] : await (async () => { if (changeSource) { return changeSource.changes } if (config.noDiff) { const status = await git.status() return status.files.map((file) => ({ filePath: file.path, status: (file.index === 'A' || file.index === '?' ? 'added' : 'modified') as 'added' | 'modified', summary: file.path, })) } const result = await getChanges({ git, options: { ignoredFiles: config.ignoredFiles || undefined, ignoredExtensions: config.ignoredExtensions || undefined, }, }) return result.staged })() if (!preparedSummary && (!changes || changes.length === 0)) { return { ok: false, draft: '', warnings: [changeSource ? 'No changes detected to summarize.' : 'No staged changes detected.'], validationErrors: [], } } const schema = useConventional ? ConventionalCommitMessageResponseSchema : CommitMessageResponseSchema const promptTemplate = useConventional ? CONVENTIONAL_COMMIT_PROMPT : COMMIT_PROMPT const prompt = getPrompt({ template: trustRepositoryConfig ? config.prompt || (promptTemplate.template as string) : promptTemplate.template as string, variables: promptTemplate.inputVariables, fallback: promptTemplate, }) const formatInstructions = FORMAT_INSTRUCTIONS_TEMPLATE(schema.description || '') const additionalContext = argv.additional ? `## Additional Context\n${argv.additional}` : '' let commitHistory = '' const previousCommitsCount = Number(argv.withPreviousCommits || 0) if (previousCommitsCount > 0) { const commitHistoryData = await getPreviousCommits({ git, count: previousCommitsCount }) if (commitHistoryData) { commitHistory = `## Commit History\n${commitHistoryData}` } } const includeBranchName = argv.includeBranchName !== undefined ? argv.includeBranchName : config.includeBranchName !== false const needsBranchName = includeBranchName || Boolean(argv.appendTicket) const branchName = needsBranchName ? await getCurrentBranchName({ git }) : '' const branchNameContext = includeBranchName ? `Current git branch name: ${branchName}` : '' const warnings: string[] = [] const hasCommitLintConfig = trustRepositoryConfig ? await hasCommitlintConfig() : false const useSafeBuiltInValidation = !trustRepositoryConfig && useConventional let commitlintRulesContext = '' let validationEnabled = useSafeBuiltInValidation || ( trustRepositoryConfig && (useConventional || hasCommitLintConfig) ) if (validationEnabled && trustRepositoryConfig) { const { getCommitlintRulesContext, checkCommitlintAvailability } = await import( '../../lib/utils/commitlintValidator' ) const availability = checkCommitlintAvailability() if (!availability.available) { warnings.push( `Skipping commitlint validation: missing packages (${availability.missingPackages.join(', ')}).` ) validationEnabled = false } else { commitlintRulesContext = await getCommitlintRulesContext() } } else if (useSafeBuiltInValidation) { // Repository commitlint config is never read on this path (untrusted), // so constrain generation with the same hardcoded rules // `validateConventionalCommitMessage` enforces, rather than only // validating after the fact. const { getBuiltInConventionalRulesContext } = await import( '../../lib/utils/commitlintValidator' ) commitlintRulesContext = getBuiltInConventionalRulesContext() } const baseVariables: Record = { summary: '', format_instructions: formatInstructions, additional_context: additionalContext, commit_history: commitHistory, branch_name_context: branchNameContext, commitlint_rules_context: commitlintRulesContext, language_context: getLanguageContext( argv.language || (trustRepositoryConfig ? config.language : undefined), { taskDescription: 'commit message', preserveConventionalTokens: useConventional, }, ), conventions_context: conventionsContext ?? '', } // Reconciles the summarizer's `|| 4096` fallback (createFileChangeParserOptions // -> summarizeDiffs) with the prompt budget below — both must share one number, // not the summarizer's 4096 vs the prompt's stray 2048. const promptTokenLimit = config.service.tokenLimit || 4096 // Budget the summary to leave headroom for the rest of the rendered prompt // (format instructions, commit history, branch context, commitlint rules) plus // the reserved response tokens, so a summary that legitimately maxes out its // target doesn't push the full prompt over budget and get silently re-trimmed. const overheadTokenCount = tokenizer(await prompt.format(baseVariables)) const summaryTokenBudget = Math.max( 512, promptTokenLimit - overheadTokenCount - DEFAULT_RESPONSE_TOKEN_RESERVE ) const summary = preparedSummary || (config.noDiff && !changeSource ? `Staged files:\n${changes.map((c) => `${c.status}: ${c.filePath}`).join('\n')}` : await fileChangeParser({ changes, commit: diffLabel, options: createFileChangeParserOptions({ command: 'commit', tokenizer, git, llm: summaryLlm, logger, provider, model: String(summaryService.model), service: { ...config.service, tokenLimit: summaryTokenBudget }, }), })) if (!summary || !summary.length) { return { ok: false, draft: '', warnings: [...warnings, 'Diff summary was empty after parsing staged changes.'], validationErrors: [], } } baseVariables.summary = summary const maxParsingAttempts = config.service.provider === 'ollama' && 'maxParsingAttempts' in config.service ? config.service.maxParsingAttempts || 3 : 3 let lastValidationErrors: string[] = [] let validationFeedback = '' let lastDraft = '' try { // Two attempts max — one initial generation plus one retry that incorporates // commitlint feedback. Beyond that we surface warnings and let the TUI user // edit the draft manually rather than driving an interactive prompt loop. for (let attempt = 1; attempt <= 2; attempt++) { const variables = { ...baseVariables, additional_context: validationFeedback ? `${baseVariables.additional_context}\n\n## Validation Errors from Previous Attempt\nPlease fix the following issues:\n${validationFeedback}` : baseVariables.additional_context, } const budgetedPrompt = await enforcePromptBudget({ prompt, variables, tokenizer, maxTokens: promptTokenLimit, }) // Streaming path (#881 phase 2). Active when the caller supplied // an `onStreamChunk` AND the config opted in. Only the FIRST // attempt streams; the commitlint-retry attempt (attempt === 2) // and the existing executeChainWithSchema retry loop run // non-streaming so we keep the schema-validated retry as the // backstop when the streamed text can't be salvaged. const streamingEnabled = Boolean( onStreamChunk && config.service.streaming?.enabled ) const shouldStreamThisAttempt = streamingEnabled && attempt === 1 let commitMsg: { title: string; body: string } if (shouldStreamThisAttempt && onStreamChunk) { // The streaming chain bypasses the schema parser during the // stream itself (no streaming-aware JSON parser today) and // delivers the raw accumulated text to a no-op `parser.invoke`. // We then salvage the structured result via the same lossy // recovery the non-streaming fallbackParser uses. If the // salvager produces a plausible draft, we use it. Otherwise we // fall through to executeChainWithSchema below for a real // schema-validated retry — paying for a second LLM call only // on the edge case where the streamed output is unsalvageable. // // `: any` matches every other `createSchemaParser` call site // (recap / changelog / review / executeChainWithSchema): since // @langchain/core 1.1.48, `StructuredOutputParser.fromZodSchema` // returns a parser whose output type is erased to `unknown` (the // bundled Zod 4 types no longer flow through), so a strictly-typed // assignment no longer satisfies `executeChainStreaming`'s // `Runnable<…, { title, body }>` parser param. The runtime parser // is unchanged; only its inferred TS type regressed. // eslint-disable-next-line @typescript-eslint/no-explicit-any const streamingParser: any = createSchemaParser(schema) // Capture the final accumulated text out-of-band so we can // attempt salvage if the parser throws on completion (audit // finding #1). Updated on every chunk; the last value is // whatever the stream produced before the parser ran. Empty // string when streaming throws before any chunks arrived. let streamedAccumulated = '' let salvaged: { title: string; body: string } | undefined try { // `executeChainStreaming` runs the parser on the accumulated // text at completion. StructuredOutputParser will throw when // the model produced unparseable JSON — we catch that below // and salvage manually. The happy-path zod-validated object // becomes our commitMsg. commitMsg = await executeChainStreaming<{ title: string; body: string }>({ llm, prompt, variables: budgetedPrompt.variables, parser: streamingParser, onChunk: ({ text, accumulated }) => { streamedAccumulated = accumulated onStreamChunk(text, accumulated) }, signal, logger, tokenizer, metadata: { task: useConventional ? 'commit-message-conventional' : 'commit-message', command: 'commit-draft', provider, model: String(model), surface: usageSurface, recordUsage, }, }) } catch (streamErr) { // User-initiated cancel (#881 phase 3). Bail out of the // entire attempt loop and let the caller distinguish // "cancelled" from "failed" in the status line. We do NOT // fall through to the non-streaming retry on cancel — the // user explicitly asked to stop, kicking off a fresh // unstreamable LLM call would defy that intent. if (streamErr instanceof LangChainCancelledError) { return { ok: false, draft: streamErr.accumulated || '', warnings, validationErrors: [], cancelled: true, } } // Audit finding #1: try the lossy salvager on the accumulated // text before paying for a second LLM call. The salvager // strips code fences, attempts strict JSON parse, and falls // back to "first line is title, rest is body." We only accept // its output when it produced a real title — the placeholder // title ("Auto-generated commit") means the salvager // couldn't extract anything meaningful and the non-streaming // retry is the better choice. if (streamedAccumulated) { const candidate = salvageCommitMessageFromText(streamedAccumulated) if (candidate.title && candidate.title !== 'Auto-generated commit') { salvaged = candidate logger.verbose( `Streaming parser failed but salvager recovered a draft from ${streamedAccumulated.length} accumulated chars; skipping non-streaming retry.`, { color: 'green' }, ) } } if (!salvaged) { logger.verbose( `Streaming attempt produced unparseable output: ${ streamErr instanceof Error ? streamErr.message : String(streamErr) }. Falling back to non-streaming.`, { color: 'yellow' } ) } } // Type-narrow: commitMsg is set inside try{}, but TS doesn't // see that across the catch. Re-init through the salvage path // if streaming threw. if (salvaged) { commitMsg = salvaged } else if (!(commitMsg!)) { // Streaming threw AND the salvager couldn't recover anything // useful; fall back to the standard non-streaming flow. // Documented trade-off from the issue: streaming gives us a // preview but the validated result still comes from the // schema-aware retry path when both streaming AND salvage // fail. commitMsg = await executeChainWithSchema(schema, llm, prompt, budgetedPrompt.variables, { logger, tokenizer, metadata: { task: useConventional ? 'commit-message-conventional' : 'commit-message', command: 'commit-draft', provider, model: String(model), surface: usageSurface, recordUsage, }, retryOptions: { maxAttempts: maxParsingAttempts }, fallbackParser: salvageCommitMessageFromText, signal, }) } } else { commitMsg = await executeChainWithSchema(schema, llm, prompt, budgetedPrompt.variables, { logger, tokenizer, metadata: { task: useConventional ? 'commit-message-conventional' : 'commit-message', command: 'commit-draft', provider, model: String(model), surface: usageSurface, recordUsage, }, retryOptions: { maxAttempts: maxParsingAttempts, }, fallbackParser: salvageCommitMessageFromText, signal, }) } const ticketId = extractTicketIdFromBranchName(branchName) const fullMessage = formatCommitMessage(commitMsg, { append: argv.append, ticketId: ticketId || undefined, appendTicket: argv.appendTicket, }) lastDraft = fullMessage if (!validationEnabled) { return { ok: true, draft: fullMessage, message: structuredDraft(fullMessage), warnings, validationErrors: [] } } const { validateCommitMessage, validateConventionalCommitMessage, } = await import('../../lib/utils/commitlintValidator') const validationResult = useSafeBuiltInValidation ? await validateConventionalCommitMessage(fullMessage) : await validateCommitMessage(fullMessage) if (validationResult.missingDependencies && validationResult.missingDependencies.length > 0) { warnings.push( `Skipping commitlint validation: missing packages (${validationResult.missingDependencies.join(', ')}).` ) return { ok: true, draft: fullMessage, message: structuredDraft(fullMessage), warnings, validationErrors: [] } } if (validationResult.valid) { return { ok: true, draft: fullMessage, message: structuredDraft(fullMessage), warnings, validationErrors: [] } } lastValidationErrors = validationResult.errors validationFeedback = validationResult.errors.map((error) => `- ${error}`).join('\n') } } catch (error) { if (error instanceof LangChainCancelledError) { return { ok: false, draft: error.accumulated || '', warnings, validationErrors: [], cancelled: true, } } throw error } // Both attempts failed validation — try a mechanical repair pass before // giving up. Re-wrap over-long body lines and normalise subject case where // the fix is unambiguous. Re-validate after the repair so we only return // ok: true when the result actually passes. if (lastDraft && lastValidationErrors.length > 0) { const repairedDraft = repairDraftAgainstValidationErrors(lastDraft, lastValidationErrors) if (repairedDraft !== lastDraft) { try { const { validateCommitMessage: revalidateCommitMessage, validateConventionalCommitMessage: revalidateConventionalCommitMessage, } = await import('../../lib/utils/commitlintValidator') const repairedResult = useSafeBuiltInValidation ? await revalidateConventionalCommitMessage(repairedDraft) : await revalidateCommitMessage(repairedDraft) if (repairedResult.valid) { warnings.push('Commit message was automatically repaired to satisfy commitlint rules.') return { ok: true, draft: repairedDraft, message: structuredDraft(repairedDraft), warnings, validationErrors: [], } } // Repair didn't fully fix all errors — update lastDraft and errors // so the caller gets the best available draft. lastDraft = repairedDraft lastValidationErrors = repairedResult.errors } catch { // Repair validation failed unexpectedly; fall through with the original draft. } } } // Return the latest draft so the user can hand-edit in the compose surface, // plus the validator output for context. return { ok: false, draft: lastDraft, ...(lastDraft ? { message: structuredDraft(lastDraft) } : {}), warnings, validationErrors: lastValidationErrors, } }