@mnemopay/sdk 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **Give any AI agent memory and a wallet in 5 lines.**
4
4
 
5
- MnemoPay unifies [Mnemosyne](https://github.com/t49qnsx7qt-kpanks/mnemosyne-engine) (cognitive memory) and [AgentPay](https://github.com/t49qnsx7qt-kpanks/agentpay-roa) (escrow economics) into a single SDK. The core innovation: **payment outcomes reinforce the memories that led to successful decisions**.
5
+ MnemoPay unifies [Mnemosyne](https://github.com/mnemopay/mnemosyne-engine) (cognitive memory) and [AgentPay](https://github.com/mnemopay/agentpay-roa) (escrow economics) into a single SDK. The core innovation: **payment outcomes reinforce the memories that led to successful decisions**.
6
6
 
7
7
  ```typescript
8
8
  import { MnemoPay } from "@mnemopay/sdk";
@@ -190,4 +190,4 @@ npm test # 67 tests covering memory, payments, feedback loop, security, concurr
190
190
 
191
191
  MIT
192
192
 
193
- Built by [J&B Enterprise LLC](https://github.com/t49qnsx7qt-kpanks)
193
+ Built by [J&B Enterprise LLC](https://github.com/mnemopay)
@@ -0,0 +1,174 @@
1
+ /**
2
+ * MnemoPay Advanced Fraud Detection — ML-grade algorithms in pure TypeScript.
3
+ *
4
+ * Three systems that close the depth gap with Stripe/Coinbase:
5
+ *
6
+ * 1. IsolationForest — Adaptive anomaly detection that LEARNS each agent's
7
+ * normal behavior and catches deviations. Replaces static z-scores.
8
+ *
9
+ * 2. TransactionGraph — Directed graph of money flows between agents.
10
+ * Detects wash trading (A→B→A cycles), fraud rings (dense subgraphs),
11
+ * and sybil attacks (correlated agents from same source).
12
+ *
13
+ * 3. BehaviorProfile — Fingerprints each agent's behavioral signature:
14
+ * typical amounts, timing patterns, charge frequency, memory-to-payment
15
+ * ratio. Detects drift from established baseline.
16
+ *
17
+ * Zero external dependencies. Runs in-process alongside FraudGuard.
18
+ */
19
+ export declare class IsolationForest {
20
+ private trees;
21
+ private readonly numTrees;
22
+ private readonly maxSamples;
23
+ private readonly maxDepth;
24
+ /** Training data buffer — keeps recent samples for incremental retraining */
25
+ private buffer;
26
+ private readonly bufferSize;
27
+ private readonly featureNames;
28
+ constructor(opts?: {
29
+ numTrees?: number;
30
+ maxSamples?: number;
31
+ maxDepth?: number;
32
+ bufferSize?: number;
33
+ });
34
+ /** Number of features expected per sample */
35
+ get numFeatures(): number;
36
+ /**
37
+ * Add a sample and retrain if buffer is full enough.
38
+ * Features: [amount, hourOfDay, minutesSinceLast, chargesLast10Min,
39
+ * avgAmountLast10, stdDevLast10, pendingCount, reputation]
40
+ */
41
+ addSample(features: number[]): void;
42
+ /** Train forest from buffer */
43
+ private train;
44
+ /** Build a single isolation tree */
45
+ private buildTree;
46
+ /**
47
+ * Score a sample. Returns 0-1 where higher = more anomalous.
48
+ * Returns -1 if not enough training data yet.
49
+ */
50
+ score(features: number[]): number;
51
+ /** Traverse tree and return path length to isolation */
52
+ private pathLength;
53
+ /** Average path length of unsuccessful search in BST (used for normalization) */
54
+ private avgPathLength;
55
+ /** Random subsample without replacement */
56
+ private subsample;
57
+ /** Has enough data to score */
58
+ get isReady(): boolean;
59
+ get sampleCount(): number;
60
+ serialize(): string;
61
+ static deserialize(json: string, opts?: ConstructorParameters<typeof IsolationForest>[0]): IsolationForest;
62
+ }
63
+ export interface CollusionSignal {
64
+ type: "wash_trading" | "fraud_ring" | "sybil_cluster" | "self_dealing";
65
+ agents: string[];
66
+ evidence: string;
67
+ severity: number;
68
+ }
69
+ export declare class TransactionGraph {
70
+ /** Adjacency list: agent → list of outgoing edges */
71
+ private edges;
72
+ /** Agent metadata: IP, creation time, etc. */
73
+ private agentMeta;
74
+ /** Total edge count */
75
+ private edgeCount;
76
+ /**
77
+ * Record a transaction between two agents.
78
+ * fromAgent paid toAgent.
79
+ */
80
+ addTransaction(fromAgent: string, toAgent: string, amount: number, txId: string): void;
81
+ /** Register agent metadata for sybil detection */
82
+ registerAgent(agentId: string, ip?: string): void;
83
+ /**
84
+ * Detect wash trading: cycles where money flows A→B→...→A.
85
+ * Returns cycles of length 2-4 (direct and indirect wash trading).
86
+ */
87
+ detectWashTrading(maxCycleLength?: number): CollusionSignal[];
88
+ private findCycles;
89
+ private getCycleFlow;
90
+ /**
91
+ * Detect sybil clusters: multiple agents sharing the same IP(s)
92
+ * that also transact with each other.
93
+ */
94
+ detectSybilClusters(): CollusionSignal[];
95
+ /**
96
+ * Detect self-dealing: agent transacting with itself via intermediaries.
97
+ * A→X→A pattern where X is a thin shell.
98
+ */
99
+ detectSelfDealing(): CollusionSignal[];
100
+ /**
101
+ * Run all collusion detectors and return combined signals.
102
+ */
103
+ detectAll(): CollusionSignal[];
104
+ /** Get graph stats */
105
+ stats(): {
106
+ agents: number;
107
+ edges: number;
108
+ avgDegree: number;
109
+ };
110
+ serialize(): string;
111
+ static deserialize(json: string): TransactionGraph;
112
+ }
113
+ export interface BehaviorSnapshot {
114
+ /** Average charge amount */
115
+ avgAmount: number;
116
+ /** Standard deviation of charge amounts */
117
+ stdAmount: number;
118
+ /** Typical hour of day for activity (0-23) */
119
+ peakHour: number;
120
+ /** Average minutes between charges */
121
+ avgInterval: number;
122
+ /** Ratio of memory ops to payment ops */
123
+ memoryToPaymentRatio: number;
124
+ /** Average charges per active day */
125
+ chargesPerDay: number;
126
+ /** Number of samples used to build this profile */
127
+ sampleCount: number;
128
+ /** When this profile was last updated */
129
+ updatedAt: number;
130
+ }
131
+ export interface DriftSignal {
132
+ type: "amount_drift" | "timing_drift" | "frequency_drift" | "behavior_shift";
133
+ description: string;
134
+ /** How far from baseline (standard deviations) */
135
+ deviation: number;
136
+ /** Severity 0-1 */
137
+ severity: number;
138
+ }
139
+ interface BehaviorEvent {
140
+ type: "charge" | "settle" | "refund" | "remember" | "recall";
141
+ amount?: number;
142
+ timestamp: number;
143
+ }
144
+ export declare class BehaviorProfile {
145
+ /** Per-agent behavior history */
146
+ private agentEvents;
147
+ /** Per-agent baseline snapshots */
148
+ private baselines;
149
+ /** Minimum events before baseline is established */
150
+ private readonly minEvents;
151
+ /** Max events to retain per agent */
152
+ private readonly maxEvents;
153
+ constructor(opts?: {
154
+ minEvents?: number;
155
+ maxEvents?: number;
156
+ });
157
+ /** Record an event for an agent */
158
+ recordEvent(agentId: string, type: BehaviorEvent["type"], amount?: number): void;
159
+ /** Build/update baseline from historical events */
160
+ private buildBaseline;
161
+ /**
162
+ * Check if current behavior drifts from baseline.
163
+ * Pass recent charge amount and context.
164
+ */
165
+ detectDrift(agentId: string, currentAmount?: number): DriftSignal[];
166
+ /** Get an agent's current baseline (if established) */
167
+ getBaseline(agentId: string): BehaviorSnapshot | undefined;
168
+ /** Check if agent has established baseline */
169
+ hasBaseline(agentId: string): boolean;
170
+ serialize(): string;
171
+ static deserialize(json: string, opts?: ConstructorParameters<typeof BehaviorProfile>[0]): BehaviorProfile;
172
+ }
173
+ export {};
174
+ //# sourceMappingURL=fraud-ml.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fraud-ml.d.ts","sourceRoot":"","sources":["../src/fraud-ml.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AA4BH,qBAAa,eAAe;IAC1B,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,6EAA6E;IAC7E,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAW;gBAE5B,IAAI,CAAC,EAAE;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,UAAU,CAAC,EAAE,MAAM,CAA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