vantuz 3.0.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.
@@ -0,0 +1,464 @@
1
+ /**
2
+ * 🧠 HIPPOCAMPUS - Gelişmiş Hafıza Sistemi
3
+ *
4
+ * Beyin'in hippocampus bölgesinden ilham alınarak tasarlanmış,
5
+ * uzun süreli hafıza yönetimi ve bağlamsal hatırlama sistemi.
6
+ *
7
+ * Özellikler:
8
+ * - Episodik hafıza (olaylar, kararlar)
9
+ * - Semantik hafıza (ürün bilgileri, kurallar)
10
+ * - Vektör tabanlı benzerlik araması
11
+ * - Otomatik hafıza konsolidasyonu
12
+ * - Önem bazlı unutma mekanizması
13
+ */
14
+
15
+ import { Sequelize, DataTypes, Op } from 'sequelize';
16
+ import path from 'path';
17
+ import crypto from 'crypto';
18
+
19
+ export class Hippocampus {
20
+ constructor(api) {
21
+ this.api = api;
22
+ this.logger = api.logger;
23
+ this.db = null;
24
+ this.models = {};
25
+ this.initialized = false;
26
+ }
27
+
28
+ async initialize() {
29
+ const dbPath = path.join(process.cwd(), '.vantuz', 'hippocampus.sqlite');
30
+
31
+ this.db = new Sequelize({
32
+ dialect: 'sqlite',
33
+ storage: dbPath,
34
+ logging: false
35
+ });
36
+
37
+ // Hafıza Modelleri
38
+ this.models.Memory = this.db.define('Memory', {
39
+ id: {
40
+ type: DataTypes.UUID,
41
+ defaultValue: DataTypes.UUIDV4,
42
+ primaryKey: true
43
+ },
44
+ type: {
45
+ type: DataTypes.STRING,
46
+ allowNull: false,
47
+ // decision, price_change, product, conversation, insight, rule
48
+ },
49
+ content: {
50
+ type: DataTypes.TEXT,
51
+ allowNull: false
52
+ },
53
+ context: {
54
+ type: DataTypes.JSON,
55
+ // İlişkili veriler: productId, platform, userId, etc.
56
+ },
57
+ embedding: {
58
+ type: DataTypes.TEXT,
59
+ // Vektör gömme (JSON olarak saklanır)
60
+ },
61
+ importance: {
62
+ type: DataTypes.FLOAT,
63
+ defaultValue: 0.5,
64
+ // 0-1 arası önem skoru
65
+ },
66
+ accessCount: {
67
+ type: DataTypes.INTEGER,
68
+ defaultValue: 0
69
+ },
70
+ lastAccessed: {
71
+ type: DataTypes.DATE
72
+ },
73
+ expiresAt: {
74
+ type: DataTypes.DATE,
75
+ // null = kalıcı hafıza
76
+ },
77
+ tags: {
78
+ type: DataTypes.JSON,
79
+ defaultValue: []
80
+ }
81
+ });
82
+
83
+ // Fiyat Karar Geçmişi
84
+ this.models.PricingDecision = this.db.define('PricingDecision', {
85
+ id: {
86
+ type: DataTypes.UUID,
87
+ defaultValue: DataTypes.UUIDV4,
88
+ primaryKey: true
89
+ },
90
+ productId: DataTypes.STRING,
91
+ barcode: DataTypes.STRING,
92
+ platform: DataTypes.STRING,
93
+ previousPrice: DataTypes.FLOAT,
94
+ newPrice: DataTypes.FLOAT,
95
+ reason: DataTypes.TEXT,
96
+ factors: {
97
+ type: DataTypes.JSON,
98
+ // { competitorPrice, competitorStock, ourStock, margin, velocity }
99
+ },
100
+ outcome: {
101
+ type: DataTypes.STRING,
102
+ // applied, rejected, pending
103
+ },
104
+ profitImpact: DataTypes.FLOAT
105
+ });
106
+
107
+ // Ürün Bağlamı
108
+ this.models.ProductContext = this.db.define('ProductContext', {
109
+ id: {
110
+ type: DataTypes.UUID,
111
+ defaultValue: DataTypes.UUIDV4,
112
+ primaryKey: true
113
+ },
114
+ barcode: {
115
+ type: DataTypes.STRING,
116
+ unique: true
117
+ },
118
+ name: DataTypes.STRING,
119
+ category: DataTypes.STRING,
120
+ avgSalePrice: DataTypes.FLOAT,
121
+ avgCost: DataTypes.FLOAT,
122
+ seasonality: DataTypes.JSON,
123
+ competitorHistory: DataTypes.JSON,
124
+ customerSentiment: {
125
+ type: DataTypes.JSON,
126
+ // { positive: 0.8, negative: 0.2, topComplaints: [] }
127
+ },
128
+ priceElasticity: DataTypes.FLOAT,
129
+ optimalPriceRange: DataTypes.JSON
130
+ });
131
+
132
+ // Konuşma Geçmişi (Session bazlı)
133
+ this.models.ConversationMemory = this.db.define('ConversationMemory', {
134
+ id: {
135
+ type: DataTypes.UUID,
136
+ defaultValue: DataTypes.UUIDV4,
137
+ primaryKey: true
138
+ },
139
+ sessionKey: DataTypes.STRING,
140
+ userId: DataTypes.STRING,
141
+ channel: DataTypes.STRING,
142
+ role: {
143
+ type: DataTypes.STRING,
144
+ // user, assistant
145
+ },
146
+ content: DataTypes.TEXT,
147
+ intent: DataTypes.STRING,
148
+ entities: DataTypes.JSON,
149
+ actionTaken: DataTypes.STRING
150
+ });
151
+
152
+ // Öğrenilen Kurallar
153
+ this.models.LearnedRule = this.db.define('LearnedRule', {
154
+ id: {
155
+ type: DataTypes.UUID,
156
+ defaultValue: DataTypes.UUIDV4,
157
+ primaryKey: true
158
+ },
159
+ trigger: DataTypes.TEXT,
160
+ condition: DataTypes.JSON,
161
+ action: DataTypes.TEXT,
162
+ confidence: {
163
+ type: DataTypes.FLOAT,
164
+ defaultValue: 0.5
165
+ },
166
+ usageCount: {
167
+ type: DataTypes.INTEGER,
168
+ defaultValue: 0
169
+ },
170
+ successRate: {
171
+ type: DataTypes.FLOAT,
172
+ defaultValue: 0.5
173
+ }
174
+ });
175
+
176
+ await this.db.sync({ alter: true });
177
+ this.initialized = true;
178
+ this.logger.info('🧠 Hippocampus veritabanı hazır.');
179
+
180
+ // Hafıza konsolidasyonu zamanlayıcısı (her gece)
181
+ this._startConsolidation();
182
+ }
183
+
184
+ // ═══════════════════════════════════════════════════════════════════════════
185
+ // HAFIZA KAYDETME
186
+ // ═══════════════════════════════════════════════════════════════════════════
187
+
188
+ async remember(type, content, context = {}, options = {}) {
189
+ const memory = await this.models.Memory.create({
190
+ type,
191
+ content: typeof content === 'string' ? content : JSON.stringify(content),
192
+ context,
193
+ importance: options.importance || this._calculateImportance(type, content),
194
+ tags: options.tags || [],
195
+ expiresAt: options.temporary ? new Date(Date.now() + 24 * 60 * 60 * 1000) : null
196
+ });
197
+
198
+ this.logger.debug(`💾 Hafıza kaydedildi: ${type} - ${memory.id}`);
199
+ return memory;
200
+ }
201
+
202
+ async recordPricingDecision(decision) {
203
+ return await this.models.PricingDecision.create(decision);
204
+ }
205
+
206
+ async updateProductContext(barcode, updates) {
207
+ const [context, created] = await this.models.ProductContext.findOrCreate({
208
+ where: { barcode },
209
+ defaults: { barcode, ...updates }
210
+ });
211
+
212
+ if (!created) {
213
+ await context.update(updates);
214
+ }
215
+
216
+ return context;
217
+ }
218
+
219
+ async recordConversation(sessionKey, userId, channel, role, content, metadata = {}) {
220
+ return await this.models.ConversationMemory.create({
221
+ sessionKey,
222
+ userId,
223
+ channel,
224
+ role,
225
+ content,
226
+ intent: metadata.intent,
227
+ entities: metadata.entities,
228
+ actionTaken: metadata.action
229
+ });
230
+ }
231
+
232
+ // ═══════════════════════════════════════════════════════════════════════════
233
+ // HAFIZA ARAMA
234
+ // ═══════════════════════════════════════════════════════════════════════════
235
+
236
+ async search({ query, type, limit = 10, minImportance = 0 }) {
237
+ const where = {};
238
+
239
+ if (type && type !== 'all') {
240
+ where.type = type;
241
+ }
242
+
243
+ if (minImportance > 0) {
244
+ where.importance = { [Op.gte]: minImportance };
245
+ }
246
+
247
+ // Basit metin araması (ileride vektör araması eklenebilir)
248
+ if (query) {
249
+ where.content = { [Op.like]: `%${query}%` };
250
+ }
251
+
252
+ const memories = await this.models.Memory.findAll({
253
+ where,
254
+ order: [['importance', 'DESC'], ['createdAt', 'DESC']],
255
+ limit
256
+ });
257
+
258
+ // Erişim sayacını güncelle
259
+ for (const mem of memories) {
260
+ await mem.update({
261
+ accessCount: mem.accessCount + 1,
262
+ lastAccessed: new Date()
263
+ });
264
+ }
265
+
266
+ return memories.map(m => ({
267
+ id: m.id,
268
+ type: m.type,
269
+ content: m.content,
270
+ context: m.context,
271
+ importance: m.importance,
272
+ createdAt: m.createdAt
273
+ }));
274
+ }
275
+
276
+ async getProductContext(barcode) {
277
+ return await this.models.ProductContext.findOne({ where: { barcode } });
278
+ }
279
+
280
+ async getPricingHistory(barcode, limit = 10) {
281
+ return await this.models.PricingDecision.findAll({
282
+ where: { barcode },
283
+ order: [['createdAt', 'DESC']],
284
+ limit
285
+ });
286
+ }
287
+
288
+ async getRecentConversations(sessionKey, limit = 20) {
289
+ return await this.models.ConversationMemory.findAll({
290
+ where: { sessionKey },
291
+ order: [['createdAt', 'DESC']],
292
+ limit
293
+ });
294
+ }
295
+
296
+ async getLearnedRules(trigger) {
297
+ return await this.models.LearnedRule.findAll({
298
+ where: {
299
+ trigger: { [Op.like]: `%${trigger}%` },
300
+ confidence: { [Op.gte]: 0.6 }
301
+ },
302
+ order: [['confidence', 'DESC'], ['usageCount', 'DESC']]
303
+ });
304
+ }
305
+
306
+ // ═══════════════════════════════════════════════════════════════════════════
307
+ // BAĞLAMSAL HATIRLATMA
308
+ // ═══════════════════════════════════════════════════════════════════════════
309
+
310
+ async getRelevantContext(input, options = {}) {
311
+ const context = {
312
+ recentDecisions: [],
313
+ productHistory: null,
314
+ relatedMemories: [],
315
+ applicableRules: []
316
+ };
317
+
318
+ // Ürün barkodu varsa ürün bağlamını al
319
+ if (options.barcode) {
320
+ context.productHistory = await this.getProductContext(options.barcode);
321
+ context.recentDecisions = await this.getPricingHistory(options.barcode, 5);
322
+ }
323
+
324
+ // İlgili hafızaları ara
325
+ context.relatedMemories = await this.search({
326
+ query: input,
327
+ type: options.type || 'all',
328
+ limit: 5,
329
+ minImportance: 0.3
330
+ });
331
+
332
+ // Uygulanabilir kuralları bul
333
+ context.applicableRules = await this.getLearnedRules(input);
334
+
335
+ return context;
336
+ }
337
+
338
+ // ═══════════════════════════════════════════════════════════════════════════
339
+ // ÖĞRENME & KONSOLİDASYON
340
+ // ═══════════════════════════════════════════════════════════════════════════
341
+
342
+ async learnRule(trigger, condition, action) {
343
+ const existing = await this.models.LearnedRule.findOne({
344
+ where: { trigger, action }
345
+ });
346
+
347
+ if (existing) {
348
+ await existing.update({
349
+ usageCount: existing.usageCount + 1,
350
+ confidence: Math.min(1, existing.confidence + 0.05)
351
+ });
352
+ return existing;
353
+ }
354
+
355
+ return await this.models.LearnedRule.create({
356
+ trigger,
357
+ condition,
358
+ action,
359
+ confidence: 0.5
360
+ });
361
+ }
362
+
363
+ async recordRuleOutcome(ruleId, success) {
364
+ const rule = await this.models.LearnedRule.findByPk(ruleId);
365
+ if (!rule) return;
366
+
367
+ const newSuccessRate = (rule.successRate * rule.usageCount + (success ? 1 : 0)) / (rule.usageCount + 1);
368
+ const newConfidence = success
369
+ ? Math.min(1, rule.confidence + 0.1)
370
+ : Math.max(0, rule.confidence - 0.1);
371
+
372
+ await rule.update({
373
+ usageCount: rule.usageCount + 1,
374
+ successRate: newSuccessRate,
375
+ confidence: newConfidence
376
+ });
377
+ }
378
+
379
+ _startConsolidation() {
380
+ // Her gece saat 3'te çalış
381
+ const now = new Date();
382
+ const night = new Date(now);
383
+ night.setHours(3, 0, 0, 0);
384
+ if (night <= now) night.setDate(night.getDate() + 1);
385
+
386
+ const delay = night - now;
387
+
388
+ setTimeout(() => {
389
+ this._consolidate();
390
+ // Sonra her 24 saatte bir
391
+ setInterval(() => this._consolidate(), 24 * 60 * 60 * 1000);
392
+ }, delay);
393
+ }
394
+
395
+ async _consolidate() {
396
+ this.logger.info('🧠 Hafıza konsolidasyonu başlıyor...');
397
+
398
+ // 1. Süresi dolmuş hafızaları sil
399
+ await this.models.Memory.destroy({
400
+ where: {
401
+ expiresAt: { [Op.lt]: new Date() }
402
+ }
403
+ });
404
+
405
+ // 2. Düşük önemli ve erişilmeyen hafızaları "unut"
406
+ const oldDate = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000); // 90 gün
407
+ await this.models.Memory.destroy({
408
+ where: {
409
+ importance: { [Op.lt]: 0.3 },
410
+ accessCount: { [Op.lt]: 3 },
411
+ lastAccessed: { [Op.lt]: oldDate }
412
+ }
413
+ });
414
+
415
+ // 3. Düşük güvenilirlikli kuralları sil
416
+ await this.models.LearnedRule.destroy({
417
+ where: {
418
+ confidence: { [Op.lt]: 0.2 },
419
+ usageCount: { [Op.gt]: 10 }
420
+ }
421
+ });
422
+
423
+ this.logger.info('🧠 Hafıza konsolidasyonu tamamlandı.');
424
+ }
425
+
426
+ _calculateImportance(type, content) {
427
+ // Tip bazlı temel önem
428
+ const baseImportance = {
429
+ decision: 0.8,
430
+ price_change: 0.7,
431
+ insight: 0.6,
432
+ rule: 0.9,
433
+ product: 0.5,
434
+ conversation: 0.3
435
+ };
436
+
437
+ return baseImportance[type] || 0.5;
438
+ }
439
+
440
+ // ═══════════════════════════════════════════════════════════════════════════
441
+ // İSTATİSTİKLER
442
+ // ═══════════════════════════════════════════════════════════════════════════
443
+
444
+ async getStats() {
445
+ const memoryCount = await this.models.Memory.count();
446
+ const decisionCount = await this.models.PricingDecision.count();
447
+ const productCount = await this.models.ProductContext.count();
448
+ const ruleCount = await this.models.LearnedRule.count();
449
+
450
+ return {
451
+ memories: memoryCount,
452
+ decisions: decisionCount,
453
+ products: productCount,
454
+ rules: ruleCount,
455
+ initialized: this.initialized
456
+ };
457
+ }
458
+
459
+ async close() {
460
+ if (this.db) {
461
+ await this.db.close();
462
+ }
463
+ }
464
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@vantuz/plugin",
3
+ "version": "2.0.0",
4
+ "description": "Vantuz AI E-Commerce Plugin for OpenClaw",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ },
10
+ "openclaw": {
11
+ "id": "vantuz",
12
+ "name": "Vantuz AI",
13
+ "description": "E-ticaret yönetim araçları: repricer, vision, sentiment, crossborder",
14
+ "version": "2.0.0"
15
+ },
16
+ "dependencies": {
17
+ "axios": "^1.6.0",
18
+ "sequelize": "^6.37.7",
19
+ "sqlite3": "^5.1.7"
20
+ }
21
+ }