petter2025 commited on
Commit
72e3e77
Β·
verified Β·
1 Parent(s): 73939b2

Update hf_demo.py

Browse files
Files changed (1) hide show
  1. hf_demo.py +81 -81
hf_demo.py CHANGED
@@ -1,62 +1,56 @@
1
  """
2
- ARF OSS v3.3.9 - Enterprise Lead Generation Engine (API Only)
3
- Compatible with Pydantic V2
4
  """
5
 
6
  import os
7
- import sys
8
  import json
9
  import uuid
10
  import hashlib
11
  import logging
12
  import sqlite3
13
- import requests
14
- from datetime import datetime
15
- from typing import Dict, List, Optional, Any, Tuple
16
  from contextlib import contextmanager
 
17
  from enum import Enum
 
18
 
19
- # FastAPI and Pydantic
20
  from fastapi import FastAPI, HTTPException, Depends, status
21
  from fastapi.middleware.cors import CORSMiddleware
22
- from fastapi.responses import JSONResponse
23
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
24
  from pydantic import BaseModel, Field, field_validator
25
  from pydantic_settings import BaseSettings, SettingsConfigDict
26
 
27
  # ============== CONFIGURATION (Pydantic V2) ==============
28
  class Settings(BaseSettings):
29
- """Centralized configuration using Pydantic Settings V2"""
30
-
31
- # Hugging Face settings (aliased to match expected env vars)
32
  hf_space_id: str = Field(default='local', alias='SPACE_ID')
33
  hf_token: str = Field(default='', alias='HF_TOKEN')
34
-
35
- # Persistence - HF persistent storage
36
  data_dir: str = Field(
37
  default='/data' if os.path.exists('/data') else './data',
38
  alias='DATA_DIR'
39
  )
40
-
41
- # Lead generation
42
  lead_email: str = "petter2025us@outlook.com"
43
  calendly_url: str = "https://calendly.com/petter2025us/arf-demo"
44
-
45
- # Webhook for lead alerts (set in HF secrets)
46
  slack_webhook: str = Field(default='', alias='SLACK_WEBHOOK')
47
  sendgrid_api_key: str = Field(default='', alias='SENDGRID_API_KEY')
48
-
49
- # Security
50
  api_key: str = Field(
51
  default_factory=lambda: str(uuid.uuid4()),
52
  alias='ARF_API_KEY'
53
  )
54
-
55
  # ARF defaults
56
  default_confidence_threshold: float = 0.9
57
  default_max_risk: str = "MEDIUM"
58
-
59
- # Pydantic V2 configuration
60
  model_config = SettingsConfigDict(
61
  populate_by_name=True,
62
  extra='ignore',
@@ -81,7 +75,7 @@ logging.basicConfig(
81
  )
82
  logger = logging.getLogger('arf.oss')
83
 
84
- # ============== ENUMS & TYPES ==============
85
  class RiskLevel(str, Enum):
86
  LOW = "LOW"
87
  MEDIUM = "MEDIUM"
@@ -101,8 +95,9 @@ class LeadSignal(str, Enum):
101
  CONFIDENCE_LOW = "confidence_low"
102
  REPEATED_FAILURE = "repeated_failure"
103
 
104
- # ============== BAYESIAN ENGINE ==============
105
  class BayesianRiskEngine:
 
106
  def __init__(self):
107
  self.prior_alpha = 2.0
108
  self.prior_beta = 5.0
@@ -115,7 +110,7 @@ class BayesianRiskEngine:
115
  }
116
  self.evidence_db = f"{settings.data_dir}/evidence.db"
117
  self._init_db()
118
-
119
  def _init_db(self):
120
  try:
121
  with self._get_db() as conn:
@@ -134,7 +129,7 @@ class BayesianRiskEngine:
134
  except sqlite3.Error as e:
135
  logger.error(f"Failed to initialize evidence database: {e}")
136
  raise RuntimeError("Could not initialize evidence storage") from e
137
-
138
  @contextmanager
139
  def _get_db(self):
140
  conn = None
@@ -147,7 +142,7 @@ class BayesianRiskEngine:
147
  finally:
148
  if conn:
149
  conn.close()
150
-
151
  def classify_action(self, action_text: str) -> str:
152
  action_lower = action_text.lower()
153
  if any(word in action_lower for word in ['database', 'db', 'sql', 'table', 'drop', 'delete']):
@@ -160,11 +155,11 @@ class BayesianRiskEngine:
160
  return 'security'
161
  else:
162
  return 'default'
163
-
164
  def get_prior(self, action_type: str) -> Tuple[float, float]:
165
  prior = self.action_priors.get(action_type, self.action_priors['default'])
166
  return prior['alpha'], prior['beta']
167
-
168
  def get_evidence(self, action_hash: str) -> Tuple[int, int]:
169
  try:
170
  with self._get_db() as conn:
@@ -177,7 +172,7 @@ class BayesianRiskEngine:
177
  except sqlite3.Error as e:
178
  logger.error(f"Failed to retrieve evidence: {e}")
179
  return (0, 0)
180
-
181
  def calculate_posterior(self, action_text: str, context: Dict[str, Any]) -> Dict[str, Any]:
182
  action_type = self.classify_action(action_text)
183
  alpha0, beta0 = self.get_prior(action_type)
@@ -189,11 +184,12 @@ class BayesianRiskEngine:
189
  context_multiplier = self._context_likelihood(context)
190
  risk_score = posterior_mean * context_multiplier
191
  risk_score = min(0.99, max(0.01, risk_score))
 
192
  variance = (alpha_n * beta_n) / ((alpha_n + beta_n)**2 * (alpha_n + beta_n + 1))
193
  std_dev = variance ** 0.5
194
  ci_lower = max(0.01, posterior_mean - 1.96 * std_dev)
195
  ci_upper = min(0.99, posterior_mean + 1.96 * std_dev)
196
-
197
  if risk_score > 0.8:
198
  risk_level = RiskLevel.CRITICAL
199
  elif risk_score > 0.6:
@@ -202,7 +198,7 @@ class BayesianRiskEngine:
202
  risk_level = RiskLevel.MEDIUM
203
  else:
204
  risk_level = RiskLevel.LOW
205
-
206
  return {
207
  "score": risk_score,
208
  "level": risk_level,
@@ -217,7 +213,7 @@ class BayesianRiskEngine:
217
  Γ— Context multiplier {context_multiplier:.2f} = {risk_score:.3f}
218
  """
219
  }
220
-
221
  def _context_likelihood(self, context: Dict) -> float:
222
  multiplier = 1.0
223
  if context.get('environment') == 'production':
@@ -234,7 +230,7 @@ class BayesianRiskEngine:
234
  if not context.get('backup_available', True):
235
  multiplier *= 1.6
236
  return multiplier
237
-
238
  def record_outcome(self, action_text: str, success: bool):
239
  action_hash = hashlib.sha256(action_text.encode()).hexdigest()
240
  action_type = self.classify_action(action_text)
@@ -258,6 +254,7 @@ class BayesianRiskEngine:
258
 
259
  # ============== POLICY ENGINE ==============
260
  class PolicyEngine:
 
261
  def __init__(self):
262
  self.config = {
263
  "confidence_threshold": settings.default_confidence_threshold,
@@ -281,11 +278,11 @@ class PolicyEngine:
281
  "require_human": [RiskLevel.CRITICAL, RiskLevel.HIGH],
282
  "require_rollback": True
283
  }
284
-
285
  def evaluate(self, action: str, risk: Dict[str, Any], confidence: float) -> Dict[str, Any]:
286
  import re
287
  gates = []
288
-
289
  # Gate 1: Confidence threshold
290
  confidence_passed = confidence >= self.config["confidence_threshold"]
291
  gates.append({
@@ -296,7 +293,7 @@ class PolicyEngine:
296
  "reason": f"Confidence {confidence:.2f} {'β‰₯' if confidence_passed else '<'} threshold {self.config['confidence_threshold']}",
297
  "type": "numerical"
298
  })
299
-
300
  # Gate 2: Risk level
301
  risk_levels = list(RiskLevel)
302
  max_idx = risk_levels.index(RiskLevel(self.config["max_autonomous_risk"]))
@@ -311,7 +308,7 @@ class PolicyEngine:
311
  "type": "categorical",
312
  "metadata": {"risk_score": risk["score"], "credible_interval": risk["credible_interval"]}
313
  })
314
-
315
  # Gate 3: Destructive check
316
  is_destructive = any(re.search(pattern, action.lower()) for pattern in self.config["destructive_patterns"])
317
  gates.append({
@@ -322,7 +319,7 @@ class PolicyEngine:
322
  "type": "boolean",
323
  "metadata": {"requires_rollback": is_destructive}
324
  })
325
-
326
  # Gate 4: Human review requirement
327
  requires_human = risk["level"] in self.config["require_human"]
328
  gates.append({
@@ -332,7 +329,7 @@ class PolicyEngine:
332
  "reason": "Human review not required" if not requires_human else f"Human review required for {risk['level'].value} risk",
333
  "type": "boolean"
334
  })
335
-
336
  # Gate 5: OSS license (always passes)
337
  gates.append({
338
  "gate": "license_check",
@@ -341,9 +338,9 @@ class PolicyEngine:
341
  "reason": "OSS edition - advisory only",
342
  "type": "license"
343
  })
344
-
345
  all_passed = all(g["passed"] for g in gates)
346
-
347
  if not all_passed:
348
  required_level = ExecutionLevel.OPERATOR_REVIEW
349
  elif risk["level"] == RiskLevel.LOW:
@@ -352,7 +349,7 @@ class PolicyEngine:
352
  required_level = ExecutionLevel.AUTONOMOUS_HIGH
353
  else:
354
  required_level = ExecutionLevel.SUPERVISED
355
-
356
  return {
357
  "allowed": all_passed,
358
  "required_level": required_level.value,
@@ -360,7 +357,7 @@ class PolicyEngine:
360
  "advisory_only": True,
361
  "oss_disclaimer": "OSS edition provides advisory only. Enterprise adds execution."
362
  }
363
-
364
  def update_config(self, key: str, value: Any):
365
  if key in self.config:
366
  self.config[key] = value
@@ -370,11 +367,12 @@ class PolicyEngine:
370
 
371
  # ============== RAG MEMORY ==============
372
  class RAGMemory:
 
373
  def __init__(self):
374
  self.db_path = f"{settings.data_dir}/memory.db"
375
  self._init_db()
376
  self.embedding_cache = {}
377
-
378
  def _init_db(self):
379
  try:
380
  with self._get_db() as conn:
@@ -409,7 +407,7 @@ class RAGMemory:
409
  except sqlite3.Error as e:
410
  logger.error(f"Failed to initialize memory database: {e}")
411
  raise RuntimeError("Could not initialize memory storage") from e
412
-
413
  @contextmanager
414
  def _get_db(self):
415
  conn = None
@@ -423,7 +421,7 @@ class RAGMemory:
423
  finally:
424
  if conn:
425
  conn.close()
426
-
427
  def _simple_embedding(self, text: str) -> List[float]:
428
  if text in self.embedding_cache:
429
  return self.embedding_cache[text]
@@ -438,7 +436,7 @@ class RAGMemory:
438
  vector = vector[:100]
439
  self.embedding_cache[text] = vector
440
  return vector
441
-
442
  def store_incident(self, action: str, risk_score: float, risk_level: RiskLevel,
443
  confidence: float, allowed: bool, gates: List[Dict]):
444
  action_hash = hashlib.sha256(action.encode()).hexdigest()[:50]
@@ -464,7 +462,7 @@ class RAGMemory:
464
  conn.commit()
465
  except sqlite3.Error as e:
466
  logger.error(f"Failed to store incident: {e}")
467
-
468
  def find_similar(self, action: str, limit: int = 5) -> List[Dict]:
469
  query_embedding = self._simple_embedding(action)
470
  try:
@@ -492,7 +490,7 @@ class RAGMemory:
492
  except sqlite3.Error as e:
493
  logger.error(f"Failed to find similar incidents: {e}")
494
  return []
495
-
496
  def track_enterprise_signal(self, signal_type: LeadSignal, action: str,
497
  risk_score: float, metadata: Dict = None):
498
  signal = {
@@ -523,12 +521,12 @@ class RAGMemory:
523
  except sqlite3.Error as e:
524
  logger.error(f"Failed to track signal: {e}")
525
  return None
526
-
527
  logger.info(f"πŸ”” Enterprise signal: {signal_type.value} - {action[:50]}...")
528
  if signal_type in [LeadSignal.HIGH_RISK_BLOCKED, LeadSignal.NOVEL_ACTION]:
529
  self._notify_sales_team(signal)
530
  return signal
531
-
532
  def _notify_sales_team(self, signal: Dict):
533
  if settings.slack_webhook:
534
  try:
@@ -542,7 +540,7 @@ class RAGMemory:
542
  }, timeout=5)
543
  except requests.RequestException as e:
544
  logger.error(f"Slack notification failed: {e}")
545
-
546
  def get_uncontacted_signals(self) -> List[Dict]:
547
  try:
548
  with self._get_db() as conn:
@@ -561,7 +559,7 @@ class RAGMemory:
561
  except sqlite3.Error as e:
562
  logger.error(f"Failed to get uncontacted signals: {e}")
563
  return []
564
-
565
  def mark_contacted(self, signal_id: str):
566
  try:
567
  with self._get_db() as conn:
@@ -581,7 +579,7 @@ async def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(sec
581
  )
582
  return credentials.credentials
583
 
584
- # ============== PYDANTIC MODELS ==============
585
  class ActionRequest(BaseModel):
586
  proposedAction: str = Field(..., min_length=1, max_length=1000)
587
  confidenceScore: float = Field(..., ge=0.0, le=1.0)
@@ -591,7 +589,7 @@ class ActionRequest(BaseModel):
591
  rollbackFeasible: bool = True
592
  user_role: str = "devops"
593
  session_id: Optional[str] = None
594
-
595
  @field_validator('proposedAction')
596
  @classmethod
597
  def validate_action(cls, v: str) -> str:
@@ -629,11 +627,11 @@ class LeadSignalResponse(BaseModel):
629
  timestamp: str
630
  metadata: Dict
631
 
632
- # ============== FASTAPI SETUP ==============
633
  app = FastAPI(
634
  title="ARF OSS Real Engine (API Only)",
635
  version="3.3.9",
636
- description="Real ARF OSS components for enterprise lead generation - API only",
637
  contact={
638
  "name": "ARF Sales",
639
  "email": settings.lead_email,
@@ -653,10 +651,11 @@ risk_engine = BayesianRiskEngine()
653
  policy_engine = PolicyEngine()
654
  memory = RAGMemory()
655
 
656
- # ============== ROOT ENDPOINT (for health checks) ==============
 
657
  @app.get("/")
658
  async def root():
659
- """Root endpoint for platform health checks"""
660
  return {
661
  "service": "ARF OSS API",
662
  "version": "3.3.9",
@@ -664,11 +663,9 @@ async def root():
664
  "docs": "/docs"
665
  }
666
 
667
- # ============== API ENDPOINTS ==============
668
-
669
  @app.get("/health")
670
  async def health_check():
671
- """Public health check endpoint"""
672
  return {
673
  "status": "healthy",
674
  "version": "3.3.9",
@@ -679,7 +676,7 @@ async def health_check():
679
 
680
  @app.get("/api/v1/config", dependencies=[Depends(verify_api_key)])
681
  async def get_config():
682
- """Get current ARF configuration"""
683
  return {
684
  "confidenceThreshold": policy_engine.config["confidence_threshold"],
685
  "maxAutonomousRisk": policy_engine.config["max_autonomous_risk"],
@@ -690,7 +687,7 @@ async def get_config():
690
 
691
  @app.post("/api/v1/config", dependencies=[Depends(verify_api_key)])
692
  async def update_config(config: ConfigUpdateRequest):
693
- """Update ARF configuration"""
694
  if config.confidenceThreshold:
695
  policy_engine.update_config("confidence_threshold", config.confidenceThreshold)
696
  if config.maxAutonomousRisk:
@@ -700,7 +697,7 @@ async def update_config(config: ConfigUpdateRequest):
700
  @app.post("/api/v1/evaluate", dependencies=[Depends(verify_api_key)], response_model=EvaluationResponse)
701
  async def evaluate_action(request: ActionRequest):
702
  """
703
- Real ARF OSS evaluation pipeline
704
  """
705
  try:
706
  context = {
@@ -709,20 +706,20 @@ async def evaluate_action(request: ActionRequest):
709
  "backup_available": request.rollbackFeasible,
710
  "requires_human": request.requiresHuman
711
  }
712
-
713
  risk = risk_engine.calculate_posterior(
714
  action_text=request.proposedAction,
715
  context=context
716
  )
717
-
718
  policy = policy_engine.evaluate(
719
  action=request.proposedAction,
720
  risk=risk,
721
  confidence=request.confidenceScore
722
  )
723
-
724
  similar = memory.find_similar(request.proposedAction, limit=3)
725
-
726
  if not policy["allowed"] and risk["score"] > 0.7:
727
  memory.track_enterprise_signal(
728
  signal_type=LeadSignal.HIGH_RISK_BLOCKED,
@@ -734,7 +731,7 @@ async def evaluate_action(request: ActionRequest):
734
  "failed_gates": [g["gate"] for g in policy["gates"] if not g["passed"]]
735
  }
736
  )
737
-
738
  if len(similar) < 2 and risk["score"] > 0.6:
739
  memory.track_enterprise_signal(
740
  signal_type=LeadSignal.NOVEL_ACTION,
@@ -742,7 +739,7 @@ async def evaluate_action(request: ActionRequest):
742
  risk_score=risk["score"],
743
  metadata={"similar_count": len(similar)}
744
  )
745
-
746
  memory.store_incident(
747
  action=request.proposedAction,
748
  risk_score=risk["score"],
@@ -751,7 +748,7 @@ async def evaluate_action(request: ActionRequest):
751
  allowed=policy["allowed"],
752
  gates=policy["gates"]
753
  )
754
-
755
  gates = []
756
  for g in policy["gates"]:
757
  gates.append(GateResult(
@@ -763,7 +760,7 @@ async def evaluate_action(request: ActionRequest):
763
  type=g.get("type", "boolean"),
764
  metadata=g.get("metadata")
765
  ))
766
-
767
  execution_ladder = {
768
  "levels": [
769
  {"name": "AUTONOMOUS_LOW", "required": gates[0].passed and gates[1].passed},
@@ -773,7 +770,7 @@ async def evaluate_action(request: ActionRequest):
773
  ],
774
  "current": policy["required_level"]
775
  }
776
-
777
  return EvaluationResponse(
778
  allowed=policy["allowed"],
779
  requiredLevel=policy["required_level"],
@@ -782,7 +779,7 @@ async def evaluate_action(request: ActionRequest):
782
  escalationReason=None if policy["allowed"] else "Failed mechanical gates",
783
  executionLadder=execution_ladder
784
  )
785
-
786
  except Exception as e:
787
  logger.error(f"Evaluation failed: {e}", exc_info=True)
788
  raise HTTPException(
@@ -793,7 +790,7 @@ async def evaluate_action(request: ActionRequest):
793
  @app.get("/api/v1/enterprise/signals", dependencies=[Depends(verify_api_key)])
794
  async def get_enterprise_signals(contacted: bool = False):
795
  """
796
- Get enterprise lead signals
797
  """
798
  try:
799
  if contacted:
@@ -823,25 +820,28 @@ async def get_enterprise_signals(contacted: bool = False):
823
 
824
  @app.post("/api/v1/enterprise/signals/{signal_id}/contact", dependencies=[Depends(verify_api_key)])
825
  async def mark_signal_contacted(signal_id: str):
 
826
  memory.mark_contacted(signal_id)
827
  return {"status": "success", "message": "Signal marked as contacted"}
828
 
829
  @app.get("/api/v1/memory/similar", dependencies=[Depends(verify_api_key)])
830
  async def get_similar_actions(action: str, limit: int = 5):
 
831
  similar = memory.find_similar(action, limit=limit)
832
  return {"similar": similar, "count": len(similar)}
833
 
834
  @app.post("/api/v1/feedback", dependencies=[Depends(verify_api_key)])
835
  async def record_outcome(action: str, success: bool):
 
836
  risk_engine.record_outcome(action, success)
837
  return {"status": "success", "message": "Outcome recorded"}
838
 
839
  # ============== MAIN ENTRY POINT ==============
840
  if __name__ == "__main__":
841
  import uvicorn
842
-
843
  port = int(os.environ.get('PORT', 7860))
844
-
845
  logger.info("="*60)
846
  logger.info("πŸš€ ARF OSS v3.3.9 (API Only) Starting")
847
  logger.info(f"πŸ“Š Data directory: {settings.data_dir}")
@@ -849,10 +849,10 @@ if __name__ == "__main__":
849
  logger.info(f"πŸ”‘ API Key: {settings.api_key[:8]}... (set in HF secrets)")
850
  logger.info(f"🌐 Serving API at: http://0.0.0.0:{port}")
851
  logger.info("="*60)
852
-
853
  uvicorn.run(
854
  "hf_demo:app",
855
- host="0.0.0.0",
856
  port=port,
857
  log_level="info",
858
  reload=False
 
1
  """
2
+ ARF OSS v3.3.9 - Enterprise Reliability Engine (Backend API only)
 
3
  """
4
 
5
  import os
 
6
  import json
7
  import uuid
8
  import hashlib
9
  import logging
10
  import sqlite3
 
 
 
11
  from contextlib import contextmanager
12
+ from datetime import datetime
13
  from enum import Enum
14
+ from typing import Dict, List, Optional, Any, Tuple
15
 
16
+ import requests
17
  from fastapi import FastAPI, HTTPException, Depends, status
18
  from fastapi.middleware.cors import CORSMiddleware
 
19
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
20
  from pydantic import BaseModel, Field, field_validator
21
  from pydantic_settings import BaseSettings, SettingsConfigDict
22
 
23
  # ============== CONFIGURATION (Pydantic V2) ==============
24
  class Settings(BaseSettings):
25
+ """Application settings loaded from environment variables."""
26
+ # Hugging Face settings
 
27
  hf_space_id: str = Field(default='local', alias='SPACE_ID')
28
  hf_token: str = Field(default='', alias='HF_TOKEN')
29
+
30
+ # Data persistence directory
31
  data_dir: str = Field(
32
  default='/data' if os.path.exists('/data') else './data',
33
  alias='DATA_DIR'
34
  )
35
+
36
+ # Contact information (used in API responses)
37
  lead_email: str = "petter2025us@outlook.com"
38
  calendly_url: str = "https://calendly.com/petter2025us/arf-demo"
39
+
40
+ # External webhooks (set in secrets)
41
  slack_webhook: str = Field(default='', alias='SLACK_WEBHOOK')
42
  sendgrid_api_key: str = Field(default='', alias='SENDGRID_API_KEY')
43
+
44
+ # API security
45
  api_key: str = Field(
46
  default_factory=lambda: str(uuid.uuid4()),
47
  alias='ARF_API_KEY'
48
  )
49
+
50
  # ARF defaults
51
  default_confidence_threshold: float = 0.9
52
  default_max_risk: str = "MEDIUM"
53
+
 
54
  model_config = SettingsConfigDict(
55
  populate_by_name=True,
56
  extra='ignore',
 
75
  )
76
  logger = logging.getLogger('arf.oss')
77
 
78
+ # ============== ENUMS ==============
79
  class RiskLevel(str, Enum):
80
  LOW = "LOW"
81
  MEDIUM = "MEDIUM"
 
95
  CONFIDENCE_LOW = "confidence_low"
96
  REPEATED_FAILURE = "repeated_failure"
97
 
98
+ # ============== BAYESIAN RISK ENGINE ==============
99
  class BayesianRiskEngine:
100
+ """True Bayesian inference with conjugate priors."""
101
  def __init__(self):
102
  self.prior_alpha = 2.0
103
  self.prior_beta = 5.0
 
110
  }
111
  self.evidence_db = f"{settings.data_dir}/evidence.db"
112
  self._init_db()
113
+
114
  def _init_db(self):
115
  try:
116
  with self._get_db() as conn:
 
129
  except sqlite3.Error as e:
130
  logger.error(f"Failed to initialize evidence database: {e}")
131
  raise RuntimeError("Could not initialize evidence storage") from e
132
+
133
  @contextmanager
134
  def _get_db(self):
135
  conn = None
 
142
  finally:
143
  if conn:
144
  conn.close()
145
+
146
  def classify_action(self, action_text: str) -> str:
147
  action_lower = action_text.lower()
148
  if any(word in action_lower for word in ['database', 'db', 'sql', 'table', 'drop', 'delete']):
 
155
  return 'security'
156
  else:
157
  return 'default'
158
+
159
  def get_prior(self, action_type: str) -> Tuple[float, float]:
160
  prior = self.action_priors.get(action_type, self.action_priors['default'])
161
  return prior['alpha'], prior['beta']
162
+
163
  def get_evidence(self, action_hash: str) -> Tuple[int, int]:
164
  try:
165
  with self._get_db() as conn:
 
172
  except sqlite3.Error as e:
173
  logger.error(f"Failed to retrieve evidence: {e}")
174
  return (0, 0)
175
+
176
  def calculate_posterior(self, action_text: str, context: Dict[str, Any]) -> Dict[str, Any]:
177
  action_type = self.classify_action(action_text)
178
  alpha0, beta0 = self.get_prior(action_type)
 
184
  context_multiplier = self._context_likelihood(context)
185
  risk_score = posterior_mean * context_multiplier
186
  risk_score = min(0.99, max(0.01, risk_score))
187
+
188
  variance = (alpha_n * beta_n) / ((alpha_n + beta_n)**2 * (alpha_n + beta_n + 1))
189
  std_dev = variance ** 0.5
190
  ci_lower = max(0.01, posterior_mean - 1.96 * std_dev)
191
  ci_upper = min(0.99, posterior_mean + 1.96 * std_dev)
192
+
193
  if risk_score > 0.8:
194
  risk_level = RiskLevel.CRITICAL
195
  elif risk_score > 0.6:
 
198
  risk_level = RiskLevel.MEDIUM
199
  else:
200
  risk_level = RiskLevel.LOW
201
+
202
  return {
203
  "score": risk_score,
204
  "level": risk_level,
 
213
  Γ— Context multiplier {context_multiplier:.2f} = {risk_score:.3f}
214
  """
215
  }
216
+
217
  def _context_likelihood(self, context: Dict) -> float:
218
  multiplier = 1.0
219
  if context.get('environment') == 'production':
 
230
  if not context.get('backup_available', True):
231
  multiplier *= 1.6
232
  return multiplier
233
+
234
  def record_outcome(self, action_text: str, success: bool):
235
  action_hash = hashlib.sha256(action_text.encode()).hexdigest()
236
  action_type = self.classify_action(action_text)
 
254
 
255
  # ============== POLICY ENGINE ==============
256
  class PolicyEngine:
257
+ """Deterministic OSS policies – advisory only."""
258
  def __init__(self):
259
  self.config = {
260
  "confidence_threshold": settings.default_confidence_threshold,
 
278
  "require_human": [RiskLevel.CRITICAL, RiskLevel.HIGH],
279
  "require_rollback": True
280
  }
281
+
282
  def evaluate(self, action: str, risk: Dict[str, Any], confidence: float) -> Dict[str, Any]:
283
  import re
284
  gates = []
285
+
286
  # Gate 1: Confidence threshold
287
  confidence_passed = confidence >= self.config["confidence_threshold"]
288
  gates.append({
 
293
  "reason": f"Confidence {confidence:.2f} {'β‰₯' if confidence_passed else '<'} threshold {self.config['confidence_threshold']}",
294
  "type": "numerical"
295
  })
296
+
297
  # Gate 2: Risk level
298
  risk_levels = list(RiskLevel)
299
  max_idx = risk_levels.index(RiskLevel(self.config["max_autonomous_risk"]))
 
308
  "type": "categorical",
309
  "metadata": {"risk_score": risk["score"], "credible_interval": risk["credible_interval"]}
310
  })
311
+
312
  # Gate 3: Destructive check
313
  is_destructive = any(re.search(pattern, action.lower()) for pattern in self.config["destructive_patterns"])
314
  gates.append({
 
319
  "type": "boolean",
320
  "metadata": {"requires_rollback": is_destructive}
321
  })
322
+
323
  # Gate 4: Human review requirement
324
  requires_human = risk["level"] in self.config["require_human"]
325
  gates.append({
 
329
  "reason": "Human review not required" if not requires_human else f"Human review required for {risk['level'].value} risk",
330
  "type": "boolean"
331
  })
332
+
333
  # Gate 5: OSS license (always passes)
334
  gates.append({
335
  "gate": "license_check",
 
338
  "reason": "OSS edition - advisory only",
339
  "type": "license"
340
  })
341
+
342
  all_passed = all(g["passed"] for g in gates)
343
+
344
  if not all_passed:
345
  required_level = ExecutionLevel.OPERATOR_REVIEW
346
  elif risk["level"] == RiskLevel.LOW:
 
349
  required_level = ExecutionLevel.AUTONOMOUS_HIGH
350
  else:
351
  required_level = ExecutionLevel.SUPERVISED
352
+
353
  return {
354
  "allowed": all_passed,
355
  "required_level": required_level.value,
 
357
  "advisory_only": True,
358
  "oss_disclaimer": "OSS edition provides advisory only. Enterprise adds execution."
359
  }
360
+
361
  def update_config(self, key: str, value: Any):
362
  if key in self.config:
363
  self.config[key] = value
 
367
 
368
  # ============== RAG MEMORY ==============
369
  class RAGMemory:
370
+ """Persistent RAG memory with SQLite and simple embeddings."""
371
  def __init__(self):
372
  self.db_path = f"{settings.data_dir}/memory.db"
373
  self._init_db()
374
  self.embedding_cache = {}
375
+
376
  def _init_db(self):
377
  try:
378
  with self._get_db() as conn:
 
407
  except sqlite3.Error as e:
408
  logger.error(f"Failed to initialize memory database: {e}")
409
  raise RuntimeError("Could not initialize memory storage") from e
410
+
411
  @contextmanager
412
  def _get_db(self):
413
  conn = None
 
421
  finally:
422
  if conn:
423
  conn.close()
424
+
425
  def _simple_embedding(self, text: str) -> List[float]:
426
  if text in self.embedding_cache:
427
  return self.embedding_cache[text]
 
436
  vector = vector[:100]
437
  self.embedding_cache[text] = vector
438
  return vector
439
+
440
  def store_incident(self, action: str, risk_score: float, risk_level: RiskLevel,
441
  confidence: float, allowed: bool, gates: List[Dict]):
442
  action_hash = hashlib.sha256(action.encode()).hexdigest()[:50]
 
462
  conn.commit()
463
  except sqlite3.Error as e:
464
  logger.error(f"Failed to store incident: {e}")
465
+
466
  def find_similar(self, action: str, limit: int = 5) -> List[Dict]:
467
  query_embedding = self._simple_embedding(action)
468
  try:
 
490
  except sqlite3.Error as e:
491
  logger.error(f"Failed to find similar incidents: {e}")
492
  return []
493
+
494
  def track_enterprise_signal(self, signal_type: LeadSignal, action: str,
495
  risk_score: float, metadata: Dict = None):
496
  signal = {
 
521
  except sqlite3.Error as e:
522
  logger.error(f"Failed to track signal: {e}")
523
  return None
524
+
525
  logger.info(f"πŸ”” Enterprise signal: {signal_type.value} - {action[:50]}...")
526
  if signal_type in [LeadSignal.HIGH_RISK_BLOCKED, LeadSignal.NOVEL_ACTION]:
527
  self._notify_sales_team(signal)
528
  return signal
529
+
530
  def _notify_sales_team(self, signal: Dict):
531
  if settings.slack_webhook:
532
  try:
 
540
  }, timeout=5)
541
  except requests.RequestException as e:
542
  logger.error(f"Slack notification failed: {e}")
543
+
544
  def get_uncontacted_signals(self) -> List[Dict]:
545
  try:
546
  with self._get_db() as conn:
 
559
  except sqlite3.Error as e:
560
  logger.error(f"Failed to get uncontacted signals: {e}")
561
  return []
562
+
563
  def mark_contacted(self, signal_id: str):
564
  try:
565
  with self._get_db() as conn:
 
579
  )
580
  return credentials.credentials
581
 
582
+ # ============== PYDANTIC SCHEMAS ==============
583
  class ActionRequest(BaseModel):
584
  proposedAction: str = Field(..., min_length=1, max_length=1000)
585
  confidenceScore: float = Field(..., ge=0.0, le=1.0)
 
589
  rollbackFeasible: bool = True
590
  user_role: str = "devops"
591
  session_id: Optional[str] = None
592
+
593
  @field_validator('proposedAction')
594
  @classmethod
595
  def validate_action(cls, v: str) -> str:
 
627
  timestamp: str
628
  metadata: Dict
629
 
630
+ # ============== FASTAPI APP ==============
631
  app = FastAPI(
632
  title="ARF OSS Real Engine (API Only)",
633
  version="3.3.9",
634
+ description="Real ARF OSS components for enterprise lead generation – backend API only.",
635
  contact={
636
  "name": "ARF Sales",
637
  "email": settings.lead_email,
 
651
  policy_engine = PolicyEngine()
652
  memory = RAGMemory()
653
 
654
+ # ============== API ENDPOINTS ==============
655
+
656
  @app.get("/")
657
  async def root():
658
+ """Root endpoint for platform health checks."""
659
  return {
660
  "service": "ARF OSS API",
661
  "version": "3.3.9",
 
663
  "docs": "/docs"
664
  }
665
 
 
 
666
  @app.get("/health")
667
  async def health_check():
668
+ """Public health check endpoint."""
669
  return {
670
  "status": "healthy",
671
  "version": "3.3.9",
 
676
 
677
  @app.get("/api/v1/config", dependencies=[Depends(verify_api_key)])
678
  async def get_config():
679
+ """Get current ARF configuration."""
680
  return {
681
  "confidenceThreshold": policy_engine.config["confidence_threshold"],
682
  "maxAutonomousRisk": policy_engine.config["max_autonomous_risk"],
 
687
 
688
  @app.post("/api/v1/config", dependencies=[Depends(verify_api_key)])
689
  async def update_config(config: ConfigUpdateRequest):
690
+ """Update ARF configuration (protected)."""
691
  if config.confidenceThreshold:
692
  policy_engine.update_config("confidence_threshold", config.confidenceThreshold)
693
  if config.maxAutonomousRisk:
 
697
  @app.post("/api/v1/evaluate", dependencies=[Depends(verify_api_key)], response_model=EvaluationResponse)
698
  async def evaluate_action(request: ActionRequest):
699
  """
700
+ Real ARF OSS evaluation pipeline – protected.
701
  """
702
  try:
703
  context = {
 
706
  "backup_available": request.rollbackFeasible,
707
  "requires_human": request.requiresHuman
708
  }
709
+
710
  risk = risk_engine.calculate_posterior(
711
  action_text=request.proposedAction,
712
  context=context
713
  )
714
+
715
  policy = policy_engine.evaluate(
716
  action=request.proposedAction,
717
  risk=risk,
718
  confidence=request.confidenceScore
719
  )
720
+
721
  similar = memory.find_similar(request.proposedAction, limit=3)
722
+
723
  if not policy["allowed"] and risk["score"] > 0.7:
724
  memory.track_enterprise_signal(
725
  signal_type=LeadSignal.HIGH_RISK_BLOCKED,
 
731
  "failed_gates": [g["gate"] for g in policy["gates"] if not g["passed"]]
732
  }
733
  )
734
+
735
  if len(similar) < 2 and risk["score"] > 0.6:
736
  memory.track_enterprise_signal(
737
  signal_type=LeadSignal.NOVEL_ACTION,
 
739
  risk_score=risk["score"],
740
  metadata={"similar_count": len(similar)}
741
  )
742
+
743
  memory.store_incident(
744
  action=request.proposedAction,
745
  risk_score=risk["score"],
 
748
  allowed=policy["allowed"],
749
  gates=policy["gates"]
750
  )
751
+
752
  gates = []
753
  for g in policy["gates"]:
754
  gates.append(GateResult(
 
760
  type=g.get("type", "boolean"),
761
  metadata=g.get("metadata")
762
  ))
763
+
764
  execution_ladder = {
765
  "levels": [
766
  {"name": "AUTONOMOUS_LOW", "required": gates[0].passed and gates[1].passed},
 
770
  ],
771
  "current": policy["required_level"]
772
  }
773
+
774
  return EvaluationResponse(
775
  allowed=policy["allowed"],
776
  requiredLevel=policy["required_level"],
 
779
  escalationReason=None if policy["allowed"] else "Failed mechanical gates",
780
  executionLadder=execution_ladder
781
  )
782
+
783
  except Exception as e:
784
  logger.error(f"Evaluation failed: {e}", exc_info=True)
785
  raise HTTPException(
 
790
  @app.get("/api/v1/enterprise/signals", dependencies=[Depends(verify_api_key)])
791
  async def get_enterprise_signals(contacted: bool = False):
792
  """
793
+ Get enterprise lead signals (protected).
794
  """
795
  try:
796
  if contacted:
 
820
 
821
  @app.post("/api/v1/enterprise/signals/{signal_id}/contact", dependencies=[Depends(verify_api_key)])
822
  async def mark_signal_contacted(signal_id: str):
823
+ """Mark a lead signal as contacted (protected)."""
824
  memory.mark_contacted(signal_id)
825
  return {"status": "success", "message": "Signal marked as contacted"}
826
 
827
  @app.get("/api/v1/memory/similar", dependencies=[Depends(verify_api_key)])
828
  async def get_similar_actions(action: str, limit: int = 5):
829
+ """Find similar historical actions (protected)."""
830
  similar = memory.find_similar(action, limit=limit)
831
  return {"similar": similar, "count": len(similar)}
832
 
833
  @app.post("/api/v1/feedback", dependencies=[Depends(verify_api_key)])
834
  async def record_outcome(action: str, success: bool):
835
+ """Record actual outcome for Bayesian updating (protected)."""
836
  risk_engine.record_outcome(action, success)
837
  return {"status": "success", "message": "Outcome recorded"}
838
 
839
  # ============== MAIN ENTRY POINT ==============
840
  if __name__ == "__main__":
841
  import uvicorn
842
+
843
  port = int(os.environ.get('PORT', 7860))
844
+
845
  logger.info("="*60)
846
  logger.info("πŸš€ ARF OSS v3.3.9 (API Only) Starting")
847
  logger.info(f"πŸ“Š Data directory: {settings.data_dir}")
 
849
  logger.info(f"πŸ”‘ API Key: {settings.api_key[:8]}... (set in HF secrets)")
850
  logger.info(f"🌐 Serving API at: http://0.0.0.0:{port}")
851
  logger.info("="*60)
852
+
853
  uvicorn.run(
854
  "hf_demo:app",
855
+ host="0.0.0.0",
856
  port=port,
857
  log_level="info",
858
  reload=False