@gotza02/sequential-thinking 10000.2.0 → 10000.2.1

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.
@@ -30,6 +30,27 @@ function normalizeTeamName(name) {
30
30
  .replace(/\s+/g, ' ')
31
31
  .trim();
32
32
  }
33
+ /**
34
+ * Check if a team name matches exactly or is contained within another name
35
+ * Uses more strict matching to avoid false positives
36
+ */
37
+ function isTeamMatch(teamName, matchName) {
38
+ const normalizedSearch = normalizeTeamName(teamName);
39
+ const normalizedMatch = normalizeTeamName(matchName);
40
+ // Exact match
41
+ if (normalizedSearch === normalizedMatch)
42
+ return true;
43
+ // Check if search is contained as a word in match
44
+ const searchWords = normalizedSearch.split(/\s+/).filter(w => w.length > 2);
45
+ const matchWords = normalizedMatch.split(/\s+/).filter(w => w.length > 2);
46
+ // Must have at least one significant word in common
47
+ const commonWords = searchWords.filter(w => matchWords.includes(w));
48
+ // For longer names, require more matching words
49
+ if (searchWords.length >= 2) {
50
+ return commonWords.length >= Math.min(2, searchWords.length);
51
+ }
52
+ return commonWords.length > 0;
53
+ }
33
54
  /**
34
55
  * Try to find match ID from API by team names and league
35
56
  */
@@ -48,9 +69,9 @@ async function findMatchId(homeTeam, awayTeam, league) {
48
69
  if (liveResult.success && liveResult.data) {
49
70
  const match = liveResult.data.find(m => {
50
71
  const isHomeMatch = homeIds.includes(m.homeTeam.id) ||
51
- normalizeTeamName(m.homeTeam.name).includes(normalizeTeamName(homeTeam));
72
+ isTeamMatch(homeTeam, m.homeTeam.name);
52
73
  const isAwayMatch = awayIds.includes(m.awayTeam.id) ||
53
- normalizeTeamName(m.awayTeam.name).includes(normalizeTeamName(awayTeam));
74
+ isTeamMatch(awayTeam, m.awayTeam.name);
54
75
  return isHomeMatch && isAwayMatch;
55
76
  });
56
77
  if (match)
@@ -248,7 +269,7 @@ function formatH2HData(h2h, homeTeam, awayTeam) {
248
269
  * Get match result character (W/D/L) for a team
249
270
  */
250
271
  function getMatchResultChar(match, teamName) {
251
- const isHome = match.homeTeam.name.includes(teamName);
272
+ const isHome = isTeamMatch(teamName, match.homeTeam.name);
252
273
  const homeScore = match.score?.home ?? 0;
253
274
  const awayScore = match.score?.away ?? 0;
254
275
  if (isHome) {
@@ -265,7 +286,8 @@ function formatTeamForm(form, teamName, isHomeTeam) {
265
286
  const label = isHomeTeam ? 'Home' : 'Away';
266
287
  let output = `### ${teamName} Recent Form (Last ${form.length})\n`;
267
288
  output += form.map(m => {
268
- const opponent = isHomeTeam ? m.awayTeam.name : m.homeTeam.name;
289
+ const isHomeInMatch = isTeamMatch(teamName, m.homeTeam.name);
290
+ const opponent = isHomeInMatch ? m.awayTeam.name : m.homeTeam.name;
269
291
  const score = m.score ? `${m.score.home}-${m.score.away}` : '?';
270
292
  const result = getMatchResultChar(m, teamName);
271
293
  return `- ${result} vs ${opponent} (${score})`;
@@ -472,15 +494,19 @@ function calculateProbabilityRange(baseProbability, dataQuality) {
472
494
  // Higher data quality = narrower range
473
495
  const qualityFactor = dataQuality.score / 100;
474
496
  const baseUncertainty = 0.15; // 15% base uncertainty
475
- // Adjust uncertainty based on data quality
497
+ // Adjust uncertainty based on data quality (better quality = smaller range)
476
498
  const adjustedUncertainty = baseUncertainty * (1 - qualityFactor * 0.7);
477
- // Calculate range
499
+ // Calculate range using standard error formula
500
+ // For binomial proportion: SE = sqrt(p*(1-p)/n)
501
+ // We use a simplified version based on data quality
478
502
  const mid = baseProbability;
479
- const margin = adjustedUncertainty * Math.sqrt(baseProbability * (1 - baseProbability));
503
+ // Margin decreases with better data quality
504
+ // Using 1.96 for ~95% confidence interval (2 standard deviations)
505
+ const margin = adjustedUncertainty * Math.sqrt(mid * (1 - mid) + 0.1);
480
506
  return {
481
- low: Math.max(0, mid - margin * 1.645), // 5th percentile
482
- mid,
483
- high: Math.min(1, mid + margin * 1.645), // 95th percentile
507
+ low: Math.max(0, mid - margin * 1.96),
508
+ mid: Math.min(1, Math.max(0, mid)),
509
+ high: Math.min(1, mid + margin * 1.96),
484
510
  };
485
511
  }
486
512
  /**
@@ -493,22 +519,33 @@ async function detectValueBets(apiData, homeTeam, awayTeam) {
493
519
  // Estimate probabilities from API data
494
520
  // Simple model: use form and H2H to estimate
495
521
  let homeWinProb = 0.33;
496
- let drawProb = 0.33;
522
+ let drawProb = 0.34;
497
523
  let awayWinProb = 0.33;
498
- if (apiData.homeForm && apiData.awayForm) {
499
- const homeWins = apiData.homeForm.filter(m => {
500
- const isHome = m.homeTeam.name.includes(homeTeam);
501
- return isHome ? (m.score?.home ?? 0) > (m.score?.away ?? 0) : (m.score?.away ?? 0) > (m.score?.home ?? 0);
502
- }).length;
503
- const awayWins = apiData.awayForm.filter(m => {
504
- const isAway = m.awayTeam.name.includes(awayTeam);
505
- return isAway ? (m.score?.away ?? 0) > (m.score?.home ?? 0) : (m.score?.home ?? 0) > (m.score?.away ?? 0);
506
- }).length;
507
- // Normalize to probabilities
508
- const total = homeWins + awayWins + 2; // +2 for draws
509
- homeWinProb = (homeWins + 1) / total;
510
- awayWinProb = (awayWins + 1) / total;
511
- drawProb = 1 - homeWinProb - awayWinProb;
524
+ if (apiData.homeForm?.length && apiData.awayForm?.length) {
525
+ // Calculate form based on points (3 for win, 1 for draw)
526
+ const homePoints = calculateFormPoints(apiData.homeForm, homeTeam);
527
+ const awayPoints = calculateFormPoints(apiData.awayForm, awayTeam);
528
+ // Number of matches played
529
+ const homeMatches = apiData.homeForm.length;
530
+ const awayMatches = apiData.awayForm.length;
531
+ // Points per game
532
+ const homePPG = homePoints / homeMatches;
533
+ const awayPPG = awayPoints / awayMatches;
534
+ // Max PPG is 3, so normalize to probability
535
+ // Give small bonus to home team (home advantage ~5-10%)
536
+ const totalPPG = homePPG + awayPPG;
537
+ if (totalPPG > 0) {
538
+ homeWinProb = Math.min(0.6, (homePPG / totalPPG) * 0.9 + 0.05); // Home advantage
539
+ awayWinProb = Math.min(0.5, (awayPPG / totalPPG) * 0.9);
540
+ // Draw probability based on how close the teams are
541
+ const ppgDiff = Math.abs(homePPG - awayPPG);
542
+ drawProb = Math.max(0.15, 0.35 - ppgDiff * 0.1); // Closer teams = higher draw chance
543
+ // Normalize to ensure sum = 1
544
+ const total = homeWinProb + drawProb + awayWinProb;
545
+ homeWinProb /= total;
546
+ drawProb /= total;
547
+ awayWinProb /= total;
548
+ }
512
549
  }
513
550
  // Calculate value for each market
514
551
  const markets = [
@@ -537,6 +574,100 @@ async function detectValueBets(apiData, homeTeam, awayTeam) {
537
574
  });
538
575
  }
539
576
  }
577
+ // Check Asian Handicap market if available
578
+ if (apiData.odds.asianHandicap) {
579
+ const ah = apiData.odds.asianHandicap;
580
+ // Estimate AH probability based on match probabilities and line
581
+ // Simplified: home wins if they overcome the handicap
582
+ const ahHomeProb = homeWinProb + (drawProb * 0.5); // Approximate
583
+ const ahAwayProb = awayWinProb + (drawProb * 0.5);
584
+ if (ah.home && ahHomeProb > 0) {
585
+ const fairOdds = 1 / ahHomeProb;
586
+ const value = (ah.home / fairOdds) - 1;
587
+ if (value >= 0.05) {
588
+ const kelly = (ahHomeProb * ah.home - 1) / (ah.home - 1);
589
+ valueBets.push({
590
+ selection: `${homeTeam} AH ${ah.line > 0 ? '+' : ''}${ah.line}`,
591
+ market: 'asian_handicap',
592
+ odds: ah.home,
593
+ fairOdds,
594
+ value,
595
+ confidence: Math.min(90, 50 + value * 200),
596
+ kellyFraction: Math.max(0, kelly / 2),
597
+ recommendedStake: Math.max(0, kelly / 2) * 100,
598
+ reasoning: `Line ${ah.line}, estimated prob ${(ahHomeProb * 100).toFixed(1)}%`,
599
+ });
600
+ }
601
+ }
602
+ if (ah.away && ahAwayProb > 0) {
603
+ const fairOdds = 1 / ahAwayProb;
604
+ const value = (ah.away / fairOdds) - 1;
605
+ if (value >= 0.05) {
606
+ const kelly = (ahAwayProb * ah.away - 1) / (ah.away - 1);
607
+ valueBets.push({
608
+ selection: `${awayTeam} AH ${ah.line > 0 ? '-' : '+'}${Math.abs(ah.line)}`,
609
+ market: 'asian_handicap',
610
+ odds: ah.away,
611
+ fairOdds,
612
+ value,
613
+ confidence: Math.min(90, 50 + value * 200),
614
+ kellyFraction: Math.max(0, kelly / 2),
615
+ recommendedStake: Math.max(0, kelly / 2) * 100,
616
+ reasoning: `Line ${-ah.line}, estimated prob ${(ahAwayProb * 100).toFixed(1)}%`,
617
+ });
618
+ }
619
+ }
620
+ }
621
+ // Check Over/Under market if available
622
+ if (apiData.odds.overUnder) {
623
+ const ou = apiData.odds.overUnder;
624
+ // Estimate over probability based on expected goals
625
+ const expectedTotal = (apiData.homeForm?.length && apiData.awayForm?.length)
626
+ ? calculateExpectedGoals(apiData, homeTeam, awayTeam)
627
+ : { home: 1.5, away: 1.2 };
628
+ const totalXG = expectedTotal.home + expectedTotal.away;
629
+ // Simple model: over if total xG > line
630
+ const overProb = totalXG > ou.line
631
+ ? 0.5 + (totalXG - ou.line) * 0.1
632
+ : 0.5 - (ou.line - totalXG) * 0.1;
633
+ const underProb = 1 - overProb;
634
+ if (ou.over && overProb > 0) {
635
+ const fairOdds = 1 / Math.min(0.9, Math.max(0.1, overProb));
636
+ const value = (ou.over / fairOdds) - 1;
637
+ if (value >= 0.05) {
638
+ const kelly = (overProb * ou.over - 1) / (ou.over - 1);
639
+ valueBets.push({
640
+ selection: `Over ${ou.line}`,
641
+ market: 'over_under',
642
+ odds: ou.over,
643
+ fairOdds,
644
+ value,
645
+ confidence: Math.min(90, 50 + value * 200),
646
+ kellyFraction: Math.max(0, kelly / 2),
647
+ recommendedStake: Math.max(0, kelly / 2) * 100,
648
+ reasoning: `Line ${ou.line}, expected goals ${totalXG.toFixed(1)}`,
649
+ });
650
+ }
651
+ }
652
+ if (ou.under && underProb > 0) {
653
+ const fairOdds = 1 / Math.min(0.9, Math.max(0.1, underProb));
654
+ const value = (ou.under / fairOdds) - 1;
655
+ if (value >= 0.05) {
656
+ const kelly = (underProb * ou.under - 1) / (ou.under - 1);
657
+ valueBets.push({
658
+ selection: `Under ${ou.line}`,
659
+ market: 'over_under',
660
+ odds: ou.under,
661
+ fairOdds,
662
+ value,
663
+ confidence: Math.min(90, 50 + value * 200),
664
+ kellyFraction: Math.max(0, kelly / 2),
665
+ recommendedStake: Math.max(0, kelly / 2) * 100,
666
+ reasoning: `Line ${ou.line}, expected goals ${totalXG.toFixed(1)}`,
667
+ });
668
+ }
669
+ }
670
+ }
540
671
  return valueBets.sort((a, b) => b.value - a.value);
541
672
  }
542
673
  /**
@@ -544,7 +675,7 @@ async function detectValueBets(apiData, homeTeam, awayTeam) {
544
675
  */
545
676
  function calculateFormPoints(form, teamName) {
546
677
  return form.reduce((sum, m) => {
547
- const isHome = m.homeTeam.name.includes(teamName);
678
+ const isHome = isTeamMatch(teamName, m.homeTeam.name);
548
679
  const score = m.score;
549
680
  if (!score)
550
681
  return sum;
@@ -558,16 +689,90 @@ function calculateFormPoints(form, teamName) {
558
689
  }, 0);
559
690
  }
560
691
  /**
561
- * Calculate probabilities from form data
692
+ * Calculate expected goals from form data
693
+ * Uses average goals scored and conceded to estimate xG
694
+ */
695
+ function calculateExpectedGoals(apiData, homeTeam, awayTeam) {
696
+ if (!apiData?.homeForm?.length || !apiData?.awayForm?.length) {
697
+ // Default: league average with home advantage
698
+ return { home: 1.5, away: 1.2 };
699
+ }
700
+ // Calculate average goals scored and conceded for home team
701
+ let homeGoalsScored = 0;
702
+ let homeGoalsConceded = 0;
703
+ let homeMatchesWithScores = 0;
704
+ for (const match of apiData.homeForm) {
705
+ if (match.score) {
706
+ const isHomeInMatch = isTeamMatch(homeTeam, match.homeTeam.name);
707
+ homeGoalsScored += isHomeInMatch ? match.score.home : match.score.away;
708
+ homeGoalsConceded += isHomeInMatch ? match.score.away : match.score.home;
709
+ homeMatchesWithScores++;
710
+ }
711
+ }
712
+ // Calculate average goals scored and conceded for away team
713
+ let awayGoalsScored = 0;
714
+ let awayGoalsConceded = 0;
715
+ let awayMatchesWithScores = 0;
716
+ for (const match of apiData.awayForm) {
717
+ if (match.score) {
718
+ const isAwayInMatch = isTeamMatch(awayTeam, match.awayTeam.name);
719
+ awayGoalsScored += isAwayInMatch ? match.score.away : match.score.home;
720
+ awayGoalsConceded += isAwayInMatch ? match.score.home : match.score.away;
721
+ awayMatchesWithScores++;
722
+ }
723
+ }
724
+ // Calculate averages
725
+ const homeScoringAvg = homeMatchesWithScores > 0 ? homeGoalsScored / homeMatchesWithScores : 1.5;
726
+ const homeConcedingAvg = homeMatchesWithScores > 0 ? homeGoalsConceded / homeMatchesWithScores : 1.2;
727
+ const awayScoringAvg = awayMatchesWithScores > 0 ? awayGoalsScored / awayMatchesWithScores : 1.2;
728
+ const awayConcedingAvg = awayMatchesWithScores > 0 ? awayGoalsConceded / awayMatchesWithScores : 1.5;
729
+ // xG estimate using average of "what team scores" and "what opponent concedes"
730
+ // with home advantage adjustment
731
+ const homeAdvantage = 1.15; // ~15% boost for home
732
+ const homeXG = ((homeScoringAvg + awayConcedingAvg) / 2) * homeAdvantage;
733
+ const awayXG = (awayScoringAvg + homeConcedingAvg) / 2;
734
+ // Clamp to reasonable values (0.5 to 3.5 goals)
735
+ return {
736
+ home: Math.min(3.5, Math.max(0.5, homeXG)),
737
+ away: Math.min(3.5, Math.max(0.5, awayXG)),
738
+ };
739
+ }
740
+ /**
741
+ * Calculate probabilities from form data using proper normalization
562
742
  */
563
743
  function calculateProbabilitiesFromForm(homeForm, awayForm, homeTeam, awayTeam) {
564
744
  const homePoints = calculateFormPoints(homeForm, homeTeam);
565
745
  const awayPoints = calculateFormPoints(awayForm, awayTeam);
566
- const totalPoints = homePoints + awayPoints + 5; // +5 for draw possibility
746
+ // Points per game
747
+ const homePPG = homePoints / Math.max(1, homeForm.length);
748
+ const awayPPG = awayPoints / Math.max(1, awayForm.length);
749
+ // Use Bradley-Terry inspired model
750
+ // Convert PPG to relative strength (max 3 points per game)
751
+ const homeStrength = homePPG / 3;
752
+ const awayStrength = awayPPG / 3;
753
+ // Apply home advantage (~10% boost)
754
+ const homeAdvantage = 1.1;
755
+ const effectiveHomeStrength = homeStrength * homeAdvantage;
756
+ // Calculate probabilities
757
+ const totalStrength = effectiveHomeStrength + awayStrength;
758
+ if (totalStrength < 0.1) {
759
+ // Not enough data, return defaults
760
+ return { homeWin: 0.35, draw: 0.30, awayWin: 0.35 };
761
+ }
762
+ // Raw win probabilities (before draw adjustment)
763
+ const rawHomeWin = effectiveHomeStrength / totalStrength;
764
+ const rawAwayWin = awayStrength / totalStrength;
765
+ // Draw probability based on how close teams are
766
+ // When teams are equal, draw probability is higher
767
+ const strengthDiff = Math.abs(homeStrength - awayStrength);
768
+ const drawProb = Math.max(0.15, 0.30 - strengthDiff * 0.3);
769
+ // Adjust win probabilities to account for draw
770
+ const remainingProb = 1 - drawProb;
771
+ const winRatio = rawHomeWin / (rawHomeWin + rawAwayWin);
567
772
  return {
568
- homeWin: (homePoints + 1.5) / totalPoints,
569
- draw: 5 / totalPoints,
570
- awayWin: (awayPoints + 1.5) / totalPoints,
773
+ homeWin: remainingProb * winRatio,
774
+ draw: drawProb,
775
+ awayWin: remainingProb * (1 - winRatio),
571
776
  };
572
777
  }
573
778
  /**
@@ -609,7 +814,7 @@ async function buildStructuredAnalysis(homeTeam, awayTeam, league, apiData, cove
609
814
  homeWinProbability: predictions.matchResult.homeWin,
610
815
  drawProbability: predictions.matchResult.draw,
611
816
  awayWinProbability: predictions.matchResult.awayWin,
612
- expectedGoals: { home: 1.3, away: 1.2 }, // Placeholder - would need xG data
817
+ expectedGoals: calculateExpectedGoals(apiData, homeTeam, awayTeam),
613
818
  keyStats: [],
614
819
  },
615
820
  tacticalScout: {
@@ -821,8 +1026,8 @@ Data cached for 1 minute.`, {
821
1026
  matches = result.data;
822
1027
  // Filter by team if specified
823
1028
  if (team) {
824
- matches = matches.filter((m) => m.homeTeam.name.toLowerCase().includes(team.toLowerCase()) ||
825
- m.awayTeam.name.toLowerCase().includes(team.toLowerCase()));
1029
+ matches = matches.filter((m) => isTeamMatch(team, m.homeTeam.name) ||
1030
+ isTeamMatch(team, m.awayTeam.name));
826
1031
  }
827
1032
  // Limit results
828
1033
  matches = matches.slice(0, limit);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gotza02/sequential-thinking",
3
- "version": "10000.2.0",
3
+ "version": "10000.2.1",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/CLAUDE.md DELETED
@@ -1,231 +0,0 @@
1
- # SmartAgent Elite Controller - System Instructions
2
-
3
- You are an AI assistant powered by the Sequential Thinking MCP server (@gotza02/sequential-thinking@10000.1.9).
4
-
5
- ## Critical Prime Directives
6
-
7
- 1. **ALWAYS use sequentialthinking tool for complex tasks**
8
- - Flow: Analysis → Planning → [Critique] → Execution → Observation → Reflection
9
- - Confidence scoring: Track your certainty level (0-100)
10
- - Block-based context: Group related thoughts
11
-
12
- 2. **NEVER hallucinate information**
13
- - Use web search (Brave/Exa/DuckDuckGo) for up-to-date facts
14
- - Use sports APIs for match data
15
- - Cache results appropriately
16
-
17
- 3. **Safety protocols are mandatory**
18
- - Auto-backup before file edits via deep_code_edit
19
- - Ask human approval for destructive actions
20
- - Path traversal checks enforced
21
-
22
- ## Complete Tool Reference
23
-
24
- ### 🧠 Sequential Thinking Tools
25
- | Tool | Purpose | When to Use |
26
- |------|---------|-------------|
27
- | `sequentialthinking` | Structured problem-solving | Complex tasks requiring multiple steps |
28
- | `analysis` | Break down requirements | Understanding the problem |
29
- | `planning` | Formulate execution plan | Before taking action |
30
- | `critique` | Review plan for risks | High-stakes decisions |
31
- | `execution` | Perform tool calls | During implementation |
32
- | `observation` | Record tool outputs | After each tool call |
33
- | `reflection` | Self-review and adjust | When stuck or after errors |
34
- | `hypothesis` | Form new theories | Based on observations |
35
-
36
- ### ⚽ Sports Intelligence Tools
37
- | Tool | Purpose | When to Use |
38
- |------|---------|-------------|
39
- | `analyze_football_match_v2` | Comprehensive match analysis | Need detailed text analysis |
40
- | `analyze_football_match_structured` | JSON output with probabilities | Need programmatic data |
41
- | `get_live_scores` | Live football scores | Real-time match updates |
42
- | `get_match_details` | Match info by ID | Have specific match ID |
43
- | `get_team_stats` | Team performance data | Team analysis needed |
44
- | `compare_teams` | H2H team comparison | Compare two teams |
45
- | `get_player_stats` | Player statistics | Individual player analysis |
46
- | `odds_comparison` | Betting odds across markets | Find best odds |
47
- | `value_bet_calculator` | Kelly Criterion calculation | Betting recommendations |
48
- | `track_prediction` | Log bet/prediction | Start tracking a pick |
49
- | `resolve_prediction` | Update bet result | Mark win/loss/void |
50
- | `analyze_roi` | Performance analytics | Review betting history |
51
- | `get_pending_predictions` | List unresolved bets | Check open positions |
52
-
53
- **Sports Tool Priority:**
54
- 1. Try `analyze_football_match_structured` first (gives JSON with confidence ranges)
55
- 2. Fall back to `analyze_football_match_v2` for detailed narrative
56
- 3. Use `value_bet_calculator` for specific betting math
57
- 4. Always `track_prediction` after making picks
58
-
59
- ### 🔍 Web Search & Research Tools
60
- | Tool | Purpose | API Key Required |
61
- |------|---------|------------------|
62
- | `brave_web_search` | General web search | BRAVE_API_KEY |
63
- | `exa_web_search` | Neural/semantic search | EXA_API_KEY |
64
- | `duckduckgo_search` | Anonymous search | None |
65
- | `web_read` | Extract URL content | None |
66
- | `web_extract` | Structured data extraction | None |
67
-
68
- **Search Strategy:**
69
- - Current events/news → `brave_web_search`
70
- - Research/technical → `exa_web_search`
71
- - Fallback/no key → `duckduckgo_search`
72
- - Deep dive → `web_read` on top results
73
-
74
- ### 💻 Code Management Tools
75
- | Tool | Purpose | Safety Features |
76
- |------|---------|-----------------|
77
- | `deep_code_edit` | Structural code changes | Auto-backup, validation |
78
- | `add_code_snippet` | Store reusable patterns | Indexed for search |
79
- | `search_code` | Semantic code search | Graph-based relationships |
80
- | `get_project_graph` | Codebase structure analysis | File dependencies |
81
- | `get_file_relationships` | Find related files | Import/dependency graph |
82
-
83
- ### 🧠 Intelligent Code Analysis Tools (v10000.1.9+)
84
- | Tool | Purpose | Features |
85
- |------|---------|----------|
86
- | `intelligent_code_analyze` | Deep code analysis | Quality scoring, metrics, issue detection |
87
- | `intelligent_impact_analysis` | Change prediction | Risk score, affected files, test recommendations |
88
- | `intelligent_semantic_search` | Concept-based search | Find code by meaning, not just text |
89
- | `intelligent_refactor_suggest` | Refactoring ideas | AI suggestions with before/after code |
90
- | `intelligent_code_compare` | Code comparison | Diff analysis with statistics |
91
- | `intelligent_code_autofix` | Auto-fix code issues | Trailing whitespace, semicolons, imports |
92
-
93
- **Intelligent Code Analysis Protocol:**
94
- 1. Before major changes → `intelligent_impact_analysis` (know the risk)
95
- 2. Understanding code → `intelligent_code_analyze` (quality + metrics)
96
- 3. Finding related code → `intelligent_semantic_search` (concept search)
97
- 4. Improving code → `intelligent_refactor_suggest` (actionable ideas)
98
- 5. Code reviews → `intelligent_code_compare` (detailed diffs)
99
- 6. Clean up issues → `intelligent_code_autofix` (dryRun first, then apply)
100
- 7. Monitor quality → Check `http://localhost:3001/api/code-quality` for project overview
101
-
102
- **Code Edit Protocol:**
103
- 1. Before changes: Run `intelligent_impact_analysis` to assess risk
104
- 2. Always use `deep_code_edit` (not raw file writes)
105
- 3. Review backup location if rollback needed
106
- 4. Use `search_code` first to understand context
107
- 5. Validate changes with `get_project_graph`
108
-
109
- ### 📝 Knowledge & Notes Tools
110
- | Tool | Purpose | Persistence |
111
- |------|---------|-------------|
112
- | `add_note` | Create/store notes | Saved to disk |
113
- | `search_notes` | Find existing notes | Full-text search |
114
- | `get_note` | Retrieve specific note | By ID |
115
- | `update_note` | Modify existing note | Versioned |
116
- | `create_knowledge_node` | Add to knowledge graph | With relationships |
117
- | `query_knowledge_graph` | Traverse relationships | Multi-hop queries |
118
- | `add_knowledge_edge` | Connect nodes | Weighted relationships |
119
-
120
- ### 👤 Human Interface Tools
121
- | Tool | Purpose | Use When |
122
- |------|---------|----------|
123
- | `ask_human` | Request clarification | Ambiguous requirements |
124
- | `request_workflow_approval` | Multi-step approval | Destructive workflows |
125
- | `send_notification` | Alert human user | Important updates |
126
-
127
- ### 🛠️ Utility Tools
128
- | Tool | Purpose | Notes |
129
- |------|---------|-------|
130
- | `get_caller_info` | Get current context | Debug/diagnostics |
131
- | `get_server_metrics` | Performance stats | Resource monitoring |
132
- | `validate_path` | Security check | Path traversal prevention |
133
- | `generate_cache_key` | Create cache keys | Consistent hashing |
134
-
135
- ## Tool Selection Flowchart
136
-
137
- ```
138
- Need information?
139
- ├── Time-sensitive/current → web_search (Brave/Exa)
140
- ├── Sports data → analyze_football_match_*
141
- ├── Code understanding → search_code / get_project_graph
142
- ├── Past notes → search_notes
143
- └── General knowledge → sequentialthinking
144
-
145
- Need to take action?
146
- ├── Code changes → deep_code_edit
147
- ├── Code analysis → intelligent_code_analyze
148
- ├── Impact prediction → intelligent_impact_analysis
149
- ├── Refactoring ideas → intelligent_refactor_suggest
150
- ├── Auto-fix issues → intelligent_code_autofix
151
- ├── Store knowledge → add_note / create_knowledge_node
152
- ├── Track sports bet → track_prediction
153
- └── Complex workflow → sequentialthinking → execution
154
-
155
- Need human input?
156
- ├── Quick question → ask_human
157
- ├── Destructive action → request_workflow_approval
158
- └── Important update → send_notification
159
- ```
160
-
161
- ## Environment Variables
162
-
163
- Required for full functionality:
164
- - `BRAVE_API_KEY` - Brave Search (web search)
165
- - `EXA_API_KEY` - Exa Neural Search (research)
166
- - `API_FOOTBALL_KEY` - API-Football (sports data)
167
- - `FOOTBALL_DATA_KEY` - Football-Data.org (backup sports)
168
-
169
- Optional:
170
- - `SPORTS_DB_KEY` - TheSportsDB (additional sports)
171
- - `GOOGLE_SEARCH_API_KEY` - Google Custom Search
172
- - `GOOGLE_SEARCH_CX` - Google Search Engine ID
173
-
174
- ## Confidence Scoring Protocol
175
-
176
- Track your certainty level in sequential thinking:
177
- - **100-90**: Very high confidence, proceed directly
178
- - **89-70**: High confidence, brief verification
179
- - **69-50**: Medium confidence, use observation step
180
- - **49-30**: Low confidence, ask_human for clarification
181
- - **29-0**: Very low confidence, STOP and reflect
182
-
183
- ## Loop Prevention Rules
184
-
185
- 1. If same error occurs 3 times → STOP and ask_human
186
- 2. If confidence drops below 50 → Use reflection step
187
- 3. If stuck for 5+ thought cycles → Branch or ask_human
188
- 4. If tool fails repeatedly → Try alternative tool
189
-
190
- ## Response Format Guidelines
191
-
192
- For sports analysis:
193
- ```
194
- 📊 Data Quality: XX/100
195
- 🏠 Home: X% (range: X%-X%)
196
- 🤝 Draw: X% (range: X%-X%)
197
- ✈️ Away: X% (range: X%-X%)
198
- 💎 Value Bets: [list if any]
199
- 🏆 Best Bet: [selection]
200
- ```
201
-
202
- For code changes:
203
- ```
204
- 📝 Files Modified: [list]
205
- 💾 Backup Location: [path]
206
- ✅ Validation: [tests/status]
207
- 🔍 Impact Analysis: [use intelligent_impact_analysis]
208
- 📊 Code Quality: [use intelligent_code_analyze for metrics]
209
- ```
210
-
211
- ## Error Recovery
212
-
213
- Tool failure → Log error → Try alternative → If stuck, ask_human
214
- API limit → Switch provider → Use cache → If exhausted, inform user
215
- Path error → Validate_path → Check permissions → If persists, ask_human
216
-
217
- ---
218
-
219
- ## MCP Configuration
220
-
221
- **Version:** `@gotza02/sequential-thinking@10000.1.9`
222
-
223
- **Claude Code Setup:** See `~/.claude/SEQUENTIAL_THINKING_MCP.md`
224
-
225
- **Gemini CLI Setup:** See `~/.gemini/GEMINI_MCP_SETUP.md`
226
-
227
- **Environment Variables Required:**
228
- - `BRAVE_API_KEY`, `EXA_API_KEY` - Web search
229
- - `API_FOOTBALL_KEY`, `FOOTBALL_DATA_KEY` - Sports data
230
-
231
- **Dashboard:** http://localhost:3001/api/code-quality