cadr-cli 2.0.0 → 2.0.2

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.
Files changed (153) hide show
  1. package/dist/adr/adr.d.ts +17 -0
  2. package/dist/adr/adr.d.ts.map +1 -0
  3. package/dist/{adr.js → adr/adr.js} +4 -44
  4. package/dist/adr/adr.js.map +1 -0
  5. package/dist/adr/adr.test.d.ts +5 -0
  6. package/dist/{adr.test.d.ts.map → adr/adr.test.d.ts.map} +1 -1
  7. package/dist/{adr.test.js → adr/adr.test.js} +0 -14
  8. package/dist/adr/adr.test.js.map +1 -0
  9. package/dist/adr/index.d.ts +2 -0
  10. package/dist/adr/index.d.ts.map +1 -0
  11. package/dist/adr/index.js +18 -0
  12. package/dist/adr/index.js.map +1 -0
  13. package/dist/analysis/analysis.orchestrator.d.ts +14 -0
  14. package/dist/analysis/analysis.orchestrator.d.ts.map +1 -0
  15. package/dist/analysis/analysis.orchestrator.js +175 -0
  16. package/dist/analysis/analysis.orchestrator.js.map +1 -0
  17. package/dist/analysis/analysis.orchestrator.test.d.ts +2 -0
  18. package/dist/analysis/analysis.orchestrator.test.d.ts.map +1 -0
  19. package/dist/analysis/analysis.orchestrator.test.js +177 -0
  20. package/dist/analysis/analysis.orchestrator.test.js.map +1 -0
  21. package/dist/analysis/strategies/git-strategy.d.ts +22 -0
  22. package/dist/analysis/strategies/git-strategy.d.ts.map +1 -0
  23. package/dist/analysis/strategies/git-strategy.js +114 -0
  24. package/dist/analysis/strategies/git-strategy.js.map +1 -0
  25. package/dist/analysis/strategies/git-strategy.test.d.ts +2 -0
  26. package/dist/analysis/strategies/git-strategy.test.d.ts.map +1 -0
  27. package/dist/analysis/strategies/git-strategy.test.js +147 -0
  28. package/dist/analysis/strategies/git-strategy.test.js.map +1 -0
  29. package/dist/commands/analyze.js +3 -3
  30. package/dist/commands/analyze.js.map +1 -1
  31. package/dist/commands/analyze.test.d.ts +2 -0
  32. package/dist/commands/analyze.test.d.ts.map +1 -0
  33. package/dist/commands/analyze.test.js +70 -0
  34. package/dist/commands/analyze.test.js.map +1 -0
  35. package/dist/commands/init.test.js +128 -2
  36. package/dist/commands/init.test.js.map +1 -1
  37. package/dist/config.test.js +167 -0
  38. package/dist/config.test.js.map +1 -1
  39. package/dist/git/git.errors.d.ts +6 -0
  40. package/dist/git/git.errors.d.ts.map +1 -0
  41. package/dist/git/git.errors.js +15 -0
  42. package/dist/git/git.errors.js.map +1 -0
  43. package/dist/git/git.errors.test.d.ts +2 -0
  44. package/dist/git/git.errors.test.d.ts.map +1 -0
  45. package/dist/git/git.errors.test.js +34 -0
  46. package/dist/git/git.errors.test.js.map +1 -0
  47. package/dist/git/git.operations.d.ts +12 -0
  48. package/dist/git/git.operations.d.ts.map +1 -0
  49. package/dist/git/git.operations.js +64 -0
  50. package/dist/git/git.operations.js.map +1 -0
  51. package/dist/git/git.operations.test.d.ts +2 -0
  52. package/dist/git/git.operations.test.d.ts.map +1 -0
  53. package/dist/git/git.operations.test.js +164 -0
  54. package/dist/git/git.operations.test.js.map +1 -0
  55. package/dist/git/index.d.ts +4 -0
  56. package/dist/git/index.d.ts.map +1 -0
  57. package/dist/git/index.js +19 -0
  58. package/dist/git/index.js.map +1 -0
  59. package/dist/llm/index.d.ts +3 -0
  60. package/dist/llm/index.d.ts.map +1 -0
  61. package/dist/llm/index.js +19 -0
  62. package/dist/llm/index.js.map +1 -0
  63. package/dist/llm/llm.d.ts +35 -0
  64. package/dist/llm/llm.d.ts.map +1 -0
  65. package/dist/{llm.js → llm/llm.js} +16 -58
  66. package/dist/llm/llm.js.map +1 -0
  67. package/dist/{llm.test.d.ts.map → llm/llm.test.d.ts.map} +1 -1
  68. package/dist/llm/llm.test.js +224 -0
  69. package/dist/llm/llm.test.js.map +1 -0
  70. package/dist/{prompts.d.ts → llm/prompts.d.ts} +1 -38
  71. package/dist/llm/prompts.d.ts.map +1 -0
  72. package/dist/{prompts.js → llm/prompts.js} +9 -54
  73. package/dist/llm/prompts.js.map +1 -0
  74. package/dist/llm/response-parser.d.ts +9 -0
  75. package/dist/llm/response-parser.d.ts.map +1 -0
  76. package/dist/llm/response-parser.js +67 -0
  77. package/dist/llm/response-parser.js.map +1 -0
  78. package/dist/llm/response-parser.test.d.ts +2 -0
  79. package/dist/llm/response-parser.test.d.ts.map +1 -0
  80. package/dist/llm/response-parser.test.js +134 -0
  81. package/dist/llm/response-parser.test.js.map +1 -0
  82. package/dist/presenters/console-presenter.d.ts +35 -0
  83. package/dist/presenters/console-presenter.d.ts.map +1 -0
  84. package/dist/presenters/console-presenter.js +114 -0
  85. package/dist/presenters/console-presenter.js.map +1 -0
  86. package/dist/presenters/console-presenter.test.d.ts +2 -0
  87. package/dist/presenters/console-presenter.test.d.ts.map +1 -0
  88. package/dist/presenters/console-presenter.test.js +227 -0
  89. package/dist/presenters/console-presenter.test.js.map +1 -0
  90. package/dist/version.test.d.ts +1 -2
  91. package/dist/version.test.d.ts.map +1 -1
  92. package/dist/version.test.js +29 -16
  93. package/dist/version.test.js.map +1 -1
  94. package/package.json +1 -1
  95. package/src/{adr.test.ts → adr/adr.test.ts} +10 -23
  96. package/src/{adr.ts → adr/adr.ts} +7 -48
  97. package/src/adr/index.ts +1 -0
  98. package/src/analysis/analysis.orchestrator.test.ts +237 -0
  99. package/src/analysis/analysis.orchestrator.ts +175 -0
  100. package/src/analysis/strategies/git-strategy.test.ts +210 -0
  101. package/src/analysis/strategies/git-strategy.ts +106 -0
  102. package/src/commands/analyze.test.ts +91 -0
  103. package/src/commands/analyze.ts +8 -9
  104. package/src/commands/init.test.ts +200 -5
  105. package/src/config.test.ts +232 -2
  106. package/src/git/git.errors.test.ts +43 -0
  107. package/src/git/git.errors.ts +10 -0
  108. package/src/git/git.operations.test.ts +222 -0
  109. package/src/git/git.operations.ts +85 -0
  110. package/src/git/index.ts +3 -0
  111. package/src/llm/index.ts +2 -0
  112. package/src/llm/llm.test.ts +315 -0
  113. package/src/{llm.ts → llm/llm.ts} +46 -107
  114. package/src/{prompts.ts → llm/prompts.ts} +30 -72
  115. package/src/llm/response-parser.test.ts +170 -0
  116. package/src/llm/response-parser.ts +90 -0
  117. package/src/presenters/console-presenter.test.ts +259 -0
  118. package/src/presenters/console-presenter.ts +152 -0
  119. package/src/version.test.ts +30 -16
  120. package/dist/adr.d.ts +0 -50
  121. package/dist/adr.d.ts.map +0 -1
  122. package/dist/adr.js.map +0 -1
  123. package/dist/adr.test.d.ts +0 -8
  124. package/dist/adr.test.js.map +0 -1
  125. package/dist/analysis.d.ts +0 -24
  126. package/dist/analysis.d.ts.map +0 -1
  127. package/dist/analysis.js +0 -281
  128. package/dist/analysis.js.map +0 -1
  129. package/dist/analysis.test.d.ts +0 -8
  130. package/dist/analysis.test.d.ts.map +0 -1
  131. package/dist/analysis.test.js +0 -351
  132. package/dist/analysis.test.js.map +0 -1
  133. package/dist/git.d.ts +0 -54
  134. package/dist/git.d.ts.map +0 -1
  135. package/dist/git.js +0 -204
  136. package/dist/git.js.map +0 -1
  137. package/dist/llm.d.ts +0 -73
  138. package/dist/llm.d.ts.map +0 -1
  139. package/dist/llm.js.map +0 -1
  140. package/dist/llm.test.js +0 -592
  141. package/dist/llm.test.js.map +0 -1
  142. package/dist/prompts.d.ts.map +0 -1
  143. package/dist/prompts.js.map +0 -1
  144. package/dist/prompts.test.d.ts +0 -2
  145. package/dist/prompts.test.d.ts.map +0 -1
  146. package/dist/prompts.test.js +0 -427
  147. package/dist/prompts.test.js.map +0 -1
  148. package/src/analysis.test.ts +0 -396
  149. package/src/analysis.ts +0 -262
  150. package/src/git.ts +0 -300
  151. package/src/llm.test.ts +0 -701
  152. package/src/prompts.test.ts +0 -515
  153. /package/dist/{llm.test.d.ts → llm/llm.test.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"version.test.js","sourceRoot":"","sources":["../src/version.test.ts"],"names":[],"mappings":";AAAA,gCAAgC;AAChC,MAAM,YAAY,GAAG,OAAO,CAAC;AAC7B,MAAM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AC,CAAC,CAAC;IAEH,IAAI,CAAC,+CAA+C,EAAE,GAAG,EAAE;QACzD,8DAA8D;QAC9D,MAAM,GAAG,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACvC,IAAA,mBAAW,GAAE,CAAC;QACd,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAW,CAAC;QACpD,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cadr-cli",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "description": "Continuous Architectural Decision Records - Automatically capture ADRs as you code",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -1,8 +1,5 @@
1
1
  /**
2
2
  * ADR File Management Module Tests
3
- *
4
- * Tests for ADR file creation, numbering, and management.
5
- * Following TDD: These tests are written BEFORE implementation.
6
3
  */
7
4
 
8
5
  import * as fs from 'fs';
@@ -20,14 +17,12 @@ describe('ADR Module', () => {
20
17
  const testDir = path.join(__dirname, '../test-adrs');
21
18
 
22
19
  beforeEach(() => {
23
- // Clean up test directory before each test
24
20
  if (fs.existsSync(testDir)) {
25
21
  fs.rmSync(testDir, { recursive: true, force: true });
26
22
  }
27
23
  });
28
24
 
29
25
  afterEach(() => {
30
- // Clean up test directory after each test
31
26
  if (fs.existsSync(testDir)) {
32
27
  fs.rmSync(testDir, { recursive: true, force: true });
33
28
  }
@@ -187,14 +182,15 @@ describe('ADR Module', () => {
187
182
  expect(result1.filePath).toContain('0001-first.md');
188
183
  expect(result2.filePath).toContain('0002-second.md');
189
184
  expect(result3.filePath).toContain('0003-third.md');
190
-
185
+
191
186
  expect(fs.existsSync(result1.filePath!)).toBe(true);
192
187
  expect(fs.existsSync(result2.filePath!)).toBe(true);
193
188
  expect(fs.existsSync(result3.filePath!)).toBe(true);
194
189
  });
195
190
 
196
191
  it('saves correct content to file', () => {
197
- const content = '# My Decision\n\n* Status: accepted\n* Date: 2025-10-21\n\n## Context\n\nSome context here.';
192
+ const content =
193
+ '# My Decision\n\n* Status: accepted\n* Date: 2025-10-21\n\n## Context\n\nSome context here.';
198
194
  const result = saveADR(content, 'My Decision', testDir);
199
195
 
200
196
  const savedContent = fs.readFileSync(result.filePath!, 'utf-8');
@@ -202,7 +198,6 @@ describe('ADR Module', () => {
202
198
  });
203
199
 
204
200
  it('uses default directory when not specified', () => {
205
- // Clean up default directory
206
201
  const defaultPath = path.join(process.cwd(), DEFAULT_ADR_DIR);
207
202
  if (fs.existsSync(defaultPath)) {
208
203
  fs.rmSync(defaultPath, { recursive: true, force: true });
@@ -213,44 +208,38 @@ describe('ADR Module', () => {
213
208
 
214
209
  expect(result.success).toBe(true);
215
210
  expect(result.filePath).toContain(DEFAULT_ADR_DIR);
216
-
217
- // Cleanup
211
+
218
212
  if (fs.existsSync(defaultPath)) {
219
213
  fs.rmSync(defaultPath, { recursive: true, force: true });
220
214
  }
221
215
  });
222
216
 
223
217
  it('handles file write errors gracefully', () => {
224
- // Create a read-only directory to trigger write error
225
218
  fs.mkdirSync(testDir, { recursive: true });
226
-
227
- // Make directory read-only (if not Windows)
219
+
228
220
  if (process.platform !== 'win32') {
229
221
  fs.chmodSync(testDir, 0o444);
230
-
222
+
231
223
  const content = '# Test\n\nContent';
232
224
  const result = saveADR(content, 'Test', testDir);
233
225
 
234
226
  expect(result.success).toBe(false);
235
227
  expect(result.error).toBeDefined();
236
228
  expect(result.filePath).toBeUndefined();
237
-
238
- // Restore permissions for cleanup
229
+
239
230
  fs.chmodSync(testDir, 0o755);
240
231
  } else {
241
- // On Windows, just verify error handling structure exists
242
- // Skip actual permission test as Windows permissions work differently
243
232
  const content = '# Test\n\nContent';
244
233
  const result = saveADR(content, 'Test', testDir);
245
-
246
- // Should succeed on Windows since we can't easily simulate permission errors
234
+
247
235
  expect(result).toHaveProperty('success');
248
236
  expect(typeof result.success).toBe('boolean');
249
237
  }
250
238
  });
251
239
 
252
240
  it('handles long titles correctly', () => {
253
- const longTitle = 'This is a very long title that should still work correctly when converted to a filename slug';
241
+ const longTitle =
242
+ 'This is a very long title that should still work correctly when converted to a filename slug';
254
243
  const content = `# ${longTitle}\n\nContent`;
255
244
  const result = saveADR(content, longTitle, testDir);
256
245
 
@@ -263,7 +252,6 @@ describe('ADR Module', () => {
263
252
  const result = saveADR(content, 'Decision with émojis 🚀', testDir);
264
253
 
265
254
  expect(result.success).toBe(true);
266
- // Should strip unicode to safe characters
267
255
  expect(result.filePath).toMatch(/0001-.+\.md$/);
268
256
  });
269
257
  });
@@ -275,4 +263,3 @@ describe('ADR Module', () => {
275
263
  });
276
264
  });
277
265
  });
278
-
@@ -1,46 +1,32 @@
1
1
  /**
2
2
  * ADR File Management Module
3
- *
3
+ *
4
4
  * Handles creation and management of Architectural Decision Record files.
5
5
  * Follows MADR (Markdown Architectural Decision Records) format.
6
6
  */
7
7
 
8
8
  import * as fs from 'fs';
9
9
  import * as path from 'path';
10
- import { loggerInstance as logger } from './logger';
10
+ import { loggerInstance as logger } from '../logger';
11
11
 
12
- /**
13
- * Default ADR directory relative to project root
14
- */
15
12
  export const DEFAULT_ADR_DIR = 'docs/adr';
16
13
 
17
- /**
18
- * Convert a title to a filename-safe slug
19
- * Example: "Use PostgreSQL for Storage" -> "use-postgresql-for-storage"
20
- */
21
14
  export function titleToSlug(title: string): string {
22
15
  return title
23
16
  .toLowerCase()
24
- .replace(/[^a-z0-9]+/g, '-') // Replace non-alphanumeric with hyphens
25
- .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
17
+ .replace(/[^a-z0-9]+/g, '-')
18
+ .replace(/^-+|-+$/g, '');
26
19
  }
27
20
 
28
- /**
29
- * Get the next ADR number by scanning existing ADR files
30
- *
31
- * @param adrDir - Directory containing ADR files
32
- * @returns Next available ADR number (e.g., 1, 2, 3...)
33
- */
34
21
  export function getNextADRNumber(adrDir: string): number {
35
22
  try {
36
23
  if (!fs.existsSync(adrDir)) {
37
- return 1; // First ADR
24
+ return 1;
38
25
  }
39
26
 
40
27
  const files = fs.readdirSync(adrDir);
41
28
  const adrNumbers: number[] = [];
42
29
 
43
- // Extract numbers from existing ADR files (format: 0001-title.md)
44
30
  for (const file of files) {
45
31
  const match = file.match(/^(\d{4})-/);
46
32
  if (match) {
@@ -52,7 +38,6 @@ export function getNextADRNumber(adrDir: string): number {
52
38
  return 1;
53
39
  }
54
40
 
55
- // Return next number after the highest existing number
56
41
  return Math.max(...adrNumbers) + 1;
57
42
  } catch (error) {
58
43
  logger.warn('Failed to scan existing ADRs, defaulting to 1', { error, adrDir });
@@ -60,11 +45,6 @@ export function getNextADRNumber(adrDir: string): number {
60
45
  }
61
46
  }
62
47
 
63
- /**
64
- * Ensure ADR directory exists, create if it doesn't
65
- *
66
- * @param adrDir - Directory path to ensure exists
67
- */
68
48
  export function ensureADRDirectory(adrDir: string): void {
69
49
  if (!fs.existsSync(adrDir)) {
70
50
  logger.info('Creating ADR directory', { adrDir });
@@ -72,56 +52,36 @@ export function ensureADRDirectory(adrDir: string): void {
72
52
  }
73
53
  }
74
54
 
75
- /**
76
- * Generate ADR filename from number and title
77
- *
78
- * @param number - ADR number (will be zero-padded to 4 digits)
79
- * @param title - ADR title (will be converted to slug)
80
- * @returns Filename like "0001-use-postgresql-for-storage.md"
81
- */
82
55
  export function generateADRFilename(number: number, title: string): string {
83
56
  const paddedNumber = String(number).padStart(4, '0');
84
57
  const slug = titleToSlug(title);
85
58
  return `${paddedNumber}-${slug}.md`;
86
59
  }
87
60
 
88
- /**
89
- * Save ADR content to file
90
- *
91
- * @param content - Full markdown content of the ADR
92
- * @param title - Title extracted from ADR content
93
- * @param adrDir - Directory to save ADR in (defaults to docs/adr)
94
- * @returns Object with success status, file path, and any error
95
- */
96
61
  export function saveADR(
97
62
  content: string,
98
63
  title: string,
99
64
  adrDir: string = DEFAULT_ADR_DIR
100
65
  ): { success: boolean; filePath?: string; error?: string } {
101
66
  try {
102
- // Ensure directory exists
103
67
  ensureADRDirectory(adrDir);
104
68
 
105
- // Get next ADR number
106
69
  const adrNumber = getNextADRNumber(adrDir);
107
70
 
108
- // Generate filename
109
71
  const filename = generateADRFilename(adrNumber, title);
110
72
  const filePath = path.join(adrDir, filename);
111
73
 
112
- // Check if file already exists (shouldn't happen, but safety check)
113
74
  if (fs.existsSync(filePath)) {
114
75
  logger.warn('ADR file already exists, using alternative name', { filePath });
115
76
  const alternativeFilename = generateADRFilename(adrNumber + 1, title);
116
77
  const alternativeFilePath = path.join(adrDir, alternativeFilename);
117
-
78
+
118
79
  fs.writeFileSync(alternativeFilePath, content, 'utf-8');
119
80
  logger.info('ADR saved successfully', { filePath: alternativeFilePath });
120
-
81
+
121
82
  return { success: true, filePath: alternativeFilePath };
122
83
  }
123
84
 
124
- // Write ADR content to file
125
85
  fs.writeFileSync(filePath, content, 'utf-8');
126
86
 
127
87
  logger.info('ADR saved successfully', { filePath, adrNumber });
@@ -133,4 +93,3 @@ export function saveADR(
133
93
  return { success: false, error: errorMessage };
134
94
  }
135
95
  }
136
-
@@ -0,0 +1 @@
1
+ export * from './adr';
@@ -0,0 +1,237 @@
1
+ jest.mock('../config');
2
+ jest.mock('../llm/prompts');
3
+ jest.mock('../llm/llm');
4
+ jest.mock('../logger');
5
+ jest.mock('../adr/adr');
6
+ jest.mock('./strategies/git-strategy');
7
+ jest.mock('../presenters/console-presenter');
8
+
9
+ import { loadConfig, getDefaultConfigPath } from '../config';
10
+ import {
11
+ formatPrompt,
12
+ formatGenerationPrompt,
13
+ promptForGeneration,
14
+ } from '../llm/prompts';
15
+ import { analyzeChanges, generateADRContent } from '../llm/llm';
16
+ import { saveADR } from '../adr/adr';
17
+ import { createGitStrategy } from './strategies/git-strategy';
18
+ import { presenter } from '../presenters/console-presenter';
19
+ import { runAnalysis } from './analysis.orchestrator';
20
+
21
+ const mockPresenter = presenter as jest.Mocked<typeof presenter>;
22
+ const mockStrategy = { getFiles: jest.fn(), getDiff: jest.fn() };
23
+
24
+ (createGitStrategy as jest.Mock).mockReturnValue(mockStrategy);
25
+ (getDefaultConfigPath as jest.Mock).mockReturnValue('cadr.yaml');
26
+ (formatPrompt as jest.Mock).mockReturnValue('formatted-prompt');
27
+ (formatGenerationPrompt as jest.Mock).mockReturnValue('formatted-generation-prompt');
28
+
29
+ const mockConfig = {
30
+ provider: 'openai' as const,
31
+ analysis_model: 'gpt-4',
32
+ api_key_env: 'KEY',
33
+ timeout_seconds: 15,
34
+ };
35
+
36
+ const defaultDiffOptions = { mode: 'all' as const };
37
+
38
+ function setupHappyPath(overrides?: { isSignificant?: boolean; confidence?: number }) {
39
+ const isSignificant = overrides?.isSignificant ?? true;
40
+ const confidence = overrides?.confidence ?? 0.9;
41
+
42
+ (loadConfig as jest.Mock).mockResolvedValue(mockConfig);
43
+ mockStrategy.getFiles.mockResolvedValue(['src/index.ts', 'src/utils.ts']);
44
+ mockStrategy.getDiff.mockResolvedValue('diff content here');
45
+ (analyzeChanges as jest.Mock).mockResolvedValue({
46
+ result: {
47
+ is_significant: isSignificant,
48
+ reason: 'Introduced new dependency',
49
+ confidence,
50
+ timestamp: '2026-01-01T00:00:00.000Z',
51
+ },
52
+ error: undefined,
53
+ });
54
+ }
55
+
56
+ describe('runAnalysis', () => {
57
+ beforeEach(() => {
58
+ jest.clearAllMocks();
59
+ (createGitStrategy as jest.Mock).mockReturnValue(mockStrategy);
60
+ (getDefaultConfigPath as jest.Mock).mockReturnValue('cadr.yaml');
61
+ (formatPrompt as jest.Mock).mockReturnValue('formatted-prompt');
62
+ (formatGenerationPrompt as jest.Mock).mockReturnValue('formatted-generation-prompt');
63
+ });
64
+
65
+ it('should show config error and return early when loadConfig returns null', async () => {
66
+ (loadConfig as jest.Mock).mockResolvedValue(null);
67
+
68
+ await runAnalysis(defaultDiffOptions);
69
+
70
+ expect(mockPresenter.showConfigError).toHaveBeenCalled();
71
+ expect(mockStrategy.getFiles).not.toHaveBeenCalled();
72
+ });
73
+
74
+ it('should show git error when getFiles throws a GitError', async () => {
75
+ (loadConfig as jest.Mock).mockResolvedValue(mockConfig);
76
+ const gitError = new Error('Not a git repo');
77
+ gitError.name = 'GitError';
78
+ mockStrategy.getFiles.mockRejectedValue(gitError);
79
+
80
+ await runAnalysis(defaultDiffOptions);
81
+
82
+ expect(mockPresenter.showGitError).toHaveBeenCalledWith('Not a git repo');
83
+ });
84
+
85
+ it('should show read files error when getFiles throws a non-GitError', async () => {
86
+ (loadConfig as jest.Mock).mockResolvedValue(mockConfig);
87
+ mockStrategy.getFiles.mockRejectedValue(new Error('some other error'));
88
+
89
+ await runAnalysis(defaultDiffOptions);
90
+
91
+ expect(mockPresenter.showReadFilesError).toHaveBeenCalled();
92
+ });
93
+
94
+ it('should show no changes when getFiles returns empty array', async () => {
95
+ (loadConfig as jest.Mock).mockResolvedValue(mockConfig);
96
+ mockStrategy.getFiles.mockResolvedValue([]);
97
+
98
+ await runAnalysis(defaultDiffOptions);
99
+
100
+ expect(mockPresenter.showNoChanges).toHaveBeenCalledWith(defaultDiffOptions);
101
+ });
102
+
103
+ it('should show read files error when getDiff throws', async () => {
104
+ (loadConfig as jest.Mock).mockResolvedValue(mockConfig);
105
+ mockStrategy.getFiles.mockResolvedValue(['file.ts']);
106
+ mockStrategy.getDiff.mockRejectedValue(new Error('diff failed'));
107
+
108
+ await runAnalysis(defaultDiffOptions);
109
+
110
+ expect(mockPresenter.showReadFilesError).toHaveBeenCalled();
111
+ });
112
+
113
+ it('should show no diff content when getDiff returns empty string', async () => {
114
+ (loadConfig as jest.Mock).mockResolvedValue(mockConfig);
115
+ mockStrategy.getFiles.mockResolvedValue(['file.ts']);
116
+ mockStrategy.getDiff.mockResolvedValue('');
117
+
118
+ await runAnalysis(defaultDiffOptions);
119
+
120
+ expect(mockPresenter.showNoDiffContent).toHaveBeenCalled();
121
+ });
122
+
123
+ it('should show analysis failed when analyzeChanges returns error', async () => {
124
+ (loadConfig as jest.Mock).mockResolvedValue(mockConfig);
125
+ mockStrategy.getFiles.mockResolvedValue(['file.ts']);
126
+ mockStrategy.getDiff.mockResolvedValue('diff content');
127
+ (analyzeChanges as jest.Mock).mockResolvedValue({
128
+ result: null,
129
+ error: 'api error',
130
+ });
131
+
132
+ await runAnalysis(defaultDiffOptions);
133
+
134
+ expect(mockPresenter.showAnalysisFailed).toHaveBeenCalledWith('api error');
135
+ });
136
+
137
+ it('should show not significant result when analysis result is not significant', async () => {
138
+ setupHappyPath({ isSignificant: false });
139
+
140
+ await runAnalysis(defaultDiffOptions);
141
+
142
+ expect(mockPresenter.showNotSignificantResult).toHaveBeenCalledWith(
143
+ expect.objectContaining({
144
+ fileCount: 2,
145
+ mode: 'all',
146
+ isSignificant: false,
147
+ reason: 'Introduced new dependency',
148
+ confidence: 0.9,
149
+ })
150
+ );
151
+ });
152
+
153
+ it('should show skipping generation when user declines', async () => {
154
+ setupHappyPath({ isSignificant: true });
155
+ (promptForGeneration as jest.Mock).mockResolvedValue(false);
156
+
157
+ await runAnalysis(defaultDiffOptions);
158
+
159
+ expect(mockPresenter.showSignificantResult).toHaveBeenCalled();
160
+ expect(mockPresenter.showSkippingGeneration).toHaveBeenCalled();
161
+ });
162
+
163
+ it('should show generation failed when generateADRContent returns error', async () => {
164
+ setupHappyPath({ isSignificant: true });
165
+ (promptForGeneration as jest.Mock).mockResolvedValue(true);
166
+ (generateADRContent as jest.Mock).mockResolvedValue({
167
+ result: null,
168
+ error: 'generation error',
169
+ });
170
+
171
+ await runAnalysis(defaultDiffOptions);
172
+
173
+ expect(mockPresenter.showGeneratingADR).toHaveBeenCalled();
174
+ expect(mockPresenter.showGenerationFailed).toHaveBeenCalledWith('generation error');
175
+ });
176
+
177
+ it('should show ADR success when generation and save succeed', async () => {
178
+ setupHappyPath({ isSignificant: true });
179
+ (promptForGeneration as jest.Mock).mockResolvedValue(true);
180
+ (generateADRContent as jest.Mock).mockResolvedValue({
181
+ result: { content: '# ADR Content', title: 'Use Redis', timestamp: '2026-01-01' },
182
+ error: undefined,
183
+ });
184
+ (saveADR as jest.Mock).mockReturnValue({
185
+ success: true,
186
+ filePath: 'docs/adr/0001-use-redis.md',
187
+ });
188
+
189
+ await runAnalysis(defaultDiffOptions);
190
+
191
+ expect(mockPresenter.showGeneratingADR).toHaveBeenCalled();
192
+ expect(saveADR).toHaveBeenCalledWith('# ADR Content', 'Use Redis');
193
+ expect(mockPresenter.showADRSuccess).toHaveBeenCalledWith('docs/adr/0001-use-redis.md');
194
+ });
195
+
196
+ it('should show ADR save error when save fails', async () => {
197
+ setupHappyPath({ isSignificant: true });
198
+ (promptForGeneration as jest.Mock).mockResolvedValue(true);
199
+ (generateADRContent as jest.Mock).mockResolvedValue({
200
+ result: { content: '# ADR Content', title: 'Use Redis', timestamp: '2026-01-01' },
201
+ error: undefined,
202
+ });
203
+ (saveADR as jest.Mock).mockReturnValue({
204
+ success: false,
205
+ error: 'permission denied',
206
+ });
207
+
208
+ await runAnalysis(defaultDiffOptions);
209
+
210
+ expect(mockPresenter.showADRSaveError).toHaveBeenCalledWith('permission denied');
211
+ });
212
+
213
+ it('should show unexpected error when runAnalysisInternal throws', async () => {
214
+ (loadConfig as jest.Mock).mockRejectedValue(new Error('unexpected boom'));
215
+
216
+ await runAnalysis(defaultDiffOptions);
217
+
218
+ expect(mockPresenter.showUnexpectedError).toHaveBeenCalled();
219
+ });
220
+
221
+ it('should call showAnalyzingFiles, showSendingToLLM, and showAnalysisComplete in happy path', async () => {
222
+ setupHappyPath({ isSignificant: false });
223
+
224
+ await runAnalysis(defaultDiffOptions);
225
+
226
+ expect(mockPresenter.showAnalyzingFiles).toHaveBeenCalledWith(
227
+ ['src/index.ts', 'src/utils.ts'],
228
+ defaultDiffOptions
229
+ );
230
+ expect(mockPresenter.showSendingToLLM).toHaveBeenCalledWith(
231
+ defaultDiffOptions,
232
+ 'openai',
233
+ 'gpt-4'
234
+ );
235
+ expect(mockPresenter.showAnalysisComplete).toHaveBeenCalled();
236
+ });
237
+ });
@@ -0,0 +1,175 @@
1
+ /* eslint-disable no-console */
2
+ import { loadConfig, getDefaultConfigPath } from '../config';
3
+ import type { DiffOptions } from '../git/index';
4
+ import {
5
+ formatPrompt,
6
+ ANALYSIS_PROMPT_V1,
7
+ formatGenerationPrompt,
8
+ promptForGeneration,
9
+ } from '../llm/prompts';
10
+ import { analyzeChanges, generateADRContent } from '../llm/llm';
11
+ import { loggerInstance as logger } from '../logger';
12
+ import { saveADR } from '../adr/adr';
13
+ import * as path from 'path';
14
+ import { createGitStrategy, type GitStrategy } from './strategies/git-strategy';
15
+ import { presenter, type AnalysisSummary } from '../presenters/console-presenter';
16
+
17
+ export interface AnalysisResult {
18
+ is_significant: boolean;
19
+ reason: string;
20
+ confidence?: number;
21
+ timestamp: string;
22
+ }
23
+
24
+ export interface GenerationResult {
25
+ content: string;
26
+ title: string;
27
+ timestamp: string;
28
+ }
29
+
30
+ async function runAnalysisInternal(diffOptions: DiffOptions): Promise<void> {
31
+ const configPath = getDefaultConfigPath();
32
+ const config = await loadConfig(configPath);
33
+
34
+ if (!config) {
35
+ presenter.showConfigError();
36
+ return;
37
+ }
38
+
39
+ const gitStrategy: GitStrategy = createGitStrategy(diffOptions);
40
+
41
+ let changedFiles: string[];
42
+ try {
43
+ changedFiles = await gitStrategy.getFiles();
44
+ } catch (error) {
45
+ const gitError = error as { name?: string; message?: string };
46
+ if (gitError.name === 'GitError') {
47
+ presenter.showGitError(gitError.message || 'Unknown Git error');
48
+ } else {
49
+ presenter.showReadFilesError();
50
+ }
51
+ logger.error('Failed to get changed files', { error, mode: diffOptions.mode });
52
+ return;
53
+ }
54
+
55
+ if (changedFiles.length === 0) {
56
+ presenter.showNoChanges(diffOptions);
57
+ return;
58
+ }
59
+
60
+ presenter.showAnalyzingFiles(changedFiles, diffOptions);
61
+
62
+ let diffContent: string;
63
+ try {
64
+ diffContent = await gitStrategy.getDiff();
65
+ } catch (error) {
66
+ presenter.showReadFilesError();
67
+ logger.error('Failed to get diff', { error, mode: diffOptions.mode });
68
+ return;
69
+ }
70
+
71
+ if (!diffContent || diffContent.trim().length === 0) {
72
+ presenter.showNoDiffContent();
73
+ return;
74
+ }
75
+
76
+ const repositoryContext = path.basename(process.cwd());
77
+ const prompt = formatPrompt(ANALYSIS_PROMPT_V1, {
78
+ file_paths: changedFiles,
79
+ diff_content: diffContent,
80
+ });
81
+
82
+ presenter.showSendingToLLM(diffOptions, config.provider, config.analysis_model);
83
+
84
+ const response = await analyzeChanges(config, {
85
+ file_paths: changedFiles,
86
+ diff_content: diffContent,
87
+ repository_context: repositoryContext,
88
+ analysis_prompt: prompt,
89
+ });
90
+
91
+ if (!response.result || response.error) {
92
+ presenter.showAnalysisFailed(response.error);
93
+ return;
94
+ }
95
+
96
+ const result = response.result;
97
+
98
+ presenter.showAnalysisComplete();
99
+
100
+ if (result.is_significant) {
101
+ const summary: AnalysisSummary = {
102
+ fileCount: changedFiles.length,
103
+ mode: diffOptions.mode,
104
+ isSignificant: true,
105
+ reason: result.reason,
106
+ confidence: result.confidence,
107
+ };
108
+ presenter.showSignificantResult(summary);
109
+
110
+ const shouldGenerate = await promptForGeneration(result.reason);
111
+
112
+ if (shouldGenerate) {
113
+ presenter.showGeneratingADR();
114
+
115
+ const generationPrompt = formatGenerationPrompt({
116
+ file_paths: changedFiles,
117
+ diff_content: diffContent,
118
+ });
119
+
120
+ const generationResponse = await generateADRContent(config, {
121
+ file_paths: changedFiles,
122
+ diff_content: diffContent,
123
+ reason: result.reason,
124
+ generation_prompt: generationPrompt,
125
+ });
126
+
127
+ if (!generationResponse.result || generationResponse.error) {
128
+ presenter.showGenerationFailed(generationResponse.error);
129
+ logger.error('ADR generation failed', { error: generationResponse.error });
130
+ } else {
131
+ const saveResult = saveADR(
132
+ generationResponse.result.content,
133
+ generationResponse.result.title
134
+ );
135
+
136
+ if (saveResult.success && saveResult.filePath) {
137
+ presenter.showADRSuccess(saveResult.filePath);
138
+ logger.info('ADR generation workflow completed successfully', {
139
+ filePath: saveResult.filePath,
140
+ title: generationResponse.result.title,
141
+ });
142
+ } else {
143
+ presenter.showADRSaveError(saveResult.error);
144
+ logger.error('Failed to save ADR', { error: saveResult.error });
145
+ }
146
+ }
147
+ } else {
148
+ presenter.showSkippingGeneration();
149
+ }
150
+ } else {
151
+ const summary: AnalysisSummary = {
152
+ fileCount: changedFiles.length,
153
+ mode: diffOptions.mode,
154
+ isSignificant: false,
155
+ reason: result.reason,
156
+ confidence: result.confidence,
157
+ };
158
+ presenter.showNotSignificantResult(summary);
159
+ }
160
+
161
+ logger.info('Analysis workflow completed successfully', {
162
+ is_significant: result.is_significant,
163
+ file_count: changedFiles.length,
164
+ });
165
+ }
166
+
167
+ export async function runAnalysis(diffOptions: DiffOptions = { mode: 'all' }): Promise<void> {
168
+ try {
169
+ logger.info('Starting analysis workflow');
170
+ await runAnalysisInternal(diffOptions);
171
+ } catch (error) {
172
+ logger.error('Unexpected error in analysis workflow', { error });
173
+ presenter.showUnexpectedError();
174
+ }
175
+ }