All files / lib/feedback runner.ts

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

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 72 73 74 75 76 77 78 79                                                                                                                                                             
import { evaluate } from './evaluator';
import { canRun, mark } from './cooldown';
import { execute } from './actions';
import { recordFeedback } from './memory';
import { updateMetrics } from './metrics';
import { DefaultPolicy } from './policy';
import { chooseAction } from './policy';
import type { Signal } from './types';
 
export async function runFeedbackCycle(signals: Signal[], at: number) {
  const evaln = evaluate(signals);
  const policy = DefaultPolicy;
 
  let action: any = null;
  let result: any = null;
  let blockedBy: string | null = null;
 
  try {
    // أمان: كريتيكال + ثقة ضعيفة جدًا → منع
    if (evaln.severity === 'CRITICAL' && (evaln.confidence ?? 1) < 0.2) {
      blockedBy = 'safety';
    } else {
      // اختار الإجراء حسب السياسة
      action = chooseAction(evaln, policy);
 
      // مهم: الـ cooldown يتحسب **فقط** لو في Action فعلي
      if (action && !canRun('FEEDBACK', at, policy.cooldownMs)) {
        blockedBy = 'cooldown';
        action = null;
      } else if (action) {
        // علّم آخر تنفيذ لنفس الدورة
        mark('FEEDBACK', at, true);
      }
 
      // تنفيذ الفعل (لو موجود) مع ضمان ok دائمًا
      if (action) {
        try {
          const execResult = await execute(action);
          result = { ...execResult, ok: true };
        } catch (err) {
          result = { ok: false, error: (err as Error).message };
        }
      } else {
        // لا يوجد فعل → اعتبر الدورة ناجحة (ok:true) علشان متريكس تتحدث
        result = { ok: true };
      }
    }
 
    // سجّل في الذاكرة
    await recordFeedback({
      at,
      evaluation: evaln,
      chosenAction: action,
      result,
      policyVersion: policy.version,
      blockedBy,
    });
 
    // حدّث المقاييس
    updateMetrics(result, at);
 
    // ارجع الناتج
    return { evaln, action, result, blockedBy };
  } catch (err) {
    console.error('[runFeedbackCycle] Crash:', err);
    const crash = { ok: false, error: String(err) };
    updateMetrics(crash, at);
    await recordFeedback({
      at,
      evaluation: evaln,
      chosenAction: action,
      result: crash,
      policyVersion: policy.version,
      blockedBy: 'error',
    });
    return { evaln, action, result: crash, blockedBy: 'error' };
  }
}