snapkitty
compilers
c
asm
File size: 5,614 Bytes
96dc096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
{-|

Module      : KAR.PolicyEngine

Description : محرك السياسة الرئيسي | Main Policy Engine

Copyright   : (c) Ahmad Ali Parr, 2026

License     : Proprietary

Maintainer  : ahmedparr93@gmail.com



Core policy evaluation engine. Evaluates intents against:

- Resource constraints (memory, CPU, thermal)

- Trust verification (nonce validation)

- Priority enforcement

- System load balancing



التقييم الرئيسي للسياسات في نظام KAR

-}

module KAR.PolicyEngine
    ( evaluateIntent
    , PolicyContext(..)
    , defaultPolicyContext
    ) where

import KAR.Types.Intent
import KAR.Types.Decision
import KAR.Types.Resource
import KAR.ResourceNegotiator (negotiateResources)
import KAR.TrustVerifier (verifyTrustNonce)
import Data.Text (Text)
import qualified Data.Text as T

-- | Policy evaluation context
data PolicyContext = PolicyContext
    { systemResources :: !SystemResources
    , globalConstraints :: !ResourceConstraints
    , enforceTrust :: !Bool
    , allowOvercommit :: !Bool
    } deriving (Eq, Show)

-- | Default policy context (strict enforcement)
defaultPolicyContext :: SystemResources -> PolicyContext
defaultPolicyContext sys = PolicyContext
    { systemResources = sys
    , globalConstraints = ResourceConstraints
        { maxMemoryBytes = 1024 * 1024 * 1024  -- 1GB per intent
        , maxCpuShares = 100                    -- 100% of one core
        , maxTempCelsius = 85                   -- 85°C thermal limit
        }
    , enforceTrust = True
    , allowOvercommit = False
    }

-- | Main policy evaluation function
-- نقطة الدخول الرئيسية لتقييم السياسات
evaluateIntent :: PolicyContext -> Intent -> PolicyDecision
evaluateIntent ctx intent =
    -- Step 1: Verify trust nonce (if enforcement enabled)
    case (enforceTrust ctx, verifyTrustNonce (trustNonce intent) intent) of
        (True, False) ->
            PolicyDecision
                { decisionOutcome = Reject "Trust nonce validation failed"
                , resourceAlloc = Nothing
                , recoveryStrategy = GracefulFail
                , estimatedCostNs = 0
                , trustVerified = False
                , policyReason = "ETRUST_NONCE_FAIL: Cryptographic validation rejected"
                }

        _ -> do
            -- Step 2: Check priority constraints
            let priorityOk = checkPriorityConstraints ctx intent
            if not priorityOk
                then rejectPriority ctx intent
                else do
                    -- Step 3: Negotiate resources
                    case negotiateResources (systemResources ctx) (globalConstraints ctx) intent of
                        Nothing ->
                            PolicyDecision
                                { decisionOutcome = Reject "Resource negotiation failed"
                                , resourceAlloc = Nothing
                                , recoveryStrategy = RetryWithBackoff 1000  -- Retry in 1s
                                , estimatedCostNs = 0
                                , trustVerified = True
                                , policyReason = "EKAR_POLICY_REJECT: Insufficient resources"
                                }

                        Just alloc ->
                            let cost = executionCost alloc
                            in PolicyDecision
                                { decisionOutcome = Approve
                                , resourceAlloc = Just alloc
                                , recoveryStrategy = RetryImmediate
                                , estimatedCostNs = cost
                                , trustVerified = True
                                , policyReason = formatApprovalReason intent alloc
                                }

-- | Check priority-specific constraints
-- التحقق من قيود الأولوية
checkPriorityConstraints :: PolicyContext -> Intent -> Bool
checkPriorityConstraints ctx intent =
    case intentPriority intent of
        Critical ->
            -- Critical intents always allowed (preemptive)
            True

        High ->
            -- High priority requires <80% CPU load
            cpuLoad (cpuState (systemResources ctx)) < 0.8

        Normal ->
            -- Normal requires <90% CPU load
            cpuLoad (cpuState (systemResources ctx)) < 0.9

        Background ->
            -- Background only if <50% CPU load
            cpuLoad (cpuState (systemResources ctx)) < 0.5

-- | Reject intent due to priority constraints
rejectPriority :: PolicyContext -> Intent -> PolicyDecision
rejectPriority ctx intent =
    let reason = T.pack $ "Priority " ++ show (intentPriority intent)
                        ++ " rejected: CPU load "
                        ++ show (cpuLoad (cpuState (systemResources ctx)))
    in PolicyDecision
        { decisionOutcome = Defer 500  -- Defer 500ms
        , resourceAlloc = Nothing
        , recoveryStrategy = RetryWithBackoff 500
        , estimatedCostNs = 0
        , trustVerified = True
        , policyReason = reason
        }

-- | Format approval reason string
formatApprovalReason :: Intent -> ResourceAllocation -> Text
formatApprovalReason intent alloc =
    T.pack $ "Approved: " ++ show (intentType intent)
          ++ " | Memory: " ++ show (allocMemoryBytes alloc `div` 1024) ++ "KB"
          ++ " | CPU: " ++ show (allocCpuShares alloc) ++ " shares"
          ++ " | Timeout: " ++ show (allocTimeout alloc) ++ "ms"