2323class CommitGuardBrain :
2424 """
2525 Elite Agent Brain: Decoupled from LLM Providers via LLMFactory.
26+ 2026 Upgrade: Cultural Persona Routing & Industry Intelligence.
2627 """
2728
29+ CULTURAL_PROMPTS = {
30+ "en" : "Standard professional tone. Focus on clarity and deadline accountability." ,
31+ "en-UK" : "British professional tone. Use polite understatements and avoid over-assertiveness." ,
32+ "ja" : "High-context Japanese tone. Prioritize harmony (wa). Use indirect observations and soft suggestions instead of direct demands." ,
33+ "de" : "Direct German Sachlichkeit. Focus on objective facts, precision, and straightforward feedback. No fluff." ,
34+ }
35+
2836 def __init__ (self ):
2937 self .provider = LLMFactory .get_provider ()
3038 self .model = settings .MODEL_NAME
3139
40+ async def detect_language (self , text : str ) -> str :
41+ """
42+ 2026 Agentic Language Detection: Uses semantic intent to identify cultural context.
43+ """
44+ # In a real 2026 deployment, we might use a dedicated lightweight model.
45+ # Here we use the main provider with a strict routing prompt.
46+ try :
47+ detected = await self .provider .chat_completion (
48+ response_model = str ,
49+ model = self .model ,
50+ messages = [
51+ {
52+ "role" : "system" ,
53+ "content" : "Detect the language and cultural nuance of the following text. Return only the code: 'en', 'ja', or 'de'." ,
54+ },
55+ {"role" : "user" , "content" : text },
56+ ],
57+ )
58+ return str (detected ).strip ().lower () if detected in ["en" , "ja" , "de" ] else "en"
59+ except Exception :
60+ return "en" # Fallback to English
61+
3262 async def analyze_excuse (self , user_input : str ) -> ExcuseAnalysis :
3363 return await self .provider .chat_completion (
3464 response_model = ExcuseAnalysis ,
@@ -93,13 +123,18 @@ async def evaluate_participation(
93123 check_in : str ,
94124 reliability_score : float ,
95125 consecutive_firm : int ,
126+ lang : str | None = None ,
127+ industry : str | None = None ,
96128 ) -> PipelineEvaluation :
97129 """
98130 The Orchestration Pipeline: Decoupled and high-fidelity evaluation.
99131 """
132+ # 0. Language Awareness
133+ target_lang = lang or await self .detect_language (check_in )
134+ target_industry = industry or settings .SELECTED_INDUSTRY
135+
100136 try :
101137 # 1. Parallel Analysis Phase (High Velocity) with Safety Timeout
102- # We enforce a 30s SLA for the initial heuristic/LLM sweep.
103138 excuse , burnout , risk = await asyncio .wait_for (
104139 asyncio .gather (
105140 self .analyze_excuse (check_in ),
@@ -115,7 +150,6 @@ async def evaluate_participation(
115150 logger .error (
116151 "orchestration_timeout" , user_id = user_id , status = "aborting_pipeline"
117152 )
118- # Fallback for critical failure: supportive neutral message
119153 return PipelineEvaluation (
120154 decision = AgentDecision (
121155 action = "escalate_to_manager" ,
@@ -124,7 +158,7 @@ async def evaluate_participation(
124158 analysis_summary = "Orchestration Timeout: AI Providers failed to respond within 30s." ,
125159 ),
126160 excuse = ExcuseAnalysis (
127- category = ExcuseCategory .LEGITIMATE , # Benefit of the doubt
161+ category = ExcuseCategory .LEGITIMATE ,
128162 confidence_score = 0.0 ,
129163 reasoning = "Timeout: Analysis incomplete." ,
130164 ),
@@ -141,31 +175,32 @@ async def evaluate_participation(
141175 ),
142176 )
143177
144- # 2. Decision Synthesis
178+ # 2. Decision Synthesis (Culture & Industry Aware)
145179 with LatencyMonitor ("decision_synthesis_latency" , user_id ):
146180 decision = await self .adapt_tone (
147181 excuse ,
148182 risk ,
149183 burnout ,
150184 reliability_score = reliability_score ,
151185 consecutive_firm_calls = consecutive_firm ,
186+ lang = target_lang ,
187+ industry = target_industry ,
152188 )
153189
154- # 3. Final Ethical Supervision (Elite Guardrail )
190+ # 3. Final Ethical Supervision (Semantic Firewall )
155191 supervisor = SafetySupervisor ()
156192 context = (
157193 f"User: { user_id } . Reliability: { reliability_score } %. "
158- f"Consecutive firm: { consecutive_firm } ."
194+ f"Consecutive firm: { consecutive_firm } . Industry: { target_industry } . "
159195 )
160196
161197 with LatencyMonitor ("safety_supervisor_latency" , user_id ):
162198 audit = await supervisor .audit_message (
163- decision .message , decision .tone , context
199+ decision .message , decision .tone , context , industry = target_industry
164200 )
165201
166202 intervention = None
167203
168- # A. HARD BLOCK (HR Territory) - Immediate Escalation, No Retry
169204 if audit .is_hard_blocked :
170205 logger .critical (
171206 "hr_legal_boundary_detected" , user_id = user_id , message = decision .message
@@ -182,40 +217,34 @@ async def evaluate_participation(
182217 intervention_type = "block" ,
183218 )
184219
185- # B. SOFT CORRECTION (Tone/Cultural) - Injection Mechanism
186220 elif not audit .is_safe :
187221 logger .warning (
188222 "safety_correction_injected" , user_id = user_id , reason = audit .reasoning
189223 )
190224 original = decision .message
191- # Capitalization Hook: Ensure correction starts with uppercase
192225 raw_correction = audit .suggested_correction or decision .message
193226 if raw_correction and len (raw_correction ) > 0 :
194227 raw_correction = raw_correction [0 ].upper () + raw_correction [1 :]
195228
196229 decision .message = raw_correction
197230 decision .analysis_summary += f" | Safety Correction: { audit .reasoning } "
198231
199- # --- SAFETY VALVE: RE-VALIDATION (Tier 4 Humility) ---
200- # Verify the correction itself is not unsafe (e.g., hallucinated threat).
201- # This doubles latency but ensures zero-trust safety.
202232 re_audit = await supervisor .audit_message (
203- decision .message , decision .tone , context
233+ decision .message , decision .tone , context , industry = target_industry
204234 )
205235 if not re_audit .is_safe :
206236 logger .critical (
207237 "unsafe_correction_caught" ,
208238 user_id = user_id ,
209239 bad_fix = decision .message ,
210240 )
211- # Fallback to HITL if the AI failed to fix it safely
212241 decision .action = "escalate_to_manager"
213242 decision .message = (
214243 "Automated correction failed safety check. Manual review required."
215244 )
216245 intervention = SafetyIntervention (
217246 original_message = original ,
218- corrected_message = None , # Discard unsafe fix
247+ corrected_message = None ,
219248 reasoning = "Safety Valve Triggered: Correction was still unsafe." ,
220249 intervention_type = "review" ,
221250 )
@@ -227,7 +256,6 @@ async def evaluate_participation(
227256 intervention_type = "correction" ,
228257 )
229258
230- # C. AMBIGUITY (Low Confidence) - Human-in-the-Loop
231259 elif (
232260 audit .requires_human_review
233261 or audit .supervisor_confidence < settings .SAFETY_CONFIDENCE_THRESHOLD
@@ -257,18 +285,26 @@ async def adapt_tone(
257285 burnout : BurnoutDetection ,
258286 reliability_score : float = 100.0 ,
259287 consecutive_firm_calls : int = 0 ,
288+ lang : str = "en" ,
289+ industry : str = "generic" ,
260290 ) -> AgentDecision :
261- # ENTERPRISE LLM PROMPT (Self-Correction / Sensitivity)
291+ # 2026 Cultural Persona Logic
292+ cultural_instruction = self .CULTURAL_PROMPTS .get (lang , self .CULTURAL_PROMPTS ["en" ])
293+
262294 prompt = f"""
263- Determine action and tone.
264- User Reliability: { reliability_score } %
265- Consecutive Strict Interventions: { consecutive_firm_calls }
266- Manager's Cultural Directness Setting: { settings .CULTURAL_DIRECTNESS_LEVEL }
295+ Role: CommitGuard Decision Agent
296+ Focus Industry: { industry }
297+ Cultural Persona: { cultural_instruction }
298+
299+ Context:
300+ - User Reliability: { reliability_score } %
301+ - Consecutive Strict Interventions: { consecutive_firm_calls }
302+ - Cultural Directness: { settings .CULTURAL_DIRECTNESS_LEVEL }
267303
268- RULES :
269- - If Consecutive Strict >= 3, you MUST use SUPPORTIVE/NEUTRAL tone
270- to avoid morale burnout.
271- - Respect the Cultural Directness: if 'low ', soften all firm feedback .
304+ Rules :
305+ - If Consecutive Strict >= 3, use SUPPORTIVE/NEUTRAL tone.
306+ - Respect the Cultural Persona above above ALL else.
307+ - If industry is 'healthcare' or 'finance ', avoid any phrasing that implies legally binding commitments unless explicit .
272308 """
273309
274310 return await self .provider .chat_completion (
0 commit comments