@mnemopay/sdk 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,214 @@
1
+ /**
2
+ * MnemoPay Adaptive Engine
3
+ *
4
+ * Business philosophy encoded in code: a system that doesn't learn from its
5
+ * own operations is dead. MnemoPay adapts to what moves the business forward
6
+ * — securely, with guardrails, with a full audit trail.
7
+ *
8
+ * The engine observes:
9
+ * - Agent behavior patterns (settlement rates, dispute frequency, charge velocity)
10
+ * - Revenue signals (which fee tiers produce the most volume, where agents churn)
11
+ * - Risk trends (emerging fraud patterns, anomaly drift, geographic shifts)
12
+ * - Memory health (recall quality, consolidation rates, storage efficiency)
13
+ *
14
+ * It adapts:
15
+ * - Fee tiers (within secure bounds) to maximize retention + revenue
16
+ * - Risk thresholds (tighten on emerging threats, loosen on proven agents)
17
+ * - Rate limits (reward trusted agents with higher throughput)
18
+ * - Memory decay (faster for low-value agents, slower for high-value)
19
+ *
20
+ * It NEVER:
21
+ * - Adapts below minimum security thresholds (floor on risk, max on limits)
22
+ * - Changes without an audit record
23
+ * - Overrides manual admin settings
24
+ * - Makes jumps > 20% in any single adaptation cycle
25
+ *
26
+ * This is the Agent FICO thesis: the longer an agent operates, the smarter
27
+ * the system becomes about that agent. Trust is earned, never assumed.
28
+ */
29
+ export interface AdaptiveConfig {
30
+ /** Enable adaptive optimization (default: true) */
31
+ enabled: boolean;
32
+ /** Minimum observations before adapting (default: 10) */
33
+ minObservations: number;
34
+ /** Maximum parameter change per cycle (0.2 = 20%) */
35
+ maxDeltaPercent: number;
36
+ /** Minimum cycle interval in minutes (default: 60) */
37
+ cycleIntervalMinutes: number;
38
+ /** Lock specific parameters from adaptation */
39
+ lockedParams: string[];
40
+ }
41
+ export declare const DEFAULT_ADAPTIVE_CONFIG: AdaptiveConfig;
42
+ export interface AgentInsight {
43
+ agentId: string;
44
+ /** Settlement success rate (0-1) */
45
+ settlementRate: number;
46
+ /** Average charge amount */
47
+ avgChargeAmount: number;
48
+ /** Disputes filed against this agent */
49
+ disputeCount: number;
50
+ /** Total revenue generated */
51
+ totalRevenue: number;
52
+ /** Memory utilization efficiency (active memories / total) */
53
+ memoryEfficiency: number;
54
+ /** Recommended risk tier: trusted | standard | elevated | restricted */
55
+ riskTier: "trusted" | "standard" | "elevated" | "restricted";
56
+ /** Recommended fee tier override (null = use default) */
57
+ recommendedFeeRate: number | null;
58
+ /** Recommended rate limit multiplier (1.0 = default, 2.0 = double) */
59
+ rateLimitMultiplier: number;
60
+ /** Agent health score (0-100) */
61
+ healthScore: number;
62
+ /** Observations count */
63
+ observations: number;
64
+ /** Last analyzed */
65
+ analyzedAt: Date;
66
+ }
67
+ export interface AdaptationRecord {
68
+ id: string;
69
+ /** What was adapted */
70
+ parameter: string;
71
+ /** Previous value */
72
+ previousValue: number;
73
+ /** New value */
74
+ newValue: number;
75
+ /** Why it was adapted */
76
+ reason: string;
77
+ /** Evidence that triggered the adaptation */
78
+ evidence: Record<string, number>;
79
+ /** When the adaptation was applied */
80
+ appliedAt: Date;
81
+ /** Whether it was actually applied (false if locked or vetoed) */
82
+ applied: boolean;
83
+ /** Veto reason if not applied */
84
+ vetoReason?: string;
85
+ }
86
+ export interface BusinessMetrics {
87
+ /** Total platform revenue (from fees) */
88
+ totalRevenue: number;
89
+ /** Revenue this cycle */
90
+ cycleRevenue: number;
91
+ /** Total agents observed */
92
+ totalAgents: number;
93
+ /** Agents with settlement rate > 80% */
94
+ trustedAgents: number;
95
+ /** Agents with disputes */
96
+ disputedAgents: number;
97
+ /** Platform-wide settlement rate */
98
+ platformSettlementRate: number;
99
+ /** Average memory utilization across agents */
100
+ avgMemoryUtilization: number;
101
+ /** Fraud detection rate (blocked/total) */
102
+ fraudDetectionRate: number;
103
+ /** System health (0-100) */
104
+ systemHealth: number;
105
+ /** Computed at */
106
+ computedAt: Date;
107
+ }
108
+ export type AdaptiveEventType = "charge" | "settle" | "refund" | "dispute" | "memory_store" | "memory_recall" | "fraud_block" | "fraud_flag";
109
+ export interface AdaptiveEvent {
110
+ type: AdaptiveEventType;
111
+ agentId: string;
112
+ amount?: number;
113
+ timestamp: number;
114
+ metadata?: Record<string, unknown>;
115
+ }
116
+ declare const SECURE_BOUNDS: {
117
+ readonly feeRate: {
118
+ readonly min: 0.005;
119
+ readonly max: 0.05;
120
+ };
121
+ readonly blockThreshold: {
122
+ readonly min: 0.3;
123
+ readonly max: 0.95;
124
+ };
125
+ readonly flagThreshold: {
126
+ readonly min: 0.1;
127
+ readonly max: 0.7;
128
+ };
129
+ readonly rateLimitMultiplier: {
130
+ readonly min: 0.5;
131
+ readonly max: 3;
132
+ };
133
+ readonly decayRate: {
134
+ readonly min: 0.001;
135
+ readonly max: 0.5;
136
+ };
137
+ readonly settlementHoldMinutes: {
138
+ readonly min: 5;
139
+ readonly max: 1440;
140
+ };
141
+ };
142
+ export declare class AdaptiveEngine {
143
+ private config;
144
+ private events;
145
+ private insights;
146
+ private adaptations;
147
+ private lastCycleAt;
148
+ /** Manual overrides set by admin — these are never auto-changed */
149
+ private adminOverrides;
150
+ private eventCounter;
151
+ constructor(config?: Partial<AdaptiveConfig>);
152
+ /**
153
+ * Record an operational event. The engine learns from every operation.
154
+ */
155
+ observe(event: AdaptiveEvent): void;
156
+ /**
157
+ * Analyze an agent's behavioral pattern and produce an insight profile.
158
+ * This is the "Agent FICO score" — built from real operational data.
159
+ */
160
+ analyzeAgent(agentId: string): AgentInsight;
161
+ /**
162
+ * Compute platform-wide business intelligence.
163
+ */
164
+ computeMetrics(): BusinessMetrics;
165
+ /**
166
+ * Run an adaptation cycle. Analyzes all data, proposes parameter changes,
167
+ * validates against secure bounds, and returns what was (or would be) changed.
168
+ *
169
+ * Returns proposed adaptations. Call applyAdaptations() to commit them.
170
+ */
171
+ runCycle(): AdaptationRecord[];
172
+ /**
173
+ * Lock a parameter from adaptive changes. Admin decisions override AI.
174
+ */
175
+ lockParam(param: string): void;
176
+ /**
177
+ * Unlock a parameter for adaptive changes.
178
+ */
179
+ unlockParam(param: string): void;
180
+ /**
181
+ * Set an admin override. This value will be used instead of adaptive suggestions.
182
+ */
183
+ setOverride(param: string, value: number): void;
184
+ /**
185
+ * Remove an admin override, allowing adaptive control.
186
+ */
187
+ removeOverride(param: string): void;
188
+ /**
189
+ * Get the effective value for a parameter (admin override > adaptation > default).
190
+ */
191
+ getEffectiveValue(param: string, defaultValue: number): number;
192
+ getInsight(agentId: string): AgentInsight | undefined;
193
+ getAdaptations(limit?: number): AdaptationRecord[];
194
+ get totalEvents(): number;
195
+ get secureBounds(): typeof SECURE_BOUNDS;
196
+ serialize(): {
197
+ config: AdaptiveConfig;
198
+ insights: [string, AgentInsight][];
199
+ adaptations: AdaptationRecord[];
200
+ overrides: [string, number][];
201
+ eventCount: number;
202
+ };
203
+ static deserialize(data: ReturnType<AdaptiveEngine["serialize"]>): AdaptiveEngine;
204
+ private isLocked;
205
+ private clamp;
206
+ /**
207
+ * Limit how much a parameter can change in one cycle.
208
+ * Prevents wild swings — stability is a security property.
209
+ */
210
+ private limitDelta;
211
+ private createRecord;
212
+ }
213
+ export {};
214
+ //# sourceMappingURL=adaptive.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adaptive.d.ts","sourceRoot":"","sources":["../src/adaptive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAIH,MAAM,WAAW,cAAc;IAC7B,mDAAmD;IACnD,OAAO,EAAE,OAAO,CAAC;IACjB,yDAAyD;IACzD,eAAe,EAAE,MAAM,CAAC;IACxB,qDAAqD;IACrD,eAAe,EAAE,MAAM,CAAC;IACxB,sDAAsD;IACtD,oBAAoB,EAAE,MAAM,CAAC;IAC7B,+CAA+C;IAC/C,YAAY,EAAE,MAAM,EAAE,CAAC;CACxB;AAED,eAAO,MAAM,uBAAuB,EAAE,cAMrC,CAAC;AAEF,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,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H,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAM9B;;OAEG;IACH,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAIhC;;OAEG;IACH,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAI/C;;OAEG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAInC;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM;IAW9D,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;IAIrD,cAAc,CAAC,KAAK,SAAK,GAAG,gBAAgB,EAAE;IAI9C,IAAI,WAAW,IAAI,MAAM,CAExB;IAED,IAAI,YAAY,IAAI,OAAO,aAAa,CAEvC;IAID,SAAS,IAAI;QACX,MAAM,EAAE,cAAc,CAAC;QACvB,QAAQ,EAAE,CAAC,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC;QACnC,WAAW,EAAE,gBAAgB,EAAE,CAAC;QAChC,SAAS,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;QAC9B,UAAU,EAAE,MAAM,CAAC;KACpB;IAUD,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,UAAU,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,GAAG,cAAc;IAmBjF,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,KAAK;IAIb;;;OAGG;IACH,OAAO,CAAC,UAAU;IASlB,OAAO,CAAC,YAAY;CAoBrB"}
@@ -0,0 +1,389 @@
1
+ "use strict";
2
+ /**
3
+ * MnemoPay Adaptive Engine
4
+ *
5
+ * Business philosophy encoded in code: a system that doesn't learn from its
6
+ * own operations is dead. MnemoPay adapts to what moves the business forward
7
+ * — securely, with guardrails, with a full audit trail.
8
+ *
9
+ * The engine observes:
10
+ * - Agent behavior patterns (settlement rates, dispute frequency, charge velocity)
11
+ * - Revenue signals (which fee tiers produce the most volume, where agents churn)
12
+ * - Risk trends (emerging fraud patterns, anomaly drift, geographic shifts)
13
+ * - Memory health (recall quality, consolidation rates, storage efficiency)
14
+ *
15
+ * It adapts:
16
+ * - Fee tiers (within secure bounds) to maximize retention + revenue
17
+ * - Risk thresholds (tighten on emerging threats, loosen on proven agents)
18
+ * - Rate limits (reward trusted agents with higher throughput)
19
+ * - Memory decay (faster for low-value agents, slower for high-value)
20
+ *
21
+ * It NEVER:
22
+ * - Adapts below minimum security thresholds (floor on risk, max on limits)
23
+ * - Changes without an audit record
24
+ * - Overrides manual admin settings
25
+ * - Makes jumps > 20% in any single adaptation cycle
26
+ *
27
+ * This is the Agent FICO thesis: the longer an agent operates, the smarter
28
+ * the system becomes about that agent. Trust is earned, never assumed.
29
+ */
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.AdaptiveEngine = exports.DEFAULT_ADAPTIVE_CONFIG = void 0;
32
+ exports.DEFAULT_ADAPTIVE_CONFIG = {
33
+ enabled: true,
34
+ minObservations: 10,
35
+ maxDeltaPercent: 0.2,
36
+ cycleIntervalMinutes: 60,
37
+ lockedParams: [],
38
+ };
39
+ // ─── Secure Bounds ──────────────────────────────────────────────────────────
40
+ // These are HARD floors and ceilings. The adaptive engine cannot breach them.
41
+ // This is the "never adapt yourself into an insecure state" principle.
42
+ const SECURE_BOUNDS = {
43
+ // Fee rates: never go below 0.5% (business viability) or above 5% (market competitiveness)
44
+ feeRate: { min: 0.005, max: 0.05 },
45
+ // Risk block threshold: never go above 0.95 (must always be able to block)
46
+ blockThreshold: { min: 0.3, max: 0.95 },
47
+ // Flag threshold: never go above block threshold
48
+ flagThreshold: { min: 0.1, max: 0.7 },
49
+ // Rate limit multiplier: trusted agents get up to 3x, never below 0.5x
50
+ rateLimitMultiplier: { min: 0.5, max: 3.0 },
51
+ // Memory decay: never so fast memories die in < 1hr, never so slow they never decay
52
+ decayRate: { min: 0.001, max: 0.5 },
53
+ // Settlement hold: never below 5 minutes (gives rail time to capture)
54
+ settlementHoldMinutes: { min: 5, max: 1440 },
55
+ };
56
+ // ─── Adaptive Engine ────────────────────────────────────────────────────────
57
+ class AdaptiveEngine {
58
+ config;
59
+ events = [];
60
+ insights = new Map();
61
+ adaptations = [];
62
+ lastCycleAt = 0;
63
+ /** Manual overrides set by admin — these are never auto-changed */
64
+ adminOverrides = new Map();
65
+ eventCounter = 0;
66
+ constructor(config) {
67
+ this.config = { ...exports.DEFAULT_ADAPTIVE_CONFIG, ...config };
68
+ }
69
+ // ── Event Ingestion ────────────────────────────────────────────────────
70
+ /**
71
+ * Record an operational event. The engine learns from every operation.
72
+ */
73
+ observe(event) {
74
+ this.events.push(event);
75
+ this.eventCounter++;
76
+ // Rolling window: keep last 50K events to bound memory usage
77
+ if (this.events.length > 50_000) {
78
+ this.events = this.events.slice(-25_000);
79
+ }
80
+ }
81
+ // ── Agent Analysis ─────────────────────────────────────────────────────
82
+ /**
83
+ * Analyze an agent's behavioral pattern and produce an insight profile.
84
+ * This is the "Agent FICO score" — built from real operational data.
85
+ */
86
+ analyzeAgent(agentId) {
87
+ const agentEvents = this.events.filter(e => e.agentId === agentId);
88
+ const charges = agentEvents.filter(e => e.type === "charge");
89
+ const settles = agentEvents.filter(e => e.type === "settle");
90
+ const refunds = agentEvents.filter(e => e.type === "refund");
91
+ const disputes = agentEvents.filter(e => e.type === "dispute");
92
+ const memStores = agentEvents.filter(e => e.type === "memory_store");
93
+ const memRecalls = agentEvents.filter(e => e.type === "memory_recall");
94
+ const fraudBlocks = agentEvents.filter(e => e.type === "fraud_block");
95
+ const totalCompleted = settles.length + refunds.length;
96
+ const settlementRate = totalCompleted > 0 ? settles.length / totalCompleted : 0;
97
+ const avgCharge = charges.length > 0
98
+ ? charges.reduce((sum, e) => sum + (e.amount ?? 0), 0) / charges.length
99
+ : 0;
100
+ const totalRevenue = settles.reduce((sum, e) => sum + (e.amount ?? 0) * 0.019, 0);
101
+ // Memory efficiency: recalls / stores (how often are stored memories actually used?)
102
+ const memoryEfficiency = memStores.length > 0
103
+ ? Math.min(memRecalls.length / memStores.length, 1.0)
104
+ : 0;
105
+ // Risk tier determination
106
+ let riskTier = "standard";
107
+ if (disputes.length > 0 || fraudBlocks.length > 2) {
108
+ riskTier = disputes.length >= 3 ? "restricted" : "elevated";
109
+ }
110
+ else if (settlementRate > 0.9 && settles.length >= 10) {
111
+ riskTier = "trusted";
112
+ }
113
+ // Recommended fee rate: reward high-volume, high-settlement agents
114
+ let recommendedFeeRate = null;
115
+ const totalVolume = settles.reduce((sum, e) => sum + (e.amount ?? 0), 0);
116
+ if (totalVolume >= 100_000)
117
+ recommendedFeeRate = 0.010;
118
+ else if (totalVolume >= 10_000)
119
+ recommendedFeeRate = 0.015;
120
+ // Rate limit multiplier: trusted agents earn higher throughput
121
+ let rateLimitMultiplier = 1.0;
122
+ if (riskTier === "trusted")
123
+ rateLimitMultiplier = 2.0;
124
+ else if (riskTier === "elevated")
125
+ rateLimitMultiplier = 0.7;
126
+ else if (riskTier === "restricted")
127
+ rateLimitMultiplier = 0.5;
128
+ // Health score (0-100)
129
+ let healthScore = 50;
130
+ healthScore += settlementRate * 20; // Up to +20 for settlements
131
+ healthScore += Math.min(settles.length, 50) * 0.2; // Up to +10 for volume
132
+ healthScore += memoryEfficiency * 10; // Up to +10 for memory usage
133
+ healthScore -= disputes.length * 5; // -5 per dispute
134
+ healthScore -= fraudBlocks.length * 10; // -10 per fraud block
135
+ healthScore = Math.max(0, Math.min(100, healthScore));
136
+ const insight = {
137
+ agentId,
138
+ settlementRate,
139
+ avgChargeAmount: Math.round(avgCharge * 100) / 100,
140
+ disputeCount: disputes.length,
141
+ totalRevenue: Math.round(totalRevenue * 100) / 100,
142
+ memoryEfficiency: Math.round(memoryEfficiency * 100) / 100,
143
+ riskTier,
144
+ recommendedFeeRate,
145
+ rateLimitMultiplier,
146
+ healthScore: Math.round(healthScore),
147
+ observations: agentEvents.length,
148
+ analyzedAt: new Date(),
149
+ };
150
+ this.insights.set(agentId, insight);
151
+ return insight;
152
+ }
153
+ // ── Business Metrics ───────────────────────────────────────────────────
154
+ /**
155
+ * Compute platform-wide business intelligence.
156
+ */
157
+ computeMetrics() {
158
+ const agentIds = new Set(this.events.map(e => e.agentId));
159
+ const settles = this.events.filter(e => e.type === "settle");
160
+ const refunds = this.events.filter(e => e.type === "refund");
161
+ const charges = this.events.filter(e => e.type === "charge");
162
+ const disputes = this.events.filter(e => e.type === "dispute");
163
+ const fraudBlocks = this.events.filter(e => e.type === "fraud_block");
164
+ const memStores = this.events.filter(e => e.type === "memory_store");
165
+ const memRecalls = this.events.filter(e => e.type === "memory_recall");
166
+ const totalRevenue = settles.reduce((sum, e) => sum + (e.amount ?? 0) * 0.019, 0);
167
+ const totalCompleted = settles.length + refunds.length;
168
+ const platformSettlementRate = totalCompleted > 0 ? settles.length / totalCompleted : 0;
169
+ // Cycle revenue (last cycle interval)
170
+ const cycleStart = Date.now() - this.config.cycleIntervalMinutes * 60_000;
171
+ const cycleSettles = settles.filter(e => e.timestamp > cycleStart);
172
+ const cycleRevenue = cycleSettles.reduce((sum, e) => sum + (e.amount ?? 0) * 0.019, 0);
173
+ // Analyze all agents for tier counts
174
+ let trustedCount = 0;
175
+ let disputedAgentIds = new Set();
176
+ for (const agentId of agentIds) {
177
+ const insight = this.analyzeAgent(agentId);
178
+ if (insight.riskTier === "trusted")
179
+ trustedCount++;
180
+ if (insight.disputeCount > 0)
181
+ disputedAgentIds.add(agentId);
182
+ }
183
+ const avgMemUtil = memStores.length > 0
184
+ ? Math.min(memRecalls.length / memStores.length, 1.0)
185
+ : 0;
186
+ const fraudDetectionRate = charges.length > 0
187
+ ? fraudBlocks.length / charges.length
188
+ : 0;
189
+ // System health: composite score
190
+ let systemHealth = 70; // baseline
191
+ systemHealth += platformSettlementRate * 15;
192
+ systemHealth -= (disputes.length / Math.max(settles.length, 1)) * 20;
193
+ systemHealth += avgMemUtil * 5;
194
+ systemHealth = Math.max(0, Math.min(100, Math.round(systemHealth)));
195
+ return {
196
+ totalRevenue: Math.round(totalRevenue * 100) / 100,
197
+ cycleRevenue: Math.round(cycleRevenue * 100) / 100,
198
+ totalAgents: agentIds.size,
199
+ trustedAgents: trustedCount,
200
+ disputedAgents: disputedAgentIds.size,
201
+ platformSettlementRate: Math.round(platformSettlementRate * 100) / 100,
202
+ avgMemoryUtilization: Math.round(avgMemUtil * 100) / 100,
203
+ fraudDetectionRate: Math.round(fraudDetectionRate * 1000) / 1000,
204
+ systemHealth,
205
+ computedAt: new Date(),
206
+ };
207
+ }
208
+ // ── Adaptive Optimization ──────────────────────────────────────────────
209
+ /**
210
+ * Run an adaptation cycle. Analyzes all data, proposes parameter changes,
211
+ * validates against secure bounds, and returns what was (or would be) changed.
212
+ *
213
+ * Returns proposed adaptations. Call applyAdaptations() to commit them.
214
+ */
215
+ runCycle() {
216
+ if (!this.config.enabled)
217
+ return [];
218
+ // Enforce minimum cycle interval
219
+ const now = Date.now();
220
+ if (now - this.lastCycleAt < this.config.cycleIntervalMinutes * 60_000) {
221
+ return [];
222
+ }
223
+ this.lastCycleAt = now;
224
+ if (this.events.length < this.config.minObservations) {
225
+ return [];
226
+ }
227
+ const metrics = this.computeMetrics();
228
+ const proposals = [];
229
+ // ── Adapt fee rate based on platform settlement rate ──────────────
230
+ if (!this.isLocked("feeRate")) {
231
+ const currentRate = 0.019; // default
232
+ let targetRate = currentRate;
233
+ // If settlement rate is high (> 90%), reward with lower fees
234
+ if (metrics.platformSettlementRate > 0.9 && metrics.totalAgents >= 5) {
235
+ targetRate = currentRate * 0.95; // 5% reduction
236
+ }
237
+ // If dispute rate is high, increase fees to cover risk
238
+ if (metrics.disputedAgents / Math.max(metrics.totalAgents, 1) > 0.1) {
239
+ targetRate = currentRate * 1.05; // 5% increase
240
+ }
241
+ targetRate = this.clamp(targetRate, SECURE_BOUNDS.feeRate.min, SECURE_BOUNDS.feeRate.max);
242
+ targetRate = this.limitDelta(currentRate, targetRate);
243
+ if (Math.abs(targetRate - currentRate) > 0.0001) {
244
+ proposals.push(this.createRecord("feeRate", currentRate, targetRate, metrics.platformSettlementRate > 0.9
245
+ ? "High platform settlement rate — rewarding ecosystem"
246
+ : "Elevated dispute rate — increasing to cover risk", { settlementRate: metrics.platformSettlementRate, disputeRatio: metrics.disputedAgents / Math.max(metrics.totalAgents, 1) }));
247
+ }
248
+ }
249
+ // ── Adapt risk thresholds based on fraud patterns ─────────────────
250
+ if (!this.isLocked("blockThreshold")) {
251
+ const currentBlock = 0.75;
252
+ let targetBlock = currentBlock;
253
+ // If fraud detection is catching too many (> 10% of charges), system may be too aggressive
254
+ if (metrics.fraudDetectionRate > 0.10) {
255
+ targetBlock = currentBlock * 1.03; // loosen slightly
256
+ }
257
+ // If zero fraud but many agents, may be too loose
258
+ if (metrics.fraudDetectionRate < 0.001 && metrics.totalAgents > 20) {
259
+ targetBlock = currentBlock * 0.98; // tighten slightly
260
+ }
261
+ targetBlock = this.clamp(targetBlock, SECURE_BOUNDS.blockThreshold.min, SECURE_BOUNDS.blockThreshold.max);
262
+ targetBlock = this.limitDelta(currentBlock, targetBlock);
263
+ if (Math.abs(targetBlock - currentBlock) > 0.001) {
264
+ proposals.push(this.createRecord("blockThreshold", currentBlock, targetBlock, metrics.fraudDetectionRate > 0.10
265
+ ? "Fraud detection too aggressive — loosening to reduce false positives"
266
+ : "Low fraud detection with many agents — tightening for safety", { fraudRate: metrics.fraudDetectionRate, totalAgents: metrics.totalAgents }));
267
+ }
268
+ }
269
+ this.adaptations.push(...proposals);
270
+ // Cap adaptation history at 1000 records
271
+ if (this.adaptations.length > 1000) {
272
+ this.adaptations = this.adaptations.slice(-500);
273
+ }
274
+ return proposals;
275
+ }
276
+ // ── Admin Controls ─────────────────────────────────────────────────────
277
+ /**
278
+ * Lock a parameter from adaptive changes. Admin decisions override AI.
279
+ */
280
+ lockParam(param) {
281
+ if (!this.config.lockedParams.includes(param)) {
282
+ this.config.lockedParams.push(param);
283
+ }
284
+ }
285
+ /**
286
+ * Unlock a parameter for adaptive changes.
287
+ */
288
+ unlockParam(param) {
289
+ this.config.lockedParams = this.config.lockedParams.filter(p => p !== param);
290
+ }
291
+ /**
292
+ * Set an admin override. This value will be used instead of adaptive suggestions.
293
+ */
294
+ setOverride(param, value) {
295
+ this.adminOverrides.set(param, value);
296
+ }
297
+ /**
298
+ * Remove an admin override, allowing adaptive control.
299
+ */
300
+ removeOverride(param) {
301
+ this.adminOverrides.delete(param);
302
+ }
303
+ /**
304
+ * Get the effective value for a parameter (admin override > adaptation > default).
305
+ */
306
+ getEffectiveValue(param, defaultValue) {
307
+ if (this.adminOverrides.has(param))
308
+ return this.adminOverrides.get(param);
309
+ // Check last applied adaptation
310
+ const lastAdaptation = [...this.adaptations]
311
+ .reverse()
312
+ .find(a => a.parameter === param && a.applied);
313
+ return lastAdaptation ? lastAdaptation.newValue : defaultValue;
314
+ }
315
+ // ── Getters ────────────────────────────────────────────────────────────
316
+ getInsight(agentId) {
317
+ return this.insights.get(agentId);
318
+ }
319
+ getAdaptations(limit = 50) {
320
+ return this.adaptations.slice(-limit);
321
+ }
322
+ get totalEvents() {
323
+ return this.eventCounter;
324
+ }
325
+ get secureBounds() {
326
+ return SECURE_BOUNDS;
327
+ }
328
+ // ── Serialization ──────────────────────────────────────────────────────
329
+ serialize() {
330
+ return {
331
+ config: this.config,
332
+ insights: Array.from(this.insights.entries()),
333
+ adaptations: this.adaptations.slice(-200), // Keep recent history
334
+ overrides: Array.from(this.adminOverrides.entries()),
335
+ eventCount: this.eventCounter,
336
+ };
337
+ }
338
+ static deserialize(data) {
339
+ const engine = new AdaptiveEngine(data.config);
340
+ for (const [id, insight] of data.insights) {
341
+ insight.analyzedAt = new Date(insight.analyzedAt);
342
+ engine.insights.set(id, insight);
343
+ }
344
+ engine.adaptations = data.adaptations.map(a => ({
345
+ ...a,
346
+ appliedAt: new Date(a.appliedAt),
347
+ }));
348
+ for (const [key, val] of data.overrides) {
349
+ engine.adminOverrides.set(key, val);
350
+ }
351
+ engine.eventCounter = data.eventCount ?? 0;
352
+ return engine;
353
+ }
354
+ // ── Internal Utilities ─────────────────────────────────────────────────
355
+ isLocked(param) {
356
+ return this.config.lockedParams.includes(param) || this.adminOverrides.has(param);
357
+ }
358
+ clamp(value, min, max) {
359
+ return Math.max(min, Math.min(max, value));
360
+ }
361
+ /**
362
+ * Limit how much a parameter can change in one cycle.
363
+ * Prevents wild swings — stability is a security property.
364
+ */
365
+ limitDelta(current, target) {
366
+ const maxDelta = current * this.config.maxDeltaPercent;
367
+ const delta = target - current;
368
+ if (Math.abs(delta) > maxDelta) {
369
+ return current + Math.sign(delta) * maxDelta;
370
+ }
371
+ return target;
372
+ }
373
+ createRecord(parameter, previousValue, newValue, reason, evidence) {
374
+ const isLocked = this.isLocked(parameter);
375
+ return {
376
+ id: `adapt_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
377
+ parameter,
378
+ previousValue: Math.round(previousValue * 10000) / 10000,
379
+ newValue: Math.round(newValue * 10000) / 10000,
380
+ reason,
381
+ evidence,
382
+ appliedAt: new Date(),
383
+ applied: !isLocked,
384
+ vetoReason: isLocked ? `Parameter '${parameter}' is locked or has admin override` : undefined,
385
+ };
386
+ }
387
+ }
388
+ exports.AdaptiveEngine = AdaptiveEngine;
389
+ //# sourceMappingURL=adaptive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adaptive.js","sourceRoot":"","sources":["../src/adaptive.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;;;AAiBU,QAAA,uBAAuB,GAAmB;IACrD,OAAO,EAAE,IAAI;IACb,eAAe,EAAE,EAAE;IACnB,eAAe,EAAE,GAAG;IACpB,oBAAoB,EAAE,EAAE;IACxB,YAAY,EAAE,EAAE;CACjB,CAAC;AAyFF,+EAA+E;AAC/E,8EAA8E;AAC9E,uEAAuE;AAEvE,MAAM,aAAa,GAAG;IACpB,2FAA2F;IAC3F,OAAO,EAAE,EAAE,GAAG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,CAAC,CAAC,CAAC,cAAc,SAAS,mCAAmC,CAAC,CAAC,CAAC,SAAS;SAC9F,CAAC;IACJ,CAAC;CACF;AA3YD,wCA2YC"}
@@ -173,6 +173,8 @@ export declare class CommerceEngine {
173
173
  private totalSpent;
174
174
  private approvalCallback;
175
175
  private externalOrderMap;
176
+ private searchLimiter;
177
+ private purchaseLimiter;
176
178
  constructor(agent: any, provider?: CommerceProvider);
177
179
  /**
178
180
  * Set a shopping mandate that defines what this agent can buy.