All files / lib/meta reflection_core.ts

0% Statements 0/30
0% Branches 0/1
0% Functions 0/1
0% Lines 0/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                                                                               
import fs from 'node:fs';
import { ConsciousConfig } from '../../config/conscious.config';
import { MetaConfig } from '../../config/meta.config';
 
/**
 * يقرأ conscious_insights.json ويستخرج نمطًا ميتا لكل سياسة:
 * - avgCorrelation: متوسط الارتباط
 * - volatility: تذبذب الارتباط
 * - support: عدد الملاحظات المحسوبة
 * - direction: positive/negative
 */
export function detectMetaPatterns() {
  const path = ConsciousConfig.storagePath;
  if (!fs.existsSync(path)) return [];
 
  const all = JSON.parse(fs.readFileSync(path, 'utf8')) as Array<{
    policyId: string;
    correlation: string | number; // محفوظ كنص أحيانًا
    timestamp: string;
  }>;
 
  // تجميع حسب السياسة + قطع لأحدث window
  const grouped: Record<string, number[]> = {};
  for (const ins of all) {
    const id = ins.policyId;
    const c = typeof ins.correlation === 'string' ? Number(ins.correlation) : ins.correlation;
    if (!Number.isFinite(c)) continue;
    grouped[id] ??= [];
    grouped[id].push(c);
  }
 
  const patterns = Object.entries(grouped).map(([policyId, corrs]) => {
    const recent = corrs.slice(-MetaConfig.patternWindow);
    const support = recent.length;
 
    const avg = mean(recent);
    const vol = Math.sqrt(mean(recent.map((x) => (x - avg) ** 2))); // الانحراف المعياري
    const direction = avg >= 0 ? 'positive' : ('negative' as const);
 
    return { policyId, avgCorrelation: avg, volatility: vol, support, direction };
  });
 
  // فلترة أساسية
  return patterns.filter((p) => p.support >= MetaConfig.minSupport);
}
 
const mean = (arr: number[]) => (arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0);