@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.
- package/dist/analyzers/ComplexityCalculator.d.ts +15 -0
- package/dist/analyzers/ComplexityCalculator.js +59 -0
- package/dist/analyzers/QualityAnalyzer.d.ts +25 -0
- package/dist/analyzers/QualityAnalyzer.js +89 -0
- package/dist/analyzers/RefactoringEngine.d.ts +20 -0
- package/dist/analyzers/RefactoringEngine.js +107 -0
- package/dist/analyzers/SymbolAnalyzer.d.ts +30 -0
- package/dist/analyzers/SymbolAnalyzer.js +123 -0
- package/dist/analyzers/index.d.ts +8 -0
- package/dist/analyzers/index.js +4 -0
- package/dist/coding.test.js +4 -0
- package/dist/dashboard/index.html +95 -0
- package/dist/dashboard/server.js +1 -1
- package/dist/graph.d.ts +0 -6
- package/dist/graph.js +9 -265
- package/dist/intelligent-code.d.ts +2 -68
- package/dist/intelligent-code.js +10 -364
- package/dist/lib.d.ts +42 -0
- package/dist/lib.js +308 -237
- package/dist/parsers/GenericParser.d.ts +6 -0
- package/dist/parsers/GenericParser.js +52 -0
- package/dist/parsers/GoParser.d.ts +6 -0
- package/dist/parsers/GoParser.js +36 -0
- package/dist/parsers/JavaParser.d.ts +6 -0
- package/dist/parsers/JavaParser.js +32 -0
- package/dist/parsers/PythonParser.d.ts +6 -0
- package/dist/parsers/PythonParser.js +50 -0
- package/dist/parsers/RustParser.d.ts +6 -0
- package/dist/parsers/RustParser.js +33 -0
- package/dist/parsers/TypeScriptParser.d.ts +9 -0
- package/dist/parsers/TypeScriptParser.js +85 -0
- package/dist/parsers/index.d.ts +7 -0
- package/dist/parsers/index.js +6 -0
- package/dist/tools/sports/tools/match.js +2 -2
- package/dist/tools/web.js +4 -1
- package/package.json +1 -1
package/dist/lib.js
CHANGED
|
@@ -20,7 +20,14 @@ export class SequentialThinkingServer {
|
|
|
20
20
|
contextManager = new ContextManager();
|
|
21
21
|
ruleManager = new RuleManager();
|
|
22
22
|
maxHistorySize;
|
|
23
|
-
|
|
23
|
+
// Constants for configuration
|
|
24
|
+
static MAX_HISTORY_SIZE = 1000;
|
|
25
|
+
static AUTO_PRUNE_THRESHOLD = 100;
|
|
26
|
+
static CONFIDENCE_CRITICAL_THRESHOLD = 50;
|
|
27
|
+
static MAX_NESTING_DEPTH = 10;
|
|
28
|
+
static STALLING_THRESHOLD = 3;
|
|
29
|
+
static EXECUTION_STRUGGLE_THRESHOLD = 3;
|
|
30
|
+
constructor(storagePath = 'thoughts_history.json', delayMs = 0, maxHistorySize = SequentialThinkingServer.MAX_HISTORY_SIZE) {
|
|
24
31
|
this.maxHistorySize = maxHistorySize;
|
|
25
32
|
this.disableThoughtLogging = (process.env.DISABLE_THOUGHT_LOGGING || "").toLowerCase() === "true";
|
|
26
33
|
this.storagePath = path.resolve(storagePath);
|
|
@@ -190,8 +197,8 @@ export class SequentialThinkingServer {
|
|
|
190
197
|
async saveHistory() {
|
|
191
198
|
await this.saveMutex.dispatch(async () => {
|
|
192
199
|
try {
|
|
193
|
-
// Auto-Pruning: Keep max
|
|
194
|
-
if (this.thoughtHistory.length >
|
|
200
|
+
// Auto-Pruning: Keep max thoughts within threshold
|
|
201
|
+
if (this.thoughtHistory.length > SequentialThinkingServer.AUTO_PRUNE_THRESHOLD) {
|
|
195
202
|
try {
|
|
196
203
|
this.autoPrune();
|
|
197
204
|
}
|
|
@@ -270,9 +277,9 @@ export class SequentialThinkingServer {
|
|
|
270
277
|
this.blocks[i].status = 'completed';
|
|
271
278
|
}
|
|
272
279
|
}
|
|
273
|
-
// Keep only last
|
|
274
|
-
if (this.thoughtHistory.length >
|
|
275
|
-
const removed = this.thoughtHistory.splice(0, this.thoughtHistory.length -
|
|
280
|
+
// Keep only last N thoughts based on threshold
|
|
281
|
+
if (this.thoughtHistory.length > SequentialThinkingServer.AUTO_PRUNE_THRESHOLD) {
|
|
282
|
+
const removed = this.thoughtHistory.splice(0, this.thoughtHistory.length - SequentialThinkingServer.AUTO_PRUNE_THRESHOLD);
|
|
276
283
|
console.error(`[AutoPrune] Removed ${removed.length} old thoughts to maintain performance.`);
|
|
277
284
|
// Sync blocks: Remove pruned thoughts from their respective blocks
|
|
278
285
|
// This prevents unbounded file growth by ensuring blocks don't retain references to deleted thoughts
|
|
@@ -457,6 +464,281 @@ export class SequentialThinkingServer {
|
|
|
457
464
|
${typeof wrappedThought === 'string' && wrappedThought.startsWith('│') ? wrappedThought : `│ ${thought.padEnd(borderLength - 2)} │`}${extraContent}
|
|
458
465
|
└${border}┘`;
|
|
459
466
|
}
|
|
467
|
+
// --- Extracted Helper Methods for processThought ---
|
|
468
|
+
/**
|
|
469
|
+
* Handle block management - create new blocks or switch context
|
|
470
|
+
*/
|
|
471
|
+
async handleBlockManagement(input, warnings) {
|
|
472
|
+
if (!input.blockId) {
|
|
473
|
+
if (!this.currentBlockId) {
|
|
474
|
+
this.currentBlockId = `block-${Date.now()}`;
|
|
475
|
+
this.blocks.push({
|
|
476
|
+
id: this.currentBlockId,
|
|
477
|
+
topic: input.thought.substring(0, 50),
|
|
478
|
+
status: 'active',
|
|
479
|
+
thoughts: [],
|
|
480
|
+
createdAt: new Date().toISOString(),
|
|
481
|
+
updatedAt: new Date().toISOString()
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
input.blockId = this.currentBlockId;
|
|
485
|
+
}
|
|
486
|
+
else if (input.blockId !== this.currentBlockId) {
|
|
487
|
+
// Context switch detected
|
|
488
|
+
const oldBlock = this.blocks.find(b => b.id === this.currentBlockId);
|
|
489
|
+
if (oldBlock) {
|
|
490
|
+
oldBlock.status = 'completed';
|
|
491
|
+
await this.learnFromFailures(oldBlock.id);
|
|
492
|
+
// Auto-Summary Trigger
|
|
493
|
+
if (oldBlock.thoughts.length > 5) {
|
|
494
|
+
warnings.push(`📜 CONTEXT MANAGEMENT: Previous block '${oldBlock.topic.substring(0, 30)}...' was long. Please use 'summarize_history' to compress it.`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
this.currentBlockId = input.blockId;
|
|
498
|
+
const existingBlock = this.blocks.find(b => b.id === input.blockId);
|
|
499
|
+
if (!existingBlock) {
|
|
500
|
+
this.blocks.push({
|
|
501
|
+
id: input.blockId,
|
|
502
|
+
topic: input.thought.substring(0, 50),
|
|
503
|
+
status: 'active',
|
|
504
|
+
thoughts: [],
|
|
505
|
+
createdAt: new Date().toISOString(),
|
|
506
|
+
updatedAt: new Date().toISOString()
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
existingBlock.status = 'active';
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Detect loops, stalling, and other thinking pattern issues
|
|
516
|
+
*/
|
|
517
|
+
detectLoopsAndStalling(input, blockThoughts, recentInBlock, lastThought, complexity) {
|
|
518
|
+
const warnings = [];
|
|
519
|
+
let isStallingOrLooping = false;
|
|
520
|
+
const thinkingTypes = ['analysis', 'planning', 'hypothesis', 'generation', 'critique'];
|
|
521
|
+
// Rule 1: Stalling Detection (Adaptive)
|
|
522
|
+
if (complexity !== 'low') {
|
|
523
|
+
if (recentInBlock.length >= SequentialThinkingServer.STALLING_THRESHOLD &&
|
|
524
|
+
recentInBlock.every(t => thinkingTypes.includes(t.thoughtType || 'analysis')) &&
|
|
525
|
+
thinkingTypes.includes(input.thoughtType || 'analysis')) {
|
|
526
|
+
warnings.push(`⚠️ STALLING DETECTED: You have been thinking for 4 consecutive steps without execution. Consider changing thoughtType to 'execution' and calling a tool to make progress.`);
|
|
527
|
+
isStallingOrLooping = true;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
// Rule 2: Repeating Action Detection
|
|
531
|
+
if (input.thoughtType === 'execution') {
|
|
532
|
+
// Check Immune System Rules
|
|
533
|
+
const ruleWarnings = this.ruleManager.checkRules(input.thought);
|
|
534
|
+
ruleWarnings.forEach(w => warnings.push(w));
|
|
535
|
+
if (recentInBlock.some(t => t.thoughtType === 'execution' && t.thought === input.thought)) {
|
|
536
|
+
warnings.push(`🛑 LOOP DETECTED: You are attempting to execute the exact same action again. You MUST change your strategy or create a branch with a different approach.`);
|
|
537
|
+
isStallingOrLooping = true;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
// Rule 3: Missing Observation
|
|
541
|
+
if (lastThought &&
|
|
542
|
+
lastThought.thoughtType === 'execution' &&
|
|
543
|
+
input.thoughtType !== 'observation' &&
|
|
544
|
+
!input.branchFromThought) {
|
|
545
|
+
warnings.push(`💡 INTERLEAVED HINT: Your last step was 'execution'. The next step SHOULD be 'observation' to record and analyze the tool result before continuing.`);
|
|
546
|
+
}
|
|
547
|
+
// Rule 4: Skipping Planning (Adaptive)
|
|
548
|
+
if (complexity !== 'low') {
|
|
549
|
+
const hasPlanning = blockThoughts.some(t => t.thoughtType === 'planning');
|
|
550
|
+
if (!hasPlanning &&
|
|
551
|
+
blockThoughts.length >= 2 &&
|
|
552
|
+
input.thoughtType === 'execution') {
|
|
553
|
+
warnings.push(`📋 PLANNING HINT: You're about to execute without a planning step. Consider adding a 'planning' thought first to outline your approach.`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
// Rule 5: Devil's Advocate (Critique Phase)
|
|
557
|
+
if (complexity === 'high' && input.thoughtType === 'execution') {
|
|
558
|
+
const hasCritique = blockThoughts.some(t => t.thoughtType === 'critique');
|
|
559
|
+
if (!hasCritique) {
|
|
560
|
+
warnings.push(`🛑 CRITIQUE REQUIRED: High complexity task requires a 'critique' step before execution. Analyze risks and flaws in your plan first.`);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
// Rule 6: Ending without Verification
|
|
564
|
+
if (input.nextThoughtNeeded === false) {
|
|
565
|
+
const hasVerification = this.thoughtHistory.some(t => t.thought.toLowerCase().includes('test') ||
|
|
566
|
+
t.thought.toLowerCase().includes('verify') ||
|
|
567
|
+
t.thought.toLowerCase().includes('check') ||
|
|
568
|
+
t.thoughtType === 'observation');
|
|
569
|
+
if (!hasVerification) {
|
|
570
|
+
warnings.push(`🚨 CRITICAL: You are ending without explicit verification/testing. Consider adding an 'observation' or verification step.`);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
// Rule 7: Same type loop
|
|
574
|
+
if (complexity !== 'low' && recentInBlock.length >= SequentialThinkingServer.STALLING_THRESHOLD &&
|
|
575
|
+
recentInBlock.every(t => t.thoughtType === input.thoughtType)) {
|
|
576
|
+
warnings.push(`⚠️ TYPE LOOP: You've used '${input.thoughtType}' for 4 consecutive steps. Consider using a different thought type to progress.`);
|
|
577
|
+
}
|
|
578
|
+
// Rule 8: Struggle Detection
|
|
579
|
+
const executionCount = blockThoughts.filter(t => t.thoughtType === 'execution').length;
|
|
580
|
+
if (executionCount >= SequentialThinkingServer.EXECUTION_STRUGGLE_THRESHOLD && input.thoughtType === 'execution') {
|
|
581
|
+
warnings.push(`🛑 STRUGGLE DETECTED: You have executed ${SequentialThinkingServer.EXECUTION_STRUGGLE_THRESHOLD}+ commands in this block without reaching a solution. If you are fixing a bug and it's not working, STOP. Do not try a 4th time linearly. Use 'branchFromThought' to try a completely different approach.`);
|
|
582
|
+
}
|
|
583
|
+
// Rule 9: Premature Solution Detection
|
|
584
|
+
const hasObservation = blockThoughts.some(t => t.thoughtType === 'observation');
|
|
585
|
+
if (input.thoughtType === 'solution' && !hasObservation && blockThoughts.length < 4 && complexity !== 'low') {
|
|
586
|
+
warnings.push(`🤔 PREMATURE SOLUTION: You are concluding this block very quickly without any 'observation'. Are you hallucinating? Please verify with a tool first.`);
|
|
587
|
+
}
|
|
588
|
+
return { isStallingOrLooping, warnings };
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Validate solution before accepting
|
|
592
|
+
*/
|
|
593
|
+
async validateSolution(input, blockThoughts, complexity, warnings) {
|
|
594
|
+
const observations = blockThoughts.filter(t => t.thoughtType === 'observation');
|
|
595
|
+
if (observations.length === 0) {
|
|
596
|
+
warnings.push(`🚫 UNVERIFIED SOLUTION: You are attempting to solve without ANY observation/tool output in this block.`);
|
|
597
|
+
}
|
|
598
|
+
else {
|
|
599
|
+
const lastObservation = observations[observations.length - 1];
|
|
600
|
+
const failureKeywords = ['error', 'fail', 'exception', 'undefined', 'not found', 'enoent'];
|
|
601
|
+
const hasFailure = failureKeywords.some(kw => lastObservation.toolResult?.toLowerCase().includes(kw));
|
|
602
|
+
if (hasFailure) {
|
|
603
|
+
warnings.push(`⚠️ FAILURE DETECTED: The last observation contains failure signals ("${lastObservation.toolResult?.substring(0, 50)}..."). Fix the error first.`);
|
|
604
|
+
}
|
|
605
|
+
// Smart Search Verification
|
|
606
|
+
const searchTools = ['web_search', 'google_web_search', 'read_webpage', 'search_file_content', 'google_search'];
|
|
607
|
+
const isSearch = lastObservation.relatedToolCall && searchTools.some(tool => lastObservation.relatedToolCall.includes(tool));
|
|
608
|
+
if (isSearch) {
|
|
609
|
+
warnings.push(`🕵️ DATA INTEGRITY CHECK: You are concluding a search task. Verify: Did you actually find the specific answer?`);
|
|
610
|
+
}
|
|
611
|
+
// Double Verification for High Complexity
|
|
612
|
+
if (complexity === 'high' && observations.length < 2) {
|
|
613
|
+
warnings.push(`⚖️ DOUBLE VERIFICATION REQUIRED: High complexity tasks require at least 2 distinct observations/verifications before conclusion.`);
|
|
614
|
+
this.confidenceScore -= 10;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
// Save solution if no warnings
|
|
618
|
+
if (warnings.length === 0) {
|
|
619
|
+
const solutionSteps = blockThoughts
|
|
620
|
+
.filter(t => t.thoughtType === 'execution')
|
|
621
|
+
.map(t => t.thought);
|
|
622
|
+
const activeBlock = this.blocks.find(b => b.id === input.blockId);
|
|
623
|
+
await this.learnFromFailures(input.blockId || "");
|
|
624
|
+
await this.saveSolution(activeBlock?.topic || 'Untitled', input.thought, solutionSteps);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Update confidence score based on thought type and warnings
|
|
629
|
+
*/
|
|
630
|
+
updateConfidenceScore(input, warnings) {
|
|
631
|
+
if (warnings.length > 0) {
|
|
632
|
+
this.confidenceScore = Math.max(0, this.confidenceScore - (5 * warnings.length));
|
|
633
|
+
}
|
|
634
|
+
if (input.thoughtType === 'reflexion') {
|
|
635
|
+
this.confidenceScore = Math.min(100, this.confidenceScore + 10);
|
|
636
|
+
}
|
|
637
|
+
else if (input.thoughtType === 'observation') {
|
|
638
|
+
const isError = input.toolResult?.toLowerCase().includes('error');
|
|
639
|
+
if (isError)
|
|
640
|
+
this.confidenceScore -= 10;
|
|
641
|
+
else
|
|
642
|
+
this.confidenceScore = Math.min(100, this.confidenceScore + 10);
|
|
643
|
+
}
|
|
644
|
+
else if (input.thoughtType === 'solution' && warnings.length === 0) {
|
|
645
|
+
// Bonus for clean solution
|
|
646
|
+
this.confidenceScore = Math.min(100, this.confidenceScore + 20);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
// --- Helper Methods for processThought ---
|
|
650
|
+
/**
|
|
651
|
+
* Get block history for current input
|
|
652
|
+
*/
|
|
653
|
+
getBlockHistory(input) {
|
|
654
|
+
return this.thoughtHistory.filter(t => t.blockId === input.blockId ||
|
|
655
|
+
(input.blockId === this.currentBlockId && t.blockId === this.currentBlockId));
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Check for smart branching - reset confidence on pivot
|
|
659
|
+
*/
|
|
660
|
+
checkSmartBranching(input) {
|
|
661
|
+
if (input.branchFromThought && this.confidenceScore < 75) {
|
|
662
|
+
this.confidenceScore = 75;
|
|
663
|
+
return `\n🌿 BRANCH DETECTED: Confidence restored to 75. Good decision to pivot.`;
|
|
664
|
+
}
|
|
665
|
+
return "";
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Check semantic thought recall for analysis type
|
|
669
|
+
*/
|
|
670
|
+
async checkSemanticRecall(input) {
|
|
671
|
+
if (input.thoughtType === 'analysis') {
|
|
672
|
+
const previousSolution = await this.findSolution(input.thought);
|
|
673
|
+
if (previousSolution) {
|
|
674
|
+
return `\n💡 RECALL: I found a similar past solution for '${previousSolution.topic}'.\nTry these steps: ${previousSolution.solution.substring(0, 100)}...`;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
return "";
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Check anti-insanity - prevent repeating failed executions
|
|
681
|
+
*/
|
|
682
|
+
checkAntiInsanity(input, historyForCheck) {
|
|
683
|
+
const warnings = [];
|
|
684
|
+
if (input.thoughtType === 'execution') {
|
|
685
|
+
const failedExecutions = historyForCheck.filter(t => {
|
|
686
|
+
if (t.thoughtType !== 'execution')
|
|
687
|
+
return false;
|
|
688
|
+
// Find the observation immediately following this execution
|
|
689
|
+
const nextThought = this.thoughtHistory.find(h => h.thoughtNumber === t.thoughtNumber + 1);
|
|
690
|
+
if (nextThought && nextThought.thoughtType === 'observation') {
|
|
691
|
+
const result = nextThought.toolResult?.toLowerCase() || "";
|
|
692
|
+
// Check for failure signals
|
|
693
|
+
return result.includes("error") || result.includes("fail") ||
|
|
694
|
+
result.includes("exception") || result.includes("enoent");
|
|
695
|
+
}
|
|
696
|
+
return false;
|
|
697
|
+
});
|
|
698
|
+
const isRepeatedFailure = failedExecutions.some(t => t.thought.trim() === input.thought.trim());
|
|
699
|
+
if (isRepeatedFailure) {
|
|
700
|
+
const failedItem = failedExecutions.find(t => t.thought.trim() === input.thought.trim());
|
|
701
|
+
warnings.push(`⛔ INSANITY CHECK: You are trying to run a command that ALREADY FAILED in thought #${failedItem?.thoughtNumber}. STOP. Do not repeat mistakes. Try a different parameter or tool.`);
|
|
702
|
+
this.confidenceScore -= 15;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
return warnings;
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Check if confidence is critical and return critical stop response if needed
|
|
709
|
+
*/
|
|
710
|
+
checkConfidenceCritical(input, historyForCheck) {
|
|
711
|
+
if (this.confidenceScore >= SequentialThinkingServer.CONFIDENCE_CRITICAL_THRESHOLD ||
|
|
712
|
+
input.thoughtType === 'reflexion' ||
|
|
713
|
+
input.thoughtType === 'analysis') {
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
// Smart Branching: Find the last valid planning point
|
|
717
|
+
const lastGoodPlan = historyForCheck
|
|
718
|
+
.slice()
|
|
719
|
+
.reverse()
|
|
720
|
+
.find(t => t.thoughtType === 'planning' || t.thoughtType === 'hypothesis');
|
|
721
|
+
const recoveryAdvice = lastGoodPlan
|
|
722
|
+
? `RECOMMENDATION: Branch from thought #${lastGoodPlan.thoughtNumber} to try a new approach.`
|
|
723
|
+
: `RECOMMENDATION: Use 'reflexion' to analyze why current attempts are failing.`;
|
|
724
|
+
return {
|
|
725
|
+
content: [{
|
|
726
|
+
type: "text",
|
|
727
|
+
text: JSON.stringify({
|
|
728
|
+
status: "CRITICAL_STOP",
|
|
729
|
+
feedback: [
|
|
730
|
+
"🚨 CONFIDENCE CRITICAL (<50). Execution blocked to prevent further damage.",
|
|
731
|
+
"🛑 STOP: You are likely in a loop or making repeated errors.",
|
|
732
|
+
"👉 REQUIRED ACTION: You must switch thoughtType to 'reflexion' to critique your errors.",
|
|
733
|
+
"⚠️ REMEMBER: You MUST provide a 'thought' string explaining your reflection. Do not leave it empty.",
|
|
734
|
+
recoveryAdvice
|
|
735
|
+
],
|
|
736
|
+
confidenceScore: this.confidenceScore
|
|
737
|
+
}, null, 2)
|
|
738
|
+
}],
|
|
739
|
+
isError: true
|
|
740
|
+
};
|
|
741
|
+
}
|
|
460
742
|
// --- 2. The New Brain: Process Thought with Interleaved Logic (Opus 4.5 Style) ---
|
|
461
743
|
async processThought(input) {
|
|
462
744
|
try {
|
|
@@ -466,226 +748,31 @@ ${typeof wrappedThought === 'string' && wrappedThought.startsWith('│') ? wrapp
|
|
|
466
748
|
const complexity = input.complexity || 'medium';
|
|
467
749
|
const warnings = [];
|
|
468
750
|
let feedbackExtension = "";
|
|
469
|
-
// --- 🔄 FEATURE 0: Smart Branching Reward
|
|
470
|
-
|
|
471
|
-
if (this.confidenceScore < 75) {
|
|
472
|
-
this.confidenceScore = 75;
|
|
473
|
-
feedbackExtension += `\n🌿 BRANCH DETECTED: Confidence restored to 75. Good decision to pivot.`;
|
|
474
|
-
}
|
|
475
|
-
}
|
|
751
|
+
// --- 🔄 FEATURE 0: Smart Branching Reward ---
|
|
752
|
+
feedbackExtension += this.checkSmartBranching(input);
|
|
476
753
|
// --- 🧠 FEATURE 1: Semantic Thought Recall ---
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
if (input.thoughtType === 'execution') {
|
|
486
|
-
const failedExecutions = historyForCheck.filter((t, index) => {
|
|
487
|
-
if (t.thoughtType !== 'execution')
|
|
488
|
-
return false;
|
|
489
|
-
// Find the observation immediately following this execution
|
|
490
|
-
// Note: This relies on thoughtNumber order
|
|
491
|
-
const nextThought = this.thoughtHistory.find(h => h.thoughtNumber === t.thoughtNumber + 1);
|
|
492
|
-
if (nextThought && nextThought.thoughtType === 'observation') {
|
|
493
|
-
const result = nextThought.toolResult?.toLowerCase() || "";
|
|
494
|
-
// Check for failure signals
|
|
495
|
-
return result.includes("error") || result.includes("fail") || result.includes("exception") || result.includes("enoent");
|
|
496
|
-
}
|
|
497
|
-
return false;
|
|
498
|
-
});
|
|
499
|
-
const isRepeatedFailure = failedExecutions.some(t => t.thought.trim() === input.thought.trim());
|
|
500
|
-
if (isRepeatedFailure) {
|
|
501
|
-
const failedItem = failedExecutions.find(t => t.thought.trim() === input.thought.trim());
|
|
502
|
-
warnings.push(`⛔ INSANITY CHECK: You are trying to run a command that ALREADY FAILED in thought #${failedItem?.thoughtNumber}. STOP. Do not repeat mistakes. Try a different parameter or tool.`);
|
|
503
|
-
this.confidenceScore -= 15;
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
// --- 📊 FEATURE 4: Meta-Cognition Score Check (Reflexion Mandate & Smart Branching) ---
|
|
507
|
-
if (this.confidenceScore < 50 && input.thoughtType !== 'reflexion' && input.thoughtType !== 'analysis') {
|
|
508
|
-
// Smart Branching: Find the last valid planning point
|
|
509
|
-
const lastGoodPlan = historyForCheck
|
|
510
|
-
.slice()
|
|
511
|
-
.reverse()
|
|
512
|
-
.find(t => t.thoughtType === 'planning' || t.thoughtType === 'hypothesis');
|
|
513
|
-
const recoveryAdvice = lastGoodPlan
|
|
514
|
-
? `RECOMMENDATION: Branch from thought #${lastGoodPlan.thoughtNumber} to try a new approach.`
|
|
515
|
-
: `RECOMMENDATION: Use 'reflexion' to analyze why current attempts are failing.`;
|
|
516
|
-
return {
|
|
517
|
-
content: [{
|
|
518
|
-
type: "text",
|
|
519
|
-
text: JSON.stringify({
|
|
520
|
-
status: "CRITICAL_STOP",
|
|
521
|
-
feedback: [
|
|
522
|
-
"🚨 CONFIDENCE CRITICAL (<50). Execution blocked to prevent further damage.",
|
|
523
|
-
"🛑 STOP: You are likely in a loop or making repeated errors.",
|
|
524
|
-
"👉 REQUIRED ACTION: You must switch thoughtType to 'reflexion' to critique your errors.",
|
|
525
|
-
"⚠️ REMEMBER: You MUST provide a 'thought' string explaining your reflection. Do not leave it empty.",
|
|
526
|
-
recoveryAdvice
|
|
527
|
-
],
|
|
528
|
-
confidenceScore: this.confidenceScore
|
|
529
|
-
}, null, 2)
|
|
530
|
-
}],
|
|
531
|
-
isError: true
|
|
532
|
-
};
|
|
533
|
-
}
|
|
754
|
+
feedbackExtension += await this.checkSemanticRecall(input);
|
|
755
|
+
// --- ⛔ FEATURE 1.5: Anti-Insanity Check ---
|
|
756
|
+
const historyForCheck = this.getBlockHistory(input);
|
|
757
|
+
warnings.push(...this.checkAntiInsanity(input, historyForCheck));
|
|
758
|
+
// --- 📊 FEATURE 4: Meta-Cognition Score Check ---
|
|
759
|
+
const criticalResult = this.checkConfidenceCritical(input, historyForCheck);
|
|
760
|
+
if (criticalResult)
|
|
761
|
+
return criticalResult;
|
|
534
762
|
// A. Block Management (Auto-Create Block)
|
|
535
|
-
|
|
536
|
-
if (!this.currentBlockId) {
|
|
537
|
-
this.currentBlockId = `block-${Date.now()}`;
|
|
538
|
-
this.blocks.push({
|
|
539
|
-
id: this.currentBlockId,
|
|
540
|
-
topic: input.thought.substring(0, 50),
|
|
541
|
-
status: 'active',
|
|
542
|
-
thoughts: [],
|
|
543
|
-
createdAt: new Date().toISOString(),
|
|
544
|
-
updatedAt: new Date().toISOString()
|
|
545
|
-
});
|
|
546
|
-
}
|
|
547
|
-
input.blockId = this.currentBlockId;
|
|
548
|
-
}
|
|
549
|
-
else if (input.blockId !== this.currentBlockId) {
|
|
550
|
-
// Context switch detected
|
|
551
|
-
const oldBlock = this.blocks.find(b => b.id === this.currentBlockId);
|
|
552
|
-
if (oldBlock) {
|
|
553
|
-
oldBlock.status = 'completed';
|
|
554
|
-
await this.learnFromFailures(oldBlock.id);
|
|
555
|
-
// Auto-Summary Trigger
|
|
556
|
-
if (oldBlock.thoughts.length > 5) {
|
|
557
|
-
warnings.push(`📜 CONTEXT MANAGEMENT: Previous block '${oldBlock.topic.substring(0, 30)}...' was long. Please use 'summarize_history' to compress it.`);
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
this.currentBlockId = input.blockId;
|
|
561
|
-
const existingBlock = this.blocks.find(b => b.id === input.blockId);
|
|
562
|
-
if (!existingBlock) {
|
|
563
|
-
this.blocks.push({
|
|
564
|
-
id: input.blockId,
|
|
565
|
-
topic: input.thought.substring(0, 50),
|
|
566
|
-
status: 'active',
|
|
567
|
-
thoughts: [],
|
|
568
|
-
createdAt: new Date().toISOString(),
|
|
569
|
-
updatedAt: new Date().toISOString()
|
|
570
|
-
});
|
|
571
|
-
}
|
|
572
|
-
else {
|
|
573
|
-
existingBlock.status = 'active';
|
|
574
|
-
}
|
|
575
|
-
}
|
|
763
|
+
await this.handleBlockManagement(input, warnings);
|
|
576
764
|
// B. Smart Loop Detection (Opus Style)
|
|
577
765
|
const blockThoughts = this.thoughtHistory.filter(t => t.blockId === input.blockId);
|
|
578
|
-
const recentInBlock = blockThoughts.slice(-
|
|
766
|
+
const recentInBlock = blockThoughts.slice(-SequentialThinkingServer.STALLING_THRESHOLD);
|
|
579
767
|
const lastThought = this.thoughtHistory[this.thoughtHistory.length - 1];
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
if (recentInBlock.length >= 3 &&
|
|
585
|
-
recentInBlock.every(t => thinkingTypes.includes(t.thoughtType || 'analysis')) &&
|
|
586
|
-
thinkingTypes.includes(input.thoughtType || 'analysis')) {
|
|
587
|
-
warnings.push(`⚠️ STALLING DETECTED: You have been thinking for 4 consecutive steps without execution. Consider changing thoughtType to 'execution' and calling a tool to make progress.`);
|
|
588
|
-
isStallingOrLooping = true;
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
// Rule 2: Repeating Action Detection
|
|
592
|
-
if (input.thoughtType === 'execution') {
|
|
593
|
-
// Check Immune System Rules
|
|
594
|
-
const ruleWarnings = this.ruleManager.checkRules(input.thought);
|
|
595
|
-
ruleWarnings.forEach(w => warnings.push(w));
|
|
596
|
-
if (ruleWarnings.length > 0)
|
|
597
|
-
this.confidenceScore -= 10;
|
|
598
|
-
if (recentInBlock.some(t => t.thoughtType === 'execution' && t.thought === input.thought)) {
|
|
599
|
-
warnings.push(`🛑 LOOP DETECTED: You are attempting to execute the exact same action again. You MUST change your strategy or create a branch with a different approach.`);
|
|
600
|
-
isStallingOrLooping = true;
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
// Rule 3: Missing Observation
|
|
604
|
-
if (lastThought &&
|
|
605
|
-
lastThought.thoughtType === 'execution' &&
|
|
606
|
-
input.thoughtType !== 'observation' &&
|
|
607
|
-
!input.branchFromThought) {
|
|
608
|
-
warnings.push(`💡 INTERLEAVED HINT: Your last step was 'execution'. The next step SHOULD be 'observation' to record and analyze the tool result before continuing.`);
|
|
609
|
-
}
|
|
610
|
-
// Rule 4: Skipping Planning (Adaptive)
|
|
611
|
-
if (complexity !== 'low') {
|
|
612
|
-
const hasPlanning = blockThoughts.some(t => t.thoughtType === 'planning');
|
|
613
|
-
if (!hasPlanning &&
|
|
614
|
-
blockThoughts.length >= 2 &&
|
|
615
|
-
input.thoughtType === 'execution') {
|
|
616
|
-
warnings.push(`📋 PLANNING HINT: You're about to execute without a planning step. Consider adding a 'planning' thought first to outline your approach.`);
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
// --- 🕵️ FEATURE 3: Devil's Advocate (Critique Phase) ---
|
|
620
|
-
if (complexity === 'high' && input.thoughtType === 'execution') {
|
|
621
|
-
const hasCritique = blockThoughts.some(t => t.thoughtType === 'critique');
|
|
622
|
-
if (!hasCritique) {
|
|
623
|
-
warnings.push(`🛑 CRITIQUE REQUIRED: High complexity task requires a 'critique' step before execution. Analyze risks and flaws in your plan first.`);
|
|
624
|
-
// Note: We don't block execution, but we heavily warn.
|
|
625
|
-
this.confidenceScore -= 10;
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
// Rule 5: Ending without Verification
|
|
629
|
-
if (input.nextThoughtNeeded === false) {
|
|
630
|
-
const hasVerification = this.thoughtHistory.some(t => t.thought.toLowerCase().includes('test') ||
|
|
631
|
-
t.thought.toLowerCase().includes('verify') ||
|
|
632
|
-
t.thought.toLowerCase().includes('check') ||
|
|
633
|
-
t.thoughtType === 'observation');
|
|
634
|
-
if (!hasVerification) {
|
|
635
|
-
warnings.push(`🚨 CRITICAL: You are ending without explicit verification/testing. Consider adding an 'observation' or verification step.`);
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
// Rule 6: Same type loop
|
|
639
|
-
if (complexity !== 'low' && recentInBlock.length >= 3 &&
|
|
640
|
-
recentInBlock.every(t => t.thoughtType === input.thoughtType)) {
|
|
641
|
-
warnings.push(`⚠️ TYPE LOOP: You've used '${input.thoughtType}' for 4 consecutive steps. Consider using a different thought type to progress.`);
|
|
642
|
-
}
|
|
643
|
-
// Rule 7: Struggle Detection
|
|
644
|
-
const executionCount = blockThoughts.filter(t => t.thoughtType === 'execution').length;
|
|
645
|
-
if (executionCount >= 3 && input.thoughtType === 'execution') {
|
|
646
|
-
warnings.push(`🛑 STRUGGLE DETECTED: You have executed 3+ commands in this block without reaching a solution. If you are fixing a bug and it's not working, STOP. Do not try a 4th time linearly. Use 'branchFromThought' to try a completely different approach.`);
|
|
647
|
-
}
|
|
648
|
-
// Rule 8: Premature Solution Detection
|
|
649
|
-
const hasObservation = blockThoughts.some(t => t.thoughtType === 'observation');
|
|
650
|
-
if (input.thoughtType === 'solution' && !hasObservation && blockThoughts.length < 4 && complexity !== 'low') {
|
|
651
|
-
warnings.push(`🤔 PREMATURE SOLUTION: You are concluding this block very quickly without any 'observation'. Are you hallucinating? Please verify with a tool first.`);
|
|
652
|
-
}
|
|
653
|
-
// Rule 10: Mandatory Verification (Gatekeeper) & Double Verification
|
|
768
|
+
const loopDetection = this.detectLoopsAndStalling(input, blockThoughts, recentInBlock, lastThought, complexity);
|
|
769
|
+
warnings.push(...loopDetection.warnings);
|
|
770
|
+
let isStallingOrLooping = loopDetection.isStallingOrLooping;
|
|
771
|
+
// C. Validate Solution
|
|
654
772
|
if (input.thoughtType === 'solution') {
|
|
655
|
-
|
|
656
|
-
if (observations.length === 0) {
|
|
657
|
-
warnings.push(`🚫 UNVERIFIED SOLUTION: You are attempting to solve without ANY observation/tool output in this block.`);
|
|
658
|
-
}
|
|
659
|
-
else {
|
|
660
|
-
const lastObservation = observations[observations.length - 1];
|
|
661
|
-
const failureKeywords = ['error', 'fail', 'exception', 'undefined', 'not found', 'enoent'];
|
|
662
|
-
const hasFailure = failureKeywords.some(kw => lastObservation.toolResult?.toLowerCase().includes(kw));
|
|
663
|
-
if (hasFailure) {
|
|
664
|
-
warnings.push(`⚠️ FAILURE DETECTED: The last observation contains failure signals ("${lastObservation.toolResult?.substring(0, 50)}..."). Fix the error first.`);
|
|
665
|
-
}
|
|
666
|
-
// Smart Search Verification
|
|
667
|
-
const searchTools = ['web_search', 'google_web_search', 'read_webpage', 'search_file_content', 'google_search'];
|
|
668
|
-
const isSearch = lastObservation.relatedToolCall && searchTools.some(tool => lastObservation.relatedToolCall.includes(tool));
|
|
669
|
-
if (isSearch) {
|
|
670
|
-
warnings.push(`🕵️ DATA INTEGRITY CHECK: You are concluding a search task. Verify: Did you actually find the specific answer?`);
|
|
671
|
-
}
|
|
672
|
-
// --- 🎚️ FEATURE 2: Double Verification for High Complexity ---
|
|
673
|
-
if (complexity === 'high' && observations.length < 2) {
|
|
674
|
-
warnings.push(`⚖️ DOUBLE VERIFICATION REQUIRED: High complexity tasks require at least 2 distinct observations/verifications before conclusion.`);
|
|
675
|
-
this.confidenceScore -= 10;
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
// --- 🧠 FEATURE 1: Save Solution (Semantic Memory) ---
|
|
679
|
-
if (warnings.length === 0) {
|
|
680
|
-
const solutionSteps = blockThoughts
|
|
681
|
-
.filter(t => t.thoughtType === 'execution')
|
|
682
|
-
.map(t => t.thought);
|
|
683
|
-
const activeBlock = this.blocks.find(b => b.id === input.blockId);
|
|
684
|
-
await this.learnFromFailures(input.blockId || "");
|
|
685
|
-
await this.saveSolution(activeBlock?.topic || 'Untitled', input.thought, solutionSteps);
|
|
686
|
-
}
|
|
773
|
+
await this.validateSolution(input, blockThoughts, complexity, warnings);
|
|
687
774
|
}
|
|
688
|
-
// Human Escalation Trigger
|
|
775
|
+
// D. Human Escalation Trigger
|
|
689
776
|
if (isStallingOrLooping) {
|
|
690
777
|
this.consecutiveStallCount++;
|
|
691
778
|
if (this.consecutiveStallCount >= 2) {
|
|
@@ -695,24 +782,8 @@ ${typeof wrappedThought === 'string' && wrappedThought.startsWith('│') ? wrapp
|
|
|
695
782
|
else {
|
|
696
783
|
this.consecutiveStallCount = 0;
|
|
697
784
|
}
|
|
698
|
-
//
|
|
699
|
-
|
|
700
|
-
this.confidenceScore = Math.max(0, this.confidenceScore - (5 * warnings.length));
|
|
701
|
-
}
|
|
702
|
-
if (input.thoughtType === 'reflexion') {
|
|
703
|
-
this.confidenceScore = Math.min(100, this.confidenceScore + 10);
|
|
704
|
-
}
|
|
705
|
-
else if (input.thoughtType === 'observation') {
|
|
706
|
-
const isError = input.toolResult?.toLowerCase().includes('error');
|
|
707
|
-
if (isError)
|
|
708
|
-
this.confidenceScore -= 10;
|
|
709
|
-
else
|
|
710
|
-
this.confidenceScore = Math.min(100, this.confidenceScore + 10);
|
|
711
|
-
}
|
|
712
|
-
else if (input.thoughtType === 'solution' && warnings.length === 0) {
|
|
713
|
-
// Bonus for clean solution
|
|
714
|
-
this.confidenceScore = Math.min(100, this.confidenceScore + 20);
|
|
715
|
-
}
|
|
785
|
+
// E. Update Confidence Score
|
|
786
|
+
this.updateConfidenceScore(input, warnings);
|
|
716
787
|
// C. Update State
|
|
717
788
|
this.addToMemory(input);
|
|
718
789
|
await this.saveHistory();
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import * as fs from 'fs/promises';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
export class GenericParser {
|
|
4
|
+
async parse(filePath) {
|
|
5
|
+
try {
|
|
6
|
+
const content = await fs.readFile(filePath, 'utf-8');
|
|
7
|
+
const imports = [];
|
|
8
|
+
const symbols = [];
|
|
9
|
+
const ext = path.extname(filePath);
|
|
10
|
+
// C/C++
|
|
11
|
+
if (['.c', '.cpp', '.h', '.hpp', '.cc', '.cxx'].includes(ext)) {
|
|
12
|
+
const includeMatches = content.matchAll(/#include\s*[<"]([^>"]+)[>"]/g);
|
|
13
|
+
for (const match of includeMatches)
|
|
14
|
+
imports.push(match[1]);
|
|
15
|
+
const funcMatches = content.matchAll(/^\w[\w\s*]+\s+(\w+)\s*\([^)]*\)\s*{/gm);
|
|
16
|
+
for (const match of funcMatches)
|
|
17
|
+
symbols.push(`function:${match[1]}`);
|
|
18
|
+
}
|
|
19
|
+
// Ruby
|
|
20
|
+
else if (ext === '.rb') {
|
|
21
|
+
const requireMatches = content.matchAll(/require\s+['"]([^'"]+)['"]/g);
|
|
22
|
+
for (const match of requireMatches)
|
|
23
|
+
imports.push(match[1]);
|
|
24
|
+
const defMatches = content.matchAll(/^def\s+([a-z_][a-z0-9_!?]*)/gm);
|
|
25
|
+
for (const match of defMatches)
|
|
26
|
+
symbols.push(`def:${match[1]}`);
|
|
27
|
+
const classMatches = content.matchAll(/^class\s+([A-Z][A-Za-z0-9_]*)/gm);
|
|
28
|
+
for (const match of classMatches)
|
|
29
|
+
symbols.push(`class:${match[1]}`);
|
|
30
|
+
}
|
|
31
|
+
// PHP
|
|
32
|
+
else if (ext === '.php') {
|
|
33
|
+
const useMatches = content.matchAll(/^use\s+([^;]+);/gm);
|
|
34
|
+
for (const match of useMatches)
|
|
35
|
+
imports.push(match[1].trim());
|
|
36
|
+
const funcMatches = content.matchAll(/^function\s+([a-z_][a-z0-9_]*)/gm);
|
|
37
|
+
for (const match of funcMatches)
|
|
38
|
+
symbols.push(`function:${match[1]}`);
|
|
39
|
+
const classMatches = content.matchAll(/^class\s+([A-Z][A-Za-z0-9_]*)/gm);
|
|
40
|
+
for (const match of classMatches)
|
|
41
|
+
symbols.push(`class:${match[1]}`);
|
|
42
|
+
}
|
|
43
|
+
return { imports, symbols };
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
console.error(`Error parsing generic file ${filePath}:`, error);
|
|
47
|
+
return { imports: [], symbols: [] };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export const genericParser = new GenericParser();
|
|
52
|
+
export default genericParser;
|