@mnemopay/sdk 0.9.1 → 0.9.3

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,256 @@
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%) — used for AIMD increase */
35
+ maxDeltaPercent: number;
36
+ /** Multiplicative decrease factor for tightening (0.5 = halve on anomaly) */
37
+ decreaseFactor: number;
38
+ /** Additive increase per healthy cycle (0.02 = +2%) */
39
+ increaseFactor: number;
40
+ /** Minimum cycle interval in minutes (default: 60) */
41
+ cycleIntervalMinutes: number;
42
+ /** Lock specific parameters from adaptation */
43
+ lockedParams: string[];
44
+ /** Minimum days of consistent behavior for trust tier upgrade */
45
+ minTrustDurationDays: number;
46
+ /** Consecutive worsening cycles before circuit breaker trips */
47
+ circuitBreakerThreshold: number;
48
+ /** PSI threshold for severe drift detection (halt adaptation) */
49
+ psiHaltThreshold: number;
50
+ /** PSI threshold for moderate drift (log warning) */
51
+ psiWarnThreshold: number;
52
+ }
53
+ export declare const DEFAULT_ADAPTIVE_CONFIG: AdaptiveConfig;
54
+ export interface AgentInsight {
55
+ agentId: string;
56
+ /** Settlement success rate (0-1) */
57
+ settlementRate: number;
58
+ /** Average charge amount */
59
+ avgChargeAmount: number;
60
+ /** Disputes filed against this agent */
61
+ disputeCount: number;
62
+ /** Total revenue generated */
63
+ totalRevenue: number;
64
+ /** Memory utilization efficiency (active memories / total) */
65
+ memoryEfficiency: number;
66
+ /** Recommended risk tier: trusted | standard | elevated | restricted */
67
+ riskTier: "trusted" | "standard" | "elevated" | "restricted";
68
+ /** Recommended fee tier override (null = use default) */
69
+ recommendedFeeRate: number | null;
70
+ /** Recommended rate limit multiplier (1.0 = default, 2.0 = double) */
71
+ rateLimitMultiplier: number;
72
+ /** Agent health score (0-100) */
73
+ healthScore: number;
74
+ /** Observations count */
75
+ observations: number;
76
+ /** Last analyzed */
77
+ analyzedAt: Date;
78
+ }
79
+ export interface AdaptationRecord {
80
+ id: string;
81
+ /** What was adapted */
82
+ parameter: string;
83
+ /** Previous value */
84
+ previousValue: number;
85
+ /** New value */
86
+ newValue: number;
87
+ /** Why it was adapted */
88
+ reason: string;
89
+ /** Evidence that triggered the adaptation */
90
+ evidence: Record<string, number>;
91
+ /** When the adaptation was applied */
92
+ appliedAt: Date;
93
+ /** Whether it was actually applied (false if locked or vetoed) */
94
+ applied: boolean;
95
+ /** Veto reason if not applied */
96
+ vetoReason?: string;
97
+ }
98
+ export interface BusinessMetrics {
99
+ /** Total platform revenue (from fees) */
100
+ totalRevenue: number;
101
+ /** Revenue this cycle */
102
+ cycleRevenue: number;
103
+ /** Total agents observed */
104
+ totalAgents: number;
105
+ /** Agents with settlement rate > 80% */
106
+ trustedAgents: number;
107
+ /** Agents with disputes */
108
+ disputedAgents: number;
109
+ /** Platform-wide settlement rate */
110
+ platformSettlementRate: number;
111
+ /** Average memory utilization across agents */
112
+ avgMemoryUtilization: number;
113
+ /** Fraud detection rate (blocked/total) */
114
+ fraudDetectionRate: number;
115
+ /** System health (0-100) */
116
+ systemHealth: number;
117
+ /** Computed at */
118
+ computedAt: Date;
119
+ }
120
+ export type AdaptiveEventType = "charge" | "settle" | "refund" | "dispute" | "memory_store" | "memory_recall" | "fraud_block" | "fraud_flag";
121
+ export interface AdaptiveEvent {
122
+ type: AdaptiveEventType;
123
+ agentId: string;
124
+ amount?: number;
125
+ timestamp: number;
126
+ metadata?: Record<string, unknown>;
127
+ }
128
+ declare const SECURE_BOUNDS: {
129
+ readonly feeRate: {
130
+ readonly min: 0.005;
131
+ readonly max: 0.05;
132
+ };
133
+ readonly blockThreshold: {
134
+ readonly min: 0.3;
135
+ readonly max: 0.95;
136
+ };
137
+ readonly flagThreshold: {
138
+ readonly min: 0.1;
139
+ readonly max: 0.7;
140
+ };
141
+ readonly rateLimitMultiplier: {
142
+ readonly min: 0.5;
143
+ readonly max: 3;
144
+ };
145
+ readonly decayRate: {
146
+ readonly min: 0.001;
147
+ readonly max: 0.5;
148
+ };
149
+ readonly settlementHoldMinutes: {
150
+ readonly min: 5;
151
+ readonly max: 1440;
152
+ };
153
+ };
154
+ export declare class AdaptiveEngine {
155
+ private config;
156
+ private events;
157
+ private insights;
158
+ private adaptations;
159
+ private lastCycleAt;
160
+ /** Manual overrides set by admin — these are never auto-changed */
161
+ private adminOverrides;
162
+ private eventCounter;
163
+ /** Circuit breaker: consecutive cycles where metrics worsened */
164
+ private consecutiveWorseningCycles;
165
+ /** Circuit breaker: is the engine halted? */
166
+ private circuitBreakerTripped;
167
+ /** Snapshot of key metrics from previous cycle (for regression detection) */
168
+ private previousCycleMetrics;
169
+ /** PSI: distribution snapshot from previous cycle for drift detection */
170
+ private previousDistribution;
171
+ /** Track first event timestamp per agent for trust duration calculation */
172
+ private agentFirstSeen;
173
+ constructor(config?: Partial<AdaptiveConfig>);
174
+ /**
175
+ * Record an operational event. The engine learns from every operation.
176
+ */
177
+ observe(event: AdaptiveEvent): void;
178
+ /**
179
+ * Analyze an agent's behavioral pattern and produce an insight profile.
180
+ * This is the "Agent FICO score" — built from real operational data.
181
+ */
182
+ analyzeAgent(agentId: string): AgentInsight;
183
+ /**
184
+ * Compute platform-wide business intelligence.
185
+ */
186
+ computeMetrics(): BusinessMetrics;
187
+ /**
188
+ * Run an adaptation cycle. Uses asymmetric AIMD:
189
+ * - Additive Increase: slow, gradual loosening on sustained good metrics
190
+ * - Multiplicative Decrease: fast, aggressive tightening on anomalies
191
+ *
192
+ * Includes circuit breaker (halt after N consecutive worsening cycles)
193
+ * and PSI drift detection (halt if input distribution shifts too much).
194
+ */
195
+ runCycle(): AdaptationRecord[];
196
+ /** Reset the circuit breaker, allowing adaptation to resume. */
197
+ resetCircuitBreaker(): void;
198
+ /** Check if circuit breaker is currently tripped. */
199
+ get isCircuitBreakerTripped(): boolean;
200
+ /**
201
+ * Compute the event type distribution for drift detection.
202
+ */
203
+ private computeEventDistribution;
204
+ /**
205
+ * Compute Population Stability Index between two distributions.
206
+ * PSI > 0.1 = moderate drift, > 0.25 = severe drift.
207
+ */
208
+ private computePSI;
209
+ /**
210
+ * Lock a parameter from adaptive changes. Admin decisions override AI.
211
+ */
212
+ lockParam(param: string): void;
213
+ /**
214
+ * Unlock a parameter for adaptive changes.
215
+ */
216
+ unlockParam(param: string): void;
217
+ /**
218
+ * Set an admin override. This value will be used instead of adaptive suggestions.
219
+ */
220
+ setOverride(param: string, value: number): void;
221
+ /**
222
+ * Remove an admin override, allowing adaptive control.
223
+ */
224
+ removeOverride(param: string): void;
225
+ /**
226
+ * Get the effective value for a parameter (admin override > adaptation > default).
227
+ */
228
+ getEffectiveValue(param: string, defaultValue: number): number;
229
+ getInsight(agentId: string): AgentInsight | undefined;
230
+ getAdaptations(limit?: number): AdaptationRecord[];
231
+ get totalEvents(): number;
232
+ get secureBounds(): typeof SECURE_BOUNDS;
233
+ /** Backdate an agent's first-seen timestamp (for testing or data migration) */
234
+ setAgentFirstSeen(agentId: string, timestamp: number): void;
235
+ serialize(): {
236
+ config: AdaptiveConfig;
237
+ insights: [string, AgentInsight][];
238
+ adaptations: AdaptationRecord[];
239
+ overrides: [string, number][];
240
+ eventCount: number;
241
+ circuitBreakerTripped: boolean;
242
+ consecutiveWorsening: number;
243
+ agentFirstSeen: [string, number][];
244
+ };
245
+ static deserialize(data: ReturnType<AdaptiveEngine["serialize"]>): AdaptiveEngine;
246
+ private isLocked;
247
+ private clamp;
248
+ /**
249
+ * Limit how much a parameter can change in one cycle.
250
+ * Prevents wild swings — stability is a security property.
251
+ */
252
+ private limitDelta;
253
+ private createRecord;
254
+ }
255
+ export {};
256
+ //# 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,8EAA8E;IAC9E,eAAe,EAAE,MAAM,CAAC;IACxB,6EAA6E;IAC7E,cAAc,EAAE,MAAM,CAAC;IACvB,uDAAuD;IACvD,cAAc,EAAE,MAAM,CAAC;IACvB,sDAAsD;IACtD,oBAAoB,EAAE,MAAM,CAAC;IAC7B,+CAA+C;IAC/C,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,iEAAiE;IACjE,oBAAoB,EAAE,MAAM,CAAC;IAC7B,gEAAgE;IAChE,uBAAuB,EAAE,MAAM,CAAC;IAChC,iEAAiE;IACjE,gBAAgB,EAAE,MAAM,CAAC;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