vantuz 3.4.2 → 3.5.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.
- package/.env.example +21 -0
- package/.openclaw/completions/openclaw.bash +227 -0
- package/.openclaw/completions/openclaw.fish +1552 -0
- package/.openclaw/completions/openclaw.ps1 +1966 -0
- package/.openclaw/completions/openclaw.zsh +3571 -0
- package/.openclaw/gateway.cmd +10 -0
- package/.openclaw/identity/device.json +7 -0
- package/.openclaw/openclaw.json +40 -0
- package/.windsurf/workflows/vantuz-dev.md +31 -0
- package/DOCS_TR.md +80 -0
- package/LICENSE +45 -45
- package/README.md +52 -21
- package/cli.js +685 -585
- package/config.js +733 -733
- package/core/agent-loop.js +190 -190
- package/core/ai-provider.js +298 -261
- package/core/automation.js +523 -523
- package/core/brand-analyst.js +101 -0
- package/core/channels.js +167 -167
- package/core/dashboard.js +230 -230
- package/core/database.js +135 -37
- package/core/eia-monitor.js +3 -1
- package/core/engine.js +648 -636
- package/core/gateway.js +447 -447
- package/core/learning.js +214 -214
- package/core/license.js +113 -0
- package/core/marketplace-adapter.js +168 -168
- package/core/memory.js +190 -190
- package/core/migrations/001-initial-schema.sql +1 -1
- package/core/queue.js +120 -120
- package/core/self-healer.js +314 -314
- package/core/unified-product.js +214 -214
- package/core/vision-service.js +113 -113
- package/index.js +217 -174
- package/modules/crm/sentiment-crm.js +231 -231
- package/modules/healer/listing-healer.js +201 -201
- package/modules/oracle/predictor.js +214 -214
- package/modules/researcher/agent.js +169 -169
- package/modules/team/agents/base.js +92 -92
- package/modules/team/agents/dev.js +33 -33
- package/modules/team/agents/josh.js +40 -40
- package/modules/team/agents/marketing.js +33 -33
- package/modules/team/agents/milo.js +36 -36
- package/modules/team/index.js +78 -78
- package/modules/team/shared-memory.js +87 -87
- package/modules/war-room/competitor-tracker.js +250 -250
- package/modules/war-room/pricing-engine.js +308 -308
- package/n11docs.md +1680 -0
- package/nodes/warehouse.js +238 -238
- package/onboard.js +1 -1
- package/openclawdocs.md +3 -0
- package/package.json +7 -5
- package/platforms/pttavm.js +14 -14
- package/plugins/vantuz/index.js +528 -528
- package/plugins/vantuz/memory/hippocampus.js +465 -465
- package/plugins/vantuz/package.json +20 -20
- package/plugins/vantuz/platforms/_template.js +118 -118
- package/plugins/vantuz/platforms/amazon.js +236 -236
- package/plugins/vantuz/platforms/ciceksepeti.js +166 -166
- package/plugins/vantuz/platforms/hepsiburada.js +180 -180
- package/plugins/vantuz/platforms/index.js +165 -165
- package/plugins/vantuz/platforms/n11.js +229 -229
- package/plugins/vantuz/platforms/pazarama.js +154 -154
- package/plugins/vantuz/platforms/pttavm.js +127 -127
- package/plugins/vantuz/platforms/trendyol.js +326 -326
- package/plugins/vantuz/services/alerts.js +253 -253
- package/plugins/vantuz/services/license.js +34 -34
- package/plugins/vantuz/services/scheduler.js +232 -232
- package/plugins/vantuz/tools/analytics.js +152 -152
- package/plugins/vantuz/tools/crossborder.js +187 -187
- package/plugins/vantuz/tools/nl-parser.js +211 -211
- package/plugins/vantuz/tools/product.js +110 -110
- package/plugins/vantuz/tools/quick-report.js +175 -175
- package/plugins/vantuz/tools/repricer.js +314 -314
- package/plugins/vantuz/tools/sentiment.js +115 -115
- package/plugins/vantuz/tools/vision.js +257 -257
- package/public.pem +9 -0
- package/server/app.js +260 -260
- package/server/public/index.html +514 -514
- package/start.bat +33 -33
- package/vantuz.sqlite +0 -0
- package/workspace/AGENTS.md +73 -0
- package/workspace/BRAND.md +29 -0
- package/workspace/SOUL.md +72 -0
- package/workspace/team/DECISIONS.md +3 -0
- package/workspace/team/GOALS.md +3 -0
- package/workspace/team/PROJECT_STATUS.md +3 -0
- package/workspace/team/agents/dev/SOUL.md +12 -0
- package/workspace/team/agents/josh/SOUL.md +12 -0
- package/workspace/team/agents/marketing/SOUL.md +12 -0
- package/workspace/team/agents/milo/SOUL.md +12 -0
- package/vantuz-3.3.4.tgz +0 -0
package/core/self-healer.js
CHANGED
|
@@ -1,314 +1,314 @@
|
|
|
1
|
-
// core/self-healer.js
|
|
2
|
-
// Self-Healing Module for Vantuz OS V2
|
|
3
|
-
// Monitors errors, auto-repairs simple issues, and rolls back broken states.
|
|
4
|
-
|
|
5
|
-
import fs from 'fs';
|
|
6
|
-
import path from 'path';
|
|
7
|
-
import os from 'os';
|
|
8
|
-
import { log } from './ai-provider.js';
|
|
9
|
-
|
|
10
|
-
const SNAPSHOT_DIR = path.join(os.homedir(), '.vantuz', 'snapshots');
|
|
11
|
-
const ERROR_LOG_FILE = path.join(os.homedir(), '.vantuz', 'memory', 'error-log.json');
|
|
12
|
-
|
|
13
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
14
|
-
// ERROR CLASSIFICATION
|
|
15
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
16
|
-
|
|
17
|
-
const AUTO_FIXABLE = {
|
|
18
|
-
'ETIMEDOUT': { fix: 'retry', description: 'Timeout — tekrar deneniyor' },
|
|
19
|
-
'ECONNRESET': { fix: 'retry', description: 'Bağlantı koptu — tekrar deneniyor' },
|
|
20
|
-
'ECONNREFUSED': { fix: 'retry_delay', description: 'Bağlantı reddedildi — gecikmeli tekrar' },
|
|
21
|
-
'ERR_BAD_REQUEST': { fix: 'inspect', description: 'Hatalı istek — parametre kontrolü' },
|
|
22
|
-
'401': { fix: 'refresh_token', description: 'Auth hatası — token yenileniyor' },
|
|
23
|
-
'403': { fix: 'refresh_token', description: 'Yetki hatası — token yenileniyor' },
|
|
24
|
-
'429': { fix: 'backoff', description: 'Rate limit — bekleniyor' },
|
|
25
|
-
'500': { fix: 'retry_delay', description: 'Sunucu hatası — gecikmeli tekrar' },
|
|
26
|
-
'503': { fix: 'retry_delay', description: 'Servis dışı — gecikmeli tekrar' },
|
|
27
|
-
'SyntaxError': { fix: 'rollback', description: 'JSON parse hatası — rollback' },
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
31
|
-
// SELF HEALER
|
|
32
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
33
|
-
|
|
34
|
-
class SelfHealer {
|
|
35
|
-
constructor() {
|
|
36
|
-
this.errorLog = this._loadErrorLog();
|
|
37
|
-
this.escalationCallbacks = [];
|
|
38
|
-
this.maxRetries = 3;
|
|
39
|
-
this._ensureDirs();
|
|
40
|
-
log('INFO', 'SelfHealer initialized', { knownErrors: this.errorLog.length });
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
_ensureDirs() {
|
|
44
|
-
if (!fs.existsSync(SNAPSHOT_DIR)) fs.mkdirSync(SNAPSHOT_DIR, { recursive: true });
|
|
45
|
-
const memDir = path.dirname(ERROR_LOG_FILE);
|
|
46
|
-
if (!fs.existsSync(memDir)) fs.mkdirSync(memDir, { recursive: true });
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Register escalation handler for un-fixable errors.
|
|
51
|
-
*/
|
|
52
|
-
onEscalation(callback) {
|
|
53
|
-
this.escalationCallbacks.push(callback);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
57
|
-
// STATE SNAPSHOTS (Rollback Support)
|
|
58
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Save a state snapshot before a risky operation.
|
|
62
|
-
* @param {string} name - Snapshot name (e.g., 'pricing-run-2026-02-13').
|
|
63
|
-
* @param {object} state - State data to snapshot.
|
|
64
|
-
*/
|
|
65
|
-
saveSnapshot(name, state) {
|
|
66
|
-
const file = path.join(SNAPSHOT_DIR, `${name}.json`);
|
|
67
|
-
fs.writeFileSync(file, JSON.stringify({
|
|
68
|
-
name,
|
|
69
|
-
timestamp: new Date().toISOString(),
|
|
70
|
-
state
|
|
71
|
-
}, null, 2), 'utf-8');
|
|
72
|
-
log('INFO', `Snapshot saved: ${name}`);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Load a snapshot by name.
|
|
77
|
-
*/
|
|
78
|
-
loadSnapshot(name) {
|
|
79
|
-
const file = path.join(SNAPSHOT_DIR, `${name}.json`);
|
|
80
|
-
if (!fs.existsSync(file)) return null;
|
|
81
|
-
return JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* List available snapshots.
|
|
86
|
-
*/
|
|
87
|
-
listSnapshots() {
|
|
88
|
-
if (!fs.existsSync(SNAPSHOT_DIR)) return [];
|
|
89
|
-
return fs.readdirSync(SNAPSHOT_DIR)
|
|
90
|
-
.filter(f => f.endsWith('.json'))
|
|
91
|
-
.map(f => {
|
|
92
|
-
const data = JSON.parse(fs.readFileSync(path.join(SNAPSHOT_DIR, f), 'utf-8'));
|
|
93
|
-
return { name: data.name, timestamp: data.timestamp };
|
|
94
|
-
})
|
|
95
|
-
.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Rollback: restore state from the last snapshot.
|
|
100
|
-
* @param {string} name - Snapshot name to restore.
|
|
101
|
-
* @returns {object|null} The restored state, or null if not found.
|
|
102
|
-
*/
|
|
103
|
-
rollback(name) {
|
|
104
|
-
const snapshot = this.loadSnapshot(name);
|
|
105
|
-
if (!snapshot) {
|
|
106
|
-
log('WARN', `Rollback failed: snapshot "${name}" not found`);
|
|
107
|
-
return null;
|
|
108
|
-
}
|
|
109
|
-
log('INFO', `🔄 ROLLBACK: "${name}" snapshot'ına geri dönüldü. Devam ediyorum.`, {
|
|
110
|
-
snapshotTime: snapshot.timestamp
|
|
111
|
-
});
|
|
112
|
-
return snapshot.state;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
116
|
-
// ERROR HANDLING + AUTO-REPAIR
|
|
117
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Attempt to heal an error.
|
|
121
|
-
* @param {Error|object} error - The error object.
|
|
122
|
-
* @param {string} module - Which module threw the error.
|
|
123
|
-
* @param {function} retryFn - Function to retry if applicable.
|
|
124
|
-
* @returns {{ healed: boolean, action: string, result?: any }}
|
|
125
|
-
*/
|
|
126
|
-
async heal(error, module, retryFn = null) {
|
|
127
|
-
const errorCode = this._classifyError(error);
|
|
128
|
-
const fixEntry = AUTO_FIXABLE[errorCode];
|
|
129
|
-
|
|
130
|
-
this._logError(error, module, errorCode);
|
|
131
|
-
|
|
132
|
-
if (!fixEntry) {
|
|
133
|
-
// Unfixable → escalate
|
|
134
|
-
this._escalate(error, module, errorCode);
|
|
135
|
-
return { healed: false, action: 'escalated', message: 'Manuel müdahale gerekiyor' };
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
log('INFO', `SelfHealer: ${fixEntry.description}`, { module, errorCode });
|
|
139
|
-
|
|
140
|
-
switch (fixEntry.fix) {
|
|
141
|
-
case 'retry':
|
|
142
|
-
return await this._retry(retryFn, 1000);
|
|
143
|
-
|
|
144
|
-
case 'retry_delay':
|
|
145
|
-
return await this._retry(retryFn, 5000);
|
|
146
|
-
|
|
147
|
-
case 'backoff':
|
|
148
|
-
return await this._retry(retryFn, 30000); // 30 sec backoff
|
|
149
|
-
|
|
150
|
-
case 'refresh_token':
|
|
151
|
-
log('WARN', 'Token yenileme denemesi yapılıyor...', { module });
|
|
152
|
-
return await this._retry(retryFn, 2000);
|
|
153
|
-
|
|
154
|
-
case 'rollback':
|
|
155
|
-
const snapshots = this.listSnapshots();
|
|
156
|
-
if (snapshots.length > 0) {
|
|
157
|
-
const restored = this.rollback(snapshots[0].name);
|
|
158
|
-
return {
|
|
159
|
-
healed: !!restored,
|
|
160
|
-
action: 'rollback',
|
|
161
|
-
message: restored
|
|
162
|
-
? `Geri aldım, devam ediyorum (${snapshots[0].name})`
|
|
163
|
-
: 'Rollback başarısız'
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
return { healed: false, action: 'rollback_failed', message: 'Snapshot bulunamadı' };
|
|
167
|
-
|
|
168
|
-
case 'inspect':
|
|
169
|
-
return { healed: false, action: 'needs_inspection', message: fixEntry.description };
|
|
170
|
-
|
|
171
|
-
default:
|
|
172
|
-
return { healed: false, action: 'unknown', message: 'Bilinmeyen fix tipi' };
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Wrap an async operation with self-healing.
|
|
178
|
-
* @param {string} module - Module name for logging.
|
|
179
|
-
* @param {function} fn - Async function to execute.
|
|
180
|
-
* @param {string} snapshotName - Optional: snapshot name for rollback support.
|
|
181
|
-
* @param {object} snapshotState - Optional: state to snapshot before execution.
|
|
182
|
-
*/
|
|
183
|
-
async withHealing(module, fn, snapshotName = null, snapshotState = null) {
|
|
184
|
-
// Save snapshot if provided
|
|
185
|
-
if (snapshotName && snapshotState) {
|
|
186
|
-
this.saveSnapshot(snapshotName, snapshotState);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
try {
|
|
190
|
-
return await fn();
|
|
191
|
-
} catch (error) {
|
|
192
|
-
log('WARN', `Error caught by SelfHealer in ${module}`, { error: error.message });
|
|
193
|
-
const healResult = await this.heal(error, module, fn);
|
|
194
|
-
|
|
195
|
-
if (healResult.healed) {
|
|
196
|
-
log('INFO', `✅ ${module}: Hata düzeltildi — ${healResult.message || healResult.action}`);
|
|
197
|
-
return healResult.result;
|
|
198
|
-
} else {
|
|
199
|
-
log('ERROR', `❌ ${module}: Hata düzeltilemedi — ${healResult.message || healResult.action}`);
|
|
200
|
-
throw error; // Re-throw if we can't fix
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
getStatus() {
|
|
206
|
-
const recent = this.errorLog.slice(-20);
|
|
207
|
-
return {
|
|
208
|
-
totalErrors: this.errorLog.length,
|
|
209
|
-
recentErrors: recent.length,
|
|
210
|
-
snapshots: this.listSnapshots().length,
|
|
211
|
-
autoFixable: recent.filter(e => AUTO_FIXABLE[e.code]).length,
|
|
212
|
-
escalated: recent.filter(e => !AUTO_FIXABLE[e.code]).length
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
217
|
-
|
|
218
|
-
_classifyError(error) {
|
|
219
|
-
const msg = (error.message || error.toString()).toUpperCase();
|
|
220
|
-
const status = error.response?.status || error.status || error.code;
|
|
221
|
-
|
|
222
|
-
// Check status code first
|
|
223
|
-
if (status && AUTO_FIXABLE[String(status)]) return String(status);
|
|
224
|
-
|
|
225
|
-
// Check error code
|
|
226
|
-
if (error.code && AUTO_FIXABLE[error.code]) return error.code;
|
|
227
|
-
|
|
228
|
-
// Check message patterns
|
|
229
|
-
if (msg.includes('ETIMEDOUT') || msg.includes('TIMEOUT')) return 'ETIMEDOUT';
|
|
230
|
-
if (msg.includes('ECONNRESET')) return 'ECONNRESET';
|
|
231
|
-
if (msg.includes('ECONNREFUSED')) return 'ECONNREFUSED';
|
|
232
|
-
if (msg.includes('SYNTAXERROR') || msg.includes('UNEXPECTED TOKEN')) return 'SyntaxError';
|
|
233
|
-
if (msg.includes('429') || msg.includes('RATE LIMIT')) return '429';
|
|
234
|
-
|
|
235
|
-
return 'UNKNOWN';
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
async _retry(fn, delayMs) {
|
|
239
|
-
if (!fn) return { healed: false, action: 'no_retry_fn', message: 'Retry fonksiyonu yok' };
|
|
240
|
-
|
|
241
|
-
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
|
|
242
|
-
try {
|
|
243
|
-
await new Promise(r => setTimeout(r, delayMs * attempt));
|
|
244
|
-
const result = await fn();
|
|
245
|
-
return { healed: true, action: 'retry', attempt, result };
|
|
246
|
-
} catch (e) {
|
|
247
|
-
if (attempt === this.maxRetries) {
|
|
248
|
-
return { healed: false, action: 'retry_exhausted', message: `${this.maxRetries} deneme başarısız` };
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
_logError(error, module, code) {
|
|
255
|
-
this.errorLog.push({
|
|
256
|
-
module,
|
|
257
|
-
code,
|
|
258
|
-
message: error.message || String(error),
|
|
259
|
-
timestamp: new Date().toISOString()
|
|
260
|
-
});
|
|
261
|
-
|
|
262
|
-
if (this.errorLog.length > 500) {
|
|
263
|
-
this.errorLog = this.errorLog.slice(-500);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
this._saveErrorLog();
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
_loadErrorLog() {
|
|
270
|
-
try {
|
|
271
|
-
if (fs.existsSync(ERROR_LOG_FILE)) {
|
|
272
|
-
return JSON.parse(fs.readFileSync(ERROR_LOG_FILE, 'utf-8'));
|
|
273
|
-
}
|
|
274
|
-
} catch (e) { /* ignore */ }
|
|
275
|
-
return [];
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
_saveErrorLog() {
|
|
279
|
-
try {
|
|
280
|
-
const tmp = ERROR_LOG_FILE + '.tmp';
|
|
281
|
-
fs.writeFileSync(tmp, JSON.stringify(this.errorLog, null, 2), 'utf-8');
|
|
282
|
-
fs.renameSync(tmp, ERROR_LOG_FILE);
|
|
283
|
-
} catch (e) { /* ignore */ }
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
_escalate(error, module, code) {
|
|
287
|
-
const ticket = {
|
|
288
|
-
type: 'SUPPORT_TICKET',
|
|
289
|
-
severity: 'critical',
|
|
290
|
-
module,
|
|
291
|
-
errorCode: code,
|
|
292
|
-
message: error.message || String(error),
|
|
293
|
-
timestamp: new Date().toISOString(),
|
|
294
|
-
note: `Kritik hata: ${module}. Otomatik düzeltme başarısız. Müdahale gerekli.`
|
|
295
|
-
};
|
|
296
|
-
|
|
297
|
-
log('ERROR', `🎫 SUPPORT TICKET: ${module} — ${code}`, ticket);
|
|
298
|
-
|
|
299
|
-
for (const cb of this.escalationCallbacks) {
|
|
300
|
-
try { cb(ticket); } catch (e) { /* swallow */ }
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
let healerInstance = null;
|
|
306
|
-
|
|
307
|
-
export function getSelfHealer() {
|
|
308
|
-
if (!healerInstance) {
|
|
309
|
-
healerInstance = new SelfHealer();
|
|
310
|
-
}
|
|
311
|
-
return healerInstance;
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
export default SelfHealer;
|
|
1
|
+
// core/self-healer.js
|
|
2
|
+
// Self-Healing Module for Vantuz OS V2
|
|
3
|
+
// Monitors errors, auto-repairs simple issues, and rolls back broken states.
|
|
4
|
+
|
|
5
|
+
import fs from 'fs';
|
|
6
|
+
import path from 'path';
|
|
7
|
+
import os from 'os';
|
|
8
|
+
import { log } from './ai-provider.js';
|
|
9
|
+
|
|
10
|
+
const SNAPSHOT_DIR = path.join(os.homedir(), '.vantuz', 'snapshots');
|
|
11
|
+
const ERROR_LOG_FILE = path.join(os.homedir(), '.vantuz', 'memory', 'error-log.json');
|
|
12
|
+
|
|
13
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
14
|
+
// ERROR CLASSIFICATION
|
|
15
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
16
|
+
|
|
17
|
+
const AUTO_FIXABLE = {
|
|
18
|
+
'ETIMEDOUT': { fix: 'retry', description: 'Timeout — tekrar deneniyor' },
|
|
19
|
+
'ECONNRESET': { fix: 'retry', description: 'Bağlantı koptu — tekrar deneniyor' },
|
|
20
|
+
'ECONNREFUSED': { fix: 'retry_delay', description: 'Bağlantı reddedildi — gecikmeli tekrar' },
|
|
21
|
+
'ERR_BAD_REQUEST': { fix: 'inspect', description: 'Hatalı istek — parametre kontrolü' },
|
|
22
|
+
'401': { fix: 'refresh_token', description: 'Auth hatası — token yenileniyor' },
|
|
23
|
+
'403': { fix: 'refresh_token', description: 'Yetki hatası — token yenileniyor' },
|
|
24
|
+
'429': { fix: 'backoff', description: 'Rate limit — bekleniyor' },
|
|
25
|
+
'500': { fix: 'retry_delay', description: 'Sunucu hatası — gecikmeli tekrar' },
|
|
26
|
+
'503': { fix: 'retry_delay', description: 'Servis dışı — gecikmeli tekrar' },
|
|
27
|
+
'SyntaxError': { fix: 'rollback', description: 'JSON parse hatası — rollback' },
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
31
|
+
// SELF HEALER
|
|
32
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
33
|
+
|
|
34
|
+
class SelfHealer {
|
|
35
|
+
constructor() {
|
|
36
|
+
this.errorLog = this._loadErrorLog();
|
|
37
|
+
this.escalationCallbacks = [];
|
|
38
|
+
this.maxRetries = 3;
|
|
39
|
+
this._ensureDirs();
|
|
40
|
+
log('INFO', 'SelfHealer initialized', { knownErrors: this.errorLog.length });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_ensureDirs() {
|
|
44
|
+
if (!fs.existsSync(SNAPSHOT_DIR)) fs.mkdirSync(SNAPSHOT_DIR, { recursive: true });
|
|
45
|
+
const memDir = path.dirname(ERROR_LOG_FILE);
|
|
46
|
+
if (!fs.existsSync(memDir)) fs.mkdirSync(memDir, { recursive: true });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Register escalation handler for un-fixable errors.
|
|
51
|
+
*/
|
|
52
|
+
onEscalation(callback) {
|
|
53
|
+
this.escalationCallbacks.push(callback);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
57
|
+
// STATE SNAPSHOTS (Rollback Support)
|
|
58
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Save a state snapshot before a risky operation.
|
|
62
|
+
* @param {string} name - Snapshot name (e.g., 'pricing-run-2026-02-13').
|
|
63
|
+
* @param {object} state - State data to snapshot.
|
|
64
|
+
*/
|
|
65
|
+
saveSnapshot(name, state) {
|
|
66
|
+
const file = path.join(SNAPSHOT_DIR, `${name}.json`);
|
|
67
|
+
fs.writeFileSync(file, JSON.stringify({
|
|
68
|
+
name,
|
|
69
|
+
timestamp: new Date().toISOString(),
|
|
70
|
+
state
|
|
71
|
+
}, null, 2), 'utf-8');
|
|
72
|
+
log('INFO', `Snapshot saved: ${name}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Load a snapshot by name.
|
|
77
|
+
*/
|
|
78
|
+
loadSnapshot(name) {
|
|
79
|
+
const file = path.join(SNAPSHOT_DIR, `${name}.json`);
|
|
80
|
+
if (!fs.existsSync(file)) return null;
|
|
81
|
+
return JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* List available snapshots.
|
|
86
|
+
*/
|
|
87
|
+
listSnapshots() {
|
|
88
|
+
if (!fs.existsSync(SNAPSHOT_DIR)) return [];
|
|
89
|
+
return fs.readdirSync(SNAPSHOT_DIR)
|
|
90
|
+
.filter(f => f.endsWith('.json'))
|
|
91
|
+
.map(f => {
|
|
92
|
+
const data = JSON.parse(fs.readFileSync(path.join(SNAPSHOT_DIR, f), 'utf-8'));
|
|
93
|
+
return { name: data.name, timestamp: data.timestamp };
|
|
94
|
+
})
|
|
95
|
+
.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Rollback: restore state from the last snapshot.
|
|
100
|
+
* @param {string} name - Snapshot name to restore.
|
|
101
|
+
* @returns {object|null} The restored state, or null if not found.
|
|
102
|
+
*/
|
|
103
|
+
rollback(name) {
|
|
104
|
+
const snapshot = this.loadSnapshot(name);
|
|
105
|
+
if (!snapshot) {
|
|
106
|
+
log('WARN', `Rollback failed: snapshot "${name}" not found`);
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
log('INFO', `🔄 ROLLBACK: "${name}" snapshot'ına geri dönüldü. Devam ediyorum.`, {
|
|
110
|
+
snapshotTime: snapshot.timestamp
|
|
111
|
+
});
|
|
112
|
+
return snapshot.state;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
116
|
+
// ERROR HANDLING + AUTO-REPAIR
|
|
117
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Attempt to heal an error.
|
|
121
|
+
* @param {Error|object} error - The error object.
|
|
122
|
+
* @param {string} module - Which module threw the error.
|
|
123
|
+
* @param {function} retryFn - Function to retry if applicable.
|
|
124
|
+
* @returns {{ healed: boolean, action: string, result?: any }}
|
|
125
|
+
*/
|
|
126
|
+
async heal(error, module, retryFn = null) {
|
|
127
|
+
const errorCode = this._classifyError(error);
|
|
128
|
+
const fixEntry = AUTO_FIXABLE[errorCode];
|
|
129
|
+
|
|
130
|
+
this._logError(error, module, errorCode);
|
|
131
|
+
|
|
132
|
+
if (!fixEntry) {
|
|
133
|
+
// Unfixable → escalate
|
|
134
|
+
this._escalate(error, module, errorCode);
|
|
135
|
+
return { healed: false, action: 'escalated', message: 'Manuel müdahale gerekiyor' };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
log('INFO', `SelfHealer: ${fixEntry.description}`, { module, errorCode });
|
|
139
|
+
|
|
140
|
+
switch (fixEntry.fix) {
|
|
141
|
+
case 'retry':
|
|
142
|
+
return await this._retry(retryFn, 1000);
|
|
143
|
+
|
|
144
|
+
case 'retry_delay':
|
|
145
|
+
return await this._retry(retryFn, 5000);
|
|
146
|
+
|
|
147
|
+
case 'backoff':
|
|
148
|
+
return await this._retry(retryFn, 30000); // 30 sec backoff
|
|
149
|
+
|
|
150
|
+
case 'refresh_token':
|
|
151
|
+
log('WARN', 'Token yenileme denemesi yapılıyor...', { module });
|
|
152
|
+
return await this._retry(retryFn, 2000);
|
|
153
|
+
|
|
154
|
+
case 'rollback':
|
|
155
|
+
const snapshots = this.listSnapshots();
|
|
156
|
+
if (snapshots.length > 0) {
|
|
157
|
+
const restored = this.rollback(snapshots[0].name);
|
|
158
|
+
return {
|
|
159
|
+
healed: !!restored,
|
|
160
|
+
action: 'rollback',
|
|
161
|
+
message: restored
|
|
162
|
+
? `Geri aldım, devam ediyorum (${snapshots[0].name})`
|
|
163
|
+
: 'Rollback başarısız'
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
return { healed: false, action: 'rollback_failed', message: 'Snapshot bulunamadı' };
|
|
167
|
+
|
|
168
|
+
case 'inspect':
|
|
169
|
+
return { healed: false, action: 'needs_inspection', message: fixEntry.description };
|
|
170
|
+
|
|
171
|
+
default:
|
|
172
|
+
return { healed: false, action: 'unknown', message: 'Bilinmeyen fix tipi' };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Wrap an async operation with self-healing.
|
|
178
|
+
* @param {string} module - Module name for logging.
|
|
179
|
+
* @param {function} fn - Async function to execute.
|
|
180
|
+
* @param {string} snapshotName - Optional: snapshot name for rollback support.
|
|
181
|
+
* @param {object} snapshotState - Optional: state to snapshot before execution.
|
|
182
|
+
*/
|
|
183
|
+
async withHealing(module, fn, snapshotName = null, snapshotState = null) {
|
|
184
|
+
// Save snapshot if provided
|
|
185
|
+
if (snapshotName && snapshotState) {
|
|
186
|
+
this.saveSnapshot(snapshotName, snapshotState);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
try {
|
|
190
|
+
return await fn();
|
|
191
|
+
} catch (error) {
|
|
192
|
+
log('WARN', `Error caught by SelfHealer in ${module}`, { error: error.message });
|
|
193
|
+
const healResult = await this.heal(error, module, fn);
|
|
194
|
+
|
|
195
|
+
if (healResult.healed) {
|
|
196
|
+
log('INFO', `✅ ${module}: Hata düzeltildi — ${healResult.message || healResult.action}`);
|
|
197
|
+
return healResult.result;
|
|
198
|
+
} else {
|
|
199
|
+
log('ERROR', `❌ ${module}: Hata düzeltilemedi — ${healResult.message || healResult.action}`);
|
|
200
|
+
throw error; // Re-throw if we can't fix
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
getStatus() {
|
|
206
|
+
const recent = this.errorLog.slice(-20);
|
|
207
|
+
return {
|
|
208
|
+
totalErrors: this.errorLog.length,
|
|
209
|
+
recentErrors: recent.length,
|
|
210
|
+
snapshots: this.listSnapshots().length,
|
|
211
|
+
autoFixable: recent.filter(e => AUTO_FIXABLE[e.code]).length,
|
|
212
|
+
escalated: recent.filter(e => !AUTO_FIXABLE[e.code]).length
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
217
|
+
|
|
218
|
+
_classifyError(error) {
|
|
219
|
+
const msg = (error.message || error.toString()).toUpperCase();
|
|
220
|
+
const status = error.response?.status || error.status || error.code;
|
|
221
|
+
|
|
222
|
+
// Check status code first
|
|
223
|
+
if (status && AUTO_FIXABLE[String(status)]) return String(status);
|
|
224
|
+
|
|
225
|
+
// Check error code
|
|
226
|
+
if (error.code && AUTO_FIXABLE[error.code]) return error.code;
|
|
227
|
+
|
|
228
|
+
// Check message patterns
|
|
229
|
+
if (msg.includes('ETIMEDOUT') || msg.includes('TIMEOUT')) return 'ETIMEDOUT';
|
|
230
|
+
if (msg.includes('ECONNRESET')) return 'ECONNRESET';
|
|
231
|
+
if (msg.includes('ECONNREFUSED')) return 'ECONNREFUSED';
|
|
232
|
+
if (msg.includes('SYNTAXERROR') || msg.includes('UNEXPECTED TOKEN')) return 'SyntaxError';
|
|
233
|
+
if (msg.includes('429') || msg.includes('RATE LIMIT')) return '429';
|
|
234
|
+
|
|
235
|
+
return 'UNKNOWN';
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async _retry(fn, delayMs) {
|
|
239
|
+
if (!fn) return { healed: false, action: 'no_retry_fn', message: 'Retry fonksiyonu yok' };
|
|
240
|
+
|
|
241
|
+
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
|
|
242
|
+
try {
|
|
243
|
+
await new Promise(r => setTimeout(r, delayMs * attempt));
|
|
244
|
+
const result = await fn();
|
|
245
|
+
return { healed: true, action: 'retry', attempt, result };
|
|
246
|
+
} catch (e) {
|
|
247
|
+
if (attempt === this.maxRetries) {
|
|
248
|
+
return { healed: false, action: 'retry_exhausted', message: `${this.maxRetries} deneme başarısız` };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
_logError(error, module, code) {
|
|
255
|
+
this.errorLog.push({
|
|
256
|
+
module,
|
|
257
|
+
code,
|
|
258
|
+
message: error.message || String(error),
|
|
259
|
+
timestamp: new Date().toISOString()
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
if (this.errorLog.length > 500) {
|
|
263
|
+
this.errorLog = this.errorLog.slice(-500);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
this._saveErrorLog();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
_loadErrorLog() {
|
|
270
|
+
try {
|
|
271
|
+
if (fs.existsSync(ERROR_LOG_FILE)) {
|
|
272
|
+
return JSON.parse(fs.readFileSync(ERROR_LOG_FILE, 'utf-8'));
|
|
273
|
+
}
|
|
274
|
+
} catch (e) { /* ignore */ }
|
|
275
|
+
return [];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
_saveErrorLog() {
|
|
279
|
+
try {
|
|
280
|
+
const tmp = ERROR_LOG_FILE + '.tmp';
|
|
281
|
+
fs.writeFileSync(tmp, JSON.stringify(this.errorLog, null, 2), 'utf-8');
|
|
282
|
+
fs.renameSync(tmp, ERROR_LOG_FILE);
|
|
283
|
+
} catch (e) { /* ignore */ }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
_escalate(error, module, code) {
|
|
287
|
+
const ticket = {
|
|
288
|
+
type: 'SUPPORT_TICKET',
|
|
289
|
+
severity: 'critical',
|
|
290
|
+
module,
|
|
291
|
+
errorCode: code,
|
|
292
|
+
message: error.message || String(error),
|
|
293
|
+
timestamp: new Date().toISOString(),
|
|
294
|
+
note: `Kritik hata: ${module}. Otomatik düzeltme başarısız. Müdahale gerekli.`
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
log('ERROR', `🎫 SUPPORT TICKET: ${module} — ${code}`, ticket);
|
|
298
|
+
|
|
299
|
+
for (const cb of this.escalationCallbacks) {
|
|
300
|
+
try { cb(ticket); } catch (e) { /* swallow */ }
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
let healerInstance = null;
|
|
306
|
+
|
|
307
|
+
export function getSelfHealer() {
|
|
308
|
+
if (!healerInstance) {
|
|
309
|
+
healerInstance = new SelfHealer();
|
|
310
|
+
}
|
|
311
|
+
return healerInstance;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export default SelfHealer;
|