@defai.digital/analysis-domain 13.0.3

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.
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Code Context Builder
3
+ *
4
+ * Gathers code from file paths for analysis.
5
+ */
6
+ import * as fs from 'fs/promises';
7
+ import * as path from 'path';
8
+ import { getLanguageFromPath, LIMIT_LINES_PER_FILE, } from '@defai.digital/contracts';
9
+ /**
10
+ * Default exclude patterns
11
+ */
12
+ const DEFAULT_EXCLUDE_PATTERNS = [
13
+ 'node_modules',
14
+ 'dist',
15
+ 'build',
16
+ '.git',
17
+ '.next',
18
+ '__pycache__',
19
+ 'venv',
20
+ '.venv',
21
+ 'coverage',
22
+ '.nyc_output',
23
+ '*.min.js',
24
+ '*.bundle.js',
25
+ '*.map',
26
+ 'package-lock.json',
27
+ 'pnpm-lock.yaml',
28
+ 'yarn.lock',
29
+ ];
30
+ /**
31
+ * Analysis context builder error
32
+ */
33
+ export class ContextBuilderError extends Error {
34
+ code;
35
+ constructor(code, message) {
36
+ super(message);
37
+ this.code = code;
38
+ this.name = 'ContextBuilderError';
39
+ }
40
+ }
41
+ /**
42
+ * Default gather options
43
+ */
44
+ const DEFAULT_OPTIONS = {
45
+ maxFiles: 20,
46
+ maxLinesPerFile: LIMIT_LINES_PER_FILE,
47
+ };
48
+ /**
49
+ * Creates a code context builder
50
+ */
51
+ export function createCodeContextBuilder() {
52
+ return {
53
+ async gatherCode(paths, options) {
54
+ const opts = { ...DEFAULT_OPTIONS, ...options };
55
+ const excludePatterns = [
56
+ ...DEFAULT_EXCLUDE_PATTERNS,
57
+ ...(opts.excludePatterns ?? []),
58
+ ];
59
+ const files = [];
60
+ let totalLines = 0;
61
+ let truncated = false;
62
+ // Resolve and deduplicate paths
63
+ const resolvedPaths = new Set();
64
+ for (const p of paths) {
65
+ const resolved = path.resolve(p);
66
+ resolvedPaths.add(resolved);
67
+ }
68
+ // Process each path
69
+ for (const filePath of resolvedPaths) {
70
+ if (files.length >= opts.maxFiles) {
71
+ truncated = true;
72
+ break;
73
+ }
74
+ try {
75
+ const stat = await fs.stat(filePath);
76
+ if (stat.isDirectory()) {
77
+ // Recursively gather files from directory
78
+ const dirFiles = await gatherFromDirectory(filePath, excludePatterns, opts.maxFiles - files.length, opts.maxLinesPerFile);
79
+ files.push(...dirFiles);
80
+ totalLines += dirFiles.reduce((sum, f) => sum + f.lines, 0);
81
+ if (files.length >= opts.maxFiles) {
82
+ truncated = true;
83
+ }
84
+ }
85
+ else if (stat.isFile()) {
86
+ // Read single file
87
+ const file = await readFile(filePath, opts.maxLinesPerFile);
88
+ if (file) {
89
+ files.push(file);
90
+ totalLines += file.lines;
91
+ }
92
+ }
93
+ }
94
+ catch (error) {
95
+ // Skip files that can't be read
96
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
97
+ continue;
98
+ }
99
+ throw error;
100
+ }
101
+ }
102
+ return {
103
+ files,
104
+ totalLines,
105
+ truncated,
106
+ };
107
+ },
108
+ };
109
+ }
110
+ /**
111
+ * Gather files from a directory recursively
112
+ */
113
+ async function gatherFromDirectory(dirPath, excludePatterns, maxFiles, maxLinesPerFile) {
114
+ const files = [];
115
+ async function walk(currentPath) {
116
+ if (files.length >= maxFiles)
117
+ return;
118
+ const entries = await fs.readdir(currentPath, { withFileTypes: true });
119
+ for (const entry of entries) {
120
+ if (files.length >= maxFiles)
121
+ return;
122
+ const fullPath = path.join(currentPath, entry.name);
123
+ const relativePath = path.relative(dirPath, fullPath);
124
+ // Check exclude patterns
125
+ if (shouldExclude(relativePath, entry.name, excludePatterns)) {
126
+ continue;
127
+ }
128
+ if (entry.isDirectory()) {
129
+ await walk(fullPath);
130
+ }
131
+ else if (entry.isFile() && isAnalyzableFile(entry.name)) {
132
+ const file = await readFile(fullPath, maxLinesPerFile);
133
+ if (file) {
134
+ files.push(file);
135
+ }
136
+ }
137
+ }
138
+ }
139
+ await walk(dirPath);
140
+ return files;
141
+ }
142
+ /**
143
+ * Read a single file
144
+ */
145
+ async function readFile(filePath, maxLines) {
146
+ try {
147
+ const content = await fs.readFile(filePath, 'utf-8');
148
+ const lines = content.split('\n');
149
+ const truncatedContent = lines.length > maxLines ? lines.slice(0, maxLines).join('\n') + '\n// ... truncated' : content;
150
+ return {
151
+ path: filePath,
152
+ content: truncatedContent,
153
+ lines: Math.min(lines.length, maxLines),
154
+ language: getLanguageFromPath(filePath),
155
+ };
156
+ }
157
+ catch {
158
+ return null;
159
+ }
160
+ }
161
+ /**
162
+ * Check if path should be excluded
163
+ */
164
+ function shouldExclude(relativePath, name, patterns) {
165
+ for (const pattern of patterns) {
166
+ if (pattern.startsWith('*.')) {
167
+ // Extension pattern
168
+ const ext = pattern.slice(1);
169
+ if (name.endsWith(ext))
170
+ return true;
171
+ }
172
+ else {
173
+ // Name or path pattern
174
+ if (name === pattern || relativePath.includes(pattern))
175
+ return true;
176
+ }
177
+ }
178
+ return false;
179
+ }
180
+ /**
181
+ * Check if file is analyzable (source code)
182
+ */
183
+ function isAnalyzableFile(name) {
184
+ const analyzableExtensions = [
185
+ '.ts',
186
+ '.tsx',
187
+ '.js',
188
+ '.jsx',
189
+ '.py',
190
+ '.rb',
191
+ '.go',
192
+ '.rs',
193
+ '.java',
194
+ '.kt',
195
+ '.swift',
196
+ '.c',
197
+ '.cpp',
198
+ '.h',
199
+ '.hpp',
200
+ '.cs',
201
+ '.php',
202
+ '.vue',
203
+ '.svelte',
204
+ ];
205
+ return analyzableExtensions.some((ext) => name.endsWith(ext));
206
+ }
207
+ /**
208
+ * Format code context for display/debugging
209
+ */
210
+ export function formatCodeContext(context) {
211
+ const lines = [];
212
+ lines.push(`Files: ${context.files.length}`);
213
+ lines.push(`Total Lines: ${context.totalLines}`);
214
+ lines.push(`Truncated: ${context.truncated}`);
215
+ lines.push('');
216
+ for (const file of context.files) {
217
+ lines.push(`--- ${file.path} (${file.language}, ${file.lines} lines) ---`);
218
+ }
219
+ return lines.join('\n');
220
+ }
221
+ //# sourceMappingURL=context-builder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-builder.js","sourceRoot":"","sources":["../src/context-builder.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAGL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAGlC;;GAEG;AACH,MAAM,wBAAwB,GAAG;IAC/B,cAAc;IACd,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,aAAa;IACb,MAAM;IACN,OAAO;IACP,UAAU;IACV,aAAa;IACb,UAAU;IACV,aAAa;IACb,OAAO;IACP,mBAAmB;IACnB,gBAAgB;IAChB,WAAW;CACZ,CAAC;AAEF;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAE1B;IADlB,YACkB,IAAY,EAC5B,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,SAAI,GAAJ,IAAI,CAAQ;QAI5B,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;CACF;AAED;;GAEG;AACH,MAAM,eAAe,GAAkB;IACrC,QAAQ,EAAE,EAAE;IACZ,eAAe,EAAE,oBAAoB;CACtC,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO;QACL,KAAK,CAAC,UAAU,CAAC,KAAe,EAAE,OAAgC;YAChE,MAAM,IAAI,GAAG,EAAE,GAAG,eAAe,EAAE,GAAG,OAAO,EAAE,CAAC;YAChD,MAAM,eAAe,GAAG;gBACtB,GAAG,wBAAwB;gBAC3B,GAAG,CAAC,IAAI,CAAC,eAAe,IAAI,EAAE,CAAC;aAChC,CAAC;YAEF,MAAM,KAAK,GAAmB,EAAE,CAAC;YACjC,IAAI,UAAU,GAAG,CAAC,CAAC;YACnB,IAAI,SAAS,GAAG,KAAK,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,CAAC;IAEf,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACjC,KAAK,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,KAAK,aAAa,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @defai.digital/analysis-domain
3
+ *
4
+ * Analysis Domain - LLM-delegated code analysis
5
+ *
6
+ * Provides bugfix, refactor, review, and explain capabilities
7
+ * by delegating analysis to LLM providers.
8
+ */
9
+ export { createCodeContextBuilder, formatCodeContext, ContextBuilderError, } from './context-builder.js';
10
+ export { createAnalysisPromptBuilder, getTaskDescription, } from './prompt-builder.js';
11
+ export { createAnalysisResponseParser, deduplicateFindings, ResponseParserError, } from './response-parser.js';
12
+ export { createAnalysisService, createSimpleProvider, AnalysisError, } from './analysis-service.js';
13
+ export { createAnalysisProviderRouter, createStubProviderRouter, type ProviderLike, type ProviderRegistryLike, type AnalysisProviderRouterConfig, } from './provider-router.js';
14
+ export type { CodeContextBuilder, AnalysisPromptBuilder, AnalysisResponseParser, AnalysisService, AnalysisServiceDeps, AnalysisProvider, ProviderRouter, ProviderRequest, ProviderResponse, GatherOptions, } from './types.js';
15
+ export type { AnalysisTask, AnalysisRequest, AnalysisResult, AnalysisFinding, CodeContext, AnalysisFile, FindingSeverity, AnalysisSeverityFilter, } from './types.js';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,4BAA4B,EAC5B,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,aAAa,GACd,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,EACxB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,KAAK,4BAA4B,GAClC,MAAM,sBAAsB,CAAC;AAG9B,YAAY,EACV,kBAAkB,EAClB,qBAAqB,EACrB,sBAAsB,EACtB,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,aAAa,GACd,MAAM,YAAY,CAAC;AAGpB,YAAY,EACV,YAAY,EACZ,eAAe,EACf,cAAc,EACd,eAAe,EACf,WAAW,EACX,YAAY,EACZ,eAAe,EACf,sBAAsB,GACvB,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @defai.digital/analysis-domain
3
+ *
4
+ * Analysis Domain - LLM-delegated code analysis
5
+ *
6
+ * Provides bugfix, refactor, review, and explain capabilities
7
+ * by delegating analysis to LLM providers.
8
+ */
9
+ // Context Builder
10
+ export { createCodeContextBuilder, formatCodeContext, ContextBuilderError, } from './context-builder.js';
11
+ // Prompt Builder
12
+ export { createAnalysisPromptBuilder, getTaskDescription, } from './prompt-builder.js';
13
+ // Response Parser
14
+ export { createAnalysisResponseParser, deduplicateFindings, ResponseParserError, } from './response-parser.js';
15
+ // Analysis Service
16
+ export { createAnalysisService, createSimpleProvider, AnalysisError, } from './analysis-service.js';
17
+ // Provider Router
18
+ export { createAnalysisProviderRouter, createStubProviderRouter, } from './provider-router.js';
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,kBAAkB;AAClB,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,sBAAsB,CAAC;AAE9B,iBAAiB;AACjB,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAE7B,kBAAkB;AAClB,OAAO,EACL,4BAA4B,EAC5B,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,sBAAsB,CAAC;AAE9B,mBAAmB;AACnB,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,aAAa,GACd,MAAM,uBAAuB,CAAC;AAE/B,kBAAkB;AAClB,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,GAIzB,MAAM,sBAAsB,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Analysis Prompt Builder
3
+ *
4
+ * Builds task-specific prompts for LLM analysis.
5
+ */
6
+ import type { AnalysisTask } from '@defai.digital/contracts';
7
+ import type { AnalysisPromptBuilder } from './types.js';
8
+ /**
9
+ * Creates an analysis prompt builder
10
+ */
11
+ export declare function createAnalysisPromptBuilder(): AnalysisPromptBuilder;
12
+ /**
13
+ * Get task description for display
14
+ */
15
+ export declare function getTaskDescription(task: AnalysisTask): string;
16
+ //# sourceMappingURL=prompt-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-builder.d.ts","sourceRoot":"","sources":["../src/prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAe,MAAM,0BAA0B,CAAC;AAC1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAsKxD;;GAEG;AACH,wBAAgB,2BAA2B,IAAI,qBAAqB,CAkBnE;AAuCD;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,GAAG,MAAM,CAa7D"}
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Analysis Prompt Builder
3
+ *
4
+ * Builds task-specific prompts for LLM analysis.
5
+ */
6
+ /**
7
+ * Bugfix analysis prompt template
8
+ */
9
+ const BUGFIX_PROMPT = `You are an expert code analyzer. Analyze the following code for bugs, errors, and potential issues.
10
+
11
+ Focus on:
12
+ - Logic errors and incorrect behavior
13
+ - Null/undefined reference issues
14
+ - Resource leaks (unclosed handles, missing cleanup)
15
+ - Type mismatches and type errors
16
+ - Concurrency issues (race conditions, deadlocks)
17
+ - Security vulnerabilities (injection, XSS, etc.)
18
+ - Error handling gaps
19
+ - Edge cases not handled
20
+
21
+ Code to analyze:
22
+ {code}
23
+
24
+ {userContext}
25
+
26
+ Return your findings as JSON in this exact format:
27
+ {
28
+ "findings": [
29
+ {
30
+ "file": "path/to/file.ts",
31
+ "line": 42,
32
+ "lineEnd": 45,
33
+ "title": "Brief issue title (max 100 chars)",
34
+ "description": "Detailed description of the issue and why it's a problem",
35
+ "severity": "high",
36
+ "category": "null-reference",
37
+ "suggestion": "How to fix this issue with specific code changes",
38
+ "confidence": 0.9
39
+ }
40
+ ]
41
+ }
42
+
43
+ Severity levels: "critical" (crashes/security), "high" (bugs), "medium" (potential issues), "low" (minor), "info" (suggestions)
44
+ Categories: "logic-error", "null-reference", "type-error", "resource-leak", "security", "concurrency", "error-handling", "edge-case", "other"
45
+
46
+ Important:
47
+ - Only report actual bugs and issues, not style preferences
48
+ - Be specific about line numbers and file paths
49
+ - Provide actionable suggestions
50
+ - If no issues found, return {"findings": []}
51
+ - Confidence should reflect certainty (0.0-1.0)`;
52
+ /**
53
+ * Refactor analysis prompt template
54
+ */
55
+ const REFACTOR_PROMPT = `You are an expert code refactoring advisor. Analyze the following code for refactoring opportunities.
56
+
57
+ Focus on:
58
+ - Functions that are too long or complex (>50 lines, >10 cyclomatic complexity)
59
+ - Duplicate code that could be extracted into shared functions
60
+ - Poor naming that reduces readability
61
+ - Complex conditionals that could be simplified
62
+ - Opportunities to improve type safety
63
+ - Code that violates single responsibility principle
64
+ - Outdated patterns that could be modernized
65
+ - Missing abstractions that would improve maintainability
66
+
67
+ Code to analyze:
68
+ {code}
69
+
70
+ {userContext}
71
+
72
+ Return your findings as JSON in this exact format:
73
+ {
74
+ "findings": [
75
+ {
76
+ "file": "path/to/file.ts",
77
+ "line": 42,
78
+ "lineEnd": 80,
79
+ "title": "Brief opportunity title (max 100 chars)",
80
+ "description": "Description of the refactoring opportunity",
81
+ "severity": "medium",
82
+ "category": "extract-function",
83
+ "suggestion": "Suggested refactoring approach with example code",
84
+ "confidence": 0.85
85
+ }
86
+ ]
87
+ }
88
+
89
+ Severity levels: "high" (significant improvement), "medium" (moderate improvement), "low" (minor improvement), "info" (optional)
90
+ Categories: "extract-function", "extract-variable", "simplify-conditional", "remove-duplication", "improve-types", "rename", "modernize", "split-responsibility", "other"
91
+
92
+ Important:
93
+ - Focus on impactful improvements that improve maintainability
94
+ - Do not report trivial style issues (formatting, spacing)
95
+ - Be specific about what to extract/change
96
+ - Provide concrete suggestions with example code
97
+ - If no opportunities found, return {"findings": []}`;
98
+ /**
99
+ * Code review prompt template
100
+ */
101
+ const REVIEW_PROMPT = `You are an expert code reviewer. Review the following code for quality, correctness, and best practices.
102
+
103
+ Consider:
104
+ - Code correctness and logic
105
+ - Error handling completeness
106
+ - Edge cases and boundary conditions
107
+ - Performance considerations
108
+ - Security best practices
109
+ - Code readability and maintainability
110
+ - Documentation quality
111
+ - Test coverage considerations
112
+
113
+ Code to review:
114
+ {code}
115
+
116
+ {userContext}
117
+
118
+ Return your review as JSON in this exact format:
119
+ {
120
+ "findings": [
121
+ {
122
+ "file": "path/to/file.ts",
123
+ "line": 42,
124
+ "title": "Review finding title",
125
+ "description": "Detailed explanation of the review finding",
126
+ "severity": "medium",
127
+ "category": "best-practice",
128
+ "suggestion": "Recommendation for improvement",
129
+ "confidence": 0.8
130
+ }
131
+ ]
132
+ }
133
+
134
+ Severity levels: "critical" (must fix), "high" (should fix), "medium" (consider fixing), "low" (nice to have), "info" (observation)
135
+ Categories: "correctness", "error-handling", "performance", "security", "readability", "documentation", "testing", "best-practice", "other"`;
136
+ /**
137
+ * Code explanation prompt template
138
+ */
139
+ const EXPLAIN_PROMPT = `You are an expert code explainer. Explain what the following code does.
140
+
141
+ Code to explain:
142
+ {code}
143
+
144
+ {userContext}
145
+
146
+ Return your explanation as JSON in this exact format:
147
+ {
148
+ "findings": [
149
+ {
150
+ "file": "path/to/file.ts",
151
+ "line": 1,
152
+ "title": "Code Overview",
153
+ "description": "High-level explanation of what this code does and its purpose",
154
+ "severity": "info",
155
+ "category": "explanation",
156
+ "suggestion": "Additional context or notes about the implementation",
157
+ "confidence": 1.0
158
+ }
159
+ ]
160
+ }
161
+
162
+ For each significant function/component, provide a separate finding explaining:
163
+ - What it does
164
+ - Key implementation details
165
+ - Any notable patterns or techniques used`;
166
+ /**
167
+ * Creates an analysis prompt builder
168
+ */
169
+ export function createAnalysisPromptBuilder() {
170
+ return {
171
+ buildPrompt(task, context, userContext) {
172
+ const template = getPromptTemplate(task);
173
+ const codeBlock = formatCodeForPrompt(context);
174
+ const contextBlock = userContext
175
+ ? `Additional context from user:\n${userContext}`
176
+ : '';
177
+ return template
178
+ .replace('{code}', codeBlock)
179
+ .replace('{userContext}', contextBlock);
180
+ },
181
+ };
182
+ }
183
+ /**
184
+ * Get prompt template for task
185
+ */
186
+ function getPromptTemplate(task) {
187
+ switch (task) {
188
+ case 'bugfix':
189
+ return BUGFIX_PROMPT;
190
+ case 'refactor':
191
+ return REFACTOR_PROMPT;
192
+ case 'review':
193
+ return REVIEW_PROMPT;
194
+ case 'explain':
195
+ return EXPLAIN_PROMPT;
196
+ default:
197
+ return REVIEW_PROMPT;
198
+ }
199
+ }
200
+ /**
201
+ * Format code context for inclusion in prompt
202
+ */
203
+ function formatCodeForPrompt(context) {
204
+ const parts = [];
205
+ for (const file of context.files) {
206
+ parts.push(`--- File: ${file.path} (${file.language}) ---`);
207
+ parts.push(file.content);
208
+ parts.push('');
209
+ }
210
+ if (context.truncated) {
211
+ parts.push('--- Note: Some files were truncated due to size limits ---');
212
+ }
213
+ return parts.join('\n');
214
+ }
215
+ /**
216
+ * Get task description for display
217
+ */
218
+ export function getTaskDescription(task) {
219
+ switch (task) {
220
+ case 'bugfix':
221
+ return 'Bug Detection';
222
+ case 'refactor':
223
+ return 'Refactoring Opportunities';
224
+ case 'review':
225
+ return 'Code Review';
226
+ case 'explain':
227
+ return 'Code Explanation';
228
+ default:
229
+ return 'Analysis';
230
+ }
231
+ }
232
+ //# sourceMappingURL=prompt-builder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-builder.js","sourceRoot":"","sources":["../src/prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAKH;;GAEG;AACH,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gDA0C0B,CAAC;AAEjD;;GAEG;AACH,MAAM,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qDA0C6B,CAAC;AAEtD;;GAEG;AACH,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4IAkCsH,CAAC;AAE7I;;GAEG;AACH,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;0CA0BmB,CAAC;AAE3C;;GAEG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO;QACL,WAAW,CACT,IAAkB,EAClB,OAAoB,EACpB,WAAoB;YAEpB,MAAM,QAAQ,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;YACzC,MAAM,SAAS,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;YAC/C,MAAM,YAAY,GAAG,WAAW;gBAC9B,CAAC,CAAC,kCAAkC,WAAW,EAAE;gBACjD,CAAC,CAAC,EAAE,CAAC;YAEP,OAAO,QAAQ;iBACZ,OAAO,CAAC,QAAQ,EAAE,SAAS,CAAC;iBAC5B,OAAO,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;QAC5C,CAAC;KACF,CA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implementations.
5
+ * Eliminates the mock provider by connecting to real provider registry.
6
+ */
7
+ import type { ProviderRouter } from './types.js';
8
+ /**
9
+ * Provider interface (minimal - matches what we need from provider adapters)
10
+ */
11
+ export interface ProviderLike {
12
+ providerId: string;
13
+ complete(request: {
14
+ requestId: string;
15
+ model: string;
16
+ messages: {
17
+ role: string;
18
+ content: string;
19
+ }[];
20
+ maxTokens?: number;
21
+ temperature?: number;
22
+ timeout?: number;
23
+ }): Promise<{
24
+ success: boolean;
25
+ content: string;
26
+ tokensUsed?: number;
27
+ } | {
28
+ success: false;
29
+ error: unknown;
30
+ }>;
31
+ isAvailable(): Promise<boolean>;
32
+ getModels(): readonly {
33
+ modelId: string;
34
+ isDefault?: boolean;
35
+ }[];
36
+ }
37
+ /**
38
+ * Provider registry interface (minimal - matches what we need)
39
+ */
40
+ export interface ProviderRegistryLike {
41
+ get(providerId: string): ProviderLike | undefined;
42
+ getProviderIds(): string[];
43
+ }
44
+ /**
45
+ * Configuration for the analysis provider router
46
+ */
47
+ export interface AnalysisProviderRouterConfig {
48
+ /** Provider registry to use */
49
+ registry: ProviderRegistryLike;
50
+ /** Default provider ID */
51
+ defaultProvider?: string;
52
+ /** Default timeout in ms */
53
+ defaultTimeout?: number;
54
+ }
55
+ /**
56
+ * Creates a provider router that bridges to real providers
57
+ */
58
+ export declare function createAnalysisProviderRouter(config: AnalysisProviderRouterConfig): ProviderRouter;
59
+ /**
60
+ * Creates a stub provider router for testing
61
+ * Returns empty findings (same as mock provider behavior)
62
+ */
63
+ export declare function createStubProviderRouter(): ProviderRouter;
64
+ //# sourceMappingURL=provider-router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-router.d.ts","sourceRoot":"","sources":["../src/provider-router.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAEV,cAAc,EAGf,MAAM,YAAY,CAAC;AAEpB;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,UAAU,EAAE,MAAM,CA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