@gotza02/sequential-thinking 10000.0.8 → 10000.1.0

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/README.md CHANGED
@@ -1,52 +1,262 @@
1
- # @gotza02/sequential-thinking
1
+ # Football Analysis System - Fixed & Enhanced
2
2
 
3
- **The Elite "Brain" for AI Agents.**
4
- An advanced Model Context Protocol (MCP) server that equips AI with structured reasoning, web search capabilities, and safety protocols.
3
+ ## การปรับปรุงที่ทำ (Priority 1-3)
5
4
 
6
- ## 🚀 Features
5
+ ### Priority 1: Core Reliability
7
6
 
8
- ### 🧠 Sequential Thinking Engine
9
- Forces the AI to think before acting using a strict block-based flow:
10
- - **Analysis:** Understand the problem deeply.
11
- - **Planning:** Formulate a step-by-step plan.
12
- - **Execution:** Perform actions (with tool support).
13
- - **Observation:** Analyze results (Mandatory step).
14
- - **Reflection:** Critique the outcome and adjust.
7
+ #### 1.1 Circuit Breaker Pattern (`core/circuit-breaker.ts`)
8
+ - ป้องกัน cascading failures เมื่อ API ล่ม
9
+ - สถานะ: CLOSED HALF-OPEN → OPEN
10
+ - Auto-reset หลังจาก timeout
15
11
 
16
- ### 🛡️ Coding Safety Net (New!)
17
- - **Auto-Backup:** Automatically creates `.bak` backups before modifying any file via `deep_code_edit`.
18
- - **Destructive Action Protection:** Prevents accidental data loss during code refactoring.
12
+ #### 1.2 Retry Mechanism (`core/retry.ts`)
13
+ - Exponential backoff with jitter
14
+ - Configurable retry policies
15
+ - แยก retryable vs non-retryable errors
19
16
 
20
- ### Sports Intelligence (Upgraded)
21
- - **Dual-Source Deep Dive:** Simultaneously scrapes news (BBC, Sky) and stats (Understat, FBref) for comprehensive coverage.
22
- - **Smart xG Extraction:** "Smart Extractor" technology specifically for Understat to get accurate Expected Goals data.
23
- - **Handicap Odds:** Dedicated search protocols for Asian Handicap and betting market analysis.
24
- - **Fallback Protection:** Intelligent warning system when API keys are missing.
17
+ #### 1.3 Enhanced Cache (`core/cache.ts`)
18
+ - Stale-while-revalidate pattern
19
+ - TTL ลดลงสำหรับ live data (15 วินาที)
20
+ - Background refresh
25
21
 
26
- ### 🌐 Web Search Integration
27
- - Built-in support for **Exa**, **Brave**, **Google Search**, and **DuckDuckGo** (New!).
28
- - Allows the AI to "pause and research" during the thinking process.
22
+ ### Priority 2: Realtime Features
29
23
 
30
- ## 🛠️ Recent Updates (v10000.0.7+)
24
+ #### 2.1 Realtime Data Manager (`core/realtime-manager.ts`)
25
+ - Polling ทุก 5-15 วินาที
26
+ - Event-driven architecture
27
+ - Score change detection
28
+ - Odds change detection
31
29
 
32
- ### 🔒 Security & Stability
33
- - **Enhanced Shell Protection:** Blocks dangerous shell metacharacters and risky commands (e.g., `curl | sh`, `rm -rf`).
34
- - **ReDoS Protection:** Validates regex patterns to prevent Denial of Service attacks.
35
- - **Path Safety:** Strict path traversal checks to keep operations within the project root.
36
- - **Resource Limits:** Enforces file size limits (10MB) for editing and parsing to prevent memory exhaustion.
30
+ #### 2.2 Alert Manager (`core/alert-manager.ts`)
31
+ - Rule-based alert engine
32
+ - Multiple notification channels (webhook, slack, discord, email)
33
+ - Cooldown และ rate limiting
34
+ - Alert history
37
35
 
38
- ### Performance & Caching
39
- - **Graph Caching:** Implemented intelligent caching for the Knowledge Graph (max 1000 files) to speed up analysis.
40
- - **Rate Limiting:** Added request rate limiting for HTTP endpoints and search providers.
41
- - **Auto-Cleanup:** Automatically manages backup files (keeps last 10) and prunes old thought history.
36
+ #### 2.3 Data Quality Validator (`core/data-quality.ts`)
37
+ - Completeness, accuracy, freshness scoring
38
+ - Issue detection
39
+ - Improvement suggestions
42
40
 
43
- ### New Capabilities
44
- - **DuckDuckGo Support:** Added a no-API-key search provider fallback.
45
- - **Graceful Shutdown:** Ensures data (thoughts, notes) is saved correctly when the server stops.
46
- - **Enhanced API:** Improved `/health` endpoint with system stats and added pagination to `/api/notes`.
41
+ ### Priority 3: Advanced Analytics
47
42
 
48
- ## 📦 Installation
43
+ #### 3.1 ML Prediction Engine (`core/ml-prediction.ts`)
44
+ - Weighted factor analysis
45
+ - Probability calculation
46
+ - Confidence scoring
47
+ - Over/Under & BTTS predictions
48
+
49
+ #### 3.2 Historical Analyzer (`core/historical-analyzer.ts`)
50
+ - Pattern detection
51
+ - Trend analysis
52
+ - Betting pattern analysis
53
+ - Referee bias analysis
54
+
55
+ #### 3.3 Dashboard Server (`dashboard/server.ts`)
56
+ - Real-time monitoring
57
+ - Cache statistics
58
+ - Circuit breaker status
59
+ - Alert management
60
+
61
+ ## การใช้งาน
62
+
63
+ ### 1. เริ่มต้นระบบ
64
+
65
+ ```typescript
66
+ import { getRealtimeManager, getAlertManager, startDashboard } from './core/index.js';
67
+
68
+ // Start realtime manager
69
+ const realtime = getRealtimeManager();
70
+ realtime.start();
71
+
72
+ // Start alert manager
73
+ const alerts = getAlertManager();
74
+ alerts.start();
75
+
76
+ // Start dashboard
77
+ startDashboard(8080);
78
+ ```
79
+
80
+ ### 2. สมัครรับข้อมูลแบบ Realtime
81
+
82
+ ```typescript
83
+ import { getRealtimeManager } from './core/index.js';
84
+
85
+ const realtime = getRealtimeManager();
86
+
87
+ // Subscribe to match events
88
+ const unsubscribe = realtime.subscribeToMatch('match-123', (event) => {
89
+ console.log(`Event: ${event.type}`, event.data);
90
+ });
91
+
92
+ // Subscribe to odds changes
93
+ realtime.subscribeToOdds('match-123', (event) => {
94
+ console.log(`Odds changed: ${event.data.newOdds}`);
95
+ });
96
+ ```
97
+
98
+ ### 3. ตั้งค่า Alerts
99
+
100
+ ```typescript
101
+ import { getAlertManager } from './core/index.js';
102
+
103
+ const alerts = getAlertManager();
104
+
105
+ // Add odds drop alert
106
+ alerts.addRule({
107
+ name: 'Arsenal Odds Drop',
108
+ type: 'odds_drop',
109
+ condition: {
110
+ type: 'odds_drop',
111
+ matchId: 'match-123',
112
+ threshold: 2.0,
113
+ percentage: 15,
114
+ },
115
+ channels: [
116
+ { type: 'webhook', config: { url: 'https://your-webhook.com' } },
117
+ { type: 'slack', config: { webhook: 'https://hooks.slack.com/...' } },
118
+ ],
119
+ cooldown: 300000, // 5 minutes
120
+ enabled: true,
121
+ });
122
+
123
+ // Add goal alert
124
+ alerts.addRule({
125
+ name: 'Goal Alert',
126
+ type: 'goal',
127
+ condition: {
128
+ type: 'event',
129
+ eventTypes: ['goal'],
130
+ },
131
+ channels: [{ type: 'console', config: {} }],
132
+ cooldown: 0,
133
+ enabled: true,
134
+ });
135
+ ```
136
+
137
+ ### 4. ใช้ Retry และ Circuit Breaker
138
+
139
+ ```typescript
140
+ import { withRetry, getCircuitBreaker } from './core/index.js';
141
+
142
+ // Simple retry
143
+ const data = await withRetry(
144
+ async () => fetchFromAPI(),
145
+ { maxAttempts: 5, initialDelay: 1000 },
146
+ 'api-call'
147
+ );
148
+
149
+ // With circuit breaker
150
+ const cb = getCircuitBreaker('api-football', { failureThreshold: 5 });
151
+ const result = await cb.execute(() => fetchFromAPI());
152
+ ```
153
+
154
+ ### 5. ML Prediction
155
+
156
+ ```typescript
157
+ import { getPredictionEngine } from './core/index.js';
158
+
159
+ const ml = getPredictionEngine();
160
+
161
+ const prediction = await ml.predict({
162
+ match: matchData,
163
+ homeForm: { last5: ['W', 'W', 'D', 'L', 'W'], goalsFor: 10, goalsAgainst: 5, xG: 8.5, xGA: 6.2 },
164
+ awayForm: { last5: ['L', 'D', 'W', 'L', 'L'], goalsFor: 6, goalsAgainst: 12, xG: 7.1, xGA: 10.5 },
165
+ h2h: headToHeadData,
166
+ homeStats: homeTeamStats,
167
+ awayStats: awayTeamStats,
168
+ injuries: { home: { keyPlayers: 1, total: 3 }, away: { keyPlayers: 0, total: 2 } },
169
+ });
170
+
171
+ console.log(`Home: ${prediction.homeWin * 100}%`);
172
+ console.log(`Draw: ${prediction.draw * 100}%`);
173
+ console.log(`Away: ${prediction.awayWin * 100}%`);
174
+ console.log(`Confidence: ${prediction.confidence}%`);
175
+ ```
176
+
177
+ ### 6. Historical Analysis
178
+
179
+ ```typescript
180
+ import { getHistoricalAnalyzer } from './core/index.js';
181
+
182
+ const analyzer = getHistoricalAnalyzer();
183
+
184
+ // Analyze team performance
185
+ const performance = analyzer.analyzeTeamPerformance('team-123');
186
+
187
+ // Find patterns
188
+ const patterns = analyzer.findBettingPatterns({
189
+ league: 'Premier League',
190
+ dateFrom: new Date('2024-01-01'),
191
+ });
192
+
193
+ // Analyze trends
194
+ const trends = analyzer.analyzeTrends('team-123', 10);
195
+ ```
196
+
197
+ ### 7. Data Quality Check
198
+
199
+ ```typescript
200
+ import { getDataQualityValidator } from './core/index.js';
201
+
202
+ const validator = getDataQualityValidator();
203
+
204
+ const report = validator.validateMatchData(matchData);
205
+
206
+ console.log(`Quality Score: ${report.overall}/100`);
207
+ console.log(`Grade: ${validator.getGrade(report.overall)}`);
208
+
209
+ if (report.issues.length > 0) {
210
+ console.log('Issues:', report.issues);
211
+ }
212
+ ```
213
+
214
+ ## Dashboard
215
+
216
+ เปิด browser ไปที่ `http://localhost:8080` เพื่อดู:
217
+ - System status
218
+ - Cache statistics
219
+ - Circuit breaker status
220
+ - Realtime data
221
+ - Alert system
222
+
223
+ ## Environment Variables
49
224
 
50
225
  ```bash
51
- npx -y @gotza02/sequential-thinking
52
- ```
226
+ # API Keys
227
+ API_FOOTBALL_KEY=your_key
228
+ FOOTBALL_DATA_KEY=your_key
229
+ ODDS_API_KEY=your_key
230
+ SPORTRADAR_KEY=your_key
231
+
232
+ # Cache
233
+ SPORTS_CACHE_TTL=300000
234
+ SPORTS_CACHE_PATH=.sports_cache.json
235
+
236
+ # Dashboard
237
+ DASHBOARD_PORT=8080
238
+ ```
239
+
240
+ ## ไฟล์ที่สร้างใหม่
241
+
242
+ ```
243
+ src/tools/sports/core/
244
+ ├── circuit-breaker.ts # Circuit breaker pattern
245
+ ├── retry.ts # Retry mechanism
246
+ ├── cache.ts # Enhanced cache (modified)
247
+ ├── realtime-manager.ts # Realtime data manager
248
+ ├── alert-manager.ts # Alert system
249
+ ├── data-quality.ts # Data quality validator
250
+ ├── ml-prediction.ts # ML prediction engine
251
+ ├── historical-analyzer.ts # Historical analysis
252
+ ├── types.ts # Type definitions (updated)
253
+ ├── constants.ts # Constants (updated)
254
+ └── index.ts # Exports
255
+
256
+ src/dashboard/
257
+ └── server.ts # Dashboard server
258
+ ```
259
+
260
+ ## License
261
+
262
+ MIT
@@ -1,2 +1,79 @@
1
- import * as http from 'http';
2
- export declare function startDashboard(port: number, historyPath: string): Promise<http.Server>;
1
+ /**
2
+ * DASHBOARD SERVER
3
+ * Real-time monitoring dashboard for the football analysis system
4
+ */
5
+ export interface DashboardStats {
6
+ cache: {
7
+ size: number;
8
+ maxSize: number;
9
+ hits: number;
10
+ breakdown: Record<string, number>;
11
+ };
12
+ circuitBreakers: Array<{
13
+ name: string;
14
+ state: string;
15
+ failures: number;
16
+ }>;
17
+ realtime: {
18
+ isRunning: boolean;
19
+ liveMatches: number;
20
+ subscribers: number;
21
+ };
22
+ alerts: {
23
+ totalRules: number;
24
+ enabledRules: number;
25
+ totalAlerts: number;
26
+ };
27
+ }
28
+ export declare class DashboardServer {
29
+ private server;
30
+ private port;
31
+ private updateInterval;
32
+ constructor(port?: number);
33
+ /**
34
+ * Start the dashboard server
35
+ */
36
+ start(): void;
37
+ /**
38
+ * Stop the dashboard server
39
+ */
40
+ stop(): void;
41
+ /**
42
+ * Handle HTTP requests
43
+ */
44
+ private handleRequest;
45
+ /**
46
+ * Serve the dashboard HTML
47
+ */
48
+ private serveDashboard;
49
+ /**
50
+ * Serve stats JSON
51
+ */
52
+ private serveStats;
53
+ /**
54
+ * Clear cache
55
+ */
56
+ private clearCache;
57
+ /**
58
+ * Reset circuit breakers
59
+ */
60
+ private resetCircuitBreakers;
61
+ /**
62
+ * Serve alert rules
63
+ */
64
+ private serveAlertRules;
65
+ /**
66
+ * Serve alert history
67
+ */
68
+ private serveAlertHistory;
69
+ /**
70
+ * Collect all stats
71
+ */
72
+ private collectStats;
73
+ /**
74
+ * Broadcast stats to all connected clients (for WebSocket upgrade)
75
+ */
76
+ private broadcastStats;
77
+ }
78
+ export declare function startDashboard(port?: number): DashboardServer;
79
+ export declare function stopDashboard(): void;