All files / lib/integration policy_history.ts

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

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                                                                                   
/**
 * @file policy_history.ts
 * Phase 8.6 — Policy Heatmap Recorder
 * -----------------------------------
 * يحتفظ بتاريخ كل snapshots بيئية في ملف policy_history.json
 * ويحسب Environment Confidence Index (ECI)
 */
 
import fs from 'node:fs';
import path from 'node:path';
import { PolicySnapshot } from '../policies/PolicyManager';
 
const historyPath = path.resolve('./storage/policy_history.json');
 
function calcECI(snapshot: PolicySnapshot): number {
  // مؤشر الثقة البيئية (0 → سيئ جداً، 1 → ممتاز)
  const perfScore = { low: 0.3, medium: 0.7, high: 1 }[snapshot.performance];
  const netScore = { offline: 0.1, slow: 0.5, fast: 1 }[snapshot.network];
  const motionScore = snapshot.motion === 'full' ? 1 : 0.7;
  return Number(((perfScore + netScore + motionScore) / 3).toFixed(2));
}
 
export function appendPolicyHistory(snapshot: PolicySnapshot) {
  if (!fs.existsSync(path.dirname(historyPath)))
    fs.mkdirSync(path.dirname(historyPath), { recursive: true });
 
  const history = fs.existsSync(historyPath)
    ? JSON.parse(fs.readFileSync(historyPath, 'utf8'))
    : [];
 
  const entry = { ...snapshot, eci: calcECI(snapshot) };
  history.push(entry);
  fs.writeFileSync(historyPath, JSON.stringify(history, null, 2));
  console.log(`📊 [Heatmap] Policy snapshot added (${entry.eci * 100}% confidence).`);
}
 
export function getLastPolicyECI(): number {
  if (!fs.existsSync(historyPath)) return 0;
  const history = JSON.parse(fs.readFileSync(historyPath, 'utf8'));
  return history.at(-1)?.eci || 0;
}