/** * Elephant Memory Bridge — MnemoPay persistent memory for GridStamp * * GridStamp has a rodent hippocampus model (short/mid/long-term spatial). * The elephant memory layer wraps around it: * * Layer 1 (Perception): Consolidation events from spatial memory * Layer 2 (Encoding): Semantic embeddings via MnemoPay recall engine * Layer 3 (Executive): Agent Credit Score + RL feedback loop * * Every consolidation, tier change, settlement, and spoofing incident * is persisted to MnemoPay for cross-session recall, fleet-wide * behavioral analysis, and insurance dispute evidence. * * Trademark notice: FICO is a registered trademark of Fair Isaac Corporation. * MnemoPay's Agent Credit Score is a FICO-style behavioral metric (300-850), * not affiliated with or endorsed by Fair Isaac Corporation. */ import type { ConsolidationEvent } from '../types/index.js'; // MnemoPay types (dynamic import to avoid hard coupling) interface MnemoPaySDK { remember(content: string, metadata?: Record): unknown; recall(query: string, options?: Record): Promise>; rlFeedback(ids: string[], reward: number, alpha?: number): Promise; /** Preferred: returns the Agent Credit Score (300-850, FICO-style; not * affiliated with Fair Isaac Corporation). */ getAgentCreditScore?(): { score: number; tier: string }; /** @deprecated Use getAgentCreditScore(). Will be removed in v2.0.0. */ getAgentFICO?(): { score: number; tier: string }; } export interface ElephantMemoryConfig { /** Robot identifier */ robotId: string; /** MnemoPay SDK instance (from MnemoPay.quick() or MnemoPay.create()) */ mnemopay: MnemoPaySDK; /** Tags added to all memories for this robot */ defaultTags?: string[]; } export class ElephantMemory { private readonly robotId: string; private readonly sdk: MnemoPaySDK; private readonly tags: string[]; private recentMemoryIds: string[] = []; constructor(config: ElephantMemoryConfig) { this.robotId = config.robotId; this.sdk = config.mnemopay; this.tags = config.defaultTags ?? ['gridstamp', 'robot']; } // ── Layer 1: Perception (capture behavioral events) ────── /** Record a memory consolidation event (short→mid or mid→long) */ async onConsolidation(event: ConsolidationEvent): Promise { const content = [ `Robot ${this.robotId} memory consolidation: ${event.from}→${event.to}.`, `${event.entryCount} entries, ${event.compressionRatio.toFixed(1)}x compression.`, ].join(' '); this.sdk.remember(content, { tags: [...this.tags, 'consolidation', event.from, event.to], importance: 0.3, source: 'gridstamp-memory', }); } /** Record a trust tier change */ async onTierChange( previousTier: string, newTier: string, points: number, reason: string, ): Promise { const direction = points > 0 ? 'promoted' : 'demoted'; const content = [ `Robot ${this.robotId} ${direction}: ${previousTier}→${newTier}.`, `Points: ${points}. Reason: ${reason}.`, ].join(' '); this.sdk.remember(content, { tags: [...this.tags, 'tier-change', direction, newTier.toLowerCase()], importance: 0.8, source: 'gridstamp-trust', }); } /** Record a spatial verification result */ async onVerification(passed: boolean, score: number, location?: string): Promise { const content = [ `Robot ${this.robotId} spatial verification: ${passed ? 'PASSED' : 'FAILED'}.`, `Score: ${score.toFixed(3)}.`, location ? `Location: ${location}.` : '', ].filter(Boolean).join(' '); this.sdk.remember(content, { tags: [...this.tags, 'verification', passed ? 'passed' : 'failed'], importance: passed ? 0.4 : 0.9, source: 'gridstamp-verification', }); } /** Record a settlement */ async onSettlement( amount: number, currency: string, payeeId: string, status: string, ): Promise { const content = [ `Robot ${this.robotId} settlement: ${amount} ${currency} to ${payeeId}.`, `Status: ${status}.`, ].join(' '); this.sdk.remember(content, { tags: [...this.tags, 'settlement', status], importance: 0.6, source: 'gridstamp-payment', }); } /** Record a spoofing incident */ async onSpoofingDetected(threatType: string, severity: string, details: string): Promise { const content = [ `Robot ${this.robotId} SPOOFING DETECTED: ${threatType} (${severity}).`, details, ].join(' '); this.sdk.remember(content, { tags: [...this.tags, 'spoofing', threatType, severity], importance: 1.0, source: 'gridstamp-antispoofing', }); } // ── Layer 2: Encoding (semantic recall) ────────────────── /** Recall relevant operational history for this robot */ async recallHistory(query: string, limit = 10): Promise> { const robotQuery = `Robot ${this.robotId}: ${query}`; const results = await this.sdk.recall(robotQuery, { limit }); this.recentMemoryIds = results.map(r => r.id); return results; } /** Recall fleet-wide patterns (not filtered by robotId) */ async recallFleetPatterns(query: string, limit = 10): Promise> { return this.sdk.recall(query, { limit }); } // ── Layer 3: Executive Monitor (Agent Credit Score + RL) ─ /** * Get the Agent Credit Score for this robot (if available). * * Returns the 300-850 behavioral score from the wrapped MnemoPay SDK. * Prefers the new `getAgentCreditScore()` method; falls back to the * legacy `getAgentFICO()` for SDKs older than the trademark scrub. */ getAgentCreditScore(): { score: number; tier: string } | null { if (this.sdk.getAgentCreditScore) return this.sdk.getAgentCreditScore(); if (this.sdk.getAgentFICO) return this.sdk.getAgentFICO(); return null; } /** * @deprecated Use `getAgentCreditScore()`. Will be removed in v2.0.0. * * Trademark notice: FICO is a registered trademark of Fair Isaac * Corporation. MnemoPay's Agent Credit Score is not affiliated with * Fair Isaac Corporation. */ getFICOScore(): { score: number; tier: string } | null { warnFICODeprecated(); return this.getAgentCreditScore(); } /** Reinforce recent memories based on outcome quality */ async reinforce(reward: number, alpha = 0.1): Promise { if (this.recentMemoryIds.length === 0) return; await this.sdk.rlFeedback(this.recentMemoryIds, reward, alpha); } /** Reinforce specific memories */ async reinforceMemories(ids: string[], reward: number, alpha = 0.1): Promise { await this.sdk.rlFeedback(ids, reward, alpha); } } // ── Deprecation warning helper ─────────────────────────────────────────── let _warnedFICODeprecated = false; /** * Warn once per process when a caller uses the deprecated `getFICOScore()` * alias. Single boolean flag avoids log spam in production loops. */ function warnFICODeprecated(): void { if (_warnedFICODeprecated) return; _warnedFICODeprecated = true; // eslint-disable-next-line no-console console.warn( '[gridstamp] ElephantMemory.getFICOScore() is deprecated and will be ' + 'removed in v2.0.0. Use getAgentCreditScore() instead. FICO is a ' + 'registered trademark of Fair Isaac Corporation; MnemoPay is not ' + 'affiliated with or endorsed by Fair Isaac Corporation.', ); }