All files / lib/evolution consistency.check.ts

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

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                                                                                                                             
// lib/evolution/consistency.check.ts
import { readEvolutionReport, upsertEvolutionReport } from '@/lib/telemetry/evolution.telemetry';
 
export function readEvolutionHistory(): any[] {
  try {
    return JSON.parse(localStorage.getItem('EVOLUTION_HISTORY') || '[]');
  } catch {
    return [];
  }
}
 
/**
 * يتحقق من اتساق البيانات بين Evolution Report و History.
 * يرجع مؤشر consistencyIndex (0 → 1) وحالة النظام.
 */
export function verifyCognitiveConsistency() {
  const report = readEvolutionReport();
  const history = readEvolutionHistory();
 
  // لا يوجد تاريخ مسجل
  if (!Array.isArray(history) || history.length === 0) {
    const patch = {
      consistencyIndex: 0,
      status: 'empty_history',
      verifiedAt: new Date().toISOString(),
    };
    upsertEvolutionReport(patch);
    return patch;
  }
 
  // ✅ تحقق من الترتيب الزمني كما هو (بدون تصحيح تلقائي)
  let inOrder = true;
  for (let i = 1; i < history.length; i++) {
    if (new Date(history[i].ts) < new Date(history[i - 1].ts)) {
      inOrder = false;
      break;
    }
  }
 
  // آخر snapshot فعلي في التاريخ
  const lastSnap = history.at(-1) || {};
 
  // سياق التقرير الحالي
  const rctx = report.lastContext || {};
  const rmetrics = report.metrics || {};
  const hmetrics = lastSnap.metrics || {};
 
  // ✅ تشابه مبسّط (device, perfMode, stability, adaptationRate)
  const similarity =
    (rctx.device === lastSnap.device ? 0.25 : 0) +
    (rctx.perfMode === lastSnap.perfMode ? 0.25 : 0) +
    (Math.abs((rmetrics.stability ?? 0) - (hmetrics.stability ?? 0)) < 0.05 ? 0.25 : 0) +
    (Math.abs((rmetrics.adaptationRate ?? 0) - (hmetrics.adaptationRate ?? 0)) < 0.005 ? 0.25 : 0);
 
  const baseIndex = Number(similarity.toFixed(2));
 
  // ❗ عدم الترتيب الزمني يخصم 50% من الثقة
  const finalIndex = inOrder ? baseIndex : Number((baseIndex * 0.5).toFixed(2));
 
  const status = finalIndex > 0.8 ? 'stable' : finalIndex > 0.5 ? 'partial' : 'inconsistent';
 
  const patch = {
    consistencyIndex: finalIndex,
    status,
    verifiedAt: new Date().toISOString(),
  };
 
  upsertEvolutionReport(patch);
  return patch;
}