web-agent-bridge 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +21 -21
  2. package/README.ar.md +572 -446
  3. package/README.md +968 -933
  4. package/bin/agent-runner.js +465 -0
  5. package/bin/cli.js +138 -80
  6. package/bin/wab.js +80 -80
  7. package/examples/bidi-agent.js +119 -119
  8. package/examples/mcp-agent.js +94 -94
  9. package/examples/next-app-router/README.md +44 -0
  10. package/examples/puppeteer-agent.js +108 -108
  11. package/examples/saas-dashboard/README.md +55 -0
  12. package/examples/shopify-hydrogen/README.md +74 -0
  13. package/examples/vision-agent.js +171 -171
  14. package/examples/wordpress-elementor/README.md +77 -0
  15. package/package.json +71 -78
  16. package/public/.well-known/ai-assets.json +59 -0
  17. package/public/admin/login.html +84 -84
  18. package/public/ai.html +196 -0
  19. package/public/cookies.html +208 -208
  20. package/public/css/premium.css +317 -0
  21. package/public/css/styles.css +1235 -1235
  22. package/public/dashboard.html +704 -704
  23. package/public/demo.html +259 -0
  24. package/public/docs.html +585 -585
  25. package/public/feed.xml +89 -0
  26. package/public/index.html +581 -332
  27. package/public/js/auth-nav.js +31 -31
  28. package/public/js/auth-redirect.js +12 -12
  29. package/public/js/cookie-consent.js +56 -56
  30. package/public/js/wab-demo-page.js +721 -0
  31. package/public/js/ws-client.js +74 -74
  32. package/public/llms-full.txt +309 -0
  33. package/public/llms.txt +85 -0
  34. package/public/login.html +83 -83
  35. package/public/openapi.json +580 -0
  36. package/public/premium-dashboard.html +2487 -0
  37. package/public/premium.html +791 -0
  38. package/public/privacy.html +295 -295
  39. package/public/register.html +103 -103
  40. package/public/robots.txt +87 -0
  41. package/public/script/wab-consent.d.ts +36 -0
  42. package/public/script/wab-consent.js +104 -0
  43. package/public/script/wab-schema.js +131 -0
  44. package/public/script/wab.d.ts +108 -0
  45. package/public/script/wab.min.js +405 -0
  46. package/public/sitemap.xml +93 -0
  47. package/public/sovereign.html +660 -0
  48. package/public/terms.html +254 -254
  49. package/public/video/tutorial.mp4 +0 -0
  50. package/script/ai-agent-bridge.js +1558 -1513
  51. package/sdk/README.md +55 -55
  52. package/sdk/index.d.ts +118 -0
  53. package/sdk/index.js +257 -203
  54. package/sdk/package.json +14 -14
  55. package/sdk/schema-discovery.js +83 -0
  56. package/server/config/secrets.js +94 -92
  57. package/server/index.js +2 -9
  58. package/server/middleware/adminAuth.js +30 -30
  59. package/server/middleware/auth.js +41 -41
  60. package/server/middleware/rateLimits.js +24 -24
  61. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  62. package/server/migrations/002_premium_features.sql +418 -0
  63. package/server/models/adapters/index.js +33 -33
  64. package/server/models/adapters/mysql.js +183 -183
  65. package/server/models/adapters/postgresql.js +172 -172
  66. package/server/models/adapters/sqlite.js +7 -7
  67. package/server/models/db.js +561 -561
  68. package/server/routes/admin-premium.js +671 -0
  69. package/server/routes/admin.js +247 -247
  70. package/server/routes/api.js +131 -138
  71. package/server/routes/auth.js +51 -51
  72. package/server/routes/billing.js +45 -45
  73. package/server/routes/discovery.js +406 -329
  74. package/server/routes/license.js +240 -240
  75. package/server/routes/noscript.js +543 -543
  76. package/server/routes/premium-v2.js +686 -0
  77. package/server/routes/premium.js +724 -0
  78. package/server/routes/sovereign.js +307 -0
  79. package/server/routes/wab-api.js +476 -476
  80. package/server/services/agent-memory.js +625 -0
  81. package/server/services/email.js +204 -204
  82. package/server/services/fairness.js +420 -420
  83. package/server/services/negotiation.js +439 -0
  84. package/server/services/plugins.js +747 -0
  85. package/server/services/premium.js +1883 -0
  86. package/server/services/reputation.js +465 -0
  87. package/server/services/self-healing.js +843 -0
  88. package/server/services/stripe.js +192 -192
  89. package/server/services/swarm.js +788 -0
  90. package/server/services/verification.js +481 -0
  91. package/server/services/vision.js +871 -0
  92. package/server/utils/cache.js +125 -125
  93. package/server/utils/migrate.js +81 -81
  94. package/server/utils/secureFields.js +50 -50
  95. package/server/ws.js +101 -101
  96. package/templates/artisan-marketplace.yaml +104 -0
  97. package/templates/book-price-scout.yaml +98 -0
  98. package/templates/electronics-price-tracker.yaml +108 -0
  99. package/templates/flight-deal-hunter.yaml +113 -0
  100. package/templates/freelancer-direct.yaml +116 -0
  101. package/templates/grocery-price-compare.yaml +93 -0
  102. package/templates/hotel-direct-booking.yaml +113 -0
  103. package/templates/local-services.yaml +98 -0
  104. package/templates/olive-oil-tunisia.yaml +88 -0
  105. package/templates/organic-farm-fresh.yaml +101 -0
  106. package/templates/restaurant-direct.yaml +97 -0
  107. package/docs/DEPLOY.md +0 -118
  108. package/docs/SPEC.md +0 -1540
  109. package/wab-mcp-adapter/README.md +0 -136
  110. package/wab-mcp-adapter/index.js +0 -555
  111. package/wab-mcp-adapter/package.json +0 -17
@@ -1,420 +1,420 @@
1
- /**
2
- * Fairness Engine — Neutrality layer ensuring AI agents give equal opportunity
3
- * to all WAB-enabled sites regardless of brand size or SEO ranking.
4
- */
5
-
6
- const { db } = require('../models/db');
7
-
8
- const WAB_VERSION = '1.2.0';
9
-
10
- // ─── Directory Table (created lazily) ────────────────────────────────
11
-
12
- db.exec(`
13
- CREATE TABLE IF NOT EXISTS wab_directory (
14
- site_id TEXT PRIMARY KEY,
15
- category TEXT DEFAULT 'general',
16
- tags TEXT DEFAULT '[]',
17
- is_independent INTEGER DEFAULT 0,
18
- commission_rate REAL DEFAULT 0,
19
- direct_benefit TEXT DEFAULT '',
20
- trust_signature TEXT,
21
- listed INTEGER DEFAULT 1,
22
- neutrality_score REAL DEFAULT 50,
23
- registered_at TEXT DEFAULT (datetime('now')),
24
- updated_at TEXT DEFAULT (datetime('now')),
25
- FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
26
- );
27
-
28
- CREATE INDEX IF NOT EXISTS idx_wab_directory_category ON wab_directory(category);
29
- CREATE INDEX IF NOT EXISTS idx_wab_directory_score ON wab_directory(neutrality_score);
30
- `);
31
-
32
- // ─── Neutrality Score Calculation ────────────────────────────────────
33
-
34
- /**
35
- * Score 0-100 based on: config completeness, trust signatures,
36
- * commission transparency, and responsiveness.
37
- */
38
- function calculateNeutralityScore(site) {
39
- let score = 0;
40
- const weights = { configCompleteness: 30, trustSignature: 20, commissionTransparency: 25, responsiveness: 25 };
41
-
42
- let config = {};
43
- try { config = JSON.parse(site.config || '{}'); } catch (_) {}
44
-
45
- // Config completeness (0-30): how well the site has configured WAB
46
- const configFields = [
47
- config.agentPermissions,
48
- config.restrictions,
49
- config.logging,
50
- config.features
51
- ];
52
- const filledFields = configFields.filter(f => f && Object.keys(f).length > 0).length;
53
- score += (filledFields / configFields.length) * weights.configCompleteness;
54
-
55
- // Permission granularity bonus
56
- if (config.agentPermissions) {
57
- const permCount = Object.keys(config.agentPermissions).length;
58
- score += Math.min(permCount / 8, 1) * 5;
59
- }
60
-
61
- // Trust signature (0-20)
62
- const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(site.id);
63
- if (dirEntry && dirEntry.trust_signature) {
64
- const isValid = validateTrustSignature(dirEntry.trust_signature);
65
- score += isValid ? weights.trustSignature : weights.trustSignature * 0.3;
66
- }
67
-
68
- // Commission transparency (0-25)
69
- if (dirEntry) {
70
- if (dirEntry.commission_rate >= 0) score += 10;
71
- if (dirEntry.direct_benefit && dirEntry.direct_benefit.length > 0) score += 10;
72
- if (dirEntry.commission_rate === 0) score += 5;
73
- }
74
-
75
- // Responsiveness (0-25): based on recent analytics activity
76
- try {
77
- const recentActivity = db.prepare(
78
- 'SELECT COUNT(*) as c FROM analytics WHERE site_id = ? AND created_at >= datetime("now", "-7 days")'
79
- ).get(site.id);
80
- if (recentActivity) {
81
- const activityScore = Math.min(recentActivity.c / 100, 1) * weights.responsiveness;
82
- score += activityScore;
83
- }
84
- } catch (_) {
85
- // analytics table may not exist yet
86
- }
87
-
88
- return Math.round(Math.min(Math.max(score, 0), 100) * 100) / 100;
89
- }
90
-
91
- // ─── Fairness-Weighted Search ────────────────────────────────────────
92
-
93
- /**
94
- * Search sites with fairness-weighted ranking rather than pure relevance.
95
- */
96
- function fairnessWeightedSearch(query, sites) {
97
- if (!sites || sites.length === 0) return [];
98
-
99
- const queryLower = (query || '').toLowerCase();
100
- const terms = queryLower.split(/\s+/).filter(Boolean);
101
-
102
- const scored = sites.map(site => {
103
- let config = {};
104
- try { config = JSON.parse(site.config || '{}'); } catch (_) {}
105
-
106
- // Base relevance: match query against name, domain, description, category
107
- let relevance = 0;
108
- const searchable = [
109
- site.name,
110
- site.domain,
111
- site.description,
112
- config.category
113
- ].filter(Boolean).join(' ').toLowerCase();
114
-
115
- for (const term of terms) {
116
- if (searchable.includes(term)) relevance += 20;
117
- }
118
- if (site.name && site.name.toLowerCase().includes(queryLower)) relevance += 30;
119
- if (site.domain && site.domain.toLowerCase().includes(queryLower)) relevance += 25;
120
-
121
- if (!queryLower) relevance = 50;
122
-
123
- // Fairness adjustments
124
- const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(site.id);
125
- let fairnessBoost = 0;
126
-
127
- // Independent businesses get +15%
128
- if (dirEntry && dirEntry.is_independent) {
129
- fairnessBoost += relevance * 0.15;
130
- }
131
-
132
- // Transparent commission gets +10%
133
- if (dirEntry && dirEntry.commission_rate >= 0 && dirEntry.direct_benefit) {
134
- fairnessBoost += relevance * 0.10;
135
- }
136
-
137
- // Neutrality score influence (up to +20%)
138
- const neutralityScore = dirEntry ? dirEntry.neutrality_score : 50;
139
- fairnessBoost += (neutralityScore / 100) * relevance * 0.20;
140
-
141
- // Randomization factor to prevent position lock-in (±5%)
142
- const jitter = (Math.random() - 0.5) * relevance * 0.10;
143
-
144
- const finalScore = relevance + fairnessBoost + jitter;
145
-
146
- return {
147
- ...site,
148
- config,
149
- _relevance: Math.round(relevance * 100) / 100,
150
- _fairnessBoost: Math.round(fairnessBoost * 100) / 100,
151
- _finalScore: Math.round(finalScore * 100) / 100,
152
- _neutralityScore: neutralityScore,
153
- _isIndependent: dirEntry ? !!dirEntry.is_independent : false
154
- };
155
- });
156
-
157
- scored.sort((a, b) => b._finalScore - a._finalScore);
158
-
159
- return ensureNeutralDistribution(scored);
160
- }
161
-
162
- // ─── Directory Registration ──────────────────────────────────────────
163
-
164
- function registerInDirectory(siteId, metadata = {}) {
165
- const site = db.prepare('SELECT * FROM sites WHERE id = ? AND active = 1').get(siteId);
166
- if (!site) return { success: false, error: 'Site not found or inactive' };
167
-
168
- const neutralityScore = calculateNeutralityScore(site);
169
-
170
- const existing = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(siteId);
171
- if (existing) {
172
- db.prepare(`
173
- UPDATE wab_directory SET
174
- category = ?, tags = ?, is_independent = ?, commission_rate = ?,
175
- direct_benefit = ?, trust_signature = ?, neutrality_score = ?,
176
- updated_at = datetime('now')
177
- WHERE site_id = ?
178
- `).run(
179
- metadata.category || existing.category || 'general',
180
- JSON.stringify(metadata.tags || JSON.parse(existing.tags || '[]')),
181
- metadata.is_independent !== undefined ? (metadata.is_independent ? 1 : 0) : existing.is_independent,
182
- metadata.commission_rate !== undefined ? metadata.commission_rate : existing.commission_rate,
183
- metadata.direct_benefit || existing.direct_benefit || '',
184
- metadata.trust_signature || existing.trust_signature || null,
185
- neutralityScore,
186
- siteId
187
- );
188
- } else {
189
- db.prepare(`
190
- INSERT INTO wab_directory (site_id, category, tags, is_independent, commission_rate, direct_benefit, trust_signature, neutrality_score)
191
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
192
- `).run(
193
- siteId,
194
- metadata.category || 'general',
195
- JSON.stringify(metadata.tags || []),
196
- metadata.is_independent ? 1 : 0,
197
- metadata.commission_rate || 0,
198
- metadata.direct_benefit || '',
199
- metadata.trust_signature || null,
200
- neutralityScore
201
- );
202
- }
203
-
204
- return {
205
- success: true,
206
- siteId,
207
- neutralityScore,
208
- category: metadata.category || 'general'
209
- };
210
- }
211
-
212
- // ─── Directory Listings ──────────────────────────────────────────────
213
-
214
- function getDirectoryListings(category, options = {}) {
215
- const { limit = 50, offset = 0, includeUnlisted = false } = options;
216
-
217
- let query = `
218
- SELECT s.*, d.category, d.tags, d.is_independent, d.commission_rate,
219
- d.direct_benefit, d.neutrality_score, d.trust_signature, d.registered_at as directory_registered_at
220
- FROM wab_directory d
221
- JOIN sites s ON d.site_id = s.id AND s.active = 1
222
- `;
223
- const params = [];
224
-
225
- const conditions = [];
226
- if (!includeUnlisted) conditions.push('d.listed = 1');
227
- if (category && category !== 'all') {
228
- conditions.push('d.category = ?');
229
- params.push(category);
230
- }
231
-
232
- if (conditions.length > 0) {
233
- query += ' WHERE ' + conditions.join(' AND ');
234
- }
235
-
236
- query += ' ORDER BY d.neutrality_score DESC, s.name ASC';
237
- query += ' LIMIT ? OFFSET ?';
238
- params.push(limit, offset);
239
-
240
- const listings = db.prepare(query).all(...params);
241
-
242
- // Apply fairness shuffling to the top results
243
- return shuffleTopResults(listings);
244
- }
245
-
246
- // ─── Trust Signature Validation ──────────────────────────────────────
247
-
248
- /**
249
- * Validate a trust signature. Signatures are opaque tokens that
250
- * indicate the site owner has verified their identity through
251
- * an external trust provider.
252
- *
253
- * Format: "wab-trust-v1:<hex-payload>" (min 32 char payload)
254
- */
255
- function validateTrustSignature(signature) {
256
- if (!signature || typeof signature !== 'string') return false;
257
-
258
- if (!signature.startsWith('wab-trust-v1:')) return false;
259
-
260
- const payload = signature.slice('wab-trust-v1:'.length);
261
- if (payload.length < 32) return false;
262
- if (!/^[a-f0-9]+$/i.test(payload)) return false;
263
-
264
- return true;
265
- }
266
-
267
- // ─── Fairness Report ─────────────────────────────────────────────────
268
-
269
- function generateFairnessReport(siteId) {
270
- const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(siteId);
271
- if (!site) return null;
272
-
273
- const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(siteId);
274
- const neutralityScore = calculateNeutralityScore(site);
275
-
276
- let config = {};
277
- try { config = JSON.parse(site.config || '{}'); } catch (_) {}
278
-
279
- const configFields = [config.agentPermissions, config.restrictions, config.logging, config.features];
280
- const filledFields = configFields.filter(f => f && Object.keys(f).length > 0).length;
281
-
282
- let recentActivity = { c: 0 };
283
- try {
284
- recentActivity = db.prepare(
285
- 'SELECT COUNT(*) as c FROM analytics WHERE site_id = ? AND created_at >= datetime("now", "-7 days")'
286
- ).get(siteId) || { c: 0 };
287
- } catch (_) {}
288
-
289
- const factors = {
290
- config_completeness: {
291
- score: Math.round((filledFields / configFields.length) * 30),
292
- max: 30,
293
- details: `${filledFields}/${configFields.length} config sections populated`
294
- },
295
- trust_verification: {
296
- score: dirEntry && dirEntry.trust_signature && validateTrustSignature(dirEntry.trust_signature) ? 20 : 0,
297
- max: 20,
298
- details: dirEntry && dirEntry.trust_signature ? 'Trust signature present' : 'No trust signature'
299
- },
300
- commission_transparency: {
301
- score: dirEntry ? ((dirEntry.commission_rate >= 0 ? 10 : 0) + (dirEntry.direct_benefit ? 10 : 0) + (dirEntry.commission_rate === 0 ? 5 : 0)) : 0,
302
- max: 25,
303
- details: dirEntry ? `Commission: ${dirEntry.commission_rate}%, Benefit: ${dirEntry.direct_benefit || 'not specified'}` : 'Not registered in directory'
304
- },
305
- responsiveness: {
306
- score: recentActivity ? Math.round(Math.min(recentActivity.c / 100, 1) * 25) : 0,
307
- max: 25,
308
- details: `${recentActivity ? recentActivity.c : 0} events in last 7 days`
309
- }
310
- };
311
-
312
- return {
313
- siteId,
314
- domain: site.domain,
315
- name: site.name,
316
- tier: site.tier,
317
- neutrality_score: neutralityScore,
318
- is_independent: dirEntry ? !!dirEntry.is_independent : false,
319
- registered_in_directory: !!dirEntry,
320
- factors,
321
- recommendations: generateRecommendations(factors, dirEntry),
322
- generated_at: new Date().toISOString()
323
- };
324
- }
325
-
326
- function generateRecommendations(factors, dirEntry) {
327
- const recs = [];
328
-
329
- if (factors.config_completeness.score < factors.config_completeness.max * 0.7) {
330
- recs.push('Complete all configuration sections (agentPermissions, restrictions, logging, features) for a higher score.');
331
- }
332
- if (factors.trust_verification.score === 0) {
333
- recs.push('Add a trust signature to verify your site identity and boost your neutrality score.');
334
- }
335
- if (!dirEntry) {
336
- recs.push('Register in the WAB directory to appear in discovery searches.');
337
- }
338
- if (factors.commission_transparency.score < factors.commission_transparency.max * 0.5) {
339
- recs.push('Specify your commission rate and direct benefit to increase transparency scoring.');
340
- }
341
- if (factors.responsiveness.score < factors.responsiveness.max * 0.3) {
342
- recs.push('Increase site activity (agent interactions) to improve responsiveness score.');
343
- }
344
-
345
- return recs;
346
- }
347
-
348
- // ─── Neutral Distribution ────────────────────────────────────────────
349
-
350
- /**
351
- * Re-rank results so no single provider dominates more than 30%
352
- * of the top results. Applies fairness rotation.
353
- */
354
- function ensureNeutralDistribution(results) {
355
- if (results.length <= 3) return results;
356
-
357
- const topCount = Math.max(Math.ceil(results.length * 0.3), 3);
358
- const topSlice = results.slice(0, topCount);
359
- const rest = results.slice(topCount);
360
-
361
- // Count how many results come from each domain owner (user_id)
362
- const ownerCounts = {};
363
- for (const r of topSlice) {
364
- const owner = r.user_id || r.domain || 'unknown';
365
- ownerCounts[owner] = (ownerCounts[owner] || 0) + 1;
366
- }
367
-
368
- const maxAllowed = Math.max(Math.ceil(topCount * 0.3), 1);
369
- const redistributed = [];
370
- const demoted = [];
371
-
372
- for (const r of topSlice) {
373
- const owner = r.user_id || r.domain || 'unknown';
374
- const currentCount = redistributed.filter(x => (x.user_id || x.domain) === owner).length;
375
- if (currentCount < maxAllowed) {
376
- redistributed.push(r);
377
- } else {
378
- demoted.push(r);
379
- }
380
- }
381
-
382
- // Shuffle the top results slightly to prevent position lock-in
383
- for (let i = redistributed.length - 1; i > 0; i--) {
384
- const swapRange = Math.min(3, i);
385
- const j = i - Math.floor(Math.random() * swapRange);
386
- if (j !== i) {
387
- [redistributed[i], redistributed[j]] = [redistributed[j], redistributed[i]];
388
- }
389
- }
390
-
391
- return [...redistributed, ...demoted, ...rest];
392
- }
393
-
394
- // ─── Helper: Shuffle Top Results ─────────────────────────────────────
395
-
396
- function shuffleTopResults(listings) {
397
- if (listings.length <= 2) return listings;
398
-
399
- const rotateCount = Math.min(5, Math.ceil(listings.length * 0.2));
400
- const top = listings.slice(0, rotateCount);
401
- const rest = listings.slice(rotateCount);
402
-
403
- // Fisher-Yates on the top segment only
404
- for (let i = top.length - 1; i > 0; i--) {
405
- const j = Math.floor(Math.random() * (i + 1));
406
- [top[i], top[j]] = [top[j], top[i]];
407
- }
408
-
409
- return [...top, ...rest];
410
- }
411
-
412
- module.exports = {
413
- calculateNeutralityScore,
414
- fairnessWeightedSearch,
415
- registerInDirectory,
416
- getDirectoryListings,
417
- validateTrustSignature,
418
- generateFairnessReport,
419
- ensureNeutralDistribution
420
- };
1
+ /**
2
+ * Fairness Engine — Neutrality layer ensuring AI agents give equal opportunity
3
+ * to all WAB-enabled sites regardless of brand size or SEO ranking.
4
+ */
5
+
6
+ const { db } = require('../models/db');
7
+
8
+ const WAB_VERSION = '1.2.0';
9
+
10
+ // ─── Directory Table (created lazily) ────────────────────────────────
11
+
12
+ db.exec(`
13
+ CREATE TABLE IF NOT EXISTS wab_directory (
14
+ site_id TEXT PRIMARY KEY,
15
+ category TEXT DEFAULT 'general',
16
+ tags TEXT DEFAULT '[]',
17
+ is_independent INTEGER DEFAULT 0,
18
+ commission_rate REAL DEFAULT 0,
19
+ direct_benefit TEXT DEFAULT '',
20
+ trust_signature TEXT,
21
+ listed INTEGER DEFAULT 1,
22
+ neutrality_score REAL DEFAULT 50,
23
+ registered_at TEXT DEFAULT (datetime('now')),
24
+ updated_at TEXT DEFAULT (datetime('now')),
25
+ FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
26
+ );
27
+
28
+ CREATE INDEX IF NOT EXISTS idx_wab_directory_category ON wab_directory(category);
29
+ CREATE INDEX IF NOT EXISTS idx_wab_directory_score ON wab_directory(neutrality_score);
30
+ `);
31
+
32
+ // ─── Neutrality Score Calculation ────────────────────────────────────
33
+
34
+ /**
35
+ * Score 0-100 based on: config completeness, trust signatures,
36
+ * commission transparency, and responsiveness.
37
+ */
38
+ function calculateNeutralityScore(site) {
39
+ let score = 0;
40
+ const weights = { configCompleteness: 30, trustSignature: 20, commissionTransparency: 25, responsiveness: 25 };
41
+
42
+ let config = {};
43
+ try { config = JSON.parse(site.config || '{}'); } catch (_) {}
44
+
45
+ // Config completeness (0-30): how well the site has configured WAB
46
+ const configFields = [
47
+ config.agentPermissions,
48
+ config.restrictions,
49
+ config.logging,
50
+ config.features
51
+ ];
52
+ const filledFields = configFields.filter(f => f && Object.keys(f).length > 0).length;
53
+ score += (filledFields / configFields.length) * weights.configCompleteness;
54
+
55
+ // Permission granularity bonus
56
+ if (config.agentPermissions) {
57
+ const permCount = Object.keys(config.agentPermissions).length;
58
+ score += Math.min(permCount / 8, 1) * 5;
59
+ }
60
+
61
+ // Trust signature (0-20)
62
+ const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(site.id);
63
+ if (dirEntry && dirEntry.trust_signature) {
64
+ const isValid = validateTrustSignature(dirEntry.trust_signature);
65
+ score += isValid ? weights.trustSignature : weights.trustSignature * 0.3;
66
+ }
67
+
68
+ // Commission transparency (0-25)
69
+ if (dirEntry) {
70
+ if (dirEntry.commission_rate >= 0) score += 10;
71
+ if (dirEntry.direct_benefit && dirEntry.direct_benefit.length > 0) score += 10;
72
+ if (dirEntry.commission_rate === 0) score += 5;
73
+ }
74
+
75
+ // Responsiveness (0-25): based on recent analytics activity
76
+ try {
77
+ const recentActivity = db.prepare(
78
+ 'SELECT COUNT(*) as c FROM analytics WHERE site_id = ? AND created_at >= datetime("now", "-7 days")'
79
+ ).get(site.id);
80
+ if (recentActivity) {
81
+ const activityScore = Math.min(recentActivity.c / 100, 1) * weights.responsiveness;
82
+ score += activityScore;
83
+ }
84
+ } catch (_) {
85
+ // analytics table may not exist yet
86
+ }
87
+
88
+ return Math.round(Math.min(Math.max(score, 0), 100) * 100) / 100;
89
+ }
90
+
91
+ // ─── Fairness-Weighted Search ────────────────────────────────────────
92
+
93
+ /**
94
+ * Search sites with fairness-weighted ranking rather than pure relevance.
95
+ */
96
+ function fairnessWeightedSearch(query, sites) {
97
+ if (!sites || sites.length === 0) return [];
98
+
99
+ const queryLower = (query || '').toLowerCase();
100
+ const terms = queryLower.split(/\s+/).filter(Boolean);
101
+
102
+ const scored = sites.map(site => {
103
+ let config = {};
104
+ try { config = JSON.parse(site.config || '{}'); } catch (_) {}
105
+
106
+ // Base relevance: match query against name, domain, description, category
107
+ let relevance = 0;
108
+ const searchable = [
109
+ site.name,
110
+ site.domain,
111
+ site.description,
112
+ config.category
113
+ ].filter(Boolean).join(' ').toLowerCase();
114
+
115
+ for (const term of terms) {
116
+ if (searchable.includes(term)) relevance += 20;
117
+ }
118
+ if (site.name && site.name.toLowerCase().includes(queryLower)) relevance += 30;
119
+ if (site.domain && site.domain.toLowerCase().includes(queryLower)) relevance += 25;
120
+
121
+ if (!queryLower) relevance = 50;
122
+
123
+ // Fairness adjustments
124
+ const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(site.id);
125
+ let fairnessBoost = 0;
126
+
127
+ // Independent businesses get +15%
128
+ if (dirEntry && dirEntry.is_independent) {
129
+ fairnessBoost += relevance * 0.15;
130
+ }
131
+
132
+ // Transparent commission gets +10%
133
+ if (dirEntry && dirEntry.commission_rate >= 0 && dirEntry.direct_benefit) {
134
+ fairnessBoost += relevance * 0.10;
135
+ }
136
+
137
+ // Neutrality score influence (up to +20%)
138
+ const neutralityScore = dirEntry ? dirEntry.neutrality_score : 50;
139
+ fairnessBoost += (neutralityScore / 100) * relevance * 0.20;
140
+
141
+ // Randomization factor to prevent position lock-in (±5%)
142
+ const jitter = (Math.random() - 0.5) * relevance * 0.10;
143
+
144
+ const finalScore = relevance + fairnessBoost + jitter;
145
+
146
+ return {
147
+ ...site,
148
+ config,
149
+ _relevance: Math.round(relevance * 100) / 100,
150
+ _fairnessBoost: Math.round(fairnessBoost * 100) / 100,
151
+ _finalScore: Math.round(finalScore * 100) / 100,
152
+ _neutralityScore: neutralityScore,
153
+ _isIndependent: dirEntry ? !!dirEntry.is_independent : false
154
+ };
155
+ });
156
+
157
+ scored.sort((a, b) => b._finalScore - a._finalScore);
158
+
159
+ return ensureNeutralDistribution(scored);
160
+ }
161
+
162
+ // ─── Directory Registration ──────────────────────────────────────────
163
+
164
+ function registerInDirectory(siteId, metadata = {}) {
165
+ const site = db.prepare('SELECT * FROM sites WHERE id = ? AND active = 1').get(siteId);
166
+ if (!site) return { success: false, error: 'Site not found or inactive' };
167
+
168
+ const neutralityScore = calculateNeutralityScore(site);
169
+
170
+ const existing = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(siteId);
171
+ if (existing) {
172
+ db.prepare(`
173
+ UPDATE wab_directory SET
174
+ category = ?, tags = ?, is_independent = ?, commission_rate = ?,
175
+ direct_benefit = ?, trust_signature = ?, neutrality_score = ?,
176
+ updated_at = datetime('now')
177
+ WHERE site_id = ?
178
+ `).run(
179
+ metadata.category || existing.category || 'general',
180
+ JSON.stringify(metadata.tags || JSON.parse(existing.tags || '[]')),
181
+ metadata.is_independent !== undefined ? (metadata.is_independent ? 1 : 0) : existing.is_independent,
182
+ metadata.commission_rate !== undefined ? metadata.commission_rate : existing.commission_rate,
183
+ metadata.direct_benefit || existing.direct_benefit || '',
184
+ metadata.trust_signature || existing.trust_signature || null,
185
+ neutralityScore,
186
+ siteId
187
+ );
188
+ } else {
189
+ db.prepare(`
190
+ INSERT INTO wab_directory (site_id, category, tags, is_independent, commission_rate, direct_benefit, trust_signature, neutrality_score)
191
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
192
+ `).run(
193
+ siteId,
194
+ metadata.category || 'general',
195
+ JSON.stringify(metadata.tags || []),
196
+ metadata.is_independent ? 1 : 0,
197
+ metadata.commission_rate || 0,
198
+ metadata.direct_benefit || '',
199
+ metadata.trust_signature || null,
200
+ neutralityScore
201
+ );
202
+ }
203
+
204
+ return {
205
+ success: true,
206
+ siteId,
207
+ neutralityScore,
208
+ category: metadata.category || 'general'
209
+ };
210
+ }
211
+
212
+ // ─── Directory Listings ──────────────────────────────────────────────
213
+
214
+ function getDirectoryListings(category, options = {}) {
215
+ const { limit = 50, offset = 0, includeUnlisted = false } = options;
216
+
217
+ let query = `
218
+ SELECT s.*, d.category, d.tags, d.is_independent, d.commission_rate,
219
+ d.direct_benefit, d.neutrality_score, d.trust_signature, d.registered_at as directory_registered_at
220
+ FROM wab_directory d
221
+ JOIN sites s ON d.site_id = s.id AND s.active = 1
222
+ `;
223
+ const params = [];
224
+
225
+ const conditions = [];
226
+ if (!includeUnlisted) conditions.push('d.listed = 1');
227
+ if (category && category !== 'all') {
228
+ conditions.push('d.category = ?');
229
+ params.push(category);
230
+ }
231
+
232
+ if (conditions.length > 0) {
233
+ query += ' WHERE ' + conditions.join(' AND ');
234
+ }
235
+
236
+ query += ' ORDER BY d.neutrality_score DESC, s.name ASC';
237
+ query += ' LIMIT ? OFFSET ?';
238
+ params.push(limit, offset);
239
+
240
+ const listings = db.prepare(query).all(...params);
241
+
242
+ // Apply fairness shuffling to the top results
243
+ return shuffleTopResults(listings);
244
+ }
245
+
246
+ // ─── Trust Signature Validation ──────────────────────────────────────
247
+
248
+ /**
249
+ * Validate a trust signature. Signatures are opaque tokens that
250
+ * indicate the site owner has verified their identity through
251
+ * an external trust provider.
252
+ *
253
+ * Format: "wab-trust-v1:<hex-payload>" (min 32 char payload)
254
+ */
255
+ function validateTrustSignature(signature) {
256
+ if (!signature || typeof signature !== 'string') return false;
257
+
258
+ if (!signature.startsWith('wab-trust-v1:')) return false;
259
+
260
+ const payload = signature.slice('wab-trust-v1:'.length);
261
+ if (payload.length < 32) return false;
262
+ if (!/^[a-f0-9]+$/i.test(payload)) return false;
263
+
264
+ return true;
265
+ }
266
+
267
+ // ─── Fairness Report ─────────────────────────────────────────────────
268
+
269
+ function generateFairnessReport(siteId) {
270
+ const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(siteId);
271
+ if (!site) return null;
272
+
273
+ const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(siteId);
274
+ const neutralityScore = calculateNeutralityScore(site);
275
+
276
+ let config = {};
277
+ try { config = JSON.parse(site.config || '{}'); } catch (_) {}
278
+
279
+ const configFields = [config.agentPermissions, config.restrictions, config.logging, config.features];
280
+ const filledFields = configFields.filter(f => f && Object.keys(f).length > 0).length;
281
+
282
+ let recentActivity = { c: 0 };
283
+ try {
284
+ recentActivity = db.prepare(
285
+ 'SELECT COUNT(*) as c FROM analytics WHERE site_id = ? AND created_at >= datetime("now", "-7 days")'
286
+ ).get(siteId) || { c: 0 };
287
+ } catch (_) {}
288
+
289
+ const factors = {
290
+ config_completeness: {
291
+ score: Math.round((filledFields / configFields.length) * 30),
292
+ max: 30,
293
+ details: `${filledFields}/${configFields.length} config sections populated`
294
+ },
295
+ trust_verification: {
296
+ score: dirEntry && dirEntry.trust_signature && validateTrustSignature(dirEntry.trust_signature) ? 20 : 0,
297
+ max: 20,
298
+ details: dirEntry && dirEntry.trust_signature ? 'Trust signature present' : 'No trust signature'
299
+ },
300
+ commission_transparency: {
301
+ score: dirEntry ? ((dirEntry.commission_rate >= 0 ? 10 : 0) + (dirEntry.direct_benefit ? 10 : 0) + (dirEntry.commission_rate === 0 ? 5 : 0)) : 0,
302
+ max: 25,
303
+ details: dirEntry ? `Commission: ${dirEntry.commission_rate}%, Benefit: ${dirEntry.direct_benefit || 'not specified'}` : 'Not registered in directory'
304
+ },
305
+ responsiveness: {
306
+ score: recentActivity ? Math.round(Math.min(recentActivity.c / 100, 1) * 25) : 0,
307
+ max: 25,
308
+ details: `${recentActivity ? recentActivity.c : 0} events in last 7 days`
309
+ }
310
+ };
311
+
312
+ return {
313
+ siteId,
314
+ domain: site.domain,
315
+ name: site.name,
316
+ tier: site.tier,
317
+ neutrality_score: neutralityScore,
318
+ is_independent: dirEntry ? !!dirEntry.is_independent : false,
319
+ registered_in_directory: !!dirEntry,
320
+ factors,
321
+ recommendations: generateRecommendations(factors, dirEntry),
322
+ generated_at: new Date().toISOString()
323
+ };
324
+ }
325
+
326
+ function generateRecommendations(factors, dirEntry) {
327
+ const recs = [];
328
+
329
+ if (factors.config_completeness.score < factors.config_completeness.max * 0.7) {
330
+ recs.push('Complete all configuration sections (agentPermissions, restrictions, logging, features) for a higher score.');
331
+ }
332
+ if (factors.trust_verification.score === 0) {
333
+ recs.push('Add a trust signature to verify your site identity and boost your neutrality score.');
334
+ }
335
+ if (!dirEntry) {
336
+ recs.push('Register in the WAB directory to appear in discovery searches.');
337
+ }
338
+ if (factors.commission_transparency.score < factors.commission_transparency.max * 0.5) {
339
+ recs.push('Specify your commission rate and direct benefit to increase transparency scoring.');
340
+ }
341
+ if (factors.responsiveness.score < factors.responsiveness.max * 0.3) {
342
+ recs.push('Increase site activity (agent interactions) to improve responsiveness score.');
343
+ }
344
+
345
+ return recs;
346
+ }
347
+
348
+ // ─── Neutral Distribution ────────────────────────────────────────────
349
+
350
+ /**
351
+ * Re-rank results so no single provider dominates more than 30%
352
+ * of the top results. Applies fairness rotation.
353
+ */
354
+ function ensureNeutralDistribution(results) {
355
+ if (results.length <= 3) return results;
356
+
357
+ const topCount = Math.max(Math.ceil(results.length * 0.3), 3);
358
+ const topSlice = results.slice(0, topCount);
359
+ const rest = results.slice(topCount);
360
+
361
+ // Count how many results come from each domain owner (user_id)
362
+ const ownerCounts = {};
363
+ for (const r of topSlice) {
364
+ const owner = r.user_id || r.domain || 'unknown';
365
+ ownerCounts[owner] = (ownerCounts[owner] || 0) + 1;
366
+ }
367
+
368
+ const maxAllowed = Math.max(Math.ceil(topCount * 0.3), 1);
369
+ const redistributed = [];
370
+ const demoted = [];
371
+
372
+ for (const r of topSlice) {
373
+ const owner = r.user_id || r.domain || 'unknown';
374
+ const currentCount = redistributed.filter(x => (x.user_id || x.domain) === owner).length;
375
+ if (currentCount < maxAllowed) {
376
+ redistributed.push(r);
377
+ } else {
378
+ demoted.push(r);
379
+ }
380
+ }
381
+
382
+ // Shuffle the top results slightly to prevent position lock-in
383
+ for (let i = redistributed.length - 1; i > 0; i--) {
384
+ const swapRange = Math.min(3, i);
385
+ const j = i - Math.floor(Math.random() * swapRange);
386
+ if (j !== i) {
387
+ [redistributed[i], redistributed[j]] = [redistributed[j], redistributed[i]];
388
+ }
389
+ }
390
+
391
+ return [...redistributed, ...demoted, ...rest];
392
+ }
393
+
394
+ // ─── Helper: Shuffle Top Results ─────────────────────────────────────
395
+
396
+ function shuffleTopResults(listings) {
397
+ if (listings.length <= 2) return listings;
398
+
399
+ const rotateCount = Math.min(5, Math.ceil(listings.length * 0.2));
400
+ const top = listings.slice(0, rotateCount);
401
+ const rest = listings.slice(rotateCount);
402
+
403
+ // Fisher-Yates on the top segment only
404
+ for (let i = top.length - 1; i > 0; i--) {
405
+ const j = Math.floor(Math.random() * (i + 1));
406
+ [top[i], top[j]] = [top[j], top[i]];
407
+ }
408
+
409
+ return [...top, ...rest];
410
+ }
411
+
412
+ module.exports = {
413
+ calculateNeutralityScore,
414
+ fairnessWeightedSearch,
415
+ registerInDirectory,
416
+ getDirectoryListings,
417
+ validateTrustSignature,
418
+ generateFairnessReport,
419
+ ensureNeutralDistribution
420
+ };