@eldrforge/ai-service 0.1.11 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1121,7 +1121,7 @@ function createGetFileHistoryTool$1() {
|
|
|
1121
1121
|
execute: async (params, context) => {
|
|
1122
1122
|
const { filePaths, limit = 10, format = "summary" } = params;
|
|
1123
1123
|
const workingDir = context?.workingDirectory || process.cwd();
|
|
1124
|
-
const formatArg = format === "detailed" ?
|
|
1124
|
+
const formatArg = format === "detailed" ? '--format="%H%n%an (%ae)%n%ad%n%s%n%n%b%n---"' : '--format="%h - %s (%an, %ar)"';
|
|
1125
1125
|
const fileArgs = filePaths.join(" ");
|
|
1126
1126
|
const command = `git log ${formatArg} -n ${limit} -- ${fileArgs}`;
|
|
1127
1127
|
try {
|
|
@@ -1630,7 +1630,7 @@ function createGetFileHistoryTool() {
|
|
|
1630
1630
|
execute: async (params, context) => {
|
|
1631
1631
|
const { filePaths, limit = 10, format = "summary" } = params;
|
|
1632
1632
|
const workingDir = context?.workingDirectory || process.cwd();
|
|
1633
|
-
const formatArg = format === "detailed" ?
|
|
1633
|
+
const formatArg = format === "detailed" ? '--format="%H%n%an (%ae)%n%ad%n%s%n%n%b%n---"' : '--format="%h - %s (%an, %ar)"';
|
|
1634
1634
|
const fileArgs = filePaths.join(" ");
|
|
1635
1635
|
const command = `git log ${formatArg} -n ${limit} -- ${fileArgs}`;
|
|
1636
1636
|
try {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/logger.ts","../src/ai.ts","../src/interactive.ts","../src/prompts/commit.ts","../src/prompts/release.ts","../src/prompts/review.ts","../src/agentic/executor.ts","../src/tools/registry.ts","../src/tools/commit-tools.ts","../src/agentic/commit.ts","../src/tools/release-tools.ts","../src/agentic/release.ts"],"sourcesContent":["/**\n * Optional logger support\n * If winston is available as a peer dependency, use it\n * Otherwise, provide a no-op logger\n */\n\nimport type { Logger } from './types';\n\nlet logger: Logger | undefined;\n\n/**\n * Set a custom logger instance\n */\nexport function setLogger(customLogger: Logger): void {\n logger = customLogger;\n}\n\n/**\n * Create a no-op logger that does nothing\n */\nexport function createNoOpLogger(): Logger {\n return {\n info: () => {},\n error: () => {},\n warn: () => {},\n debug: () => {},\n };\n}\n\n/**\n * Attempt to load winston logger\n * @returns winston logger if available, otherwise null\n */\nexport function tryLoadWinston(): Logger | null {\n try {\n // Dynamic import to avoid hard dependency\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const winston = require('winston');\n if (winston && winston.createLogger) {\n return winston.createLogger({\n level: 'info',\n format: winston.format.simple(),\n transports: [new winston.transports.Console()],\n });\n }\n } catch {\n // Winston not available\n }\n return null;\n}\n\n/**\n * Get the current logger or a no-op logger\n */\nexport function getLogger(): Logger {\n if (logger) {\n return logger;\n }\n\n // Try to load winston if available\n const winstonLogger = tryLoadWinston();\n if (winstonLogger) {\n logger = winstonLogger;\n return winstonLogger;\n }\n\n // Return no-op logger\n return createNoOpLogger();\n}\n","import { OpenAI } from 'openai';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\nimport { safeJsonParse } from '@eldrforge/git-tools';\nimport fs from 'fs';\nimport { getLogger } from './logger';\nimport type { AIConfig, Transcription, StorageAdapter, Logger } from './types';\n\nexport interface OpenAIOptions {\n responseFormat?: any;\n model?: string;\n debug?: boolean;\n debugFile?: string;\n debugRequestFile?: string;\n debugResponseFile?: string;\n maxTokens?: number;\n openaiReasoning?: 'low' | 'medium' | 'high';\n openaiMaxOutputTokens?: number;\n storage?: StorageAdapter;\n logger?: Logger;\n tools?: any[]; // OpenAI tool definitions\n toolChoice?: 'auto' | 'none' | 'required' | { type: 'function'; function: { name: string } };\n}\n\nexport interface TranscriptionOptions {\n model?: string;\n debug?: boolean;\n debugFile?: string;\n debugRequestFile?: string;\n debugResponseFile?: string;\n outputDirectory?: string;\n storage?: StorageAdapter;\n logger?: Logger;\n onArchive?: (audioPath: string, transcriptionText: string) => Promise<void>;\n}\n\n/**\n * Get the appropriate model to use based on command-specific configuration\n * Command-specific model overrides the global model setting\n */\nexport function getModelForCommand(config: AIConfig, commandName: string): string {\n let commandModel: string | undefined;\n\n switch (commandName) {\n case 'commit':\n case 'audio-commit':\n commandModel = config.commands?.commit?.model;\n break;\n case 'release':\n commandModel = config.commands?.release?.model;\n break;\n case 'review':\n case 'audio-review':\n commandModel = config.commands?.review?.model;\n break;\n default:\n // For other commands, just use global model\n break;\n }\n\n // Return command-specific model if available, otherwise global model\n return commandModel || config.model || 'gpt-4o-mini';\n}\n\n/**\n * Get the appropriate OpenAI reasoning level based on command-specific configuration\n * Command-specific reasoning overrides the global reasoning setting\n */\nexport function getOpenAIReasoningForCommand(config: AIConfig, commandName: string): 'low' | 'medium' | 'high' {\n let commandReasoning: 'low' | 'medium' | 'high' | undefined;\n\n switch (commandName) {\n case 'commit':\n case 'audio-commit':\n commandReasoning = config.commands?.commit?.reasoning;\n break;\n case 'release':\n commandReasoning = config.commands?.release?.reasoning;\n break;\n case 'review':\n case 'audio-review':\n commandReasoning = config.commands?.review?.reasoning;\n break;\n default:\n // For other commands, just use global reasoning\n break;\n }\n\n // Return command-specific reasoning if available, otherwise global reasoning\n return commandReasoning || config.reasoning || 'low';\n}\n\nexport class OpenAIError extends Error {\n constructor(message: string, public readonly isTokenLimitError: boolean = false) {\n super(message);\n this.name = 'OpenAIError';\n }\n}\n\n// Check if an error is a token limit exceeded error\nexport function isTokenLimitError(error: any): boolean {\n if (!error?.message) return false;\n\n const message = error.message.toLowerCase();\n return message.includes('maximum context length') ||\n message.includes('context_length_exceeded') ||\n message.includes('token limit') ||\n message.includes('too many tokens') ||\n message.includes('reduce the length');\n}\n\n// Check if an error is a rate limit error\nexport function isRateLimitError(error: any): boolean {\n if (!error?.message && !error?.code && !error?.status) return false;\n\n // Check for OpenAI specific rate limit indicators\n if (error.status === 429 || error.code === 'rate_limit_exceeded') {\n return true;\n }\n\n // Only check message if it exists\n if (error.message) {\n const message = error.message.toLowerCase();\n return message.includes('rate limit exceeded') ||\n message.includes('too many requests') ||\n message.includes('quota exceeded') ||\n (message.includes('rate') && message.includes('limit'));\n }\n\n return false;\n}\n\n/**\n * Create OpenAI completion with optional debug and retry support\n */\nexport async function createCompletion(\n messages: ChatCompletionMessageParam[],\n options: OpenAIOptions = { model: \"gpt-4o-mini\" }\n): Promise<string | any> {\n const logger = options.logger || getLogger();\n let openai: OpenAI | null = null;\n\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n // Create the client which we'll close in the finally block.\n const timeoutMs = parseInt(process.env.OPENAI_TIMEOUT_MS || '300000'); // Default to 5 minutes\n openai = new OpenAI({\n apiKey: apiKey,\n timeout: timeoutMs,\n });\n\n const modelToUse = options.model || \"gpt-4o-mini\";\n\n // Calculate request size\n const requestSize = JSON.stringify(messages).length;\n const requestSizeKB = (requestSize / 1024).toFixed(2);\n\n // Log model, reasoning level, and request size\n const reasoningInfo = options.openaiReasoning ? ` | Reasoning: ${options.openaiReasoning}` : '';\n logger.info('🤖 Making request to OpenAI');\n logger.info(' Model: %s%s', modelToUse, reasoningInfo);\n logger.info(' Request size: %s KB (%s bytes)', requestSizeKB, requestSize.toLocaleString());\n\n logger.debug('Sending prompt to OpenAI: %j', messages);\n\n // Use openaiMaxOutputTokens if specified (highest priority), otherwise fall back to maxTokens, or default to 10000\n const maxCompletionTokens = options.openaiMaxOutputTokens ?? options.maxTokens ?? 10000;\n\n // Save request debug file if enabled\n if (options.debug && (options.debugRequestFile || options.debugFile) && options.storage) {\n const requestData = {\n model: modelToUse,\n messages,\n max_completion_tokens: maxCompletionTokens,\n response_format: options.responseFormat,\n reasoning_effort: options.openaiReasoning,\n };\n const debugFile = options.debugRequestFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(requestData, null, 2));\n logger.debug('Wrote request debug file to %s', debugFile);\n }\n\n // Prepare the API call options\n const apiOptions: any = {\n model: modelToUse,\n messages,\n max_completion_tokens: maxCompletionTokens,\n response_format: options.responseFormat,\n };\n\n // Add tools if provided\n if (options.tools && options.tools.length > 0) {\n apiOptions.tools = options.tools;\n apiOptions.tool_choice = options.toolChoice || 'auto';\n }\n\n // Add reasoning parameter if specified and model supports it\n if (options.openaiReasoning && (modelToUse.includes('gpt-5') || modelToUse.includes('o3'))) {\n apiOptions.reasoning_effort = options.openaiReasoning;\n }\n\n // Add timeout wrapper to the OpenAI API call\n const startTime = Date.now();\n const completionPromise = openai.chat.completions.create(apiOptions);\n\n // Create timeout promise with proper cleanup to prevent memory leaks\n let timeoutId: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<never>((_, reject) => {\n const timeoutMs = parseInt(process.env.OPENAI_TIMEOUT_MS || '300000'); // Default to 5 minutes\n timeoutId = setTimeout(() => reject(new OpenAIError(`OpenAI API call timed out after ${timeoutMs/1000} seconds`)), timeoutMs);\n });\n\n // Add progress indicator that updates every 5 seconds\n let progressIntervalId: NodeJS.Timeout | null = null;\n progressIntervalId = setInterval(() => {\n const elapsed = Math.round((Date.now() - startTime) / 1000);\n logger.info(' ⏳ Waiting for response... %ds', elapsed);\n }, 5000);\n\n let completion;\n try {\n completion = await Promise.race([completionPromise, timeoutPromise]);\n } finally {\n // Clear the timeout to prevent memory leaks\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n }\n // Clear the progress interval\n if (progressIntervalId !== null) {\n clearInterval(progressIntervalId);\n }\n }\n\n const elapsedTime = Date.now() - startTime;\n\n // Save response debug file if enabled\n if (options.debug && (options.debugResponseFile || options.debugFile) && options.storage) {\n const debugFile = options.debugResponseFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(completion, null, 2));\n logger.debug('Wrote response debug file to %s', debugFile);\n }\n\n const message = completion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError('No response message received from OpenAI');\n }\n\n // If tools are being used, return the full message object (includes tool_calls)\n if (options.tools && options.tools.length > 0) {\n // Log elapsed time\n const elapsedTimeFormatted = elapsedTime >= 1000\n ? `${(elapsedTime / 1000).toFixed(1)}s`\n : `${elapsedTime}ms`;\n logger.info(' Time: %s', elapsedTimeFormatted);\n\n // Log token usage if available\n if (completion.usage) {\n logger.info(' Token usage: %s prompt + %s completion = %s total',\n completion.usage.prompt_tokens?.toLocaleString() || '?',\n completion.usage.completion_tokens?.toLocaleString() || '?',\n completion.usage.total_tokens?.toLocaleString() || '?'\n );\n }\n\n return message; // Return full message object for tool handling\n }\n\n // For non-tool calls, return content as string\n const response = message.content?.trim();\n if (!response) {\n throw new OpenAIError('No response content received from OpenAI');\n }\n\n // Calculate and log response size\n const responseSize = response.length;\n const responseSizeKB = (responseSize / 1024).toFixed(2);\n logger.info(' Response size: %s KB (%s bytes)', responseSizeKB, responseSize.toLocaleString());\n\n // Log elapsed time\n const elapsedTimeFormatted = elapsedTime >= 1000\n ? `${(elapsedTime / 1000).toFixed(1)}s`\n : `${elapsedTime}ms`;\n logger.info(' Time: %s', elapsedTimeFormatted);\n\n // Log token usage if available\n if (completion.usage) {\n logger.info(' Token usage: %s prompt + %s completion = %s total',\n completion.usage.prompt_tokens?.toLocaleString() || '?',\n completion.usage.completion_tokens?.toLocaleString() || '?',\n completion.usage.total_tokens?.toLocaleString() || '?'\n );\n }\n\n logger.debug('Received response from OpenAI: %s...', response.substring(0, 30));\n if (options.responseFormat) {\n return safeJsonParse(response, 'OpenAI API response');\n } else {\n return response;\n }\n\n } catch (error: any) {\n logger.error('Error calling OpenAI API: %s %s', error.message, error.stack);\n const isTokenError = isTokenLimitError(error);\n throw new OpenAIError(`Failed to create completion: ${error.message}`, isTokenError);\n } finally {\n // OpenAI client cleanup is handled automatically by the library\n // No manual cleanup needed for newer versions\n }\n}\n\n/**\n * Create completion with automatic retry on token limit errors\n */\nexport async function createCompletionWithRetry(\n messages: ChatCompletionMessageParam[],\n options: OpenAIOptions = { model: \"gpt-4o-mini\" },\n retryCallback?: (attempt: number) => Promise<ChatCompletionMessageParam[]>\n): Promise<string | any> {\n const logger = options.logger || getLogger();\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const messagesToSend = attempt === 1 ? messages : (retryCallback ? await retryCallback(attempt) : messages);\n return await createCompletion(messagesToSend, options);\n } catch (error: any) {\n if (error instanceof OpenAIError && error.isTokenLimitError && attempt < maxRetries && retryCallback) {\n logger.warn('Token limit exceeded on attempt %d/%d, retrying with reduced content...', attempt, maxRetries);\n // Add exponential backoff for token limit errors\n const backoffMs = Math.min(1000 * Math.pow(2, attempt - 1), 10000);\n await new Promise(resolve => setTimeout(resolve, backoffMs));\n continue;\n } else if (isRateLimitError(error) && attempt < maxRetries) {\n // Handle rate limiting with exponential backoff\n const backoffMs = Math.min(2000 * Math.pow(2, attempt - 1), 15000); // More reasonable backoff: 2s, 4s, 8s, max 15s\n logger.warn(`Rate limit hit on attempt ${attempt}/${maxRetries}, waiting ${backoffMs}ms before retry...`);\n await new Promise(resolve => setTimeout(resolve, backoffMs));\n continue;\n }\n throw error;\n }\n }\n\n // This should never be reached, but TypeScript requires it\n throw new OpenAIError('Max retries exceeded');\n}\n\n/**\n * Transcribe audio file using OpenAI Whisper API\n */\nexport async function transcribeAudio(\n filePath: string,\n options: TranscriptionOptions = { model: \"whisper-1\" }\n): Promise<Transcription> {\n const logger = options.logger || getLogger();\n let openai: OpenAI | null = null;\n let audioStream: fs.ReadStream | null = null;\n let streamClosed = false;\n\n // Helper function to safely close the stream\n const closeAudioStream = () => {\n if (audioStream && !streamClosed) {\n try {\n // Only call destroy if it exists and the stream isn't already destroyed\n if (typeof audioStream.destroy === 'function' && !audioStream.destroyed) {\n audioStream.destroy();\n }\n streamClosed = true;\n logger.debug('Audio stream closed successfully');\n } catch (streamErr) {\n logger.debug('Failed to destroy audio read stream: %s', (streamErr as Error).message);\n streamClosed = true; // Mark as closed even if destroy failed\n }\n }\n };\n\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n openai = new OpenAI({\n apiKey: apiKey,\n });\n\n logger.debug('Transcribing audio file: %s', filePath);\n\n // Save request debug file if enabled\n if (options.debug && (options.debugRequestFile || options.debugFile) && options.storage) {\n const requestData = {\n model: options.model || \"whisper-1\",\n file: filePath, // Can't serialize the stream, so just save the file path\n response_format: \"json\",\n };\n const debugFile = options.debugRequestFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(requestData, null, 2));\n logger.debug('Wrote request debug file to %s', debugFile);\n }\n\n audioStream = fs.createReadStream(filePath);\n\n // Set up error handler for the stream to ensure cleanup on stream errors\n // Only add handler if the stream has the 'on' method (real streams)\n if (audioStream && typeof audioStream.on === 'function') {\n audioStream.on('error', (streamError) => {\n logger.error('Audio stream error: %s', streamError.message);\n closeAudioStream();\n });\n }\n\n let transcription;\n try {\n transcription = await openai.audio.transcriptions.create({\n model: options.model || \"whisper-1\",\n file: audioStream,\n response_format: \"json\",\n });\n // Close the stream immediately after successful API call to prevent race conditions\n closeAudioStream();\n } catch (apiError) {\n // Close the stream immediately if the API call fails\n closeAudioStream();\n throw apiError;\n }\n\n // Save response debug file if enabled\n if (options.debug && (options.debugResponseFile || options.debugFile) && options.storage) {\n const debugFile = options.debugResponseFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(transcription, null, 2));\n logger.debug('Wrote response debug file to %s', debugFile);\n }\n\n const response = transcription;\n if (!response) {\n throw new OpenAIError('No transcription received from OpenAI');\n }\n\n logger.debug('Received transcription from OpenAI: %s', response);\n\n // Archive the audio file and transcription if callback provided\n if (options.onArchive) {\n try {\n await options.onArchive(filePath, response.text);\n } catch (archiveError: any) {\n // Don't fail the transcription if archiving fails, just log the error\n logger.warn('Failed to archive audio file: %s', archiveError.message);\n }\n }\n\n return response;\n\n } catch (error: any) {\n logger.error('Error transcribing audio file: %s %s', error.message, error.stack);\n throw new OpenAIError(`Failed to transcribe audio: ${error.message}`);\n } finally {\n // Ensure the audio stream is properly closed to release file handles\n closeAudioStream();\n // OpenAI client cleanup is handled automatically by the library\n // No manual cleanup needed for newer versions\n }\n}\n\n","#!/usr/bin/env node\nimport { getLogger } from './logger';\nimport type { Logger, Choice, InteractiveOptions } from './types';\nimport { spawnSync } from 'child_process';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as fs from 'fs/promises';\n\n/**\n * Get user choice interactively from terminal input\n * @param prompt The prompt message to display\n * @param choices Array of available choices\n * @param options Additional options for customizing behavior\n * @returns Promise resolving to the selected choice key\n */\nexport async function getUserChoice(\n prompt: string,\n choices: Choice[],\n options: InteractiveOptions = {}\n): Promise<string> {\n const logger = options.logger || getLogger();\n\n logger.info(prompt);\n choices.forEach(choice => {\n logger.info(` [${choice.key}] ${choice.label}`);\n });\n logger.info('');\n\n // Check if stdin is a TTY (terminal) or piped\n if (!process.stdin.isTTY) {\n logger.error('⚠️ STDIN is piped but interactive mode is enabled');\n logger.error(' Interactive prompts cannot be used when input is piped');\n logger.error(' Solutions:');\n logger.error(' • Use terminal input instead of piping');\n\n // Add any additional suggestions\n if (options.nonTtyErrorSuggestions) {\n options.nonTtyErrorSuggestions.forEach(suggestion => {\n logger.error(` • ${suggestion}`);\n });\n }\n\n return 's'; // Default to skip\n }\n\n return new Promise((resolve, reject) => {\n let isResolved = false;\n let dataHandler: ((key: Buffer) => void) | null = null;\n let errorHandler: ((error: Error) => void) | null = null;\n\n const cleanup = () => {\n if (dataHandler) {\n process.stdin.removeListener('data', dataHandler);\n }\n if (errorHandler) {\n process.stdin.removeListener('error', errorHandler);\n }\n\n try {\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n process.stdin.pause();\n // Detach stdin again now that we're done\n if (typeof process.stdin.unref === 'function') {\n process.stdin.unref();\n }\n } catch {\n // Ignore cleanup errors\n }\n };\n\n const safeResolve = (value: string) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n resolve(value);\n }\n };\n\n const safeReject = (error: Error) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n reject(error);\n }\n };\n\n try {\n // Ensure stdin is referenced so the process doesn't exit while waiting for input\n if (typeof process.stdin.ref === 'function') {\n process.stdin.ref();\n }\n\n process.stdin.setRawMode(true);\n process.stdin.resume();\n\n dataHandler = (key: Buffer) => {\n try {\n const keyStr = key.toString().toLowerCase();\n const choice = choices.find(c => c.key === keyStr);\n if (choice) {\n logger.info(`Selected: ${choice.label}\\n`);\n safeResolve(choice.key);\n }\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Unknown error processing input'));\n }\n };\n\n errorHandler = (error: Error) => {\n safeReject(error);\n };\n\n process.stdin.on('data', dataHandler);\n process.stdin.on('error', errorHandler);\n\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Failed to setup input handlers'));\n }\n });\n}\n\n/**\n * Secure temporary file handle that prevents TOCTOU vulnerabilities\n */\nexport class SecureTempFile {\n private fd: fs.FileHandle | null = null;\n private filePath: string;\n private isCleanedUp = false;\n private logger: Logger;\n\n private constructor(filePath: string, fd: fs.FileHandle, logger?: Logger) {\n this.filePath = filePath;\n this.fd = fd;\n this.logger = logger || getLogger();\n }\n\n /**\n * Create a secure temporary file with proper permissions and atomic operations\n * @param prefix Prefix for the temporary filename\n * @param extension File extension (e.g., '.txt', '.md')\n * @param logger Optional logger instance\n * @returns Promise resolving to SecureTempFile instance\n */\n static async create(prefix: string = 'ai-service', extension: string = '.txt', logger?: Logger): Promise<SecureTempFile> {\n const tmpDir = os.tmpdir();\n const log = logger || getLogger();\n\n // Ensure temp directory exists and is writable (skip check in test environments)\n if (!process.env.VITEST) {\n try {\n await fs.access(tmpDir, fs.constants.W_OK);\n } catch (error: any) {\n // Try to create the directory if it doesn't exist\n try {\n await fs.mkdir(tmpDir, { recursive: true, mode: 0o700 });\n } catch (mkdirError: any) {\n throw new Error(`Temp directory not writable: ${tmpDir} - ${error.message}. Failed to create: ${mkdirError.message}`);\n }\n }\n }\n\n const tmpFilePath = path.join(tmpDir, `${prefix}_${Date.now()}_${Math.random().toString(36).substring(7)}${extension}`);\n\n // Create file with exclusive access and restrictive permissions (owner read/write only)\n // Using 'wx' flag ensures exclusive creation (fails if file exists)\n let fd: fs.FileHandle;\n try {\n fd = await fs.open(tmpFilePath, 'wx', 0o600);\n } catch (error: any) {\n if (error.code === 'EEXIST') {\n // Highly unlikely with timestamp + random suffix, but handle it\n throw new Error(`Temporary file already exists: ${tmpFilePath}`);\n }\n throw new Error(`Failed to create temporary file: ${error.message}`);\n }\n\n return new SecureTempFile(tmpFilePath, fd, log);\n }\n\n /**\n * Get the file path (use with caution in external commands)\n */\n get path(): string {\n if (this.isCleanedUp) {\n throw new Error('Temp file has been cleaned up');\n }\n return this.filePath;\n }\n\n /**\n * Write content to the temporary file\n */\n async writeContent(content: string): Promise<void> {\n if (!this.fd || this.isCleanedUp) {\n throw new Error('Temp file is not available for writing');\n }\n await this.fd.writeFile(content, 'utf8');\n }\n\n /**\n * Read content from the temporary file\n */\n async readContent(): Promise<string> {\n if (!this.fd || this.isCleanedUp) {\n throw new Error('Temp file is not available for reading');\n }\n const content = await this.fd.readFile('utf8');\n return content;\n }\n\n /**\n * Close the file handle\n */\n async close(): Promise<void> {\n if (this.fd && !this.isCleanedUp) {\n await this.fd.close();\n this.fd = null;\n }\n }\n\n /**\n * Securely cleanup the temporary file - prevents TOCTOU by using file descriptor\n */\n async cleanup(): Promise<void> {\n if (this.isCleanedUp) {\n return; // Already cleaned up\n }\n\n try {\n // Close file descriptor first if still open\n if (this.fd) {\n await this.fd.close();\n this.fd = null;\n }\n\n // Now safely remove the file\n // Use fs.unlink which is safer than checking existence first\n await fs.unlink(this.filePath);\n } catch (error: any) {\n // Only ignore ENOENT (file not found) errors\n if (error.code !== 'ENOENT') {\n this.logger.warn(`Failed to cleanup temp file ${this.filePath}: ${error.message}`);\n // Don't throw here to avoid masking main operations\n }\n } finally {\n this.isCleanedUp = true;\n }\n }\n}\n\n/**\n * Create a secure temporary file for editing with proper permissions\n * @param prefix Prefix for the temporary filename\n * @param extension File extension (e.g., '.txt', '.md')\n * @param logger Optional logger instance\n * @returns Promise resolving to the temporary file path\n * @deprecated Use SecureTempFile.create() for better security\n */\nexport async function createSecureTempFile(prefix: string = 'ai-service', extension: string = '.txt', logger?: Logger): Promise<string> {\n const secureTempFile = await SecureTempFile.create(prefix, extension, logger);\n await secureTempFile.close();\n return secureTempFile.path;\n}\n\n/**\n * Clean up a temporary file\n * @param filePath Path to the temporary file to clean up\n * @param logger Optional logger instance\n * @deprecated Use SecureTempFile.cleanup() for better security\n */\nexport async function cleanupTempFile(filePath: string, logger?: Logger): Promise<void> {\n const log = logger || getLogger();\n try {\n await fs.unlink(filePath);\n } catch (error: any) {\n // Only ignore ENOENT (file not found) errors\n if (error.code !== 'ENOENT') {\n log.warn(`Failed to cleanup temp file ${filePath}: ${error.message}`);\n }\n }\n}\n\nexport interface EditorResult {\n content: string;\n wasEdited: boolean;\n}\n\n/**\n * Open content in user's editor for editing\n * @param content Initial content to edit\n * @param templateLines Additional template lines to include (will be filtered out)\n * @param fileExtension File extension for syntax highlighting\n * @param editor Editor command to use (defaults to EDITOR/VISUAL env var or 'vi')\n * @param logger Optional logger instance\n * @returns Promise resolving to the edited content\n */\nexport async function editContentInEditor(\n content: string,\n templateLines: string[] = [],\n fileExtension: string = '.txt',\n editor?: string,\n logger?: Logger\n): Promise<EditorResult> {\n const log = logger || getLogger();\n const editorCmd = editor || process.env.EDITOR || process.env.VISUAL || 'vi';\n\n const secureTempFile = await SecureTempFile.create('ai-service_edit', fileExtension, log);\n try {\n // Build template content\n const templateContent = [\n ...templateLines,\n ...(templateLines.length > 0 ? [''] : []), // Add separator if we have template lines\n content,\n '',\n ].join('\\n');\n\n await secureTempFile.writeContent(templateContent);\n await secureTempFile.close(); // Close before external editor access\n\n log.info(`📝 Opening ${editorCmd} to edit content...`);\n\n // Open the editor synchronously\n const result = spawnSync(editorCmd, [secureTempFile.path], { stdio: 'inherit' });\n\n if (result.error) {\n throw new Error(`Failed to launch editor '${editorCmd}': ${result.error.message}`);\n }\n\n // Read the file back in, stripping comment lines\n const fileContent = (await fs.readFile(secureTempFile.path, 'utf8'))\n .split('\\n')\n .filter(line => !line.trim().startsWith('#'))\n .join('\\n')\n .trim();\n\n if (!fileContent) {\n throw new Error('Content is empty after editing');\n }\n\n log.info('✅ Content updated successfully');\n\n return {\n content: fileContent,\n wasEdited: fileContent !== content.trim()\n };\n\n } finally {\n // Always clean up the temp file securely\n await secureTempFile.cleanup();\n }\n}\n\n/**\n * Standard choices for interactive feedback loops\n */\nexport const STANDARD_CHOICES = {\n CONFIRM: { key: 'c', label: 'Confirm and proceed' },\n EDIT: { key: 'e', label: 'Edit in editor' },\n SKIP: { key: 's', label: 'Skip and abort' },\n IMPROVE: { key: 'i', label: 'Improve with LLM feedback' }\n} as const;\n\n/**\n * Get text input from the user\n * @param prompt The prompt message to display\n * @param options Additional options for customizing behavior\n * @returns Promise resolving to the user's text input\n */\nexport async function getUserTextInput(\n prompt: string,\n options: InteractiveOptions = {}\n): Promise<string> {\n const logger = options.logger || getLogger();\n\n // Check if stdin is a TTY (terminal) or piped\n if (!process.stdin.isTTY) {\n logger.error('⚠️ STDIN is piped but interactive text input is required');\n logger.error(' Interactive text input cannot be used when input is piped');\n logger.error(' Solutions:');\n logger.error(' • Use terminal input instead of piping');\n\n // Add any additional suggestions\n if (options.nonTtyErrorSuggestions) {\n options.nonTtyErrorSuggestions.forEach(suggestion => {\n logger.error(` • ${suggestion}`);\n });\n }\n\n throw new Error('Interactive text input requires a terminal');\n }\n\n logger.info(prompt);\n logger.info('(Press Enter when done, or type Ctrl+C to cancel)');\n logger.info('');\n\n return new Promise((resolve, reject) => {\n let inputBuffer = '';\n let isResolved = false;\n let dataHandler: ((chunk: string) => void) | null = null;\n let errorHandler: ((error: Error) => void) | null = null;\n\n const cleanup = () => {\n if (dataHandler) {\n process.stdin.removeListener('data', dataHandler);\n }\n if (errorHandler) {\n process.stdin.removeListener('error', errorHandler);\n }\n\n try {\n process.stdin.pause();\n // Detach stdin again now that we're done\n if (typeof process.stdin.unref === 'function') {\n process.stdin.unref();\n }\n } catch {\n // Ignore cleanup errors\n }\n };\n\n const safeResolve = (value: string) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n resolve(value);\n }\n };\n\n const safeReject = (error: Error) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n reject(error);\n }\n };\n\n try {\n // Ensure stdin is referenced so the process doesn't exit while waiting for input\n if (typeof process.stdin.ref === 'function') {\n process.stdin.ref();\n }\n\n process.stdin.setEncoding('utf8');\n process.stdin.resume();\n\n dataHandler = (chunk: string) => {\n try {\n inputBuffer += chunk;\n\n // Check if user pressed Enter (newline character)\n if (inputBuffer.includes('\\n')) {\n const userInput = inputBuffer.replace(/\\n$/, '').trim();\n\n if (userInput === '') {\n logger.warn('Empty input received. Please provide feedback text.');\n safeReject(new Error('Empty input received'));\n } else {\n logger.info(`✅ Received feedback: \"${userInput}\"\\n`);\n safeResolve(userInput);\n }\n }\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Unknown error processing input'));\n }\n };\n\n errorHandler = (error: Error) => {\n safeReject(error);\n };\n\n process.stdin.on('data', dataHandler);\n process.stdin.on('error', errorHandler);\n\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Failed to setup input handlers'));\n }\n });\n}\n\n/**\n * Get LLM improvement feedback from the user using the editor\n * @param contentType Type of content being improved (e.g., 'commit message', 'release notes')\n * @param currentContent The current content to be improved\n * @param editor Optional editor command\n * @param logger Optional logger instance\n * @returns Promise resolving to the user's feedback text\n */\nexport async function getLLMFeedbackInEditor(\n contentType: string,\n currentContent: string,\n editor?: string,\n logger?: Logger\n): Promise<string> {\n const templateLines = [\n '# Provide Your Instructions and Guidance for a Revision Here',\n '#',\n '# Type your guidance above this line. Be specific about what you want changed,',\n '# added, or improved. You can also edit the original content below directly',\n '# to provide examples or show desired changes.',\n '#',\n '# Lines starting with \"#\" will be ignored.',\n '',\n '### YOUR FEEDBACK AND GUIDANCE:',\n '',\n '# (Type your improvement instructions here)',\n '',\n `### ORIGINAL ${contentType.toUpperCase()}:`,\n ''\n ];\n\n const result = await editContentInEditor(\n currentContent,\n templateLines,\n '.md',\n editor,\n logger\n );\n\n // Extract just the feedback section (everything before the original content)\n const lines = result.content.split('\\n');\n const originalSectionIndex = lines.findIndex(line =>\n line.trim().toLowerCase().startsWith('### original')\n );\n\n let feedback: string;\n if (originalSectionIndex >= 0) {\n // Take everything before the \"### ORIGINAL\" section\n feedback = lines.slice(0, originalSectionIndex).join('\\n').trim();\n } else {\n // If no original section found, take everything\n feedback = result.content.trim();\n }\n\n // Remove the feedback header if it exists\n feedback = feedback.replace(/^### YOUR FEEDBACK AND GUIDANCE:\\s*/i, '').trim();\n\n if (!feedback) {\n throw new Error('No feedback provided. Please provide improvement instructions.');\n }\n\n return feedback;\n}\n\n/**\n * Check if interactive mode is available (TTY check)\n * @param errorMessage Custom error message to throw if TTY not available\n * @param logger Optional logger instance\n * @throws Error if not in TTY environment\n */\nexport function requireTTY(errorMessage: string = 'Interactive mode requires a terminal. Use --dry-run instead.', logger?: Logger): void {\n const log = logger || getLogger();\n if (!process.stdin.isTTY) {\n log.error('❌ Interactive mode requires a terminal (TTY)');\n log.error(' Solutions:');\n log.error(' • Run without piping input');\n log.error(' • Use --dry-run to see the generated content');\n throw new Error(errorMessage);\n }\n}\n\n","import { Prompt, recipe } from '@riotprompt/riotprompt';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Types for the commit prompt\nexport type CommitContent = {\n diffContent: string;\n userDirection?: string;\n isFileContent?: boolean; // Flag to indicate if diffContent is actually file content\n githubIssuesContext?: string; // GitHub issues related to current version/milestone\n};\n\nexport type CommitContext = {\n logContext?: string;\n context?: string;\n directories?: string[];\n};\n\nexport type CommitConfig = {\n overridePaths?: string[];\n overrides?: boolean;\n}\n\n/**\n * Build a commit prompt using RiotPrompt Recipes.\n *\n * This prompt is configured to generate multiline commit messages by default,\n * with separate lines/bullet points for different groups of changes rather\n * than squeezing everything into single lines.\n *\n * @param config The configuration for overrides\n * @param content Mandatory content inputs (e.g. diff)\n * @param ctx Optional contextual inputs configured by the user\n */\nexport const createCommitPrompt = async (\n { overridePaths: _overridePaths, overrides: _overrides }: CommitConfig,\n { diffContent, userDirection, isFileContent, githubIssuesContext }: CommitContent,\n { logContext, context, directories }: CommitContext = {}\n): Promise<Prompt> => {\n const basePath = __dirname;\n\n // Build content items for the prompt\n const contentItems = [];\n const contextItems = [];\n\n // Developer Note: Direction is injected first as the highest-priority prompt input\n // This ensures user guidance takes precedence over other context sources like\n // GitHub issues or commit history.\n if (userDirection) {\n contentItems.push({ content: userDirection, title: 'User Direction' });\n }\n if (diffContent) {\n const contentTitle = isFileContent ? 'Project Files' : 'Diff';\n contentItems.push({ content: diffContent, title: contentTitle });\n }\n if (githubIssuesContext) {\n contentItems.push({ content: githubIssuesContext, title: 'Recent GitHub Issues' });\n }\n\n // IMPORTANT: Log context provides background but can contaminate output if too large.\n // LLMs tend to pattern-match against recent commits instead of describing the actual diff.\n // Keep messageLimit low (3-5) to minimize contamination.\n if (logContext) {\n contextItems.push({ content: logContext, title: 'Log Context' });\n }\n if (context) {\n contextItems.push({ content: context, title: 'User Context' });\n }\n if (directories && directories.length > 0) {\n contextItems.push({ directories, title: 'Directories' });\n }\n\n return recipe(basePath)\n .persona({ path: 'personas/you.md' })\n .instructions({ path: 'instructions/commit.md' })\n .overridePaths(_overridePaths ?? [])\n .overrides(_overrides ?? true)\n .content(...contentItems)\n .context(...contextItems)\n .cook();\n};\n\n","import { ContentItem, Prompt, recipe } from '@riotprompt/riotprompt';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Types for the release prompt\nexport type ReleaseConfig = {\n overridePaths?: string[];\n overrides?: boolean;\n}\n\nexport type ReleaseContent = {\n releaseFocus?: string;\n logContent: string;\n diffContent: string;\n milestoneIssues?: string;\n};\n\nexport type ReleaseContext = {\n context?: string;\n directories?: string[];\n};\n\nexport type ReleasePromptResult = {\n prompt: Prompt;\n maxTokens: number;\n isLargeRelease: boolean;\n};\n\n/**\n * Analyzes release content to determine if it's a large release\n * and calculates appropriate token limits\n */\nconst analyzeReleaseSize = (logContent: string, diffContent?: string, milestoneIssues?: string): { isLarge: boolean; maxTokens: number } => {\n const logLines = logContent.split('\\n').length;\n const diffLines = diffContent ? diffContent.split('\\n').length : 0;\n const milestoneLines = milestoneIssues ? milestoneIssues.split('\\n').length : 0;\n const totalContentLength = logContent.length + (diffContent?.length || 0) + (milestoneIssues?.length || 0);\n\n // Consider it a large release if:\n // - More than 20 commits (log lines typically ~3-5 per commit)\n // - More than 500 diff lines\n // - Milestone issues present (indicates significant work)\n // - Total content length > 50KB\n const isLarge = logLines > 60 || diffLines > 500 || milestoneLines > 50 || totalContentLength > 50000;\n\n if (isLarge) {\n // For large releases, significantly increase token limit\n return { isLarge: true, maxTokens: 25000 };\n } else {\n // Standard token limit for normal releases\n return { isLarge: false, maxTokens: 10000 };\n }\n};\n\n/**\n * Build a release prompt using RiotPrompt Recipes.\n */\nexport const createReleasePrompt = async (\n { overrides: _overrides, overridePaths: _overridePaths }: ReleaseConfig,\n { releaseFocus, logContent, diffContent, milestoneIssues }: ReleaseContent,\n { context, directories }: ReleaseContext = {}\n): Promise<ReleasePromptResult> => {\n const basePath = __dirname;\n\n // Analyze release size to determine token requirements\n const { isLarge: isLargeRelease, maxTokens } = analyzeReleaseSize(logContent, diffContent, milestoneIssues);\n\n // Build content items for the prompt\n const contentItems: ContentItem[] = [];\n const contextItems: ContentItem[] = [];\n\n if (diffContent) {\n contentItems.push({ content: diffContent, title: 'Diff' });\n }\n if (logContent) {\n contentItems.push({ content: logContent, title: 'Log Context' });\n }\n if (milestoneIssues) {\n contentItems.push({ content: milestoneIssues, title: 'Resolved Issues from Milestone' });\n }\n if (releaseFocus) {\n contentItems.push({ content: releaseFocus, title: 'Release Focus' });\n }\n\n // Add release size context to help guide the AI\n if (isLargeRelease) {\n contextItems.push({\n content: `This appears to be a LARGE RELEASE with significant changes. Please provide comprehensive, detailed release notes that thoroughly document all major changes, improvements, and fixes. Don't summarize - dive deep into the details.`,\n title: 'Release Size Context'\n });\n }\n\n if (context) {\n contextItems.push({ content: context, title: 'User Context' });\n }\n if (directories && directories.length > 0) {\n contextItems.push({ directories, title: 'Directories' });\n }\n\n const prompt = await recipe(basePath)\n .persona({ path: 'personas/releaser.md' })\n .instructions({ path: 'instructions/release.md' })\n .overridePaths(_overridePaths ?? [])\n .overrides(_overrides ?? true)\n .content(...contentItems)\n .context(...contextItems)\n .cook();\n\n return {\n prompt,\n maxTokens,\n isLargeRelease\n };\n};\n\n","import { ContentItem, Prompt, recipe } from '@riotprompt/riotprompt';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport type ReviewConfig = {\n overridePaths?: string[];\n overrides?: boolean;\n}\n\nexport type ReviewContent = {\n notes: string;\n};\n\nexport type ReviewContext = {\n logContext?: string;\n diffContext?: string;\n releaseNotesContext?: string;\n issuesContext?: string;\n context?: string;\n directories?: string[];\n};\n\n/**\n * Build a review prompt using RiotPrompt Recipes.\n */\nexport const createReviewPrompt = async (\n { overridePaths: _overridePaths, overrides: _overrides }: ReviewConfig,\n { notes }: ReviewContent,\n { logContext, diffContext, releaseNotesContext, issuesContext, context, directories }: ReviewContext = {}\n): Promise<Prompt> => {\n const basePath = __dirname;\n\n // Build content items for the prompt\n const contentItems: ContentItem[] = [];\n const contextItems: ContentItem[] = [];\n\n if (notes) {\n contentItems.push({ content: notes, title: 'Review Notes' });\n }\n\n if (logContext) {\n contextItems.push({ content: logContext, title: 'Log Context' });\n }\n if (diffContext) {\n contextItems.push({ content: diffContext, title: 'Diff Context' });\n }\n if (releaseNotesContext) {\n contextItems.push({ content: releaseNotesContext, title: 'Release Notes Context' });\n }\n if (issuesContext) {\n contextItems.push({ content: issuesContext, title: 'Issues Context' });\n }\n if (context) {\n contextItems.push({ content: context, title: 'User Context' });\n }\n if (directories && directories.length > 0) {\n contextItems.push({ directories, title: 'Directories' });\n }\n\n return recipe(basePath)\n .persona({ path: 'personas/you.md' })\n .instructions({ path: 'instructions/review.md' })\n .overridePaths(_overridePaths ?? [])\n .overrides(_overrides ?? true)\n .content(...contentItems)\n .context(...contextItems)\n .cook();\n};\n\n","import type { ChatCompletionMessageParam } from 'openai/resources';\nimport { createCompletionWithRetry } from '../ai';\nimport type { ToolRegistry } from '../tools/registry';\nimport type { ToolResult } from '../tools/types';\n\nexport interface AgenticConfig {\n messages: ChatCompletionMessageParam[];\n tools: ToolRegistry;\n model?: string;\n maxIterations?: number;\n debug?: boolean;\n debugRequestFile?: string;\n debugResponseFile?: string;\n storage?: any;\n logger?: any;\n openaiReasoning?: 'low' | 'medium' | 'high';\n}\n\nexport interface ToolExecutionMetric {\n name: string;\n success: boolean;\n duration: number;\n error?: string;\n iteration: number;\n timestamp: string;\n}\n\nexport interface AgenticResult {\n finalMessage: string;\n iterations: number;\n toolCallsExecuted: number;\n conversationHistory: ChatCompletionMessageParam[];\n toolMetrics: ToolExecutionMetric[];\n}\n\n/**\n * Execute an agentic loop where the LLM can call tools to gather information\n */\nexport class AgenticExecutor {\n private logger?: any;\n private toolMetrics: ToolExecutionMetric[] = [];\n\n constructor(logger?: any) {\n this.logger = logger;\n }\n\n /**\n * Run the agentic loop\n */\n async run(config: AgenticConfig): Promise<AgenticResult> {\n const {\n messages: initialMessages,\n tools,\n model = 'gpt-4o',\n maxIterations = 10,\n debug = false,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning = false,\n } = config;\n\n const messages = [...initialMessages];\n let iterations = 0;\n let toolCallsExecuted = 0;\n\n this.log('Starting agentic loop', { maxIterations, toolCount: tools.count() });\n\n while (iterations < maxIterations) {\n iterations++;\n this.log(`Iteration ${iterations}/${maxIterations}`);\n\n // Call LLM with tools available\n const response = await createCompletionWithRetry(\n messages,\n {\n model,\n openaiReasoning: openaiReasoning || undefined,\n debug,\n debugRequestFile: debugRequestFile ? `${debugRequestFile}-iter${iterations}` : undefined,\n debugResponseFile: debugResponseFile ? `${debugResponseFile}-iter${iterations}` : undefined,\n storage,\n logger,\n tools: tools.toOpenAIFormat(),\n }\n );\n\n // When tools are enabled, response is the full message object\n const message = typeof response === 'string' ? { role: 'assistant', content: response } : response;\n\n // Check if there are tool calls in the response\n const toolCalls = message.tool_calls || [];\n\n if (toolCalls.length === 0) {\n // No tool calls, agent is done\n const finalContent = message.content || '';\n this.log('Agent completed without tool calls', { iterations, toolCallsExecuted });\n messages.push({\n role: 'assistant',\n content: finalContent,\n });\n return {\n finalMessage: finalContent,\n iterations,\n toolCallsExecuted,\n conversationHistory: messages,\n toolMetrics: this.toolMetrics,\n };\n }\n\n // Add assistant message with tool calls\n messages.push({\n role: 'assistant',\n content: message.content || null,\n tool_calls: toolCalls,\n });\n\n // Execute tool calls\n this.log(`Executing ${toolCalls.length} tool call(s)`);\n\n for (const toolCall of toolCalls) {\n const startTime = Date.now();\n const toolName = toolCall.function.name;\n\n try {\n this.log(`Executing tool: ${toolName}`, toolCall.function.arguments);\n\n // Log to info level so user can see tool execution in real-time\n if (this.logger?.info) {\n this.logger.info(`🔧 Running tool: ${toolName}`);\n }\n\n // Parse arguments\n const args = JSON.parse(toolCall.function.arguments);\n\n // Execute the tool\n const result = await tools.execute(toolName, args);\n\n const duration = Date.now() - startTime;\n\n // Add tool result to conversation\n messages.push({\n role: 'tool',\n tool_call_id: toolCall.id,\n content: this.formatToolResult({ id: toolCall.id, name: toolName, result }),\n });\n\n toolCallsExecuted++;\n\n // Track successful execution\n this.toolMetrics.push({\n name: toolName,\n success: true,\n duration,\n iteration: iterations,\n timestamp: new Date().toISOString(),\n });\n\n this.log(`Tool ${toolName} succeeded in ${duration}ms`);\n\n if (this.logger?.info) {\n this.logger.info(`✅ Tool ${toolName} completed (${duration}ms)`);\n }\n } catch (error: any) {\n const duration = Date.now() - startTime;\n const errorMessage = error.message || String(error);\n\n this.log(`Tool ${toolName} failed: ${errorMessage}`);\n\n // Track failed execution\n this.toolMetrics.push({\n name: toolName,\n success: false,\n duration,\n error: errorMessage,\n iteration: iterations,\n timestamp: new Date().toISOString(),\n });\n\n if (this.logger?.warn) {\n this.logger.warn(`❌ Tool ${toolName} failed: ${errorMessage}`);\n }\n\n // Add error result to conversation\n messages.push({\n role: 'tool',\n tool_call_id: toolCall.id,\n content: `Tool execution failed: ${errorMessage}`,\n });\n }\n }\n\n this.log(`Completed tool execution`, { toolCallsExecuted });\n }\n\n // Max iterations reached\n this.log('Max iterations reached, forcing completion', { iterations, toolCallsExecuted });\n\n // Make one final call without tools to get a synthesized response\n messages.push({\n role: 'user',\n content: 'Please provide your final analysis and commit message based on your investigation. Do not request any more tools.',\n });\n\n const finalResponse = await createCompletionWithRetry(\n messages,\n {\n model,\n openaiReasoning: openaiReasoning || undefined,\n debug,\n storage,\n logger,\n }\n );\n\n messages.push({\n role: 'assistant',\n content: finalResponse,\n });\n\n return {\n finalMessage: finalResponse,\n iterations,\n toolCallsExecuted,\n conversationHistory: messages,\n toolMetrics: this.toolMetrics,\n };\n }\n\n /**\n * Format tool result for inclusion in conversation\n */\n private formatToolResult(result: ToolResult): string {\n if (typeof result.result === 'string') {\n return result.result;\n }\n return JSON.stringify(result.result, null, 2);\n }\n\n /**\n * Log a message if logger is available\n */\n private log(message: string, data?: any): void {\n if (this.logger?.debug) {\n if (data) {\n this.logger.debug(`[AgenticExecutor] ${message}`, data);\n } else {\n this.logger.debug(`[AgenticExecutor] ${message}`);\n }\n }\n }\n}\n\n/**\n * Create and run an agentic executor\n */\nexport async function runAgentic(config: AgenticConfig): Promise<AgenticResult> {\n const executor = new AgenticExecutor(config.logger);\n return await executor.run(config);\n}\n\n","import type { Tool, OpenAITool, ToolContext } from './types';\n\n/**\n * Registry for managing tools available to agentic LLM interactions\n */\nexport class ToolRegistry {\n private tools: Map<string, Tool> = new Map();\n private context?: ToolContext;\n\n constructor(context?: ToolContext) {\n this.context = context;\n }\n\n /**\n * Register a tool in the registry\n */\n register(tool: Tool): void {\n if (this.tools.has(tool.name)) {\n throw new Error(`Tool with name \"${tool.name}\" is already registered`);\n }\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Register multiple tools at once\n */\n registerAll(tools: Tool[]): void {\n for (const tool of tools) {\n this.register(tool);\n }\n }\n\n /**\n * Get a tool by name\n */\n get(name: string): Tool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get all registered tools\n */\n getAll(): Tool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Check if a tool exists\n */\n has(name: string): boolean {\n return this.tools.has(name);\n }\n\n /**\n * Execute a tool by name with given parameters\n */\n async execute(name: string, params: any): Promise<any> {\n const tool = this.tools.get(name);\n if (!tool) {\n throw new Error(`Tool \"${name}\" not found in registry`);\n }\n\n try {\n return await tool.execute(params, this.context);\n } catch (error: any) {\n throw new Error(`Tool \"${name}\" execution failed: ${error.message}`);\n }\n }\n\n /**\n * Convert tools to OpenAI function calling format\n */\n toOpenAIFormat(): OpenAITool[] {\n return this.getAll().map(tool => ({\n type: 'function' as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n }\n\n /**\n * Get tool definitions (without execute functions) for serialization\n */\n getDefinitions(): Array<{ name: string; description: string; parameters: any }> {\n return this.getAll().map(tool => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n }\n\n /**\n * Clear all registered tools\n */\n clear(): void {\n this.tools.clear();\n }\n\n /**\n * Get count of registered tools\n */\n count(): number {\n return this.tools.size;\n }\n}\n\n/**\n * Create a new tool registry with optional context\n */\nexport function createToolRegistry(context?: ToolContext): ToolRegistry {\n return new ToolRegistry(context);\n}\n\n","import type { Tool, ToolContext } from './types';\nimport { run } from '@eldrforge/git-tools';\nimport * as path from 'path';\n\n/**\n * Create tools for commit message generation\n */\nexport function createCommitTools(): Tool[] {\n return [\n createGetFileHistoryTool(),\n createGetFileContentTool(),\n createSearchCodebaseTool(),\n createGetRelatedTestsTool(),\n createGetFileDependenciesTool(),\n createAnalyzeDiffSectionTool(),\n createGetRecentCommitsTool(),\n createGroupFilesByConcernTool(),\n ];\n}\n\n/**\n * Get git commit history for specific files\n */\nfunction createGetFileHistoryTool(): Tool {\n return {\n name: 'get_file_history',\n description: 'Get git commit history for one or more files to understand their evolution and past changes',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Array of file paths to get history for',\n items: { type: 'string', description: 'File path' },\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 10)',\n default: 10,\n },\n format: {\n type: 'string',\n description: 'Output format: \"summary\" for brief or \"detailed\" for full messages',\n enum: ['summary', 'detailed'],\n default: 'summary',\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; limit?: number; format?: 'summary' | 'detailed' }, context?: ToolContext) => {\n const { filePaths, limit = 10, format = 'summary' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const formatArg = format === 'detailed' ? '--format=%H%n%an (%ae)%n%ad%n%s%n%n%b%n---' : '--format=%h - %s (%an, %ar)';\n const fileArgs = filePaths.join(' ');\n const command = `git log ${formatArg} -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No history found for specified files';\n } catch (error: any) {\n throw new Error(`Failed to get file history: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get the full current content of a file\n */\nfunction createGetFileContentTool(): Tool {\n return {\n name: 'get_file_content',\n description: 'Get the complete current content of a file to understand context around changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the file',\n },\n includeLineNumbers: {\n type: 'boolean',\n description: 'Include line numbers in output (default: false)',\n default: false,\n },\n },\n required: ['filePath'],\n },\n execute: async (params: { filePath: string; includeLineNumbers?: boolean }, context?: ToolContext) => {\n const { filePath, includeLineNumbers = false } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n\n if (includeLineNumbers) {\n const lines = content.split('\\n');\n return lines.map((line: string, idx: number) => `${idx + 1}: ${line}`).join('\\n');\n }\n\n return content;\n } catch (error: any) {\n throw new Error(`Failed to read file: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Search for code patterns or identifiers across the codebase\n */\nfunction createSearchCodebaseTool(): Tool {\n return {\n name: 'search_codebase',\n description: 'Search for code patterns, function names, or text across the codebase using git grep',\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search pattern (can be plain text or regex)',\n },\n fileTypes: {\n type: 'array',\n description: 'Limit search to specific file extensions (e.g., [\"ts\", \"js\"])',\n items: { type: 'string', description: 'File extension' },\n },\n contextLines: {\n type: 'number',\n description: 'Number of context lines to show around matches (default: 2)',\n default: 2,\n },\n },\n required: ['query'],\n },\n execute: async (params: { query: string; fileTypes?: string[]; contextLines?: number }, context?: ToolContext) => {\n const { query, fileTypes, contextLines = 2 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n // Build command with proper git grep syntax: pattern comes BEFORE pathspec\n let command = `git grep -n -C ${contextLines} \"${query}\"`;\n\n if (fileTypes && fileTypes.length > 0) {\n // Use separate quoted patterns for each file type to avoid shell expansion issues\n const patterns = fileTypes.map(ext => `'*.${ext}'`).join(' ');\n command += ` -- ${patterns}`;\n }\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No matches found';\n } catch (error: any) {\n // git grep returns exit code 1 when no matches found\n if (error.message.includes('exit code 1')) {\n return 'No matches found';\n }\n throw new Error(`Search failed: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Find test files related to changed production files\n */\nfunction createGetRelatedTestsTool(): Tool {\n return {\n name: 'get_related_tests',\n description: 'Find test files related to production files to understand what the code is supposed to do',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Production file paths',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n const relatedTests: string[] = [];\n\n for (const filePath of filePaths) {\n // Common test patterns\n const patterns = [\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.test.$1'),\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.spec.$1'),\n filePath.replace('/src/', '/tests/').replace('/lib/', '/tests/'),\n path.join('tests', filePath),\n path.join('test', filePath),\n ];\n\n for (const pattern of patterns) {\n try {\n await storage.readFile(pattern, 'utf-8');\n relatedTests.push(pattern);\n } catch {\n // File doesn't exist, continue\n }\n }\n }\n\n if (relatedTests.length === 0) {\n return 'No related test files found';\n }\n\n return `Found related test files:\\n${relatedTests.join('\\n')}`;\n },\n };\n}\n\n/**\n * Understand what files import/depend on changed files\n */\nfunction createGetFileDependenciesTool(): Tool {\n return {\n name: 'get_file_dependencies',\n description: 'Find which files import or depend on the changed files to assess change impact',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to analyze dependencies for',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const results: string[] = [];\n\n for (const filePath of filePaths) {\n // Extract filename without extension for searching imports\n const fileName = path.basename(filePath, path.extname(filePath));\n\n // Search for imports of this file\n const searchPatterns = [\n `from.*['\"].*${fileName}`,\n `import.*['\"].*${fileName}`,\n `require\\\\(['\"].*${fileName}`,\n ];\n\n for (const pattern of searchPatterns) {\n try {\n const command = `git grep -l \"${pattern}\"`;\n const output = await run(command, { cwd: workingDir });\n if (output.stdout) {\n results.push(`Files importing ${filePath}:\\n${output.stdout}`);\n break; // Found matches, no need to try other patterns\n }\n } catch {\n // No matches or error, continue\n }\n }\n }\n\n return results.length > 0\n ? results.join('\\n\\n')\n : 'No files found that import the specified files';\n },\n };\n}\n\n/**\n * Get detailed analysis of specific lines in a diff\n */\nfunction createAnalyzeDiffSectionTool(): Tool {\n return {\n name: 'analyze_diff_section',\n description: 'Get expanded context around specific lines in a file to better understand changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'File containing the section to analyze',\n },\n startLine: {\n type: 'number',\n description: 'Starting line number',\n },\n endLine: {\n type: 'number',\n description: 'Ending line number',\n },\n contextLines: {\n type: 'number',\n description: 'Number of additional context lines to show before and after (default: 10)',\n default: 10,\n },\n },\n required: ['filePath', 'startLine', 'endLine'],\n },\n execute: async (params: { filePath: string; startLine: number; endLine: number; contextLines?: number }, context?: ToolContext) => {\n const { filePath, startLine, endLine, contextLines = 10 } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n\n const actualStart = Math.max(0, startLine - contextLines - 1);\n const actualEnd = Math.min(lines.length, endLine + contextLines);\n\n const section = lines.slice(actualStart, actualEnd)\n .map((line: string, idx: number) => `${actualStart + idx + 1}: ${line}`)\n .join('\\n');\n\n return `Lines ${actualStart + 1}-${actualEnd} from ${filePath}:\\n\\n${section}`;\n } catch (error: any) {\n throw new Error(`Failed to analyze diff section: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get recent commits that touched the same files\n */\nfunction createGetRecentCommitsTool(): Tool {\n return {\n name: 'get_recent_commits',\n description: 'Get recent commits that modified the same files to understand recent work in this area',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to check for recent commits',\n items: { type: 'string', description: 'File path' },\n },\n since: {\n type: 'string',\n description: 'Time period to look back (e.g., \"1 week ago\", \"2 days ago\")',\n default: '1 week ago',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 5)',\n default: 5,\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; since?: string; limit?: number }, context?: ToolContext) => {\n const { filePaths, since = '1 week ago', limit = 5 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const fileArgs = filePaths.join(' ');\n const command = `git log --format=\"%h - %s (%an, %ar)\" --since=\"${since}\" -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || `No commits found in the specified time period (${since})`;\n } catch (error: any) {\n throw new Error(`Failed to get recent commits: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Analyze changed files and suggest logical groupings\n */\nfunction createGroupFilesByConcernTool(): Tool {\n return {\n name: 'group_files_by_concern',\n description: 'Analyze changed files and suggest logical groupings that might represent separate commits',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'All changed files to analyze',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }) => {\n const { filePaths } = params;\n\n // Group files by directory and type\n const groups: Record<string, string[]> = {};\n\n for (const filePath of filePaths) {\n const dir = path.dirname(filePath);\n const ext = path.extname(filePath);\n const basename = path.basename(filePath, ext);\n\n // Determine category\n let category = 'other';\n\n if (basename.includes('.test') || basename.includes('.spec') || dir.includes('test')) {\n category = 'tests';\n } else if (filePath.includes('package.json') || filePath.includes('package-lock.json')) {\n category = 'dependencies';\n } else if (ext === '.md' || basename === 'README') {\n category = 'documentation';\n } else if (dir.includes('src') || dir.includes('lib')) {\n // Group by module/subdirectory\n category = `source:${dir.split('/').slice(0, 3).join('/')}`;\n }\n\n if (!groups[category]) {\n groups[category] = [];\n }\n groups[category].push(filePath);\n }\n\n // Format the groupings\n const output = Object.entries(groups)\n .map(([category, files]) => {\n return `${category} (${files.length} files):\\n${files.map(f => ` - ${f}`).join('\\n')}`;\n })\n .join('\\n\\n');\n\n const groupCount = Object.keys(groups).length;\n const suggestion = groupCount > 1\n ? `\\n\\nSuggestion: These ${groupCount} groups might be better as separate commits if they represent different concerns.`\n : '\\n\\nSuggestion: All files appear to be related and should be in a single commit.';\n\n return output + suggestion;\n },\n };\n}\n\n","import type { ChatCompletionMessageParam } from 'openai/resources';\nimport { runAgentic, type AgenticConfig, type ToolExecutionMetric } from './executor';\nimport { createToolRegistry } from '../tools/registry';\nimport { createCommitTools } from '../tools/commit-tools';\nimport type { StorageAdapter, Logger } from '../types';\n\nexport interface AgenticCommitConfig {\n changedFiles: string[];\n diffContent: string;\n userDirection?: string;\n logContext?: string;\n model?: string;\n maxIterations?: number;\n debug?: boolean;\n debugRequestFile?: string;\n debugResponseFile?: string;\n storage?: StorageAdapter;\n logger?: Logger;\n openaiReasoning?: 'low' | 'medium' | 'high';\n}\n\nexport interface AgenticCommitResult {\n commitMessage: string;\n iterations: number;\n toolCallsExecuted: number;\n suggestedSplits: Array<{\n files: string[];\n message: string;\n rationale: string;\n }>;\n conversationHistory: ChatCompletionMessageParam[];\n toolMetrics: ToolExecutionMetric[];\n}\n\n/**\n * Run agentic commit message generation\n */\nexport async function runAgenticCommit(config: AgenticCommitConfig): Promise<AgenticCommitResult> {\n const {\n changedFiles,\n diffContent,\n userDirection,\n logContext,\n model = 'gpt-4o',\n maxIterations = 10,\n debug = false,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n } = config;\n\n // Create tool registry with context\n const toolRegistry = createToolRegistry({\n workingDirectory: process.cwd(),\n storage,\n logger,\n });\n\n // Register commit-specific tools\n const tools = createCommitTools();\n toolRegistry.registerAll(tools);\n\n // Build initial system prompt\n const systemPrompt = buildSystemPrompt();\n\n // Build initial user message\n const userMessage = buildUserMessage(changedFiles, diffContent, userDirection, logContext);\n\n // Prepare messages for agentic loop\n const messages: ChatCompletionMessageParam[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userMessage },\n ];\n\n // Run agentic loop\n const agenticConfig: AgenticConfig = {\n messages,\n tools: toolRegistry,\n model,\n maxIterations,\n debug,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n };\n\n const result = await runAgentic(agenticConfig);\n\n // Parse the final message to extract commit message and suggested splits\n const parsed = parseAgenticResult(result.finalMessage);\n\n return {\n commitMessage: parsed.commitMessage,\n iterations: result.iterations,\n toolCallsExecuted: result.toolCallsExecuted,\n suggestedSplits: parsed.suggestedSplits,\n conversationHistory: result.conversationHistory,\n toolMetrics: result.toolMetrics,\n };\n}\n\n/**\n * Build the system prompt for agentic commit generation\n */\nfunction buildSystemPrompt(): string {\n return `You are an expert software engineer tasked with generating meaningful commit messages.\n\nYou have access to tools that let you investigate changes in detail:\n- get_file_history: View commit history for files\n- get_file_content: Read full file contents\n- search_codebase: Search for patterns across the codebase\n- get_related_tests: Find test files related to changes\n- get_file_dependencies: Understand file dependencies and imports\n- analyze_diff_section: Get expanded context around specific changes\n- get_recent_commits: See recent commits to the same files\n- group_files_by_concern: Suggest logical groupings of changed files\n\nYour process should be:\n1. Analyze the changed files and diff to understand the scope\n2. Use tools to investigate specific changes that need more context\n3. Identify if changes represent one cohesive commit or multiple logical commits\n4. Generate a commit message (or multiple if splits suggested) that accurately describes changes\n\nGuidelines:\n- Use tools strategically - don't call every tool on every file\n- Look at test changes to understand intent\n- Check recent history to avoid redundant messages\n- Consider suggesting split commits for unrelated changes\n- Synthesize findings into clear, informative commit messages\n- Follow conventional commit format when appropriate (feat:, fix:, refactor:, etc.)\n\nOutput format:\nWhen you're ready to provide the final commit message, format it as:\n\nCOMMIT_MESSAGE:\n[Your generated commit message here]\n\nIf you recommend splitting into multiple commits, also include:\n\nSUGGESTED_SPLITS:\nSplit 1:\nFiles: [list of files]\nRationale: [why these belong together]\nMessage: [commit message for this split]\n\nSplit 2:\n...\n\nIf changes should remain as one commit, do not include SUGGESTED_SPLITS section.`;\n}\n\n/**\n * Build the initial user message\n */\nfunction buildUserMessage(\n changedFiles: string[],\n diffContent: string,\n userDirection?: string,\n logContext?: string\n): string {\n let message = `I have staged changes that need a commit message.\n\nChanged files (${changedFiles.length}):\n${changedFiles.map(f => ` - ${f}`).join('\\n')}\n\nDiff:\n${diffContent}`;\n\n if (userDirection) {\n message += `\\n\\nUser direction: ${userDirection}`;\n }\n\n if (logContext) {\n message += `\\n\\nRecent commit history for context:\n${logContext}`;\n }\n\n message += `\\n\\nPlease investigate these changes and generate an appropriate commit message.\nUse the available tools to gather additional context as needed.\nIf these changes should be split into multiple commits, suggest the groupings.`;\n\n return message;\n}\n\n/**\n * Parse the agentic result to extract commit message and splits\n */\nfunction parseAgenticResult(finalMessage: string): {\n commitMessage: string;\n suggestedSplits: Array<{ files: string[]; message: string; rationale: string }>;\n} {\n // Look for COMMIT_MESSAGE: marker\n const commitMatch = finalMessage.match(/COMMIT_MESSAGE:\\s*\\n([\\s\\S]*?)(?=\\n\\nSUGGESTED_SPLITS:|$)/);\n const commitMessage = commitMatch ? commitMatch[1].trim() : finalMessage.trim();\n\n // Look for SUGGESTED_SPLITS: section\n const suggestedSplits: Array<{ files: string[]; message: string; rationale: string }> = [];\n const splitsMatch = finalMessage.match(/SUGGESTED_SPLITS:\\s*\\n([\\s\\S]*)/);\n\n if (splitsMatch) {\n const splitsText = splitsMatch[1];\n // Parse each split\n const splitRegex = /Split \\d+:\\s*\\nFiles: ([\\s\\S]*?)\\nRationale: ([\\s\\S]*?)\\nMessage: ([\\s\\S]*?)(?=\\n\\nSplit \\d+:|$)/g;\n let match;\n\n while ((match = splitRegex.exec(splitsText)) !== null) {\n const filesText = match[1].trim();\n const files = filesText\n .split('\\n')\n .map(line => line.trim().replace(/^[-*]\\s*/, ''))\n .filter(line => line.length > 0);\n\n suggestedSplits.push({\n files,\n rationale: match[2].trim(),\n message: match[3].trim(),\n });\n }\n }\n\n return { commitMessage, suggestedSplits };\n}\n\n","import type { Tool, ToolContext } from './types';\nimport { run } from '@eldrforge/git-tools';\nimport * as path from 'path';\n\n/**\n * Create tools for release notes generation\n */\nexport function createReleaseTools(): Tool[] {\n return [\n createGetFileHistoryTool(),\n createGetFileContentTool(),\n createSearchCodebaseTool(),\n createGetRelatedTestsTool(),\n createGetFileDependenciesTool(),\n createAnalyzeDiffSectionTool(),\n createGetRecentCommitsTool(),\n createGroupFilesByConcernTool(),\n createGetTagHistoryTool(),\n createComparePreviousReleaseTool(),\n createGetReleaseStatsTool(),\n createGetBreakingChangesTool(),\n createAnalyzeCommitPatternsTool(),\n ];\n}\n\n/**\n * Get git commit history for specific files\n */\nfunction createGetFileHistoryTool(): Tool {\n return {\n name: 'get_file_history',\n description: 'Get git commit history for one or more files to understand their evolution and past changes',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Array of file paths to get history for',\n items: { type: 'string', description: 'File path' },\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 10)',\n default: 10,\n },\n format: {\n type: 'string',\n description: 'Output format: \"summary\" for brief or \"detailed\" for full messages',\n enum: ['summary', 'detailed'],\n default: 'summary',\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; limit?: number; format?: 'summary' | 'detailed' }, context?: ToolContext) => {\n const { filePaths, limit = 10, format = 'summary' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const formatArg = format === 'detailed' ? '--format=%H%n%an (%ae)%n%ad%n%s%n%n%b%n---' : '--format=%h - %s (%an, %ar)';\n const fileArgs = filePaths.join(' ');\n const command = `git log ${formatArg} -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No history found for specified files';\n } catch (error: any) {\n throw new Error(`Failed to get file history: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get the full current content of a file\n */\nfunction createGetFileContentTool(): Tool {\n return {\n name: 'get_file_content',\n description: 'Get the complete current content of a file to understand context around changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the file',\n },\n includeLineNumbers: {\n type: 'boolean',\n description: 'Include line numbers in output (default: false)',\n default: false,\n },\n },\n required: ['filePath'],\n },\n execute: async (params: { filePath: string; includeLineNumbers?: boolean }, context?: ToolContext) => {\n const { filePath, includeLineNumbers = false } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n\n if (includeLineNumbers) {\n const lines = content.split('\\n');\n return lines.map((line: string, idx: number) => `${idx + 1}: ${line}`).join('\\n');\n }\n\n return content;\n } catch (error: any) {\n throw new Error(`Failed to read file: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Search for code patterns or identifiers across the codebase\n */\nfunction createSearchCodebaseTool(): Tool {\n return {\n name: 'search_codebase',\n description: 'Search for code patterns, function names, or text across the codebase using git grep',\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search pattern (can be plain text or regex)',\n },\n fileTypes: {\n type: 'array',\n description: 'Limit search to specific file extensions (e.g., [\"ts\", \"js\"])',\n items: { type: 'string', description: 'File extension' },\n },\n contextLines: {\n type: 'number',\n description: 'Number of context lines to show around matches (default: 2)',\n default: 2,\n },\n },\n required: ['query'],\n },\n execute: async (params: { query: string; fileTypes?: string[]; contextLines?: number }, context?: ToolContext) => {\n const { query, fileTypes, contextLines = 2 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n // Build command with proper git grep syntax: pattern comes BEFORE pathspec\n let command = `git grep -n -C ${contextLines} \"${query}\"`;\n\n if (fileTypes && fileTypes.length > 0) {\n // Use separate quoted patterns for each file type to avoid shell expansion issues\n const patterns = fileTypes.map(ext => `'*.${ext}'`).join(' ');\n command += ` -- ${patterns}`;\n }\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No matches found';\n } catch (error: any) {\n // git grep returns exit code 1 when no matches found\n if (error.message.includes('exit code 1')) {\n return 'No matches found';\n }\n throw new Error(`Search failed: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Find test files related to changed production files\n */\nfunction createGetRelatedTestsTool(): Tool {\n return {\n name: 'get_related_tests',\n description: 'Find test files related to production files to understand what the code is supposed to do',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Production file paths',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n const relatedTests: string[] = [];\n\n for (const filePath of filePaths) {\n // Common test patterns\n const patterns = [\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.test.$1'),\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.spec.$1'),\n filePath.replace('/src/', '/tests/').replace('/lib/', '/tests/'),\n path.join('tests', filePath),\n path.join('test', filePath),\n ];\n\n for (const pattern of patterns) {\n try {\n await storage.readFile(pattern, 'utf-8');\n relatedTests.push(pattern);\n } catch {\n // File doesn't exist, continue\n }\n }\n }\n\n if (relatedTests.length === 0) {\n return 'No related test files found';\n }\n\n return `Found related test files:\\n${relatedTests.join('\\n')}`;\n },\n };\n}\n\n/**\n * Understand what files import/depend on changed files\n */\nfunction createGetFileDependenciesTool(): Tool {\n return {\n name: 'get_file_dependencies',\n description: 'Find which files import or depend on the changed files to assess change impact',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to analyze dependencies for',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const results: string[] = [];\n\n for (const filePath of filePaths) {\n // Extract filename without extension for searching imports\n const fileName = path.basename(filePath, path.extname(filePath));\n\n // Search for imports of this file\n const searchPatterns = [\n `from.*['\"].*${fileName}`,\n `import.*['\"].*${fileName}`,\n `require\\\\(['\"].*${fileName}`,\n ];\n\n for (const pattern of searchPatterns) {\n try {\n const command = `git grep -l \"${pattern}\"`;\n const output = await run(command, { cwd: workingDir });\n if (output.stdout) {\n results.push(`Files importing ${filePath}:\\n${output.stdout}`);\n break; // Found matches, no need to try other patterns\n }\n } catch {\n // No matches or error, continue\n }\n }\n }\n\n return results.length > 0\n ? results.join('\\n\\n')\n : 'No files found that import the specified files';\n },\n };\n}\n\n/**\n * Get detailed analysis of specific lines in a diff\n */\nfunction createAnalyzeDiffSectionTool(): Tool {\n return {\n name: 'analyze_diff_section',\n description: 'Get expanded context around specific lines in a file to better understand changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'File containing the section to analyze',\n },\n startLine: {\n type: 'number',\n description: 'Starting line number',\n },\n endLine: {\n type: 'number',\n description: 'Ending line number',\n },\n contextLines: {\n type: 'number',\n description: 'Number of additional context lines to show before and after (default: 10)',\n default: 10,\n },\n },\n required: ['filePath', 'startLine', 'endLine'],\n },\n execute: async (params: { filePath: string; startLine: number; endLine: number; contextLines?: number }, context?: ToolContext) => {\n const { filePath, startLine, endLine, contextLines = 10 } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n\n const actualStart = Math.max(0, startLine - contextLines - 1);\n const actualEnd = Math.min(lines.length, endLine + contextLines);\n\n const section = lines.slice(actualStart, actualEnd)\n .map((line: string, idx: number) => `${actualStart + idx + 1}: ${line}`)\n .join('\\n');\n\n return `Lines ${actualStart + 1}-${actualEnd} from ${filePath}:\\n\\n${section}`;\n } catch (error: any) {\n throw new Error(`Failed to analyze diff section: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get recent commits that touched the same files\n */\nfunction createGetRecentCommitsTool(): Tool {\n return {\n name: 'get_recent_commits',\n description: 'Get recent commits that modified the same files to understand recent work in this area',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to check for recent commits',\n items: { type: 'string', description: 'File path' },\n },\n since: {\n type: 'string',\n description: 'Time period to look back (e.g., \"1 week ago\", \"2 days ago\")',\n default: '1 week ago',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 5)',\n default: 5,\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; since?: string; limit?: number }, context?: ToolContext) => {\n const { filePaths, since = '1 week ago', limit = 5 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const fileArgs = filePaths.join(' ');\n const command = `git log --format=\"%h - %s (%an, %ar)\" --since=\"${since}\" -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || `No commits found in the specified time period (${since})`;\n } catch (error: any) {\n throw new Error(`Failed to get recent commits: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Analyze changed files and suggest logical groupings\n */\nfunction createGroupFilesByConcernTool(): Tool {\n return {\n name: 'group_files_by_concern',\n description: 'Analyze changed files and suggest logical groupings that might represent separate concerns',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'All changed files to analyze',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }) => {\n const { filePaths } = params;\n\n // Group files by directory and type\n const groups: Record<string, string[]> = {};\n\n for (const filePath of filePaths) {\n const dir = path.dirname(filePath);\n const ext = path.extname(filePath);\n const basename = path.basename(filePath, ext);\n\n // Determine category\n let category = 'other';\n\n if (basename.includes('.test') || basename.includes('.spec') || dir.includes('test')) {\n category = 'tests';\n } else if (filePath.includes('package.json') || filePath.includes('package-lock.json')) {\n category = 'dependencies';\n } else if (ext === '.md' || basename === 'README') {\n category = 'documentation';\n } else if (dir.includes('src') || dir.includes('lib')) {\n // Group by module/subdirectory\n category = `source:${dir.split('/').slice(0, 3).join('/')}`;\n }\n\n if (!groups[category]) {\n groups[category] = [];\n }\n groups[category].push(filePath);\n }\n\n // Format the groupings\n const output = Object.entries(groups)\n .map(([category, files]) => {\n return `${category} (${files.length} files):\\n${files.map(f => ` - ${f}`).join('\\n')}`;\n })\n .join('\\n\\n');\n\n const groupCount = Object.keys(groups).length;\n const suggestion = groupCount > 1\n ? `\\n\\nSuggestion: These ${groupCount} groups represent different concerns in the release.`\n : '\\n\\nSuggestion: All files appear to be related to a single concern.';\n\n return output + suggestion;\n },\n };\n}\n\n/**\n * Get history of previous release tags\n */\nfunction createGetTagHistoryTool(): Tool {\n return {\n name: 'get_tag_history',\n description: 'Get the history of previous release tags to understand release patterns and versioning',\n parameters: {\n type: 'object',\n properties: {\n limit: {\n type: 'number',\n description: 'Number of recent tags to retrieve (default: 10)',\n default: 10,\n },\n pattern: {\n type: 'string',\n description: 'Filter tags by pattern (e.g., \"v*\" for version tags)',\n },\n },\n },\n execute: async (params: { limit?: number; pattern?: string }, context?: ToolContext) => {\n const { limit = 10, pattern } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n let command = 'git tag --sort=-creatordate';\n if (pattern) {\n command += ` -l \"${pattern}\"`;\n }\n command += ` | head -n ${limit}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n if (!output.stdout) {\n return 'No tags found in repository';\n }\n\n // Get detailed info for each tag\n const tags = output.stdout.trim().split('\\n');\n const detailedInfo: string[] = [];\n\n for (const tag of tags) {\n try {\n const tagInfo = await run(`git show --quiet --format=\"%ci - %s\" ${tag}`, { cwd: workingDir });\n detailedInfo.push(`${tag}: ${tagInfo.stdout.trim()}`);\n } catch {\n detailedInfo.push(`${tag}: (no info available)`);\n }\n }\n\n return `Recent release tags:\\n${detailedInfo.join('\\n')}`;\n } catch (error: any) {\n throw new Error(`Failed to get tag history: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Compare this release with a previous release\n */\nfunction createComparePreviousReleaseTool(): Tool {\n return {\n name: 'compare_previous_release',\n description: 'Compare this release with a previous release to understand what changed between versions',\n parameters: {\n type: 'object',\n properties: {\n previousTag: {\n type: 'string',\n description: 'Previous release tag to compare against',\n },\n currentRef: {\n type: 'string',\n description: 'Current reference (default: HEAD)',\n default: 'HEAD',\n },\n statsOnly: {\n type: 'boolean',\n description: 'Return only statistics, not full diff (default: true)',\n default: true,\n },\n },\n required: ['previousTag'],\n },\n execute: async (params: { previousTag: string; currentRef?: string; statsOnly?: boolean }, context?: ToolContext) => {\n const { previousTag, currentRef = 'HEAD', statsOnly = true } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n try {\n // Get commit count\n const commitCountCmd = `git rev-list --count ${previousTag}..${currentRef}`;\n const commitCount = await run(commitCountCmd, { cwd: workingDir });\n\n // Get file change stats\n const statsCmd = `git diff --stat ${previousTag}..${currentRef}`;\n const stats = await run(statsCmd, { cwd: workingDir });\n\n let result = `Comparison between ${previousTag} and ${currentRef}:\\n\\n`;\n result += `Commits: ${commitCount.stdout.trim()}\\n\\n`;\n result += `File changes:\\n${stats.stdout}`;\n\n if (!statsOnly) {\n // Get short log of commits\n const logCmd = `git log --oneline ${previousTag}..${currentRef}`;\n const log = await run(logCmd, { cwd: workingDir });\n result += `\\n\\nCommit summary:\\n${log.stdout}`;\n }\n\n return result;\n } catch (error: any) {\n throw new Error(`Failed to compare releases: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get statistics about the release\n */\nfunction createGetReleaseStatsTool(): Tool {\n return {\n name: 'get_release_stats',\n description: 'Get comprehensive statistics about the release including contributors, file changes, and commit patterns',\n parameters: {\n type: 'object',\n properties: {\n fromRef: {\n type: 'string',\n description: 'Starting reference for the release range',\n },\n toRef: {\n type: 'string',\n description: 'Ending reference for the release range (default: HEAD)',\n default: 'HEAD',\n },\n },\n required: ['fromRef'],\n },\n execute: async (params: { fromRef: string; toRef?: string }, context?: ToolContext) => {\n const { fromRef, toRef = 'HEAD' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n try {\n const results: string[] = [];\n\n // Commit count\n const commitCount = await run(`git rev-list --count ${fromRef}..${toRef}`, { cwd: workingDir });\n results.push(`Total commits: ${commitCount.stdout.trim()}`);\n\n // Contributors\n const contributors = await run(\n `git shortlog -sn ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n results.push(`\\nContributors:\\n${contributors.stdout}`);\n\n // File change summary\n const fileStats = await run(\n `git diff --shortstat ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n results.push(`\\nFile changes: ${fileStats.stdout.trim()}`);\n\n // Most changed files\n const topFiles = await run(\n `git diff --stat ${fromRef}..${toRef} | sort -k2 -rn | head -n 10`,\n { cwd: workingDir }\n );\n results.push(`\\nTop 10 most changed files:\\n${topFiles.stdout}`);\n\n return results.join('\\n');\n } catch (error: any) {\n throw new Error(`Failed to get release stats: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Identify potential breaking changes\n */\nfunction createGetBreakingChangesTool(): Tool {\n return {\n name: 'get_breaking_changes',\n description: 'Search for potential breaking changes by looking for specific patterns in commits and diffs',\n parameters: {\n type: 'object',\n properties: {\n fromRef: {\n type: 'string',\n description: 'Starting reference for the release range',\n },\n toRef: {\n type: 'string',\n description: 'Ending reference for the release range (default: HEAD)',\n default: 'HEAD',\n },\n },\n required: ['fromRef'],\n },\n execute: async (params: { fromRef: string; toRef?: string }, context?: ToolContext) => {\n const { fromRef, toRef = 'HEAD' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const results: string[] = [];\n\n try {\n // Search for BREAKING CHANGE in commit messages\n const breakingCommits = await run(\n `git log --grep=\"BREAKING CHANGE\" --oneline ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n if (breakingCommits.stdout) {\n results.push(`Commits with BREAKING CHANGE:\\n${breakingCommits.stdout}`);\n }\n\n // Search for removed exports\n const removedExports = await run(\n `git diff ${fromRef}..${toRef} | grep \"^-export\"`,\n { cwd: workingDir }\n );\n if (removedExports.stdout) {\n results.push(`\\nRemoved exports (potential breaking):\\n${removedExports.stdout}`);\n }\n\n // Search for changed function signatures\n const changedSignatures = await run(\n `git diff ${fromRef}..${toRef} | grep -E \"^[-+].*function|^[-+].*const.*=.*=>|^[-+].*interface|^[-+].*type.*=\"`,\n { cwd: workingDir }\n );\n if (changedSignatures.stdout) {\n results.push(`\\nChanged function/type signatures (review for breaking changes):\\n${changedSignatures.stdout.split('\\n').slice(0, 20).join('\\n')}`);\n }\n\n if (results.length === 0) {\n return 'No obvious breaking changes detected. Manual review recommended for API changes.';\n }\n\n return results.join('\\n\\n');\n } catch {\n // Some commands may fail if no matches found\n if (results.length > 0) {\n return results.join('\\n\\n');\n }\n return 'No obvious breaking changes detected. Manual review recommended for API changes.';\n }\n },\n };\n}\n\n/**\n * Analyze commit patterns to identify themes\n */\nfunction createAnalyzeCommitPatternsTool(): Tool {\n return {\n name: 'analyze_commit_patterns',\n description: 'Analyze commit messages to identify patterns and themes in the release',\n parameters: {\n type: 'object',\n properties: {\n fromRef: {\n type: 'string',\n description: 'Starting reference for the release range',\n },\n toRef: {\n type: 'string',\n description: 'Ending reference for the release range (default: HEAD)',\n default: 'HEAD',\n },\n },\n required: ['fromRef'],\n },\n execute: async (params: { fromRef: string; toRef?: string }, context?: ToolContext) => {\n const { fromRef, toRef = 'HEAD' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n try {\n const results: string[] = [];\n\n // Get all commit messages\n const commits = await run(\n `git log --format=\"%s\" ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n\n const messages = commits.stdout.trim().split('\\n');\n\n // Count conventional commit types\n const types: Record<string, number> = {};\n const keywords: Record<string, number> = {};\n\n for (const msg of messages) {\n // Check for conventional commit format\n const conventionalMatch = msg.match(/^(\\w+)(\\(.+?\\))?:/);\n if (conventionalMatch) {\n const type = conventionalMatch[1];\n types[type] = (types[type] || 0) + 1;\n }\n\n // Extract keywords (words longer than 4 chars)\n const words = msg.toLowerCase().match(/\\b\\w{5,}\\b/g) || [];\n for (const word of words) {\n keywords[word] = (keywords[word] || 0) + 1;\n }\n }\n\n // Format commit types\n if (Object.keys(types).length > 0) {\n results.push('Commit types:');\n const sortedTypes = Object.entries(types)\n .sort((a, b) => b[1] - a[1])\n .map(([type, count]) => ` ${type}: ${count}`)\n .join('\\n');\n results.push(sortedTypes);\n }\n\n // Format top keywords\n const topKeywords = Object.entries(keywords)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 15)\n .map(([word, count]) => ` ${word}: ${count}`)\n .join('\\n');\n\n if (topKeywords) {\n results.push('\\nTop keywords in commits:');\n results.push(topKeywords);\n }\n\n return results.join('\\n');\n } catch (error: any) {\n throw new Error(`Failed to analyze commit patterns: ${error.message}`);\n }\n },\n };\n}\n\n","import type { ChatCompletionMessageParam } from 'openai/resources';\nimport { runAgentic, type AgenticConfig, type ToolExecutionMetric } from './executor';\nimport { createToolRegistry } from '../tools/registry';\nimport { createReleaseTools } from '../tools/release-tools';\nimport type { StorageAdapter, Logger } from '../types';\n\nexport interface AgenticReleaseConfig {\n fromRef: string;\n toRef: string;\n logContent: string;\n diffContent: string;\n milestoneIssues?: string;\n releaseFocus?: string;\n userContext?: string;\n model?: string;\n maxIterations?: number;\n debug?: boolean;\n debugRequestFile?: string;\n debugResponseFile?: string;\n storage?: StorageAdapter;\n logger?: Logger;\n openaiReasoning?: 'low' | 'medium' | 'high';\n}\n\nexport interface AgenticReleaseResult {\n releaseNotes: {\n title: string;\n body: string;\n };\n iterations: number;\n toolCallsExecuted: number;\n conversationHistory: ChatCompletionMessageParam[];\n toolMetrics: ToolExecutionMetric[];\n}\n\n/**\n * Run agentic release notes generation\n */\nexport async function runAgenticRelease(config: AgenticReleaseConfig): Promise<AgenticReleaseResult> {\n const {\n fromRef,\n toRef,\n logContent,\n diffContent,\n milestoneIssues,\n releaseFocus,\n userContext,\n model = 'gpt-4o',\n maxIterations = 30,\n debug = false,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n } = config;\n\n // Create tool registry with context\n const toolRegistry = createToolRegistry({\n workingDirectory: process.cwd(),\n storage,\n logger,\n });\n\n // Register release-specific tools\n const tools = createReleaseTools();\n toolRegistry.registerAll(tools);\n\n // Build initial system prompt\n const systemPrompt = buildSystemPrompt();\n\n // Build initial user message\n const userMessage = buildUserMessage({\n fromRef,\n toRef,\n logContent,\n diffContent,\n milestoneIssues,\n releaseFocus,\n userContext,\n });\n\n // Prepare messages for agentic loop\n const messages: ChatCompletionMessageParam[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userMessage },\n ];\n\n // Run agentic loop\n const agenticConfig: AgenticConfig = {\n messages,\n tools: toolRegistry,\n model,\n maxIterations,\n debug,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n };\n\n const result = await runAgentic(agenticConfig);\n\n // Parse the final message to extract release notes\n const parsed = parseAgenticResult(result.finalMessage);\n\n return {\n releaseNotes: parsed.releaseNotes,\n iterations: result.iterations,\n toolCallsExecuted: result.toolCallsExecuted,\n conversationHistory: result.conversationHistory,\n toolMetrics: result.toolMetrics,\n };\n}\n\n/**\n * Build the system prompt for agentic release notes generation\n */\nfunction buildSystemPrompt(): string {\n return `You are an expert software engineer and technical writer tasked with generating comprehensive, thoughtful release notes.\n\nYou have access to tools that let you investigate the release in detail:\n- get_file_history: View commit history for specific files\n- get_file_content: Read full file contents to understand context\n- search_codebase: Search for patterns across the codebase\n- get_related_tests: Find test files to understand functionality\n- get_file_dependencies: Understand file dependencies and impact\n- analyze_diff_section: Get expanded context around specific changes\n- get_recent_commits: See recent commits to the same files\n- group_files_by_concern: Identify logical groupings of changes\n- get_tag_history: View previous release tags and patterns\n- compare_previous_release: Compare with previous releases\n- get_release_stats: Get comprehensive statistics about the release\n- get_breaking_changes: Identify potential breaking changes\n- analyze_commit_patterns: Identify themes and patterns in commits\n\nYour process should be:\n1. Analyze the commit log and diff to understand the overall scope of changes\n2. Use tools strategically to investigate significant changes that need more context\n3. Look at previous releases to understand how this release fits into the project's evolution\n4. Identify patterns, themes, and connections between changes\n5. Check for breaking changes and significant architectural shifts\n6. Understand the \"why\" behind changes by examining commit messages, issues, and code\n7. Synthesize findings into comprehensive, thoughtful release notes\n\nGuidelines:\n- Use tools strategically - focus on understanding significant changes\n- Look at test changes to understand intent and functionality\n- Check previous releases to provide context and compare scope\n- Identify patterns and themes across multiple commits\n- Consider the audience and what context they need\n- Be thorough and analytical, especially for large releases\n- Follow the release notes format and best practices provided\n\nOutput format:\nWhen you're ready to provide the final release notes, format them as JSON:\n\nRELEASE_NOTES:\n{\n \"title\": \"A concise, single-line title capturing the most significant changes\",\n \"body\": \"The detailed release notes in Markdown format, following best practices for structure, depth, and analysis\"\n}\n\nThe release notes should:\n- Demonstrate genuine understanding of the changes\n- Provide context and explain implications\n- Connect related changes to reveal patterns\n- Be substantial and analytical, not formulaic\n- Sound like they were written by a human who studied the changes\n- Be grounded in actual commits and issues (no hallucinations)`;\n}\n\n/**\n * Build the initial user message\n */\nfunction buildUserMessage(params: {\n fromRef: string;\n toRef: string;\n logContent: string;\n diffContent: string;\n milestoneIssues?: string;\n releaseFocus?: string;\n userContext?: string;\n}): string {\n const { fromRef, toRef, logContent, diffContent, milestoneIssues, releaseFocus, userContext } = params;\n\n let message = `I need comprehensive release notes for changes from ${fromRef} to ${toRef}.\n\n## Commit Log\n${logContent}\n\n## Diff Summary\n${diffContent}`;\n\n if (milestoneIssues) {\n message += `\\n\\n## Resolved Issues from Milestone\n${milestoneIssues}`;\n }\n\n if (releaseFocus) {\n message += `\\n\\n## Release Focus\n${releaseFocus}\n\nThis is the PRIMARY GUIDE for how to frame and structure the release notes. Use this to determine emphasis and narrative.`;\n }\n\n if (userContext) {\n message += `\\n\\n## Additional Context\n${userContext}`;\n }\n\n message += `\\n\\nPlease investigate these changes thoroughly and generate comprehensive release notes that:\n1. Demonstrate deep understanding of what changed and why\n2. Provide context about how changes relate to each other\n3. Explain implications for users and developers\n4. Connect this release to previous releases and project evolution\n5. Identify any breaking changes or significant architectural shifts\n6. Follow best practices for technical writing and release notes\n\nUse the available tools to gather additional context as needed. Take your time to understand the changes deeply before writing the release notes.`;\n\n return message;\n}\n\n/**\n * Parse the agentic result to extract release notes\n */\nfunction parseAgenticResult(finalMessage: string): {\n releaseNotes: { title: string; body: string };\n} {\n // Look for RELEASE_NOTES: marker with JSON\n const jsonMatch = finalMessage.match(/RELEASE_NOTES:\\s*\\n([\\s\\S]*)/);\n\n if (jsonMatch) {\n try {\n const jsonStr = jsonMatch[1].trim();\n // Try to parse the JSON\n const parsed = JSON.parse(jsonStr);\n\n if (parsed.title && parsed.body) {\n return {\n releaseNotes: {\n title: parsed.title,\n body: parsed.body,\n },\n };\n }\n } catch {\n // JSON parsing failed, fall through to fallback\n }\n }\n\n // Fallback: try to extract title and body from the message\n const lines = finalMessage.split('\\n');\n let title = '';\n let body = '';\n let inBody = false;\n\n for (const line of lines) {\n if (!title && line.trim() && !line.startsWith('#')) {\n title = line.trim();\n } else if (title && line.trim()) {\n inBody = true;\n }\n\n if (inBody) {\n body += line + '\\n';\n }\n }\n\n // If we still don't have good content, use the whole message\n if (!title || !body) {\n title = 'Release Notes';\n body = finalMessage;\n }\n\n return {\n releaseNotes: {\n title: title.trim(),\n body: body.trim(),\n },\n };\n}\n\n"],"names":["isTokenLimitError","logger","timeoutMs","elapsedTimeFormatted","fs","__filename","__dirname","path","createGetFileHistoryTool","createGetFileContentTool","createSearchCodebaseTool","createGetRelatedTestsTool","createGetFileDependenciesTool","createAnalyzeDiffSectionTool","createGetRecentCommitsTool","createGroupFilesByConcernTool","buildSystemPrompt","buildUserMessage","parseAgenticResult"],"mappings":";;;;;;;;;;AAQA,IAAI;AAKG,SAAS,UAAU,cAA4B;AAClD,WAAS;AACb;AAKO,SAAS,mBAA2B;AACvC,SAAO;AAAA,IACH,MAAM,MAAM;AAAA,IAAC;AAAA,IACb,OAAO,MAAM;AAAA,IAAC;AAAA,IACd,MAA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AAI,SAAS;AAEb,aAAW,QAAQ,OAAO;AACtB,QAAI,CAAC,SAAS,KAAK,KAAA,KAAU,CAAC,KAAK,WAAW,GAAG,GAAG;AAChD,cAAQ,KAAK,KAAA;AAAA,IACjB,WAAW,SAAS,KAAK,KAAA,GAAQ;AAC7B,eAAS;AAAA,IACb;AAEA,QAAI,QAAQ;AACR,cAAQ,OAAO;AAAA,IACnB;AAAA,EACJ;AAGA,MAAI,CAAC,SAAS,CAAC,MAAM;AACjB,YAAQ;AACR,WAAO;AAAA,EACX;AAEA,SAAO;AAAA,IACH,cAAc;AAAA,MACV,OAAO,MAAM,KAAA;AAAA,MACb,MAAM,KAAK,KAAA;AAAA,IAAK;AAAA,EACpB;AAER;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/logger.ts","../src/ai.ts","../src/interactive.ts","../src/prompts/commit.ts","../src/prompts/release.ts","../src/prompts/review.ts","../src/agentic/executor.ts","../src/tools/registry.ts","../src/tools/commit-tools.ts","../src/agentic/commit.ts","../src/tools/release-tools.ts","../src/agentic/release.ts"],"sourcesContent":["/**\n * Optional logger support\n * If winston is available as a peer dependency, use it\n * Otherwise, provide a no-op logger\n */\n\nimport type { Logger } from './types';\n\nlet logger: Logger | undefined;\n\n/**\n * Set a custom logger instance\n */\nexport function setLogger(customLogger: Logger): void {\n logger = customLogger;\n}\n\n/**\n * Create a no-op logger that does nothing\n */\nexport function createNoOpLogger(): Logger {\n return {\n info: () => {},\n error: () => {},\n warn: () => {},\n debug: () => {},\n };\n}\n\n/**\n * Attempt to load winston logger\n * @returns winston logger if available, otherwise null\n */\nexport function tryLoadWinston(): Logger | null {\n try {\n // Dynamic import to avoid hard dependency\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const winston = require('winston');\n if (winston && winston.createLogger) {\n return winston.createLogger({\n level: 'info',\n format: winston.format.simple(),\n transports: [new winston.transports.Console()],\n });\n }\n } catch {\n // Winston not available\n }\n return null;\n}\n\n/**\n * Get the current logger or a no-op logger\n */\nexport function getLogger(): Logger {\n if (logger) {\n return logger;\n }\n\n // Try to load winston if available\n const winstonLogger = tryLoadWinston();\n if (winstonLogger) {\n logger = winstonLogger;\n return winstonLogger;\n }\n\n // Return no-op logger\n return createNoOpLogger();\n}\n","import { OpenAI } from 'openai';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\nimport { safeJsonParse } from '@eldrforge/git-tools';\nimport fs from 'fs';\nimport { getLogger } from './logger';\nimport type { AIConfig, Transcription, StorageAdapter, Logger } from './types';\n\nexport interface OpenAIOptions {\n responseFormat?: any;\n model?: string;\n debug?: boolean;\n debugFile?: string;\n debugRequestFile?: string;\n debugResponseFile?: string;\n maxTokens?: number;\n openaiReasoning?: 'low' | 'medium' | 'high';\n openaiMaxOutputTokens?: number;\n storage?: StorageAdapter;\n logger?: Logger;\n tools?: any[]; // OpenAI tool definitions\n toolChoice?: 'auto' | 'none' | 'required' | { type: 'function'; function: { name: string } };\n}\n\nexport interface TranscriptionOptions {\n model?: string;\n debug?: boolean;\n debugFile?: string;\n debugRequestFile?: string;\n debugResponseFile?: string;\n outputDirectory?: string;\n storage?: StorageAdapter;\n logger?: Logger;\n onArchive?: (audioPath: string, transcriptionText: string) => Promise<void>;\n}\n\n/**\n * Get the appropriate model to use based on command-specific configuration\n * Command-specific model overrides the global model setting\n */\nexport function getModelForCommand(config: AIConfig, commandName: string): string {\n let commandModel: string | undefined;\n\n switch (commandName) {\n case 'commit':\n case 'audio-commit':\n commandModel = config.commands?.commit?.model;\n break;\n case 'release':\n commandModel = config.commands?.release?.model;\n break;\n case 'review':\n case 'audio-review':\n commandModel = config.commands?.review?.model;\n break;\n default:\n // For other commands, just use global model\n break;\n }\n\n // Return command-specific model if available, otherwise global model\n return commandModel || config.model || 'gpt-4o-mini';\n}\n\n/**\n * Get the appropriate OpenAI reasoning level based on command-specific configuration\n * Command-specific reasoning overrides the global reasoning setting\n */\nexport function getOpenAIReasoningForCommand(config: AIConfig, commandName: string): 'low' | 'medium' | 'high' {\n let commandReasoning: 'low' | 'medium' | 'high' | undefined;\n\n switch (commandName) {\n case 'commit':\n case 'audio-commit':\n commandReasoning = config.commands?.commit?.reasoning;\n break;\n case 'release':\n commandReasoning = config.commands?.release?.reasoning;\n break;\n case 'review':\n case 'audio-review':\n commandReasoning = config.commands?.review?.reasoning;\n break;\n default:\n // For other commands, just use global reasoning\n break;\n }\n\n // Return command-specific reasoning if available, otherwise global reasoning\n return commandReasoning || config.reasoning || 'low';\n}\n\nexport class OpenAIError extends Error {\n constructor(message: string, public readonly isTokenLimitError: boolean = false) {\n super(message);\n this.name = 'OpenAIError';\n }\n}\n\n// Check if an error is a token limit exceeded error\nexport function isTokenLimitError(error: any): boolean {\n if (!error?.message) return false;\n\n const message = error.message.toLowerCase();\n return message.includes('maximum context length') ||\n message.includes('context_length_exceeded') ||\n message.includes('token limit') ||\n message.includes('too many tokens') ||\n message.includes('reduce the length');\n}\n\n// Check if an error is a rate limit error\nexport function isRateLimitError(error: any): boolean {\n if (!error?.message && !error?.code && !error?.status) return false;\n\n // Check for OpenAI specific rate limit indicators\n if (error.status === 429 || error.code === 'rate_limit_exceeded') {\n return true;\n }\n\n // Only check message if it exists\n if (error.message) {\n const message = error.message.toLowerCase();\n return message.includes('rate limit exceeded') ||\n message.includes('too many requests') ||\n message.includes('quota exceeded') ||\n (message.includes('rate') && message.includes('limit'));\n }\n\n return false;\n}\n\n/**\n * Create OpenAI completion with optional debug and retry support\n */\nexport async function createCompletion(\n messages: ChatCompletionMessageParam[],\n options: OpenAIOptions = { model: \"gpt-4o-mini\" }\n): Promise<string | any> {\n const logger = options.logger || getLogger();\n let openai: OpenAI | null = null;\n\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n // Create the client which we'll close in the finally block.\n const timeoutMs = parseInt(process.env.OPENAI_TIMEOUT_MS || '300000'); // Default to 5 minutes\n openai = new OpenAI({\n apiKey: apiKey,\n timeout: timeoutMs,\n });\n\n const modelToUse = options.model || \"gpt-4o-mini\";\n\n // Calculate request size\n const requestSize = JSON.stringify(messages).length;\n const requestSizeKB = (requestSize / 1024).toFixed(2);\n\n // Log model, reasoning level, and request size\n const reasoningInfo = options.openaiReasoning ? ` | Reasoning: ${options.openaiReasoning}` : '';\n logger.info('🤖 Making request to OpenAI');\n logger.info(' Model: %s%s', modelToUse, reasoningInfo);\n logger.info(' Request size: %s KB (%s bytes)', requestSizeKB, requestSize.toLocaleString());\n\n logger.debug('Sending prompt to OpenAI: %j', messages);\n\n // Use openaiMaxOutputTokens if specified (highest priority), otherwise fall back to maxTokens, or default to 10000\n const maxCompletionTokens = options.openaiMaxOutputTokens ?? options.maxTokens ?? 10000;\n\n // Save request debug file if enabled\n if (options.debug && (options.debugRequestFile || options.debugFile) && options.storage) {\n const requestData = {\n model: modelToUse,\n messages,\n max_completion_tokens: maxCompletionTokens,\n response_format: options.responseFormat,\n reasoning_effort: options.openaiReasoning,\n };\n const debugFile = options.debugRequestFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(requestData, null, 2));\n logger.debug('Wrote request debug file to %s', debugFile);\n }\n\n // Prepare the API call options\n const apiOptions: any = {\n model: modelToUse,\n messages,\n max_completion_tokens: maxCompletionTokens,\n response_format: options.responseFormat,\n };\n\n // Add tools if provided\n if (options.tools && options.tools.length > 0) {\n apiOptions.tools = options.tools;\n apiOptions.tool_choice = options.toolChoice || 'auto';\n }\n\n // Add reasoning parameter if specified and model supports it\n if (options.openaiReasoning && (modelToUse.includes('gpt-5') || modelToUse.includes('o3'))) {\n apiOptions.reasoning_effort = options.openaiReasoning;\n }\n\n // Add timeout wrapper to the OpenAI API call\n const startTime = Date.now();\n const completionPromise = openai.chat.completions.create(apiOptions);\n\n // Create timeout promise with proper cleanup to prevent memory leaks\n let timeoutId: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<never>((_, reject) => {\n const timeoutMs = parseInt(process.env.OPENAI_TIMEOUT_MS || '300000'); // Default to 5 minutes\n timeoutId = setTimeout(() => reject(new OpenAIError(`OpenAI API call timed out after ${timeoutMs/1000} seconds`)), timeoutMs);\n });\n\n // Add progress indicator that updates every 5 seconds\n let progressIntervalId: NodeJS.Timeout | null = null;\n progressIntervalId = setInterval(() => {\n const elapsed = Math.round((Date.now() - startTime) / 1000);\n logger.info(' ⏳ Waiting for response... %ds', elapsed);\n }, 5000);\n\n let completion;\n try {\n completion = await Promise.race([completionPromise, timeoutPromise]);\n } finally {\n // Clear the timeout to prevent memory leaks\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n }\n // Clear the progress interval\n if (progressIntervalId !== null) {\n clearInterval(progressIntervalId);\n }\n }\n\n const elapsedTime = Date.now() - startTime;\n\n // Save response debug file if enabled\n if (options.debug && (options.debugResponseFile || options.debugFile) && options.storage) {\n const debugFile = options.debugResponseFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(completion, null, 2));\n logger.debug('Wrote response debug file to %s', debugFile);\n }\n\n const message = completion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError('No response message received from OpenAI');\n }\n\n // If tools are being used, return the full message object (includes tool_calls)\n if (options.tools && options.tools.length > 0) {\n // Log elapsed time\n const elapsedTimeFormatted = elapsedTime >= 1000\n ? `${(elapsedTime / 1000).toFixed(1)}s`\n : `${elapsedTime}ms`;\n logger.info(' Time: %s', elapsedTimeFormatted);\n\n // Log token usage if available\n if (completion.usage) {\n logger.info(' Token usage: %s prompt + %s completion = %s total',\n completion.usage.prompt_tokens?.toLocaleString() || '?',\n completion.usage.completion_tokens?.toLocaleString() || '?',\n completion.usage.total_tokens?.toLocaleString() || '?'\n );\n }\n\n return message; // Return full message object for tool handling\n }\n\n // For non-tool calls, return content as string\n const response = message.content?.trim();\n if (!response) {\n throw new OpenAIError('No response content received from OpenAI');\n }\n\n // Calculate and log response size\n const responseSize = response.length;\n const responseSizeKB = (responseSize / 1024).toFixed(2);\n logger.info(' Response size: %s KB (%s bytes)', responseSizeKB, responseSize.toLocaleString());\n\n // Log elapsed time\n const elapsedTimeFormatted = elapsedTime >= 1000\n ? `${(elapsedTime / 1000).toFixed(1)}s`\n : `${elapsedTime}ms`;\n logger.info(' Time: %s', elapsedTimeFormatted);\n\n // Log token usage if available\n if (completion.usage) {\n logger.info(' Token usage: %s prompt + %s completion = %s total',\n completion.usage.prompt_tokens?.toLocaleString() || '?',\n completion.usage.completion_tokens?.toLocaleString() || '?',\n completion.usage.total_tokens?.toLocaleString() || '?'\n );\n }\n\n logger.debug('Received response from OpenAI: %s...', response.substring(0, 30));\n if (options.responseFormat) {\n return safeJsonParse(response, 'OpenAI API response');\n } else {\n return response;\n }\n\n } catch (error: any) {\n logger.error('Error calling OpenAI API: %s %s', error.message, error.stack);\n const isTokenError = isTokenLimitError(error);\n throw new OpenAIError(`Failed to create completion: ${error.message}`, isTokenError);\n } finally {\n // OpenAI client cleanup is handled automatically by the library\n // No manual cleanup needed for newer versions\n }\n}\n\n/**\n * Create completion with automatic retry on token limit errors\n */\nexport async function createCompletionWithRetry(\n messages: ChatCompletionMessageParam[],\n options: OpenAIOptions = { model: \"gpt-4o-mini\" },\n retryCallback?: (attempt: number) => Promise<ChatCompletionMessageParam[]>\n): Promise<string | any> {\n const logger = options.logger || getLogger();\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const messagesToSend = attempt === 1 ? messages : (retryCallback ? await retryCallback(attempt) : messages);\n return await createCompletion(messagesToSend, options);\n } catch (error: any) {\n if (error instanceof OpenAIError && error.isTokenLimitError && attempt < maxRetries && retryCallback) {\n logger.warn('Token limit exceeded on attempt %d/%d, retrying with reduced content...', attempt, maxRetries);\n // Add exponential backoff for token limit errors\n const backoffMs = Math.min(1000 * Math.pow(2, attempt - 1), 10000);\n await new Promise(resolve => setTimeout(resolve, backoffMs));\n continue;\n } else if (isRateLimitError(error) && attempt < maxRetries) {\n // Handle rate limiting with exponential backoff\n const backoffMs = Math.min(2000 * Math.pow(2, attempt - 1), 15000); // More reasonable backoff: 2s, 4s, 8s, max 15s\n logger.warn(`Rate limit hit on attempt ${attempt}/${maxRetries}, waiting ${backoffMs}ms before retry...`);\n await new Promise(resolve => setTimeout(resolve, backoffMs));\n continue;\n }\n throw error;\n }\n }\n\n // This should never be reached, but TypeScript requires it\n throw new OpenAIError('Max retries exceeded');\n}\n\n/**\n * Transcribe audio file using OpenAI Whisper API\n */\nexport async function transcribeAudio(\n filePath: string,\n options: TranscriptionOptions = { model: \"whisper-1\" }\n): Promise<Transcription> {\n const logger = options.logger || getLogger();\n let openai: OpenAI | null = null;\n let audioStream: fs.ReadStream | null = null;\n let streamClosed = false;\n\n // Helper function to safely close the stream\n const closeAudioStream = () => {\n if (audioStream && !streamClosed) {\n try {\n // Only call destroy if it exists and the stream isn't already destroyed\n if (typeof audioStream.destroy === 'function' && !audioStream.destroyed) {\n audioStream.destroy();\n }\n streamClosed = true;\n logger.debug('Audio stream closed successfully');\n } catch (streamErr) {\n logger.debug('Failed to destroy audio read stream: %s', (streamErr as Error).message);\n streamClosed = true; // Mark as closed even if destroy failed\n }\n }\n };\n\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n openai = new OpenAI({\n apiKey: apiKey,\n });\n\n logger.debug('Transcribing audio file: %s', filePath);\n\n // Save request debug file if enabled\n if (options.debug && (options.debugRequestFile || options.debugFile) && options.storage) {\n const requestData = {\n model: options.model || \"whisper-1\",\n file: filePath, // Can't serialize the stream, so just save the file path\n response_format: \"json\",\n };\n const debugFile = options.debugRequestFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(requestData, null, 2));\n logger.debug('Wrote request debug file to %s', debugFile);\n }\n\n audioStream = fs.createReadStream(filePath);\n\n // Set up error handler for the stream to ensure cleanup on stream errors\n // Only add handler if the stream has the 'on' method (real streams)\n if (audioStream && typeof audioStream.on === 'function') {\n audioStream.on('error', (streamError) => {\n logger.error('Audio stream error: %s', streamError.message);\n closeAudioStream();\n });\n }\n\n let transcription;\n try {\n transcription = await openai.audio.transcriptions.create({\n model: options.model || \"whisper-1\",\n file: audioStream,\n response_format: \"json\",\n });\n // Close the stream immediately after successful API call to prevent race conditions\n closeAudioStream();\n } catch (apiError) {\n // Close the stream immediately if the API call fails\n closeAudioStream();\n throw apiError;\n }\n\n // Save response debug file if enabled\n if (options.debug && (options.debugResponseFile || options.debugFile) && options.storage) {\n const debugFile = options.debugResponseFile || options.debugFile;\n await options.storage.writeTemp(debugFile!, JSON.stringify(transcription, null, 2));\n logger.debug('Wrote response debug file to %s', debugFile);\n }\n\n const response = transcription;\n if (!response) {\n throw new OpenAIError('No transcription received from OpenAI');\n }\n\n logger.debug('Received transcription from OpenAI: %s', response);\n\n // Archive the audio file and transcription if callback provided\n if (options.onArchive) {\n try {\n await options.onArchive(filePath, response.text);\n } catch (archiveError: any) {\n // Don't fail the transcription if archiving fails, just log the error\n logger.warn('Failed to archive audio file: %s', archiveError.message);\n }\n }\n\n return response;\n\n } catch (error: any) {\n logger.error('Error transcribing audio file: %s %s', error.message, error.stack);\n throw new OpenAIError(`Failed to transcribe audio: ${error.message}`);\n } finally {\n // Ensure the audio stream is properly closed to release file handles\n closeAudioStream();\n // OpenAI client cleanup is handled automatically by the library\n // No manual cleanup needed for newer versions\n }\n}\n\n","#!/usr/bin/env node\nimport { getLogger } from './logger';\nimport type { Logger, Choice, InteractiveOptions } from './types';\nimport { spawnSync } from 'child_process';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as fs from 'fs/promises';\n\n/**\n * Get user choice interactively from terminal input\n * @param prompt The prompt message to display\n * @param choices Array of available choices\n * @param options Additional options for customizing behavior\n * @returns Promise resolving to the selected choice key\n */\nexport async function getUserChoice(\n prompt: string,\n choices: Choice[],\n options: InteractiveOptions = {}\n): Promise<string> {\n const logger = options.logger || getLogger();\n\n logger.info(prompt);\n choices.forEach(choice => {\n logger.info(` [${choice.key}] ${choice.label}`);\n });\n logger.info('');\n\n // Check if stdin is a TTY (terminal) or piped\n if (!process.stdin.isTTY) {\n logger.error('⚠️ STDIN is piped but interactive mode is enabled');\n logger.error(' Interactive prompts cannot be used when input is piped');\n logger.error(' Solutions:');\n logger.error(' • Use terminal input instead of piping');\n\n // Add any additional suggestions\n if (options.nonTtyErrorSuggestions) {\n options.nonTtyErrorSuggestions.forEach(suggestion => {\n logger.error(` • ${suggestion}`);\n });\n }\n\n return 's'; // Default to skip\n }\n\n return new Promise((resolve, reject) => {\n let isResolved = false;\n let dataHandler: ((key: Buffer) => void) | null = null;\n let errorHandler: ((error: Error) => void) | null = null;\n\n const cleanup = () => {\n if (dataHandler) {\n process.stdin.removeListener('data', dataHandler);\n }\n if (errorHandler) {\n process.stdin.removeListener('error', errorHandler);\n }\n\n try {\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n process.stdin.pause();\n // Detach stdin again now that we're done\n if (typeof process.stdin.unref === 'function') {\n process.stdin.unref();\n }\n } catch {\n // Ignore cleanup errors\n }\n };\n\n const safeResolve = (value: string) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n resolve(value);\n }\n };\n\n const safeReject = (error: Error) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n reject(error);\n }\n };\n\n try {\n // Ensure stdin is referenced so the process doesn't exit while waiting for input\n if (typeof process.stdin.ref === 'function') {\n process.stdin.ref();\n }\n\n process.stdin.setRawMode(true);\n process.stdin.resume();\n\n dataHandler = (key: Buffer) => {\n try {\n const keyStr = key.toString().toLowerCase();\n const choice = choices.find(c => c.key === keyStr);\n if (choice) {\n logger.info(`Selected: ${choice.label}\\n`);\n safeResolve(choice.key);\n }\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Unknown error processing input'));\n }\n };\n\n errorHandler = (error: Error) => {\n safeReject(error);\n };\n\n process.stdin.on('data', dataHandler);\n process.stdin.on('error', errorHandler);\n\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Failed to setup input handlers'));\n }\n });\n}\n\n/**\n * Secure temporary file handle that prevents TOCTOU vulnerabilities\n */\nexport class SecureTempFile {\n private fd: fs.FileHandle | null = null;\n private filePath: string;\n private isCleanedUp = false;\n private logger: Logger;\n\n private constructor(filePath: string, fd: fs.FileHandle, logger?: Logger) {\n this.filePath = filePath;\n this.fd = fd;\n this.logger = logger || getLogger();\n }\n\n /**\n * Create a secure temporary file with proper permissions and atomic operations\n * @param prefix Prefix for the temporary filename\n * @param extension File extension (e.g., '.txt', '.md')\n * @param logger Optional logger instance\n * @returns Promise resolving to SecureTempFile instance\n */\n static async create(prefix: string = 'ai-service', extension: string = '.txt', logger?: Logger): Promise<SecureTempFile> {\n const tmpDir = os.tmpdir();\n const log = logger || getLogger();\n\n // Ensure temp directory exists and is writable (skip check in test environments)\n if (!process.env.VITEST) {\n try {\n await fs.access(tmpDir, fs.constants.W_OK);\n } catch (error: any) {\n // Try to create the directory if it doesn't exist\n try {\n await fs.mkdir(tmpDir, { recursive: true, mode: 0o700 });\n } catch (mkdirError: any) {\n throw new Error(`Temp directory not writable: ${tmpDir} - ${error.message}. Failed to create: ${mkdirError.message}`);\n }\n }\n }\n\n const tmpFilePath = path.join(tmpDir, `${prefix}_${Date.now()}_${Math.random().toString(36).substring(7)}${extension}`);\n\n // Create file with exclusive access and restrictive permissions (owner read/write only)\n // Using 'wx' flag ensures exclusive creation (fails if file exists)\n let fd: fs.FileHandle;\n try {\n fd = await fs.open(tmpFilePath, 'wx', 0o600);\n } catch (error: any) {\n if (error.code === 'EEXIST') {\n // Highly unlikely with timestamp + random suffix, but handle it\n throw new Error(`Temporary file already exists: ${tmpFilePath}`);\n }\n throw new Error(`Failed to create temporary file: ${error.message}`);\n }\n\n return new SecureTempFile(tmpFilePath, fd, log);\n }\n\n /**\n * Get the file path (use with caution in external commands)\n */\n get path(): string {\n if (this.isCleanedUp) {\n throw new Error('Temp file has been cleaned up');\n }\n return this.filePath;\n }\n\n /**\n * Write content to the temporary file\n */\n async writeContent(content: string): Promise<void> {\n if (!this.fd || this.isCleanedUp) {\n throw new Error('Temp file is not available for writing');\n }\n await this.fd.writeFile(content, 'utf8');\n }\n\n /**\n * Read content from the temporary file\n */\n async readContent(): Promise<string> {\n if (!this.fd || this.isCleanedUp) {\n throw new Error('Temp file is not available for reading');\n }\n const content = await this.fd.readFile('utf8');\n return content;\n }\n\n /**\n * Close the file handle\n */\n async close(): Promise<void> {\n if (this.fd && !this.isCleanedUp) {\n await this.fd.close();\n this.fd = null;\n }\n }\n\n /**\n * Securely cleanup the temporary file - prevents TOCTOU by using file descriptor\n */\n async cleanup(): Promise<void> {\n if (this.isCleanedUp) {\n return; // Already cleaned up\n }\n\n try {\n // Close file descriptor first if still open\n if (this.fd) {\n await this.fd.close();\n this.fd = null;\n }\n\n // Now safely remove the file\n // Use fs.unlink which is safer than checking existence first\n await fs.unlink(this.filePath);\n } catch (error: any) {\n // Only ignore ENOENT (file not found) errors\n if (error.code !== 'ENOENT') {\n this.logger.warn(`Failed to cleanup temp file ${this.filePath}: ${error.message}`);\n // Don't throw here to avoid masking main operations\n }\n } finally {\n this.isCleanedUp = true;\n }\n }\n}\n\n/**\n * Create a secure temporary file for editing with proper permissions\n * @param prefix Prefix for the temporary filename\n * @param extension File extension (e.g., '.txt', '.md')\n * @param logger Optional logger instance\n * @returns Promise resolving to the temporary file path\n * @deprecated Use SecureTempFile.create() for better security\n */\nexport async function createSecureTempFile(prefix: string = 'ai-service', extension: string = '.txt', logger?: Logger): Promise<string> {\n const secureTempFile = await SecureTempFile.create(prefix, extension, logger);\n await secureTempFile.close();\n return secureTempFile.path;\n}\n\n/**\n * Clean up a temporary file\n * @param filePath Path to the temporary file to clean up\n * @param logger Optional logger instance\n * @deprecated Use SecureTempFile.cleanup() for better security\n */\nexport async function cleanupTempFile(filePath: string, logger?: Logger): Promise<void> {\n const log = logger || getLogger();\n try {\n await fs.unlink(filePath);\n } catch (error: any) {\n // Only ignore ENOENT (file not found) errors\n if (error.code !== 'ENOENT') {\n log.warn(`Failed to cleanup temp file ${filePath}: ${error.message}`);\n }\n }\n}\n\nexport interface EditorResult {\n content: string;\n wasEdited: boolean;\n}\n\n/**\n * Open content in user's editor for editing\n * @param content Initial content to edit\n * @param templateLines Additional template lines to include (will be filtered out)\n * @param fileExtension File extension for syntax highlighting\n * @param editor Editor command to use (defaults to EDITOR/VISUAL env var or 'vi')\n * @param logger Optional logger instance\n * @returns Promise resolving to the edited content\n */\nexport async function editContentInEditor(\n content: string,\n templateLines: string[] = [],\n fileExtension: string = '.txt',\n editor?: string,\n logger?: Logger\n): Promise<EditorResult> {\n const log = logger || getLogger();\n const editorCmd = editor || process.env.EDITOR || process.env.VISUAL || 'vi';\n\n const secureTempFile = await SecureTempFile.create('ai-service_edit', fileExtension, log);\n try {\n // Build template content\n const templateContent = [\n ...templateLines,\n ...(templateLines.length > 0 ? [''] : []), // Add separator if we have template lines\n content,\n '',\n ].join('\\n');\n\n await secureTempFile.writeContent(templateContent);\n await secureTempFile.close(); // Close before external editor access\n\n log.info(`📝 Opening ${editorCmd} to edit content...`);\n\n // Open the editor synchronously\n const result = spawnSync(editorCmd, [secureTempFile.path], { stdio: 'inherit' });\n\n if (result.error) {\n throw new Error(`Failed to launch editor '${editorCmd}': ${result.error.message}`);\n }\n\n // Read the file back in, stripping comment lines\n const fileContent = (await fs.readFile(secureTempFile.path, 'utf8'))\n .split('\\n')\n .filter(line => !line.trim().startsWith('#'))\n .join('\\n')\n .trim();\n\n if (!fileContent) {\n throw new Error('Content is empty after editing');\n }\n\n log.info('✅ Content updated successfully');\n\n return {\n content: fileContent,\n wasEdited: fileContent !== content.trim()\n };\n\n } finally {\n // Always clean up the temp file securely\n await secureTempFile.cleanup();\n }\n}\n\n/**\n * Standard choices for interactive feedback loops\n */\nexport const STANDARD_CHOICES = {\n CONFIRM: { key: 'c', label: 'Confirm and proceed' },\n EDIT: { key: 'e', label: 'Edit in editor' },\n SKIP: { key: 's', label: 'Skip and abort' },\n IMPROVE: { key: 'i', label: 'Improve with LLM feedback' }\n} as const;\n\n/**\n * Get text input from the user\n * @param prompt The prompt message to display\n * @param options Additional options for customizing behavior\n * @returns Promise resolving to the user's text input\n */\nexport async function getUserTextInput(\n prompt: string,\n options: InteractiveOptions = {}\n): Promise<string> {\n const logger = options.logger || getLogger();\n\n // Check if stdin is a TTY (terminal) or piped\n if (!process.stdin.isTTY) {\n logger.error('⚠️ STDIN is piped but interactive text input is required');\n logger.error(' Interactive text input cannot be used when input is piped');\n logger.error(' Solutions:');\n logger.error(' • Use terminal input instead of piping');\n\n // Add any additional suggestions\n if (options.nonTtyErrorSuggestions) {\n options.nonTtyErrorSuggestions.forEach(suggestion => {\n logger.error(` • ${suggestion}`);\n });\n }\n\n throw new Error('Interactive text input requires a terminal');\n }\n\n logger.info(prompt);\n logger.info('(Press Enter when done, or type Ctrl+C to cancel)');\n logger.info('');\n\n return new Promise((resolve, reject) => {\n let inputBuffer = '';\n let isResolved = false;\n let dataHandler: ((chunk: string) => void) | null = null;\n let errorHandler: ((error: Error) => void) | null = null;\n\n const cleanup = () => {\n if (dataHandler) {\n process.stdin.removeListener('data', dataHandler);\n }\n if (errorHandler) {\n process.stdin.removeListener('error', errorHandler);\n }\n\n try {\n process.stdin.pause();\n // Detach stdin again now that we're done\n if (typeof process.stdin.unref === 'function') {\n process.stdin.unref();\n }\n } catch {\n // Ignore cleanup errors\n }\n };\n\n const safeResolve = (value: string) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n resolve(value);\n }\n };\n\n const safeReject = (error: Error) => {\n if (!isResolved) {\n isResolved = true;\n cleanup();\n reject(error);\n }\n };\n\n try {\n // Ensure stdin is referenced so the process doesn't exit while waiting for input\n if (typeof process.stdin.ref === 'function') {\n process.stdin.ref();\n }\n\n process.stdin.setEncoding('utf8');\n process.stdin.resume();\n\n dataHandler = (chunk: string) => {\n try {\n inputBuffer += chunk;\n\n // Check if user pressed Enter (newline character)\n if (inputBuffer.includes('\\n')) {\n const userInput = inputBuffer.replace(/\\n$/, '').trim();\n\n if (userInput === '') {\n logger.warn('Empty input received. Please provide feedback text.');\n safeReject(new Error('Empty input received'));\n } else {\n logger.info(`✅ Received feedback: \"${userInput}\"\\n`);\n safeResolve(userInput);\n }\n }\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Unknown error processing input'));\n }\n };\n\n errorHandler = (error: Error) => {\n safeReject(error);\n };\n\n process.stdin.on('data', dataHandler);\n process.stdin.on('error', errorHandler);\n\n } catch (error) {\n safeReject(error instanceof Error ? error : new Error('Failed to setup input handlers'));\n }\n });\n}\n\n/**\n * Get LLM improvement feedback from the user using the editor\n * @param contentType Type of content being improved (e.g., 'commit message', 'release notes')\n * @param currentContent The current content to be improved\n * @param editor Optional editor command\n * @param logger Optional logger instance\n * @returns Promise resolving to the user's feedback text\n */\nexport async function getLLMFeedbackInEditor(\n contentType: string,\n currentContent: string,\n editor?: string,\n logger?: Logger\n): Promise<string> {\n const templateLines = [\n '# Provide Your Instructions and Guidance for a Revision Here',\n '#',\n '# Type your guidance above this line. Be specific about what you want changed,',\n '# added, or improved. You can also edit the original content below directly',\n '# to provide examples or show desired changes.',\n '#',\n '# Lines starting with \"#\" will be ignored.',\n '',\n '### YOUR FEEDBACK AND GUIDANCE:',\n '',\n '# (Type your improvement instructions here)',\n '',\n `### ORIGINAL ${contentType.toUpperCase()}:`,\n ''\n ];\n\n const result = await editContentInEditor(\n currentContent,\n templateLines,\n '.md',\n editor,\n logger\n );\n\n // Extract just the feedback section (everything before the original content)\n const lines = result.content.split('\\n');\n const originalSectionIndex = lines.findIndex(line =>\n line.trim().toLowerCase().startsWith('### original')\n );\n\n let feedback: string;\n if (originalSectionIndex >= 0) {\n // Take everything before the \"### ORIGINAL\" section\n feedback = lines.slice(0, originalSectionIndex).join('\\n').trim();\n } else {\n // If no original section found, take everything\n feedback = result.content.trim();\n }\n\n // Remove the feedback header if it exists\n feedback = feedback.replace(/^### YOUR FEEDBACK AND GUIDANCE:\\s*/i, '').trim();\n\n if (!feedback) {\n throw new Error('No feedback provided. Please provide improvement instructions.');\n }\n\n return feedback;\n}\n\n/**\n * Check if interactive mode is available (TTY check)\n * @param errorMessage Custom error message to throw if TTY not available\n * @param logger Optional logger instance\n * @throws Error if not in TTY environment\n */\nexport function requireTTY(errorMessage: string = 'Interactive mode requires a terminal. Use --dry-run instead.', logger?: Logger): void {\n const log = logger || getLogger();\n if (!process.stdin.isTTY) {\n log.error('❌ Interactive mode requires a terminal (TTY)');\n log.error(' Solutions:');\n log.error(' • Run without piping input');\n log.error(' • Use --dry-run to see the generated content');\n throw new Error(errorMessage);\n }\n}\n\n","import { Prompt, recipe } from '@riotprompt/riotprompt';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Types for the commit prompt\nexport type CommitContent = {\n diffContent: string;\n userDirection?: string;\n isFileContent?: boolean; // Flag to indicate if diffContent is actually file content\n githubIssuesContext?: string; // GitHub issues related to current version/milestone\n};\n\nexport type CommitContext = {\n logContext?: string;\n context?: string;\n directories?: string[];\n};\n\nexport type CommitConfig = {\n overridePaths?: string[];\n overrides?: boolean;\n}\n\n/**\n * Build a commit prompt using RiotPrompt Recipes.\n *\n * This prompt is configured to generate multiline commit messages by default,\n * with separate lines/bullet points for different groups of changes rather\n * than squeezing everything into single lines.\n *\n * @param config The configuration for overrides\n * @param content Mandatory content inputs (e.g. diff)\n * @param ctx Optional contextual inputs configured by the user\n */\nexport const createCommitPrompt = async (\n { overridePaths: _overridePaths, overrides: _overrides }: CommitConfig,\n { diffContent, userDirection, isFileContent, githubIssuesContext }: CommitContent,\n { logContext, context, directories }: CommitContext = {}\n): Promise<Prompt> => {\n const basePath = __dirname;\n\n // Build content items for the prompt\n const contentItems = [];\n const contextItems = [];\n\n // Developer Note: Direction is injected first as the highest-priority prompt input\n // This ensures user guidance takes precedence over other context sources like\n // GitHub issues or commit history.\n if (userDirection) {\n contentItems.push({ content: userDirection, title: 'User Direction' });\n }\n if (diffContent) {\n const contentTitle = isFileContent ? 'Project Files' : 'Diff';\n contentItems.push({ content: diffContent, title: contentTitle });\n }\n if (githubIssuesContext) {\n contentItems.push({ content: githubIssuesContext, title: 'Recent GitHub Issues' });\n }\n\n // IMPORTANT: Log context provides background but can contaminate output if too large.\n // LLMs tend to pattern-match against recent commits instead of describing the actual diff.\n // Keep messageLimit low (3-5) to minimize contamination.\n if (logContext) {\n contextItems.push({ content: logContext, title: 'Log Context' });\n }\n if (context) {\n contextItems.push({ content: context, title: 'User Context' });\n }\n if (directories && directories.length > 0) {\n contextItems.push({ directories, title: 'Directories' });\n }\n\n return recipe(basePath)\n .persona({ path: 'personas/you.md' })\n .instructions({ path: 'instructions/commit.md' })\n .overridePaths(_overridePaths ?? [])\n .overrides(_overrides ?? true)\n .content(...contentItems)\n .context(...contextItems)\n .cook();\n};\n\n","import { ContentItem, Prompt, recipe } from '@riotprompt/riotprompt';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Types for the release prompt\nexport type ReleaseConfig = {\n overridePaths?: string[];\n overrides?: boolean;\n}\n\nexport type ReleaseContent = {\n releaseFocus?: string;\n logContent: string;\n diffContent: string;\n milestoneIssues?: string;\n};\n\nexport type ReleaseContext = {\n context?: string;\n directories?: string[];\n};\n\nexport type ReleasePromptResult = {\n prompt: Prompt;\n maxTokens: number;\n isLargeRelease: boolean;\n};\n\n/**\n * Analyzes release content to determine if it's a large release\n * and calculates appropriate token limits\n */\nconst analyzeReleaseSize = (logContent: string, diffContent?: string, milestoneIssues?: string): { isLarge: boolean; maxTokens: number } => {\n const logLines = logContent.split('\\n').length;\n const diffLines = diffContent ? diffContent.split('\\n').length : 0;\n const milestoneLines = milestoneIssues ? milestoneIssues.split('\\n').length : 0;\n const totalContentLength = logContent.length + (diffContent?.length || 0) + (milestoneIssues?.length || 0);\n\n // Consider it a large release if:\n // - More than 20 commits (log lines typically ~3-5 per commit)\n // - More than 500 diff lines\n // - Milestone issues present (indicates significant work)\n // - Total content length > 50KB\n const isLarge = logLines > 60 || diffLines > 500 || milestoneLines > 50 || totalContentLength > 50000;\n\n if (isLarge) {\n // For large releases, significantly increase token limit\n return { isLarge: true, maxTokens: 25000 };\n } else {\n // Standard token limit for normal releases\n return { isLarge: false, maxTokens: 10000 };\n }\n};\n\n/**\n * Build a release prompt using RiotPrompt Recipes.\n */\nexport const createReleasePrompt = async (\n { overrides: _overrides, overridePaths: _overridePaths }: ReleaseConfig,\n { releaseFocus, logContent, diffContent, milestoneIssues }: ReleaseContent,\n { context, directories }: ReleaseContext = {}\n): Promise<ReleasePromptResult> => {\n const basePath = __dirname;\n\n // Analyze release size to determine token requirements\n const { isLarge: isLargeRelease, maxTokens } = analyzeReleaseSize(logContent, diffContent, milestoneIssues);\n\n // Build content items for the prompt\n const contentItems: ContentItem[] = [];\n const contextItems: ContentItem[] = [];\n\n if (diffContent) {\n contentItems.push({ content: diffContent, title: 'Diff' });\n }\n if (logContent) {\n contentItems.push({ content: logContent, title: 'Log Context' });\n }\n if (milestoneIssues) {\n contentItems.push({ content: milestoneIssues, title: 'Resolved Issues from Milestone' });\n }\n if (releaseFocus) {\n contentItems.push({ content: releaseFocus, title: 'Release Focus' });\n }\n\n // Add release size context to help guide the AI\n if (isLargeRelease) {\n contextItems.push({\n content: `This appears to be a LARGE RELEASE with significant changes. Please provide comprehensive, detailed release notes that thoroughly document all major changes, improvements, and fixes. Don't summarize - dive deep into the details.`,\n title: 'Release Size Context'\n });\n }\n\n if (context) {\n contextItems.push({ content: context, title: 'User Context' });\n }\n if (directories && directories.length > 0) {\n contextItems.push({ directories, title: 'Directories' });\n }\n\n const prompt = await recipe(basePath)\n .persona({ path: 'personas/releaser.md' })\n .instructions({ path: 'instructions/release.md' })\n .overridePaths(_overridePaths ?? [])\n .overrides(_overrides ?? true)\n .content(...contentItems)\n .context(...contextItems)\n .cook();\n\n return {\n prompt,\n maxTokens,\n isLargeRelease\n };\n};\n\n","import { ContentItem, Prompt, recipe } from '@riotprompt/riotprompt';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport type ReviewConfig = {\n overridePaths?: string[];\n overrides?: boolean;\n}\n\nexport type ReviewContent = {\n notes: string;\n};\n\nexport type ReviewContext = {\n logContext?: string;\n diffContext?: string;\n releaseNotesContext?: string;\n issuesContext?: string;\n context?: string;\n directories?: string[];\n};\n\n/**\n * Build a review prompt using RiotPrompt Recipes.\n */\nexport const createReviewPrompt = async (\n { overridePaths: _overridePaths, overrides: _overrides }: ReviewConfig,\n { notes }: ReviewContent,\n { logContext, diffContext, releaseNotesContext, issuesContext, context, directories }: ReviewContext = {}\n): Promise<Prompt> => {\n const basePath = __dirname;\n\n // Build content items for the prompt\n const contentItems: ContentItem[] = [];\n const contextItems: ContentItem[] = [];\n\n if (notes) {\n contentItems.push({ content: notes, title: 'Review Notes' });\n }\n\n if (logContext) {\n contextItems.push({ content: logContext, title: 'Log Context' });\n }\n if (diffContext) {\n contextItems.push({ content: diffContext, title: 'Diff Context' });\n }\n if (releaseNotesContext) {\n contextItems.push({ content: releaseNotesContext, title: 'Release Notes Context' });\n }\n if (issuesContext) {\n contextItems.push({ content: issuesContext, title: 'Issues Context' });\n }\n if (context) {\n contextItems.push({ content: context, title: 'User Context' });\n }\n if (directories && directories.length > 0) {\n contextItems.push({ directories, title: 'Directories' });\n }\n\n return recipe(basePath)\n .persona({ path: 'personas/you.md' })\n .instructions({ path: 'instructions/review.md' })\n .overridePaths(_overridePaths ?? [])\n .overrides(_overrides ?? true)\n .content(...contentItems)\n .context(...contextItems)\n .cook();\n};\n\n","import type { ChatCompletionMessageParam } from 'openai/resources';\nimport { createCompletionWithRetry } from '../ai';\nimport type { ToolRegistry } from '../tools/registry';\nimport type { ToolResult } from '../tools/types';\n\nexport interface AgenticConfig {\n messages: ChatCompletionMessageParam[];\n tools: ToolRegistry;\n model?: string;\n maxIterations?: number;\n debug?: boolean;\n debugRequestFile?: string;\n debugResponseFile?: string;\n storage?: any;\n logger?: any;\n openaiReasoning?: 'low' | 'medium' | 'high';\n}\n\nexport interface ToolExecutionMetric {\n name: string;\n success: boolean;\n duration: number;\n error?: string;\n iteration: number;\n timestamp: string;\n}\n\nexport interface AgenticResult {\n finalMessage: string;\n iterations: number;\n toolCallsExecuted: number;\n conversationHistory: ChatCompletionMessageParam[];\n toolMetrics: ToolExecutionMetric[];\n}\n\n/**\n * Execute an agentic loop where the LLM can call tools to gather information\n */\nexport class AgenticExecutor {\n private logger?: any;\n private toolMetrics: ToolExecutionMetric[] = [];\n\n constructor(logger?: any) {\n this.logger = logger;\n }\n\n /**\n * Run the agentic loop\n */\n async run(config: AgenticConfig): Promise<AgenticResult> {\n const {\n messages: initialMessages,\n tools,\n model = 'gpt-4o',\n maxIterations = 10,\n debug = false,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning = false,\n } = config;\n\n const messages = [...initialMessages];\n let iterations = 0;\n let toolCallsExecuted = 0;\n\n this.log('Starting agentic loop', { maxIterations, toolCount: tools.count() });\n\n while (iterations < maxIterations) {\n iterations++;\n this.log(`Iteration ${iterations}/${maxIterations}`);\n\n // Call LLM with tools available\n const response = await createCompletionWithRetry(\n messages,\n {\n model,\n openaiReasoning: openaiReasoning || undefined,\n debug,\n debugRequestFile: debugRequestFile ? `${debugRequestFile}-iter${iterations}` : undefined,\n debugResponseFile: debugResponseFile ? `${debugResponseFile}-iter${iterations}` : undefined,\n storage,\n logger,\n tools: tools.toOpenAIFormat(),\n }\n );\n\n // When tools are enabled, response is the full message object\n const message = typeof response === 'string' ? { role: 'assistant', content: response } : response;\n\n // Check if there are tool calls in the response\n const toolCalls = message.tool_calls || [];\n\n if (toolCalls.length === 0) {\n // No tool calls, agent is done\n const finalContent = message.content || '';\n this.log('Agent completed without tool calls', { iterations, toolCallsExecuted });\n messages.push({\n role: 'assistant',\n content: finalContent,\n });\n return {\n finalMessage: finalContent,\n iterations,\n toolCallsExecuted,\n conversationHistory: messages,\n toolMetrics: this.toolMetrics,\n };\n }\n\n // Add assistant message with tool calls\n messages.push({\n role: 'assistant',\n content: message.content || null,\n tool_calls: toolCalls,\n });\n\n // Execute tool calls\n this.log(`Executing ${toolCalls.length} tool call(s)`);\n\n for (const toolCall of toolCalls) {\n const startTime = Date.now();\n const toolName = toolCall.function.name;\n\n try {\n this.log(`Executing tool: ${toolName}`, toolCall.function.arguments);\n\n // Log to info level so user can see tool execution in real-time\n if (this.logger?.info) {\n this.logger.info(`🔧 Running tool: ${toolName}`);\n }\n\n // Parse arguments\n const args = JSON.parse(toolCall.function.arguments);\n\n // Execute the tool\n const result = await tools.execute(toolName, args);\n\n const duration = Date.now() - startTime;\n\n // Add tool result to conversation\n messages.push({\n role: 'tool',\n tool_call_id: toolCall.id,\n content: this.formatToolResult({ id: toolCall.id, name: toolName, result }),\n });\n\n toolCallsExecuted++;\n\n // Track successful execution\n this.toolMetrics.push({\n name: toolName,\n success: true,\n duration,\n iteration: iterations,\n timestamp: new Date().toISOString(),\n });\n\n this.log(`Tool ${toolName} succeeded in ${duration}ms`);\n\n if (this.logger?.info) {\n this.logger.info(`✅ Tool ${toolName} completed (${duration}ms)`);\n }\n } catch (error: any) {\n const duration = Date.now() - startTime;\n const errorMessage = error.message || String(error);\n\n this.log(`Tool ${toolName} failed: ${errorMessage}`);\n\n // Track failed execution\n this.toolMetrics.push({\n name: toolName,\n success: false,\n duration,\n error: errorMessage,\n iteration: iterations,\n timestamp: new Date().toISOString(),\n });\n\n if (this.logger?.warn) {\n this.logger.warn(`❌ Tool ${toolName} failed: ${errorMessage}`);\n }\n\n // Add error result to conversation\n messages.push({\n role: 'tool',\n tool_call_id: toolCall.id,\n content: `Tool execution failed: ${errorMessage}`,\n });\n }\n }\n\n this.log(`Completed tool execution`, { toolCallsExecuted });\n }\n\n // Max iterations reached\n this.log('Max iterations reached, forcing completion', { iterations, toolCallsExecuted });\n\n // Make one final call without tools to get a synthesized response\n messages.push({\n role: 'user',\n content: 'Please provide your final analysis and commit message based on your investigation. Do not request any more tools.',\n });\n\n const finalResponse = await createCompletionWithRetry(\n messages,\n {\n model,\n openaiReasoning: openaiReasoning || undefined,\n debug,\n storage,\n logger,\n }\n );\n\n messages.push({\n role: 'assistant',\n content: finalResponse,\n });\n\n return {\n finalMessage: finalResponse,\n iterations,\n toolCallsExecuted,\n conversationHistory: messages,\n toolMetrics: this.toolMetrics,\n };\n }\n\n /**\n * Format tool result for inclusion in conversation\n */\n private formatToolResult(result: ToolResult): string {\n if (typeof result.result === 'string') {\n return result.result;\n }\n return JSON.stringify(result.result, null, 2);\n }\n\n /**\n * Log a message if logger is available\n */\n private log(message: string, data?: any): void {\n if (this.logger?.debug) {\n if (data) {\n this.logger.debug(`[AgenticExecutor] ${message}`, data);\n } else {\n this.logger.debug(`[AgenticExecutor] ${message}`);\n }\n }\n }\n}\n\n/**\n * Create and run an agentic executor\n */\nexport async function runAgentic(config: AgenticConfig): Promise<AgenticResult> {\n const executor = new AgenticExecutor(config.logger);\n return await executor.run(config);\n}\n\n","import type { Tool, OpenAITool, ToolContext } from './types';\n\n/**\n * Registry for managing tools available to agentic LLM interactions\n */\nexport class ToolRegistry {\n private tools: Map<string, Tool> = new Map();\n private context?: ToolContext;\n\n constructor(context?: ToolContext) {\n this.context = context;\n }\n\n /**\n * Register a tool in the registry\n */\n register(tool: Tool): void {\n if (this.tools.has(tool.name)) {\n throw new Error(`Tool with name \"${tool.name}\" is already registered`);\n }\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Register multiple tools at once\n */\n registerAll(tools: Tool[]): void {\n for (const tool of tools) {\n this.register(tool);\n }\n }\n\n /**\n * Get a tool by name\n */\n get(name: string): Tool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get all registered tools\n */\n getAll(): Tool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Check if a tool exists\n */\n has(name: string): boolean {\n return this.tools.has(name);\n }\n\n /**\n * Execute a tool by name with given parameters\n */\n async execute(name: string, params: any): Promise<any> {\n const tool = this.tools.get(name);\n if (!tool) {\n throw new Error(`Tool \"${name}\" not found in registry`);\n }\n\n try {\n return await tool.execute(params, this.context);\n } catch (error: any) {\n throw new Error(`Tool \"${name}\" execution failed: ${error.message}`);\n }\n }\n\n /**\n * Convert tools to OpenAI function calling format\n */\n toOpenAIFormat(): OpenAITool[] {\n return this.getAll().map(tool => ({\n type: 'function' as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n }\n\n /**\n * Get tool definitions (without execute functions) for serialization\n */\n getDefinitions(): Array<{ name: string; description: string; parameters: any }> {\n return this.getAll().map(tool => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n }\n\n /**\n * Clear all registered tools\n */\n clear(): void {\n this.tools.clear();\n }\n\n /**\n * Get count of registered tools\n */\n count(): number {\n return this.tools.size;\n }\n}\n\n/**\n * Create a new tool registry with optional context\n */\nexport function createToolRegistry(context?: ToolContext): ToolRegistry {\n return new ToolRegistry(context);\n}\n\n","import type { Tool, ToolContext } from './types';\nimport { run } from '@eldrforge/git-tools';\nimport * as path from 'path';\n\n/**\n * Create tools for commit message generation\n */\nexport function createCommitTools(): Tool[] {\n return [\n createGetFileHistoryTool(),\n createGetFileContentTool(),\n createSearchCodebaseTool(),\n createGetRelatedTestsTool(),\n createGetFileDependenciesTool(),\n createAnalyzeDiffSectionTool(),\n createGetRecentCommitsTool(),\n createGroupFilesByConcernTool(),\n ];\n}\n\n/**\n * Get git commit history for specific files\n */\nfunction createGetFileHistoryTool(): Tool {\n return {\n name: 'get_file_history',\n description: 'Get git commit history for one or more files to understand their evolution and past changes',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Array of file paths to get history for',\n items: { type: 'string', description: 'File path' },\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 10)',\n default: 10,\n },\n format: {\n type: 'string',\n description: 'Output format: \"summary\" for brief or \"detailed\" for full messages',\n enum: ['summary', 'detailed'],\n default: 'summary',\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; limit?: number; format?: 'summary' | 'detailed' }, context?: ToolContext) => {\n const { filePaths, limit = 10, format = 'summary' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n // Use proper shell quoting to avoid issues with parentheses in format strings\n const formatArg = format === 'detailed' ? '--format=\"%H%n%an (%ae)%n%ad%n%s%n%n%b%n---\"' : '--format=\"%h - %s (%an, %ar)\"';\n const fileArgs = filePaths.join(' ');\n const command = `git log ${formatArg} -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No history found for specified files';\n } catch (error: any) {\n throw new Error(`Failed to get file history: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get the full current content of a file\n */\nfunction createGetFileContentTool(): Tool {\n return {\n name: 'get_file_content',\n description: 'Get the complete current content of a file to understand context around changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the file',\n },\n includeLineNumbers: {\n type: 'boolean',\n description: 'Include line numbers in output (default: false)',\n default: false,\n },\n },\n required: ['filePath'],\n },\n execute: async (params: { filePath: string; includeLineNumbers?: boolean }, context?: ToolContext) => {\n const { filePath, includeLineNumbers = false } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n\n if (includeLineNumbers) {\n const lines = content.split('\\n');\n return lines.map((line: string, idx: number) => `${idx + 1}: ${line}`).join('\\n');\n }\n\n return content;\n } catch (error: any) {\n throw new Error(`Failed to read file: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Search for code patterns or identifiers across the codebase\n */\nfunction createSearchCodebaseTool(): Tool {\n return {\n name: 'search_codebase',\n description: 'Search for code patterns, function names, or text across the codebase using git grep',\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search pattern (can be plain text or regex)',\n },\n fileTypes: {\n type: 'array',\n description: 'Limit search to specific file extensions (e.g., [\"ts\", \"js\"])',\n items: { type: 'string', description: 'File extension' },\n },\n contextLines: {\n type: 'number',\n description: 'Number of context lines to show around matches (default: 2)',\n default: 2,\n },\n },\n required: ['query'],\n },\n execute: async (params: { query: string; fileTypes?: string[]; contextLines?: number }, context?: ToolContext) => {\n const { query, fileTypes, contextLines = 2 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n // Build command with proper git grep syntax: pattern comes BEFORE pathspec\n let command = `git grep -n -C ${contextLines} \"${query}\"`;\n\n if (fileTypes && fileTypes.length > 0) {\n // Use separate quoted patterns for each file type to avoid shell expansion issues\n const patterns = fileTypes.map(ext => `'*.${ext}'`).join(' ');\n command += ` -- ${patterns}`;\n }\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No matches found';\n } catch (error: any) {\n // git grep returns exit code 1 when no matches found\n if (error.message.includes('exit code 1')) {\n return 'No matches found';\n }\n throw new Error(`Search failed: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Find test files related to changed production files\n */\nfunction createGetRelatedTestsTool(): Tool {\n return {\n name: 'get_related_tests',\n description: 'Find test files related to production files to understand what the code is supposed to do',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Production file paths',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n const relatedTests: string[] = [];\n\n for (const filePath of filePaths) {\n // Common test patterns\n const patterns = [\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.test.$1'),\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.spec.$1'),\n filePath.replace('/src/', '/tests/').replace('/lib/', '/tests/'),\n path.join('tests', filePath),\n path.join('test', filePath),\n ];\n\n for (const pattern of patterns) {\n try {\n await storage.readFile(pattern, 'utf-8');\n relatedTests.push(pattern);\n } catch {\n // File doesn't exist, continue\n }\n }\n }\n\n if (relatedTests.length === 0) {\n return 'No related test files found';\n }\n\n return `Found related test files:\\n${relatedTests.join('\\n')}`;\n },\n };\n}\n\n/**\n * Understand what files import/depend on changed files\n */\nfunction createGetFileDependenciesTool(): Tool {\n return {\n name: 'get_file_dependencies',\n description: 'Find which files import or depend on the changed files to assess change impact',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to analyze dependencies for',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const results: string[] = [];\n\n for (const filePath of filePaths) {\n // Extract filename without extension for searching imports\n const fileName = path.basename(filePath, path.extname(filePath));\n\n // Search for imports of this file\n const searchPatterns = [\n `from.*['\"].*${fileName}`,\n `import.*['\"].*${fileName}`,\n `require\\\\(['\"].*${fileName}`,\n ];\n\n for (const pattern of searchPatterns) {\n try {\n const command = `git grep -l \"${pattern}\"`;\n const output = await run(command, { cwd: workingDir });\n if (output.stdout) {\n results.push(`Files importing ${filePath}:\\n${output.stdout}`);\n break; // Found matches, no need to try other patterns\n }\n } catch {\n // No matches or error, continue\n }\n }\n }\n\n return results.length > 0\n ? results.join('\\n\\n')\n : 'No files found that import the specified files';\n },\n };\n}\n\n/**\n * Get detailed analysis of specific lines in a diff\n */\nfunction createAnalyzeDiffSectionTool(): Tool {\n return {\n name: 'analyze_diff_section',\n description: 'Get expanded context around specific lines in a file to better understand changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'File containing the section to analyze',\n },\n startLine: {\n type: 'number',\n description: 'Starting line number',\n },\n endLine: {\n type: 'number',\n description: 'Ending line number',\n },\n contextLines: {\n type: 'number',\n description: 'Number of additional context lines to show before and after (default: 10)',\n default: 10,\n },\n },\n required: ['filePath', 'startLine', 'endLine'],\n },\n execute: async (params: { filePath: string; startLine: number; endLine: number; contextLines?: number }, context?: ToolContext) => {\n const { filePath, startLine, endLine, contextLines = 10 } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n\n const actualStart = Math.max(0, startLine - contextLines - 1);\n const actualEnd = Math.min(lines.length, endLine + contextLines);\n\n const section = lines.slice(actualStart, actualEnd)\n .map((line: string, idx: number) => `${actualStart + idx + 1}: ${line}`)\n .join('\\n');\n\n return `Lines ${actualStart + 1}-${actualEnd} from ${filePath}:\\n\\n${section}`;\n } catch (error: any) {\n throw new Error(`Failed to analyze diff section: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get recent commits that touched the same files\n */\nfunction createGetRecentCommitsTool(): Tool {\n return {\n name: 'get_recent_commits',\n description: 'Get recent commits that modified the same files to understand recent work in this area',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to check for recent commits',\n items: { type: 'string', description: 'File path' },\n },\n since: {\n type: 'string',\n description: 'Time period to look back (e.g., \"1 week ago\", \"2 days ago\")',\n default: '1 week ago',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 5)',\n default: 5,\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; since?: string; limit?: number }, context?: ToolContext) => {\n const { filePaths, since = '1 week ago', limit = 5 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const fileArgs = filePaths.join(' ');\n const command = `git log --format=\"%h - %s (%an, %ar)\" --since=\"${since}\" -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || `No commits found in the specified time period (${since})`;\n } catch (error: any) {\n throw new Error(`Failed to get recent commits: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Analyze changed files and suggest logical groupings\n */\nfunction createGroupFilesByConcernTool(): Tool {\n return {\n name: 'group_files_by_concern',\n description: 'Analyze changed files and suggest logical groupings that might represent separate commits',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'All changed files to analyze',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }) => {\n const { filePaths } = params;\n\n // Group files by directory and type\n const groups: Record<string, string[]> = {};\n\n for (const filePath of filePaths) {\n const dir = path.dirname(filePath);\n const ext = path.extname(filePath);\n const basename = path.basename(filePath, ext);\n\n // Determine category\n let category = 'other';\n\n if (basename.includes('.test') || basename.includes('.spec') || dir.includes('test')) {\n category = 'tests';\n } else if (filePath.includes('package.json') || filePath.includes('package-lock.json')) {\n category = 'dependencies';\n } else if (ext === '.md' || basename === 'README') {\n category = 'documentation';\n } else if (dir.includes('src') || dir.includes('lib')) {\n // Group by module/subdirectory\n category = `source:${dir.split('/').slice(0, 3).join('/')}`;\n }\n\n if (!groups[category]) {\n groups[category] = [];\n }\n groups[category].push(filePath);\n }\n\n // Format the groupings\n const output = Object.entries(groups)\n .map(([category, files]) => {\n return `${category} (${files.length} files):\\n${files.map(f => ` - ${f}`).join('\\n')}`;\n })\n .join('\\n\\n');\n\n const groupCount = Object.keys(groups).length;\n const suggestion = groupCount > 1\n ? `\\n\\nSuggestion: These ${groupCount} groups might be better as separate commits if they represent different concerns.`\n : '\\n\\nSuggestion: All files appear to be related and should be in a single commit.';\n\n return output + suggestion;\n },\n };\n}\n\n","import type { ChatCompletionMessageParam } from 'openai/resources';\nimport { runAgentic, type AgenticConfig, type ToolExecutionMetric } from './executor';\nimport { createToolRegistry } from '../tools/registry';\nimport { createCommitTools } from '../tools/commit-tools';\nimport type { StorageAdapter, Logger } from '../types';\n\nexport interface AgenticCommitConfig {\n changedFiles: string[];\n diffContent: string;\n userDirection?: string;\n logContext?: string;\n model?: string;\n maxIterations?: number;\n debug?: boolean;\n debugRequestFile?: string;\n debugResponseFile?: string;\n storage?: StorageAdapter;\n logger?: Logger;\n openaiReasoning?: 'low' | 'medium' | 'high';\n}\n\nexport interface AgenticCommitResult {\n commitMessage: string;\n iterations: number;\n toolCallsExecuted: number;\n suggestedSplits: Array<{\n files: string[];\n message: string;\n rationale: string;\n }>;\n conversationHistory: ChatCompletionMessageParam[];\n toolMetrics: ToolExecutionMetric[];\n}\n\n/**\n * Run agentic commit message generation\n */\nexport async function runAgenticCommit(config: AgenticCommitConfig): Promise<AgenticCommitResult> {\n const {\n changedFiles,\n diffContent,\n userDirection,\n logContext,\n model = 'gpt-4o',\n maxIterations = 10,\n debug = false,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n } = config;\n\n // Create tool registry with context\n const toolRegistry = createToolRegistry({\n workingDirectory: process.cwd(),\n storage,\n logger,\n });\n\n // Register commit-specific tools\n const tools = createCommitTools();\n toolRegistry.registerAll(tools);\n\n // Build initial system prompt\n const systemPrompt = buildSystemPrompt();\n\n // Build initial user message\n const userMessage = buildUserMessage(changedFiles, diffContent, userDirection, logContext);\n\n // Prepare messages for agentic loop\n const messages: ChatCompletionMessageParam[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userMessage },\n ];\n\n // Run agentic loop\n const agenticConfig: AgenticConfig = {\n messages,\n tools: toolRegistry,\n model,\n maxIterations,\n debug,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n };\n\n const result = await runAgentic(agenticConfig);\n\n // Parse the final message to extract commit message and suggested splits\n const parsed = parseAgenticResult(result.finalMessage);\n\n return {\n commitMessage: parsed.commitMessage,\n iterations: result.iterations,\n toolCallsExecuted: result.toolCallsExecuted,\n suggestedSplits: parsed.suggestedSplits,\n conversationHistory: result.conversationHistory,\n toolMetrics: result.toolMetrics,\n };\n}\n\n/**\n * Build the system prompt for agentic commit generation\n */\nfunction buildSystemPrompt(): string {\n return `You are an expert software engineer tasked with generating meaningful commit messages.\n\nYou have access to tools that let you investigate changes in detail:\n- get_file_history: View commit history for files\n- get_file_content: Read full file contents\n- search_codebase: Search for patterns across the codebase\n- get_related_tests: Find test files related to changes\n- get_file_dependencies: Understand file dependencies and imports\n- analyze_diff_section: Get expanded context around specific changes\n- get_recent_commits: See recent commits to the same files\n- group_files_by_concern: Suggest logical groupings of changed files\n\nYour process should be:\n1. Analyze the changed files and diff to understand the scope\n2. Use tools to investigate specific changes that need more context\n3. Identify if changes represent one cohesive commit or multiple logical commits\n4. Generate a commit message (or multiple if splits suggested) that accurately describes changes\n\nGuidelines:\n- Use tools strategically - don't call every tool on every file\n- Look at test changes to understand intent\n- Check recent history to avoid redundant messages\n- Consider suggesting split commits for unrelated changes\n- Synthesize findings into clear, informative commit messages\n- Follow conventional commit format when appropriate (feat:, fix:, refactor:, etc.)\n\nOutput format:\nWhen you're ready to provide the final commit message, format it as:\n\nCOMMIT_MESSAGE:\n[Your generated commit message here]\n\nIf you recommend splitting into multiple commits, also include:\n\nSUGGESTED_SPLITS:\nSplit 1:\nFiles: [list of files]\nRationale: [why these belong together]\nMessage: [commit message for this split]\n\nSplit 2:\n...\n\nIf changes should remain as one commit, do not include SUGGESTED_SPLITS section.`;\n}\n\n/**\n * Build the initial user message\n */\nfunction buildUserMessage(\n changedFiles: string[],\n diffContent: string,\n userDirection?: string,\n logContext?: string\n): string {\n let message = `I have staged changes that need a commit message.\n\nChanged files (${changedFiles.length}):\n${changedFiles.map(f => ` - ${f}`).join('\\n')}\n\nDiff:\n${diffContent}`;\n\n if (userDirection) {\n message += `\\n\\nUser direction: ${userDirection}`;\n }\n\n if (logContext) {\n message += `\\n\\nRecent commit history for context:\n${logContext}`;\n }\n\n message += `\\n\\nPlease investigate these changes and generate an appropriate commit message.\nUse the available tools to gather additional context as needed.\nIf these changes should be split into multiple commits, suggest the groupings.`;\n\n return message;\n}\n\n/**\n * Parse the agentic result to extract commit message and splits\n */\nfunction parseAgenticResult(finalMessage: string): {\n commitMessage: string;\n suggestedSplits: Array<{ files: string[]; message: string; rationale: string }>;\n} {\n // Look for COMMIT_MESSAGE: marker\n const commitMatch = finalMessage.match(/COMMIT_MESSAGE:\\s*\\n([\\s\\S]*?)(?=\\n\\nSUGGESTED_SPLITS:|$)/);\n const commitMessage = commitMatch ? commitMatch[1].trim() : finalMessage.trim();\n\n // Look for SUGGESTED_SPLITS: section\n const suggestedSplits: Array<{ files: string[]; message: string; rationale: string }> = [];\n const splitsMatch = finalMessage.match(/SUGGESTED_SPLITS:\\s*\\n([\\s\\S]*)/);\n\n if (splitsMatch) {\n const splitsText = splitsMatch[1];\n // Parse each split\n const splitRegex = /Split \\d+:\\s*\\nFiles: ([\\s\\S]*?)\\nRationale: ([\\s\\S]*?)\\nMessage: ([\\s\\S]*?)(?=\\n\\nSplit \\d+:|$)/g;\n let match;\n\n while ((match = splitRegex.exec(splitsText)) !== null) {\n const filesText = match[1].trim();\n const files = filesText\n .split('\\n')\n .map(line => line.trim().replace(/^[-*]\\s*/, ''))\n .filter(line => line.length > 0);\n\n suggestedSplits.push({\n files,\n rationale: match[2].trim(),\n message: match[3].trim(),\n });\n }\n }\n\n return { commitMessage, suggestedSplits };\n}\n\n","import type { Tool, ToolContext } from './types';\nimport { run } from '@eldrforge/git-tools';\nimport * as path from 'path';\n\n/**\n * Create tools for release notes generation\n */\nexport function createReleaseTools(): Tool[] {\n return [\n createGetFileHistoryTool(),\n createGetFileContentTool(),\n createSearchCodebaseTool(),\n createGetRelatedTestsTool(),\n createGetFileDependenciesTool(),\n createAnalyzeDiffSectionTool(),\n createGetRecentCommitsTool(),\n createGroupFilesByConcernTool(),\n createGetTagHistoryTool(),\n createComparePreviousReleaseTool(),\n createGetReleaseStatsTool(),\n createGetBreakingChangesTool(),\n createAnalyzeCommitPatternsTool(),\n ];\n}\n\n/**\n * Get git commit history for specific files\n */\nfunction createGetFileHistoryTool(): Tool {\n return {\n name: 'get_file_history',\n description: 'Get git commit history for one or more files to understand their evolution and past changes',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Array of file paths to get history for',\n items: { type: 'string', description: 'File path' },\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 10)',\n default: 10,\n },\n format: {\n type: 'string',\n description: 'Output format: \"summary\" for brief or \"detailed\" for full messages',\n enum: ['summary', 'detailed'],\n default: 'summary',\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; limit?: number; format?: 'summary' | 'detailed' }, context?: ToolContext) => {\n const { filePaths, limit = 10, format = 'summary' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n // Use proper shell quoting to avoid issues with parentheses in format strings\n const formatArg = format === 'detailed' ? '--format=\"%H%n%an (%ae)%n%ad%n%s%n%n%b%n---\"' : '--format=\"%h - %s (%an, %ar)\"';\n const fileArgs = filePaths.join(' ');\n const command = `git log ${formatArg} -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No history found for specified files';\n } catch (error: any) {\n throw new Error(`Failed to get file history: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get the full current content of a file\n */\nfunction createGetFileContentTool(): Tool {\n return {\n name: 'get_file_content',\n description: 'Get the complete current content of a file to understand context around changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the file',\n },\n includeLineNumbers: {\n type: 'boolean',\n description: 'Include line numbers in output (default: false)',\n default: false,\n },\n },\n required: ['filePath'],\n },\n execute: async (params: { filePath: string; includeLineNumbers?: boolean }, context?: ToolContext) => {\n const { filePath, includeLineNumbers = false } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n\n if (includeLineNumbers) {\n const lines = content.split('\\n');\n return lines.map((line: string, idx: number) => `${idx + 1}: ${line}`).join('\\n');\n }\n\n return content;\n } catch (error: any) {\n throw new Error(`Failed to read file: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Search for code patterns or identifiers across the codebase\n */\nfunction createSearchCodebaseTool(): Tool {\n return {\n name: 'search_codebase',\n description: 'Search for code patterns, function names, or text across the codebase using git grep',\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search pattern (can be plain text or regex)',\n },\n fileTypes: {\n type: 'array',\n description: 'Limit search to specific file extensions (e.g., [\"ts\", \"js\"])',\n items: { type: 'string', description: 'File extension' },\n },\n contextLines: {\n type: 'number',\n description: 'Number of context lines to show around matches (default: 2)',\n default: 2,\n },\n },\n required: ['query'],\n },\n execute: async (params: { query: string; fileTypes?: string[]; contextLines?: number }, context?: ToolContext) => {\n const { query, fileTypes, contextLines = 2 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n // Build command with proper git grep syntax: pattern comes BEFORE pathspec\n let command = `git grep -n -C ${contextLines} \"${query}\"`;\n\n if (fileTypes && fileTypes.length > 0) {\n // Use separate quoted patterns for each file type to avoid shell expansion issues\n const patterns = fileTypes.map(ext => `'*.${ext}'`).join(' ');\n command += ` -- ${patterns}`;\n }\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || 'No matches found';\n } catch (error: any) {\n // git grep returns exit code 1 when no matches found\n if (error.message.includes('exit code 1')) {\n return 'No matches found';\n }\n throw new Error(`Search failed: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Find test files related to changed production files\n */\nfunction createGetRelatedTestsTool(): Tool {\n return {\n name: 'get_related_tests',\n description: 'Find test files related to production files to understand what the code is supposed to do',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Production file paths',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n const relatedTests: string[] = [];\n\n for (const filePath of filePaths) {\n // Common test patterns\n const patterns = [\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.test.$1'),\n filePath.replace(/\\.(ts|js|tsx|jsx)$/, '.spec.$1'),\n filePath.replace('/src/', '/tests/').replace('/lib/', '/tests/'),\n path.join('tests', filePath),\n path.join('test', filePath),\n ];\n\n for (const pattern of patterns) {\n try {\n await storage.readFile(pattern, 'utf-8');\n relatedTests.push(pattern);\n } catch {\n // File doesn't exist, continue\n }\n }\n }\n\n if (relatedTests.length === 0) {\n return 'No related test files found';\n }\n\n return `Found related test files:\\n${relatedTests.join('\\n')}`;\n },\n };\n}\n\n/**\n * Understand what files import/depend on changed files\n */\nfunction createGetFileDependenciesTool(): Tool {\n return {\n name: 'get_file_dependencies',\n description: 'Find which files import or depend on the changed files to assess change impact',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to analyze dependencies for',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }, context?: ToolContext) => {\n const { filePaths } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const results: string[] = [];\n\n for (const filePath of filePaths) {\n // Extract filename without extension for searching imports\n const fileName = path.basename(filePath, path.extname(filePath));\n\n // Search for imports of this file\n const searchPatterns = [\n `from.*['\"].*${fileName}`,\n `import.*['\"].*${fileName}`,\n `require\\\\(['\"].*${fileName}`,\n ];\n\n for (const pattern of searchPatterns) {\n try {\n const command = `git grep -l \"${pattern}\"`;\n const output = await run(command, { cwd: workingDir });\n if (output.stdout) {\n results.push(`Files importing ${filePath}:\\n${output.stdout}`);\n break; // Found matches, no need to try other patterns\n }\n } catch {\n // No matches or error, continue\n }\n }\n }\n\n return results.length > 0\n ? results.join('\\n\\n')\n : 'No files found that import the specified files';\n },\n };\n}\n\n/**\n * Get detailed analysis of specific lines in a diff\n */\nfunction createAnalyzeDiffSectionTool(): Tool {\n return {\n name: 'analyze_diff_section',\n description: 'Get expanded context around specific lines in a file to better understand changes',\n parameters: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'File containing the section to analyze',\n },\n startLine: {\n type: 'number',\n description: 'Starting line number',\n },\n endLine: {\n type: 'number',\n description: 'Ending line number',\n },\n contextLines: {\n type: 'number',\n description: 'Number of additional context lines to show before and after (default: 10)',\n default: 10,\n },\n },\n required: ['filePath', 'startLine', 'endLine'],\n },\n execute: async (params: { filePath: string; startLine: number; endLine: number; contextLines?: number }, context?: ToolContext) => {\n const { filePath, startLine, endLine, contextLines = 10 } = params;\n const storage = context?.storage;\n\n if (!storage) {\n throw new Error('Storage adapter not available in context');\n }\n\n try {\n const content = await storage.readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n\n const actualStart = Math.max(0, startLine - contextLines - 1);\n const actualEnd = Math.min(lines.length, endLine + contextLines);\n\n const section = lines.slice(actualStart, actualEnd)\n .map((line: string, idx: number) => `${actualStart + idx + 1}: ${line}`)\n .join('\\n');\n\n return `Lines ${actualStart + 1}-${actualEnd} from ${filePath}:\\n\\n${section}`;\n } catch (error: any) {\n throw new Error(`Failed to analyze diff section: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get recent commits that touched the same files\n */\nfunction createGetRecentCommitsTool(): Tool {\n return {\n name: 'get_recent_commits',\n description: 'Get recent commits that modified the same files to understand recent work in this area',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'Files to check for recent commits',\n items: { type: 'string', description: 'File path' },\n },\n since: {\n type: 'string',\n description: 'Time period to look back (e.g., \"1 week ago\", \"2 days ago\")',\n default: '1 week ago',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of commits to return (default: 5)',\n default: 5,\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[]; since?: string; limit?: number }, context?: ToolContext) => {\n const { filePaths, since = '1 week ago', limit = 5 } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const fileArgs = filePaths.join(' ');\n const command = `git log --format=\"%h - %s (%an, %ar)\" --since=\"${since}\" -n ${limit} -- ${fileArgs}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n return output.stdout || `No commits found in the specified time period (${since})`;\n } catch (error: any) {\n throw new Error(`Failed to get recent commits: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Analyze changed files and suggest logical groupings\n */\nfunction createGroupFilesByConcernTool(): Tool {\n return {\n name: 'group_files_by_concern',\n description: 'Analyze changed files and suggest logical groupings that might represent separate concerns',\n parameters: {\n type: 'object',\n properties: {\n filePaths: {\n type: 'array',\n description: 'All changed files to analyze',\n items: { type: 'string', description: 'File path' },\n },\n },\n required: ['filePaths'],\n },\n execute: async (params: { filePaths: string[] }) => {\n const { filePaths } = params;\n\n // Group files by directory and type\n const groups: Record<string, string[]> = {};\n\n for (const filePath of filePaths) {\n const dir = path.dirname(filePath);\n const ext = path.extname(filePath);\n const basename = path.basename(filePath, ext);\n\n // Determine category\n let category = 'other';\n\n if (basename.includes('.test') || basename.includes('.spec') || dir.includes('test')) {\n category = 'tests';\n } else if (filePath.includes('package.json') || filePath.includes('package-lock.json')) {\n category = 'dependencies';\n } else if (ext === '.md' || basename === 'README') {\n category = 'documentation';\n } else if (dir.includes('src') || dir.includes('lib')) {\n // Group by module/subdirectory\n category = `source:${dir.split('/').slice(0, 3).join('/')}`;\n }\n\n if (!groups[category]) {\n groups[category] = [];\n }\n groups[category].push(filePath);\n }\n\n // Format the groupings\n const output = Object.entries(groups)\n .map(([category, files]) => {\n return `${category} (${files.length} files):\\n${files.map(f => ` - ${f}`).join('\\n')}`;\n })\n .join('\\n\\n');\n\n const groupCount = Object.keys(groups).length;\n const suggestion = groupCount > 1\n ? `\\n\\nSuggestion: These ${groupCount} groups represent different concerns in the release.`\n : '\\n\\nSuggestion: All files appear to be related to a single concern.';\n\n return output + suggestion;\n },\n };\n}\n\n/**\n * Get history of previous release tags\n */\nfunction createGetTagHistoryTool(): Tool {\n return {\n name: 'get_tag_history',\n description: 'Get the history of previous release tags to understand release patterns and versioning',\n parameters: {\n type: 'object',\n properties: {\n limit: {\n type: 'number',\n description: 'Number of recent tags to retrieve (default: 10)',\n default: 10,\n },\n pattern: {\n type: 'string',\n description: 'Filter tags by pattern (e.g., \"v*\" for version tags)',\n },\n },\n },\n execute: async (params: { limit?: number; pattern?: string }, context?: ToolContext) => {\n const { limit = 10, pattern } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n let command = 'git tag --sort=-creatordate';\n if (pattern) {\n command += ` -l \"${pattern}\"`;\n }\n command += ` | head -n ${limit}`;\n\n try {\n const output = await run(command, { cwd: workingDir });\n if (!output.stdout) {\n return 'No tags found in repository';\n }\n\n // Get detailed info for each tag\n const tags = output.stdout.trim().split('\\n');\n const detailedInfo: string[] = [];\n\n for (const tag of tags) {\n try {\n const tagInfo = await run(`git show --quiet --format=\"%ci - %s\" ${tag}`, { cwd: workingDir });\n detailedInfo.push(`${tag}: ${tagInfo.stdout.trim()}`);\n } catch {\n detailedInfo.push(`${tag}: (no info available)`);\n }\n }\n\n return `Recent release tags:\\n${detailedInfo.join('\\n')}`;\n } catch (error: any) {\n throw new Error(`Failed to get tag history: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Compare this release with a previous release\n */\nfunction createComparePreviousReleaseTool(): Tool {\n return {\n name: 'compare_previous_release',\n description: 'Compare this release with a previous release to understand what changed between versions',\n parameters: {\n type: 'object',\n properties: {\n previousTag: {\n type: 'string',\n description: 'Previous release tag to compare against',\n },\n currentRef: {\n type: 'string',\n description: 'Current reference (default: HEAD)',\n default: 'HEAD',\n },\n statsOnly: {\n type: 'boolean',\n description: 'Return only statistics, not full diff (default: true)',\n default: true,\n },\n },\n required: ['previousTag'],\n },\n execute: async (params: { previousTag: string; currentRef?: string; statsOnly?: boolean }, context?: ToolContext) => {\n const { previousTag, currentRef = 'HEAD', statsOnly = true } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n try {\n // Get commit count\n const commitCountCmd = `git rev-list --count ${previousTag}..${currentRef}`;\n const commitCount = await run(commitCountCmd, { cwd: workingDir });\n\n // Get file change stats\n const statsCmd = `git diff --stat ${previousTag}..${currentRef}`;\n const stats = await run(statsCmd, { cwd: workingDir });\n\n let result = `Comparison between ${previousTag} and ${currentRef}:\\n\\n`;\n result += `Commits: ${commitCount.stdout.trim()}\\n\\n`;\n result += `File changes:\\n${stats.stdout}`;\n\n if (!statsOnly) {\n // Get short log of commits\n const logCmd = `git log --oneline ${previousTag}..${currentRef}`;\n const log = await run(logCmd, { cwd: workingDir });\n result += `\\n\\nCommit summary:\\n${log.stdout}`;\n }\n\n return result;\n } catch (error: any) {\n throw new Error(`Failed to compare releases: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Get statistics about the release\n */\nfunction createGetReleaseStatsTool(): Tool {\n return {\n name: 'get_release_stats',\n description: 'Get comprehensive statistics about the release including contributors, file changes, and commit patterns',\n parameters: {\n type: 'object',\n properties: {\n fromRef: {\n type: 'string',\n description: 'Starting reference for the release range',\n },\n toRef: {\n type: 'string',\n description: 'Ending reference for the release range (default: HEAD)',\n default: 'HEAD',\n },\n },\n required: ['fromRef'],\n },\n execute: async (params: { fromRef: string; toRef?: string }, context?: ToolContext) => {\n const { fromRef, toRef = 'HEAD' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n try {\n const results: string[] = [];\n\n // Commit count\n const commitCount = await run(`git rev-list --count ${fromRef}..${toRef}`, { cwd: workingDir });\n results.push(`Total commits: ${commitCount.stdout.trim()}`);\n\n // Contributors\n const contributors = await run(\n `git shortlog -sn ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n results.push(`\\nContributors:\\n${contributors.stdout}`);\n\n // File change summary\n const fileStats = await run(\n `git diff --shortstat ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n results.push(`\\nFile changes: ${fileStats.stdout.trim()}`);\n\n // Most changed files\n const topFiles = await run(\n `git diff --stat ${fromRef}..${toRef} | sort -k2 -rn | head -n 10`,\n { cwd: workingDir }\n );\n results.push(`\\nTop 10 most changed files:\\n${topFiles.stdout}`);\n\n return results.join('\\n');\n } catch (error: any) {\n throw new Error(`Failed to get release stats: ${error.message}`);\n }\n },\n };\n}\n\n/**\n * Identify potential breaking changes\n */\nfunction createGetBreakingChangesTool(): Tool {\n return {\n name: 'get_breaking_changes',\n description: 'Search for potential breaking changes by looking for specific patterns in commits and diffs',\n parameters: {\n type: 'object',\n properties: {\n fromRef: {\n type: 'string',\n description: 'Starting reference for the release range',\n },\n toRef: {\n type: 'string',\n description: 'Ending reference for the release range (default: HEAD)',\n default: 'HEAD',\n },\n },\n required: ['fromRef'],\n },\n execute: async (params: { fromRef: string; toRef?: string }, context?: ToolContext) => {\n const { fromRef, toRef = 'HEAD' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n const results: string[] = [];\n\n try {\n // Search for BREAKING CHANGE in commit messages\n const breakingCommits = await run(\n `git log --grep=\"BREAKING CHANGE\" --oneline ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n if (breakingCommits.stdout) {\n results.push(`Commits with BREAKING CHANGE:\\n${breakingCommits.stdout}`);\n }\n\n // Search for removed exports\n const removedExports = await run(\n `git diff ${fromRef}..${toRef} | grep \"^-export\"`,\n { cwd: workingDir }\n );\n if (removedExports.stdout) {\n results.push(`\\nRemoved exports (potential breaking):\\n${removedExports.stdout}`);\n }\n\n // Search for changed function signatures\n const changedSignatures = await run(\n `git diff ${fromRef}..${toRef} | grep -E \"^[-+].*function|^[-+].*const.*=.*=>|^[-+].*interface|^[-+].*type.*=\"`,\n { cwd: workingDir }\n );\n if (changedSignatures.stdout) {\n results.push(`\\nChanged function/type signatures (review for breaking changes):\\n${changedSignatures.stdout.split('\\n').slice(0, 20).join('\\n')}`);\n }\n\n if (results.length === 0) {\n return 'No obvious breaking changes detected. Manual review recommended for API changes.';\n }\n\n return results.join('\\n\\n');\n } catch {\n // Some commands may fail if no matches found\n if (results.length > 0) {\n return results.join('\\n\\n');\n }\n return 'No obvious breaking changes detected. Manual review recommended for API changes.';\n }\n },\n };\n}\n\n/**\n * Analyze commit patterns to identify themes\n */\nfunction createAnalyzeCommitPatternsTool(): Tool {\n return {\n name: 'analyze_commit_patterns',\n description: 'Analyze commit messages to identify patterns and themes in the release',\n parameters: {\n type: 'object',\n properties: {\n fromRef: {\n type: 'string',\n description: 'Starting reference for the release range',\n },\n toRef: {\n type: 'string',\n description: 'Ending reference for the release range (default: HEAD)',\n default: 'HEAD',\n },\n },\n required: ['fromRef'],\n },\n execute: async (params: { fromRef: string; toRef?: string }, context?: ToolContext) => {\n const { fromRef, toRef = 'HEAD' } = params;\n const workingDir = context?.workingDirectory || process.cwd();\n\n try {\n const results: string[] = [];\n\n // Get all commit messages\n const commits = await run(\n `git log --format=\"%s\" ${fromRef}..${toRef}`,\n { cwd: workingDir }\n );\n\n const messages = commits.stdout.trim().split('\\n');\n\n // Count conventional commit types\n const types: Record<string, number> = {};\n const keywords: Record<string, number> = {};\n\n for (const msg of messages) {\n // Check for conventional commit format\n const conventionalMatch = msg.match(/^(\\w+)(\\(.+?\\))?:/);\n if (conventionalMatch) {\n const type = conventionalMatch[1];\n types[type] = (types[type] || 0) + 1;\n }\n\n // Extract keywords (words longer than 4 chars)\n const words = msg.toLowerCase().match(/\\b\\w{5,}\\b/g) || [];\n for (const word of words) {\n keywords[word] = (keywords[word] || 0) + 1;\n }\n }\n\n // Format commit types\n if (Object.keys(types).length > 0) {\n results.push('Commit types:');\n const sortedTypes = Object.entries(types)\n .sort((a, b) => b[1] - a[1])\n .map(([type, count]) => ` ${type}: ${count}`)\n .join('\\n');\n results.push(sortedTypes);\n }\n\n // Format top keywords\n const topKeywords = Object.entries(keywords)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 15)\n .map(([word, count]) => ` ${word}: ${count}`)\n .join('\\n');\n\n if (topKeywords) {\n results.push('\\nTop keywords in commits:');\n results.push(topKeywords);\n }\n\n return results.join('\\n');\n } catch (error: any) {\n throw new Error(`Failed to analyze commit patterns: ${error.message}`);\n }\n },\n };\n}\n\n","import type { ChatCompletionMessageParam } from 'openai/resources';\nimport { runAgentic, type AgenticConfig, type ToolExecutionMetric } from './executor';\nimport { createToolRegistry } from '../tools/registry';\nimport { createReleaseTools } from '../tools/release-tools';\nimport type { StorageAdapter, Logger } from '../types';\n\nexport interface AgenticReleaseConfig {\n fromRef: string;\n toRef: string;\n logContent: string;\n diffContent: string;\n milestoneIssues?: string;\n releaseFocus?: string;\n userContext?: string;\n model?: string;\n maxIterations?: number;\n debug?: boolean;\n debugRequestFile?: string;\n debugResponseFile?: string;\n storage?: StorageAdapter;\n logger?: Logger;\n openaiReasoning?: 'low' | 'medium' | 'high';\n}\n\nexport interface AgenticReleaseResult {\n releaseNotes: {\n title: string;\n body: string;\n };\n iterations: number;\n toolCallsExecuted: number;\n conversationHistory: ChatCompletionMessageParam[];\n toolMetrics: ToolExecutionMetric[];\n}\n\n/**\n * Run agentic release notes generation\n */\nexport async function runAgenticRelease(config: AgenticReleaseConfig): Promise<AgenticReleaseResult> {\n const {\n fromRef,\n toRef,\n logContent,\n diffContent,\n milestoneIssues,\n releaseFocus,\n userContext,\n model = 'gpt-4o',\n maxIterations = 30,\n debug = false,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n } = config;\n\n // Create tool registry with context\n const toolRegistry = createToolRegistry({\n workingDirectory: process.cwd(),\n storage,\n logger,\n });\n\n // Register release-specific tools\n const tools = createReleaseTools();\n toolRegistry.registerAll(tools);\n\n // Build initial system prompt\n const systemPrompt = buildSystemPrompt();\n\n // Build initial user message\n const userMessage = buildUserMessage({\n fromRef,\n toRef,\n logContent,\n diffContent,\n milestoneIssues,\n releaseFocus,\n userContext,\n });\n\n // Prepare messages for agentic loop\n const messages: ChatCompletionMessageParam[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userMessage },\n ];\n\n // Run agentic loop\n const agenticConfig: AgenticConfig = {\n messages,\n tools: toolRegistry,\n model,\n maxIterations,\n debug,\n debugRequestFile,\n debugResponseFile,\n storage,\n logger,\n openaiReasoning,\n };\n\n const result = await runAgentic(agenticConfig);\n\n // Parse the final message to extract release notes\n const parsed = parseAgenticResult(result.finalMessage);\n\n return {\n releaseNotes: parsed.releaseNotes,\n iterations: result.iterations,\n toolCallsExecuted: result.toolCallsExecuted,\n conversationHistory: result.conversationHistory,\n toolMetrics: result.toolMetrics,\n };\n}\n\n/**\n * Build the system prompt for agentic release notes generation\n */\nfunction buildSystemPrompt(): string {\n return `You are an expert software engineer and technical writer tasked with generating comprehensive, thoughtful release notes.\n\nYou have access to tools that let you investigate the release in detail:\n- get_file_history: View commit history for specific files\n- get_file_content: Read full file contents to understand context\n- search_codebase: Search for patterns across the codebase\n- get_related_tests: Find test files to understand functionality\n- get_file_dependencies: Understand file dependencies and impact\n- analyze_diff_section: Get expanded context around specific changes\n- get_recent_commits: See recent commits to the same files\n- group_files_by_concern: Identify logical groupings of changes\n- get_tag_history: View previous release tags and patterns\n- compare_previous_release: Compare with previous releases\n- get_release_stats: Get comprehensive statistics about the release\n- get_breaking_changes: Identify potential breaking changes\n- analyze_commit_patterns: Identify themes and patterns in commits\n\nYour process should be:\n1. Analyze the commit log and diff to understand the overall scope of changes\n2. Use tools strategically to investigate significant changes that need more context\n3. Look at previous releases to understand how this release fits into the project's evolution\n4. Identify patterns, themes, and connections between changes\n5. Check for breaking changes and significant architectural shifts\n6. Understand the \"why\" behind changes by examining commit messages, issues, and code\n7. Synthesize findings into comprehensive, thoughtful release notes\n\nGuidelines:\n- Use tools strategically - focus on understanding significant changes\n- Look at test changes to understand intent and functionality\n- Check previous releases to provide context and compare scope\n- Identify patterns and themes across multiple commits\n- Consider the audience and what context they need\n- Be thorough and analytical, especially for large releases\n- Follow the release notes format and best practices provided\n\nOutput format:\nWhen you're ready to provide the final release notes, format them as JSON:\n\nRELEASE_NOTES:\n{\n \"title\": \"A concise, single-line title capturing the most significant changes\",\n \"body\": \"The detailed release notes in Markdown format, following best practices for structure, depth, and analysis\"\n}\n\nThe release notes should:\n- Demonstrate genuine understanding of the changes\n- Provide context and explain implications\n- Connect related changes to reveal patterns\n- Be substantial and analytical, not formulaic\n- Sound like they were written by a human who studied the changes\n- Be grounded in actual commits and issues (no hallucinations)`;\n}\n\n/**\n * Build the initial user message\n */\nfunction buildUserMessage(params: {\n fromRef: string;\n toRef: string;\n logContent: string;\n diffContent: string;\n milestoneIssues?: string;\n releaseFocus?: string;\n userContext?: string;\n}): string {\n const { fromRef, toRef, logContent, diffContent, milestoneIssues, releaseFocus, userContext } = params;\n\n let message = `I need comprehensive release notes for changes from ${fromRef} to ${toRef}.\n\n## Commit Log\n${logContent}\n\n## Diff Summary\n${diffContent}`;\n\n if (milestoneIssues) {\n message += `\\n\\n## Resolved Issues from Milestone\n${milestoneIssues}`;\n }\n\n if (releaseFocus) {\n message += `\\n\\n## Release Focus\n${releaseFocus}\n\nThis is the PRIMARY GUIDE for how to frame and structure the release notes. Use this to determine emphasis and narrative.`;\n }\n\n if (userContext) {\n message += `\\n\\n## Additional Context\n${userContext}`;\n }\n\n message += `\\n\\nPlease investigate these changes thoroughly and generate comprehensive release notes that:\n1. Demonstrate deep understanding of what changed and why\n2. Provide context about how changes relate to each other\n3. Explain implications for users and developers\n4. Connect this release to previous releases and project evolution\n5. Identify any breaking changes or significant architectural shifts\n6. Follow best practices for technical writing and release notes\n\nUse the available tools to gather additional context as needed. Take your time to understand the changes deeply before writing the release notes.`;\n\n return message;\n}\n\n/**\n * Parse the agentic result to extract release notes\n */\nfunction parseAgenticResult(finalMessage: string): {\n releaseNotes: { title: string; body: string };\n} {\n // Look for RELEASE_NOTES: marker with JSON\n const jsonMatch = finalMessage.match(/RELEASE_NOTES:\\s*\\n([\\s\\S]*)/);\n\n if (jsonMatch) {\n try {\n const jsonStr = jsonMatch[1].trim();\n // Try to parse the JSON\n const parsed = JSON.parse(jsonStr);\n\n if (parsed.title && parsed.body) {\n return {\n releaseNotes: {\n title: parsed.title,\n body: parsed.body,\n },\n };\n }\n } catch {\n // JSON parsing failed, fall through to fallback\n }\n }\n\n // Fallback: try to extract title and body from the message\n const lines = finalMessage.split('\\n');\n let title = '';\n let body = '';\n let inBody = false;\n\n for (const line of lines) {\n if (!title && line.trim() && !line.startsWith('#')) {\n title = line.trim();\n } else if (title && line.trim()) {\n inBody = true;\n }\n\n if (inBody) {\n body += line + '\\n';\n }\n }\n\n // If we still don't have good content, use the whole message\n if (!title || !body) {\n title = 'Release Notes';\n body = finalMessage;\n }\n\n return {\n releaseNotes: {\n title: title.trim(),\n body: body.trim(),\n },\n };\n}\n\n"],"names":["isTokenLimitError","logger","timeoutMs","elapsedTimeFormatted","fs","__filename","__dirname","path","createGetFileHistoryTool","createGetFileContentTool","createSearchCodebaseTool","createGetRelatedTestsTool","createGetFileDependenciesTool","createAnalyzeDiffSectionTool","createGetRecentCommitsTool","createGroupFilesByConcernTool","buildSystemPrompt","buildUserMessage","parseAgenticResult"],"mappings":";;;;;;;;;;AAQA,IAAI;AAKG,SAAS,UAAU,cAA4B;AAClD,WAAS;AACb;AAKO,SAAS,mBAA2B;AACvC,SAAO;AAAA,IACH,MAAM,MAAM;AAAA,IAAC;AAAA,IACb,OAAO,MAAM;AAAA,IAAC;AAAA,IACd,MAAM,MAAM;AAAA,IAAC;AAAA,IACb,OAAO,MAAM;AAAA,IAAC;AAAA,EAAA;AAEtB;AAMO,SAAS,iBAAgC;AAC5C,MAAI;AAGA,UAAM,UAAU,QAAQ,SAAS;AACjC,QAAI,WAAW,QAAQ,cAAc;AACjC,aAAO,QAAQ,aAAa;AAAA,QACxB,OAAO;AAAA,QACP,QAAQ,QAAQ,OAAO,OAAA;AAAA,QACvB,YAAY,CAAC,IAAI,QAAQ,WAAW,SAAS;AAAA,MAAA,CAChD;AAAA,IACL;AAAA,EACJ,QAAQ;AAAA,EAER;AACA,SAAO;AACX;AAKO,SAAS,YAAoB;AAChC,MAAI,QAAQ;AACR,WAAO;AAAA,EACX;AAGA,QAAM,gBAAgB,eAAA;AACtB,MAAI,eAAe;AACf,aAAS;A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