vantuz 3.3.6 → 3.3.7

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.
@@ -0,0 +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;
@@ -0,0 +1,214 @@
1
+ // core/unified-product.js
2
+ // Unified Product Model for Vantuz OS V2
3
+ // Normalizes product data from ALL platforms into one Vantuz format.
4
+
5
+ import { log } from './ai-provider.js';
6
+
7
+ // ═══════════════════════════════════════════════════════════════════════════
8
+ // UNIFIED PRODUCT SCHEMA
9
+ // ═══════════════════════════════════════════════════════════════════════════
10
+
11
+ /**
12
+ * Creates a Unified Product from raw platform data.
13
+ * @param {object} raw - Raw product data from any platform API.
14
+ * @param {string} platform - Source platform name.
15
+ * @returns {object} Unified Product.
16
+ */
17
+ export function normalizeProduct(raw, platform) {
18
+ const normalized = {
19
+ // Identity
20
+ sku: raw.sku || raw.stockCode || raw.merchantSku || raw.productCode || null,
21
+ barcode: raw.barcode || raw.barcodes?.[0] || raw.gtin || null,
22
+ title: raw.title || raw.productName || raw.name || '',
23
+ brand: raw.brand || raw.brandName || '',
24
+ category: raw.category || raw.categoryName || '',
25
+
26
+ // Pricing
27
+ price: parseFloat(raw.salePrice || raw.price || raw.listingPrice || 0),
28
+ listPrice: parseFloat(raw.listPrice || raw.marketPrice || raw.originalPrice || 0),
29
+ cost: parseFloat(raw.cost || raw.costPrice || 0),
30
+ currency: raw.currency || 'TRY',
31
+
32
+ // Stock
33
+ stock: parseInt(raw.quantity || raw.stock || raw.stockQuantity || 0, 10),
34
+
35
+ // Images
36
+ images: raw.images || raw.imageUrls || (raw.imageUrl ? [raw.imageUrl] : []),
37
+
38
+ // Status
39
+ onSale: raw.onSale ?? raw.approved ?? raw.active ?? true,
40
+
41
+ // Platform-specific data
42
+ platforms: {
43
+ [platform]: {
44
+ id: raw.id || raw.productId || raw.contentId || null,
45
+ url: raw.url || raw.productUrl || null,
46
+ lastSync: new Date().toISOString(),
47
+ raw: raw // Keep original for debugging
48
+ }
49
+ },
50
+
51
+ // Analytics (populated by other modules)
52
+ competitors: [],
53
+ salesVelocity: 0, // units/day — filled by Oracle
54
+ margin: 0, // calculated below
55
+ stockoutDate: null, // filled by Oracle
56
+ sentimentScore: null, // filled by CRM
57
+
58
+ // Meta
59
+ _source: platform,
60
+ _normalizedAt: new Date().toISOString()
61
+ };
62
+
63
+ // Calculate margin
64
+ if (normalized.cost > 0 && normalized.price > 0) {
65
+ normalized.margin = ((normalized.price - normalized.cost) / normalized.price) * 100;
66
+ }
67
+
68
+ return normalized;
69
+ }
70
+
71
+ /**
72
+ * Merge a new platform occurrence into an existing unified product.
73
+ * (Same barcode, different platform.)
74
+ * @param {object} existing - Existing unified product.
75
+ * @param {object} raw - New raw data.
76
+ * @param {string} platform - Source platform.
77
+ * @returns {object} Merged product.
78
+ */
79
+ export function mergeProduct(existing, raw, platform) {
80
+ const incoming = normalizeProduct(raw, platform);
81
+
82
+ // Add to platforms map
83
+ existing.platforms[platform] = incoming.platforms[platform];
84
+
85
+ // Use the lowest price as the "effective" price
86
+ if (incoming.price > 0 && (incoming.price < existing.price || existing.price === 0)) {
87
+ existing.price = incoming.price;
88
+ }
89
+
90
+ // Sum stock across platforms
91
+ existing.stock = Object.values(existing.platforms).reduce((sum, p) => {
92
+ const pStock = parseInt(p.raw?.quantity || p.raw?.stock || 0, 10);
93
+ return sum + pStock;
94
+ }, 0);
95
+
96
+ // Use best title (longest, usually most SEO-friendly)
97
+ if (incoming.title.length > existing.title.length) {
98
+ existing.title = incoming.title;
99
+ }
100
+
101
+ // Merge images (unique)
102
+ const allImages = [...(existing.images || []), ...(incoming.images || [])];
103
+ existing.images = [...new Set(allImages)];
104
+
105
+ // Recalculate margin
106
+ if (existing.cost > 0 && existing.price > 0) {
107
+ existing.margin = ((existing.price - existing.cost) / existing.price) * 100;
108
+ }
109
+
110
+ return existing;
111
+ }
112
+
113
+ // ═══════════════════════════════════════════════════════════════════════════
114
+ // PRODUCT CATALOG (In-Memory + Disk)
115
+ // ═══════════════════════════════════════════════════════════════════════════
116
+
117
+ import fs from 'fs';
118
+ import path from 'path';
119
+ import os from 'os';
120
+
121
+ const CATALOG_FILE = path.join(os.homedir(), '.vantuz', 'memory', 'catalog.json');
122
+
123
+ class ProductCatalog {
124
+ constructor() {
125
+ this.products = new Map(); // barcode -> UnifiedProduct
126
+ this._load();
127
+ }
128
+
129
+ _load() {
130
+ try {
131
+ if (fs.existsSync(CATALOG_FILE)) {
132
+ const data = JSON.parse(fs.readFileSync(CATALOG_FILE, 'utf-8'));
133
+ for (const [barcode, product] of Object.entries(data)) {
134
+ this.products.set(barcode, product);
135
+ }
136
+ log('INFO', `Product catalog loaded`, { count: this.products.size });
137
+ }
138
+ } catch (e) {
139
+ log('WARN', 'Catalog load failed', { error: e.message });
140
+ }
141
+ }
142
+
143
+ _save() {
144
+ const dir = path.dirname(CATALOG_FILE);
145
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
146
+ const obj = Object.fromEntries(this.products);
147
+ const tmp = CATALOG_FILE + '.tmp';
148
+ fs.writeFileSync(tmp, JSON.stringify(obj, null, 2), 'utf-8');
149
+ fs.renameSync(tmp, CATALOG_FILE);
150
+ }
151
+
152
+ /**
153
+ * Ingest raw product data from a platform.
154
+ */
155
+ ingest(rawProducts, platform) {
156
+ let added = 0, updated = 0;
157
+
158
+ for (const raw of rawProducts) {
159
+ const barcode = raw.barcode || raw.barcodes?.[0] || raw.gtin;
160
+ if (!barcode) continue;
161
+
162
+ if (this.products.has(barcode)) {
163
+ mergeProduct(this.products.get(barcode), raw, platform);
164
+ updated++;
165
+ } else {
166
+ this.products.set(barcode, normalizeProduct(raw, platform));
167
+ added++;
168
+ }
169
+ }
170
+
171
+ this._save();
172
+ log('INFO', `Catalog ingested from ${platform}`, { added, updated, total: this.products.size });
173
+ return { added, updated, total: this.products.size };
174
+ }
175
+
176
+ get(barcode) {
177
+ return this.products.get(barcode) || null;
178
+ }
179
+
180
+ getAll() {
181
+ return [...this.products.values()];
182
+ }
183
+
184
+ /**
185
+ * Find products that are low on stock.
186
+ * @param {number} threshold - Min stock threshold (default: 5).
187
+ */
188
+ getLowStock(threshold = 5) {
189
+ return this.getAll().filter(p => p.stock > 0 && p.stock <= threshold);
190
+ }
191
+
192
+ /**
193
+ * Find products below target margin.
194
+ * @param {number} minMargin - Minimum margin % (default: 15).
195
+ */
196
+ getLowMargin(minMargin = 15) {
197
+ return this.getAll().filter(p => p.margin > 0 && p.margin < minMargin);
198
+ }
199
+
200
+ get size() {
201
+ return this.products.size;
202
+ }
203
+ }
204
+
205
+ let catalogInstance = null;
206
+
207
+ export function getCatalog() {
208
+ if (!catalogInstance) {
209
+ catalogInstance = new ProductCatalog();
210
+ }
211
+ return catalogInstance;
212
+ }
213
+
214
+ export default ProductCatalog;
package/core/vector-db.js CHANGED
@@ -1,17 +1,90 @@
1
1
  // core/vector-db.js
2
+ // Persistent Vector Database for Vantuz AI
3
+ // Uses JSON file persistence instead of in-memory-only storage.
4
+
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import os from 'os';
2
8
  import { log } from './ai-provider.js';
3
9
 
10
+ const VECTOR_DIR = path.join(os.homedir(), '.vantuz', 'memory');
11
+ const VECTOR_FILE = path.join(VECTOR_DIR, 'vectors.json');
12
+
13
+ function ensureDir() {
14
+ if (!fs.existsSync(VECTOR_DIR)) {
15
+ fs.mkdirSync(VECTOR_DIR, { recursive: true });
16
+ }
17
+ }
18
+
19
+ function loadFromDisk() {
20
+ try {
21
+ if (fs.existsSync(VECTOR_FILE)) {
22
+ const raw = fs.readFileSync(VECTOR_FILE, 'utf-8');
23
+ const data = JSON.parse(raw);
24
+ // Convert plain object back to Map
25
+ const map = new Map();
26
+ for (const [name, collection] of Object.entries(data)) {
27
+ map.set(name, collection);
28
+ }
29
+ log('INFO', `VectorDB loaded from disk`, { collections: map.size });
30
+ return map;
31
+ }
32
+ } catch (e) {
33
+ log('WARN', 'VectorDB disk load failed, starting fresh', { error: e.message });
34
+ }
35
+ return new Map();
36
+ }
37
+
38
+ function saveToDisk(collections) {
39
+ ensureDir();
40
+ const obj = {};
41
+ for (const [name, collection] of collections) {
42
+ obj[name] = collection;
43
+ }
44
+ const tmp = VECTOR_FILE + '.tmp';
45
+ fs.writeFileSync(tmp, JSON.stringify(obj), 'utf-8');
46
+ fs.renameSync(tmp, VECTOR_FILE);
47
+ }
48
+
4
49
  class VectorDB {
5
50
  constructor() {
6
- this.collections = new Map(); // collectionName -> { vectors: [], metadatas: [] }
7
- log('INFO', 'In-memory VectorDB initialized');
51
+ ensureDir();
52
+ this.collections = loadFromDisk();
53
+ this._dirty = false;
54
+ this._saveTimer = null;
55
+ log('INFO', 'Persistent VectorDB initialized', { collections: this.collections.size });
56
+ }
57
+
58
+ /**
59
+ * Debounced save — writes to disk at most every 2 seconds.
60
+ */
61
+ _scheduleSave() {
62
+ this._dirty = true;
63
+ if (this._saveTimer) return;
64
+ this._saveTimer = setTimeout(() => {
65
+ if (this._dirty) {
66
+ saveToDisk(this.collections);
67
+ this._dirty = false;
68
+ log('INFO', 'VectorDB persisted to disk');
69
+ }
70
+ this._saveTimer = null;
71
+ }, 2000);
72
+ }
73
+
74
+ /**
75
+ * Force immediate save.
76
+ */
77
+ flush() {
78
+ if (this._saveTimer) {
79
+ clearTimeout(this._saveTimer);
80
+ this._saveTimer = null;
81
+ }
82
+ saveToDisk(this.collections);
83
+ this._dirty = false;
8
84
  }
9
85
 
10
86
  /**
11
87
  * Kosinüs benzerliğini hesaplar.
12
- * @param {number[]} vec1
13
- * @param {number[]} vec2
14
- * @returns {number} Kosinüs benzerliği.
15
88
  */
16
89
  _cosineSimilarity(vec1, vec2) {
17
90
  if (vec1.length !== vec2.length) {
@@ -29,19 +102,18 @@ class VectorDB {
29
102
  magnitude2 = Math.sqrt(magnitude2);
30
103
 
31
104
  if (magnitude1 === 0 || magnitude2 === 0) {
32
- return 0; // Avoid division by zero
105
+ return 0;
33
106
  }
34
107
  return dotProduct / (magnitude1 * magnitude2);
35
108
  }
36
109
 
37
110
  /**
38
111
  * Vektör koleksiyonu oluşturur veya alır.
39
- * @param {string} collectionName
40
- * @returns {{vectors: Array<number[]>, metadatas: Array<Object>}}
41
112
  */
42
113
  getCollection(collectionName) {
43
114
  if (!this.collections.has(collectionName)) {
44
115
  this.collections.set(collectionName, { vectors: [], metadatas: [] });
116
+ this._scheduleSave();
45
117
  log('INFO', `Vector collection "${collectionName}" created.`);
46
118
  }
47
119
  return this.collections.get(collectionName);
@@ -49,23 +121,17 @@ class VectorDB {
49
121
 
50
122
  /**
51
123
  * Koleksiyona vektör ve metadata ekler.
52
- * @param {string} collectionName
53
- * @param {number[]} vector
54
- * @param {Object} metadata
55
124
  */
56
125
  add(collectionName, vector, metadata) {
57
126
  const collection = this.getCollection(collectionName);
58
127
  collection.vectors.push(vector);
59
128
  collection.metadatas.push(metadata);
129
+ this._scheduleSave();
60
130
  log('INFO', `Vector added to collection "${collectionName}"`);
61
131
  }
62
132
 
63
133
  /**
64
134
  * Bir sorgu vektörüne en benzer vektörleri bulur.
65
- * @param {string} collectionName
66
- * @param {number[]} queryVector
67
- * @param {number} topK En çok kaç sonuç döndürülecek.
68
- * @returns {Array<{metadata: Object, similarity: number}>} Sıralanmış sonuçlar.
69
135
  */
70
136
  search(collectionName, queryVector, topK = 5) {
71
137
  const collection = this.collections.get(collectionName);
@@ -81,8 +147,8 @@ class VectorDB {
81
147
  };
82
148
  });
83
149
 
84
- results.sort((a, b) => b.similarity - a.similarity); // Yüksek benzerlik önde
85
- log('INFO', `Search performed on collection "${collectionName}", found ${results.length} results.`);
150
+ results.sort((a, b) => b.similarity - a.similarity);
151
+ log('INFO', `Search on "${collectionName}", found ${results.length} results.`);
86
152
  return results.slice(0, topK);
87
153
  }
88
154
  }