web-agent-bridge 3.3.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/LICENSE +84 -72
  2. package/README.ar.md +1563 -1286
  3. package/README.md +137 -1764
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -237
  6. package/bin/wab-init.js +244 -0
  7. package/bin/wab.js +80 -80
  8. package/examples/azure-dns-wab.js +83 -0
  9. package/examples/bidi-agent.js +119 -119
  10. package/examples/cloudflare-wab-dns.js +121 -0
  11. package/examples/cpanel-wab-dns.js +114 -0
  12. package/examples/cross-site-agent.js +91 -91
  13. package/examples/dns-discovery-agent.js +166 -0
  14. package/examples/gcp-dns-wab.js +76 -0
  15. package/examples/governance-agent.js +169 -0
  16. package/examples/mcp-agent.js +94 -94
  17. package/examples/next-app-router/README.md +44 -44
  18. package/examples/plesk-wab-dns.js +103 -0
  19. package/examples/puppeteer-agent.js +108 -108
  20. package/examples/route53-wab-dns.js +144 -0
  21. package/examples/saas-dashboard/README.md +55 -55
  22. package/examples/safe-mode-agent.js +96 -0
  23. package/examples/self-discovery.js +106 -0
  24. package/examples/shopify-hydrogen/README.md +74 -74
  25. package/examples/vision-agent.js +171 -171
  26. package/examples/wab-sign.js +74 -0
  27. package/examples/wab-verify.js +60 -0
  28. package/examples/wordpress-elementor/README.md +77 -77
  29. package/package.json +93 -93
  30. package/public/.well-known/agent-tools.json +180 -180
  31. package/public/.well-known/ai-assets.json +59 -59
  32. package/public/.well-known/security.txt +8 -8
  33. package/public/.well-known/wab.json +28 -0
  34. package/public/activate.html +448 -0
  35. package/public/adopt.html +236 -0
  36. package/public/adoption-metrics.html +188 -0
  37. package/public/agent-workspace.html +359 -349
  38. package/public/ai.html +198 -198
  39. package/public/api.html +397 -413
  40. package/public/azure-dns-integration.html +289 -0
  41. package/public/browser.html +486 -486
  42. package/public/cloudflare-integration.html +380 -0
  43. package/public/commander-dashboard.html +243 -243
  44. package/public/cookies.html +210 -210
  45. package/public/cpanel-integration.html +398 -0
  46. package/public/css/agent-workspace.css +1713 -1713
  47. package/public/css/premium.css +317 -317
  48. package/public/css/styles.css +1401 -1235
  49. package/public/dashboard-shieldlink.html +295 -0
  50. package/public/dashboard.html +711 -706
  51. package/public/dns.html +436 -507
  52. package/public/docs.html +588 -587
  53. package/public/enterprise-mesh.ar.html +80 -0
  54. package/public/enterprise-mesh.html +81 -0
  55. package/public/feed.xml +89 -89
  56. package/public/gcp-dns-integration.html +318 -0
  57. package/public/governance.ar.html +70 -0
  58. package/public/governance.html +69 -0
  59. package/public/growth.html +465 -463
  60. package/public/index.html +1372 -1070
  61. package/public/integrations.html +556 -556
  62. package/public/js/activate.js +449 -0
  63. package/public/js/agent-workspace.js +1740 -1740
  64. package/public/js/auth-nav.js +117 -31
  65. package/public/js/auth-redirect.js +12 -12
  66. package/public/js/cookie-consent.js +56 -56
  67. package/public/js/dns.js +438 -0
  68. package/public/js/wab-demo-page.js +721 -721
  69. package/public/js/ws-client.js +74 -74
  70. package/public/l-preview.html +242 -0
  71. package/public/llms-full.txt +360 -360
  72. package/public/llms.txt +125 -125
  73. package/public/login.html +85 -85
  74. package/public/mesh-dashboard.html +328 -328
  75. package/public/milestones.html +346 -0
  76. package/public/one-click.html +779 -0
  77. package/public/openapi.json +669 -580
  78. package/public/partners.ar.html +145 -0
  79. package/public/partners.html +143 -0
  80. package/public/phone-shield.html +281 -281
  81. package/public/plesk-integration.html +375 -0
  82. package/public/premium-dashboard.html +2489 -2489
  83. package/public/premium.html +793 -793
  84. package/public/privacy.html +297 -297
  85. package/public/provider-onboarding.html +172 -0
  86. package/public/provider-sandbox.html +134 -0
  87. package/public/providers.html +359 -0
  88. package/public/refusals.html +172 -0
  89. package/public/register.html +105 -105
  90. package/public/registrar-integrations.html +141 -0
  91. package/public/ring4.html +292 -0
  92. package/public/robots.txt +99 -87
  93. package/public/route53-integration.html +531 -0
  94. package/public/score.html +263 -0
  95. package/public/script/wab-consent.d.ts +36 -36
  96. package/public/script/wab-consent.js +104 -104
  97. package/public/script/wab-schema.js +131 -131
  98. package/public/script/wab.d.ts +108 -108
  99. package/public/script/wab.min.js +580 -580
  100. package/public/security.txt +8 -8
  101. package/public/shieldlink.html +244 -0
  102. package/public/shieldqr.html +231 -0
  103. package/public/sitemap.xml +19 -1
  104. package/public/terms.html +256 -256
  105. package/public/trust-graph-api.ar.html +92 -0
  106. package/public/trust-graph-api.html +91 -0
  107. package/public/wab-features.html +560 -0
  108. package/public/wab-trust.html +200 -0
  109. package/public/wab-truth.html +375 -0
  110. package/public/wab-vs-protocols.html +210 -0
  111. package/public/whitepaper.html +449 -0
  112. package/script/ai-agent-bridge.js +1754 -1754
  113. package/sdk/README.md +99 -99
  114. package/sdk/agent-mesh.js +449 -449
  115. package/sdk/auto-discovery.js +301 -0
  116. package/sdk/commander.js +262 -262
  117. package/sdk/governance.js +262 -0
  118. package/sdk/index.d.ts +464 -464
  119. package/sdk/index.js +649 -636
  120. package/sdk/multi-agent.js +318 -318
  121. package/sdk/package.json +2 -2
  122. package/sdk/safe-mode.js +221 -0
  123. package/sdk/safety-shield.js +219 -219
  124. package/sdk/schema-discovery.js +83 -83
  125. package/server/adapters/index.js +520 -520
  126. package/server/config/plans.js +412 -367
  127. package/server/config/secrets.js +102 -102
  128. package/server/control-plane/index.js +301 -301
  129. package/server/data-plane/index.js +354 -354
  130. package/server/index.js +790 -531
  131. package/server/llm/index.js +404 -404
  132. package/server/middleware/adminAuth.js +35 -35
  133. package/server/middleware/api-tier.js +170 -0
  134. package/server/middleware/auth.js +50 -50
  135. package/server/middleware/featureGate.js +88 -88
  136. package/server/middleware/rateLimits.js +100 -100
  137. package/server/middleware/sensitiveAction.js +157 -157
  138. package/server/middleware/wab-trust.js +141 -0
  139. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  140. package/server/migrations/002_premium_features.sql +418 -418
  141. package/server/migrations/003_ads_integer_cents.sql +33 -33
  142. package/server/migrations/004_agent_os.sql +158 -158
  143. package/server/migrations/005_marketplace_metering.sql +126 -126
  144. package/server/migrations/006_growth_suite.sql +138 -0
  145. package/server/migrations/007_governance.sql +106 -0
  146. package/server/migrations/008_plans.sql +144 -0
  147. package/server/migrations/009_shieldqr.sql +30 -0
  148. package/server/migrations/010_extended_trust.sql +33 -0
  149. package/server/migrations/011_outreach.sql +47 -0
  150. package/server/migrations/012_shieldlink.sql +116 -0
  151. package/server/migrations/013_ct_monitor.sql +13 -0
  152. package/server/migrations/014_wab_advanced_features.sql +128 -0
  153. package/server/migrations/015_wab_truth_layer.sql +101 -0
  154. package/server/migrations/016_ring4_external_trust.sql +84 -0
  155. package/server/migrations/017_ring4_extensions.sql +69 -0
  156. package/server/migrations/018_commercial_foundations.sql +167 -0
  157. package/server/migrations/019_unify_tier_constraints.sql +133 -0
  158. package/server/models/adapters/index.js +33 -33
  159. package/server/models/adapters/mysql.js +183 -183
  160. package/server/models/adapters/postgresql.js +172 -172
  161. package/server/models/adapters/sqlite.js +7 -7
  162. package/server/models/db.js +740 -681
  163. package/server/observability/failure-analysis.js +337 -337
  164. package/server/observability/index.js +394 -394
  165. package/server/protocol/capabilities.js +223 -223
  166. package/server/protocol/index.js +243 -243
  167. package/server/protocol/schema.js +584 -584
  168. package/server/registry/certification.js +271 -271
  169. package/server/registry/index.js +326 -326
  170. package/server/routes/activate.js +478 -0
  171. package/server/routes/admin-outreach.js +239 -0
  172. package/server/routes/admin-plans.js +76 -0
  173. package/server/routes/admin-premium.js +674 -671
  174. package/server/routes/admin-shieldlink.js +137 -0
  175. package/server/routes/admin-shieldqr.js +90 -0
  176. package/server/routes/admin-trust-monitor.js +139 -0
  177. package/server/routes/admin.js +550 -261
  178. package/server/routes/adopt.js +61 -0
  179. package/server/routes/ads.js +130 -130
  180. package/server/routes/agent-workspace.js +540 -540
  181. package/server/routes/api-keys.js +127 -0
  182. package/server/routes/api.js +150 -150
  183. package/server/routes/auth.js +71 -71
  184. package/server/routes/billing.js +57 -45
  185. package/server/routes/commander.js +316 -316
  186. package/server/routes/customer-shieldlink.js +133 -0
  187. package/server/routes/demo-showcase.js +332 -332
  188. package/server/routes/demo-store.js +154 -154
  189. package/server/routes/diagnose.js +373 -0
  190. package/server/routes/discovery.js +2348 -417
  191. package/server/routes/enterprise-mesh.js +170 -0
  192. package/server/routes/gateway.js +173 -173
  193. package/server/routes/governance-saas.js +203 -0
  194. package/server/routes/governance.js +208 -0
  195. package/server/routes/growth.js +1048 -0
  196. package/server/routes/intent.js +328 -0
  197. package/server/routes/license.js +251 -251
  198. package/server/routes/mesh.js +469 -469
  199. package/server/routes/noscript.js +543 -543
  200. package/server/routes/partners.js +201 -0
  201. package/server/routes/plans.js +33 -0
  202. package/server/routes/premium-v2.js +686 -686
  203. package/server/routes/premium.js +724 -724
  204. package/server/routes/providers.js +650 -0
  205. package/server/routes/reputation.js +411 -0
  206. package/server/routes/ring4.js +885 -0
  207. package/server/routes/runtime.js +2148 -2148
  208. package/server/routes/shieldlink.js +70 -0
  209. package/server/routes/shieldqr.js +88 -0
  210. package/server/routes/sovereign.js +465 -465
  211. package/server/routes/truth-layer.js +670 -0
  212. package/server/routes/universal.js +200 -200
  213. package/server/routes/unsubscribe.js +51 -0
  214. package/server/routes/wab-api.js +850 -850
  215. package/server/routes/wab-cache.js +282 -0
  216. package/server/runtime/container-worker.js +111 -111
  217. package/server/runtime/container.js +448 -448
  218. package/server/runtime/distributed-worker.js +362 -362
  219. package/server/runtime/event-bus.js +210 -210
  220. package/server/runtime/index.js +253 -253
  221. package/server/runtime/queue.js +599 -599
  222. package/server/runtime/replay.js +666 -666
  223. package/server/runtime/sandbox.js +266 -266
  224. package/server/runtime/scheduler.js +534 -534
  225. package/server/runtime/session-engine.js +293 -293
  226. package/server/runtime/state-manager.js +188 -188
  227. package/server/secrets/wab-signing-key.pem +3 -0
  228. package/server/secrets/wab-signing-pub.pem +3 -0
  229. package/server/security/cross-site-redactor.js +196 -196
  230. package/server/security/dry-run.js +180 -180
  231. package/server/security/human-gate-rate-limit.js +147 -147
  232. package/server/security/human-gate-transports.js +178 -178
  233. package/server/security/human-gate.js +281 -281
  234. package/server/security/index.js +368 -368
  235. package/server/security/intent-engine.js +245 -245
  236. package/server/security/reward-guard.js +171 -171
  237. package/server/security/rollback-store.js +239 -239
  238. package/server/security/token-scope.js +404 -404
  239. package/server/security/url-policy.js +139 -139
  240. package/server/services/adoption-agent.js +182 -0
  241. package/server/services/agent-chat.js +506 -506
  242. package/server/services/agent-learning.js +601 -601
  243. package/server/services/agent-memory.js +625 -625
  244. package/server/services/agent-mesh.js +555 -555
  245. package/server/services/agent-symphony.js +717 -717
  246. package/server/services/agent-tasks.js +1807 -1807
  247. package/server/services/api-key-engine.js +292 -292
  248. package/server/services/cluster.js +894 -894
  249. package/server/services/commander.js +738 -738
  250. package/server/services/edge-compute.js +440 -440
  251. package/server/services/email.js +233 -204
  252. package/server/services/fairness-engine.js +409 -0
  253. package/server/services/fairness.js +420 -0
  254. package/server/services/governance.js +466 -0
  255. package/server/services/hosted-runtime.js +205 -205
  256. package/server/services/lfd.js +635 -635
  257. package/server/services/local-ai.js +389 -389
  258. package/server/services/marketplace.js +270 -270
  259. package/server/services/metering.js +182 -182
  260. package/server/services/modules/affiliate-intelligence.js +93 -93
  261. package/server/services/modules/agent-firewall.js +90 -90
  262. package/server/services/modules/bounty.js +89 -89
  263. package/server/services/modules/collective-bargaining.js +92 -92
  264. package/server/services/modules/dark-pattern.js +66 -66
  265. package/server/services/modules/gov-intelligence.js +45 -45
  266. package/server/services/modules/neural.js +55 -55
  267. package/server/services/modules/notary.js +49 -49
  268. package/server/services/modules/price-time-machine.js +86 -86
  269. package/server/services/modules/protocol.js +104 -104
  270. package/server/services/negotiation.js +439 -439
  271. package/server/services/outreach-agent.js +312 -0
  272. package/server/services/plans.js +214 -0
  273. package/server/services/plugins.js +771 -771
  274. package/server/services/premium.js +1 -1
  275. package/server/services/price-intelligence.js +566 -566
  276. package/server/services/price-shield.js +1137 -1137
  277. package/server/services/provider-clients.js +740 -0
  278. package/server/services/reputation.js +465 -465
  279. package/server/services/search-engine.js +357 -357
  280. package/server/services/security.js +513 -513
  281. package/server/services/self-healing.js +843 -843
  282. package/server/services/shieldlink.js +492 -0
  283. package/server/services/shieldqr.js +322 -0
  284. package/server/services/sovereign-shield.js +542 -542
  285. package/server/services/ssl-ct-monitor.js +224 -0
  286. package/server/services/ssl-inspector.js +42 -0
  287. package/server/services/ssl-monitor.js +167 -0
  288. package/server/services/stripe.js +206 -192
  289. package/server/services/swarm.js +788 -788
  290. package/server/services/universal-scraper.js +662 -662
  291. package/server/services/verification.js +481 -481
  292. package/server/services/vision.js +1163 -1163
  293. package/server/services/wab-crypto.js +178 -0
  294. package/server/utils/cache.js +125 -125
  295. package/server/utils/migrate.js +81 -81
  296. package/server/utils/safe-fetch.js +228 -228
  297. package/server/utils/secureFields.js +50 -50
  298. package/server/ws.js +161 -161
  299. package/templates/artisan-marketplace.yaml +104 -104
  300. package/templates/book-price-scout.yaml +98 -98
  301. package/templates/electronics-price-tracker.yaml +108 -108
  302. package/templates/flight-deal-hunter.yaml +113 -113
  303. package/templates/freelancer-direct.yaml +116 -116
  304. package/templates/grocery-price-compare.yaml +93 -93
  305. package/templates/hotel-direct-booking.yaml +113 -113
  306. package/templates/local-services.yaml +98 -98
  307. package/templates/olive-oil-tunisia.yaml +88 -88
  308. package/templates/organic-farm-fresh.yaml +101 -101
  309. package/templates/restaurant-direct.yaml +97 -97
  310. package/templates/ring4/banking-sovereign.yaml +55 -0
  311. package/templates/ring4/ecommerce-sovereign.yaml +58 -0
  312. package/templates/ring4/healthcare-sovereign.yaml +60 -0
@@ -0,0 +1,670 @@
1
+ /**
2
+ * server/routes/truth-layer.js
3
+ * WAB Truth Layer — unified API for 4 features:
4
+ * 1. Semantic Memory Network (anonymized agent observations per intent)
5
+ * 2. Temporal Trust (time-stability dimension)
6
+ * 3. Intent-to-Action Bridge (Action Graphs)
7
+ * 4. Reality Anchor (cross-site fact verification)
8
+ *
9
+ * Mounted at /api/truth
10
+ *
11
+ * Endpoints:
12
+ * --- Semantic Memory ---
13
+ * POST /api/truth/memory/observe — agent reports an observation
14
+ * GET /api/truth/memory/:domain — semantic summary for a domain
15
+ * GET /api/truth/memory/:domain/:intent — summary for a specific intent
16
+ *
17
+ * --- Temporal Trust ---
18
+ * GET /api/truth/temporal/:domain — temporal trust profile
19
+ * POST /api/truth/temporal/snapshot — record a trust snapshot (internal)
20
+ *
21
+ * --- Action Graph ---
22
+ * GET /api/truth/action/:domain/:intent — get action graph
23
+ * POST /api/truth/action/register — site owner registers an action graph
24
+ * POST /api/truth/action/resolve — agent: intent → recommended graph
25
+ *
26
+ * --- Reality Anchor ---
27
+ * POST /api/truth/reality/submit — submit observed fact
28
+ * GET /api/truth/reality/:fact_key — verify a fact against the network
29
+ * POST /api/truth/reality/verify — bulk verification
30
+ *
31
+ * --- Unified ---
32
+ * GET /api/truth/profile/:domain — full Truth profile (all 4 in one)
33
+ */
34
+
35
+ 'use strict';
36
+
37
+ const express = require('express');
38
+ const crypto = require('crypto');
39
+ const router = express.Router();
40
+ const { db } = require('../models/db');
41
+
42
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
43
+ const VALID_DOMAIN = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/i;
44
+ const normDomain = (d) => String(d || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
45
+ const validDomain = (d) => VALID_DOMAIN.test(d) && d.length <= 253;
46
+
47
+ const VALID_INTENT_CATEGORIES = ['booking','payment','search','auth','checkout','support','navigation','content','other'];
48
+ const VALID_OBSERVATIONS = ['fast','slow','reliable','flaky','success','failure','blocked','rate_limited'];
49
+ const VALID_FACT_TYPES = ['price','availability','rating','event','count','status'];
50
+
51
+ const DAILY_SALT = () =>
52
+ crypto.createHash('sha256').update(new Date().toISOString().slice(0,10) + ':wab-truth').digest('hex');
53
+
54
+ const anonAgent = (agentId) =>
55
+ crypto.createHash('sha256').update(String(agentId || 'anon') + DAILY_SALT()).digest('hex').slice(0, 16);
56
+
57
+ // Bootstrap schema (idempotent)
58
+ db.exec(`
59
+ CREATE TABLE IF NOT EXISTS semantic_memory (
60
+ id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL,
61
+ intent_category TEXT NOT NULL, observation TEXT NOT NULL,
62
+ latency_ms INTEGER, success INTEGER NOT NULL DEFAULT 1,
63
+ agent_hash TEXT NOT NULL, weight REAL NOT NULL DEFAULT 1.0,
64
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
65
+ );
66
+ CREATE INDEX IF NOT EXISTS idx_sem_mem_domain_intent ON semantic_memory(domain, intent_category, created_at DESC);
67
+
68
+ CREATE TABLE IF NOT EXISTS semantic_summary (
69
+ domain TEXT NOT NULL, intent_category TEXT NOT NULL,
70
+ sample_count INTEGER NOT NULL DEFAULT 0, success_rate REAL NOT NULL DEFAULT 0,
71
+ avg_latency_ms INTEGER, p95_latency_ms INTEGER,
72
+ reliability REAL NOT NULL DEFAULT 0, top_tags TEXT,
73
+ last_updated_at TEXT NOT NULL DEFAULT (datetime('now')),
74
+ PRIMARY KEY (domain, intent_category)
75
+ );
76
+
77
+ CREATE TABLE IF NOT EXISTS temporal_trust_snapshots (
78
+ id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL,
79
+ snapshot_at TEXT NOT NULL DEFAULT (datetime('now')),
80
+ score REAL NOT NULL DEFAULT 0, dns_stable INTEGER NOT NULL DEFAULT 1,
81
+ manifest_hash TEXT, cert_fingerprint TEXT,
82
+ observations INTEGER NOT NULL DEFAULT 0
83
+ );
84
+ CREATE INDEX IF NOT EXISTS idx_temp_trust_domain ON temporal_trust_snapshots(domain, snapshot_at DESC);
85
+
86
+ CREATE TABLE IF NOT EXISTS temporal_trust (
87
+ domain TEXT PRIMARY KEY, age_days INTEGER NOT NULL DEFAULT 0,
88
+ stability_score REAL NOT NULL DEFAULT 0, volatility REAL NOT NULL DEFAULT 0,
89
+ manifest_change_count INTEGER NOT NULL DEFAULT 0, dns_failure_count INTEGER NOT NULL DEFAULT 0,
90
+ classification TEXT NOT NULL DEFAULT 'new',
91
+ last_computed_at TEXT NOT NULL DEFAULT (datetime('now'))
92
+ );
93
+
94
+ CREATE TABLE IF NOT EXISTS action_graphs (
95
+ id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL,
96
+ intent_key TEXT NOT NULL, graph_json TEXT NOT NULL,
97
+ version INTEGER NOT NULL DEFAULT 1, active INTEGER NOT NULL DEFAULT 1,
98
+ owner_token_hash TEXT,
99
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
100
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
101
+ );
102
+ CREATE INDEX IF NOT EXISTS idx_action_graph_domain ON action_graphs(domain);
103
+
104
+ CREATE TABLE IF NOT EXISTS reality_facts (
105
+ id INTEGER PRIMARY KEY AUTOINCREMENT, fact_key TEXT NOT NULL,
106
+ fact_type TEXT NOT NULL, domain TEXT NOT NULL,
107
+ value_json TEXT NOT NULL, unit TEXT, agent_hash TEXT NOT NULL,
108
+ trust_weight REAL NOT NULL DEFAULT 1.0, expires_at TEXT,
109
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
110
+ );
111
+ CREATE INDEX IF NOT EXISTS idx_reality_key ON reality_facts(fact_key, created_at DESC);
112
+ CREATE INDEX IF NOT EXISTS idx_reality_type ON reality_facts(fact_type, created_at DESC);
113
+ `);
114
+
115
+ // ═════════════════════════════════════════════════════════════════════════════
116
+ // 1. SEMANTIC MEMORY NETWORK
117
+ // ═════════════════════════════════════════════════════════════════════════════
118
+
119
+ function refreshSemanticSummary(domain, intentCategory) {
120
+ const rows = db.prepare(
121
+ `SELECT observation, success, latency_ms FROM semantic_memory
122
+ WHERE domain = ? AND intent_category = ?
123
+ AND created_at >= datetime('now','-30 days')`
124
+ ).all(domain, intentCategory);
125
+
126
+ if (rows.length === 0) return null;
127
+
128
+ const successCount = rows.filter(r => r.success === 1).length;
129
+ const successRate = successCount / rows.length;
130
+ const latencies = rows.map(r => r.latency_ms).filter(x => Number.isFinite(x) && x >= 0).sort((a,b) => a-b);
131
+ const avgLatency = latencies.length ? Math.round(latencies.reduce((a,b) => a+b, 0) / latencies.length) : null;
132
+ const p95Latency = latencies.length ? latencies[Math.floor(latencies.length * 0.95)] || latencies[latencies.length - 1] : null;
133
+
134
+ // reliability = 1 - variance of success outcomes
135
+ const mean = successRate;
136
+ const variance = rows.reduce((acc, r) => acc + Math.pow((r.success ? 1 : 0) - mean, 2), 0) / rows.length;
137
+ const reliability = Math.max(0, Math.min(1, 1 - variance * 4));
138
+
139
+ const tagCounts = {};
140
+ for (const r of rows) tagCounts[r.observation] = (tagCounts[r.observation] || 0) + 1;
141
+ const topTags = Object.entries(tagCounts).sort((a,b) => b[1] - a[1]).slice(0, 5).map(([tag, count]) => ({ tag, count }));
142
+
143
+ db.prepare(`
144
+ INSERT INTO semantic_summary (domain, intent_category, sample_count, success_rate, avg_latency_ms, p95_latency_ms, reliability, top_tags, last_updated_at)
145
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
146
+ ON CONFLICT(domain, intent_category) DO UPDATE SET
147
+ sample_count = excluded.sample_count, success_rate = excluded.success_rate,
148
+ avg_latency_ms = excluded.avg_latency_ms, p95_latency_ms = excluded.p95_latency_ms,
149
+ reliability = excluded.reliability, top_tags = excluded.top_tags,
150
+ last_updated_at = datetime('now')
151
+ `).run(domain, intentCategory, rows.length, successRate, avgLatency, p95Latency, reliability, JSON.stringify(topTags));
152
+
153
+ return { sample_count: rows.length, success_rate: successRate, avg_latency_ms: avgLatency, p95_latency_ms: p95Latency, reliability, top_tags: topTags };
154
+ }
155
+
156
+ // POST /api/truth/memory/observe — agent submits an anonymized observation
157
+ router.post('/memory/observe', express.json({ limit: '4kb' }), (req, res) => {
158
+ const { domain, intent_category, observation, latency_ms, success = true, agent_id } = req.body || {};
159
+ const d = normDomain(domain);
160
+ if (!validDomain(d)) return res.status(400).json({ error: 'invalid_domain' });
161
+ if (!VALID_INTENT_CATEGORIES.includes(intent_category)) return res.status(400).json({ error: 'invalid_intent_category', allowed: VALID_INTENT_CATEGORIES });
162
+ if (!VALID_OBSERVATIONS.includes(observation)) return res.status(400).json({ error: 'invalid_observation', allowed: VALID_OBSERVATIONS });
163
+
164
+ const lat = Number.isFinite(Number(latency_ms)) ? Math.max(0, Math.min(60000, Number(latency_ms))) : null;
165
+ const succ = success ? 1 : 0;
166
+ const hash = anonAgent(agent_id);
167
+
168
+ db.prepare(
169
+ `INSERT INTO semantic_memory (domain, intent_category, observation, latency_ms, success, agent_hash) VALUES (?, ?, ?, ?, ?, ?)`
170
+ ).run(d, intent_category, observation, lat, succ, hash);
171
+
172
+ // Lazy refresh (only every ~10 inserts to avoid contention)
173
+ if (Math.random() < 0.1) refreshSemanticSummary(d, intent_category);
174
+
175
+ return res.json({ ok: true, domain: d, intent: intent_category, anonymized: true });
176
+ });
177
+
178
+ // GET /api/truth/memory/:domain — overall semantic summary
179
+ router.get('/memory/:domain', (req, res) => {
180
+ const domain = normDomain(req.params.domain);
181
+ if (!validDomain(domain)) return res.status(400).json({ error: 'invalid_domain' });
182
+
183
+ // Refresh stale categories
184
+ const categories = db.prepare(
185
+ `SELECT DISTINCT intent_category FROM semantic_memory WHERE domain = ?`
186
+ ).all(domain).map(r => r.intent_category);
187
+
188
+ for (const cat of categories) refreshSemanticSummary(domain, cat);
189
+
190
+ const summaries = db.prepare(
191
+ `SELECT intent_category, sample_count, success_rate, avg_latency_ms, p95_latency_ms, reliability, top_tags, last_updated_at
192
+ FROM semantic_summary WHERE domain = ? ORDER BY sample_count DESC`
193
+ ).all(domain).map(r => ({ ...r, top_tags: r.top_tags ? JSON.parse(r.top_tags) : [] }));
194
+
195
+ const overall = summaries.reduce((acc, s) => {
196
+ acc.total_samples += s.sample_count;
197
+ acc.weighted_success += s.success_rate * s.sample_count;
198
+ return acc;
199
+ }, { total_samples: 0, weighted_success: 0 });
200
+
201
+ return res.json({
202
+ domain,
203
+ summaries,
204
+ overall: {
205
+ total_samples: overall.total_samples,
206
+ avg_success_rate: overall.total_samples ? overall.weighted_success / overall.total_samples : null,
207
+ categories_tracked: summaries.length,
208
+ },
209
+ generated_at: new Date().toISOString(),
210
+ });
211
+ });
212
+
213
+ // GET /api/truth/memory/:domain/:intent — specific intent summary
214
+ router.get('/memory/:domain/:intent', (req, res) => {
215
+ const domain = normDomain(req.params.domain);
216
+ const intent = req.params.intent;
217
+ if (!validDomain(domain)) return res.status(400).json({ error: 'invalid_domain' });
218
+ if (!VALID_INTENT_CATEGORIES.includes(intent)) return res.status(400).json({ error: 'invalid_intent_category' });
219
+
220
+ const fresh = refreshSemanticSummary(domain, intent);
221
+ const row = db.prepare(
222
+ `SELECT * FROM semantic_summary WHERE domain = ? AND intent_category = ?`
223
+ ).get(domain, intent);
224
+
225
+ if (!row) return res.status(404).json({ error: 'no_data', domain, intent });
226
+
227
+ return res.json({
228
+ domain,
229
+ intent_category: intent,
230
+ ...row,
231
+ top_tags: row.top_tags ? JSON.parse(row.top_tags) : [],
232
+ generated_at: new Date().toISOString(),
233
+ });
234
+ });
235
+
236
+ // ═════════════════════════════════════════════════════════════════════════════
237
+ // 2. TEMPORAL TRUST
238
+ // ═════════════════════════════════════════════════════════════════════════════
239
+
240
+ function computeTemporalTrust(domain) {
241
+ const snapshots = db.prepare(
242
+ `SELECT score, dns_stable, manifest_hash, cert_fingerprint, snapshot_at
243
+ FROM temporal_trust_snapshots WHERE domain = ? ORDER BY snapshot_at ASC`
244
+ ).all(domain);
245
+
246
+ // First-seen from reputation_events if available, else from snapshots
247
+ const firstSeen = (() => {
248
+ try {
249
+ const r = db.prepare(`SELECT first_seen_at FROM wab_rep_scores WHERE domain = ?`).get(domain);
250
+ if (r && r.first_seen_at) return new Date(r.first_seen_at);
251
+ } catch { /* table may not exist */ }
252
+ if (snapshots.length) return new Date(snapshots[0].snapshot_at);
253
+ return new Date();
254
+ })();
255
+
256
+ const ageDays = Math.max(0, Math.floor((Date.now() - firstSeen.getTime()) / 86400000));
257
+
258
+ let dnsFailures = 0;
259
+ let manifestChanges = 0;
260
+ let prevManifest = null;
261
+ let prevCert = null;
262
+ let certChanges = 0;
263
+ for (const s of snapshots) {
264
+ if (!s.dns_stable) dnsFailures++;
265
+ if (prevManifest && s.manifest_hash && s.manifest_hash !== prevManifest) manifestChanges++;
266
+ if (prevCert && s.cert_fingerprint && s.cert_fingerprint !== prevCert) certChanges++;
267
+ prevManifest = s.manifest_hash || prevManifest;
268
+ prevCert = s.cert_fingerprint || prevCert;
269
+ }
270
+
271
+ // Score variance → volatility
272
+ const scores = snapshots.map(s => s.score).filter(Number.isFinite);
273
+ let volatility = 0;
274
+ if (scores.length >= 3) {
275
+ const mean = scores.reduce((a,b) => a+b, 0) / scores.length;
276
+ const variance = scores.reduce((acc, x) => acc + Math.pow(x - mean, 2), 0) / scores.length;
277
+ volatility = Math.min(1, Math.sqrt(variance) / 50); // normalize
278
+ }
279
+
280
+ // Stability score: rewards age + low volatility + few sudden changes
281
+ const ageFactor = Math.min(40, ageDays * 0.5); // up to 40pts (80 days = max)
282
+ const stableFactor = Math.max(0, 30 - manifestChanges * 5 - certChanges * 3); // up to 30pts
283
+ const dnsFactor = Math.max(0, 20 - dnsFailures * 4); // up to 20pts
284
+ const volFactor = Math.max(0, 10 - volatility * 10); // up to 10pts
285
+ const stabilityScore = Math.round(ageFactor + stableFactor + dnsFactor + volFactor);
286
+
287
+ // Classification
288
+ let classification = 'new';
289
+ if (ageDays < 7) classification = 'new';
290
+ else if (ageDays < 30 && stabilityScore >= 40) classification = 'emerging';
291
+ else if (ageDays >= 30 && stabilityScore >= 70) classification = 'established';
292
+ else if (ageDays >= 90 && stabilityScore >= 85 && volatility < 0.2) classification = 'flagship';
293
+ else if (manifestChanges >= 5 || volatility > 0.6 || dnsFailures >= 5) classification = 'suspect';
294
+
295
+ db.prepare(`
296
+ INSERT INTO temporal_trust (domain, age_days, stability_score, volatility, manifest_change_count, dns_failure_count, classification, last_computed_at)
297
+ VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
298
+ ON CONFLICT(domain) DO UPDATE SET
299
+ age_days = excluded.age_days, stability_score = excluded.stability_score,
300
+ volatility = excluded.volatility, manifest_change_count = excluded.manifest_change_count,
301
+ dns_failure_count = excluded.dns_failure_count, classification = excluded.classification,
302
+ last_computed_at = datetime('now')
303
+ `).run(domain, ageDays, stabilityScore, volatility, manifestChanges, dnsFailures, classification);
304
+
305
+ return { domain, age_days: ageDays, stability_score: stabilityScore, volatility: +volatility.toFixed(3),
306
+ manifest_change_count: manifestChanges, dns_failure_count: dnsFailures, classification,
307
+ snapshots_count: snapshots.length };
308
+ }
309
+
310
+ // GET /api/truth/temporal/:domain
311
+ router.get('/temporal/:domain', (req, res) => {
312
+ const domain = normDomain(req.params.domain);
313
+ if (!validDomain(domain)) return res.status(400).json({ error: 'invalid_domain' });
314
+
315
+ const result = computeTemporalTrust(domain);
316
+
317
+ // 30-day score timeline
318
+ const timeline = db.prepare(
319
+ `SELECT DATE(snapshot_at) as date, AVG(score) as avg_score, COUNT(*) as samples
320
+ FROM temporal_trust_snapshots WHERE domain = ? AND snapshot_at >= datetime('now','-30 days')
321
+ GROUP BY DATE(snapshot_at) ORDER BY date ASC`
322
+ ).all(domain);
323
+
324
+ return res.json({
325
+ ...result,
326
+ timeline,
327
+ badge: {
328
+ label: result.classification,
329
+ color: classifColor(result.classification),
330
+ icon: classifIcon(result.classification),
331
+ },
332
+ generated_at: new Date().toISOString(),
333
+ });
334
+ });
335
+
336
+ function classifColor(c) {
337
+ return { new:'#94a3b8', emerging:'#3b82f6', established:'#10b981', flagship:'#8b5cf6', suspect:'#ef4444' }[c] || '#94a3b8';
338
+ }
339
+ function classifIcon(c) {
340
+ return { new:'🌱', emerging:'📈', established:'🏛️', flagship:'⭐', suspect:'⚠️' }[c] || '•';
341
+ }
342
+
343
+ // POST /api/truth/temporal/snapshot — record a trust snapshot
344
+ router.post('/temporal/snapshot', express.json({ limit: '4kb' }), (req, res) => {
345
+ const { domain, score, dns_stable = true, manifest_hash, cert_fingerprint, observations = 0 } = req.body || {};
346
+ const d = normDomain(domain);
347
+ if (!validDomain(d)) return res.status(400).json({ error: 'invalid_domain' });
348
+ const s = Math.max(0, Math.min(100, Number(score) || 0));
349
+
350
+ db.prepare(
351
+ `INSERT INTO temporal_trust_snapshots (domain, score, dns_stable, manifest_hash, cert_fingerprint, observations)
352
+ VALUES (?, ?, ?, ?, ?, ?)`
353
+ ).run(d, s, dns_stable ? 1 : 0,
354
+ manifest_hash ? String(manifest_hash).slice(0, 128) : null,
355
+ cert_fingerprint ? String(cert_fingerprint).slice(0, 128) : null,
356
+ Number(observations) || 0);
357
+
358
+ return res.json({ ok: true, domain: d });
359
+ });
360
+
361
+ // ═════════════════════════════════════════════════════════════════════════════
362
+ // 3. INTENT-TO-ACTION BRIDGE (Action Graphs)
363
+ // ═════════════════════════════════════════════════════════════════════════════
364
+
365
+ function validateActionGraph(g) {
366
+ if (!g || typeof g !== 'object') return 'graph_required';
367
+ if (!Array.isArray(g.nodes) || g.nodes.length === 0) return 'nodes_required';
368
+ if (!Array.isArray(g.edges)) return 'edges_required';
369
+ for (const n of g.nodes) {
370
+ if (!n || typeof n !== 'object' || !n.id || !n.type) return 'invalid_node';
371
+ if (!['action','requirement','choice','outcome','start'].includes(n.type)) return 'bad_node_type';
372
+ }
373
+ const ids = new Set(g.nodes.map(n => n.id));
374
+ for (const e of g.edges) {
375
+ if (!e || !ids.has(e.from) || !ids.has(e.to)) return 'invalid_edge';
376
+ }
377
+ return null;
378
+ }
379
+
380
+ // POST /api/truth/action/register
381
+ router.post('/action/register', express.json({ limit: '64kb' }), (req, res) => {
382
+ const { domain, intent_key, graph, owner_token } = req.body || {};
383
+ const d = normDomain(domain);
384
+ if (!validDomain(d)) return res.status(400).json({ error: 'invalid_domain' });
385
+ if (!intent_key || typeof intent_key !== 'string' || intent_key.length > 64)
386
+ return res.status(400).json({ error: 'invalid_intent_key' });
387
+
388
+ const err = validateActionGraph(graph);
389
+ if (err) return res.status(400).json({ error: err });
390
+
391
+ const ownerHash = owner_token ? crypto.createHash('sha256').update(String(owner_token)).digest('hex') : null;
392
+
393
+ // Deactivate previous active version
394
+ db.prepare(`UPDATE action_graphs SET active = 0 WHERE domain = ? AND intent_key = ? AND active = 1`)
395
+ .run(d, intent_key);
396
+
397
+ const maxVer = db.prepare(`SELECT COALESCE(MAX(version),0) AS v FROM action_graphs WHERE domain = ? AND intent_key = ?`)
398
+ .get(d, intent_key).v;
399
+
400
+ const info = db.prepare(
401
+ `INSERT INTO action_graphs (domain, intent_key, graph_json, version, active, owner_token_hash)
402
+ VALUES (?, ?, ?, ?, 1, ?)`
403
+ ).run(d, intent_key, JSON.stringify(graph), maxVer + 1, ownerHash);
404
+
405
+ return res.json({ ok: true, domain: d, intent_key, version: maxVer + 1, id: info.lastInsertRowid });
406
+ });
407
+
408
+ // GET /api/truth/action/:domain/:intent
409
+ router.get('/action/:domain/:intent', (req, res) => {
410
+ const domain = normDomain(req.params.domain);
411
+ const intent = req.params.intent;
412
+ if (!validDomain(domain)) return res.status(400).json({ error: 'invalid_domain' });
413
+
414
+ const row = db.prepare(
415
+ `SELECT graph_json, version, updated_at FROM action_graphs
416
+ WHERE domain = ? AND intent_key = ? AND active = 1 ORDER BY version DESC LIMIT 1`
417
+ ).get(domain, intent);
418
+
419
+ if (!row) return res.status(404).json({ error: 'no_graph', domain, intent_key: intent });
420
+
421
+ let graph;
422
+ try { graph = JSON.parse(row.graph_json); }
423
+ catch { return res.status(500).json({ error: 'corrupt_graph' }); }
424
+
425
+ return res.json({ domain, intent_key: intent, version: row.version, graph, updated_at: row.updated_at });
426
+ });
427
+
428
+ // POST /api/truth/action/resolve — agent sends intent string, gets best matching graph
429
+ router.post('/action/resolve', express.json({ limit: '8kb' }), (req, res) => {
430
+ const { domain, intent_text, hints } = req.body || {};
431
+ const d = normDomain(domain);
432
+ if (!validDomain(d)) return res.status(400).json({ error: 'invalid_domain' });
433
+ if (!intent_text || typeof intent_text !== 'string') return res.status(400).json({ error: 'invalid_intent_text' });
434
+
435
+ const text = intent_text.toLowerCase();
436
+ const graphs = db.prepare(
437
+ `SELECT intent_key, graph_json, version FROM action_graphs WHERE domain = ? AND active = 1`
438
+ ).all(d);
439
+
440
+ if (graphs.length === 0) return res.status(404).json({ error: 'no_graphs_for_domain', domain: d });
441
+
442
+ // Simple scoring: keyword & label overlap
443
+ let best = null;
444
+ for (const g of graphs) {
445
+ let parsed; try { parsed = JSON.parse(g.graph_json); } catch { continue; }
446
+ let score = 0;
447
+ const key = g.intent_key.toLowerCase();
448
+ if (text.includes(key.replace(/_/g, ' '))) score += 60;
449
+ const labels = (parsed.nodes || []).map(n => String(n.label || '').toLowerCase());
450
+ for (const lbl of labels) if (lbl && text.includes(lbl)) score += 8;
451
+ const kws = parsed.keywords || [];
452
+ for (const kw of kws) if (text.includes(String(kw).toLowerCase())) score += 15;
453
+ if (Array.isArray(hints)) for (const h of hints) if (key.includes(String(h).toLowerCase())) score += 5;
454
+ if (!best || score > best.score) best = { intent_key: g.intent_key, score, graph: parsed, version: g.version };
455
+ }
456
+
457
+ if (!best || best.score === 0) return res.status(404).json({ error: 'no_match', domain: d });
458
+
459
+ // Log resolution (anonymized)
460
+ try {
461
+ db.prepare(
462
+ `INSERT INTO intent_resolutions (domain, intent_key, matched_action, confidence, context_keys) VALUES (?, ?, ?, ?, ?)`
463
+ ).run(d, best.intent_key, 'action_graph', best.score / 100, null);
464
+ } catch { /* table may not exist */ }
465
+
466
+ return res.json({ domain: d, matched_intent: best.intent_key, confidence: Math.min(1, best.score / 100),
467
+ version: best.version, graph: best.graph });
468
+ });
469
+
470
+ // ═════════════════════════════════════════════════════════════════════════════
471
+ // 4. REALITY ANCHOR
472
+ // ═════════════════════════════════════════════════════════════════════════════
473
+
474
+ function getDomainTrustWeight(domain) {
475
+ try {
476
+ const r = db.prepare(`SELECT score FROM wab_rep_scores WHERE domain = ?`).get(domain);
477
+ if (r && Number.isFinite(r.score)) return Math.max(0.1, Math.min(1.5, r.score / 100));
478
+ } catch { /* fallback */ }
479
+ return 1.0;
480
+ }
481
+
482
+ // POST /api/truth/reality/submit
483
+ router.post('/reality/submit', express.json({ limit: '8kb' }), (req, res) => {
484
+ const { fact_key, fact_type, domain, value, unit, agent_id, ttl_hours = 24 } = req.body || {};
485
+ if (!fact_key || typeof fact_key !== 'string' || fact_key.length > 200)
486
+ return res.status(400).json({ error: 'invalid_fact_key' });
487
+ if (!VALID_FACT_TYPES.includes(fact_type)) return res.status(400).json({ error: 'invalid_fact_type', allowed: VALID_FACT_TYPES });
488
+ const d = normDomain(domain);
489
+ if (!validDomain(d)) return res.status(400).json({ error: 'invalid_domain' });
490
+ if (value === undefined || value === null) return res.status(400).json({ error: 'value_required' });
491
+
492
+ const hash = anonAgent(agent_id);
493
+ const weight = getDomainTrustWeight(d);
494
+ const ttl = Math.max(1, Math.min(720, Number(ttl_hours) || 24));
495
+ const expiresAt = new Date(Date.now() + ttl * 3600000).toISOString().replace('T',' ').slice(0,19);
496
+
497
+ db.prepare(
498
+ `INSERT INTO reality_facts (fact_key, fact_type, domain, value_json, unit, agent_hash, trust_weight, expires_at)
499
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
500
+ ).run(fact_key.slice(0, 200), fact_type, d, JSON.stringify(value),
501
+ unit ? String(unit).slice(0, 16) : null, hash, weight, expiresAt);
502
+
503
+ return res.json({ ok: true, fact_key, anonymized: true, trust_weight: weight, expires_at: expiresAt });
504
+ });
505
+
506
+ // GET /api/truth/reality/:fact_key — verify against the network
507
+ router.get('/reality/:fact_key', (req, res) => {
508
+ const factKey = String(req.params.fact_key).slice(0, 200);
509
+
510
+ const rows = db.prepare(
511
+ `SELECT fact_type, domain, value_json, unit, trust_weight, agent_hash, created_at
512
+ FROM reality_facts
513
+ WHERE fact_key = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
514
+ ORDER BY created_at DESC LIMIT 500`
515
+ ).all(factKey);
516
+
517
+ if (rows.length === 0) return res.status(404).json({ error: 'no_observations', fact_key: factKey });
518
+
519
+ const factType = rows[0].fact_type;
520
+ const observations = rows.map(r => ({ ...r, value: safeParse(r.value_json) }));
521
+
522
+ // Numeric consensus
523
+ let consensus = null;
524
+ const numeric = observations
525
+ .map(o => ({ v: extractNumeric(o.value), w: o.trust_weight }))
526
+ .filter(x => Number.isFinite(x.v));
527
+
528
+ if (numeric.length >= 2) {
529
+ const totalW = numeric.reduce((a,b) => a + b.w, 0);
530
+ const weightedMean = numeric.reduce((a,b) => a + b.v * b.w, 0) / totalW;
531
+ const variance = numeric.reduce((a,b) => a + Math.pow(b.v - weightedMean, 2) * b.w, 0) / totalW;
532
+ const stddev = Math.sqrt(variance);
533
+ const sorted = numeric.map(x => x.v).sort((a,b) => a-b);
534
+ consensus = {
535
+ type: 'numeric',
536
+ weighted_mean: +weightedMean.toFixed(4),
537
+ median: sorted[Math.floor(sorted.length / 2)],
538
+ min: sorted[0],
539
+ max: sorted[sorted.length - 1],
540
+ stddev: +stddev.toFixed(4),
541
+ confidence: Math.max(0, Math.min(1, 1 - (stddev / Math.max(1, Math.abs(weightedMean))))),
542
+ };
543
+ } else {
544
+ // Categorical consensus (vote)
545
+ const tally = {};
546
+ for (const o of observations) {
547
+ const k = JSON.stringify(o.value);
548
+ tally[k] = (tally[k] || 0) + o.trust_weight;
549
+ }
550
+ const sorted = Object.entries(tally).sort((a,b) => b[1] - a[1]);
551
+ const top = sorted[0];
552
+ const totalW = sorted.reduce((a,b) => a + b[1], 0);
553
+ consensus = {
554
+ type: 'categorical',
555
+ top_value: safeParse(top[0]),
556
+ agreement: +(top[1] / totalW).toFixed(3),
557
+ distinct_values: sorted.length,
558
+ };
559
+ }
560
+
561
+ const uniqueAgents = new Set(observations.map(o => o.agent_hash)).size;
562
+ const uniqueDomains = new Set(observations.map(o => o.domain)).size;
563
+
564
+ return res.json({
565
+ fact_key: factKey,
566
+ fact_type: factType,
567
+ unit: rows[0].unit,
568
+ observations_count: observations.length,
569
+ unique_agents: uniqueAgents,
570
+ unique_domains: uniqueDomains,
571
+ consensus,
572
+ sources: observations.slice(0, 20).map(o => ({
573
+ domain: o.domain, value: o.value, trust_weight: o.trust_weight, at: o.created_at,
574
+ })),
575
+ generated_at: new Date().toISOString(),
576
+ });
577
+ });
578
+
579
+ function safeParse(s) { try { return JSON.parse(s); } catch { return s; } }
580
+ function extractNumeric(v) {
581
+ if (typeof v === 'number') return v;
582
+ if (v && typeof v === 'object' && Number.isFinite(v.amount)) return v.amount;
583
+ if (v && typeof v === 'object' && Number.isFinite(v.value)) return v.value;
584
+ const n = Number(v);
585
+ return Number.isFinite(n) ? n : NaN;
586
+ }
587
+
588
+ // POST /api/truth/reality/verify — bulk
589
+ router.post('/reality/verify', express.json({ limit: '8kb' }), (req, res) => {
590
+ const { fact_keys } = req.body || {};
591
+ if (!Array.isArray(fact_keys) || fact_keys.length === 0) return res.status(400).json({ error: 'fact_keys_required' });
592
+ if (fact_keys.length > 50) return res.status(400).json({ error: 'too_many', max: 50 });
593
+
594
+ const out = {};
595
+ for (const k of fact_keys) {
596
+ const key = String(k).slice(0, 200);
597
+ const rows = db.prepare(
598
+ `SELECT value_json, trust_weight FROM reality_facts
599
+ WHERE fact_key = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
600
+ ORDER BY created_at DESC LIMIT 100`
601
+ ).all(key);
602
+ if (rows.length === 0) { out[key] = { found: false }; continue; }
603
+ const nums = rows.map(r => ({ v: extractNumeric(safeParse(r.value_json)), w: r.trust_weight }))
604
+ .filter(x => Number.isFinite(x.v));
605
+ if (nums.length) {
606
+ const totalW = nums.reduce((a,b) => a + b.w, 0);
607
+ const mean = nums.reduce((a,b) => a + b.v * b.w, 0) / totalW;
608
+ out[key] = { found: true, type: 'numeric', value: +mean.toFixed(4), samples: rows.length };
609
+ } else {
610
+ out[key] = { found: true, type: 'categorical', samples: rows.length };
611
+ }
612
+ }
613
+
614
+ return res.json({ results: out, generated_at: new Date().toISOString() });
615
+ });
616
+
617
+ // ═════════════════════════════════════════════════════════════════════════════
618
+ // UNIFIED TRUTH PROFILE
619
+ // ═════════════════════════════════════════════════════════════════════════════
620
+
621
+ // GET /api/truth/profile/:domain — full Truth Layer profile for a domain
622
+ router.get('/profile/:domain', (req, res) => {
623
+ const domain = normDomain(req.params.domain);
624
+ if (!validDomain(domain)) return res.status(400).json({ error: 'invalid_domain' });
625
+
626
+ // Semantic
627
+ const categories = db.prepare(
628
+ `SELECT DISTINCT intent_category FROM semantic_memory WHERE domain = ?`
629
+ ).all(domain).map(r => r.intent_category);
630
+ for (const cat of categories) refreshSemanticSummary(domain, cat);
631
+ const semantic = db.prepare(
632
+ `SELECT intent_category, sample_count, success_rate, avg_latency_ms, reliability
633
+ FROM semantic_summary WHERE domain = ? ORDER BY sample_count DESC LIMIT 10`
634
+ ).all(domain);
635
+
636
+ // Temporal
637
+ const temporal = computeTemporalTrust(domain);
638
+
639
+ // Action graphs
640
+ const graphs = db.prepare(
641
+ `SELECT intent_key, version, updated_at FROM action_graphs WHERE domain = ? AND active = 1`
642
+ ).all(domain);
643
+
644
+ // Reality facts originating from this domain
645
+ const factsFromDomain = db.prepare(
646
+ `SELECT fact_type, COUNT(*) as count FROM reality_facts
647
+ WHERE domain = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
648
+ GROUP BY fact_type`
649
+ ).all(domain);
650
+
651
+ // Reputation (if available)
652
+ let reputation = null;
653
+ try {
654
+ const r = db.prepare(`SELECT score, label, trend FROM wab_rep_scores WHERE domain = ?`).get(domain);
655
+ if (r) reputation = r;
656
+ } catch { /* no-op */ }
657
+
658
+ return res.json({
659
+ domain,
660
+ truth_layer_version: '1.0',
661
+ reputation,
662
+ semantic: { categories: semantic, total_categories: semantic.length },
663
+ temporal,
664
+ action_graphs: { count: graphs.length, intents: graphs },
665
+ reality_anchor: { facts_published: factsFromDomain },
666
+ generated_at: new Date().toISOString(),
667
+ });
668
+ });
669
+
670
+ module.exports = { truthRouter: router };