web-agent-bridge 3.2.0 → 3.3.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.
Files changed (202) hide show
  1. package/LICENSE +72 -72
  2. package/README.ar.md +1286 -1152
  3. package/README.md +1764 -1635
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -138
  6. package/bin/wab.js +80 -80
  7. package/examples/bidi-agent.js +119 -119
  8. package/examples/cross-site-agent.js +91 -91
  9. package/examples/mcp-agent.js +94 -94
  10. package/examples/next-app-router/README.md +44 -44
  11. package/examples/puppeteer-agent.js +108 -108
  12. package/examples/saas-dashboard/README.md +55 -55
  13. package/examples/shopify-hydrogen/README.md +74 -74
  14. package/examples/vision-agent.js +171 -171
  15. package/examples/wordpress-elementor/README.md +77 -77
  16. package/package.json +16 -3
  17. package/public/.well-known/agent-tools.json +180 -180
  18. package/public/.well-known/ai-assets.json +59 -59
  19. package/public/.well-known/security.txt +8 -0
  20. package/public/agent-workspace.html +349 -349
  21. package/public/ai.html +198 -198
  22. package/public/api.html +413 -412
  23. package/public/browser.html +486 -486
  24. package/public/commander-dashboard.html +243 -243
  25. package/public/cookies.html +210 -210
  26. package/public/css/agent-workspace.css +1713 -1713
  27. package/public/css/premium.css +317 -317
  28. package/public/css/styles.css +1235 -1235
  29. package/public/dashboard.html +706 -706
  30. package/public/dns.html +507 -0
  31. package/public/docs.html +587 -587
  32. package/public/feed.xml +89 -89
  33. package/public/growth.html +463 -463
  34. package/public/index.html +1070 -982
  35. package/public/integrations.html +556 -0
  36. package/public/js/agent-workspace.js +1740 -1740
  37. package/public/js/auth-nav.js +31 -31
  38. package/public/js/auth-redirect.js +12 -12
  39. package/public/js/cookie-consent.js +56 -56
  40. package/public/js/wab-demo-page.js +721 -721
  41. package/public/js/ws-client.js +74 -74
  42. package/public/llms-full.txt +360 -360
  43. package/public/llms.txt +125 -125
  44. package/public/login.html +85 -85
  45. package/public/mesh-dashboard.html +328 -328
  46. package/public/openapi.json +580 -580
  47. package/public/phone-shield.html +281 -0
  48. package/public/premium-dashboard.html +2489 -2489
  49. package/public/premium.html +793 -793
  50. package/public/privacy.html +297 -297
  51. package/public/register.html +105 -105
  52. package/public/robots.txt +87 -87
  53. package/public/script/wab-consent.d.ts +36 -36
  54. package/public/script/wab-consent.js +104 -104
  55. package/public/script/wab-schema.js +131 -131
  56. package/public/script/wab.d.ts +108 -108
  57. package/public/script/wab.min.js +580 -580
  58. package/public/security.txt +8 -0
  59. package/public/terms.html +256 -256
  60. package/script/ai-agent-bridge.js +1754 -1754
  61. package/sdk/README.md +99 -99
  62. package/sdk/agent-mesh.js +449 -449
  63. package/sdk/commander.js +262 -262
  64. package/sdk/index.d.ts +464 -464
  65. package/sdk/index.js +12 -1
  66. package/sdk/multi-agent.js +318 -318
  67. package/sdk/package.json +1 -1
  68. package/sdk/safety-shield.js +219 -0
  69. package/sdk/schema-discovery.js +83 -83
  70. package/server/adapters/index.js +520 -520
  71. package/server/config/plans.js +367 -367
  72. package/server/config/secrets.js +102 -102
  73. package/server/control-plane/index.js +301 -301
  74. package/server/data-plane/index.js +354 -354
  75. package/server/index.js +531 -427
  76. package/server/llm/index.js +404 -404
  77. package/server/middleware/adminAuth.js +35 -35
  78. package/server/middleware/auth.js +50 -50
  79. package/server/middleware/featureGate.js +88 -88
  80. package/server/middleware/rateLimits.js +100 -100
  81. package/server/middleware/sensitiveAction.js +157 -0
  82. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  83. package/server/migrations/002_premium_features.sql +418 -418
  84. package/server/migrations/003_ads_integer_cents.sql +33 -33
  85. package/server/migrations/004_agent_os.sql +158 -158
  86. package/server/migrations/005_marketplace_metering.sql +126 -126
  87. package/server/models/adapters/index.js +33 -33
  88. package/server/models/adapters/mysql.js +183 -183
  89. package/server/models/adapters/postgresql.js +172 -172
  90. package/server/models/adapters/sqlite.js +7 -7
  91. package/server/models/db.js +681 -681
  92. package/server/observability/failure-analysis.js +337 -337
  93. package/server/observability/index.js +394 -394
  94. package/server/protocol/capabilities.js +223 -223
  95. package/server/protocol/index.js +243 -243
  96. package/server/protocol/schema.js +584 -584
  97. package/server/registry/certification.js +271 -271
  98. package/server/registry/index.js +326 -326
  99. package/server/routes/admin-premium.js +671 -671
  100. package/server/routes/admin.js +261 -261
  101. package/server/routes/ads.js +130 -130
  102. package/server/routes/agent-workspace.js +540 -540
  103. package/server/routes/api.js +150 -150
  104. package/server/routes/auth.js +71 -71
  105. package/server/routes/billing.js +45 -45
  106. package/server/routes/commander.js +316 -316
  107. package/server/routes/demo-showcase.js +332 -332
  108. package/server/routes/demo-store.js +154 -0
  109. package/server/routes/discovery.js +417 -417
  110. package/server/routes/gateway.js +173 -157
  111. package/server/routes/license.js +251 -240
  112. package/server/routes/mesh.js +469 -469
  113. package/server/routes/noscript.js +543 -543
  114. package/server/routes/premium-v2.js +686 -686
  115. package/server/routes/premium.js +724 -724
  116. package/server/routes/runtime.js +2148 -2147
  117. package/server/routes/sovereign.js +465 -385
  118. package/server/routes/universal.js +200 -185
  119. package/server/routes/wab-api.js +850 -501
  120. package/server/runtime/container-worker.js +111 -111
  121. package/server/runtime/container.js +448 -448
  122. package/server/runtime/distributed-worker.js +362 -362
  123. package/server/runtime/event-bus.js +210 -210
  124. package/server/runtime/index.js +253 -253
  125. package/server/runtime/queue.js +599 -599
  126. package/server/runtime/replay.js +666 -666
  127. package/server/runtime/sandbox.js +266 -266
  128. package/server/runtime/scheduler.js +534 -534
  129. package/server/runtime/session-engine.js +293 -293
  130. package/server/runtime/state-manager.js +188 -188
  131. package/server/security/cross-site-redactor.js +196 -0
  132. package/server/security/dry-run.js +180 -0
  133. package/server/security/human-gate-rate-limit.js +147 -0
  134. package/server/security/human-gate-transports.js +178 -0
  135. package/server/security/human-gate.js +281 -0
  136. package/server/security/index.js +368 -368
  137. package/server/security/intent-engine.js +245 -0
  138. package/server/security/reward-guard.js +171 -0
  139. package/server/security/rollback-store.js +239 -0
  140. package/server/security/token-scope.js +404 -0
  141. package/server/security/url-policy.js +139 -0
  142. package/server/services/agent-chat.js +506 -506
  143. package/server/services/agent-learning.js +601 -575
  144. package/server/services/agent-memory.js +625 -625
  145. package/server/services/agent-mesh.js +555 -539
  146. package/server/services/agent-symphony.js +717 -717
  147. package/server/services/agent-tasks.js +1807 -1807
  148. package/server/services/api-key-engine.js +292 -261
  149. package/server/services/cluster.js +894 -894
  150. package/server/services/commander.js +738 -738
  151. package/server/services/edge-compute.js +440 -440
  152. package/server/services/email.js +204 -204
  153. package/server/services/hosted-runtime.js +205 -205
  154. package/server/services/lfd.js +635 -635
  155. package/server/services/local-ai.js +389 -389
  156. package/server/services/marketplace.js +270 -270
  157. package/server/services/metering.js +182 -182
  158. package/server/services/modules/affiliate-intelligence.js +93 -93
  159. package/server/services/modules/agent-firewall.js +90 -90
  160. package/server/services/modules/bounty.js +89 -89
  161. package/server/services/modules/collective-bargaining.js +92 -92
  162. package/server/services/modules/dark-pattern.js +66 -66
  163. package/server/services/modules/gov-intelligence.js +45 -45
  164. package/server/services/modules/neural.js +55 -55
  165. package/server/services/modules/notary.js +49 -49
  166. package/server/services/modules/price-time-machine.js +86 -86
  167. package/server/services/modules/protocol.js +104 -104
  168. package/server/services/negotiation.js +439 -439
  169. package/server/services/plugins.js +771 -771
  170. package/server/services/price-intelligence.js +566 -566
  171. package/server/services/price-shield.js +1137 -1137
  172. package/server/services/reputation.js +465 -465
  173. package/server/services/search-engine.js +357 -357
  174. package/server/services/security.js +513 -513
  175. package/server/services/self-healing.js +843 -843
  176. package/server/services/sovereign-shield.js +542 -0
  177. package/server/services/stripe.js +192 -192
  178. package/server/services/swarm.js +788 -788
  179. package/server/services/universal-scraper.js +662 -661
  180. package/server/services/verification.js +481 -481
  181. package/server/services/vision.js +1163 -1163
  182. package/server/utils/cache.js +125 -125
  183. package/server/utils/migrate.js +81 -81
  184. package/server/utils/safe-fetch.js +228 -0
  185. package/server/utils/secureFields.js +50 -50
  186. package/server/ws.js +161 -161
  187. package/templates/artisan-marketplace.yaml +104 -104
  188. package/templates/book-price-scout.yaml +98 -98
  189. package/templates/electronics-price-tracker.yaml +108 -108
  190. package/templates/flight-deal-hunter.yaml +113 -113
  191. package/templates/freelancer-direct.yaml +116 -116
  192. package/templates/grocery-price-compare.yaml +93 -93
  193. package/templates/hotel-direct-booking.yaml +113 -113
  194. package/templates/local-services.yaml +98 -98
  195. package/templates/olive-oil-tunisia.yaml +88 -88
  196. package/templates/organic-farm-fresh.yaml +101 -101
  197. package/templates/restaurant-direct.yaml +97 -97
  198. package/public/score.html +0 -263
  199. package/server/migrations/006_growth_suite.sql +0 -138
  200. package/server/routes/growth.js +0 -962
  201. package/server/services/fairness-engine.js +0 -409
  202. package/server/services/fairness.js +0 -420
@@ -1,575 +1,601 @@
1
- /**
2
- * Agent Learning Engine — Local Reinforcement Learning
3
- *
4
- * Agents learn from user decisions, building behavioral models locally
5
- * without sending data to external LLMs. The engine tracks:
6
- * - Decision patterns (what the user chooses and when)
7
- * - Reward signals (accepted/rejected/modified outcomes)
8
- * - Policy weights (which factors matter most to this user)
9
- * - Prediction accuracy over time
10
- *
11
- * Learning algorithms:
12
- * - Multi-armed bandit (UCB1) for exploration/exploitation
13
- * - Linear policy model with sigmoid activation and gradient descent
14
- * - Temporal discount for preference freshness (recent > old)
15
- * - Sequential pattern mining for behavior chains
16
- * - Confidence estimation: volume × accuracy × recency
17
- */
18
-
19
- const crypto = require('crypto');
20
- const { db } = require('../models/db');
21
-
22
- // ─── Schema ──────────────────────────────────────────────────────────
23
-
24
- db.exec(`
25
- CREATE TABLE IF NOT EXISTS learning_decisions (
26
- id TEXT PRIMARY KEY,
27
- site_id TEXT NOT NULL,
28
- agent_id TEXT NOT NULL,
29
- domain TEXT NOT NULL,
30
- action TEXT NOT NULL,
31
- context TEXT DEFAULT '{}',
32
- outcome TEXT DEFAULT 'pending',
33
- reward REAL DEFAULT 0.0,
34
- predicted_reward REAL,
35
- features TEXT DEFAULT '{}',
36
- created_at TEXT DEFAULT (datetime('now'))
37
- );
38
-
39
- CREATE TABLE IF NOT EXISTS learning_policies (
40
- id TEXT PRIMARY KEY,
41
- site_id TEXT NOT NULL,
42
- agent_id TEXT NOT NULL,
43
- domain TEXT NOT NULL,
44
- feature TEXT NOT NULL,
45
- weight REAL DEFAULT 0.0,
46
- update_count INTEGER DEFAULT 0,
47
- last_error REAL DEFAULT 0.0,
48
- created_at TEXT DEFAULT (datetime('now')),
49
- updated_at TEXT DEFAULT (datetime('now')),
50
- UNIQUE(site_id, agent_id, domain, feature)
51
- );
52
-
53
- CREATE TABLE IF NOT EXISTS learning_patterns (
54
- id TEXT PRIMARY KEY,
55
- site_id TEXT NOT NULL,
56
- agent_id TEXT NOT NULL,
57
- pattern_type TEXT NOT NULL,
58
- sequence TEXT NOT NULL,
59
- frequency INTEGER DEFAULT 1,
60
- confidence REAL DEFAULT 0.5,
61
- last_seen TEXT DEFAULT (datetime('now')),
62
- created_at TEXT DEFAULT (datetime('now'))
63
- );
64
-
65
- CREATE TABLE IF NOT EXISTS learning_bandit_arms (
66
- id TEXT PRIMARY KEY,
67
- site_id TEXT NOT NULL,
68
- agent_id TEXT NOT NULL,
69
- domain TEXT NOT NULL,
70
- action TEXT NOT NULL,
71
- pulls INTEGER DEFAULT 0,
72
- total_reward REAL DEFAULT 0.0,
73
- avg_reward REAL DEFAULT 0.0,
74
- ucb_score REAL DEFAULT 0.0,
75
- created_at TEXT DEFAULT (datetime('now')),
76
- updated_at TEXT DEFAULT (datetime('now')),
77
- UNIQUE(site_id, agent_id, domain, action)
78
- );
79
-
80
- CREATE TABLE IF NOT EXISTS learning_sessions (
81
- id TEXT PRIMARY KEY,
82
- site_id TEXT NOT NULL,
83
- agent_id TEXT NOT NULL,
84
- decisions_made INTEGER DEFAULT 0,
85
- correct_predictions INTEGER DEFAULT 0,
86
- accuracy REAL DEFAULT 0.0,
87
- started_at TEXT DEFAULT (datetime('now')),
88
- ended_at TEXT
89
- );
90
-
91
- CREATE INDEX IF NOT EXISTS idx_learn_dec_site ON learning_decisions(site_id, agent_id);
92
- CREATE INDEX IF NOT EXISTS idx_learn_dec_domain ON learning_decisions(domain);
93
- CREATE INDEX IF NOT EXISTS idx_learn_dec_outcome ON learning_decisions(outcome);
94
- CREATE INDEX IF NOT EXISTS idx_learn_pol_lookup ON learning_policies(site_id, agent_id, domain);
95
- CREATE INDEX IF NOT EXISTS idx_learn_pat_seq ON learning_patterns(site_id, agent_id, pattern_type);
96
- CREATE INDEX IF NOT EXISTS idx_learn_bandit ON learning_bandit_arms(site_id, agent_id, domain);
97
- `);
98
-
99
- // ─── Config ──────────────────────────────────────────────────────────
100
-
101
- const LEARNING_RATE = 0.1;
102
- const DISCOUNT_FACTOR = 0.95; // Temporal discount per decision step
103
- const DECAY_RATE = 0.01; // Recency decay per hour
104
- const UCB_EXPLORATION = 1.414; // √2 for UCB1
105
- const MIN_CONFIDENCE = 0.01;
106
- const MAX_SEQUENCE_LENGTH = 5;
107
-
108
- // ─── Prepared Statements ─────────────────────────────────────────────
109
-
110
- const stmts = {
111
- insertDecision: db.prepare('INSERT INTO learning_decisions (id, site_id, agent_id, domain, action, context, predicted_reward, features) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'),
112
- updateOutcome: db.prepare('UPDATE learning_decisions SET outcome = ?, reward = ? WHERE id = ?'),
113
- getDecision: db.prepare('SELECT * FROM learning_decisions WHERE id = ?'),
114
- getRecentDecisions: db.prepare('SELECT * FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY created_at DESC LIMIT ?'),
115
- getDecisionsByOutcome: db.prepare("SELECT * FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome = ? ORDER BY created_at DESC LIMIT ?"),
116
- getAllDomainDecisions: db.prepare('SELECT * FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY created_at DESC'),
117
- countDecisions: db.prepare('SELECT COUNT(*) as count FROM learning_decisions WHERE site_id = ? AND agent_id = ?'),
118
- getRecentRewards: db.prepare("SELECT reward, created_at FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome != 'pending' ORDER BY created_at DESC LIMIT ?"),
119
-
120
- upsertPolicy: db.prepare("INSERT INTO learning_policies (id, site_id, agent_id, domain, feature, weight) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(site_id, agent_id, domain, feature) DO UPDATE SET weight = ?, update_count = update_count + 1, last_error = ?, updated_at = datetime('now')"),
121
- getPolicies: db.prepare('SELECT * FROM learning_policies WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY ABS(weight) DESC'),
122
- getPolicy: db.prepare('SELECT * FROM learning_policies WHERE site_id = ? AND agent_id = ? AND domain = ? AND feature = ?'),
123
-
124
- insertPattern: db.prepare('INSERT INTO learning_patterns (id, site_id, agent_id, pattern_type, sequence, confidence) VALUES (?, ?, ?, ?, ?, ?)'),
125
- findPattern: db.prepare('SELECT * FROM learning_patterns WHERE site_id = ? AND agent_id = ? AND sequence = ?'),
126
- updatePattern: db.prepare("UPDATE learning_patterns SET frequency = frequency + 1, confidence = ?, last_seen = datetime('now') WHERE id = ?"),
127
- getTopPatterns: db.prepare('SELECT * FROM learning_patterns WHERE site_id = ? AND agent_id = ? AND pattern_type = ? ORDER BY frequency DESC, confidence DESC LIMIT ?'),
128
-
129
- upsertArm: db.prepare('INSERT INTO learning_bandit_arms (id, site_id, agent_id, domain, action) VALUES (?, ?, ?, ?, ?) ON CONFLICT(site_id, agent_id, domain, action) DO NOTHING'),
130
- getArms: db.prepare('SELECT * FROM learning_bandit_arms WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY ucb_score DESC'),
131
- getArm: db.prepare('SELECT * FROM learning_bandit_arms WHERE site_id = ? AND agent_id = ? AND domain = ? AND action = ?'),
132
- updateArm: db.prepare("UPDATE learning_bandit_arms SET pulls = pulls + 1, total_reward = total_reward + ?, avg_reward = ?, ucb_score = ?, updated_at = datetime('now') WHERE site_id = ? AND agent_id = ? AND domain = ? AND action = ?"),
133
-
134
- insertSession: db.prepare('INSERT INTO learning_sessions (id, site_id, agent_id) VALUES (?, ?, ?)'),
135
- updateSession: db.prepare("UPDATE learning_sessions SET decisions_made = ?, correct_predictions = ?, accuracy = ?, ended_at = datetime('now') WHERE id = ?"),
136
- getSessionHistory: db.prepare('SELECT * FROM learning_sessions WHERE site_id = ? AND agent_id = ? ORDER BY started_at DESC LIMIT ?'),
137
-
138
- getStats: db.prepare(`SELECT
139
- (SELECT COUNT(*) FROM learning_decisions WHERE site_id = ? AND agent_id = ?) as total_decisions,
140
- (SELECT COUNT(*) FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome = 'accepted') as accepted,
141
- (SELECT COUNT(*) FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome = 'rejected') as rejected,
142
- (SELECT AVG(reward) FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome != 'pending') as avg_reward,
143
- (SELECT COUNT(DISTINCT domain) FROM learning_policies WHERE site_id = ? AND agent_id = ?) as policy_domains,
144
- (SELECT COUNT(*) FROM learning_patterns WHERE site_id = ? AND agent_id = ?) as total_patterns`),
145
-
146
- deletePolicies: db.prepare('DELETE FROM learning_policies WHERE site_id = ? AND agent_id = ? AND domain = ?'),
147
- deletePatterns: db.prepare('DELETE FROM learning_patterns WHERE site_id = ? AND agent_id = ?'),
148
- deleteArms: db.prepare('DELETE FROM learning_bandit_arms WHERE site_id = ? AND agent_id = ? AND domain = ?'),
149
- deleteDecisions: db.prepare('DELETE FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND domain = ?'),
150
- };
151
-
152
- // ─── Core Learning API ───────────────────────────────────────────────
153
-
154
- /**
155
- * Record a decision the agent is about to make, with predicted reward.
156
- */
157
- function recordDecision(siteId, agentId, domain, action, context = {}, features = {}) {
158
- const id = crypto.randomUUID();
159
- const extractedFeatures = { ..._extractFeatures(context), ...features };
160
- const predictedReward = _predict(siteId, agentId, domain, extractedFeatures);
161
-
162
- stmts.insertDecision.run(id, siteId, agentId, domain, action,
163
- JSON.stringify(context), predictedReward, JSON.stringify(extractedFeatures));
164
-
165
- // Ensure bandit arm exists
166
- stmts.upsertArm.run(crypto.randomUUID(), siteId, agentId, domain, action);
167
-
168
- return { decisionId: id, predictedReward, confidence: _getConfidence(siteId, agentId, domain) };
169
- }
170
-
171
- /**
172
- * Provide feedback on a decision — the outcome and actual reward.
173
- * This is the core learning signal.
174
- */
175
- function feedback(decisionId, outcome, reward) {
176
- const decision = stmts.getDecision.get(decisionId);
177
- if (!decision) throw new Error('Decision not found');
178
-
179
- stmts.updateOutcome.run(outcome, reward, decisionId);
180
-
181
- const features = JSON.parse(decision.features || '{}');
182
- const predError = reward - (decision.predicted_reward || 0);
183
-
184
- // Update policy weights via gradient descent with temporal discount
185
- _updatePolicies(decision.site_id, decision.agent_id, decision.domain, features, predError);
186
-
187
- // Update bandit arm with actual reward
188
- _updateBanditArm(decision.site_id, decision.agent_id, decision.domain, decision.action, reward);
189
-
190
- // Mine patterns from recent decisions
191
- _minePatterns(decision.site_id, decision.agent_id, decision.domain);
192
-
193
- return {
194
- decisionId,
195
- predictionError: Math.round(predError * 1000) / 1000,
196
- updatedConfidence: _getConfidence(decision.site_id, decision.agent_id, decision.domain),
197
- accuracy: Math.round((1 - Math.abs(predError)) * 1000) / 1000,
198
- };
199
- }
200
-
201
- /**
202
- * Batch feedback — provide multiple outcomes at once.
203
- */
204
- function batchFeedback(feedbackList) {
205
- const results = [];
206
- const txn = db.transaction(() => {
207
- for (const fb of feedbackList) {
208
- try {
209
- results.push(feedback(fb.decisionId, fb.outcome, fb.reward));
210
- } catch (err) {
211
- results.push({ decisionId: fb.decisionId, error: err.message });
212
- }
213
- }
214
- });
215
- txn();
216
- return results;
217
- }
218
-
219
- /**
220
- * Get the best action for a domain using learned policies + bandit scores.
221
- * UCB scores are normalized to [0,1] before blending with policy prediction.
222
- */
223
- function recommend(siteId, agentId, domain, availableActions, context = {}) {
224
- const features = _extractFeatures(context);
225
-
226
- // Get all arms to find normalization bounds
227
- const allArms = stmts.getArms.all(siteId, agentId, domain);
228
- const armMap = {};
229
- for (const arm of allArms) armMap[arm.action] = arm;
230
-
231
- // Normalize UCB scores to [0,1]
232
- let minUCB = Infinity, maxUCB = -Infinity;
233
- for (const arm of allArms) {
234
- if (arm.pulls > 0) {
235
- if (arm.ucb_score < minUCB) minUCB = arm.ucb_score;
236
- if (arm.ucb_score > maxUCB) maxUCB = arm.ucb_score;
237
- }
238
- }
239
- const ucbRange = maxUCB - minUCB;
240
-
241
- const scored = availableActions.map((action) => {
242
- const arm = armMap[action] || _getOrCreateArm(siteId, agentId, domain, action);
243
- const policyScore = _predict(siteId, agentId, domain, { ...features, [`action:${action}`]: 1 });
244
-
245
- // Normalize bandit score to [0,1]
246
- let normalizedBandit;
247
- if (arm.pulls === 0) {
248
- normalizedBandit = 1.0; // unexplored arms get maximum exploration bonus
249
- } else if (ucbRange > 0) {
250
- normalizedBandit = (arm.ucb_score - minUCB) / ucbRange;
251
- } else {
252
- normalizedBandit = arm.avg_reward; // single arm use raw avg
253
- }
254
-
255
- // Blend: as confidence grows, lean more on policy, less on exploration
256
- const confidence = _getConfidence(siteId, agentId, domain);
257
- const policyWeight = 0.4 + confidence * 0.4; // [0.4, 0.8]
258
- const banditWeight = 1 - policyWeight; // [0.2, 0.6]
259
- const blended = policyWeight * policyScore + banditWeight * normalizedBandit;
260
-
261
- return {
262
- action,
263
- score: Math.round(blended * 1000) / 1000,
264
- policyScore: Math.round(policyScore * 1000) / 1000,
265
- banditScore: Math.round(normalizedBandit * 1000) / 1000,
266
- pulls: arm.pulls,
267
- avgReward: Math.round((arm.avg_reward || 0) * 1000) / 1000,
268
- };
269
- });
270
-
271
- scored.sort((a, b) => b.score - a.score);
272
-
273
- const confidence = _getConfidence(siteId, agentId, domain);
274
- const topPatterns = stmts.getTopPatterns.all(siteId, agentId, 'action_sequence', 5);
275
-
276
- return {
277
- recommended: scored[0]?.action || availableActions[0],
278
- rankings: scored,
279
- confidence,
280
- explorationLevel: confidence < 0.3 ? 'high' : confidence < 0.6 ? 'medium' : 'low',
281
- patterns: topPatterns.map((p) => ({
282
- sequence: p.sequence, frequency: p.frequency, confidence: p.confidence
283
- })),
284
- };
285
- }
286
-
287
- /**
288
- * Get learned preference summary for a domain.
289
- */
290
- function getPreferences(siteId, agentId, domain) {
291
- const policies = stmts.getPolicies.all(siteId, agentId, domain);
292
- const decisions = stmts.getRecentDecisions.all(siteId, agentId, domain, 50);
293
- const patterns = stmts.getTopPatterns.all(siteId, agentId, 'action_sequence', 10);
294
-
295
- const accepted = decisions.filter((d) => d.outcome === 'accepted');
296
- const rejected = decisions.filter((d) => d.outcome === 'rejected');
297
-
298
- // Build preference profile from weights
299
- const profile = {};
300
- for (const p of policies) {
301
- if (Math.abs(p.weight) > 0.05) {
302
- profile[p.feature] = {
303
- weight: Math.round(p.weight * 1000) / 1000,
304
- direction: p.weight > 0 ? 'preferred' : 'avoided',
305
- strength: Math.abs(p.weight) > 0.5 ? 'strong' : Math.abs(p.weight) > 0.2 ? 'moderate' : 'weak',
306
- updates: p.update_count,
307
- };
308
- }
309
- }
310
-
311
- // Compute action frequencies
312
- const actionFreqs = {};
313
- for (const d of decisions) {
314
- actionFreqs[d.action] = (actionFreqs[d.action] || 0) + 1;
315
- }
316
-
317
- return {
318
- domain,
319
- profile,
320
- acceptRate: decisions.length > 0 ? Math.round((accepted.length / decisions.length) * 1000) / 1000 : 0,
321
- rejectRate: decisions.length > 0 ? Math.round((rejected.length / decisions.length) * 1000) / 1000 : 0,
322
- totalDecisions: decisions.length,
323
- avgReward: decisions.length > 0
324
- ? Math.round((decisions.reduce((s, d) => s + d.reward, 0) / decisions.length) * 1000) / 1000
325
- : 0,
326
- topActions: Object.entries(actionFreqs)
327
- .sort(([, a], [, b]) => b - a)
328
- .slice(0, 5)
329
- .map(([action, count]) => ({ action, count, percentage: Math.round((count / decisions.length) * 100) })),
330
- topPatterns: patterns.map((p) => ({ sequence: p.sequence, frequency: p.frequency })),
331
- confidence: _getConfidence(siteId, agentId, domain),
332
- };
333
- }
334
-
335
- /**
336
- * Get reward history — recent rewards over time for charting.
337
- */
338
- function getRewardHistory(siteId, agentId, limit = 30) {
339
- return stmts.getRecentRewards.all(siteId, agentId, limit).reverse();
340
- }
341
-
342
- // ─── Learning Sessions ───────────────────────────────────────────────
343
-
344
- function startSession(siteId, agentId) {
345
- const id = crypto.randomUUID();
346
- stmts.insertSession.run(id, siteId, agentId);
347
- return { sessionId: id };
348
- }
349
-
350
- function endSession(sessionId, decisionsMade, correctPredictions) {
351
- const accuracy = decisionsMade > 0 ? correctPredictions / decisionsMade : 0;
352
- stmts.updateSession.run(decisionsMade, correctPredictions, accuracy, sessionId);
353
- return { accuracy: Math.round(accuracy * 1000) / 1000 };
354
- }
355
-
356
- // ─── Reset ───────────────────────────────────────────────────────────
357
-
358
- /**
359
- * Reset all learned data for a specific domain.
360
- */
361
- function resetDomain(siteId, agentId, domain) {
362
- const txn = db.transaction(() => {
363
- stmts.deletePolicies.run(siteId, agentId, domain);
364
- stmts.deleteArms.run(siteId, agentId, domain);
365
- stmts.deleteDecisions.run(siteId, agentId, domain);
366
- });
367
- txn();
368
- return { reset: true, domain };
369
- }
370
-
371
- /**
372
- * Reset all patterns for an agent.
373
- */
374
- function resetPatterns(siteId, agentId) {
375
- stmts.deletePatterns.run(siteId, agentId);
376
- return { reset: true };
377
- }
378
-
379
- // ─── Stats ───────────────────────────────────────────────────────────
380
-
381
- function getStats(siteId, agentId) {
382
- const row = stmts.getStats.get(siteId, agentId, siteId, agentId, siteId, agentId, siteId, agentId, siteId, agentId, siteId, agentId);
383
- const sessions = stmts.getSessionHistory.all(siteId, agentId, 10);
384
- const recentAccuracy = sessions.length > 0 ? sessions.reduce((s, sess) => s + sess.accuracy, 0) / sessions.length : 0;
385
- const rewardHistory = stmts.getRecentRewards.all(siteId, agentId, 30).reverse();
386
-
387
- return {
388
- ...row,
389
- avg_reward: row.avg_reward !== null ? Math.round(row.avg_reward * 1000) / 1000 : 0,
390
- recentAccuracy: Math.round(recentAccuracy * 1000) / 1000,
391
- sessionsCount: sessions.length,
392
- acceptRate: row.total_decisions > 0
393
- ? Math.round((row.accepted / row.total_decisions) * 1000) / 1000
394
- : 0,
395
- rewardHistory,
396
- };
397
- }
398
-
399
- // ─── Internal: Prediction via Linear Model ───────────────────────────
400
-
401
- function _predict(siteId, agentId, domain, features) {
402
- const policies = stmts.getPolicies.all(siteId, agentId, domain);
403
- if (policies.length === 0) return 0.5; // No data yet — neutral prediction
404
-
405
- let score = 0;
406
- let matchedFeatures = 0;
407
- for (const p of policies) {
408
- const featureVal = features[p.feature];
409
- if (featureVal !== undefined) {
410
- const fv = typeof featureVal === 'number' ? featureVal : (featureVal ? 1 : 0);
411
-
412
- // Apply temporal discount: older policies (fewer recent updates) matter less
413
- const recencyBoost = p.update_count > 0 ? Math.pow(DISCOUNT_FACTOR, Math.max(0, 10 - p.update_count)) : 1;
414
- score += p.weight * fv * recencyBoost;
415
- matchedFeatures++;
416
- }
417
- }
418
-
419
- // Sigmoid squash to [0, 1]
420
- return 1 / (1 + Math.exp(-score));
421
- }
422
-
423
- function _updatePolicies(siteId, agentId, domain, features, error) {
424
- for (const [feature, value] of Object.entries(features)) {
425
- const fv = typeof value === 'number' ? value : (value ? 1 : 0);
426
- if (fv === 0) continue; // Skip zero-valued features
427
-
428
- const gradient = error * fv * LEARNING_RATE;
429
- const existing = stmts.getPolicy.get(siteId, agentId, domain, feature);
430
-
431
- // Apply weight decay to prevent unbounded growth
432
- const currentWeight = existing ? existing.weight * DISCOUNT_FACTOR : 0;
433
- const newWeight = currentWeight + gradient;
434
-
435
- // Clamp weights to [-5, 5] to prevent extreme values
436
- const clampedWeight = Math.max(-5, Math.min(5, newWeight));
437
-
438
- stmts.upsertPolicy.run(
439
- crypto.randomUUID(), siteId, agentId, domain, feature, clampedWeight,
440
- clampedWeight, Math.abs(error)
441
- );
442
- }
443
- }
444
-
445
- // ─── Internal: Multi-Armed Bandit ────────────────────────────────────
446
-
447
- function _getOrCreateArm(siteId, agentId, domain, action) {
448
- stmts.upsertArm.run(crypto.randomUUID(), siteId, agentId, domain, action);
449
- const arm = stmts.getArm.get(siteId, agentId, domain, action);
450
- return arm || { pulls: 0, ucb_score: 0, avg_reward: 0, total_reward: 0 };
451
- }
452
-
453
- function _updateBanditArm(siteId, agentId, domain, action, reward) {
454
- const arm = stmts.getArm.get(siteId, agentId, domain, action);
455
- if (!arm) {
456
- stmts.upsertArm.run(crypto.randomUUID(), siteId, agentId, domain, action);
457
- return;
458
- }
459
-
460
- const newPulls = arm.pulls + 1;
461
- const newTotalReward = arm.total_reward + reward;
462
- const newAvgReward = newTotalReward / newPulls;
463
-
464
- // UCB1: avg_reward + C * sqrt(ln(N) / n_i)
465
- // We need total pulls across all arms in this domain
466
- const arms = stmts.getArms.all(siteId, agentId, domain);
467
- const totalPulls = arms.reduce((s, a) => s + a.pulls, 0) + 1; // +1 for this pull
468
-
469
- const exploration = UCB_EXPLORATION * Math.sqrt(Math.log(totalPulls) / newPulls);
470
- const ucbScore = newAvgReward + exploration;
471
-
472
- stmts.updateArm.run(reward, newAvgReward, ucbScore, siteId, agentId, domain, action);
473
- }
474
-
475
- // ─── Internal: Pattern Mining ────────────────────────────────────────
476
-
477
- function _minePatterns(siteId, agentId, domain) {
478
- const decisions = stmts.getRecentDecisions.all(siteId, agentId, domain, 20);
479
- if (decisions.length < 3) return;
480
-
481
- // Extract action sequences of length 2-5
482
- for (let len = 2; len <= Math.min(MAX_SEQUENCE_LENGTH, decisions.length); len++) {
483
- const sequence = decisions.slice(0, len).map((d) => d.action).reverse().join(' → ');
484
- const existing = stmts.findPattern.get(siteId, agentId, sequence);
485
-
486
- if (existing) {
487
- // Asymptotic approach to 1.0 confidence grows slower as it increases
488
- const newConf = Math.min(0.99, existing.confidence + 0.05 * (1 - existing.confidence));
489
- stmts.updatePattern.run(newConf, existing.id);
490
- } else {
491
- stmts.insertPattern.run(crypto.randomUUID(), siteId, agentId, 'action_sequence', sequence, 0.3);
492
- }
493
- }
494
- }
495
-
496
- // ─── Internal: Feature Extraction ────────────────────────────────────
497
-
498
- function _extractFeatures(context) {
499
- const features = {};
500
-
501
- if (context.price !== undefined) {
502
- features.price = context.price;
503
- // Bucketize price for discrete learning
504
- if (context.price < 10) features['price_bucket:cheap'] = 1;
505
- else if (context.price < 50) features['price_bucket:moderate'] = 1;
506
- else if (context.price < 200) features['price_bucket:premium'] = 1;
507
- else features['price_bucket:luxury'] = 1;
508
- }
509
- if (context.quantity !== undefined) features.quantity = context.quantity;
510
- if (context.discount !== undefined) {
511
- features.discount = context.discount;
512
- features.has_discount = context.discount > 0 ? 1 : 0;
513
- }
514
- if (context.rating !== undefined) {
515
- features.rating = context.rating;
516
- features.high_rated = context.rating >= 4.0 ? 1 : 0;
517
- }
518
- if (context.category) features[`category:${context.category}`] = 1;
519
- if (context.brand) features[`brand:${context.brand}`] = 1;
520
- if (context.timeOfDay !== undefined) {
521
- features.morning = context.timeOfDay < 12 ? 1 : 0;
522
- features.afternoon = context.timeOfDay >= 12 && context.timeOfDay < 18 ? 1 : 0;
523
- features.evening = context.timeOfDay >= 18 ? 1 : 0;
524
- }
525
- if (context.isRepeat !== undefined) features.repeat_visit = context.isRepeat ? 1 : 0;
526
- if (context.urgency !== undefined) features.urgency = context.urgency;
527
- if (context.inStock !== undefined) features.in_stock = context.inStock ? 1 : 0;
528
-
529
- // Pass through any raw numeric features
530
- for (const [k, v] of Object.entries(context)) {
531
- if (features[k] === undefined && typeof v === 'number') {
532
- features[k] = v;
533
- }
534
- }
535
-
536
- return features;
537
- }
538
-
539
- // ─── Internal: Confidence Estimation ─────────────────────────────────
540
-
541
- function _getConfidence(siteId, agentId, domain) {
542
- const decisions = stmts.getRecentDecisions.all(siteId, agentId, domain, 50);
543
- if (decisions.length === 0) return 0;
544
-
545
- const withOutcome = decisions.filter((d) => d.outcome !== 'pending');
546
- if (withOutcome.length === 0) return MIN_CONFIDENCE;
547
-
548
- // Volume component: log scale, saturates around 30 decisions
549
- const volumeConf = Math.min(1, withOutcome.length / 30);
550
-
551
- // Accuracy component: how close predictions were to actual rewards
552
- let accuracySum = 0;
553
- for (const d of withOutcome) {
554
- if (d.predicted_reward !== null) {
555
- const error = Math.abs(d.reward - d.predicted_reward);
556
- accuracySum += Math.max(0, 1 - error);
557
- }
558
- }
559
- const accuracyConf = withOutcome.length > 0 ? accuracySum / withOutcome.length : 0.5;
560
-
561
- // Recency component: exponential decay based on age of newest data
562
- const latestTs = new Date(withOutcome[0].created_at).getTime();
563
- const ageHours = (Date.now() - latestTs) / 3600000;
564
- const recencyConf = Math.exp(-DECAY_RATE * ageHours);
565
-
566
- return Math.max(MIN_CONFIDENCE, Math.min(0.99,
567
- volumeConf * 0.3 + accuracyConf * 0.5 + recencyConf * 0.2
568
- ));
569
- }
570
-
571
- module.exports = {
572
- recordDecision, feedback, batchFeedback, recommend, getPreferences,
573
- getRewardHistory, startSession, endSession,
574
- resetDomain, resetPatterns, getStats,
575
- };
1
+ /**
2
+ * Agent Learning Engine — Local Reinforcement Learning
3
+ *
4
+ * Agents learn from user decisions, building behavioral models locally
5
+ * without sending data to external LLMs. The engine tracks:
6
+ * - Decision patterns (what the user chooses and when)
7
+ * - Reward signals (accepted/rejected/modified outcomes)
8
+ * - Policy weights (which factors matter most to this user)
9
+ * - Prediction accuracy over time
10
+ *
11
+ * Learning algorithms:
12
+ * - Multi-armed bandit (UCB1) for exploration/exploitation
13
+ * - Linear policy model with sigmoid activation and gradient descent
14
+ * - Temporal discount for preference freshness (recent > old)
15
+ * - Sequential pattern mining for behavior chains
16
+ * - Confidence estimation: volume × accuracy × recency
17
+ */
18
+
19
+ const crypto = require('crypto');
20
+ const { db } = require('../models/db');
21
+ let rewardGuard;
22
+ try { rewardGuard = require('../security/reward-guard'); } catch { rewardGuard = null; }
23
+
24
+ // ─── Schema ──────────────────────────────────────────────────────────
25
+
26
+ db.exec(`
27
+ CREATE TABLE IF NOT EXISTS learning_decisions (
28
+ id TEXT PRIMARY KEY,
29
+ site_id TEXT NOT NULL,
30
+ agent_id TEXT NOT NULL,
31
+ domain TEXT NOT NULL,
32
+ action TEXT NOT NULL,
33
+ context TEXT DEFAULT '{}',
34
+ outcome TEXT DEFAULT 'pending',
35
+ reward REAL DEFAULT 0.0,
36
+ predicted_reward REAL,
37
+ features TEXT DEFAULT '{}',
38
+ created_at TEXT DEFAULT (datetime('now'))
39
+ );
40
+
41
+ CREATE TABLE IF NOT EXISTS learning_policies (
42
+ id TEXT PRIMARY KEY,
43
+ site_id TEXT NOT NULL,
44
+ agent_id TEXT NOT NULL,
45
+ domain TEXT NOT NULL,
46
+ feature TEXT NOT NULL,
47
+ weight REAL DEFAULT 0.0,
48
+ update_count INTEGER DEFAULT 0,
49
+ last_error REAL DEFAULT 0.0,
50
+ created_at TEXT DEFAULT (datetime('now')),
51
+ updated_at TEXT DEFAULT (datetime('now')),
52
+ UNIQUE(site_id, agent_id, domain, feature)
53
+ );
54
+
55
+ CREATE TABLE IF NOT EXISTS learning_patterns (
56
+ id TEXT PRIMARY KEY,
57
+ site_id TEXT NOT NULL,
58
+ agent_id TEXT NOT NULL,
59
+ pattern_type TEXT NOT NULL,
60
+ sequence TEXT NOT NULL,
61
+ frequency INTEGER DEFAULT 1,
62
+ confidence REAL DEFAULT 0.5,
63
+ last_seen TEXT DEFAULT (datetime('now')),
64
+ created_at TEXT DEFAULT (datetime('now'))
65
+ );
66
+
67
+ CREATE TABLE IF NOT EXISTS learning_bandit_arms (
68
+ id TEXT PRIMARY KEY,
69
+ site_id TEXT NOT NULL,
70
+ agent_id TEXT NOT NULL,
71
+ domain TEXT NOT NULL,
72
+ action TEXT NOT NULL,
73
+ pulls INTEGER DEFAULT 0,
74
+ total_reward REAL DEFAULT 0.0,
75
+ avg_reward REAL DEFAULT 0.0,
76
+ ucb_score REAL DEFAULT 0.0,
77
+ created_at TEXT DEFAULT (datetime('now')),
78
+ updated_at TEXT DEFAULT (datetime('now')),
79
+ UNIQUE(site_id, agent_id, domain, action)
80
+ );
81
+
82
+ CREATE TABLE IF NOT EXISTS learning_sessions (
83
+ id TEXT PRIMARY KEY,
84
+ site_id TEXT NOT NULL,
85
+ agent_id TEXT NOT NULL,
86
+ decisions_made INTEGER DEFAULT 0,
87
+ correct_predictions INTEGER DEFAULT 0,
88
+ accuracy REAL DEFAULT 0.0,
89
+ started_at TEXT DEFAULT (datetime('now')),
90
+ ended_at TEXT
91
+ );
92
+
93
+ CREATE INDEX IF NOT EXISTS idx_learn_dec_site ON learning_decisions(site_id, agent_id);
94
+ CREATE INDEX IF NOT EXISTS idx_learn_dec_domain ON learning_decisions(domain);
95
+ CREATE INDEX IF NOT EXISTS idx_learn_dec_outcome ON learning_decisions(outcome);
96
+ CREATE INDEX IF NOT EXISTS idx_learn_pol_lookup ON learning_policies(site_id, agent_id, domain);
97
+ CREATE INDEX IF NOT EXISTS idx_learn_pat_seq ON learning_patterns(site_id, agent_id, pattern_type);
98
+ CREATE INDEX IF NOT EXISTS idx_learn_bandit ON learning_bandit_arms(site_id, agent_id, domain);
99
+ `);
100
+
101
+ // ─── Config ──────────────────────────────────────────────────────────
102
+
103
+ const LEARNING_RATE = 0.1;
104
+ const DISCOUNT_FACTOR = 0.95; // Temporal discount per decision step
105
+ const DECAY_RATE = 0.01; // Recency decay per hour
106
+ const UCB_EXPLORATION = 1.414; // √2 for UCB1
107
+ const MIN_CONFIDENCE = 0.01;
108
+ const MAX_SEQUENCE_LENGTH = 5;
109
+
110
+ // ─── Prepared Statements ─────────────────────────────────────────────
111
+
112
+ const stmts = {
113
+ insertDecision: db.prepare('INSERT INTO learning_decisions (id, site_id, agent_id, domain, action, context, predicted_reward, features) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'),
114
+ updateOutcome: db.prepare('UPDATE learning_decisions SET outcome = ?, reward = ? WHERE id = ?'),
115
+ getDecision: db.prepare('SELECT * FROM learning_decisions WHERE id = ?'),
116
+ getRecentDecisions: db.prepare('SELECT * FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY created_at DESC LIMIT ?'),
117
+ getDecisionsByOutcome: db.prepare("SELECT * FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome = ? ORDER BY created_at DESC LIMIT ?"),
118
+ getAllDomainDecisions: db.prepare('SELECT * FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY created_at DESC'),
119
+ countDecisions: db.prepare('SELECT COUNT(*) as count FROM learning_decisions WHERE site_id = ? AND agent_id = ?'),
120
+ getRecentRewards: db.prepare("SELECT reward, created_at FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome != 'pending' ORDER BY created_at DESC LIMIT ?"),
121
+
122
+ upsertPolicy: db.prepare("INSERT INTO learning_policies (id, site_id, agent_id, domain, feature, weight) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(site_id, agent_id, domain, feature) DO UPDATE SET weight = ?, update_count = update_count + 1, last_error = ?, updated_at = datetime('now')"),
123
+ getPolicies: db.prepare('SELECT * FROM learning_policies WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY ABS(weight) DESC'),
124
+ getPolicy: db.prepare('SELECT * FROM learning_policies WHERE site_id = ? AND agent_id = ? AND domain = ? AND feature = ?'),
125
+
126
+ insertPattern: db.prepare('INSERT INTO learning_patterns (id, site_id, agent_id, pattern_type, sequence, confidence) VALUES (?, ?, ?, ?, ?, ?)'),
127
+ findPattern: db.prepare('SELECT * FROM learning_patterns WHERE site_id = ? AND agent_id = ? AND sequence = ?'),
128
+ updatePattern: db.prepare("UPDATE learning_patterns SET frequency = frequency + 1, confidence = ?, last_seen = datetime('now') WHERE id = ?"),
129
+ getTopPatterns: db.prepare('SELECT * FROM learning_patterns WHERE site_id = ? AND agent_id = ? AND pattern_type = ? ORDER BY frequency DESC, confidence DESC LIMIT ?'),
130
+
131
+ upsertArm: db.prepare('INSERT INTO learning_bandit_arms (id, site_id, agent_id, domain, action) VALUES (?, ?, ?, ?, ?) ON CONFLICT(site_id, agent_id, domain, action) DO NOTHING'),
132
+ getArms: db.prepare('SELECT * FROM learning_bandit_arms WHERE site_id = ? AND agent_id = ? AND domain = ? ORDER BY ucb_score DESC'),
133
+ getArm: db.prepare('SELECT * FROM learning_bandit_arms WHERE site_id = ? AND agent_id = ? AND domain = ? AND action = ?'),
134
+ updateArm: db.prepare("UPDATE learning_bandit_arms SET pulls = pulls + 1, total_reward = total_reward + ?, avg_reward = ?, ucb_score = ?, updated_at = datetime('now') WHERE site_id = ? AND agent_id = ? AND domain = ? AND action = ?"),
135
+
136
+ insertSession: db.prepare('INSERT INTO learning_sessions (id, site_id, agent_id) VALUES (?, ?, ?)'),
137
+ updateSession: db.prepare("UPDATE learning_sessions SET decisions_made = ?, correct_predictions = ?, accuracy = ?, ended_at = datetime('now') WHERE id = ?"),
138
+ getSessionHistory: db.prepare('SELECT * FROM learning_sessions WHERE site_id = ? AND agent_id = ? ORDER BY started_at DESC LIMIT ?'),
139
+
140
+ getStats: db.prepare(`SELECT
141
+ (SELECT COUNT(*) FROM learning_decisions WHERE site_id = ? AND agent_id = ?) as total_decisions,
142
+ (SELECT COUNT(*) FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome = 'accepted') as accepted,
143
+ (SELECT COUNT(*) FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome = 'rejected') as rejected,
144
+ (SELECT AVG(reward) FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND outcome != 'pending') as avg_reward,
145
+ (SELECT COUNT(DISTINCT domain) FROM learning_policies WHERE site_id = ? AND agent_id = ?) as policy_domains,
146
+ (SELECT COUNT(*) FROM learning_patterns WHERE site_id = ? AND agent_id = ?) as total_patterns`),
147
+
148
+ deletePolicies: db.prepare('DELETE FROM learning_policies WHERE site_id = ? AND agent_id = ? AND domain = ?'),
149
+ deletePatterns: db.prepare('DELETE FROM learning_patterns WHERE site_id = ? AND agent_id = ?'),
150
+ deleteArms: db.prepare('DELETE FROM learning_bandit_arms WHERE site_id = ? AND agent_id = ? AND domain = ?'),
151
+ deleteDecisions: db.prepare('DELETE FROM learning_decisions WHERE site_id = ? AND agent_id = ? AND domain = ?'),
152
+ };
153
+
154
+ // ─── Core Learning API ───────────────────────────────────────────────
155
+
156
+ /**
157
+ * Record a decision the agent is about to make, with predicted reward.
158
+ */
159
+ function recordDecision(siteId, agentId, domain, action, context = {}, features = {}) {
160
+ const id = crypto.randomUUID();
161
+ const extractedFeatures = { ..._extractFeatures(context), ...features };
162
+ const predictedReward = _predict(siteId, agentId, domain, extractedFeatures);
163
+
164
+ stmts.insertDecision.run(id, siteId, agentId, domain, action,
165
+ JSON.stringify(context), predictedReward, JSON.stringify(extractedFeatures));
166
+
167
+ // Ensure bandit arm exists
168
+ stmts.upsertArm.run(crypto.randomUUID(), siteId, agentId, domain, action);
169
+
170
+ return { decisionId: id, predictedReward, confidence: _getConfidence(siteId, agentId, domain) };
171
+ }
172
+
173
+ /**
174
+ * Provide feedback on a decision — the outcome and actual reward.
175
+ * This is the core learning signal.
176
+ */
177
+ function feedback(decisionId, outcome, reward, opts = {}) {
178
+ const decision = stmts.getDecision.get(decisionId);
179
+ if (!decision) throw new Error('Decision not found');
180
+
181
+ // ── Reward guard: clamp / block / flag malicious or anomalous rewards ──
182
+ let safeReward = reward;
183
+ let guardDecision = 'accepted';
184
+ if (rewardGuard) {
185
+ const sanitized = rewardGuard.sanitizeReward({
186
+ siteId: decision.site_id,
187
+ agentId: decision.agent_id,
188
+ domain: decision.domain,
189
+ action: decision.action,
190
+ reward,
191
+ actorId: opts.actorId,
192
+ approvedBy: opts.approvedBy,
193
+ });
194
+ safeReward = sanitized.reward;
195
+ guardDecision = sanitized.decision;
196
+ if (guardDecision === 'blocked') {
197
+ // Don't propagate to policy / bandit.
198
+ stmts.updateOutcome.run(outcome, safeReward, decisionId);
199
+ return { decisionId, blocked: true, reason: sanitized.reason, guardDecision };
200
+ }
201
+ }
202
+
203
+ stmts.updateOutcome.run(outcome, safeReward, decisionId);
204
+
205
+ const features = JSON.parse(decision.features || '{}');
206
+ const predError = safeReward - (decision.predicted_reward || 0);
207
+
208
+ // Update policy weights via gradient descent with temporal discount
209
+ _updatePolicies(decision.site_id, decision.agent_id, decision.domain, features, predError);
210
+
211
+ // Update bandit arm with actual reward
212
+ _updateBanditArm(decision.site_id, decision.agent_id, decision.domain, decision.action, safeReward);
213
+
214
+ // Mine patterns from recent decisions
215
+ _minePatterns(decision.site_id, decision.agent_id, decision.domain);
216
+
217
+ return {
218
+ decisionId,
219
+ predictionError: Math.round(predError * 1000) / 1000,
220
+ updatedConfidence: _getConfidence(decision.site_id, decision.agent_id, decision.domain),
221
+ accuracy: Math.round((1 - Math.abs(predError)) * 1000) / 1000,
222
+ guardDecision,
223
+ appliedReward: safeReward,
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Batch feedback — provide multiple outcomes at once.
229
+ */
230
+ function batchFeedback(feedbackList) {
231
+ const results = [];
232
+ const txn = db.transaction(() => {
233
+ for (const fb of feedbackList) {
234
+ try {
235
+ results.push(feedback(fb.decisionId, fb.outcome, fb.reward));
236
+ } catch (err) {
237
+ results.push({ decisionId: fb.decisionId, error: err.message });
238
+ }
239
+ }
240
+ });
241
+ txn();
242
+ return results;
243
+ }
244
+
245
+ /**
246
+ * Get the best action for a domain using learned policies + bandit scores.
247
+ * UCB scores are normalized to [0,1] before blending with policy prediction.
248
+ */
249
+ function recommend(siteId, agentId, domain, availableActions, context = {}) {
250
+ const features = _extractFeatures(context);
251
+
252
+ // Get all arms to find normalization bounds
253
+ const allArms = stmts.getArms.all(siteId, agentId, domain);
254
+ const armMap = {};
255
+ for (const arm of allArms) armMap[arm.action] = arm;
256
+
257
+ // Normalize UCB scores to [0,1]
258
+ let minUCB = Infinity, maxUCB = -Infinity;
259
+ for (const arm of allArms) {
260
+ if (arm.pulls > 0) {
261
+ if (arm.ucb_score < minUCB) minUCB = arm.ucb_score;
262
+ if (arm.ucb_score > maxUCB) maxUCB = arm.ucb_score;
263
+ }
264
+ }
265
+ const ucbRange = maxUCB - minUCB;
266
+
267
+ const scored = availableActions.map((action) => {
268
+ const arm = armMap[action] || _getOrCreateArm(siteId, agentId, domain, action);
269
+ const policyScore = _predict(siteId, agentId, domain, { ...features, [`action:${action}`]: 1 });
270
+
271
+ // Normalize bandit score to [0,1]
272
+ let normalizedBandit;
273
+ if (arm.pulls === 0) {
274
+ normalizedBandit = 1.0; // unexplored arms get maximum exploration bonus
275
+ } else if (ucbRange > 0) {
276
+ normalizedBandit = (arm.ucb_score - minUCB) / ucbRange;
277
+ } else {
278
+ normalizedBandit = arm.avg_reward; // single arm — use raw avg
279
+ }
280
+
281
+ // Blend: as confidence grows, lean more on policy, less on exploration
282
+ const confidence = _getConfidence(siteId, agentId, domain);
283
+ const policyWeight = 0.4 + confidence * 0.4; // [0.4, 0.8]
284
+ const banditWeight = 1 - policyWeight; // [0.2, 0.6]
285
+ const blended = policyWeight * policyScore + banditWeight * normalizedBandit;
286
+
287
+ return {
288
+ action,
289
+ score: Math.round(blended * 1000) / 1000,
290
+ policyScore: Math.round(policyScore * 1000) / 1000,
291
+ banditScore: Math.round(normalizedBandit * 1000) / 1000,
292
+ pulls: arm.pulls,
293
+ avgReward: Math.round((arm.avg_reward || 0) * 1000) / 1000,
294
+ };
295
+ });
296
+
297
+ scored.sort((a, b) => b.score - a.score);
298
+
299
+ const confidence = _getConfidence(siteId, agentId, domain);
300
+ const topPatterns = stmts.getTopPatterns.all(siteId, agentId, 'action_sequence', 5);
301
+
302
+ return {
303
+ recommended: scored[0]?.action || availableActions[0],
304
+ rankings: scored,
305
+ confidence,
306
+ explorationLevel: confidence < 0.3 ? 'high' : confidence < 0.6 ? 'medium' : 'low',
307
+ patterns: topPatterns.map((p) => ({
308
+ sequence: p.sequence, frequency: p.frequency, confidence: p.confidence
309
+ })),
310
+ };
311
+ }
312
+
313
+ /**
314
+ * Get learned preference summary for a domain.
315
+ */
316
+ function getPreferences(siteId, agentId, domain) {
317
+ const policies = stmts.getPolicies.all(siteId, agentId, domain);
318
+ const decisions = stmts.getRecentDecisions.all(siteId, agentId, domain, 50);
319
+ const patterns = stmts.getTopPatterns.all(siteId, agentId, 'action_sequence', 10);
320
+
321
+ const accepted = decisions.filter((d) => d.outcome === 'accepted');
322
+ const rejected = decisions.filter((d) => d.outcome === 'rejected');
323
+
324
+ // Build preference profile from weights
325
+ const profile = {};
326
+ for (const p of policies) {
327
+ if (Math.abs(p.weight) > 0.05) {
328
+ profile[p.feature] = {
329
+ weight: Math.round(p.weight * 1000) / 1000,
330
+ direction: p.weight > 0 ? 'preferred' : 'avoided',
331
+ strength: Math.abs(p.weight) > 0.5 ? 'strong' : Math.abs(p.weight) > 0.2 ? 'moderate' : 'weak',
332
+ updates: p.update_count,
333
+ };
334
+ }
335
+ }
336
+
337
+ // Compute action frequencies
338
+ const actionFreqs = {};
339
+ for (const d of decisions) {
340
+ actionFreqs[d.action] = (actionFreqs[d.action] || 0) + 1;
341
+ }
342
+
343
+ return {
344
+ domain,
345
+ profile,
346
+ acceptRate: decisions.length > 0 ? Math.round((accepted.length / decisions.length) * 1000) / 1000 : 0,
347
+ rejectRate: decisions.length > 0 ? Math.round((rejected.length / decisions.length) * 1000) / 1000 : 0,
348
+ totalDecisions: decisions.length,
349
+ avgReward: decisions.length > 0
350
+ ? Math.round((decisions.reduce((s, d) => s + d.reward, 0) / decisions.length) * 1000) / 1000
351
+ : 0,
352
+ topActions: Object.entries(actionFreqs)
353
+ .sort(([, a], [, b]) => b - a)
354
+ .slice(0, 5)
355
+ .map(([action, count]) => ({ action, count, percentage: Math.round((count / decisions.length) * 100) })),
356
+ topPatterns: patterns.map((p) => ({ sequence: p.sequence, frequency: p.frequency })),
357
+ confidence: _getConfidence(siteId, agentId, domain),
358
+ };
359
+ }
360
+
361
+ /**
362
+ * Get reward history — recent rewards over time for charting.
363
+ */
364
+ function getRewardHistory(siteId, agentId, limit = 30) {
365
+ return stmts.getRecentRewards.all(siteId, agentId, limit).reverse();
366
+ }
367
+
368
+ // ─── Learning Sessions ───────────────────────────────────────────────
369
+
370
+ function startSession(siteId, agentId) {
371
+ const id = crypto.randomUUID();
372
+ stmts.insertSession.run(id, siteId, agentId);
373
+ return { sessionId: id };
374
+ }
375
+
376
+ function endSession(sessionId, decisionsMade, correctPredictions) {
377
+ const accuracy = decisionsMade > 0 ? correctPredictions / decisionsMade : 0;
378
+ stmts.updateSession.run(decisionsMade, correctPredictions, accuracy, sessionId);
379
+ return { accuracy: Math.round(accuracy * 1000) / 1000 };
380
+ }
381
+
382
+ // ─── Reset ───────────────────────────────────────────────────────────
383
+
384
+ /**
385
+ * Reset all learned data for a specific domain.
386
+ */
387
+ function resetDomain(siteId, agentId, domain) {
388
+ const txn = db.transaction(() => {
389
+ stmts.deletePolicies.run(siteId, agentId, domain);
390
+ stmts.deleteArms.run(siteId, agentId, domain);
391
+ stmts.deleteDecisions.run(siteId, agentId, domain);
392
+ });
393
+ txn();
394
+ return { reset: true, domain };
395
+ }
396
+
397
+ /**
398
+ * Reset all patterns for an agent.
399
+ */
400
+ function resetPatterns(siteId, agentId) {
401
+ stmts.deletePatterns.run(siteId, agentId);
402
+ return { reset: true };
403
+ }
404
+
405
+ // ─── Stats ───────────────────────────────────────────────────────────
406
+
407
+ function getStats(siteId, agentId) {
408
+ const row = stmts.getStats.get(siteId, agentId, siteId, agentId, siteId, agentId, siteId, agentId, siteId, agentId, siteId, agentId);
409
+ const sessions = stmts.getSessionHistory.all(siteId, agentId, 10);
410
+ const recentAccuracy = sessions.length > 0 ? sessions.reduce((s, sess) => s + sess.accuracy, 0) / sessions.length : 0;
411
+ const rewardHistory = stmts.getRecentRewards.all(siteId, agentId, 30).reverse();
412
+
413
+ return {
414
+ ...row,
415
+ avg_reward: row.avg_reward !== null ? Math.round(row.avg_reward * 1000) / 1000 : 0,
416
+ recentAccuracy: Math.round(recentAccuracy * 1000) / 1000,
417
+ sessionsCount: sessions.length,
418
+ acceptRate: row.total_decisions > 0
419
+ ? Math.round((row.accepted / row.total_decisions) * 1000) / 1000
420
+ : 0,
421
+ rewardHistory,
422
+ };
423
+ }
424
+
425
+ // ─── Internal: Prediction via Linear Model ───────────────────────────
426
+
427
+ function _predict(siteId, agentId, domain, features) {
428
+ const policies = stmts.getPolicies.all(siteId, agentId, domain);
429
+ if (policies.length === 0) return 0.5; // No data yet — neutral prediction
430
+
431
+ let score = 0;
432
+ let matchedFeatures = 0;
433
+ for (const p of policies) {
434
+ const featureVal = features[p.feature];
435
+ if (featureVal !== undefined) {
436
+ const fv = typeof featureVal === 'number' ? featureVal : (featureVal ? 1 : 0);
437
+
438
+ // Apply temporal discount: older policies (fewer recent updates) matter less
439
+ const recencyBoost = p.update_count > 0 ? Math.pow(DISCOUNT_FACTOR, Math.max(0, 10 - p.update_count)) : 1;
440
+ score += p.weight * fv * recencyBoost;
441
+ matchedFeatures++;
442
+ }
443
+ }
444
+
445
+ // Sigmoid squash to [0, 1]
446
+ return 1 / (1 + Math.exp(-score));
447
+ }
448
+
449
+ function _updatePolicies(siteId, agentId, domain, features, error) {
450
+ for (const [feature, value] of Object.entries(features)) {
451
+ const fv = typeof value === 'number' ? value : (value ? 1 : 0);
452
+ if (fv === 0) continue; // Skip zero-valued features
453
+
454
+ const gradient = error * fv * LEARNING_RATE;
455
+ const existing = stmts.getPolicy.get(siteId, agentId, domain, feature);
456
+
457
+ // Apply weight decay to prevent unbounded growth
458
+ const currentWeight = existing ? existing.weight * DISCOUNT_FACTOR : 0;
459
+ const newWeight = currentWeight + gradient;
460
+
461
+ // Clamp weights to [-5, 5] to prevent extreme values
462
+ const clampedWeight = Math.max(-5, Math.min(5, newWeight));
463
+
464
+ stmts.upsertPolicy.run(
465
+ crypto.randomUUID(), siteId, agentId, domain, feature, clampedWeight,
466
+ clampedWeight, Math.abs(error)
467
+ );
468
+ }
469
+ }
470
+
471
+ // ─── Internal: Multi-Armed Bandit ────────────────────────────────────
472
+
473
+ function _getOrCreateArm(siteId, agentId, domain, action) {
474
+ stmts.upsertArm.run(crypto.randomUUID(), siteId, agentId, domain, action);
475
+ const arm = stmts.getArm.get(siteId, agentId, domain, action);
476
+ return arm || { pulls: 0, ucb_score: 0, avg_reward: 0, total_reward: 0 };
477
+ }
478
+
479
+ function _updateBanditArm(siteId, agentId, domain, action, reward) {
480
+ const arm = stmts.getArm.get(siteId, agentId, domain, action);
481
+ if (!arm) {
482
+ stmts.upsertArm.run(crypto.randomUUID(), siteId, agentId, domain, action);
483
+ return;
484
+ }
485
+
486
+ const newPulls = arm.pulls + 1;
487
+ const newTotalReward = arm.total_reward + reward;
488
+ const newAvgReward = newTotalReward / newPulls;
489
+
490
+ // UCB1: avg_reward + C * sqrt(ln(N) / n_i)
491
+ // We need total pulls across all arms in this domain
492
+ const arms = stmts.getArms.all(siteId, agentId, domain);
493
+ const totalPulls = arms.reduce((s, a) => s + a.pulls, 0) + 1; // +1 for this pull
494
+
495
+ const exploration = UCB_EXPLORATION * Math.sqrt(Math.log(totalPulls) / newPulls);
496
+ const ucbScore = newAvgReward + exploration;
497
+
498
+ stmts.updateArm.run(reward, newAvgReward, ucbScore, siteId, agentId, domain, action);
499
+ }
500
+
501
+ // ─── Internal: Pattern Mining ────────────────────────────────────────
502
+
503
+ function _minePatterns(siteId, agentId, domain) {
504
+ const decisions = stmts.getRecentDecisions.all(siteId, agentId, domain, 20);
505
+ if (decisions.length < 3) return;
506
+
507
+ // Extract action sequences of length 2-5
508
+ for (let len = 2; len <= Math.min(MAX_SEQUENCE_LENGTH, decisions.length); len++) {
509
+ const sequence = decisions.slice(0, len).map((d) => d.action).reverse().join(' ');
510
+ const existing = stmts.findPattern.get(siteId, agentId, sequence);
511
+
512
+ if (existing) {
513
+ // Asymptotic approach to 1.0 — confidence grows slower as it increases
514
+ const newConf = Math.min(0.99, existing.confidence + 0.05 * (1 - existing.confidence));
515
+ stmts.updatePattern.run(newConf, existing.id);
516
+ } else {
517
+ stmts.insertPattern.run(crypto.randomUUID(), siteId, agentId, 'action_sequence', sequence, 0.3);
518
+ }
519
+ }
520
+ }
521
+
522
+ // ─── Internal: Feature Extraction ────────────────────────────────────
523
+
524
+ function _extractFeatures(context) {
525
+ const features = {};
526
+
527
+ if (context.price !== undefined) {
528
+ features.price = context.price;
529
+ // Bucketize price for discrete learning
530
+ if (context.price < 10) features['price_bucket:cheap'] = 1;
531
+ else if (context.price < 50) features['price_bucket:moderate'] = 1;
532
+ else if (context.price < 200) features['price_bucket:premium'] = 1;
533
+ else features['price_bucket:luxury'] = 1;
534
+ }
535
+ if (context.quantity !== undefined) features.quantity = context.quantity;
536
+ if (context.discount !== undefined) {
537
+ features.discount = context.discount;
538
+ features.has_discount = context.discount > 0 ? 1 : 0;
539
+ }
540
+ if (context.rating !== undefined) {
541
+ features.rating = context.rating;
542
+ features.high_rated = context.rating >= 4.0 ? 1 : 0;
543
+ }
544
+ if (context.category) features[`category:${context.category}`] = 1;
545
+ if (context.brand) features[`brand:${context.brand}`] = 1;
546
+ if (context.timeOfDay !== undefined) {
547
+ features.morning = context.timeOfDay < 12 ? 1 : 0;
548
+ features.afternoon = context.timeOfDay >= 12 && context.timeOfDay < 18 ? 1 : 0;
549
+ features.evening = context.timeOfDay >= 18 ? 1 : 0;
550
+ }
551
+ if (context.isRepeat !== undefined) features.repeat_visit = context.isRepeat ? 1 : 0;
552
+ if (context.urgency !== undefined) features.urgency = context.urgency;
553
+ if (context.inStock !== undefined) features.in_stock = context.inStock ? 1 : 0;
554
+
555
+ // Pass through any raw numeric features
556
+ for (const [k, v] of Object.entries(context)) {
557
+ if (features[k] === undefined && typeof v === 'number') {
558
+ features[k] = v;
559
+ }
560
+ }
561
+
562
+ return features;
563
+ }
564
+
565
+ // ─── Internal: Confidence Estimation ─────────────────────────────────
566
+
567
+ function _getConfidence(siteId, agentId, domain) {
568
+ const decisions = stmts.getRecentDecisions.all(siteId, agentId, domain, 50);
569
+ if (decisions.length === 0) return 0;
570
+
571
+ const withOutcome = decisions.filter((d) => d.outcome !== 'pending');
572
+ if (withOutcome.length === 0) return MIN_CONFIDENCE;
573
+
574
+ // Volume component: log scale, saturates around 30 decisions
575
+ const volumeConf = Math.min(1, withOutcome.length / 30);
576
+
577
+ // Accuracy component: how close predictions were to actual rewards
578
+ let accuracySum = 0;
579
+ for (const d of withOutcome) {
580
+ if (d.predicted_reward !== null) {
581
+ const error = Math.abs(d.reward - d.predicted_reward);
582
+ accuracySum += Math.max(0, 1 - error);
583
+ }
584
+ }
585
+ const accuracyConf = withOutcome.length > 0 ? accuracySum / withOutcome.length : 0.5;
586
+
587
+ // Recency component: exponential decay based on age of newest data
588
+ const latestTs = new Date(withOutcome[0].created_at).getTime();
589
+ const ageHours = (Date.now() - latestTs) / 3600000;
590
+ const recencyConf = Math.exp(-DECAY_RATE * ageHours);
591
+
592
+ return Math.max(MIN_CONFIDENCE, Math.min(0.99,
593
+ volumeConf * 0.3 + accuracyConf * 0.5 + recencyConf * 0.2
594
+ ));
595
+ }
596
+
597
+ module.exports = {
598
+ recordDecision, feedback, batchFeedback, recommend, getPreferences,
599
+ getRewardHistory, startSession, endSession,
600
+ resetDomain, resetPatterns, getStats,
601
+ };