@johnhenry/browsermesh-core 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/trust.mjs ADDED
@@ -0,0 +1,425 @@
1
+ /**
2
+ * clawser-mesh-trust.js -- Trust graph management.
3
+ *
4
+ * Float [0.0, 1.0] trust with multiplicative transitive decay,
5
+ * scope intersection, and reputation aggregation.
6
+ *
7
+ * Wraps mesh-primitives trust functions with higher-level management:
8
+ * scope-aware filtering, reputation computation, persistence, and
9
+ * JSON round-trip.
10
+ *
11
+ * No browser-only imports at module level.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-trust.test.mjs
15
+ */
16
+
17
+ import {
18
+ createTrustEdge,
19
+ computeTransitiveTrust,
20
+ TRUST_CATEGORIES,
21
+ } from '@johnhenry/browsermesh-primitives';
22
+
23
+ // Re-export primitives for consumers
24
+ export { TRUST_CATEGORIES, createTrustEdge, computeTransitiveTrust };
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // TrustGraph
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /**
31
+ * @typedef {object} TrustEdgeWrapper
32
+ * @property {import('./packages/mesh-primitives/src/trust.mjs').TrustEdge} edge
33
+ * @property {string[]} scopes - Scope tags for this trust relationship
34
+ */
35
+
36
+ /**
37
+ * @typedef {object} ReputationInfo
38
+ * @property {number} trustCount - Number of inbound trust edges
39
+ * @property {number} avgLevel - Average trust level
40
+ * @property {string[]} scopes - Union of all inbound scopes
41
+ */
42
+
43
+ /**
44
+ * @typedef {object} TransitiveTrustResult
45
+ * @property {number} level - Computed trust in [0.0, 1.0]
46
+ * @property {boolean} direct - Whether a direct edge exists
47
+ */
48
+
49
+ /**
50
+ * Scope-aware trust graph with transitive computation and persistence.
51
+ *
52
+ * @class
53
+ */
54
+ export class TrustGraph {
55
+ /**
56
+ * Internal storage: each entry holds the frozen TrustEdge from primitives
57
+ * plus associated scopes.
58
+ *
59
+ * @type {{ edge: object, scopes: string[] }[]}
60
+ */
61
+ #entries = [];
62
+
63
+ /** @type {Map<string, number>} keyed by `${fromId}|${toId}` → timestamp */
64
+ #interactions = new Map();
65
+
66
+ /** @type {*} */
67
+ #storage;
68
+
69
+ /**
70
+ * @param {object} [opts]
71
+ * @param {*} [opts.storage] - Optional persistence adapter
72
+ */
73
+ constructor(opts = {}) {
74
+ this.#storage = opts.storage || null;
75
+ }
76
+
77
+ // -- Edge management ----------------------------------------------------
78
+
79
+ /**
80
+ * Add or replace a trust edge.
81
+ *
82
+ * If an edge from `fromId` to `toId` already exists it is replaced.
83
+ *
84
+ * @param {string} fromId - Truster pod ID
85
+ * @param {string} toId - Trustee pod ID
86
+ * @param {number} level - Trust in [0.0, 1.0]
87
+ * @param {string[]} [scopes] - Scope tags (e.g. ['code', 'data'])
88
+ * @param {object} [opts]
89
+ * @param {string} [opts.category] - One of TRUST_CATEGORIES (default: DIRECT)
90
+ * @param {number} [opts.timestamp]
91
+ * @param {number} [opts.expires] - Optional expiration timestamp (ms)
92
+ * @returns {object} The created TrustEdge
93
+ */
94
+ addEdge(fromId, toId, level, scopes = [], opts = {}) {
95
+ if (typeof level !== 'number' || level < 0 || level > 1) {
96
+ throw new RangeError(`Trust level must be in [0.0, 1.0], got ${level}`);
97
+ }
98
+
99
+ // Remove existing edge between same pair
100
+ this.#entries = this.#entries.filter(
101
+ (e) => !(e.edge.from === fromId && e.edge.to === toId)
102
+ );
103
+
104
+ const edge = createTrustEdge({
105
+ from: fromId,
106
+ to: toId,
107
+ category: opts.category || TRUST_CATEGORIES.DIRECT,
108
+ value: level,
109
+ timestamp: opts.timestamp || Date.now(),
110
+ });
111
+
112
+ // Wrap with scopes and optional expires
113
+ this.#entries.push({
114
+ edge,
115
+ scopes: Array.isArray(scopes) ? [...scopes] : [],
116
+ expires: opts.expires ?? null,
117
+ });
118
+
119
+ return edge;
120
+ }
121
+
122
+ /**
123
+ * Remove a trust edge.
124
+ *
125
+ * @param {string} fromId
126
+ * @param {string} toId
127
+ * @returns {boolean} true if an edge was removed
128
+ */
129
+ removeEdge(fromId, toId) {
130
+ const before = this.#entries.length;
131
+ this.#entries = this.#entries.filter(
132
+ (e) => !(e.edge.from === fromId && e.edge.to === toId)
133
+ );
134
+ return this.#entries.length < before;
135
+ }
136
+
137
+ /**
138
+ * Get a direct edge (or null).
139
+ *
140
+ * @param {string} fromId
141
+ * @param {string} toId
142
+ * @returns {object|null} The TrustEdge or null
143
+ */
144
+ getEdge(fromId, toId) {
145
+ const found = this.#entries.find(
146
+ (e) => e.edge.from === fromId && e.edge.to === toId
147
+ );
148
+ return found ? found.edge : null;
149
+ }
150
+
151
+ /**
152
+ * Get the scopes associated with a direct edge.
153
+ *
154
+ * @param {string} fromId
155
+ * @param {string} toId
156
+ * @returns {string[]}
157
+ */
158
+ getEdgeScopes(fromId, toId) {
159
+ const found = this.#entries.find(
160
+ (e) => e.edge.from === fromId && e.edge.to === toId
161
+ );
162
+ return found ? [...found.scopes] : [];
163
+ }
164
+
165
+ // -- Trust computation --------------------------------------------------
166
+
167
+ /**
168
+ * Get the trust level from `fromId` to `toId`, checking direct first
169
+ * then falling back to transitive computation.
170
+ *
171
+ * @param {string} fromId
172
+ * @param {string} toId
173
+ * @returns {number} Trust in [0.0, 1.0]
174
+ */
175
+ getTrustLevel(fromId, toId) {
176
+ const direct = this.getEdge(fromId, toId);
177
+ if (direct) return direct.value;
178
+ const edges = this.#entries.map((e) => e.edge);
179
+ return computeTransitiveTrust(edges, fromId, toId);
180
+ }
181
+
182
+ /**
183
+ * Get transitive trust with metadata.
184
+ *
185
+ * @param {string} fromId
186
+ * @param {string} toId
187
+ * @param {number} [maxDepth=3]
188
+ * @returns {TransitiveTrustResult}
189
+ */
190
+ getTransitiveTrust(fromId, toId, maxDepth = 3) {
191
+ const edges = this.#entries.map((e) => e.edge);
192
+ const level = computeTransitiveTrust(edges, fromId, toId, maxDepth);
193
+ const direct = this.getEdge(fromId, toId);
194
+ return { level, direct: !!direct };
195
+ }
196
+
197
+ // -- Peer queries -------------------------------------------------------
198
+
199
+ /**
200
+ * Get all peers trusted by `fromId` at or above `minLevel`.
201
+ * Optionally filtered by scope.
202
+ *
203
+ * @param {string} fromId
204
+ * @param {number} [minLevel=0.01]
205
+ * @param {string|null} [scope=null] - Filter by scope tag
206
+ * @returns {string[]} Pod IDs of trusted peers
207
+ */
208
+ getTrustedPeers(fromId, minLevel = 0.01, scope = null) {
209
+ const peers = [];
210
+ for (const entry of this.#entries) {
211
+ if (entry.edge.from !== fromId) continue;
212
+ if (entry.edge.value < minLevel) continue;
213
+ if (scope && entry.scopes.length > 0 && !entry.scopes.includes(scope)) {
214
+ continue;
215
+ }
216
+ peers.push(entry.edge.to);
217
+ }
218
+ return peers;
219
+ }
220
+
221
+ /**
222
+ * Check whether `fromId` trusts `toId` at the given threshold,
223
+ * optionally within a specific scope.
224
+ *
225
+ * @param {string} fromId
226
+ * @param {string} toId
227
+ * @param {string|null} [scope=null]
228
+ * @param {number} [minLevel=0.25]
229
+ * @returns {boolean}
230
+ */
231
+ isTrusted(fromId, toId, scope = null, minLevel = 0.25) {
232
+ const level = this.getTrustLevel(fromId, toId);
233
+ if (level < minLevel) return false;
234
+ if (scope) {
235
+ const entry = this.#entries.find(
236
+ (e) => e.edge.from === fromId && e.edge.to === toId
237
+ );
238
+ if (entry && entry.scopes.length > 0 && !entry.scopes.includes(scope)) {
239
+ return false;
240
+ }
241
+ }
242
+ return true;
243
+ }
244
+
245
+ // -- Reputation ---------------------------------------------------------
246
+
247
+ /**
248
+ * Compute aggregate reputation for `toId` across all inbound edges.
249
+ *
250
+ * @param {string} toId
251
+ * @returns {ReputationInfo}
252
+ */
253
+ getReputation(toId) {
254
+ const inbound = this.#entries.filter((e) => e.edge.to === toId);
255
+ if (inbound.length === 0) {
256
+ return { trustCount: 0, avgLevel: 0, scopes: [] };
257
+ }
258
+
259
+ const total = inbound.reduce((sum, e) => sum + e.edge.value, 0);
260
+ const avgLevel = total / inbound.length;
261
+
262
+ const scopeSet = new Set();
263
+ for (const e of inbound) {
264
+ for (const s of e.scopes) scopeSet.add(s);
265
+ }
266
+
267
+ return {
268
+ trustCount: inbound.length,
269
+ avgLevel,
270
+ scopes: [...scopeSet],
271
+ };
272
+ }
273
+
274
+ // -- Reputation Decay ---------------------------------------------------
275
+
276
+ /**
277
+ * Record an interaction between two peers, updating the timestamp.
278
+ *
279
+ * @param {string} fromId
280
+ * @param {string} toId
281
+ * @param {number} [timestamp=Date.now()] - Override for testing
282
+ */
283
+ recordInteraction(fromId, toId, timestamp) {
284
+ this.#interactions.set(`${fromId}|${toId}`, timestamp ?? Date.now());
285
+ }
286
+
287
+ /**
288
+ * Get the timestamp of the last recorded interaction.
289
+ *
290
+ * @param {string} fromId
291
+ * @param {string} toId
292
+ * @returns {number|null} Timestamp or null if no interaction recorded
293
+ */
294
+ getLastInteraction(fromId, toId) {
295
+ return this.#interactions.get(`${fromId}|${toId}`) ?? null;
296
+ }
297
+
298
+ /**
299
+ * Get the trust level with time-based decay applied.
300
+ *
301
+ * If no interaction has been recorded for this pair, falls back to
302
+ * the raw `getTrustLevel()` with no decay applied.
303
+ *
304
+ * @param {string} fromId
305
+ * @param {string} toId
306
+ * @param {object} [opts]
307
+ * @param {number} [opts.decayRate=0.99] - Daily decay multiplier in (0, 1]
308
+ * @param {number} [opts.now] - Current time for testing
309
+ * @returns {number} Decayed trust in [0.0, 1.0]
310
+ */
311
+ getDecayedTrustLevel(fromId, toId, opts = {}) {
312
+ const level = this.getTrustLevel(fromId, toId);
313
+ const lastInteraction = this.getLastInteraction(fromId, toId);
314
+ if (lastInteraction === null) return level;
315
+
316
+ const now = opts.now ?? Date.now();
317
+ const decayRate = opts.decayRate ?? 0.99;
318
+ const daysSince = (now - lastInteraction) / (1000 * 60 * 60 * 24);
319
+ return level * Math.pow(decayRate, daysSince);
320
+ }
321
+
322
+ /**
323
+ * Batch-apply decay to all edges, pruning those that fall below threshold.
324
+ *
325
+ * For each edge, computes the decayed trust level. If the decayed value is
326
+ * below 0.01, the edge is pruned. If `maxAgeDays` is provided, edges whose
327
+ * last interaction is older than that are also pruned.
328
+ *
329
+ * @param {number|null} [maxAgeDays=null] - Prune interactions older than this
330
+ * @returns {number} Number of edges pruned
331
+ */
332
+ applyDecay(maxAgeDays = null) {
333
+ const now = Date.now();
334
+ const msPerDay = 1000 * 60 * 60 * 24;
335
+ let pruned = 0;
336
+
337
+ this.#entries = this.#entries.filter((entry) => {
338
+ const key = `${entry.edge.from}|${entry.edge.to}`;
339
+ const lastInteraction = this.#interactions.get(key);
340
+
341
+ // Check maxAgeDays constraint
342
+ if (maxAgeDays !== null && lastInteraction !== undefined) {
343
+ const ageDays = (now - lastInteraction) / msPerDay;
344
+ if (ageDays > maxAgeDays) {
345
+ this.#interactions.delete(key);
346
+ pruned++;
347
+ return false;
348
+ }
349
+ }
350
+
351
+ // Check decay threshold
352
+ if (lastInteraction !== undefined) {
353
+ const daysSince = (now - lastInteraction) / msPerDay;
354
+ const decayed = entry.edge.value * Math.pow(0.99, daysSince);
355
+ if (decayed < 0.01) {
356
+ this.#interactions.delete(key);
357
+ pruned++;
358
+ return false;
359
+ }
360
+ }
361
+
362
+ return true;
363
+ });
364
+
365
+ return pruned;
366
+ }
367
+
368
+ // -- Maintenance --------------------------------------------------------
369
+
370
+ /**
371
+ * Remove all expired edges.
372
+ *
373
+ * @param {number} [now=Date.now()]
374
+ * @returns {number} Number of edges pruned
375
+ */
376
+ pruneExpired(now = Date.now()) {
377
+ const before = this.#entries.length;
378
+ this.#entries = this.#entries.filter(
379
+ (e) => e.expires === null || e.expires > now
380
+ );
381
+ return before - this.#entries.length;
382
+ }
383
+
384
+ /** @returns {number} */
385
+ get size() {
386
+ return this.#entries.length;
387
+ }
388
+
389
+ // -- Serialization ------------------------------------------------------
390
+
391
+ /**
392
+ * Serialize the trust graph to a JSON-friendly array.
393
+ *
394
+ * @returns {object[]}
395
+ */
396
+ toJSON() {
397
+ return this.#entries.map((e) => ({
398
+ from: e.edge.from,
399
+ to: e.edge.to,
400
+ category: e.edge.category,
401
+ value: e.edge.value,
402
+ timestamp: e.edge.timestamp,
403
+ scopes: [...e.scopes],
404
+ expires: e.expires,
405
+ }));
406
+ }
407
+
408
+ /**
409
+ * Deserialize from an array of serialized edge data.
410
+ *
411
+ * @param {object[]} data
412
+ * @returns {TrustGraph}
413
+ */
414
+ static fromJSON(data) {
415
+ const tg = new TrustGraph();
416
+ for (const item of data) {
417
+ tg.addEdge(item.from, item.to, item.value, item.scopes || [], {
418
+ category: item.category,
419
+ timestamp: item.timestamp,
420
+ expires: item.expires ?? null,
421
+ });
422
+ }
423
+ return tg;
424
+ }
425
+ }