@gotza02/sequential-thinking 10000.1.7 → 10000.1.8

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 (36) hide show
  1. package/dist/analyzers/ComplexityCalculator.d.ts +15 -0
  2. package/dist/analyzers/ComplexityCalculator.js +59 -0
  3. package/dist/analyzers/QualityAnalyzer.d.ts +25 -0
  4. package/dist/analyzers/QualityAnalyzer.js +89 -0
  5. package/dist/analyzers/RefactoringEngine.d.ts +20 -0
  6. package/dist/analyzers/RefactoringEngine.js +107 -0
  7. package/dist/analyzers/SymbolAnalyzer.d.ts +30 -0
  8. package/dist/analyzers/SymbolAnalyzer.js +123 -0
  9. package/dist/analyzers/index.d.ts +8 -0
  10. package/dist/analyzers/index.js +4 -0
  11. package/dist/coding.test.js +4 -0
  12. package/dist/dashboard/index.html +95 -0
  13. package/dist/dashboard/server.js +1 -1
  14. package/dist/graph.d.ts +0 -6
  15. package/dist/graph.js +9 -265
  16. package/dist/intelligent-code.d.ts +2 -68
  17. package/dist/intelligent-code.js +10 -364
  18. package/dist/lib.d.ts +42 -0
  19. package/dist/lib.js +308 -237
  20. package/dist/parsers/GenericParser.d.ts +6 -0
  21. package/dist/parsers/GenericParser.js +52 -0
  22. package/dist/parsers/GoParser.d.ts +6 -0
  23. package/dist/parsers/GoParser.js +36 -0
  24. package/dist/parsers/JavaParser.d.ts +6 -0
  25. package/dist/parsers/JavaParser.js +32 -0
  26. package/dist/parsers/PythonParser.d.ts +6 -0
  27. package/dist/parsers/PythonParser.js +50 -0
  28. package/dist/parsers/RustParser.d.ts +6 -0
  29. package/dist/parsers/RustParser.js +33 -0
  30. package/dist/parsers/TypeScriptParser.d.ts +9 -0
  31. package/dist/parsers/TypeScriptParser.js +85 -0
  32. package/dist/parsers/index.d.ts +7 -0
  33. package/dist/parsers/index.js +6 -0
  34. package/dist/tools/sports/tools/match.js +2 -2
  35. package/dist/tools/web.js +4 -1
  36. package/package.json +1 -1
@@ -8,6 +8,7 @@ import { exec } from 'child_process';
8
8
  import { promisify } from 'util';
9
9
  import ts from 'typescript';
10
10
  import { validatePath } from './utils.js';
11
+ import { complexityCalculator, qualityAnalyzer, symbolAnalyzer, refactoringEngine } from './analyzers/index.js';
11
12
  const execAsync = promisify(exec);
12
13
  // ============= Intelligent Code Analyzer =============
13
14
  export class IntelligentCodeAnalyzer {
@@ -25,271 +26,14 @@ export class IntelligentCodeAnalyzer {
25
26
  const content = await fs.readFile(absolutePath, 'utf-8');
26
27
  // Parse AST
27
28
  const sourceFile = ts.createSourceFile(absolutePath, content, ts.ScriptTarget.Latest, true);
28
- // Calculate metrics
29
- const metrics = this.calculateMetrics(sourceFile, content);
30
- // Analyze quality
31
- const quality = await this.analyzeQuality(sourceFile, content, metrics);
32
- // Extract symbols with analysis
33
- const symbols = this.analyzeSymbols(sourceFile);
29
+ // Calculate metrics using extracted analyzer
30
+ const metrics = complexityCalculator.calculate(sourceFile, content);
31
+ // Analyze quality using extracted analyzer
32
+ const quality = await qualityAnalyzer.analyze(sourceFile, content, metrics);
33
+ // Extract symbols with analysis using extracted analyzer
34
+ const symbols = symbolAnalyzer.analyze(sourceFile);
34
35
  return { metrics, quality, ast: sourceFile, symbols };
35
36
  }
36
- calculateMetrics(sourceFile, content) {
37
- let complexity = 0;
38
- let functionCount = 0;
39
- let maxNestingDepth = 0;
40
- let currentDepth = 0;
41
- const visit = (node) => {
42
- // Cyclomatic complexity
43
- if (ts.isIfStatement(node) ||
44
- ts.isConditionalExpression(node) ||
45
- ts.isWhileStatement(node) ||
46
- ts.isForStatement(node) ||
47
- ts.isForInStatement(node) ||
48
- ts.isForOfStatement(node) ||
49
- ts.isCaseClause(node) ||
50
- (ts.isBinaryExpression(node) &&
51
- (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
52
- node.operatorToken.kind === ts.SyntaxKind.BarBarToken))) {
53
- complexity++;
54
- }
55
- // Function count
56
- if (ts.isFunctionDeclaration(node) ||
57
- ts.isArrowFunction(node) ||
58
- ts.isMethodDeclaration(node)) {
59
- functionCount++;
60
- }
61
- // Nesting depth
62
- if (ts.isBlock(node) ||
63
- ts.isIfStatement(node) ||
64
- ts.isForStatement(node) ||
65
- ts.isWhileStatement(node)) {
66
- currentDepth++;
67
- maxNestingDepth = Math.max(maxNestingDepth, currentDepth);
68
- }
69
- ts.forEachChild(node, visit);
70
- if (ts.isBlock(node) ||
71
- ts.isIfStatement(node) ||
72
- ts.isForStatement(node) ||
73
- ts.isWhileStatement(node)) {
74
- currentDepth--;
75
- }
76
- };
77
- visit(sourceFile);
78
- const lines = content.split('\n');
79
- const codeLines = lines.filter(l => l.trim().length > 0 && !l.trim().startsWith('//'));
80
- const commentLines = lines.filter(l => l.trim().startsWith('//') || l.trim().startsWith('/*'));
81
- return {
82
- complexity: complexity + 1, // Base complexity is 1
83
- linesOfCode: codeLines.length,
84
- commentRatio: codeLines.length > 0 ? commentLines.length / codeLines.length : 0,
85
- functionCount,
86
- maxNestingDepth,
87
- duplicateCode: 0, // Would need cross-file analysis
88
- };
89
- }
90
- async analyzeQuality(sourceFile, content, metrics) {
91
- const issues = [];
92
- // Complexity checks
93
- if (metrics.complexity > 20) {
94
- issues.push({
95
- type: 'warning',
96
- category: 'complexity',
97
- message: `High cyclomatic complexity (${metrics.complexity}). Consider refactoring.`,
98
- severity: 7,
99
- suggestion: 'Extract smaller functions or simplify conditional logic',
100
- autoFixable: false,
101
- });
102
- }
103
- if (metrics.maxNestingDepth > 4) {
104
- issues.push({
105
- type: 'warning',
106
- category: 'maintainability',
107
- message: `Deep nesting detected (${metrics.maxNestingDepth} levels)`,
108
- severity: 6,
109
- suggestion: 'Use early returns or extract nested logic into functions',
110
- autoFixable: false,
111
- });
112
- }
113
- // Comment ratio
114
- if (metrics.commentRatio < 0.05 && metrics.linesOfCode > 50) {
115
- issues.push({
116
- type: 'info',
117
- category: 'maintainability',
118
- message: 'Low comment ratio. Consider adding documentation.',
119
- severity: 3,
120
- suggestion: 'Add JSDoc comments for public APIs',
121
- autoFixable: false,
122
- });
123
- }
124
- // Function length
125
- const visit = (node) => {
126
- if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
127
- const start = node.getStart(sourceFile);
128
- const end = node.getEnd();
129
- const functionLines = content.substring(start, end).split('\n').length;
130
- if (functionLines > 50) {
131
- issues.push({
132
- type: 'warning',
133
- category: 'maintainability',
134
- message: `Long function detected (${functionLines} lines)`,
135
- line: ts.getLineAndCharacterOfPosition(sourceFile, node.getStart()).line + 1,
136
- severity: 6,
137
- suggestion: 'Extract helper functions to reduce function length',
138
- autoFixable: false,
139
- });
140
- }
141
- }
142
- ts.forEachChild(node, visit);
143
- };
144
- visit(sourceFile);
145
- // Check for any types
146
- const anyTypeRegex = /:\s*any\b/g;
147
- const anyMatches = content.match(anyTypeRegex);
148
- if (anyMatches && anyMatches.length > 5) {
149
- issues.push({
150
- type: 'warning',
151
- category: 'maintainability',
152
- message: `Excessive use of 'any' type (${anyMatches.length} occurrences)`,
153
- severity: 5,
154
- suggestion: 'Replace with proper types or use unknown with type guards',
155
- autoFixable: false,
156
- });
157
- }
158
- // Calculate scores
159
- const maintainability = Math.max(0, 100 - metrics.complexity * 2 - metrics.maxNestingDepth * 5);
160
- const reliability = Math.max(0, 100 - (anyMatches?.length || 0) * 5);
161
- const security = 100; // Would need security-specific checks
162
- const performance = 100; // Would need performance analysis
163
- const issuePenalty = issues.reduce((sum, i) => sum + i.severity * 2, 0);
164
- const overall = Math.max(0, Math.min(100, (maintainability + reliability + security + performance) / 4 - issuePenalty));
165
- return {
166
- overall: Math.round(overall),
167
- maintainability: Math.round(maintainability),
168
- reliability: Math.round(reliability),
169
- security,
170
- performance,
171
- issues: issues.sort((a, b) => b.severity - a.severity),
172
- };
173
- }
174
- analyzeSymbols(sourceFile) {
175
- const symbols = [];
176
- const visit = (node) => {
177
- if (ts.isFunctionDeclaration(node) && node.name) {
178
- const symbol = this.analyzeFunction(node, sourceFile);
179
- if (symbol)
180
- symbols.push(symbol);
181
- }
182
- else if (ts.isClassDeclaration(node) && node.name) {
183
- const symbol = this.analyzeClass(node, sourceFile);
184
- if (symbol)
185
- symbols.push(symbol);
186
- }
187
- else if (ts.isInterfaceDeclaration(node)) {
188
- const symbol = this.analyzeInterface(node, sourceFile);
189
- if (symbol)
190
- symbols.push(symbol);
191
- }
192
- ts.forEachChild(node, visit);
193
- };
194
- visit(sourceFile);
195
- return symbols;
196
- }
197
- analyzeFunction(node, sourceFile) {
198
- if (!node.name)
199
- return null;
200
- const params = node.parameters.map(p => ({
201
- name: p.name.getText(sourceFile),
202
- type: p.type?.getText(sourceFile) || 'unknown',
203
- optional: !!p.questionToken,
204
- }));
205
- const returnType = node.type?.getText(sourceFile) || 'inferred';
206
- // Check for async
207
- const isAsync = node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword);
208
- // Calculate function complexity
209
- let complexity = 1;
210
- const countComplexity = (n) => {
211
- if (ts.isIfStatement(n) ||
212
- ts.isWhileStatement(n) ||
213
- ts.isForStatement(n) ||
214
- ts.isConditionalExpression(n)) {
215
- complexity++;
216
- }
217
- ts.forEachChild(n, countComplexity);
218
- };
219
- countComplexity(node);
220
- return {
221
- name: node.name.text,
222
- kind: 'function',
223
- params,
224
- returnType,
225
- isAsync,
226
- complexity,
227
- isExported: node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) || false,
228
- documentation: this.extractJSDoc(node, sourceFile),
229
- };
230
- }
231
- analyzeClass(node, sourceFile) {
232
- if (!node.name)
233
- return null;
234
- const methods = [];
235
- const properties = [];
236
- node.members.forEach(member => {
237
- if (ts.isMethodDeclaration(member) && member.name) {
238
- methods.push({
239
- name: member.name.getText(sourceFile),
240
- kind: 'method',
241
- params: member.parameters.map(p => ({
242
- name: p.name.getText(sourceFile),
243
- type: p.type?.getText(sourceFile) || 'unknown',
244
- })),
245
- returnType: member.type?.getText(sourceFile) || 'void',
246
- isAsync: member.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || false,
247
- complexity: 1,
248
- isExported: false,
249
- });
250
- }
251
- else if (ts.isPropertyDeclaration(member) && member.name) {
252
- properties.push({
253
- name: member.name.getText(sourceFile),
254
- type: member.type?.getText(sourceFile) || 'unknown',
255
- });
256
- }
257
- });
258
- return {
259
- name: node.name.text,
260
- kind: 'class',
261
- methods,
262
- properties,
263
- isExported: node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) || false,
264
- documentation: this.extractJSDoc(node, sourceFile),
265
- };
266
- }
267
- analyzeInterface(node, sourceFile) {
268
- const properties = node.members.map(member => {
269
- if (ts.isPropertySignature(member) && member.name) {
270
- return {
271
- name: member.name.getText(sourceFile),
272
- type: member.type?.getText(sourceFile) || 'unknown',
273
- optional: !!member.questionToken,
274
- };
275
- }
276
- return null;
277
- }).filter((p) => p !== null);
278
- return {
279
- name: node.name.text,
280
- kind: 'interface',
281
- properties,
282
- isExported: node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) || false,
283
- documentation: this.extractJSDoc(node, sourceFile),
284
- };
285
- }
286
- extractJSDoc(node, sourceFile) {
287
- const jsDoc = node.jsDoc;
288
- if (jsDoc && jsDoc.length > 0) {
289
- return jsDoc[0].comment?.toString();
290
- }
291
- return undefined;
292
- }
293
37
  /**
294
38
  * Smart impact analysis - predicts what will be affected by changes
295
39
  */
@@ -396,109 +140,11 @@ export class IntelligentCodeAnalyzer {
396
140
  * Generate intelligent refactoring suggestions
397
141
  */
398
142
  async suggestRefactoring(filePath) {
399
- const { ast, metrics, quality } = await this.analyzeFile(filePath);
143
+ const { ast, metrics } = await this.analyzeFile(filePath);
400
144
  if (!ast)
401
145
  return [];
402
- const suggestions = [];
403
- // Suggest extracting long functions
404
- if (metrics.complexity > 10) {
405
- const longFunctions = this.findLongFunctions(ast);
406
- for (const func of longFunctions) {
407
- suggestions.push({
408
- type: 'extract-method',
409
- description: `Extract ${func.name} into smaller functions`,
410
- currentCode: func.code,
411
- suggestedCode: `// Suggested: Split into ${Math.ceil(func.lines / 20)} helper functions`,
412
- confidence: 85,
413
- impact: 'medium',
414
- effort: 'moderate',
415
- benefits: ['Reduced complexity', 'Better testability', 'Easier maintenance'],
416
- });
417
- }
418
- }
419
- // Simplify nested conditionals
420
- const nestedConditionals = this.findNestedConditionals(ast);
421
- for (const nested of nestedConditionals) {
422
- suggestions.push({
423
- type: 'simplify',
424
- description: 'Simplify deeply nested conditionals',
425
- currentCode: nested.code,
426
- suggestedCode: '// Use early returns or extract into guard clauses',
427
- confidence: 90,
428
- impact: 'low',
429
- effort: 'quick',
430
- benefits: ['Improved readability', 'Reduced cognitive load'],
431
- });
432
- }
433
- // Add types for any
434
- const anyUsages = this.findAnyUsages(ast);
435
- if (anyUsages.length > 0) {
436
- suggestions.push({
437
- type: 'add-types',
438
- description: `Replace ${anyUsages.length} 'any' types with proper types`,
439
- currentCode: anyUsages.map(a => a.code).join('\n'),
440
- suggestedCode: '// Define proper interfaces or use unknown with type guards',
441
- confidence: 80,
442
- impact: 'medium',
443
- effort: 'moderate',
444
- benefits: ['Type safety', 'Better IDE support', 'Fewer runtime errors'],
445
- });
446
- }
447
- return suggestions.sort((a, b) => b.confidence - a.confidence);
448
- }
449
- findLongFunctions(sourceFile) {
450
- const functions = [];
451
- const content = sourceFile.getFullText();
452
- const visit = (node) => {
453
- if (ts.isFunctionDeclaration(node) && node.name) {
454
- const start = node.getStart(sourceFile);
455
- const end = node.getEnd();
456
- const code = content.substring(start, end);
457
- const lines = code.split('\n').length;
458
- if (lines > 30) {
459
- functions.push({
460
- name: node.name.text,
461
- lines,
462
- code: code.substring(0, 200) + '...',
463
- });
464
- }
465
- }
466
- ts.forEachChild(node, visit);
467
- };
468
- visit(sourceFile);
469
- return functions;
470
- }
471
- findNestedConditionals(sourceFile) {
472
- const nested = [];
473
- const content = sourceFile.getFullText();
474
- const visit = (node, depth = 0) => {
475
- if (ts.isIfStatement(node)) {
476
- if (depth > 3) {
477
- const code = content.substring(node.getStart(sourceFile), node.getEnd());
478
- nested.push({ depth, code: code.substring(0, 150) + '...' });
479
- }
480
- ts.forEachChild(node, n => visit(n, depth + 1));
481
- }
482
- else {
483
- ts.forEachChild(node, n => visit(n, depth));
484
- }
485
- };
486
- visit(sourceFile);
487
- return nested;
488
- }
489
- findAnyUsages(sourceFile) {
490
- const usages = [];
491
- const content = sourceFile.getFullText();
492
- const visit = (node) => {
493
- if (ts.isTypeReferenceNode(node) && node.typeName.getText(sourceFile) === 'any') {
494
- usages.push({
495
- code: content.substring(node.getStart(sourceFile), node.getEnd()),
496
- });
497
- }
498
- ts.forEachChild(node, visit);
499
- };
500
- visit(sourceFile);
501
- return usages;
146
+ // Use refactoring engine to generate suggestions
147
+ return refactoringEngine.suggest(ast, metrics);
502
148
  }
503
149
  /**
504
150
  * Semantic code search - find code by concept, not just text
package/dist/lib.d.ts CHANGED
@@ -41,6 +41,12 @@ export declare class SequentialThinkingServer {
41
41
  private contextManager;
42
42
  private ruleManager;
43
43
  private maxHistorySize;
44
+ private static readonly MAX_HISTORY_SIZE;
45
+ private static readonly AUTO_PRUNE_THRESHOLD;
46
+ private static readonly CONFIDENCE_CRITICAL_THRESHOLD;
47
+ private static readonly MAX_NESTING_DEPTH;
48
+ private static readonly STALLING_THRESHOLD;
49
+ private static readonly EXECUTION_STRUGGLE_THRESHOLD;
44
50
  constructor(storagePath?: string, delayMs?: number, maxHistorySize?: number);
45
51
  private loadHistory;
46
52
  private attemptRecovery;
@@ -58,6 +64,42 @@ export declare class SequentialThinkingServer {
58
64
  searchHistory(query: string): Promise<ThoughtData[]>;
59
65
  private addToMemory;
60
66
  private formatThought;
67
+ /**
68
+ * Handle block management - create new blocks or switch context
69
+ */
70
+ private handleBlockManagement;
71
+ /**
72
+ * Detect loops, stalling, and other thinking pattern issues
73
+ */
74
+ private detectLoopsAndStalling;
75
+ /**
76
+ * Validate solution before accepting
77
+ */
78
+ private validateSolution;
79
+ /**
80
+ * Update confidence score based on thought type and warnings
81
+ */
82
+ private updateConfidenceScore;
83
+ /**
84
+ * Get block history for current input
85
+ */
86
+ private getBlockHistory;
87
+ /**
88
+ * Check for smart branching - reset confidence on pivot
89
+ */
90
+ private checkSmartBranching;
91
+ /**
92
+ * Check semantic thought recall for analysis type
93
+ */
94
+ private checkSemanticRecall;
95
+ /**
96
+ * Check anti-insanity - prevent repeating failed executions
97
+ */
98
+ private checkAntiInsanity;
99
+ /**
100
+ * Check if confidence is critical and return critical stop response if needed
101
+ */
102
+ private checkConfidenceCritical;
61
103
  processThought(input: ThoughtData): Promise<{
62
104
  content: any[];
63
105
  isError?: boolean;