@grunnverk/commands-git 1.0.0

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 ADDED
@@ -0,0 +1,2976 @@
1
+ import { Formatter } from '@riotprompt/riotprompt';
2
+ import 'dotenv/config';
3
+ import shellescape from 'shell-escape';
4
+ import { getDryRunLogger, DEFAULT_MAX_DIFF_BYTES, DEFAULT_EXCLUDED_PATTERNS, Diff, Files, Log, DEFAULT_OUTPUT_DIRECTORY, sanitizeDirection, toAIConfig, createStorageAdapter, createLoggerAdapter, getOutputPath, getTimestampedResponseFilename, getTimestampedRequestFilename, filterContent, getTimestampedCommitFilename, improveContentWithLLM, getLogger, getTimestampedReviewNotesFilename, getTimestampedReviewFilename } from '@grunnverk/core';
5
+ import { ValidationError, ExternalDependencyError, CommandError, createStorage, checkForFileDependencies as checkForFileDependencies$1, logFileDependencyWarning, logFileDependencySuggestions, FileOperationError } from '@grunnverk/shared';
6
+ import { run, validateString, safeJsonParse, validatePackageJson, unstageAll, stageFiles, verifyStagedFiles, getCurrentBranch, runSecure, getGitStatusSummary } from '@grunnverk/git-tools';
7
+ import { getRecentClosedIssuesForCommit, handleIssueCreation, getReleaseNotesContent, getIssuesContent } from '@grunnverk/github-tools';
8
+ import { runAgenticCommit, requireTTY, generateReflectionReport, getUserChoice, STANDARD_CHOICES, getLLMFeedbackInEditor, editContentInEditor, createCompletionWithRetry, createCommitPrompt, createReviewPrompt, createCompletion } from '@grunnverk/ai-service';
9
+ import path from 'path';
10
+ import os from 'os';
11
+ import { spawn } from 'child_process';
12
+ import fs from 'fs/promises';
13
+
14
+ // Helper function to read context files
15
+ async function readContextFiles(contextFiles, logger) {
16
+ if (!contextFiles || contextFiles.length === 0) {
17
+ return '';
18
+ }
19
+ const storage = createStorage();
20
+ const contextParts = [];
21
+ for (const filePath of contextFiles){
22
+ try {
23
+ const content = await storage.readFile(filePath, 'utf8');
24
+ contextParts.push(`## Context from ${filePath}\n\n${content}\n`);
25
+ logger.debug(`Read context from file: ${filePath}`);
26
+ } catch (error) {
27
+ logger.warn(`Failed to read context file ${filePath}: ${error.message}`);
28
+ }
29
+ }
30
+ return contextParts.join('\n---\n\n');
31
+ }
32
+ // Helper function to generate self-reflection output using observability module
33
+ async function generateSelfReflection(agenticResult, outputDirectory, storage, logger) {
34
+ try {
35
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').split('.')[0];
36
+ const reflectionPath = getOutputPath(outputDirectory, `agentic-reflection-commit-${timestamp}.md`);
37
+ // Use new observability reflection generator
38
+ const report = await generateReflectionReport({
39
+ iterations: agenticResult.iterations || 0,
40
+ toolCallsExecuted: agenticResult.toolCallsExecuted || 0,
41
+ maxIterations: agenticResult.maxIterations || 10,
42
+ toolMetrics: agenticResult.toolMetrics || [],
43
+ conversationHistory: agenticResult.conversationHistory || [],
44
+ commitMessage: agenticResult.commitMessage,
45
+ suggestedSplits: agenticResult.suggestedSplits || [],
46
+ logger
47
+ });
48
+ // Save the report to output directory
49
+ await storage.writeFile(reflectionPath, report, 'utf8');
50
+ logger.info('');
51
+ logger.info('═'.repeat(80));
52
+ logger.info('📊 SELF-REFLECTION REPORT GENERATED');
53
+ logger.info('═'.repeat(80));
54
+ logger.info('');
55
+ logger.info('📁 Location: %s', reflectionPath);
56
+ logger.info('');
57
+ logger.info('📈 Report Summary:');
58
+ const iterations = agenticResult.iterations || 0;
59
+ const toolCalls = agenticResult.toolCallsExecuted || 0;
60
+ const uniqueTools = new Set((agenticResult.toolMetrics || []).map((m)=>m.name)).size;
61
+ logger.info(` • ${iterations} iterations completed`);
62
+ logger.info(` • ${toolCalls} tool calls executed`);
63
+ logger.info(` • ${uniqueTools} unique tools used`);
64
+ logger.info('');
65
+ logger.info('💡 Use this report to:');
66
+ logger.info(' • Understand which tools were most effective');
67
+ logger.info(' • Identify performance bottlenecks');
68
+ logger.info(' • Review the complete agentic conversation');
69
+ logger.info(' • Improve tool implementation based on metrics');
70
+ logger.info('');
71
+ logger.info('═'.repeat(80));
72
+ } catch (error) {
73
+ logger.warn('Failed to generate self-reflection output: %s', error.message);
74
+ logger.debug('Self-reflection error details:', error);
75
+ }
76
+ }
77
+ // Helper function to get current version from package.json
78
+ async function getCurrentVersion(storage) {
79
+ try {
80
+ const packageJsonContents = await storage.readFile('package.json', 'utf-8');
81
+ const packageJson = safeJsonParse(packageJsonContents, 'package.json');
82
+ const validated = validatePackageJson(packageJson, 'package.json');
83
+ return validated.version;
84
+ } catch {
85
+ // Return undefined if we can't read the version (not a critical failure)
86
+ return undefined;
87
+ }
88
+ }
89
+ // Helper function to edit commit message using editor
90
+ async function editCommitMessageInteractively(commitMessage) {
91
+ const templateLines = [
92
+ '# Edit your commit message below. Lines starting with "#" will be ignored.',
93
+ '# Save and close the editor when you are done.'
94
+ ];
95
+ const result = await editContentInEditor(commitMessage, templateLines, '.txt');
96
+ return result.content;
97
+ }
98
+ // Helper function to improve commit message using LLM
99
+ async function improveCommitMessageWithLLM(commitMessage, runConfig, promptConfig, promptContext, outputDirectory, diffContent) {
100
+ // Get user feedback on what to improve using the editor
101
+ const userFeedback = await getLLMFeedbackInEditor('commit message', commitMessage);
102
+ // Create AI config from kodrdriv config
103
+ const aiConfig = toAIConfig(runConfig);
104
+ const aiStorageAdapter = createStorageAdapter(outputDirectory);
105
+ const aiLogger = createLoggerAdapter(false);
106
+ const improvementConfig = {
107
+ contentType: 'commit message',
108
+ createImprovedPrompt: async (promptConfig, currentMessage, promptContext)=>{
109
+ var _aiConfig_commands_commit, _aiConfig_commands;
110
+ const improvementPromptContent = {
111
+ diffContent: diffContent,
112
+ userDirection: `Please improve this commit message based on the user's feedback: "${userFeedback}".
113
+
114
+ Current commit message: "${currentMessage}"
115
+
116
+ Please revise the commit message according to the user's feedback while maintaining accuracy and following conventional commit standards if appropriate.`
117
+ };
118
+ const prompt = await createCommitPrompt(promptConfig, improvementPromptContent, promptContext);
119
+ // Format the prompt into a proper request with messages
120
+ const modelToUse = ((_aiConfig_commands = aiConfig.commands) === null || _aiConfig_commands === void 0 ? void 0 : (_aiConfig_commands_commit = _aiConfig_commands.commit) === null || _aiConfig_commands_commit === void 0 ? void 0 : _aiConfig_commands_commit.model) || aiConfig.model || 'gpt-4o-mini';
121
+ return Formatter.create({
122
+ logger: getDryRunLogger(false)
123
+ }).formatPrompt(modelToUse, prompt);
124
+ },
125
+ callLLM: async (request, runConfig, outputDirectory)=>{
126
+ var _aiConfig_commands_commit, _aiConfig_commands, _aiConfig_commands_commit1, _aiConfig_commands1;
127
+ return await createCompletionWithRetry(request.messages, {
128
+ model: ((_aiConfig_commands = aiConfig.commands) === null || _aiConfig_commands === void 0 ? void 0 : (_aiConfig_commands_commit = _aiConfig_commands.commit) === null || _aiConfig_commands_commit === void 0 ? void 0 : _aiConfig_commands_commit.model) || aiConfig.model,
129
+ openaiReasoning: ((_aiConfig_commands1 = aiConfig.commands) === null || _aiConfig_commands1 === void 0 ? void 0 : (_aiConfig_commands_commit1 = _aiConfig_commands1.commit) === null || _aiConfig_commands_commit1 === void 0 ? void 0 : _aiConfig_commands_commit1.reasoning) || aiConfig.reasoning,
130
+ debug: runConfig.debug,
131
+ debugRequestFile: getOutputPath(outputDirectory, getTimestampedRequestFilename('commit-improve')),
132
+ debugResponseFile: getOutputPath(outputDirectory, getTimestampedResponseFilename('commit-improve')),
133
+ storage: aiStorageAdapter,
134
+ logger: aiLogger
135
+ });
136
+ }
137
+ };
138
+ return await improveContentWithLLM(commitMessage, runConfig, promptConfig, promptContext, outputDirectory, improvementConfig);
139
+ }
140
+ // Interactive feedback loop for commit message
141
+ async function handleInteractiveCommitFeedback(commitMessage, runConfig, promptConfig, promptContext, outputDirectory, storage, diffContent, hasActualChanges, cached) {
142
+ var _runConfig_commit, _runConfig_commit1;
143
+ const logger = getDryRunLogger(false);
144
+ let currentMessage = commitMessage;
145
+ // Determine what the confirm action will do based on configuration
146
+ const senditEnabled = (_runConfig_commit = runConfig.commit) === null || _runConfig_commit === void 0 ? void 0 : _runConfig_commit.sendit;
147
+ const willActuallyCommit = senditEnabled && hasActualChanges && cached;
148
+ // Create dynamic confirm choice based on configuration
149
+ const isAmendMode = (_runConfig_commit1 = runConfig.commit) === null || _runConfig_commit1 === void 0 ? void 0 : _runConfig_commit1.amend;
150
+ const confirmChoice = willActuallyCommit ? {
151
+ key: 'c',
152
+ label: isAmendMode ? 'Amend last commit with this message (sendit enabled)' : 'Commit changes with this message (sendit enabled)'
153
+ } : {
154
+ key: 'c',
155
+ label: 'Accept message (you will need to commit manually)'
156
+ };
157
+ while(true){
158
+ // Display the current commit message
159
+ logger.info('\n📝 Generated Commit Message:');
160
+ logger.info('─'.repeat(50));
161
+ logger.info(currentMessage);
162
+ logger.info('─'.repeat(50));
163
+ // Show configuration status
164
+ if (senditEnabled) {
165
+ if (willActuallyCommit) {
166
+ logger.info('\nSENDIT_MODE_ACTIVE: SendIt mode enabled | Action: Commit choice will execute git commit automatically | Staged Changes: Available');
167
+ } else {
168
+ logger.info('\nSENDIT_MODE_NO_CHANGES: SendIt mode configured but no staged changes | Action: Only message save available | Staged Changes: None');
169
+ }
170
+ } else {
171
+ logger.info('\nSENDIT_MODE_INACTIVE: SendIt mode not active | Action: Accept choice will only save message | Commit: Manual');
172
+ }
173
+ // Get user choice
174
+ const userChoice = await getUserChoice('\nWhat would you like to do with this commit message?', [
175
+ confirmChoice,
176
+ STANDARD_CHOICES.EDIT,
177
+ STANDARD_CHOICES.SKIP,
178
+ STANDARD_CHOICES.IMPROVE
179
+ ], {
180
+ nonTtyErrorSuggestions: [
181
+ 'Use --sendit flag to auto-commit without review'
182
+ ]
183
+ });
184
+ switch(userChoice){
185
+ case 'c':
186
+ return {
187
+ action: 'commit',
188
+ finalMessage: currentMessage
189
+ };
190
+ case 'e':
191
+ try {
192
+ currentMessage = await editCommitMessageInteractively(currentMessage);
193
+ } catch (error) {
194
+ logger.error(`Failed to edit commit message: ${error.message}`);
195
+ // Continue the loop to show options again
196
+ }
197
+ break;
198
+ case 's':
199
+ return {
200
+ action: 'skip',
201
+ finalMessage: currentMessage
202
+ };
203
+ case 'i':
204
+ try {
205
+ currentMessage = await improveCommitMessageWithLLM(currentMessage, runConfig, promptConfig, promptContext, outputDirectory, diffContent);
206
+ } catch (error) {
207
+ logger.error(`Failed to improve commit message: ${error.message}`);
208
+ // Continue the loop to show options again
209
+ }
210
+ break;
211
+ }
212
+ }
213
+ }
214
+ // Helper function to check if there are any commits in the repository
215
+ const hasCommits = async ()=>{
216
+ try {
217
+ await run('git rev-parse HEAD');
218
+ return true;
219
+ } catch {
220
+ // No commits found or not a git repository
221
+ return false;
222
+ }
223
+ };
224
+ // Helper function to push the commit
225
+ const pushCommit = async (pushConfig, logger, isDryRun)=>{
226
+ if (!pushConfig) {
227
+ return; // No push requested
228
+ }
229
+ // Determine the remote to push to
230
+ let remote = 'origin';
231
+ if (typeof pushConfig === 'string') {
232
+ remote = pushConfig;
233
+ }
234
+ const pushCommand = `git push ${remote}`;
235
+ if (isDryRun) {
236
+ logger.info('Would push to %s with: %s', remote, pushCommand);
237
+ } else {
238
+ logger.info('🚀 Pushing to %s...', remote);
239
+ try {
240
+ await run(pushCommand);
241
+ logger.info('✅ Push successful!');
242
+ } catch (error) {
243
+ logger.error('Failed to push to %s: %s', remote, error.message);
244
+ throw new ExternalDependencyError(`Failed to push to ${remote}`, 'git', error);
245
+ }
246
+ }
247
+ };
248
+ // Simplified cached determination with single check
249
+ const determineCachedState = async (config)=>{
250
+ var _config_commit, _config_commit1, _config_commit2;
251
+ // If amend is used, we use staged changes (since we're amending the last commit)
252
+ if ((_config_commit = config.commit) === null || _config_commit === void 0 ? void 0 : _config_commit.amend) {
253
+ // For amend mode, check that there's a previous commit to amend
254
+ const hasAnyCommits = await hasCommits();
255
+ if (!hasAnyCommits) {
256
+ throw new ValidationError('Cannot use --amend: no commits found in repository. Create an initial commit first.');
257
+ }
258
+ return true;
259
+ }
260
+ // If add is used, we always look at staged changes after add
261
+ if ((_config_commit1 = config.commit) === null || _config_commit1 === void 0 ? void 0 : _config_commit1.add) {
262
+ return true;
263
+ }
264
+ // If explicitly set, use that value
265
+ if (((_config_commit2 = config.commit) === null || _config_commit2 === void 0 ? void 0 : _config_commit2.cached) !== undefined) {
266
+ return config.commit.cached;
267
+ }
268
+ // Otherwise, check if there are staged changes
269
+ return await Diff.hasStagedChanges();
270
+ };
271
+ // Single validation of sendit + cached state
272
+ const validateSenditState = (config, cached, isDryRun, logger)=>{
273
+ var _config_commit;
274
+ if (((_config_commit = config.commit) === null || _config_commit === void 0 ? void 0 : _config_commit.sendit) && !cached && !isDryRun) {
275
+ const message = 'SendIt mode enabled, but no changes to commit.';
276
+ logger.warn(message);
277
+ return false; // Return false to indicate no changes to commit
278
+ }
279
+ return true; // Return true to indicate we can proceed
280
+ };
281
+ // Better file save handling with fallbacks
282
+ const saveCommitMessage = async (outputDirectory, summary, storage, logger)=>{
283
+ const timestampedFilename = getTimestampedCommitFilename();
284
+ const primaryPath = getOutputPath(outputDirectory, timestampedFilename);
285
+ try {
286
+ await storage.writeFile(primaryPath, summary, 'utf-8');
287
+ logger.debug('Saved timestamped commit message: %s', primaryPath);
288
+ return; // Success, no fallback needed
289
+ } catch (error) {
290
+ logger.warn('Failed to save commit message to primary location (%s): %s', primaryPath, error.message);
291
+ logger.debug('Primary save error details:', error);
292
+ // First fallback: try output directory root (in case subdirectory has issues)
293
+ try {
294
+ const outputRootPath = getOutputPath('output', timestampedFilename);
295
+ await storage.writeFile(outputRootPath, summary, 'utf-8');
296
+ logger.info('COMMIT_MESSAGE_SAVED_FALLBACK: Saved commit message to fallback location | Path: %s | Purpose: Preserve message for later use', outputRootPath);
297
+ return;
298
+ } catch (outputError) {
299
+ logger.warn('Failed to save to output directory fallback: %s', outputError.message);
300
+ }
301
+ // Last resort fallback: save to current directory (this creates the clutter!)
302
+ try {
303
+ const fallbackPath = `commit-message-${Date.now()}.txt`;
304
+ await storage.writeFile(fallbackPath, summary, 'utf-8');
305
+ logger.warn('⚠️ Saved commit message to current directory as last resort: %s', fallbackPath);
306
+ logger.warn('⚠️ This file should be moved to the output directory and may clutter your workspace');
307
+ } catch (fallbackError) {
308
+ logger.error('Failed to save commit message anywhere: %s', fallbackError.message);
309
+ logger.error('Commit message will only be available in console output');
310
+ // Continue execution - commit message is still returned
311
+ }
312
+ }
313
+ };
314
+ /**
315
+ * Deduplicate files across splits - each file can only be in one split
316
+ * Later splits lose files that were already claimed by earlier splits
317
+ * Returns filtered splits with empty splits removed
318
+ */ function deduplicateSplits(splits, logger) {
319
+ const claimedFiles = new Set();
320
+ const result = [];
321
+ for (const split of splits){
322
+ // Find files in this split that haven't been claimed yet
323
+ const uniqueFiles = [];
324
+ const duplicates = [];
325
+ for (const file of split.files){
326
+ if (claimedFiles.has(file)) {
327
+ duplicates.push(file);
328
+ } else {
329
+ uniqueFiles.push(file);
330
+ claimedFiles.add(file);
331
+ }
332
+ }
333
+ // Log if duplicates were found
334
+ if (duplicates.length > 0) {
335
+ logger.warn(`Removing duplicate files from split "${split.message.split('\n')[0]}": ${duplicates.join(', ')}`);
336
+ }
337
+ // Only include split if it has files
338
+ if (uniqueFiles.length > 0) {
339
+ result.push({
340
+ ...split,
341
+ files: uniqueFiles
342
+ });
343
+ } else {
344
+ logger.warn(`Skipping empty split after deduplication: "${split.message.split('\n')[0]}"`);
345
+ }
346
+ }
347
+ return result;
348
+ }
349
+ /**
350
+ * Interactive review of a single split before committing
351
+ */ async function reviewSplitInteractively(split, index, total, logger) {
352
+ logger.info('');
353
+ logger.info('═'.repeat(80));
354
+ logger.info(`📋 Commit ${index + 1} of ${total}`);
355
+ logger.info('═'.repeat(80));
356
+ logger.info('');
357
+ logger.info('Files (%d):', split.files.length);
358
+ split.files.forEach((f)=>logger.info(` - ${f}`));
359
+ logger.info('');
360
+ logger.info('Rationale:');
361
+ logger.info(` ${split.rationale}`);
362
+ logger.info('');
363
+ logger.info('Proposed Message:');
364
+ logger.info('─'.repeat(50));
365
+ logger.info(split.message);
366
+ logger.info('─'.repeat(50));
367
+ logger.info('');
368
+ const choices = [
369
+ {
370
+ key: 'c',
371
+ label: 'Commit with this message'
372
+ },
373
+ {
374
+ key: 'e',
375
+ label: 'Edit message before committing'
376
+ },
377
+ {
378
+ key: 's',
379
+ label: 'Skip this commit'
380
+ },
381
+ {
382
+ key: 't',
383
+ label: 'Stop - no more commits'
384
+ }
385
+ ];
386
+ const choice = await getUserChoice('What would you like to do?', choices, {
387
+ nonTtyErrorSuggestions: [
388
+ 'Use --sendit to auto-commit without review'
389
+ ]
390
+ });
391
+ if (choice === 'e') {
392
+ // Edit the message
393
+ const edited = await editCommitMessageInteractively(split.message);
394
+ return {
395
+ action: 'commit',
396
+ modifiedMessage: edited
397
+ };
398
+ } else if (choice === 'c') {
399
+ return {
400
+ action: 'commit'
401
+ };
402
+ } else if (choice === 's') {
403
+ return {
404
+ action: 'skip'
405
+ };
406
+ } else {
407
+ return {
408
+ action: 'stop'
409
+ };
410
+ }
411
+ }
412
+ /**
413
+ * Create a single commit from a split
414
+ */ async function createSingleSplitCommit(split, commitMessage, isDryRun, logger) {
415
+ // Stage the files for this split
416
+ if (isDryRun) {
417
+ logger.debug(`[DRY RUN] Would stage: ${split.files.join(', ')}`);
418
+ } else {
419
+ await stageFiles(split.files);
420
+ // Verify files were staged correctly
421
+ const verification = await verifyStagedFiles(split.files);
422
+ if (!verification.allPresent) {
423
+ throw new ValidationError(`Stage verification failed. Missing: ${verification.missing.join(', ')}. ` + `Unexpected: ${verification.unexpected.join(', ')}`);
424
+ }
425
+ }
426
+ // Create the commit
427
+ if (isDryRun) {
428
+ logger.debug(`[DRY RUN] Would commit with message: ${commitMessage}`);
429
+ return undefined;
430
+ } else {
431
+ const validatedMessage = validateString(commitMessage, 'commit message');
432
+ const escapedMessage = shellescape([
433
+ validatedMessage
434
+ ]);
435
+ await run(`git commit -m ${escapedMessage}`);
436
+ // Get the SHA of the commit we just created
437
+ const result = await run('git rev-parse HEAD');
438
+ const sha = (typeof result === 'string' ? result : result.stdout).trim();
439
+ logger.debug(`Created commit: ${sha}`);
440
+ return sha;
441
+ }
442
+ }
443
+ /**
444
+ * Execute a series of split commits
445
+ */ async function executeSplitCommits(options) {
446
+ const { splits, isDryRun, interactive, logger } = options;
447
+ const result = {
448
+ success: false,
449
+ commitsCreated: 0,
450
+ commits: [],
451
+ skipped: 0
452
+ };
453
+ try {
454
+ logger.debug('Preparing to create split commits...');
455
+ logger.info('');
456
+ logger.info('═'.repeat(80));
457
+ logger.info(`🔀 Creating ${splits.length} commits from staged changes`);
458
+ logger.info('═'.repeat(80));
459
+ // Process each split
460
+ for(let i = 0; i < splits.length; i++){
461
+ const split = splits[i];
462
+ logger.info('');
463
+ logger.info(`Processing commit ${i + 1} of ${splits.length}...`);
464
+ // Interactive review if enabled
465
+ let commitMessage = split.message;
466
+ if (interactive && !isDryRun) {
467
+ const review = await reviewSplitInteractively(split, i, splits.length, logger);
468
+ if (review.action === 'stop') {
469
+ logger.info('User stopped split commit process');
470
+ logger.info(`Created ${result.commitsCreated} commits before stopping`);
471
+ result.success = false;
472
+ return result;
473
+ } else if (review.action === 'skip') {
474
+ logger.info(`Skipped commit ${i + 1}`);
475
+ result.skipped++;
476
+ continue;
477
+ } else if (review.action === 'edit') {
478
+ commitMessage = review.modifiedMessage;
479
+ }
480
+ }
481
+ try {
482
+ // Unstage everything first
483
+ if (!isDryRun) {
484
+ await unstageAll();
485
+ }
486
+ // Create this split's commit
487
+ const sha = await createSingleSplitCommit(split, commitMessage, isDryRun, logger);
488
+ result.commits.push({
489
+ message: commitMessage,
490
+ files: split.files,
491
+ sha
492
+ });
493
+ result.commitsCreated++;
494
+ if (isDryRun) {
495
+ logger.info(`[DRY RUN] Would create commit ${i + 1}: ${commitMessage.split('\n')[0]}`);
496
+ } else {
497
+ logger.info(`✅ Created commit ${i + 1}: ${sha === null || sha === void 0 ? void 0 : sha.substring(0, 7)} - ${commitMessage.split('\n')[0]}`);
498
+ }
499
+ } catch (error) {
500
+ logger.error(`Failed to create commit ${i + 1}: ${error.message}`);
501
+ logger.info(`Successfully created ${result.commitsCreated} commits before error`);
502
+ // Re-stage remaining files for user
503
+ if (!isDryRun) {
504
+ const remainingFiles = splits.slice(i).flatMap((s)=>s.files);
505
+ try {
506
+ await stageFiles(remainingFiles);
507
+ logger.info(`Remaining ${remainingFiles.length} files are staged for manual commit`);
508
+ } catch (restageError) {
509
+ logger.error(`Failed to re-stage remaining files: ${restageError.message}`);
510
+ }
511
+ }
512
+ result.success = false;
513
+ result.error = error;
514
+ return result;
515
+ }
516
+ }
517
+ result.success = true;
518
+ return result;
519
+ } catch (error) {
520
+ logger.error(`Split commit process failed: ${error.message}`);
521
+ result.success = false;
522
+ result.error = error;
523
+ return result;
524
+ }
525
+ }
526
+ /**
527
+ * Format a summary message for split commits
528
+ */ function formatSplitCommitSummary(result) {
529
+ const lines = [];
530
+ lines.push('');
531
+ lines.push('═'.repeat(80));
532
+ lines.push('✅ COMMIT SPLITTING COMPLETE');
533
+ lines.push('═'.repeat(80));
534
+ lines.push('');
535
+ lines.push(`Total commits created: ${result.commitsCreated}`);
536
+ if (result.skipped > 0) {
537
+ lines.push(`Commits skipped: ${result.skipped}`);
538
+ }
539
+ lines.push('');
540
+ if (result.commits.length > 0) {
541
+ lines.push('Commits:');
542
+ lines.push('');
543
+ result.commits.forEach((commit, idx)=>{
544
+ const sha = commit.sha ? `${commit.sha.substring(0, 7)} ` : '';
545
+ const firstLine = commit.message.split('\n')[0];
546
+ lines.push(` ${idx + 1}. ${sha}${firstLine}`);
547
+ lines.push(` Files: ${commit.files.length}`);
548
+ });
549
+ }
550
+ lines.push('');
551
+ lines.push('═'.repeat(80));
552
+ return lines.join('\n');
553
+ }
554
+ const executeInternal$3 = async (runConfig)=>{
555
+ var _ref, _ref1, _runConfig_excludedPatterns;
556
+ var _runConfig_commit, _runConfig_commit1, _runConfig_commit2, _runConfig_commit3, _runConfig_commit4, _runConfig_commit5, _runConfig_commit6, _runConfig_commit7, _aiConfig_commands_commit, _aiConfig_commands, _aiConfig_commands_commit1, _aiConfig_commands1, _aiConfig_commands_commit2, _aiConfig_commands2, _runConfig_commit8, _aiConfig_commands_commit3, _aiConfig_commands3, _runConfig_commit9, _runConfig_commit10, _runConfig_commit11, _runConfig_commit12, _runConfig_commit13, _runConfig_commit14, _runConfig_commit15;
557
+ const isDryRun = runConfig.dryRun || false;
558
+ const logger = getDryRunLogger(isDryRun);
559
+ logger.info('COMMIT_START: Starting commit message generation | Mode: %s', isDryRun ? 'dry-run' : 'live');
560
+ // Track if user explicitly chose to skip in interactive mode
561
+ let userSkippedCommit = false;
562
+ if ((_runConfig_commit = runConfig.commit) === null || _runConfig_commit === void 0 ? void 0 : _runConfig_commit.add) {
563
+ if (isDryRun) {
564
+ logger.info('GIT_ADD_DRY_RUN: Would stage all changes | Mode: dry-run | Command: git add -A');
565
+ } else {
566
+ logger.info('GIT_ADD_STAGING: Adding all changes to index | Command: git add -A | Scope: all files | Purpose: Stage for commit');
567
+ await run('git add -A');
568
+ logger.info('GIT_ADD_SUCCESS: Successfully staged all changes | Command: git add -A | Status: completed');
569
+ }
570
+ }
571
+ // Determine cached state with single, clear logic
572
+ logger.info('COMMIT_CHECK_STAGED: Checking for staged changes | Action: Analyzing git status');
573
+ const cached = await determineCachedState(runConfig);
574
+ logger.info('COMMIT_STAGED_STATUS: Staged changes detected: %s | Cached: %s', cached ? 'yes' : 'no', cached);
575
+ // Validate sendit state early - now returns boolean instead of throwing
576
+ validateSenditState(runConfig, cached, isDryRun, logger);
577
+ logger.info('COMMIT_GENERATE_DIFF: Generating diff content | Max bytes: %d', (_ref = (_runConfig_commit1 = runConfig.commit) === null || _runConfig_commit1 === void 0 ? void 0 : _runConfig_commit1.maxDiffBytes) !== null && _ref !== void 0 ? _ref : DEFAULT_MAX_DIFF_BYTES);
578
+ let diffContent = '';
579
+ const maxDiffBytes = (_ref1 = (_runConfig_commit2 = runConfig.commit) === null || _runConfig_commit2 === void 0 ? void 0 : _runConfig_commit2.maxDiffBytes) !== null && _ref1 !== void 0 ? _ref1 : DEFAULT_MAX_DIFF_BYTES;
580
+ const options = {
581
+ cached,
582
+ excludedPatterns: (_runConfig_excludedPatterns = runConfig.excludedPatterns) !== null && _runConfig_excludedPatterns !== void 0 ? _runConfig_excludedPatterns : DEFAULT_EXCLUDED_PATTERNS,
583
+ maxDiffBytes
584
+ };
585
+ const diff = await Diff.create(options);
586
+ diffContent = await diff.get();
587
+ logger.info('COMMIT_DIFF_GENERATED: Diff content generated | Size: %d bytes | Has changes: %s', diffContent.length, diffContent.trim().length > 0 ? 'yes' : 'no');
588
+ // Check if there are actually any changes in the diff
589
+ let hasActualChanges = diffContent.trim().length > 0;
590
+ // If no changes found with current patterns, check for critical excluded files
591
+ if (!hasActualChanges) {
592
+ const criticalChanges = await Diff.hasCriticalExcludedChanges();
593
+ if (criticalChanges.hasChanges) {
594
+ var _runConfig_commit16;
595
+ logger.info('CRITICAL_FILES_DETECTED: No changes with exclusion patterns, but critical files modified | Files: %s | Action: May need to include critical files', criticalChanges.files.join(', '));
596
+ if (((_runConfig_commit16 = runConfig.commit) === null || _runConfig_commit16 === void 0 ? void 0 : _runConfig_commit16.sendit) && !isDryRun) {
597
+ var _runConfig_excludedPatterns1;
598
+ // In sendit mode, automatically include critical files
599
+ logger.info('SENDIT_INCLUDING_CRITICAL: SendIt mode including critical files in diff | Purpose: Ensure all important changes are captured');
600
+ const minimalPatterns = Diff.getMinimalExcludedPatterns((_runConfig_excludedPatterns1 = runConfig.excludedPatterns) !== null && _runConfig_excludedPatterns1 !== void 0 ? _runConfig_excludedPatterns1 : DEFAULT_EXCLUDED_PATTERNS);
601
+ const updatedOptions = {
602
+ ...options,
603
+ excludedPatterns: minimalPatterns
604
+ };
605
+ const updatedDiff = await Diff.create(updatedOptions);
606
+ diffContent = await updatedDiff.get();
607
+ if (diffContent.trim().length > 0) {
608
+ logger.info('CRITICAL_FILES_INCLUDED: Successfully added critical files to diff | Status: ready for commit message generation');
609
+ // Update hasActualChanges since we now have content after including critical files
610
+ hasActualChanges = true;
611
+ } else {
612
+ logger.warn('No changes detected even after including critical files.');
613
+ return 'No changes to commit.';
614
+ }
615
+ } else {
616
+ var _runConfig_excludedPatterns2;
617
+ // In non-sendit mode, suggest including the files
618
+ logger.warn('Consider including these files by using:');
619
+ logger.warn(' kodrdriv commit --excluded-paths %s', ((_runConfig_excludedPatterns2 = runConfig.excludedPatterns) !== null && _runConfig_excludedPatterns2 !== void 0 ? _runConfig_excludedPatterns2 : DEFAULT_EXCLUDED_PATTERNS).filter((p)=>!criticalChanges.files.some((f)=>p.includes(f.split('/').pop() || ''))).map((p)=>`"${p}"`).join(' '));
620
+ logger.warn('Or run with --sendit to automatically include critical files.');
621
+ if (!isDryRun) {
622
+ return 'No changes to commit. Use suggestions above to include critical files.';
623
+ } else {
624
+ logger.info('Generating commit message template for future use...');
625
+ }
626
+ }
627
+ } else {
628
+ var _runConfig_commit17;
629
+ // No changes at all - try fallback to file content for new repositories
630
+ logger.info('NO_CHANGES_DETECTED: No changes found in working directory | Status: clean | Action: Nothing to commit');
631
+ if (((_runConfig_commit17 = runConfig.commit) === null || _runConfig_commit17 === void 0 ? void 0 : _runConfig_commit17.sendit) && !isDryRun) {
632
+ logger.warn('No changes detected to commit. Skipping commit operation.');
633
+ return 'No changes to commit.';
634
+ } else {
635
+ var _runConfig_excludedPatterns3;
636
+ logger.info('NO_DIFF_FALLBACK: No diff content available | Action: Attempting to generate commit message from file content | Strategy: fallback');
637
+ // Create file content collector as fallback
638
+ const fileOptions = {
639
+ excludedPatterns: (_runConfig_excludedPatterns3 = runConfig.excludedPatterns) !== null && _runConfig_excludedPatterns3 !== void 0 ? _runConfig_excludedPatterns3 : DEFAULT_EXCLUDED_PATTERNS,
640
+ maxTotalBytes: maxDiffBytes * 5,
641
+ workingDirectory: process.cwd()
642
+ };
643
+ const files = await Files.create(fileOptions);
644
+ const fileContent = await files.get();
645
+ if (fileContent && fileContent.trim().length > 0) {
646
+ logger.info('FILE_CONTENT_USING: Using file content for commit message generation | Content Length: %d characters | Source: file content', fileContent.length);
647
+ diffContent = fileContent;
648
+ hasActualChanges = true; // We have content to work with
649
+ } else {
650
+ var _runConfig_commit18;
651
+ if ((_runConfig_commit18 = runConfig.commit) === null || _runConfig_commit18 === void 0 ? void 0 : _runConfig_commit18.sendit) {
652
+ logger.info('COMMIT_SKIPPED: Skipping commit operation | Reason: No changes detected | Action: None');
653
+ return 'No changes to commit.';
654
+ } else {
655
+ logger.info('COMMIT_TEMPLATE_GENERATING: Creating commit message template for future use | Reason: No changes | Purpose: Provide template');
656
+ }
657
+ }
658
+ }
659
+ }
660
+ }
661
+ const logOptions = {
662
+ limit: (_runConfig_commit3 = runConfig.commit) === null || _runConfig_commit3 === void 0 ? void 0 : _runConfig_commit3.messageLimit
663
+ };
664
+ const log = await Log.create(logOptions);
665
+ const logContext = await log.get();
666
+ // Always ensure output directory exists for request/response files and GitHub issues lookup
667
+ const outputDirectory = runConfig.outputDirectory || DEFAULT_OUTPUT_DIRECTORY;
668
+ const storage = createStorage();
669
+ await storage.ensureDirectory(outputDirectory);
670
+ // Get GitHub issues context for large commits [[memory:5887795]]
671
+ let githubIssuesContext = '';
672
+ try {
673
+ const currentVersion = await getCurrentVersion(storage);
674
+ if (currentVersion) {
675
+ logger.debug(`Found current version: ${currentVersion}, fetching related GitHub issues...`);
676
+ githubIssuesContext = await getRecentClosedIssuesForCommit(currentVersion, 10);
677
+ if (githubIssuesContext) {
678
+ logger.debug(`Fetched GitHub issues context (${githubIssuesContext.length} characters)`);
679
+ } else {
680
+ logger.debug('No relevant GitHub issues found for commit context');
681
+ }
682
+ } else {
683
+ logger.debug('Could not determine current version, fetching recent issues without milestone filtering...');
684
+ githubIssuesContext = await getRecentClosedIssuesForCommit(undefined, 10);
685
+ if (githubIssuesContext) {
686
+ logger.debug(`Fetched general GitHub issues context (${githubIssuesContext.length} characters)`);
687
+ }
688
+ }
689
+ } catch (error) {
690
+ logger.debug(`Failed to fetch GitHub issues for commit context: ${error.message}`);
691
+ // Continue without GitHub context - this shouldn't block commit generation
692
+ }
693
+ const promptConfig = {
694
+ overridePaths: runConfig.discoveredConfigDirs || [],
695
+ overrides: runConfig.overrides || false
696
+ };
697
+ const userDirection = sanitizeDirection((_runConfig_commit4 = runConfig.commit) === null || _runConfig_commit4 === void 0 ? void 0 : _runConfig_commit4.direction);
698
+ if (userDirection) {
699
+ logger.debug('Using user direction: %s', userDirection);
700
+ }
701
+ // Create adapters for ai-service
702
+ const aiConfig = toAIConfig(runConfig);
703
+ const aiStorageAdapter = createStorageAdapter(outputDirectory);
704
+ const aiLogger = createLoggerAdapter(isDryRun);
705
+ // Read context from files if provided
706
+ const contextFromFiles = await readContextFiles((_runConfig_commit5 = runConfig.commit) === null || _runConfig_commit5 === void 0 ? void 0 : _runConfig_commit5.contextFiles, logger);
707
+ // Combine file context with existing context
708
+ const combinedContext = [
709
+ (_runConfig_commit6 = runConfig.commit) === null || _runConfig_commit6 === void 0 ? void 0 : _runConfig_commit6.context,
710
+ contextFromFiles
711
+ ].filter(Boolean).join('\n\n---\n\n');
712
+ // Define promptContext for use in interactive improvements
713
+ const promptContext = {
714
+ logContext,
715
+ context: combinedContext || undefined,
716
+ directories: runConfig.contextDirectories
717
+ };
718
+ // Announce self-reflection if enabled
719
+ if ((_runConfig_commit7 = runConfig.commit) === null || _runConfig_commit7 === void 0 ? void 0 : _runConfig_commit7.selfReflection) {
720
+ logger.info('📊 Self-reflection enabled - detailed analysis will be generated');
721
+ }
722
+ // Get list of changed files
723
+ const changedFilesResult = await run(`git diff --name-only ${cached ? '--cached' : ''}`);
724
+ const changedFilesOutput = typeof changedFilesResult === 'string' ? changedFilesResult : changedFilesResult.stdout;
725
+ const changedFiles = changedFilesOutput.split('\n').filter((f)=>f.trim().length > 0);
726
+ logger.debug('Changed files for analysis: %d files', changedFiles.length);
727
+ // Run agentic commit generation
728
+ logger.info('COMMIT_AI_GENERATION: Starting AI-powered commit message generation | Model: %s | Reasoning: %s | Files: %d', ((_aiConfig_commands = aiConfig.commands) === null || _aiConfig_commands === void 0 ? void 0 : (_aiConfig_commands_commit = _aiConfig_commands.commit) === null || _aiConfig_commands_commit === void 0 ? void 0 : _aiConfig_commands_commit.model) || aiConfig.model || 'gpt-4o-mini', ((_aiConfig_commands1 = aiConfig.commands) === null || _aiConfig_commands1 === void 0 ? void 0 : (_aiConfig_commands_commit1 = _aiConfig_commands1.commit) === null || _aiConfig_commands_commit1 === void 0 ? void 0 : _aiConfig_commands_commit1.reasoning) || aiConfig.reasoning || 'low', changedFiles.length);
729
+ const agenticResult = await runAgenticCommit({
730
+ changedFiles,
731
+ diffContent,
732
+ userDirection,
733
+ logContext,
734
+ model: ((_aiConfig_commands2 = aiConfig.commands) === null || _aiConfig_commands2 === void 0 ? void 0 : (_aiConfig_commands_commit2 = _aiConfig_commands2.commit) === null || _aiConfig_commands_commit2 === void 0 ? void 0 : _aiConfig_commands_commit2.model) || aiConfig.model,
735
+ maxIterations: ((_runConfig_commit8 = runConfig.commit) === null || _runConfig_commit8 === void 0 ? void 0 : _runConfig_commit8.maxAgenticIterations) || 10,
736
+ debug: runConfig.debug,
737
+ debugRequestFile: getOutputPath(outputDirectory, getTimestampedRequestFilename('commit')),
738
+ debugResponseFile: getOutputPath(outputDirectory, getTimestampedResponseFilename('commit')),
739
+ storage: aiStorageAdapter,
740
+ logger: aiLogger,
741
+ openaiReasoning: ((_aiConfig_commands3 = aiConfig.commands) === null || _aiConfig_commands3 === void 0 ? void 0 : (_aiConfig_commands_commit3 = _aiConfig_commands3.commit) === null || _aiConfig_commands_commit3 === void 0 ? void 0 : _aiConfig_commands_commit3.reasoning) || aiConfig.reasoning
742
+ });
743
+ const iterations = agenticResult.iterations || 0;
744
+ const toolCalls = agenticResult.toolCallsExecuted || 0;
745
+ logger.info(`🔍 Analysis complete: ${iterations} iterations, ${toolCalls} tool calls`);
746
+ // Generate self-reflection output if enabled
747
+ if ((_runConfig_commit9 = runConfig.commit) === null || _runConfig_commit9 === void 0 ? void 0 : _runConfig_commit9.selfReflection) {
748
+ await generateSelfReflection(agenticResult, outputDirectory, storage, logger);
749
+ }
750
+ // Check for suggested splits
751
+ if (agenticResult.suggestedSplits.length > 1 && ((_runConfig_commit10 = runConfig.commit) === null || _runConfig_commit10 === void 0 ? void 0 : _runConfig_commit10.allowCommitSplitting)) {
752
+ var _runConfig_commit19;
753
+ logger.info('\n📋 AI suggests splitting this into %d commits:', agenticResult.suggestedSplits.length);
754
+ for(let i = 0; i < agenticResult.suggestedSplits.length; i++){
755
+ const split = agenticResult.suggestedSplits[i];
756
+ logger.info('\nCommit %d (%d files):', i + 1, split.files.length);
757
+ logger.info(' Files: %s', split.files.join(', '));
758
+ logger.info(' Rationale: %s', split.rationale);
759
+ logger.info(' Message: %s', split.message);
760
+ }
761
+ // NEW: Check if auto-split is enabled (defaults to true if not specified)
762
+ const autoSplitEnabled = ((_runConfig_commit19 = runConfig.commit) === null || _runConfig_commit19 === void 0 ? void 0 : _runConfig_commit19.autoSplit) !== false; // Default to true
763
+ if (autoSplitEnabled) {
764
+ var _runConfig_commit20, _runConfig_commit21;
765
+ logger.info('\n🔄 Auto-split enabled - creating separate commits...\n');
766
+ // Deduplicate files across splits to prevent staging errors
767
+ // (AI sometimes suggests the same file in multiple splits)
768
+ const deduplicatedSplits = deduplicateSplits(agenticResult.suggestedSplits, logger);
769
+ if (deduplicatedSplits.length === 0) {
770
+ throw new CommandError('All splits were empty after deduplication - no files to commit', 'SPLIT_EMPTY', false);
771
+ }
772
+ const splitResult = await executeSplitCommits({
773
+ splits: deduplicatedSplits,
774
+ isDryRun,
775
+ interactive: !!(((_runConfig_commit20 = runConfig.commit) === null || _runConfig_commit20 === void 0 ? void 0 : _runConfig_commit20.interactive) && !((_runConfig_commit21 = runConfig.commit) === null || _runConfig_commit21 === void 0 ? void 0 : _runConfig_commit21.sendit)),
776
+ logger});
777
+ if (splitResult.success) {
778
+ var _runConfig_commit22;
779
+ // Push if requested (all commits)
780
+ if (((_runConfig_commit22 = runConfig.commit) === null || _runConfig_commit22 === void 0 ? void 0 : _runConfig_commit22.push) && !isDryRun) {
781
+ await pushCommit(runConfig.commit.push, logger, isDryRun);
782
+ }
783
+ return formatSplitCommitSummary(splitResult);
784
+ } else {
785
+ var _splitResult_error;
786
+ const errorMessage = ((_splitResult_error = splitResult.error) === null || _splitResult_error === void 0 ? void 0 : _splitResult_error.message) || 'Unknown error';
787
+ throw new CommandError(`Failed to create split commits: ${errorMessage}`, 'SPLIT_COMMIT_FAILED', false, splitResult.error);
788
+ }
789
+ } else {
790
+ logger.info('\n⚠️ Commit splitting is not automated. Please stage and commit files separately.');
791
+ logger.info('Using combined message for now...\n');
792
+ logger.info('💡 To enable automatic splitting, add autoSplit: true to your commit configuration');
793
+ }
794
+ } else if (agenticResult.suggestedSplits.length > 1) {
795
+ logger.debug('AI suggested %d splits but commit splitting is not enabled', agenticResult.suggestedSplits.length);
796
+ }
797
+ const rawSummary = agenticResult.commitMessage;
798
+ // Apply stop-context filtering to commit message
799
+ const filterResult = filterContent(rawSummary, runConfig.stopContext);
800
+ const summary = filterResult.filtered;
801
+ // Save timestamped copy of commit message with better error handling
802
+ await saveCommitMessage(outputDirectory, summary, storage, logger);
803
+ // 🛡️ Universal Safety Check: Run before ANY commit operation
804
+ // This protects both direct commits (--sendit) and automated commits (publish, etc.)
805
+ const willCreateCommit = ((_runConfig_commit11 = runConfig.commit) === null || _runConfig_commit11 === void 0 ? void 0 : _runConfig_commit11.sendit) && hasActualChanges && cached;
806
+ if (willCreateCommit && !((_runConfig_commit12 = runConfig.commit) === null || _runConfig_commit12 === void 0 ? void 0 : _runConfig_commit12.skipFileCheck) && !isDryRun) {
807
+ logger.debug('Checking for file: dependencies before commit operation...');
808
+ try {
809
+ const fileDependencyIssues = await checkForFileDependencies$1(storage, process.cwd());
810
+ if (fileDependencyIssues.length > 0) {
811
+ var _runConfig_commit23;
812
+ logger.error('🚫 COMMIT BLOCKED: Found file: dependencies that should not be committed!');
813
+ logger.error('');
814
+ logFileDependencyWarning(fileDependencyIssues, 'commit');
815
+ logFileDependencySuggestions(true);
816
+ logger.error('Generated commit message was:');
817
+ logger.error('%s', summary);
818
+ logger.error('');
819
+ if ((_runConfig_commit23 = runConfig.commit) === null || _runConfig_commit23 === void 0 ? void 0 : _runConfig_commit23.sendit) {
820
+ logger.error('To bypass this check, use: kodrdriv commit --skip-file-check --sendit');
821
+ } else {
822
+ logger.error('To bypass this check, add skipFileCheck: true to your commit configuration');
823
+ }
824
+ throw new ValidationError('Found file: dependencies that should not be committed. Use --skip-file-check to bypass.');
825
+ }
826
+ logger.debug('✅ No file: dependencies found, proceeding with commit');
827
+ } catch (error) {
828
+ logger.warn('Warning: Could not check for file: dependencies: %s', error.message);
829
+ logger.warn('Proceeding with commit...');
830
+ }
831
+ } else if (((_runConfig_commit13 = runConfig.commit) === null || _runConfig_commit13 === void 0 ? void 0 : _runConfig_commit13.skipFileCheck) && willCreateCommit) {
832
+ logger.warn('⚠️ Skipping file: dependency check as requested');
833
+ }
834
+ // Handle interactive mode
835
+ if (((_runConfig_commit14 = runConfig.commit) === null || _runConfig_commit14 === void 0 ? void 0 : _runConfig_commit14.interactive) && !isDryRun) {
836
+ var _runConfig_commit24;
837
+ requireTTY('Interactive mode requires a terminal. Use --sendit or --dry-run instead.');
838
+ const interactiveResult = await handleInteractiveCommitFeedback(summary, runConfig, promptConfig, promptContext, outputDirectory, storage, diffContent, hasActualChanges, cached);
839
+ if (interactiveResult.action === 'skip') {
840
+ logger.info('COMMIT_ABORTED: User aborted commit operation | Reason: User choice | Action: No commit performed');
841
+ logger.info('COMMIT_NO_ACTION: No commit will be performed | Status: aborted | Next: User can retry or modify changes');
842
+ userSkippedCommit = true;
843
+ return interactiveResult.finalMessage;
844
+ }
845
+ // User chose to commit - check if sendit is enabled to determine what action to take
846
+ const senditEnabled = (_runConfig_commit24 = runConfig.commit) === null || _runConfig_commit24 === void 0 ? void 0 : _runConfig_commit24.sendit;
847
+ const willActuallyCommit = senditEnabled && hasActualChanges && cached;
848
+ if (willActuallyCommit) {
849
+ var _runConfig_commit25;
850
+ const commitAction = ((_runConfig_commit25 = runConfig.commit) === null || _runConfig_commit25 === void 0 ? void 0 : _runConfig_commit25.amend) ? 'amending last commit' : 'committing';
851
+ logger.info('SENDIT_EXECUTING: SendIt enabled, executing commit action | Action: %s | Message Length: %d | Final Message: \n\n%s\n\n', commitAction.charAt(0).toUpperCase() + commitAction.slice(1), interactiveResult.finalMessage.length, interactiveResult.finalMessage);
852
+ try {
853
+ var _runConfig_commit26, _runConfig_commit27;
854
+ const validatedSummary = validateString(interactiveResult.finalMessage, 'commit summary');
855
+ const escapedSummary = shellescape([
856
+ validatedSummary
857
+ ]);
858
+ const commitCommand = ((_runConfig_commit26 = runConfig.commit) === null || _runConfig_commit26 === void 0 ? void 0 : _runConfig_commit26.amend) ? `git commit --amend -m ${escapedSummary}` : `git commit -m ${escapedSummary}`;
859
+ await run(commitCommand);
860
+ logger.info('COMMIT_SUCCESS: Commit operation completed successfully | Status: committed | Action: Changes saved to repository');
861
+ // Push if requested
862
+ await pushCommit((_runConfig_commit27 = runConfig.commit) === null || _runConfig_commit27 === void 0 ? void 0 : _runConfig_commit27.push, logger, isDryRun);
863
+ } catch (error) {
864
+ logger.error('Failed to commit:', error);
865
+ throw new ExternalDependencyError('Failed to create commit', 'git', error);
866
+ }
867
+ } else if (senditEnabled && (!hasActualChanges || !cached)) {
868
+ logger.info('📝 SendIt enabled but no staged changes available. Final message saved: \n\n%s\n\n', interactiveResult.finalMessage);
869
+ if (!hasActualChanges) {
870
+ logger.info('💡 No changes detected to commit');
871
+ } else if (!cached) {
872
+ logger.info('💡 No staged changes found. Use "git add" to stage changes or configure add: true in commit settings');
873
+ }
874
+ } else {
875
+ logger.info('📝 Message accepted (SendIt not enabled). Use this commit message manually: \n\n%s\n\n', interactiveResult.finalMessage);
876
+ logger.info('💡 To automatically commit, add sendit: true to your commit configuration');
877
+ }
878
+ return interactiveResult.finalMessage;
879
+ }
880
+ // Safety check: Never commit if user explicitly skipped in interactive mode
881
+ if (userSkippedCommit) {
882
+ logger.debug('Skipping sendit logic because user chose to skip in interactive mode');
883
+ return summary;
884
+ }
885
+ if ((_runConfig_commit15 = runConfig.commit) === null || _runConfig_commit15 === void 0 ? void 0 : _runConfig_commit15.sendit) {
886
+ if (isDryRun) {
887
+ var _runConfig_commit28, _runConfig_commit29;
888
+ logger.info('Would commit with message: \n\n%s\n\n', summary);
889
+ const commitAction = ((_runConfig_commit28 = runConfig.commit) === null || _runConfig_commit28 === void 0 ? void 0 : _runConfig_commit28.amend) ? 'git commit --amend -m <generated-message>' : 'git commit -m <generated-message>';
890
+ logger.info('Would execute: %s', commitAction);
891
+ // Show push command in dry run if requested
892
+ if ((_runConfig_commit29 = runConfig.commit) === null || _runConfig_commit29 === void 0 ? void 0 : _runConfig_commit29.push) {
893
+ const remote = typeof runConfig.commit.push === 'string' ? runConfig.commit.push : 'origin';
894
+ logger.info('Would push to %s with: git push %s', remote, remote);
895
+ }
896
+ } else if (hasActualChanges && cached) {
897
+ var _runConfig_commit30;
898
+ const commitAction = ((_runConfig_commit30 = runConfig.commit) === null || _runConfig_commit30 === void 0 ? void 0 : _runConfig_commit30.amend) ? 'amending commit' : 'committing';
899
+ logger.info('SendIt mode enabled. %s with message: \n\n%s\n\n', commitAction.charAt(0).toUpperCase() + commitAction.slice(1), summary);
900
+ try {
901
+ var _runConfig_commit31, _runConfig_commit32;
902
+ const validatedSummary = validateString(summary, 'commit summary');
903
+ const escapedSummary = shellescape([
904
+ validatedSummary
905
+ ]);
906
+ const commitCommand = ((_runConfig_commit31 = runConfig.commit) === null || _runConfig_commit31 === void 0 ? void 0 : _runConfig_commit31.amend) ? `git commit --amend -m ${escapedSummary}` : `git commit -m ${escapedSummary}`;
907
+ await run(commitCommand);
908
+ logger.info('Commit successful!');
909
+ // Push if requested
910
+ await pushCommit((_runConfig_commit32 = runConfig.commit) === null || _runConfig_commit32 === void 0 ? void 0 : _runConfig_commit32.push, logger, isDryRun);
911
+ } catch (error) {
912
+ logger.error('Failed to commit:', error);
913
+ throw new ExternalDependencyError('Failed to create commit', 'git', error);
914
+ }
915
+ } else {
916
+ logger.info('SendIt mode enabled, but no changes to commit. Generated message: \n\n%s\n\n', summary);
917
+ }
918
+ } else if (isDryRun) {
919
+ logger.info('Generated commit message: \n\n%s\n\n', summary);
920
+ } else {
921
+ // Default behavior when neither --interactive nor --sendit is specified
922
+ logger.info('Generated commit message: \n\n%s\n\n', summary);
923
+ }
924
+ return summary;
925
+ };
926
+ const execute$4 = async (runConfig)=>{
927
+ try {
928
+ return await executeInternal$3(runConfig);
929
+ } catch (error) {
930
+ // Import getLogger for error handling
931
+ const { getLogger } = await import('@grunnverk/core');
932
+ const standardLogger = getLogger();
933
+ if (error instanceof ValidationError || error instanceof ExternalDependencyError || error instanceof CommandError) {
934
+ standardLogger.error(`commit failed: ${error.message}`);
935
+ if (error.cause && typeof error.cause === 'object' && 'message' in error.cause) {
936
+ standardLogger.debug(`Caused by: ${error.cause.message}`);
937
+ } else if (error.cause) {
938
+ standardLogger.debug(`Caused by: ${error.cause}`);
939
+ }
940
+ throw error;
941
+ }
942
+ // Unexpected errors
943
+ standardLogger.error(`commit encountered unexpected error: ${error.message}`);
944
+ throw error;
945
+ }
946
+ };
947
+
948
+ function _define_property(obj, key, value) {
949
+ if (key in obj) {
950
+ Object.defineProperty(obj, key, {
951
+ value: value,
952
+ enumerable: true,
953
+ configurable: true,
954
+ writable: true
955
+ });
956
+ } else {
957
+ obj[key] = value;
958
+ }
959
+ return obj;
960
+ }
961
+ // Performance timing helper
962
+ class PerformanceTimer {
963
+ static start(logger, operation) {
964
+ logger.verbose(`⏱️ Starting: ${operation}`);
965
+ return new PerformanceTimer(logger);
966
+ }
967
+ end(operation) {
968
+ const duration = Date.now() - this.startTime;
969
+ this.logger.verbose(`⏱️ Completed: ${operation} (${duration}ms)`);
970
+ return duration;
971
+ }
972
+ constructor(logger){
973
+ _define_property(this, "startTime", void 0);
974
+ _define_property(this, "logger", void 0);
975
+ this.logger = logger;
976
+ this.startTime = Date.now();
977
+ }
978
+ }
979
+ const EXCLUDED_DIRECTORIES = [
980
+ 'node_modules',
981
+ 'dist',
982
+ 'build',
983
+ 'coverage',
984
+ '.git',
985
+ '.next',
986
+ '.nuxt',
987
+ 'out',
988
+ 'public',
989
+ 'static',
990
+ 'assets'
991
+ ];
992
+ // Batch read multiple package.json files in parallel
993
+ const batchReadPackageJsonFiles = async (packageJsonPaths, storage, rootDir)=>{
994
+ const logger = getLogger();
995
+ const timer = PerformanceTimer.start(logger, `Batch reading ${packageJsonPaths.length} package.json files`);
996
+ const readPromises = packageJsonPaths.map(async (packageJsonPath)=>{
997
+ try {
998
+ const packageJsonContent = await storage.readFile(packageJsonPath, 'utf-8');
999
+ const parsed = safeJsonParse(packageJsonContent, packageJsonPath);
1000
+ const packageJson = validatePackageJson(parsed, packageJsonPath, false);
1001
+ const relativePath = path.relative(rootDir, path.dirname(packageJsonPath));
1002
+ return {
1003
+ path: packageJsonPath,
1004
+ packageJson,
1005
+ relativePath: relativePath || '.'
1006
+ };
1007
+ } catch (error) {
1008
+ logger.debug(`Skipped invalid package.json at ${packageJsonPath}: ${error.message}`);
1009
+ return null;
1010
+ }
1011
+ });
1012
+ const results = await Promise.all(readPromises);
1013
+ const validResults = results.filter((result)=>result !== null);
1014
+ timer.end(`Successfully read ${validResults.length}/${packageJsonPaths.length} package.json files`);
1015
+ return validResults;
1016
+ };
1017
+ // Optimized recursive package.json finder with parallel processing
1018
+ const findAllPackageJsonFiles = async (rootDir, storage)=>{
1019
+ const logger = getLogger();
1020
+ const timer = PerformanceTimer.start(logger, 'Optimized scanning for package.json files');
1021
+ const scanForPaths = async (currentDir, depth = 0)=>{
1022
+ // Prevent infinite recursion and overly deep scanning
1023
+ if (depth > 5) {
1024
+ return [];
1025
+ }
1026
+ try {
1027
+ if (!await storage.exists(currentDir) || !await storage.isDirectory(currentDir)) {
1028
+ return [];
1029
+ }
1030
+ const items = await storage.listFiles(currentDir);
1031
+ const foundPaths = [];
1032
+ // Check for package.json in current directory
1033
+ if (items.includes('package.json')) {
1034
+ const packageJsonPath = path.join(currentDir, 'package.json');
1035
+ foundPaths.push(packageJsonPath);
1036
+ }
1037
+ // Process subdirectories in parallel
1038
+ const subdirPromises = [];
1039
+ for (const item of items){
1040
+ if (EXCLUDED_DIRECTORIES.includes(item)) {
1041
+ continue;
1042
+ }
1043
+ const itemPath = path.join(currentDir, item);
1044
+ subdirPromises.push((async ()=>{
1045
+ try {
1046
+ if (await storage.isDirectory(itemPath)) {
1047
+ return await scanForPaths(itemPath, depth + 1);
1048
+ }
1049
+ } catch (error) {
1050
+ logger.debug(`Skipped directory ${itemPath}: ${error.message}`);
1051
+ }
1052
+ return [];
1053
+ })());
1054
+ }
1055
+ if (subdirPromises.length > 0) {
1056
+ const subdirResults = await Promise.all(subdirPromises);
1057
+ for (const subdirPaths of subdirResults){
1058
+ foundPaths.push(...subdirPaths);
1059
+ }
1060
+ }
1061
+ return foundPaths;
1062
+ } catch (error) {
1063
+ logger.debug(`Failed to scan directory ${currentDir}: ${error.message}`);
1064
+ return [];
1065
+ }
1066
+ };
1067
+ const pathsTimer = PerformanceTimer.start(logger, 'Finding all package.json paths');
1068
+ const allPaths = await scanForPaths(rootDir);
1069
+ pathsTimer.end(`Found ${allPaths.length} package.json file paths`);
1070
+ // Phase 2: Batch read all package.json files in parallel
1071
+ const packageJsonFiles = await batchReadPackageJsonFiles(allPaths, storage, rootDir);
1072
+ timer.end(`Found ${packageJsonFiles.length} valid package.json files`);
1073
+ return packageJsonFiles;
1074
+ };
1075
+ // Optimized package scanning with parallel processing
1076
+ const scanDirectoryForPackages = async (rootDir, storage)=>{
1077
+ const logger = getLogger();
1078
+ const timer = PerformanceTimer.start(logger, `Optimized package scanning: ${rootDir}`);
1079
+ const packageMap = new Map(); // packageName -> relativePath
1080
+ const absoluteRootDir = path.resolve(process.cwd(), rootDir);
1081
+ logger.verbose(`Scanning directory for packages: ${absoluteRootDir}`);
1082
+ try {
1083
+ // Quick existence and directory check
1084
+ const existsTimer = PerformanceTimer.start(logger, `Checking directory: ${absoluteRootDir}`);
1085
+ if (!await storage.exists(absoluteRootDir) || !await storage.isDirectory(absoluteRootDir)) {
1086
+ existsTimer.end(`Directory not found or not a directory: ${absoluteRootDir}`);
1087
+ timer.end(`Directory invalid: ${rootDir}`);
1088
+ return packageMap;
1089
+ }
1090
+ existsTimer.end(`Directory verified: ${absoluteRootDir}`);
1091
+ // Get all items and process in parallel
1092
+ const listTimer = PerformanceTimer.start(logger, `Listing contents: ${absoluteRootDir}`);
1093
+ const items = await storage.listFiles(absoluteRootDir);
1094
+ listTimer.end(`Listed ${items.length} items`);
1095
+ // Create batched promises for better performance
1096
+ const BATCH_SIZE = 10; // Process directories in batches to avoid overwhelming filesystem
1097
+ const batches = [];
1098
+ for(let i = 0; i < items.length; i += BATCH_SIZE){
1099
+ const batch = items.slice(i, i + BATCH_SIZE);
1100
+ batches.push(batch);
1101
+ }
1102
+ const processTimer = PerformanceTimer.start(logger, `Processing ${batches.length} batches of directories`);
1103
+ for (const batch of batches){
1104
+ const batchPromises = batch.map(async (item)=>{
1105
+ const itemPath = path.join(absoluteRootDir, item);
1106
+ try {
1107
+ if (await storage.isDirectory(itemPath)) {
1108
+ const packageJsonPath = path.join(itemPath, 'package.json');
1109
+ if (await storage.exists(packageJsonPath)) {
1110
+ const packageJsonContent = await storage.readFile(packageJsonPath, 'utf-8');
1111
+ const parsed = safeJsonParse(packageJsonContent, packageJsonPath);
1112
+ const packageJson = validatePackageJson(parsed, packageJsonPath);
1113
+ if (packageJson.name) {
1114
+ const relativePath = path.relative(process.cwd(), itemPath);
1115
+ return {
1116
+ name: packageJson.name,
1117
+ path: relativePath
1118
+ };
1119
+ }
1120
+ }
1121
+ }
1122
+ } catch (error) {
1123
+ logger.debug(`Skipped ${itemPath}: ${error.message || error}`);
1124
+ }
1125
+ return null;
1126
+ });
1127
+ const batchResults = await Promise.all(batchPromises);
1128
+ for (const result of batchResults){
1129
+ if (result) {
1130
+ packageMap.set(result.name, result.path);
1131
+ logger.debug(`Found package: ${result.name} at ${result.path}`);
1132
+ }
1133
+ }
1134
+ }
1135
+ processTimer.end(`Processed ${items.length} directories in ${batches.length} batches`);
1136
+ logger.verbose(`Found ${packageMap.size} packages in ${items.length} subdirectories`);
1137
+ } catch (error) {
1138
+ logger.warn(`PERFORMANCE_DIR_READ_FAILED: Unable to read directory | Directory: ${absoluteRootDir} | Error: ${error}`);
1139
+ }
1140
+ timer.end(`Found ${packageMap.size} packages in: ${rootDir}`);
1141
+ return packageMap;
1142
+ };
1143
+ // Parallel scope processing for better performance
1144
+ const findPackagesByScope = async (dependencies, scopeRoots, storage)=>{
1145
+ const logger = getLogger();
1146
+ const timer = PerformanceTimer.start(logger, 'Finding packages by scope (optimized)');
1147
+ const workspacePackages = new Map();
1148
+ logger.silly(`Checking dependencies against scope roots: ${JSON.stringify(scopeRoots)}`);
1149
+ // Process all scopes in parallel for maximum performance
1150
+ const scopeTimer = PerformanceTimer.start(logger, 'Parallel scope scanning');
1151
+ const scopePromises = Object.entries(scopeRoots).map(async ([scope, rootDir])=>{
1152
+ logger.verbose(`Scanning scope ${scope} at root directory: ${rootDir}`);
1153
+ const scopePackages = await scanDirectoryForPackages(rootDir, storage);
1154
+ // Filter packages that match the scope
1155
+ const matchingPackages = [];
1156
+ for (const [packageName, packagePath] of scopePackages){
1157
+ if (packageName.startsWith(scope)) {
1158
+ matchingPackages.push([
1159
+ packageName,
1160
+ packagePath
1161
+ ]);
1162
+ logger.debug(`Registered package: ${packageName} -> ${packagePath}`);
1163
+ }
1164
+ }
1165
+ return {
1166
+ scope,
1167
+ packages: matchingPackages
1168
+ };
1169
+ });
1170
+ const allScopeResults = await Promise.all(scopePromises);
1171
+ // Aggregate all packages from all scopes
1172
+ const allPackages = new Map();
1173
+ for (const { scope, packages } of allScopeResults){
1174
+ for (const [packageName, packagePath] of packages){
1175
+ allPackages.set(packageName, packagePath);
1176
+ }
1177
+ }
1178
+ scopeTimer.end(`Scanned ${Object.keys(scopeRoots).length} scope roots, found ${allPackages.size} packages`);
1179
+ // Match dependencies to available packages
1180
+ const matchTimer = PerformanceTimer.start(logger, 'Matching dependencies to packages');
1181
+ for (const [depName, depVersion] of Object.entries(dependencies)){
1182
+ logger.debug(`Processing dependency: ${depName}@${depVersion}`);
1183
+ if (allPackages.has(depName)) {
1184
+ const packagePath = allPackages.get(depName);
1185
+ workspacePackages.set(depName, packagePath);
1186
+ logger.verbose(`Found sibling package: ${depName} at ${packagePath}`);
1187
+ }
1188
+ }
1189
+ matchTimer.end(`Matched ${workspacePackages.size} dependencies to workspace packages`);
1190
+ timer.end(`Found ${workspacePackages.size} packages to link`);
1191
+ return workspacePackages;
1192
+ };
1193
+ // Utility to collect all dependencies from package.json files efficiently
1194
+ const collectAllDependencies = (packageJsonFiles)=>{
1195
+ const logger = getLogger();
1196
+ const timer = PerformanceTimer.start(logger, 'Collecting all dependencies');
1197
+ const allDependencies = {};
1198
+ for (const { packageJson } of packageJsonFiles){
1199
+ Object.assign(allDependencies, packageJson.dependencies);
1200
+ Object.assign(allDependencies, packageJson.devDependencies);
1201
+ Object.assign(allDependencies, packageJson.peerDependencies);
1202
+ }
1203
+ timer.end(`Collected ${Object.keys(allDependencies).length} unique dependencies`);
1204
+ return allDependencies;
1205
+ };
1206
+ // Utility to check for file: dependencies
1207
+ const checkForFileDependencies = (packageJsonFiles)=>{
1208
+ const logger = getLogger();
1209
+ const timer = PerformanceTimer.start(logger, 'Checking for file: dependencies');
1210
+ const filesWithFileDepedencies = [];
1211
+ for (const { path: packagePath, packageJson, relativePath } of packageJsonFiles){
1212
+ const fileDeps = [];
1213
+ // Check all dependency types for file: paths
1214
+ const allDeps = {
1215
+ ...packageJson.dependencies,
1216
+ ...packageJson.devDependencies,
1217
+ ...packageJson.peerDependencies
1218
+ };
1219
+ for (const [name, version] of Object.entries(allDeps)){
1220
+ if (version.startsWith('file:')) {
1221
+ fileDeps.push(`${name}: ${version}`);
1222
+ }
1223
+ }
1224
+ if (fileDeps.length > 0) {
1225
+ filesWithFileDepedencies.push({
1226
+ path: relativePath,
1227
+ dependencies: fileDeps
1228
+ });
1229
+ }
1230
+ }
1231
+ if (filesWithFileDepedencies.length > 0) {
1232
+ logger.warn('FILE_DEPS_WARNING: Found file: dependencies that should not be committed | Count: ' + filesWithFileDepedencies.length + ' | Impact: May cause build issues');
1233
+ for (const file of filesWithFileDepedencies){
1234
+ logger.warn(`FILE_DEPS_PACKAGE: Package with file dependencies | Path: ${file.path}`);
1235
+ for (const dep of file.dependencies){
1236
+ logger.warn(`FILE_DEPS_DETAIL: File dependency detected | Dependency: ${dep}`);
1237
+ }
1238
+ }
1239
+ logger.warn('');
1240
+ logger.warn('FILE_DEPS_RESOLUTION: Action required before committing | Command: kodrdriv unlink | Purpose: Restore registry versions');
1241
+ logger.warn('FILE_DEPS_PREVENTION: Alternative option | Action: Add pre-commit hook | Purpose: Prevent accidental commits of linked dependencies');
1242
+ }
1243
+ timer.end(`Checked ${packageJsonFiles.length} files, found ${filesWithFileDepedencies.length} with file: dependencies`);
1244
+ };
1245
+
1246
+ /**
1247
+ * Check if running in MCP server mode
1248
+ */ const isMcpMode = ()=>process.env.KODRDRIV_MCP_SERVER === 'true';
1249
+ /**
1250
+ * Get an MCP-aware logger that suppresses info/warn/debug output in MCP mode.
1251
+ * Errors are always logged since they indicate problems that need attention.
1252
+ */ const getMcpAwareLogger = ()=>{
1253
+ const coreLogger = getLogger();
1254
+ if (!isMcpMode()) {
1255
+ // In normal mode, just return the core logger
1256
+ return coreLogger;
1257
+ }
1258
+ // In MCP mode, wrap the logger to suppress non-error output
1259
+ return {
1260
+ info: (_message, ..._args)=>{},
1261
+ warn: (_message, ..._args)=>{},
1262
+ debug: (_message, ..._args)=>{},
1263
+ verbose: (_message, ..._args)=>{},
1264
+ silly: (_message, ..._args)=>{},
1265
+ // Always log errors - they indicate real problems
1266
+ error: (message, ...args)=>coreLogger.error(message, ...args)
1267
+ };
1268
+ };
1269
+
1270
+ /**
1271
+ * Execute precommit checks by running the package's precommit script.
1272
+ * Expects the package to have a "precommit" script in package.json.
1273
+ */ const execute$3 = async (runConfig)=>{
1274
+ var _runConfig_precommit, _packageJson_scripts;
1275
+ const logger = getMcpAwareLogger();
1276
+ const isDryRun = runConfig.dryRun || false;
1277
+ const packageDir = process.cwd();
1278
+ const shouldFix = ((_runConfig_precommit = runConfig.precommit) === null || _runConfig_precommit === void 0 ? void 0 : _runConfig_precommit.fix) || false;
1279
+ // Verify precommit script exists
1280
+ const fs = await import('fs/promises');
1281
+ const packageJsonPath = path.join(packageDir, 'package.json');
1282
+ let packageName = packageDir;
1283
+ let packageJson;
1284
+ try {
1285
+ var _packageJson_scripts1;
1286
+ const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');
1287
+ packageJson = JSON.parse(packageJsonContent);
1288
+ packageName = packageJson.name || packageDir;
1289
+ if (!((_packageJson_scripts1 = packageJson.scripts) === null || _packageJson_scripts1 === void 0 ? void 0 : _packageJson_scripts1.precommit)) {
1290
+ throw new Error(`Package "${packageName}" is missing a "precommit" script in package.json`);
1291
+ }
1292
+ } catch (error) {
1293
+ if (error.code === 'ENOENT') {
1294
+ throw new Error(`No package.json found at ${packageJsonPath}`);
1295
+ }
1296
+ throw error;
1297
+ }
1298
+ // If --fix is enabled, try to run lint --fix before precommit
1299
+ if (shouldFix && ((_packageJson_scripts = packageJson.scripts) === null || _packageJson_scripts === void 0 ? void 0 : _packageJson_scripts.lint)) {
1300
+ const lintFixCommand = 'npm run lint -- --fix';
1301
+ if (isDryRun) {
1302
+ logger.info(`DRY RUN: Would execute: ${lintFixCommand}`);
1303
+ } else {
1304
+ try {
1305
+ logger.info(`🔧 Running lint --fix before precommit checks: ${lintFixCommand}`);
1306
+ await run(lintFixCommand, {
1307
+ cwd: packageDir
1308
+ });
1309
+ logger.info(`✅ Lint fixes applied`);
1310
+ } catch (error) {
1311
+ // Log warning but continue with precommit - lint --fix may fail on some issues
1312
+ logger.warn(`⚠️ Lint --fix had issues (continuing with precommit): ${error.message}`);
1313
+ }
1314
+ }
1315
+ }
1316
+ const commandToRun = 'npm run precommit';
1317
+ if (isDryRun) {
1318
+ logger.info(`DRY RUN: Would execute: ${commandToRun}`);
1319
+ return `DRY RUN: Would run precommit checks: ${commandToRun}`;
1320
+ }
1321
+ // Execute the precommit script
1322
+ const timer = PerformanceTimer.start(logger, 'Precommit checks');
1323
+ try {
1324
+ logger.info(`🔧 Running precommit checks: ${commandToRun}`);
1325
+ await run(commandToRun, {
1326
+ cwd: packageDir
1327
+ });
1328
+ const duration = timer.end('Precommit checks');
1329
+ const seconds = (duration / 1000).toFixed(1);
1330
+ logger.info(`✅ Precommit checks passed (${seconds}s)`);
1331
+ return `Precommit checks completed successfully in ${seconds}s`;
1332
+ } catch (error) {
1333
+ timer.end('Precommit checks');
1334
+ logger.error(`❌ Precommit checks failed: ${error.message}`);
1335
+ throw error;
1336
+ }
1337
+ };
1338
+
1339
+ const executeInternal$2 = async (runConfig)=>{
1340
+ const isDryRun = runConfig.dryRun || false;
1341
+ const logger = getDryRunLogger(isDryRun);
1342
+ const storage = createStorage();
1343
+ const outputDirectory = runConfig.outputDirectory || DEFAULT_OUTPUT_DIRECTORY;
1344
+ if (isDryRun) {
1345
+ logger.info(`CLEAN_DRY_RUN: Would remove output directory | Mode: dry-run | Directory: ${outputDirectory} | Action: Would delete if exists`);
1346
+ logger.info(`CLEAN_CHECK_DRY_RUN: Would check directory existence | Mode: dry-run | Directory: ${outputDirectory}`);
1347
+ logger.info('CLEAN_REMOVE_DRY_RUN: Would remove directory if present | Mode: dry-run | Action: Delete');
1348
+ return;
1349
+ }
1350
+ logger.info(`CLEAN_STARTING: Removing output directory | Directory: ${outputDirectory} | Action: Delete | Purpose: Clean generated files`);
1351
+ try {
1352
+ if (await storage.exists(outputDirectory)) {
1353
+ await storage.removeDirectory(outputDirectory);
1354
+ logger.info(`CLEAN_SUCCESS: Successfully removed output directory | Directory: ${outputDirectory} | Status: deleted`);
1355
+ } else {
1356
+ logger.info(`CLEAN_NOT_EXISTS: Output directory does not exist | Directory: ${outputDirectory} | Status: nothing-to-clean`);
1357
+ }
1358
+ } catch (error) {
1359
+ logger.error(`CLEAN_FAILED: Failed to clean output directory | Directory: ${outputDirectory} | Error: ${error.message}`);
1360
+ throw new FileOperationError('Failed to remove output directory', outputDirectory, error);
1361
+ }
1362
+ };
1363
+ const execute$2 = async (runConfig)=>{
1364
+ try {
1365
+ await executeInternal$2(runConfig);
1366
+ } catch (error) {
1367
+ const logger = getLogger();
1368
+ if (error instanceof FileOperationError) {
1369
+ logger.error(`CLEAN_COMMAND_FAILED: Clean command failed | Error: ${error.message}`);
1370
+ if (error.cause && typeof error.cause === 'object' && 'message' in error.cause) {
1371
+ logger.debug(`Caused by: ${error.cause.message}`);
1372
+ }
1373
+ throw error;
1374
+ }
1375
+ // Unexpected errors
1376
+ logger.error(`CLEAN_UNEXPECTED_ERROR: Clean encountered unexpected error | Error: ${error.message} | Type: unexpected`);
1377
+ throw error;
1378
+ }
1379
+ };
1380
+
1381
+ // Utility function to read a review note from a file
1382
+ const readReviewNoteFromFile = async (filePath)=>{
1383
+ const logger = getLogger();
1384
+ try {
1385
+ logger.debug(`Reading review note from file: ${filePath}`);
1386
+ const content = await fs.readFile(filePath, 'utf8');
1387
+ if (!content.trim()) {
1388
+ throw new ValidationError(`Review file is empty: ${filePath}`);
1389
+ }
1390
+ logger.debug(`Successfully read review note from file: ${filePath} (${content.length} characters)`);
1391
+ return content.trim();
1392
+ } catch (error) {
1393
+ if (error.code === 'ENOENT') {
1394
+ throw new FileOperationError(`Review file not found: ${filePath}`, filePath, error);
1395
+ }
1396
+ if (error instanceof ValidationError) {
1397
+ throw error;
1398
+ }
1399
+ throw new FileOperationError(`Failed to read review file: ${error.message}`, filePath, error);
1400
+ }
1401
+ };
1402
+ // Utility function to get all review files in a directory
1403
+ const getReviewFilesInDirectory = async (directoryPath)=>{
1404
+ const logger = getLogger();
1405
+ try {
1406
+ logger.debug(`Scanning directory for review files: ${directoryPath}`);
1407
+ const entries = await fs.readdir(directoryPath, {
1408
+ withFileTypes: true
1409
+ });
1410
+ // Filter for regular files (not directories) and get full paths
1411
+ const files = entries.filter((entry)=>entry.isFile()).map((entry)=>path.join(directoryPath, entry.name)).sort(); // Sort alphabetically
1412
+ logger.debug(`Found ${files.length} files in directory: ${directoryPath}`);
1413
+ return files;
1414
+ } catch (error) {
1415
+ if (error.code === 'ENOENT') {
1416
+ throw new FileOperationError(`Directory not found: ${directoryPath}`, directoryPath, error);
1417
+ }
1418
+ throw new FileOperationError(`Failed to read directory: ${directoryPath}`, directoryPath, error);
1419
+ }
1420
+ };
1421
+ // New function for file selection phase
1422
+ const selectFilesForProcessing = async (reviewFiles, senditMode)=>{
1423
+ const logger = getLogger();
1424
+ if (senditMode) {
1425
+ logger.info(`REVIEW_AUTO_SELECT: Auto-selecting all files for processing | Mode: sendit | File Count: ${reviewFiles.length} | Confirmation: automatic`);
1426
+ return reviewFiles;
1427
+ }
1428
+ // Check if we're in an interactive environment
1429
+ if (!isTTYSafe()) {
1430
+ logger.warn(`REVIEW_NON_INTERACTIVE_SELECT: Non-interactive environment detected | Action: Selecting all files | Mode: non-interactive`);
1431
+ return reviewFiles;
1432
+ }
1433
+ logger.info(`\nREVIEW_SELECTION_PHASE: Starting file selection phase | File Count: ${reviewFiles.length} | Purpose: Choose files to process`);
1434
+ logger.info(`REVIEW_SELECTION_FILES: Found files to review | Count: ${reviewFiles.length} | Action: Select files for processing`);
1435
+ logger.info(`REVIEW_SELECTION_OPTIONS: File selection options available | [c]=Confirm | [s]=Skip | [a]=Abort`);
1436
+ logger.info(``);
1437
+ const selectedFiles = [];
1438
+ let shouldAbort = false;
1439
+ for(let i = 0; i < reviewFiles.length; i++){
1440
+ const filePath = reviewFiles[i];
1441
+ logger.info(`REVIEW_SELECTION_FILE: File for review | Progress: ${i + 1}/${reviewFiles.length} | File: ${filePath}`);
1442
+ const choice = await getUserChoice(`Select action for this file:`, [
1443
+ {
1444
+ key: 'c',
1445
+ label: 'Confirm and process'
1446
+ },
1447
+ {
1448
+ key: 's',
1449
+ label: 'Skip this file'
1450
+ },
1451
+ {
1452
+ key: 'a',
1453
+ label: 'Abort entire review'
1454
+ }
1455
+ ]);
1456
+ if (choice === 'a') {
1457
+ logger.info(`REVIEW_ABORTED: User aborted review process | Action: Aborting | Reason: User request`);
1458
+ shouldAbort = true;
1459
+ break;
1460
+ } else if (choice === 'c') {
1461
+ selectedFiles.push(filePath);
1462
+ logger.info(`REVIEW_FILE_SELECTED: File selected for processing | File: ${filePath} | Action: Will be processed`);
1463
+ } else if (choice === 's') {
1464
+ logger.info(`REVIEW_FILE_SKIPPED: File skipped during selection | File: ${filePath} | Action: Will not be processed`);
1465
+ }
1466
+ }
1467
+ if (shouldAbort) {
1468
+ throw new Error('Review process aborted by user');
1469
+ }
1470
+ if (selectedFiles.length === 0) {
1471
+ throw new Error('No files were selected for processing');
1472
+ }
1473
+ logger.info(`\n📋 File selection complete. ${selectedFiles.length} files selected for processing:`);
1474
+ selectedFiles.forEach((file, index)=>{
1475
+ logger.info(` ${index + 1}. ${file}`);
1476
+ });
1477
+ logger.info(``);
1478
+ return selectedFiles;
1479
+ };
1480
+ // Safe temp file handling with proper permissions and validation
1481
+ const createSecureTempFile = async ()=>{
1482
+ const logger = getLogger();
1483
+ const tmpDir = os.tmpdir();
1484
+ // Ensure temp directory exists and is writable
1485
+ try {
1486
+ // Use constant value directly to avoid import restrictions
1487
+ const W_OK = 2; // fs.constants.W_OK value
1488
+ await fs.access(tmpDir, W_OK);
1489
+ } catch (error) {
1490
+ logger.error(`TEMP_DIR_NOT_WRITABLE: Temporary directory is not writable | Directory: ${tmpDir} | Impact: Cannot create temp files`);
1491
+ throw new FileOperationError(`Temp directory not writable: ${error.message}`, tmpDir, error);
1492
+ }
1493
+ const tmpFilePath = path.join(tmpDir, `kodrdriv_review_${Date.now()}_${Math.random().toString(36).substring(7)}.md`);
1494
+ // Create file with restrictive permissions (owner read/write only)
1495
+ try {
1496
+ const fd = await fs.open(tmpFilePath, 'w', 0o600);
1497
+ await fd.close();
1498
+ logger.debug(`Created secure temp file: ${tmpFilePath}`);
1499
+ return tmpFilePath;
1500
+ } catch (error) {
1501
+ logger.error(`TEMP_FILE_CREATE_FAILED: Unable to create temporary file | Error: ${error.message} | Impact: Cannot proceed with review`);
1502
+ throw new FileOperationError(`Failed to create temp file: ${error.message}`, 'temporary file', error);
1503
+ }
1504
+ };
1505
+ // Safe file cleanup with proper error handling
1506
+ const cleanupTempFile = async (filePath)=>{
1507
+ const logger = getLogger();
1508
+ try {
1509
+ await fs.unlink(filePath);
1510
+ logger.debug(`Cleaned up temp file: ${filePath}`);
1511
+ } catch (error) {
1512
+ // Only ignore ENOENT (file not found) errors, log others
1513
+ if (error.code !== 'ENOENT') {
1514
+ logger.warn(`TEMP_FILE_CLEANUP_FAILED: Unable to cleanup temporary file | File: ${filePath} | Error: ${error.message} | Impact: File may remain`);
1515
+ // Don't throw here to avoid masking the main operation
1516
+ }
1517
+ }
1518
+ };
1519
+ // Editor with optional timeout and proper error handling
1520
+ const openEditorWithTimeout = async (editorCmd, filePath, timeoutMs)=>{
1521
+ const logger = getLogger();
1522
+ return new Promise((resolve, reject)=>{
1523
+ if (timeoutMs) {
1524
+ logger.debug(`Opening editor: ${editorCmd} ${filePath} (timeout: ${timeoutMs}ms)`);
1525
+ } else {
1526
+ logger.debug(`Opening editor: ${editorCmd} ${filePath} (no timeout)`);
1527
+ }
1528
+ const child = spawn(editorCmd, [
1529
+ filePath
1530
+ ], {
1531
+ stdio: 'inherit',
1532
+ shell: false // Prevent shell injection
1533
+ });
1534
+ let timeout;
1535
+ let timeoutCleared = false;
1536
+ const clearTimeoutSafely = ()=>{
1537
+ if (timeout && !timeoutCleared) {
1538
+ clearTimeout(timeout);
1539
+ timeoutCleared = true;
1540
+ }
1541
+ };
1542
+ if (timeoutMs) {
1543
+ timeout = setTimeout(()=>{
1544
+ clearTimeoutSafely(); // Clear the timeout immediately when it fires
1545
+ logger.warn(`Editor timed out after ${timeoutMs}ms, terminating...`);
1546
+ child.kill('SIGTERM');
1547
+ // Give it a moment to terminate gracefully, then force kill
1548
+ setTimeout(()=>{
1549
+ if (!child.killed) {
1550
+ logger.warn('Editor did not terminate gracefully, force killing...');
1551
+ child.kill('SIGKILL');
1552
+ }
1553
+ }, 5000);
1554
+ reject(new Error(`Editor '${editorCmd}' timed out after ${timeoutMs}ms. Consider using a different editor or increasing the timeout.`));
1555
+ }, timeoutMs);
1556
+ }
1557
+ child.on('exit', (code, signal)=>{
1558
+ clearTimeoutSafely();
1559
+ logger.debug(`Editor exited with code ${code}, signal ${signal}`);
1560
+ if (signal === 'SIGTERM' || signal === 'SIGKILL') {
1561
+ reject(new Error(`Editor was terminated (${signal})`));
1562
+ } else if (code === 0) {
1563
+ resolve();
1564
+ } else {
1565
+ reject(new Error(`Editor exited with non-zero code: ${code}`));
1566
+ }
1567
+ });
1568
+ child.on('error', (error)=>{
1569
+ clearTimeoutSafely();
1570
+ logger.error(`Editor error: ${error.message}`);
1571
+ reject(new Error(`Failed to launch editor '${editorCmd}': ${error.message}`));
1572
+ });
1573
+ });
1574
+ };
1575
+ // Validate API response format before use
1576
+ const validateReviewResult = (data)=>{
1577
+ if (!data || typeof data !== 'object') {
1578
+ throw new Error('Invalid API response: expected object, got ' + typeof data);
1579
+ }
1580
+ if (typeof data.summary !== 'string') {
1581
+ throw new Error('Invalid API response: missing or invalid summary field');
1582
+ }
1583
+ if (typeof data.totalIssues !== 'number' || data.totalIssues < 0) {
1584
+ throw new Error('Invalid API response: missing or invalid totalIssues field');
1585
+ }
1586
+ if (data.issues && !Array.isArray(data.issues)) {
1587
+ throw new Error('Invalid API response: issues field must be an array');
1588
+ }
1589
+ // Validate each issue if present
1590
+ if (data.issues) {
1591
+ for(let i = 0; i < data.issues.length; i++){
1592
+ const issue = data.issues[i];
1593
+ if (!issue || typeof issue !== 'object') {
1594
+ throw new Error(`Invalid API response: issue ${i} is not an object`);
1595
+ }
1596
+ if (typeof issue.title !== 'string') {
1597
+ throw new Error(`Invalid API response: issue ${i} missing title`);
1598
+ }
1599
+ if (typeof issue.priority !== 'string') {
1600
+ throw new Error(`Invalid API response: issue ${i} missing priority`);
1601
+ }
1602
+ }
1603
+ }
1604
+ return data;
1605
+ };
1606
+ // Enhanced TTY detection with fallback handling
1607
+ const isTTYSafe = ()=>{
1608
+ try {
1609
+ // Primary check
1610
+ if (process.stdin.isTTY === false) {
1611
+ return false;
1612
+ }
1613
+ // Additional checks for edge cases
1614
+ if (process.stdin.isTTY === true) {
1615
+ return true;
1616
+ }
1617
+ // Handle undefined case (some environments)
1618
+ if (process.stdin.isTTY === undefined) {
1619
+ // Check if we can reasonably assume interactive mode
1620
+ return process.stdout.isTTY === true && process.stderr.isTTY === true;
1621
+ }
1622
+ return false;
1623
+ } catch (error) {
1624
+ // If TTY detection fails entirely, assume non-interactive
1625
+ getLogger().debug(`TTY detection failed: ${error}, assuming non-interactive`);
1626
+ return false;
1627
+ }
1628
+ };
1629
+ // Safe file write with disk space and permission validation
1630
+ const safeWriteFile = async (filePath, content, encoding = 'utf-8')=>{
1631
+ const logger = getLogger();
1632
+ try {
1633
+ // Check if parent directory exists and is writable
1634
+ const parentDir = path.dirname(filePath);
1635
+ const W_OK = 2; // fs.constants.W_OK value
1636
+ await fs.access(parentDir, W_OK);
1637
+ // Check available disk space (basic check by writing a small test)
1638
+ const testFile = `${filePath}.test`;
1639
+ try {
1640
+ await fs.writeFile(testFile, 'test', encoding);
1641
+ await fs.unlink(testFile);
1642
+ } catch (error) {
1643
+ if (error.code === 'ENOSPC') {
1644
+ throw new Error(`Insufficient disk space to write file: ${filePath}`);
1645
+ }
1646
+ throw error;
1647
+ }
1648
+ // Write the actual file
1649
+ await fs.writeFile(filePath, content, encoding);
1650
+ logger.debug(`Successfully wrote file: ${filePath} (${content.length} characters)`);
1651
+ } catch (error) {
1652
+ logger.error(`Failed to write file ${filePath}: ${error.message}`);
1653
+ throw new Error(`Failed to write file ${filePath}: ${error.message}`);
1654
+ }
1655
+ };
1656
+ // Helper function to process a single review note
1657
+ const processSingleReview = async (reviewNote, runConfig, outputDirectory)=>{
1658
+ var _runConfig_review, _runConfig_review1, _runConfig_review2, _runConfig_review3, _runConfig_review_context, _runConfig_review4, _runConfig_review5, _aiConfig_commands_review, _aiConfig_commands, _analysisResult_issues;
1659
+ const logger = getLogger();
1660
+ // Gather additional context based on configuration with improved error handling
1661
+ let logContext = '';
1662
+ let diffContext = '';
1663
+ let releaseNotesContext = '';
1664
+ let issuesContext = '';
1665
+ const contextErrors = [];
1666
+ // Fetch commit history if enabled
1667
+ if ((_runConfig_review = runConfig.review) === null || _runConfig_review === void 0 ? void 0 : _runConfig_review.includeCommitHistory) {
1668
+ try {
1669
+ logger.debug('Fetching recent commit history...');
1670
+ const log = await Log.create({
1671
+ limit: runConfig.review.commitHistoryLimit
1672
+ });
1673
+ const logContent = await log.get();
1674
+ if (logContent.trim()) {
1675
+ logContext += `\n\n[Recent Commit History]\n${logContent}`;
1676
+ logger.debug('Added commit history to context (%d characters)', logContent.length);
1677
+ }
1678
+ } catch (error) {
1679
+ const errorMsg = `Failed to fetch commit history: ${error.message}`;
1680
+ logger.warn(errorMsg);
1681
+ contextErrors.push(errorMsg);
1682
+ }
1683
+ }
1684
+ // Fetch recent diffs if enabled
1685
+ if ((_runConfig_review1 = runConfig.review) === null || _runConfig_review1 === void 0 ? void 0 : _runConfig_review1.includeRecentDiffs) {
1686
+ try {
1687
+ var _runConfig_excludedPatterns;
1688
+ logger.debug('Fetching recent commit diffs...');
1689
+ const basePatterns = (_runConfig_excludedPatterns = runConfig.excludedPatterns) !== null && _runConfig_excludedPatterns !== void 0 ? _runConfig_excludedPatterns : DEFAULT_EXCLUDED_PATTERNS;
1690
+ const recentDiffs = await Diff.getRecentDiffsForReview({
1691
+ limit: runConfig.review.diffHistoryLimit,
1692
+ baseExcludedPatterns: basePatterns
1693
+ });
1694
+ diffContext += recentDiffs;
1695
+ if (recentDiffs.trim()) {
1696
+ logger.debug('Added recent diffs to context (%d characters)', recentDiffs.length);
1697
+ }
1698
+ } catch (error) {
1699
+ const errorMsg = `Failed to fetch recent diffs: ${error.message}`;
1700
+ logger.warn(errorMsg);
1701
+ contextErrors.push(errorMsg);
1702
+ }
1703
+ }
1704
+ // Fetch release notes if enabled
1705
+ if ((_runConfig_review2 = runConfig.review) === null || _runConfig_review2 === void 0 ? void 0 : _runConfig_review2.includeReleaseNotes) {
1706
+ try {
1707
+ logger.debug('Fetching recent release notes from GitHub...');
1708
+ const releaseNotesContent = await getReleaseNotesContent({
1709
+ limit: runConfig.review.releaseNotesLimit || 3
1710
+ });
1711
+ if (releaseNotesContent.trim()) {
1712
+ releaseNotesContext += `\n\n[Recent Release Notes]\n${releaseNotesContent}`;
1713
+ logger.debug('Added release notes to context (%d characters)', releaseNotesContent.length);
1714
+ }
1715
+ } catch (error) {
1716
+ const errorMsg = `Failed to fetch release notes: ${error.message}`;
1717
+ logger.warn(errorMsg);
1718
+ contextErrors.push(errorMsg);
1719
+ }
1720
+ }
1721
+ // Fetch GitHub issues if enabled
1722
+ if ((_runConfig_review3 = runConfig.review) === null || _runConfig_review3 === void 0 ? void 0 : _runConfig_review3.includeGithubIssues) {
1723
+ try {
1724
+ logger.debug('Fetching open GitHub issues...');
1725
+ issuesContext = await getIssuesContent({
1726
+ limit: runConfig.review.githubIssuesLimit || 20
1727
+ });
1728
+ if (issuesContext.trim()) {
1729
+ logger.debug('Added GitHub issues to context (%d characters)', issuesContext.length);
1730
+ }
1731
+ } catch (error) {
1732
+ const errorMsg = `Failed to fetch GitHub issues: ${error.message}`;
1733
+ logger.warn(errorMsg);
1734
+ contextErrors.push(errorMsg);
1735
+ }
1736
+ }
1737
+ // Report context gathering results
1738
+ if (contextErrors.length > 0) {
1739
+ var _runConfig_review6;
1740
+ logger.warn(`Context gathering completed with ${contextErrors.length} error(s):`);
1741
+ contextErrors.forEach((error)=>logger.warn(` - ${error}`));
1742
+ // For critical operations, consider failing if too many context sources fail
1743
+ const maxContextErrors = ((_runConfig_review6 = runConfig.review) === null || _runConfig_review6 === void 0 ? void 0 : _runConfig_review6.maxContextErrors) || contextErrors.length; // Default: allow all errors
1744
+ if (contextErrors.length > maxContextErrors) {
1745
+ throw new Error(`Too many context gathering errors (${contextErrors.length}), aborting review. Consider checking your configuration and network connectivity.`);
1746
+ }
1747
+ }
1748
+ // Analyze review note for issues using OpenAI
1749
+ logger.info('REVIEW_ANALYSIS_STARTING: Analyzing review note for project issues | Source: review note | Purpose: Identify actionable issues');
1750
+ logger.debug('Context summary:');
1751
+ logger.debug(' - Review note: %d chars', reviewNote.length);
1752
+ logger.debug(' - Log context: %d chars', logContext.length);
1753
+ logger.debug(' - Diff context: %d chars', diffContext.length);
1754
+ logger.debug(' - Release notes context: %d chars', releaseNotesContext.length);
1755
+ logger.debug(' - Issues context: %d chars', issuesContext.length);
1756
+ logger.debug(' - User context: %d chars', ((_runConfig_review4 = runConfig.review) === null || _runConfig_review4 === void 0 ? void 0 : (_runConfig_review_context = _runConfig_review4.context) === null || _runConfig_review_context === void 0 ? void 0 : _runConfig_review_context.length) || 0);
1757
+ const promptConfig = {
1758
+ overridePaths: runConfig.discoveredConfigDirs || [],
1759
+ overrides: runConfig.overrides || false
1760
+ };
1761
+ // Create adapters for ai-service
1762
+ const aiConfig = toAIConfig(runConfig);
1763
+ const aiStorageAdapter = createStorageAdapter(outputDirectory);
1764
+ const aiLogger = createLoggerAdapter(runConfig.dryRun || false);
1765
+ const promptContent = {
1766
+ notes: reviewNote
1767
+ };
1768
+ const promptContext = {
1769
+ context: (_runConfig_review5 = runConfig.review) === null || _runConfig_review5 === void 0 ? void 0 : _runConfig_review5.context,
1770
+ logContext,
1771
+ diffContext,
1772
+ releaseNotesContext,
1773
+ issuesContext
1774
+ };
1775
+ const prompt = await createReviewPrompt(promptConfig, promptContent, promptContext);
1776
+ const modelToUse = ((_aiConfig_commands = aiConfig.commands) === null || _aiConfig_commands === void 0 ? void 0 : (_aiConfig_commands_review = _aiConfig_commands.review) === null || _aiConfig_commands_review === void 0 ? void 0 : _aiConfig_commands_review.model) || aiConfig.model || 'gpt-4o-mini';
1777
+ const request = Formatter.create({
1778
+ logger
1779
+ }).formatPrompt(modelToUse, prompt);
1780
+ let analysisResult;
1781
+ try {
1782
+ var _aiConfig_commands_review1, _aiConfig_commands1, _rawAnalysisResult_issues;
1783
+ const rawResult = await createCompletion(request.messages, {
1784
+ model: modelToUse,
1785
+ openaiReasoning: ((_aiConfig_commands1 = aiConfig.commands) === null || _aiConfig_commands1 === void 0 ? void 0 : (_aiConfig_commands_review1 = _aiConfig_commands1.review) === null || _aiConfig_commands_review1 === void 0 ? void 0 : _aiConfig_commands_review1.reasoning) || aiConfig.reasoning,
1786
+ responseFormat: {
1787
+ type: 'json_object'
1788
+ },
1789
+ debug: runConfig.debug,
1790
+ debugRequestFile: getOutputPath(outputDirectory, getTimestampedRequestFilename('review-analysis')),
1791
+ debugResponseFile: getOutputPath(outputDirectory, getTimestampedResponseFilename('review-analysis')),
1792
+ storage: aiStorageAdapter,
1793
+ logger: aiLogger
1794
+ });
1795
+ // Validate the API response before using it
1796
+ const rawAnalysisResult = validateReviewResult(rawResult);
1797
+ // Apply stop-context filtering to issues
1798
+ analysisResult = {
1799
+ ...rawAnalysisResult,
1800
+ summary: filterContent(rawAnalysisResult.summary, runConfig.stopContext).filtered,
1801
+ issues: (_rawAnalysisResult_issues = rawAnalysisResult.issues) === null || _rawAnalysisResult_issues === void 0 ? void 0 : _rawAnalysisResult_issues.map((issue)=>({
1802
+ ...issue,
1803
+ title: filterContent(issue.title, runConfig.stopContext).filtered,
1804
+ description: filterContent(issue.description || '', runConfig.stopContext).filtered
1805
+ }))
1806
+ };
1807
+ } catch (error) {
1808
+ logger.error(`REVIEW_ANALYSIS_FAILED: Unable to analyze review note | Error: ${error.message} | Impact: Cannot identify issues`);
1809
+ throw new Error(`Review analysis failed: ${error.message}`);
1810
+ }
1811
+ logger.info('REVIEW_ANALYSIS_COMPLETE: Review note analysis completed successfully | Status: completed | Next: Issue creation if enabled');
1812
+ logger.debug('Analysis result summary: %s', analysisResult.summary);
1813
+ logger.debug('Total issues found: %d', analysisResult.totalIssues);
1814
+ logger.debug('Issues array length: %d', ((_analysisResult_issues = analysisResult.issues) === null || _analysisResult_issues === void 0 ? void 0 : _analysisResult_issues.length) || 0);
1815
+ if (analysisResult.issues && analysisResult.issues.length > 0) {
1816
+ analysisResult.issues.forEach((issue, index)=>{
1817
+ logger.debug(' Issue %d: [%s] %s', index + 1, issue.priority, issue.title);
1818
+ });
1819
+ }
1820
+ // Save timestamped copy of analysis result to output directory
1821
+ try {
1822
+ const reviewFilename = getTimestampedReviewFilename();
1823
+ const reviewPath = getOutputPath(outputDirectory, reviewFilename);
1824
+ // Format the analysis result as markdown
1825
+ const reviewContent = `# Review Analysis Result\n\n` + `## Summary\n${analysisResult.summary}\n\n` + `## Total Issues Found\n${analysisResult.totalIssues}\n\n` + `## Issues\n\n${JSON.stringify(analysisResult.issues, null, 2)}\n\n` + `---\n\n*Analysis completed at ${new Date().toISOString()}*`;
1826
+ await safeWriteFile(reviewPath, reviewContent);
1827
+ logger.debug('Saved timestamped review analysis: %s', reviewPath);
1828
+ } catch (error) {
1829
+ logger.warn('Failed to save timestamped review analysis: %s', error.message);
1830
+ // Don't fail the entire operation for this
1831
+ }
1832
+ return analysisResult;
1833
+ };
1834
+ const executeInternal$1 = async (runConfig)=>{
1835
+ var _runConfig_review, _runConfig_review1, _runConfig_review2, _runConfig_review3, _runConfig_review4, _runConfig_review5, _runConfig_review6, _runConfig_review7, _runConfig_review8, _runConfig_review9, _runConfig_review10, _runConfig_review11, _runConfig_review12, _runConfig_review13, _runConfig_review14, _runConfig_review15, _runConfig_review16, _runConfig_review17, _runConfig_review18;
1836
+ const logger = getLogger();
1837
+ const isDryRun = runConfig.dryRun || false;
1838
+ // Show configuration even in dry-run mode
1839
+ logger.debug('Review context configuration:');
1840
+ logger.debug(' Include commit history: %s', (_runConfig_review = runConfig.review) === null || _runConfig_review === void 0 ? void 0 : _runConfig_review.includeCommitHistory);
1841
+ logger.debug(' Include recent diffs: %s', (_runConfig_review1 = runConfig.review) === null || _runConfig_review1 === void 0 ? void 0 : _runConfig_review1.includeRecentDiffs);
1842
+ logger.debug(' Include release notes: %s', (_runConfig_review2 = runConfig.review) === null || _runConfig_review2 === void 0 ? void 0 : _runConfig_review2.includeReleaseNotes);
1843
+ logger.debug(' Include GitHub issues: %s', (_runConfig_review3 = runConfig.review) === null || _runConfig_review3 === void 0 ? void 0 : _runConfig_review3.includeGithubIssues);
1844
+ logger.debug(' Commit history limit: %d', (_runConfig_review4 = runConfig.review) === null || _runConfig_review4 === void 0 ? void 0 : _runConfig_review4.commitHistoryLimit);
1845
+ logger.debug(' Diff history limit: %d', (_runConfig_review5 = runConfig.review) === null || _runConfig_review5 === void 0 ? void 0 : _runConfig_review5.diffHistoryLimit);
1846
+ logger.debug(' Release notes limit: %d', (_runConfig_review6 = runConfig.review) === null || _runConfig_review6 === void 0 ? void 0 : _runConfig_review6.releaseNotesLimit);
1847
+ logger.debug(' GitHub issues limit: %d', (_runConfig_review7 = runConfig.review) === null || _runConfig_review7 === void 0 ? void 0 : _runConfig_review7.githubIssuesLimit);
1848
+ logger.debug(' Sendit mode (auto-create issues): %s', (_runConfig_review8 = runConfig.review) === null || _runConfig_review8 === void 0 ? void 0 : _runConfig_review8.sendit);
1849
+ logger.debug(' File: %s', ((_runConfig_review9 = runConfig.review) === null || _runConfig_review9 === void 0 ? void 0 : _runConfig_review9.file) || 'not specified');
1850
+ logger.debug(' Directory: %s', ((_runConfig_review10 = runConfig.review) === null || _runConfig_review10 === void 0 ? void 0 : _runConfig_review10.directory) || 'not specified');
1851
+ if (isDryRun) {
1852
+ var _runConfig_review19, _runConfig_review20, _runConfig_review21, _runConfig_review22, _runConfig_review23;
1853
+ if ((_runConfig_review19 = runConfig.review) === null || _runConfig_review19 === void 0 ? void 0 : _runConfig_review19.file) {
1854
+ logger.info('DRY RUN: Would read review note from file: %s', runConfig.review.file);
1855
+ } else if ((_runConfig_review20 = runConfig.review) === null || _runConfig_review20 === void 0 ? void 0 : _runConfig_review20.directory) {
1856
+ logger.info('DRY RUN: Would process review files in directory: %s', runConfig.review.directory);
1857
+ logger.info('DRY RUN: Would first select which files to process, then analyze selected files');
1858
+ } else if ((_runConfig_review21 = runConfig.review) === null || _runConfig_review21 === void 0 ? void 0 : _runConfig_review21.note) {
1859
+ logger.info('DRY RUN: Would analyze provided note for review');
1860
+ } else {
1861
+ logger.info('DRY RUN: Would open editor to capture review note');
1862
+ }
1863
+ logger.info('DRY RUN: Would gather additional context based on configuration above');
1864
+ logger.info('DRY RUN: Would analyze note and identify issues');
1865
+ if ((_runConfig_review22 = runConfig.review) === null || _runConfig_review22 === void 0 ? void 0 : _runConfig_review22.sendit) {
1866
+ logger.info('DRY RUN: Would automatically create GitHub issues (sendit mode enabled)');
1867
+ } else {
1868
+ logger.info('DRY RUN: Would prompt for confirmation before creating GitHub issues');
1869
+ }
1870
+ // Show what exclusion patterns would be used in dry-run mode
1871
+ if ((_runConfig_review23 = runConfig.review) === null || _runConfig_review23 === void 0 ? void 0 : _runConfig_review23.includeRecentDiffs) {
1872
+ var _runConfig_excludedPatterns;
1873
+ const basePatterns = (_runConfig_excludedPatterns = runConfig.excludedPatterns) !== null && _runConfig_excludedPatterns !== void 0 ? _runConfig_excludedPatterns : DEFAULT_EXCLUDED_PATTERNS;
1874
+ const reviewExcluded = Diff.getReviewExcludedPatterns(basePatterns);
1875
+ logger.info('DRY RUN: Would use %d exclusion patterns for diff context', reviewExcluded.length);
1876
+ logger.debug('DRY RUN: Sample exclusions: %s', reviewExcluded.slice(0, 15).join(', ') + (reviewExcluded.length > 15 ? '...' : ''));
1877
+ }
1878
+ return 'DRY RUN: Review command would analyze note, gather context, and create GitHub issues';
1879
+ }
1880
+ // Enhanced TTY check with proper error handling
1881
+ const isInteractive = isTTYSafe();
1882
+ if (!isInteractive && !((_runConfig_review11 = runConfig.review) === null || _runConfig_review11 === void 0 ? void 0 : _runConfig_review11.sendit)) {
1883
+ logger.error('❌ STDIN is piped but --sendit flag is not enabled');
1884
+ logger.error(' Interactive prompts cannot be used when input is piped');
1885
+ logger.error(' Solutions:');
1886
+ logger.error(' • Add --sendit flag to auto-create all issues');
1887
+ logger.error(' • Use terminal input instead of piping');
1888
+ logger.error(' • Example: echo "note" | kodrdriv review --sendit');
1889
+ throw new ValidationError('Piped input requires --sendit flag for non-interactive operation');
1890
+ }
1891
+ // Get the review note from configuration
1892
+ let reviewNote = (_runConfig_review12 = runConfig.review) === null || _runConfig_review12 === void 0 ? void 0 : _runConfig_review12.note;
1893
+ let reviewFiles = [];
1894
+ // Check if we should process a single file
1895
+ if ((_runConfig_review13 = runConfig.review) === null || _runConfig_review13 === void 0 ? void 0 : _runConfig_review13.file) {
1896
+ logger.info(`📁 Reading review note from file: ${runConfig.review.file}`);
1897
+ reviewNote = await readReviewNoteFromFile(runConfig.review.file);
1898
+ reviewFiles = [
1899
+ runConfig.review.file
1900
+ ];
1901
+ } else if ((_runConfig_review14 = runConfig.review) === null || _runConfig_review14 === void 0 ? void 0 : _runConfig_review14.directory) {
1902
+ var _runConfig_review24;
1903
+ logger.info(`📁 Processing review files in directory: ${runConfig.review.directory}`);
1904
+ reviewFiles = await getReviewFilesInDirectory(runConfig.review.directory);
1905
+ if (reviewFiles.length === 0) {
1906
+ throw new ValidationError(`No review files found in directory: ${runConfig.review.directory}`);
1907
+ }
1908
+ logger.info(`📁 Found ${reviewFiles.length} files to process`);
1909
+ // Set a dummy reviewNote for directory mode to satisfy validation
1910
+ // The actual review notes will be read from each file during processing
1911
+ reviewNote = `Processing ${reviewFiles.length} files from directory`;
1912
+ // If not in sendit mode, explain the two-phase process
1913
+ if (!((_runConfig_review24 = runConfig.review) === null || _runConfig_review24 === void 0 ? void 0 : _runConfig_review24.sendit)) {
1914
+ logger.info(`📝 Interactive mode: You will first select which files to process, then they will be analyzed in order.`);
1915
+ logger.info(`📝 Use --sendit to process all files automatically without confirmation.`);
1916
+ }
1917
+ } else if ((_runConfig_review15 = runConfig.review) === null || _runConfig_review15 === void 0 ? void 0 : _runConfig_review15.note) {
1918
+ reviewNote = runConfig.review.note;
1919
+ reviewFiles = [
1920
+ 'provided note'
1921
+ ];
1922
+ } else {
1923
+ // Open editor to capture review note
1924
+ const editor = process.env.EDITOR || process.env.VISUAL || 'vi';
1925
+ let tmpFilePath = null;
1926
+ try {
1927
+ var _runConfig_review25;
1928
+ // Create secure temporary file
1929
+ tmpFilePath = await createSecureTempFile();
1930
+ // Pre-populate the file with a helpful header so users know what to do.
1931
+ const templateContent = [
1932
+ '# Kodrdriv Review Note',
1933
+ '',
1934
+ '# Please enter your review note below. Lines starting with "#" will be ignored.',
1935
+ '# Save and close the editor when you are done.',
1936
+ '',
1937
+ ''
1938
+ ].join('\n');
1939
+ await safeWriteFile(tmpFilePath, templateContent);
1940
+ logger.info(`No review note provided – opening ${editor} to capture input...`);
1941
+ // Open the editor with optional timeout protection
1942
+ const editorTimeout = (_runConfig_review25 = runConfig.review) === null || _runConfig_review25 === void 0 ? void 0 : _runConfig_review25.editorTimeout; // No default timeout - let user take their time
1943
+ await openEditorWithTimeout(editor, tmpFilePath, editorTimeout);
1944
+ // Read the file back in, stripping comment lines and whitespace.
1945
+ const fileContent = (await fs.readFile(tmpFilePath, 'utf8')).split('\n').filter((line)=>!line.trim().startsWith('#')).join('\n').trim();
1946
+ if (!fileContent) {
1947
+ throw new ValidationError('Review note is empty – aborting. Provide a note as an argument, via STDIN, or through the editor.');
1948
+ }
1949
+ reviewNote = fileContent;
1950
+ // If the original runConfig.review object exists, update it so downstream code has the note.
1951
+ if (runConfig.review) {
1952
+ runConfig.review.note = reviewNote;
1953
+ }
1954
+ } catch (error) {
1955
+ logger.error(`Failed to capture review note via editor: ${error.message}`);
1956
+ throw error;
1957
+ } finally{
1958
+ // Always clean up the temp file
1959
+ if (tmpFilePath) {
1960
+ await cleanupTempFile(tmpFilePath);
1961
+ }
1962
+ }
1963
+ reviewFiles = [
1964
+ 'editor input'
1965
+ ];
1966
+ }
1967
+ if (!reviewNote || !reviewNote.trim()) {
1968
+ throw new ValidationError('No review note provided or captured');
1969
+ }
1970
+ logger.info('📝 Starting review analysis...');
1971
+ logger.debug('Review note: %s', reviewNote);
1972
+ logger.debug('Review note length: %d characters', reviewNote.length);
1973
+ const outputDirectory = runConfig.outputDirectory || DEFAULT_OUTPUT_DIRECTORY;
1974
+ const storage = createStorage();
1975
+ await storage.ensureDirectory(outputDirectory);
1976
+ // Save timestamped copy of review notes to output directory
1977
+ try {
1978
+ const reviewNotesFilename = getTimestampedReviewNotesFilename();
1979
+ const reviewNotesPath = getOutputPath(outputDirectory, reviewNotesFilename);
1980
+ const reviewNotesContent = `# Review Notes\n\n${reviewNote}\n\n`;
1981
+ await safeWriteFile(reviewNotesPath, reviewNotesContent);
1982
+ logger.debug('Saved timestamped review notes: %s', reviewNotesPath);
1983
+ } catch (error) {
1984
+ logger.warn('Failed to save review notes: %s', error.message);
1985
+ }
1986
+ // Phase 1: File selection (only for directory mode)
1987
+ let selectedFiles;
1988
+ if ((_runConfig_review16 = runConfig.review) === null || _runConfig_review16 === void 0 ? void 0 : _runConfig_review16.directory) {
1989
+ var _runConfig_review26;
1990
+ selectedFiles = await selectFilesForProcessing(reviewFiles, ((_runConfig_review26 = runConfig.review) === null || _runConfig_review26 === void 0 ? void 0 : _runConfig_review26.sendit) || false);
1991
+ } else {
1992
+ // For single note mode, just use the note directly
1993
+ selectedFiles = [
1994
+ 'single note'
1995
+ ];
1996
+ }
1997
+ // Phase 2: Process selected files in order
1998
+ logger.info(`\n📝 Starting analysis phase...`);
1999
+ const results = [];
2000
+ const processedFiles = [];
2001
+ if ((_runConfig_review17 = runConfig.review) === null || _runConfig_review17 === void 0 ? void 0 : _runConfig_review17.directory) {
2002
+ // Directory mode: process each selected file
2003
+ for(let i = 0; i < selectedFiles.length; i++){
2004
+ const filePath = selectedFiles[i];
2005
+ try {
2006
+ logger.info(`📝 Processing file ${i + 1}/${selectedFiles.length}: ${filePath}`);
2007
+ const fileNote = await readReviewNoteFromFile(filePath);
2008
+ const fileResult = await processSingleReview(fileNote, runConfig, outputDirectory);
2009
+ results.push(fileResult);
2010
+ processedFiles.push(filePath);
2011
+ } catch (error) {
2012
+ // Check if this is a critical error that should be propagated
2013
+ if (error.message.includes('Too many context gathering errors')) {
2014
+ throw error; // Propagate critical context errors
2015
+ }
2016
+ logger.warn(`Failed to process file ${filePath}: ${error.message}`);
2017
+ // Continue with other files for non-critical errors
2018
+ }
2019
+ }
2020
+ } else {
2021
+ // Single note mode: process the note directly
2022
+ try {
2023
+ logger.info(`📝 Processing single review note`);
2024
+ const fileResult = await processSingleReview(reviewNote, runConfig, outputDirectory);
2025
+ results.push(fileResult);
2026
+ processedFiles.push('single note');
2027
+ } catch (error) {
2028
+ logger.warn(`Failed to process review note: ${error.message}`);
2029
+ throw error; // Re-throw for single note mode since there's only one item
2030
+ }
2031
+ }
2032
+ if (results.length === 0) {
2033
+ throw new ValidationError('No files were processed successfully');
2034
+ }
2035
+ // Combine results if we processed multiple files
2036
+ let analysisResult;
2037
+ if (results.length === 1) {
2038
+ analysisResult = results[0];
2039
+ } else {
2040
+ logger.info(`✅ Successfully processed ${results.length} review files`);
2041
+ // Create a combined summary
2042
+ const totalIssues = results.reduce((sum, result)=>sum + result.totalIssues, 0);
2043
+ const allIssues = results.flatMap((result)=>result.issues || []);
2044
+ analysisResult = {
2045
+ summary: `Combined analysis of ${results.length} review files. Total issues found: ${totalIssues}`,
2046
+ totalIssues,
2047
+ issues: allIssues
2048
+ };
2049
+ // Save combined results
2050
+ try {
2051
+ const combinedFilename = getTimestampedReviewFilename();
2052
+ const combinedPath = getOutputPath(outputDirectory, combinedFilename);
2053
+ const combinedContent = `# Combined Review Analysis Result\n\n` + `## Summary\n${analysisResult.summary}\n\n` + `## Total Issues Found\n${totalIssues}\n\n` + `## Files Processed\n${processedFiles.join('\n')}\n\n` + `## Issues\n\n${JSON.stringify(allIssues, null, 2)}\n\n` + `---\n\n*Combined analysis completed at ${new Date().toISOString()}*`;
2054
+ await safeWriteFile(combinedPath, combinedContent);
2055
+ logger.debug('Saved combined review analysis: %s', combinedPath);
2056
+ } catch (error) {
2057
+ logger.warn('Failed to save combined review analysis: %s', error.message);
2058
+ }
2059
+ }
2060
+ // Handle GitHub issue creation using the issues module
2061
+ const senditMode = ((_runConfig_review18 = runConfig.review) === null || _runConfig_review18 === void 0 ? void 0 : _runConfig_review18.sendit) || false;
2062
+ return await handleIssueCreation(analysisResult, senditMode);
2063
+ };
2064
+ const execute$1 = async (runConfig)=>{
2065
+ try {
2066
+ return await executeInternal$1(runConfig);
2067
+ } catch (error) {
2068
+ const logger = getLogger();
2069
+ if (error instanceof ValidationError) {
2070
+ logger.error(`review failed: ${error.message}`);
2071
+ throw error;
2072
+ }
2073
+ if (error instanceof FileOperationError) {
2074
+ logger.error(`review failed: ${error.message}`);
2075
+ if (error.cause && typeof error.cause === 'object' && 'message' in error.cause) {
2076
+ logger.debug(`Caused by: ${error.cause.message}`);
2077
+ }
2078
+ throw error;
2079
+ }
2080
+ if (error instanceof CommandError) {
2081
+ logger.error(`review failed: ${error.message}`);
2082
+ if (error.cause && typeof error.cause === 'object' && 'message' in error.cause) {
2083
+ logger.debug(`Caused by: ${error.cause.message}`);
2084
+ }
2085
+ throw error;
2086
+ }
2087
+ // Unexpected errors
2088
+ logger.error(`review encountered unexpected error: ${error.message}`);
2089
+ throw error;
2090
+ }
2091
+ };
2092
+
2093
+ // Patterns for files that can be auto-resolved
2094
+ const AUTO_RESOLVABLE_PATTERNS = {
2095
+ // Package lock files - just regenerate
2096
+ packageLock: /^package-lock\.json$/,
2097
+ yarnLock: /^yarn\.lock$/,
2098
+ pnpmLock: /^pnpm-lock\.yaml$/,
2099
+ // Generated files - take theirs and regenerate
2100
+ dist: /^dist\//,
2101
+ coverage: /^coverage\//,
2102
+ nodeModules: /^node_modules\//,
2103
+ // Build artifacts
2104
+ buildOutput: /\.(js\.map|d\.ts)$/
2105
+ };
2106
+ /**
2107
+ * Check if a file can be auto-resolved
2108
+ */ function canAutoResolve(filename) {
2109
+ if (AUTO_RESOLVABLE_PATTERNS.packageLock.test(filename)) {
2110
+ return {
2111
+ canResolve: true,
2112
+ strategy: 'regenerate-lock'
2113
+ };
2114
+ }
2115
+ if (AUTO_RESOLVABLE_PATTERNS.yarnLock.test(filename)) {
2116
+ return {
2117
+ canResolve: true,
2118
+ strategy: 'regenerate-lock'
2119
+ };
2120
+ }
2121
+ if (AUTO_RESOLVABLE_PATTERNS.pnpmLock.test(filename)) {
2122
+ return {
2123
+ canResolve: true,
2124
+ strategy: 'regenerate-lock'
2125
+ };
2126
+ }
2127
+ if (AUTO_RESOLVABLE_PATTERNS.dist.test(filename)) {
2128
+ return {
2129
+ canResolve: true,
2130
+ strategy: 'take-theirs-regenerate'
2131
+ };
2132
+ }
2133
+ if (AUTO_RESOLVABLE_PATTERNS.coverage.test(filename)) {
2134
+ return {
2135
+ canResolve: true,
2136
+ strategy: 'take-theirs'
2137
+ };
2138
+ }
2139
+ if (AUTO_RESOLVABLE_PATTERNS.nodeModules.test(filename)) {
2140
+ return {
2141
+ canResolve: true,
2142
+ strategy: 'take-theirs'
2143
+ };
2144
+ }
2145
+ if (AUTO_RESOLVABLE_PATTERNS.buildOutput.test(filename)) {
2146
+ return {
2147
+ canResolve: true,
2148
+ strategy: 'take-theirs-regenerate'
2149
+ };
2150
+ }
2151
+ return {
2152
+ canResolve: false,
2153
+ strategy: 'manual'
2154
+ };
2155
+ }
2156
+ /**
2157
+ * Check if this is a package.json version conflict that can be auto-resolved
2158
+ */ async function tryResolvePackageJsonConflict(filepath, logger) {
2159
+ const storage = createStorage();
2160
+ try {
2161
+ const content = await storage.readFile(filepath, 'utf-8');
2162
+ // Check if this is actually a conflict file
2163
+ if (!content.includes('<<<<<<<') || !content.includes('>>>>>>>')) {
2164
+ return {
2165
+ resolved: false,
2166
+ error: 'Not a conflict file'
2167
+ };
2168
+ }
2169
+ // Try to parse ours and theirs versions
2170
+ const oursMatch = content.match(/<<<<<<< .*?\n([\s\S]*?)=======\n/);
2171
+ const theirsMatch = content.match(/=======\n([\s\S]*?)>>>>>>> /);
2172
+ if (!oursMatch || !theirsMatch) {
2173
+ return {
2174
+ resolved: false,
2175
+ error: 'Cannot parse conflict markers'
2176
+ };
2177
+ }
2178
+ // For package.json, if only version differs, take the higher version
2179
+ // This is a simplified heuristic - real conflicts may need more logic
2180
+ const oursPart = oursMatch[1];
2181
+ const theirsPart = theirsMatch[1];
2182
+ // Check if this is just a version conflict
2183
+ const versionPattern = /"version":\s*"([^"]+)"/;
2184
+ const oursVersion = oursPart.match(versionPattern);
2185
+ const theirsVersion = theirsPart.match(versionPattern);
2186
+ if (oursVersion && theirsVersion) {
2187
+ // Both have versions - take higher one
2188
+ const semver = await import('semver');
2189
+ const higher = semver.gt(oursVersion[1].replace(/-.*$/, ''), theirsVersion[1].replace(/-.*$/, '')) ? oursVersion[1] : theirsVersion[1];
2190
+ // Replace the conflicted version with the higher one
2191
+ let resolvedContent = content;
2192
+ // Simple approach: take theirs but use higher version
2193
+ // Remove conflict markers and use theirs as base
2194
+ resolvedContent = content.replace(/<<<<<<< .*?\n[\s\S]*?=======\n([\s\S]*?)>>>>>>> .*?\n/g, '$1');
2195
+ // Update version to higher one
2196
+ resolvedContent = resolvedContent.replace(/"version":\s*"[^"]+"/, `"version": "${higher}"`);
2197
+ await storage.writeFile(filepath, resolvedContent, 'utf-8');
2198
+ logger.info(`PULL_RESOLVED_VERSION: Auto-resolved version conflict | File: ${filepath} | Version: ${higher}`);
2199
+ return {
2200
+ resolved: true
2201
+ };
2202
+ }
2203
+ return {
2204
+ resolved: false,
2205
+ error: 'Complex conflict - not just version'
2206
+ };
2207
+ } catch (error) {
2208
+ return {
2209
+ resolved: false,
2210
+ error: error.message
2211
+ };
2212
+ }
2213
+ }
2214
+ /**
2215
+ * Resolve a single conflict file
2216
+ */ async function resolveConflict(filepath, strategy, logger, isDryRun) {
2217
+ if (isDryRun) {
2218
+ logger.info(`PULL_RESOLVE_DRY_RUN: Would resolve conflict | File: ${filepath} | Strategy: ${strategy}`);
2219
+ return {
2220
+ file: filepath,
2221
+ resolved: true,
2222
+ strategy
2223
+ };
2224
+ }
2225
+ try {
2226
+ switch(strategy){
2227
+ case 'regenerate-lock':
2228
+ {
2229
+ // Accept theirs and regenerate
2230
+ await runSecure('git', [
2231
+ 'checkout',
2232
+ '--theirs',
2233
+ filepath
2234
+ ]);
2235
+ await runSecure('git', [
2236
+ 'add',
2237
+ filepath
2238
+ ]);
2239
+ logger.info(`PULL_CONFLICT_RESOLVED: Accepted remote lock file | File: ${filepath} | Strategy: ${strategy} | Note: Will regenerate after pull`);
2240
+ return {
2241
+ file: filepath,
2242
+ resolved: true,
2243
+ strategy
2244
+ };
2245
+ }
2246
+ case 'take-theirs':
2247
+ case 'take-theirs-regenerate':
2248
+ {
2249
+ await runSecure('git', [
2250
+ 'checkout',
2251
+ '--theirs',
2252
+ filepath
2253
+ ]);
2254
+ await runSecure('git', [
2255
+ 'add',
2256
+ filepath
2257
+ ]);
2258
+ logger.info(`PULL_CONFLICT_RESOLVED: Accepted remote version | File: ${filepath} | Strategy: ${strategy}`);
2259
+ return {
2260
+ file: filepath,
2261
+ resolved: true,
2262
+ strategy
2263
+ };
2264
+ }
2265
+ case 'version-bump':
2266
+ {
2267
+ const result = await tryResolvePackageJsonConflict(filepath, logger);
2268
+ if (result.resolved) {
2269
+ await runSecure('git', [
2270
+ 'add',
2271
+ filepath
2272
+ ]);
2273
+ return {
2274
+ file: filepath,
2275
+ resolved: true,
2276
+ strategy
2277
+ };
2278
+ }
2279
+ return {
2280
+ file: filepath,
2281
+ resolved: false,
2282
+ strategy,
2283
+ error: result.error
2284
+ };
2285
+ }
2286
+ default:
2287
+ return {
2288
+ file: filepath,
2289
+ resolved: false,
2290
+ strategy,
2291
+ error: 'Unknown resolution strategy'
2292
+ };
2293
+ }
2294
+ } catch (error) {
2295
+ return {
2296
+ file: filepath,
2297
+ resolved: false,
2298
+ strategy,
2299
+ error: error.message
2300
+ };
2301
+ }
2302
+ }
2303
+ /**
2304
+ * Get list of conflicted files
2305
+ */ async function getConflictedFiles() {
2306
+ try {
2307
+ const { stdout } = await runSecure('git', [
2308
+ 'diff',
2309
+ '--name-only',
2310
+ '--diff-filter=U'
2311
+ ]);
2312
+ return stdout.trim().split('\n').filter((f)=>f.trim());
2313
+ } catch {
2314
+ return [];
2315
+ }
2316
+ }
2317
+ /**
2318
+ * Try to auto-resolve all conflicts
2319
+ */ async function autoResolveConflicts(logger, isDryRun) {
2320
+ const conflictedFiles = await getConflictedFiles();
2321
+ const resolved = [];
2322
+ const manual = [];
2323
+ for (const file of conflictedFiles){
2324
+ const { canResolve, strategy } = canAutoResolve(file);
2325
+ // Special handling for package.json
2326
+ if (file === 'package.json' || file.endsWith('/package.json')) {
2327
+ const result = await resolveConflict(file, 'version-bump', logger, isDryRun);
2328
+ if (result.resolved) {
2329
+ resolved.push(file);
2330
+ } else {
2331
+ manual.push(file);
2332
+ }
2333
+ continue;
2334
+ }
2335
+ if (canResolve) {
2336
+ const result = await resolveConflict(file, strategy, logger, isDryRun);
2337
+ if (result.resolved) {
2338
+ resolved.push(file);
2339
+ } else {
2340
+ manual.push(file);
2341
+ }
2342
+ } else {
2343
+ manual.push(file);
2344
+ }
2345
+ }
2346
+ return {
2347
+ resolved,
2348
+ manual
2349
+ };
2350
+ }
2351
+ /**
2352
+ * Stash local changes if any
2353
+ */ async function stashIfNeeded(logger, isDryRun) {
2354
+ const status = await getGitStatusSummary();
2355
+ if (status.hasUncommittedChanges || status.hasUnstagedFiles) {
2356
+ const changeCount = status.uncommittedCount + status.unstagedCount;
2357
+ logger.info(`PULL_STASHING: Stashing ${changeCount} local changes before pull | Staged: ${status.uncommittedCount} | Unstaged: ${status.unstagedCount}`);
2358
+ if (!isDryRun) {
2359
+ await runSecure('git', [
2360
+ 'stash',
2361
+ 'push',
2362
+ '-m',
2363
+ `kodrdriv-pull-auto-stash-${Date.now()}`
2364
+ ]);
2365
+ }
2366
+ return true;
2367
+ }
2368
+ return false;
2369
+ }
2370
+ /**
2371
+ * Apply stash if we created one
2372
+ */ async function applyStashIfNeeded(didStash, logger, isDryRun) {
2373
+ if (!didStash) return false;
2374
+ logger.info('PULL_STASH_POP: Restoring stashed changes');
2375
+ if (!isDryRun) {
2376
+ try {
2377
+ await runSecure('git', [
2378
+ 'stash',
2379
+ 'pop'
2380
+ ]);
2381
+ return true;
2382
+ } catch (error) {
2383
+ logger.warn(`PULL_STASH_CONFLICT: Stash pop had conflicts | Error: ${error.message} | Action: Stash preserved, manual intervention needed`);
2384
+ // Don't fail - user can manually resolve stash conflicts
2385
+ return false;
2386
+ }
2387
+ }
2388
+ return true;
2389
+ }
2390
+ /**
2391
+ * Regenerate lock files after pull
2392
+ */ async function regenerateLockFiles(resolvedFiles, logger, isDryRun) {
2393
+ const needsRegenerate = resolvedFiles.some((f)=>f === 'package-lock.json' || f.endsWith('/package-lock.json'));
2394
+ if (needsRegenerate) {
2395
+ logger.info('PULL_REGENERATE_LOCK: Regenerating package-lock.json');
2396
+ if (!isDryRun) {
2397
+ try {
2398
+ await run('npm install');
2399
+ logger.info('PULL_REGENERATE_SUCCESS: Lock file regenerated successfully');
2400
+ } catch (error) {
2401
+ logger.warn(`PULL_REGENERATE_FAILED: Failed to regenerate lock file | Error: ${error.message}`);
2402
+ }
2403
+ }
2404
+ }
2405
+ }
2406
+ /**
2407
+ * Main pull execution
2408
+ */ async function executePull(remote, branch, logger, isDryRun) {
2409
+ const currentBranch = await getCurrentBranch();
2410
+ const targetBranch = branch || currentBranch;
2411
+ logger.info(`PULL_STARTING: Pulling changes | Remote: ${remote} | Branch: ${targetBranch} | Current: ${currentBranch}`);
2412
+ // Step 1: Stash any local changes
2413
+ const didStash = await stashIfNeeded(logger, isDryRun);
2414
+ // Step 2: Fetch first to see what's coming
2415
+ logger.info(`PULL_FETCH: Fetching from ${remote}`);
2416
+ if (!isDryRun) {
2417
+ try {
2418
+ await runSecure('git', [
2419
+ 'fetch',
2420
+ remote,
2421
+ targetBranch
2422
+ ]);
2423
+ } catch (error) {
2424
+ logger.error(`PULL_FETCH_FAILED: Failed to fetch | Error: ${error.message}`);
2425
+ if (didStash) await applyStashIfNeeded(true, logger, isDryRun);
2426
+ return {
2427
+ success: false,
2428
+ hadConflicts: false,
2429
+ autoResolved: [],
2430
+ manualRequired: [],
2431
+ stashApplied: didStash,
2432
+ strategy: 'failed',
2433
+ message: `Fetch failed: ${error.message}`
2434
+ };
2435
+ }
2436
+ }
2437
+ // Step 3: Try fast-forward first
2438
+ logger.info('PULL_STRATEGY: Attempting fast-forward merge');
2439
+ if (!isDryRun) {
2440
+ try {
2441
+ await runSecure('git', [
2442
+ 'merge',
2443
+ '--ff-only',
2444
+ `${remote}/${targetBranch}`
2445
+ ]);
2446
+ await applyStashIfNeeded(didStash, logger, isDryRun);
2447
+ logger.info('PULL_SUCCESS: Fast-forward merge successful');
2448
+ return {
2449
+ success: true,
2450
+ hadConflicts: false,
2451
+ autoResolved: [],
2452
+ manualRequired: [],
2453
+ stashApplied: didStash,
2454
+ strategy: 'fast-forward',
2455
+ message: 'Fast-forward merge successful'
2456
+ };
2457
+ } catch {
2458
+ logger.info('PULL_FF_FAILED: Fast-forward not possible, trying rebase');
2459
+ }
2460
+ }
2461
+ // Step 4: Try rebase
2462
+ logger.info('PULL_STRATEGY: Attempting rebase');
2463
+ if (!isDryRun) {
2464
+ try {
2465
+ await runSecure('git', [
2466
+ 'rebase',
2467
+ `${remote}/${targetBranch}`
2468
+ ]);
2469
+ await applyStashIfNeeded(didStash, logger, isDryRun);
2470
+ logger.info('PULL_SUCCESS: Rebase successful');
2471
+ return {
2472
+ success: true,
2473
+ hadConflicts: false,
2474
+ autoResolved: [],
2475
+ manualRequired: [],
2476
+ stashApplied: didStash,
2477
+ strategy: 'rebase',
2478
+ message: 'Rebase successful'
2479
+ };
2480
+ } catch {
2481
+ // Check if rebase is in progress with conflicts
2482
+ const conflictedFiles = await getConflictedFiles();
2483
+ if (conflictedFiles.length > 0) {
2484
+ logger.info(`PULL_CONFLICTS: Rebase has ${conflictedFiles.length} conflicts, attempting auto-resolution`);
2485
+ // Step 5: Try to auto-resolve conflicts
2486
+ const { resolved, manual } = await autoResolveConflicts(logger, isDryRun);
2487
+ if (manual.length === 0) {
2488
+ // All conflicts resolved, continue rebase
2489
+ logger.info('PULL_ALL_RESOLVED: All conflicts auto-resolved, continuing rebase');
2490
+ try {
2491
+ await runSecure('git', [
2492
+ 'rebase',
2493
+ '--continue'
2494
+ ]);
2495
+ await regenerateLockFiles(resolved, logger, isDryRun);
2496
+ await applyStashIfNeeded(didStash, logger, isDryRun);
2497
+ return {
2498
+ success: true,
2499
+ hadConflicts: true,
2500
+ autoResolved: resolved,
2501
+ manualRequired: [],
2502
+ stashApplied: didStash,
2503
+ strategy: 'rebase',
2504
+ message: `Rebase successful with ${resolved.length} auto-resolved conflicts`
2505
+ };
2506
+ } catch (continueError) {
2507
+ logger.warn(`PULL_CONTINUE_FAILED: Rebase continue failed | Error: ${continueError.message}`);
2508
+ }
2509
+ } else {
2510
+ // Some conflicts need manual resolution
2511
+ logger.warn(`PULL_MANUAL_REQUIRED: ${manual.length} conflicts require manual resolution`);
2512
+ logger.warn('PULL_MANUAL_FILES: Files needing manual resolution:');
2513
+ manual.forEach((f)=>logger.warn(` - ${f}`));
2514
+ logger.info('PULL_HINT: After resolving conflicts manually, run: git rebase --continue');
2515
+ // Keep rebase in progress so user can finish
2516
+ return {
2517
+ success: false,
2518
+ hadConflicts: true,
2519
+ autoResolved: resolved,
2520
+ manualRequired: manual,
2521
+ stashApplied: false,
2522
+ strategy: 'rebase',
2523
+ message: `Rebase paused: ${manual.length} files need manual conflict resolution`
2524
+ };
2525
+ }
2526
+ } else {
2527
+ // Rebase failed for other reason, abort and try merge
2528
+ logger.info('PULL_REBASE_ABORT: Rebase failed, aborting and trying merge');
2529
+ try {
2530
+ await runSecure('git', [
2531
+ 'rebase',
2532
+ '--abort'
2533
+ ]);
2534
+ } catch {
2535
+ // Ignore abort errors
2536
+ }
2537
+ }
2538
+ }
2539
+ }
2540
+ // Step 6: Fall back to regular merge
2541
+ logger.info('PULL_STRATEGY: Attempting merge');
2542
+ if (!isDryRun) {
2543
+ try {
2544
+ await runSecure('git', [
2545
+ 'merge',
2546
+ `${remote}/${targetBranch}`
2547
+ ]);
2548
+ await applyStashIfNeeded(didStash, logger, isDryRun);
2549
+ logger.info('PULL_SUCCESS: Merge successful');
2550
+ return {
2551
+ success: true,
2552
+ hadConflicts: false,
2553
+ autoResolved: [],
2554
+ manualRequired: [],
2555
+ stashApplied: didStash,
2556
+ strategy: 'merge',
2557
+ message: 'Merge successful'
2558
+ };
2559
+ } catch {
2560
+ // Check for merge conflicts
2561
+ const conflictedFiles = await getConflictedFiles();
2562
+ if (conflictedFiles.length > 0) {
2563
+ logger.info(`PULL_CONFLICTS: Merge has ${conflictedFiles.length} conflicts, attempting auto-resolution`);
2564
+ const { resolved, manual } = await autoResolveConflicts(logger, isDryRun);
2565
+ if (manual.length === 0) {
2566
+ // All conflicts resolved, commit the merge
2567
+ logger.info('PULL_ALL_RESOLVED: All conflicts auto-resolved, completing merge');
2568
+ try {
2569
+ await runSecure('git', [
2570
+ 'commit',
2571
+ '-m',
2572
+ `Merge ${remote}/${targetBranch} (auto-resolved by kodrdriv)`
2573
+ ]);
2574
+ await regenerateLockFiles(resolved, logger, isDryRun);
2575
+ await applyStashIfNeeded(didStash, logger, isDryRun);
2576
+ return {
2577
+ success: true,
2578
+ hadConflicts: true,
2579
+ autoResolved: resolved,
2580
+ manualRequired: [],
2581
+ stashApplied: didStash,
2582
+ strategy: 'merge',
2583
+ message: `Merge successful with ${resolved.length} auto-resolved conflicts`
2584
+ };
2585
+ } catch (commitError) {
2586
+ logger.error(`PULL_COMMIT_FAILED: Merge commit failed | Error: ${commitError.message}`);
2587
+ }
2588
+ } else {
2589
+ logger.warn(`PULL_MANUAL_REQUIRED: ${manual.length} conflicts require manual resolution`);
2590
+ manual.forEach((f)=>logger.warn(` - ${f}`));
2591
+ logger.info('PULL_HINT: After resolving conflicts manually, run: git commit');
2592
+ return {
2593
+ success: false,
2594
+ hadConflicts: true,
2595
+ autoResolved: resolved,
2596
+ manualRequired: manual,
2597
+ stashApplied: false,
2598
+ strategy: 'merge',
2599
+ message: `Merge paused: ${manual.length} files need manual conflict resolution`
2600
+ };
2601
+ }
2602
+ }
2603
+ }
2604
+ }
2605
+ // If we got here, something went wrong
2606
+ if (didStash) {
2607
+ logger.warn('PULL_STASH_PRESERVED: Local changes still stashed, use "git stash pop" to restore');
2608
+ }
2609
+ return {
2610
+ success: false,
2611
+ hadConflicts: false,
2612
+ autoResolved: [],
2613
+ manualRequired: [],
2614
+ stashApplied: false,
2615
+ strategy: 'failed',
2616
+ message: 'Pull failed - unable to merge or rebase'
2617
+ };
2618
+ }
2619
+ /**
2620
+ * Internal execution
2621
+ */ const executeInternal = async (runConfig)=>{
2622
+ const isDryRun = runConfig.dryRun || false;
2623
+ const logger = getDryRunLogger(isDryRun);
2624
+ // Get pull configuration
2625
+ const pullConfig = runConfig.pull || {};
2626
+ const remote = pullConfig.remote || 'origin';
2627
+ const branch = pullConfig.branch;
2628
+ // Execute pull
2629
+ const result = await executePull(remote, branch, logger, isDryRun);
2630
+ // Format output
2631
+ const lines = [];
2632
+ lines.push('');
2633
+ lines.push('═'.repeat(60));
2634
+ lines.push(result.success ? '✅ PULL COMPLETE' : '⚠️ PULL NEEDS ATTENTION');
2635
+ lines.push('═'.repeat(60));
2636
+ lines.push('');
2637
+ lines.push(`Strategy: ${result.strategy}`);
2638
+ lines.push(`Message: ${result.message}`);
2639
+ if (result.hadConflicts) {
2640
+ lines.push('');
2641
+ lines.push(`Conflicts detected: ${result.autoResolved.length + result.manualRequired.length}`);
2642
+ if (result.autoResolved.length > 0) {
2643
+ lines.push(`✓ Auto-resolved: ${result.autoResolved.length}`);
2644
+ result.autoResolved.forEach((f)=>lines.push(` - ${f}`));
2645
+ }
2646
+ if (result.manualRequired.length > 0) {
2647
+ lines.push(`✗ Manual resolution needed: ${result.manualRequired.length}`);
2648
+ result.manualRequired.forEach((f)=>lines.push(` - ${f}`));
2649
+ }
2650
+ }
2651
+ if (result.stashApplied) {
2652
+ lines.push('');
2653
+ lines.push('ℹ️ Local changes have been restored from stash');
2654
+ }
2655
+ lines.push('');
2656
+ lines.push('═'.repeat(60));
2657
+ const output = lines.join('\n');
2658
+ logger.info(output);
2659
+ return output;
2660
+ };
2661
+ /**
2662
+ * Execute pull command
2663
+ */ const execute = async (runConfig)=>{
2664
+ try {
2665
+ return await executeInternal(runConfig);
2666
+ } catch (error) {
2667
+ const logger = getLogger();
2668
+ logger.error(`PULL_COMMAND_FAILED: Pull command failed | Error: ${error.message}`);
2669
+ throw error;
2670
+ }
2671
+ };
2672
+
2673
+ const logger = getLogger();
2674
+ // Cache file to store test run timestamps per package
2675
+ const TEST_CACHE_FILE = '.kodrdriv-test-cache.json';
2676
+ /**
2677
+ * Load test cache from disk
2678
+ */ async function loadTestCache(packageDir) {
2679
+ const cachePath = path.join(packageDir, TEST_CACHE_FILE);
2680
+ try {
2681
+ const content = await fs.readFile(cachePath, 'utf-8');
2682
+ return JSON.parse(content);
2683
+ } catch {
2684
+ return {};
2685
+ }
2686
+ }
2687
+ /**
2688
+ * Save test cache to disk
2689
+ */ async function saveTestCache(packageDir, cache) {
2690
+ const cachePath = path.join(packageDir, TEST_CACHE_FILE);
2691
+ try {
2692
+ await fs.writeFile(cachePath, JSON.stringify(cache, null, 2), 'utf-8');
2693
+ } catch (error) {
2694
+ logger.debug(`Failed to save test cache: ${error.message}`);
2695
+ }
2696
+ }
2697
+ /**
2698
+ * Get the current git commit hash
2699
+ */ async function getCurrentCommitHash(packageDir) {
2700
+ try {
2701
+ const { stdout } = await runSecure('git', [
2702
+ 'rev-parse',
2703
+ 'HEAD'
2704
+ ], {
2705
+ cwd: packageDir
2706
+ });
2707
+ return stdout.trim();
2708
+ } catch {
2709
+ return null;
2710
+ }
2711
+ }
2712
+ /**
2713
+ * Check if source files have changed since the last test run
2714
+ */ async function hasSourceFilesChanged(packageDir, lastCommitHash) {
2715
+ if (!lastCommitHash) {
2716
+ return {
2717
+ changed: true,
2718
+ reason: 'No previous test run recorded'
2719
+ };
2720
+ }
2721
+ try {
2722
+ // Get current commit hash
2723
+ const currentCommitHash = await getCurrentCommitHash(packageDir);
2724
+ if (!currentCommitHash) {
2725
+ return {
2726
+ changed: true,
2727
+ reason: 'Not in a git repository'
2728
+ };
2729
+ }
2730
+ // If commit hash changed, files definitely changed
2731
+ if (currentCommitHash !== lastCommitHash) {
2732
+ return {
2733
+ changed: true,
2734
+ reason: `Commit hash changed: ${lastCommitHash.substring(0, 7)} -> ${currentCommitHash.substring(0, 7)}`
2735
+ };
2736
+ }
2737
+ // Check if there are any uncommitted changes to source files
2738
+ const { stdout } = await runSecure('git', [
2739
+ 'status',
2740
+ '--porcelain'
2741
+ ], {
2742
+ cwd: packageDir
2743
+ });
2744
+ const changedFiles = stdout.split('\n').filter((line)=>line.trim()).map((line)=>line.substring(3).trim()).filter((file)=>{
2745
+ // Only consider source files, not build artifacts or config files
2746
+ const ext = path.extname(file);
2747
+ return(// TypeScript/JavaScript source files
2748
+ [
2749
+ '.ts',
2750
+ '.tsx',
2751
+ '.js',
2752
+ '.jsx'
2753
+ ].includes(ext) || // Test files
2754
+ file.includes('.test.') || file.includes('.spec.') || // Config files that affect build/test
2755
+ [
2756
+ 'tsconfig.json',
2757
+ 'vite.config.ts',
2758
+ 'vitest.config.ts',
2759
+ 'package.json'
2760
+ ].includes(path.basename(file)));
2761
+ });
2762
+ if (changedFiles.length > 0) {
2763
+ return {
2764
+ changed: true,
2765
+ reason: `Uncommitted changes in: ${changedFiles.slice(0, 3).join(', ')}${changedFiles.length > 3 ? '...' : ''}`
2766
+ };
2767
+ }
2768
+ return {
2769
+ changed: false,
2770
+ reason: 'No source file changes detected'
2771
+ };
2772
+ } catch (error) {
2773
+ logger.debug(`Error checking for source file changes: ${error.message}`);
2774
+ // Conservative: assume changed if we can't verify
2775
+ return {
2776
+ changed: true,
2777
+ reason: `Could not verify changes: ${error.message}`
2778
+ };
2779
+ }
2780
+ }
2781
+ /**
2782
+ * Check if dist directory needs to be cleaned (is outdated compared to source files)
2783
+ */ async function isCleanNeeded(packageDir) {
2784
+ const storage = createStorage();
2785
+ const distPath = path.join(packageDir, 'dist');
2786
+ try {
2787
+ // Check if dist directory exists
2788
+ const distExists = await storage.exists('dist');
2789
+ if (!distExists) {
2790
+ return {
2791
+ needed: false,
2792
+ reason: 'dist directory does not exist'
2793
+ };
2794
+ }
2795
+ // Get dist directory modification time
2796
+ const distStats = await fs.stat(distPath);
2797
+ const distMtime = distStats.mtimeMs;
2798
+ // Use git to find source files that are newer than dist
2799
+ try {
2800
+ // Get all tracked source files
2801
+ const { stdout: trackedFiles } = await runSecure('git', [
2802
+ 'ls-files'
2803
+ ], {
2804
+ cwd: packageDir
2805
+ });
2806
+ const files = trackedFiles.split('\n').filter(Boolean);
2807
+ // Check if any source files are newer than dist
2808
+ for (const file of files){
2809
+ const ext = path.extname(file);
2810
+ if (![
2811
+ '.ts',
2812
+ '.tsx',
2813
+ '.js',
2814
+ '.jsx',
2815
+ '.json'
2816
+ ].includes(ext)) {
2817
+ continue;
2818
+ }
2819
+ // Skip dist files
2820
+ if (file.startsWith('dist/')) {
2821
+ continue;
2822
+ }
2823
+ try {
2824
+ const filePath = path.join(packageDir, file);
2825
+ const fileStats = await fs.stat(filePath);
2826
+ if (fileStats.mtimeMs > distMtime) {
2827
+ return {
2828
+ needed: true,
2829
+ reason: `${file} is newer than dist directory`
2830
+ };
2831
+ }
2832
+ } catch {
2833
+ continue;
2834
+ }
2835
+ }
2836
+ return {
2837
+ needed: false,
2838
+ reason: 'dist directory is up to date with source files'
2839
+ };
2840
+ } catch (error) {
2841
+ // If git check fails, fall back to checking common source directories
2842
+ logger.debug(`Git-based check failed, using fallback: ${error.message}`);
2843
+ const sourceDirs = [
2844
+ 'src',
2845
+ 'tests'
2846
+ ];
2847
+ for (const dir of sourceDirs){
2848
+ const dirPath = path.join(packageDir, dir);
2849
+ try {
2850
+ const dirStats = await fs.stat(dirPath);
2851
+ if (dirStats.mtimeMs > distMtime) {
2852
+ return {
2853
+ needed: true,
2854
+ reason: `${dir} directory is newer than dist`
2855
+ };
2856
+ }
2857
+ } catch {
2858
+ continue;
2859
+ }
2860
+ }
2861
+ // Conservative: if we can't verify, assume clean is needed
2862
+ return {
2863
+ needed: true,
2864
+ reason: 'Could not verify dist freshness, cleaning to be safe'
2865
+ };
2866
+ }
2867
+ } catch (error) {
2868
+ logger.debug(`Error checking if clean is needed: ${error.message}`);
2869
+ // Conservative: assume clean is needed if we can't check
2870
+ return {
2871
+ needed: true,
2872
+ reason: `Could not verify: ${error.message}`
2873
+ };
2874
+ }
2875
+ }
2876
+ /**
2877
+ * Check if tests need to be run (source files changed since last test run)
2878
+ */ async function isTestNeeded(packageDir) {
2879
+ try {
2880
+ // Load test cache
2881
+ const cache = await loadTestCache(packageDir);
2882
+ const cacheKey = packageDir;
2883
+ // Check if we have a cached test run for this package
2884
+ const cached = cache[cacheKey];
2885
+ if (!cached) {
2886
+ return {
2887
+ needed: true,
2888
+ reason: 'No previous test run recorded'
2889
+ };
2890
+ }
2891
+ // Check if source files have changed since last test run
2892
+ const changeCheck = await hasSourceFilesChanged(packageDir, cached.lastCommitHash);
2893
+ if (changeCheck.changed) {
2894
+ return {
2895
+ needed: true,
2896
+ reason: changeCheck.reason
2897
+ };
2898
+ }
2899
+ return {
2900
+ needed: false,
2901
+ reason: 'No source file changes since last test run'
2902
+ };
2903
+ } catch (error) {
2904
+ logger.debug(`Error checking if test is needed: ${error.message}`);
2905
+ // Conservative: assume test is needed if we can't check
2906
+ return {
2907
+ needed: true,
2908
+ reason: `Could not verify: ${error.message}`
2909
+ };
2910
+ }
2911
+ }
2912
+ /**
2913
+ * Record that tests were run for this package
2914
+ */ async function recordTestRun(packageDir) {
2915
+ try {
2916
+ const cache = await loadTestCache(packageDir);
2917
+ const cacheKey = packageDir;
2918
+ const commitHash = await getCurrentCommitHash(packageDir);
2919
+ cache[cacheKey] = {
2920
+ lastTestRun: Date.now(),
2921
+ lastCommitHash: commitHash || 'unknown'
2922
+ };
2923
+ await saveTestCache(packageDir, cache);
2924
+ } catch (error) {
2925
+ logger.debug(`Failed to record test run: ${error.message}`);
2926
+ }
2927
+ }
2928
+ /**
2929
+ * Optimize a precommit command by skipping unnecessary steps
2930
+ * Returns the optimized command and information about what was skipped
2931
+ */ async function optimizePrecommitCommand(packageDir, originalCommand, options = {}) {
2932
+ const { skipClean = true, skipTest = true } = options;
2933
+ // Parse the original command to extract individual scripts
2934
+ // Common patterns: "npm run precommit", "npm run clean && npm run build && npm run lint && npm run test"
2935
+ const isPrecommitScript = originalCommand.includes('precommit') || originalCommand.includes('pre-commit');
2936
+ let optimizedCommand = originalCommand;
2937
+ const skipped = {
2938
+ clean: false,
2939
+ test: false
2940
+ };
2941
+ const reasons = {};
2942
+ // If it's a precommit script, we need to check what it actually runs
2943
+ // For now, we'll optimize the common pattern: clean && build && lint && test
2944
+ if (isPrecommitScript || originalCommand.includes('clean')) {
2945
+ if (skipClean) {
2946
+ const cleanCheck = await isCleanNeeded(packageDir);
2947
+ if (!cleanCheck.needed) {
2948
+ // Remove clean from the command
2949
+ optimizedCommand = optimizedCommand.replace(/npm\s+run\s+clean\s+&&\s*/g, '').replace(/npm\s+run\s+clean\s+/g, '').replace(/\s*&&\s*npm\s+run\s+clean/g, '').trim();
2950
+ skipped.clean = true;
2951
+ reasons.clean = cleanCheck.reason;
2952
+ }
2953
+ }
2954
+ }
2955
+ if (isPrecommitScript || originalCommand.includes('test')) {
2956
+ if (skipTest) {
2957
+ const testCheck = await isTestNeeded(packageDir);
2958
+ if (!testCheck.needed) {
2959
+ // Remove test from the command
2960
+ optimizedCommand = optimizedCommand.replace(/\s*&&\s*npm\s+run\s+test\s*/g, '').replace(/\s*&&\s*npm\s+run\s+test$/g, '').replace(/npm\s+run\s+test\s+&&\s*/g, '').trim();
2961
+ skipped.test = true;
2962
+ reasons.test = testCheck.reason;
2963
+ }
2964
+ }
2965
+ }
2966
+ // Clean up any double && or trailing &&
2967
+ optimizedCommand = optimizedCommand.replace(/\s*&&\s*&&/g, ' && ').replace(/&&\s*$/, '').trim();
2968
+ return {
2969
+ optimizedCommand,
2970
+ skipped,
2971
+ reasons
2972
+ };
2973
+ }
2974
+
2975
+ export { PerformanceTimer, batchReadPackageJsonFiles, checkForFileDependencies, execute$2 as clean, collectAllDependencies, execute$4 as commit, findAllPackageJsonFiles, findPackagesByScope, isCleanNeeded, isTestNeeded, optimizePrecommitCommand, execute$3 as precommit, execute as pull, recordTestRun, execute$1 as review, scanDirectoryForPackages };
2976
+ //# sourceMappingURL=index.js.map