-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.py
More file actions
1526 lines (1187 loc) · 60.8 KB
/
validation.py
File metadata and controls
1526 lines (1187 loc) · 60.8 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ============================================================================
# validation.py - Validation framework with plugin registry
# ============================================================================
from abc import ABC
from collections.abc import Callable
from typing import Any
import numpy as np
from metadata.tracking import track_mechanism
from schemas import CognitiveTensor, Entity, ExposureEvent, PhysicalTensor
class Validator(ABC):
"""Base validator with plugin registry"""
_validators = {}
@classmethod
def register(cls, name: str, severity: str = "ERROR"):
def decorator(func: Callable):
cls._validators[name] = {"func": func, "severity": severity}
return func
return decorator
@classmethod
def validate_all(cls, entity: Entity, context: dict) -> list[dict]:
violations = []
for name, validator in cls._validators.items():
result = validator["func"](entity, context)
if not result["valid"]:
violations.append(
{
"validator": name,
"severity": validator["severity"],
"message": result["message"],
}
)
return violations
def validate_entity(self, entity: Entity, context: dict | None = None) -> dict[str, Any]:
"""
Validate an entity and return results.
Args:
entity: Entity to validate
context: Optional validation context
Returns:
Dict with validation results
"""
context = context or {}
violations = self.validate_all(entity, context)
return {
"valid": len(violations) == 0,
"violations": violations,
"entity_id": entity.entity_id,
}
@Validator.register("information_conservation", "ERROR")
def validate_information_conservation(entity: Entity, context: dict, store=None) -> dict:
"""Validate knowledge ⊆ exposure history"""
# Handle both Entity and EntityPopulation types
from schemas import EntityPopulation # Canonical location (breaks circular dep)
# If store is provided, query actual exposure events from database
if store:
entity_id = getattr(entity, "entity_id", "")
exposure_events = store.get_exposure_events(entity_id)
exposure = {event.information for event in exposure_events}
else:
# Fallback to context-based validation for backward compatibility
exposure_history = context.get("exposure_history", [])
# Handle both list of strings and list of ExposureEvent objects
if exposure_history and isinstance(exposure_history[0], ExposureEvent):
exposure = {event.information for event in exposure_history}
else:
exposure = set(exposure_history)
# Get knowledge state from either Entity or EntityPopulation
if isinstance(entity, EntityPopulation):
knowledge = set(entity.knowledge_state)
elif hasattr(entity, "entity_metadata"):
knowledge = set(entity.entity_metadata.get("knowledge_state", []))
else:
knowledge = set()
unknown = knowledge - exposure
if unknown:
return {"valid": False, "message": f"Entity knows about {unknown} without exposure"}
return {"valid": True, "message": "Information conservation satisfied"}
@Validator.register("energy_budget", "WARNING")
def validate_energy_budget(entity: Entity, context: dict) -> dict:
"""Validate interaction costs ≤ capacity with circadian adjustments"""
# Handle both Entity and EntityPopulation types
from schemas import EntityPopulation # Canonical location (breaks circular dep)
if isinstance(entity, EntityPopulation):
budget = entity.energy_budget
current_knowledge = set(entity.knowledge_state)
elif hasattr(entity, "entity_metadata"):
budget = entity.entity_metadata.get("energy_budget", 100)
current_knowledge = set(entity.entity_metadata.get("knowledge_state", []))
else:
# No energy data available
return {"valid": True, "message": "No energy budget data to validate"}
previous_knowledge = set(context.get("previous_knowledge", []) or [])
new_knowledge_count = len(current_knowledge - previous_knowledge)
# Base cost per knowledge item
base_expenditure = new_knowledge_count * 5
# Apply circadian adjustments if timepoint is available
timepoint = context.get("timepoint")
circadian_config = context.get("circadian_config", {})
if timepoint and circadian_config:
# Estimate activity type based on context (could be made more sophisticated)
activity_type = context.get("activity_type", "work") # Default assumption
expenditure = compute_energy_cost_with_circadian(
activity_type, timepoint.timestamp.hour, base_expenditure, circadian_config
)
else:
expenditure = base_expenditure
if expenditure > budget * 1.2: # Allow 20% temporary excess
hour_info = f" at {timepoint.timestamp.hour:02d}:00" if timepoint else ""
return {
"valid": False,
"message": f"Energy expenditure {expenditure:.1f}{hour_info} exceeds budget {budget}",
}
return {"valid": True, "message": "Energy budget satisfied"}
@Validator.register("behavioral_inertia", "WARNING")
def validate_behavioral_inertia(entity: Entity, context: dict) -> dict:
"""Validate personality drift is gradual"""
if "previous_personality" not in context or not context["previous_personality"]:
return {"valid": True, "message": "No previous state to compare"}
current = np.array(entity.entity_metadata.get("personality_traits", []))
previous = np.array(context["previous_personality"])
if len(current) == 0 or len(previous) == 0:
return {"valid": True, "message": "Personality data not available"}
# Handle different length arrays (take minimum length)
min_len = min(len(current), len(previous))
current = current[:min_len]
previous = previous[:min_len]
drift = np.linalg.norm(current - previous)
if drift > 1.0: # Threshold for significant personality change
return {"valid": False, "message": f"Personality drift {drift:.2f} exceeds threshold 1.0"}
return {"valid": True, "message": "Behavioral inertia satisfied"}
@Validator.register("biological_constraints", "ERROR")
@track_mechanism("M4", "constraint_enforcement")
def validate_biological_constraints(entity: Entity, context: dict) -> dict:
"""Validate age-dependent capabilities and biological plausibility"""
# Handle both Entity and EntityPopulation types
from schemas import EntityPopulation # Canonical location (breaks circular dep)
if isinstance(entity, EntityPopulation):
# EntityPopulation doesn't have age, skip validation
return {"valid": True, "message": "No age data in EntityPopulation"}
elif hasattr(entity, "entity_metadata"):
age = entity.entity_metadata.get("age", 0)
else:
return {"valid": True, "message": "No age data available"}
action = context.get("action", "")
violations = []
# Age-based constraint checks
if age > 100 and "physical_labor" in action:
violations.append(f"age {age} incompatible with physical labor")
if (age < 18 or age > 50) and "childbirth" in action:
violations.append(f"age {age} outside plausible childbirth range (18-50)")
if age < 5 and any(a in action for a in ["negotiate", "strategic_planning", "combat"]):
violations.append(f"age {age} incompatible with {action}")
if age > 80 and any(a in action for a in ["sprint", "heavy_lifting", "combat"]):
violations.append(f"age {age} incompatible with {action}")
# Resource constraint checks (if quantitative state available)
resource_state = context.get("resource_state", {})
for resource_name, value in resource_state.items():
constraint = context.get("resource_constraints", {}).get(resource_name)
if constraint:
if "min" in constraint and value < constraint["min"]:
violations.append(
f"{resource_name} ({value:.1f}) below minimum ({constraint['min']})"
)
if "max" in constraint and value > constraint["max"]:
violations.append(
f"{resource_name} ({value:.1f}) above maximum ({constraint['max']})"
)
if violations:
return {"valid": False, "message": f"Constraint violations: {'; '.join(violations)}"}
return {"valid": True, "message": "Biological constraints satisfied"}
@Validator.register("network_flow", "WARNING")
def validate_network_flow(entity: Entity, context: dict) -> dict:
"""Validate that influence/status changes propagate through relationship graph edges"""
graph = context.get("graph")
if not graph or entity.entity_id not in graph:
return {"valid": True, "message": "No graph available for network flow validation"}
# Get current knowledge as a proxy for "influence" or "status"
current_knowledge = set(entity.entity_metadata.get("knowledge_state", []))
previous_knowledge = set(context.get("previous_knowledge", []) or [])
# Check for new knowledge acquisition
new_knowledge = current_knowledge - previous_knowledge
if not new_knowledge:
return {"valid": True, "message": "No new knowledge to validate network flow"}
# Check if entity has connections to sources of this knowledge
connected_entities = set(graph.neighbors(entity.entity_id))
# Note: Don't include self for network flow validation - self-knowledge is allowed
# Get knowledge from connected entities (simplified - in real implementation,
# we'd need to track knowledge propagation through time)
connected_knowledge = set()
for connected_id in connected_entities:
if connected_id in context.get("all_entity_knowledge", {}):
connected_knowledge.update(context["all_entity_knowledge"][connected_id])
# Check if new knowledge could have come from connected entities
unexplained_knowledge = new_knowledge - connected_knowledge
# Allow some knowledge to come from events/exposure (not just direct connections)
exposure_knowledge = set(context.get("exposure_history", []))
truly_unexplained = unexplained_knowledge - exposure_knowledge
# DEBUG: Uncomment for validation debugging
# print(f"DEBUG {entity.entity_id}: new={new_knowledge}, connected={connected_entities}, connected_knowledge={connected_knowledge}, unexplained={unexplained_knowledge}, exposure={exposure_knowledge}, truly_unexplained={truly_unexplained}")
if truly_unexplained:
return {
"valid": False,
"message": f"Entity gained knowledge {list(truly_unexplained)} without network connections or exposure",
}
return {"valid": True, "message": "Network flow validation satisfied"}
@Validator.register("temporal_causality", "ERROR")
def validate_temporal_causality(entity: Entity, context: dict) -> dict:
"""Validate that entity knowledge follows causal temporal constraints"""
store = context.get("store")
timepoint_id = context.get("timepoint_id")
if not store or not timepoint_id:
return {"valid": True, "message": "Insufficient context for temporal causality validation"}
# Check each knowledge item for temporal validity
from temporal_chain import (
validate_temporal_reference, # Import locally to avoid circular import
)
knowledge_state = entity.entity_metadata.get("knowledge_state", [])
invalid_items = []
for knowledge_item in knowledge_state:
validation = validate_temporal_reference(
entity.entity_id, knowledge_item, timepoint_id, store
)
if not validation["valid"]:
invalid_items.append(knowledge_item)
if invalid_items:
return {
"valid": False,
"message": f"Entity has knowledge {invalid_items} that violates temporal causality",
}
return {"valid": True, "message": "Temporal causality satisfied"}
# ============================================================================
# Body-Mind Coupling Functions (Mechanism 8.1)
# ============================================================================
def couple_pain_to_cognition(
physical: PhysicalTensor, cognitive: CognitiveTensor
) -> CognitiveTensor:
"""Pain affects cognitive state - reduces energy, worsens mood, lowers patience"""
pain_factor = physical.pain_level
# Reduce energy budget based on pain level
cognitive.energy_budget *= 1.0 - pain_factor * 0.5
# Reduce emotional valence (more negative mood)
cognitive.emotional_valence -= pain_factor * 0.3
# Reduce patience threshold
cognitive.patience_threshold -= pain_factor * 0.4
# Reduce decision confidence
cognitive.decision_confidence *= 1.0 - pain_factor * 0.2
return cognitive
def couple_illness_to_cognition(
physical: PhysicalTensor, cognitive: CognitiveTensor
) -> CognitiveTensor:
"""Illness impairs judgment and engagement"""
if physical.fever > 38.5: # High fever threshold
# Reduce decision confidence due to cognitive impairment
cognitive.decision_confidence *= 0.7
# Increase risk tolerance (fever makes people more reckless)
cognitive.risk_tolerance += 0.2
# Reduce social engagement due to illness
cognitive.social_engagement -= 0.4
return cognitive
# ============================================================================
# Dialog Quality Validators (Mechanism 11)
# ============================================================================
@Validator.register("dialog_realism", severity="WARNING")
def validate_dialog_realism(entity: Entity, context: dict = None) -> dict:
"""Check if dialog respects physical/emotional constraints"""
if context is None:
context = {}
# This validator only applies to Dialog objects, skip for regular entities
if not hasattr(entity, "entity_metadata") or "dialog_data" not in entity.entity_metadata:
return {"valid": True, "message": "Not a dialog entity, skipping dialog validation"}
dialog_data = entity.entity_metadata.get("dialog_data", {})
# Parse dialog turns
turns = dialog_data.get("turns", [])
if isinstance(turns, str):
import json
turns = json.loads(turns)
validation_issues = []
# Get entities from context if available
entities = context.get("entities", [])
if not entities:
# If no entities in context, skip detailed validation
return {"valid": True, "message": "No entities in context for dialog validation"}
for i, turn in enumerate(turns):
speaker_id = turn.get("speaker")
content = turn.get("content", "")
turn_index = i + 1
# Find speaker entity
speaker = next((e for e in entities if e.entity_id == speaker_id), None)
if not speaker:
continue
# Get speaker's current state
physical = speaker.physical_tensor
cognitive = speaker.cognitive_tensor
# Apply body-mind coupling for validation
coupled_cognitive = couple_pain_to_cognition(physical, cognitive)
coupled_cognitive = couple_illness_to_cognition(physical, coupled_cognitive)
# Check turn length vs. energy
content_length = len(content)
if coupled_cognitive.energy_budget < 30 and content_length > 200:
validation_issues.append(
f"{speaker_id} too low energy ({coupled_cognitive.energy_budget:.1f}) for long response ({content_length} chars)"
)
# Check tone vs. emotional state
emotional_tone = turn.get("emotional_tone", "").lower()
valence = coupled_cognitive.emotional_valence
if valence < -0.5 and not any(
neg in emotional_tone for neg in ["sad", "angry", "frustrated", "negative"]
):
validation_issues.append(
f"{speaker_id} should have negative tone given emotional valence {valence:.2f}"
)
# Check pain impact on engagement
if physical.pain_level > 0.6 and turn_index > 5: # Long conversation
validation_issues.append(
f"{speaker_id} unlikely to sustain conversation with pain level {physical.pain_level}"
)
# Check stamina impact on conversation length
stamina = physical.stamina
if stamina < 0.3 and content_length > 50:
validation_issues.append(
f"{speaker_id} has low stamina ({stamina:.2f}) but gives detailed response"
)
if validation_issues:
return {"valid": False, "message": f"Dialog realism issues: {'; '.join(validation_issues)}"}
return {"valid": True, "message": "Dialog respects physical/emotional constraints"}
@Validator.register("dialog_knowledge_consistency", severity="ERROR")
def validate_dialog_knowledge_consistency(entity: Entity, context: dict = None) -> dict:
"""Check if dialog speakers only reference knowledge they actually have"""
if context is None:
context = {}
# This validator only applies to Dialog objects, skip for regular entities
if not hasattr(entity, "entity_metadata") or "dialog_data" not in entity.entity_metadata:
return {
"valid": True,
"message": "Not a dialog entity, skipping dialog knowledge validation",
}
dialog_data = entity.entity_metadata.get("dialog_data", {})
# Parse dialog turns
turns = dialog_data.get("turns", [])
if isinstance(turns, str):
import json
turns = json.loads(turns)
knowledge_violations = []
# Get entities from context if available
entities = context.get("entities", [])
if not entities:
# If no entities in context, skip detailed validation
return {"valid": True, "message": "No entities in context for dialog knowledge validation"}
for turn in turns:
speaker_id = turn.get("speaker")
content = turn.get("content", "")
knowledge_refs = turn.get("knowledge_references", [])
# Find speaker entity
speaker = next((e for e in entities if e.entity_id == speaker_id), None)
if not speaker:
continue
# Get speaker's knowledge state
speaker_knowledge = set(speaker.entity_metadata.get("knowledge_state", []))
# Check explicit knowledge references
for ref in knowledge_refs:
if ref not in speaker_knowledge:
knowledge_violations.append(f"{speaker_id} references unknown knowledge: '{ref}'")
# Check for anachronistic references in content (simple heuristic)
words = content.lower().split()
for word in words:
if word[0].isupper() and len(word) > 3: # Potential proper noun
if word.lower() not in [k.lower() for k in speaker_knowledge]:
# Allow some flexibility for proper nouns that might not be in knowledge
continue
if knowledge_violations:
return {
"valid": False,
"message": f"Knowledge consistency violations: {'; '.join(knowledge_violations)}",
}
return {"valid": True, "message": "Dialog respects knowledge constraints"}
@Validator.register("dialog_relationship_consistency", severity="WARNING")
def validate_dialog_relationship_consistency(entity: Entity, context: dict = None) -> dict:
"""Check if dialog tone matches established relationship dynamics"""
if context is None:
context = {}
# This validator only applies to Dialog objects, skip for regular entities
if not hasattr(entity, "entity_metadata") or "dialog_data" not in entity.entity_metadata:
return {
"valid": True,
"message": "Not a dialog entity, skipping dialog relationship validation",
}
dialog_data = entity.entity_metadata.get("dialog_data", {})
# Parse dialog turns
turns = dialog_data.get("turns", [])
if isinstance(turns, str):
import json
turns = json.loads(turns)
relationship_issues = []
# Get entities from context if available
entities = context.get("entities", [])
if not entities:
# If no entities in context, skip detailed validation
return {
"valid": True,
"message": "No entities in context for dialog relationship validation",
}
# Build relationship map
entity_map = {e.entity_id: e for e in entities}
for turn in turns:
speaker_id = turn.get("speaker")
turn.get("content", "")
emotional_tone = turn.get("emotional_tone", "").lower()
# Check relationship with each other participant
for entity in entities:
if entity.entity_id == speaker_id:
continue
# Compute relationship metrics
from workflows import compute_relationship_metrics
metrics = compute_relationship_metrics(entity_map[speaker_id], entity)
trust_level = metrics.get("trust", 0.5)
alignment = metrics.get("alignment", 0.0)
# Check if tone matches relationship
if trust_level < 0.3 and not any(
neg in emotional_tone for neg in ["guarded", "formal", "tense", "hostile"]
):
relationship_issues.append(
f"{speaker_id} should show guarded tone with {entity.entity_id} (trust: {trust_level:.2f})"
)
if alignment < -0.5 and not any(
neg in emotional_tone for neg in ["critical", "oppositional", "disagreeable"]
):
relationship_issues.append(
f"{speaker_id} should show disagreement with {entity.entity_id} (alignment: {alignment:.2f})"
)
if relationship_issues:
return {
"valid": False,
"message": f"Relationship consistency issues: {'; '.join(relationship_issues)}",
}
return {"valid": True, "message": "Dialog tone matches relationship dynamics"}
# ============================================================================
# Mechanism 14: Circadian Activity Patterns
# ============================================================================
def get_activity_probability(hour: int, activity: str, circadian_config: dict) -> float:
"""Get probability of an activity at a given hour"""
activity_probs = circadian_config.get("activity_probabilities", {})
if activity not in activity_probs:
return 0.1 # Default low probability for unknown activities
activity_config = activity_probs[activity]
allowed_hours = activity_config.get("hours", [])
base_probability = activity_config.get("probability", 0.1)
if hour in allowed_hours:
return base_probability
# Check for adjacent hours (some flexibility)
if hour - 1 in allowed_hours or hour + 1 in allowed_hours:
return base_probability * 0.5 # Half probability for adjacent hours
return 0.05 # Very low probability for inappropriate hours
@track_mechanism("M14", "circadian_patterns")
def compute_energy_cost_with_circadian(
activity: str, hour: int, base_cost: float, circadian_config: dict
) -> float:
"""Compute energy cost adjusted for circadian factors"""
multipliers = circadian_config.get("energy_multipliers", {})
fatigue_threshold = multipliers.get("base_fatigue_threshold", 16)
# Base circadian penalty for nighttime activities
if 22 <= hour or hour < 6:
circadian_penalty = multipliers.get("night_penalty", 1.5)
else:
circadian_penalty = 1.0
# Fatigue accumulation based on hours awake
hours_awake = (hour - 6) if hour >= 6 else (hour + 18) # Assuming wake at 6am
if hours_awake > fatigue_threshold:
fatigue_factor = (
1.0
+ (hours_awake - fatigue_threshold)
* multipliers.get("fatigue_accumulation", 0.5)
/ fatigue_threshold
)
else:
fatigue_factor = 1.0
return base_cost * circadian_penalty * fatigue_factor
@Validator.register("circadian_plausibility", severity="WARNING")
def validate_circadian_activity(entity: Entity, context: dict = None) -> dict:
"""Check if activity is plausible at the given time of day"""
if context is None:
context = {}
# Get activity and timepoint from context
activity = context.get("activity")
timepoint = context.get("timepoint")
# If no activity or timepoint specified, skip validation
if not activity or not timepoint:
return {
"valid": True,
"message": "No activity or timepoint specified for circadian validation",
}
# Get circadian config from context or default
circadian_config = context.get("circadian_config", {})
hour = timepoint.timestamp.hour
probability = get_activity_probability(hour, activity, circadian_config)
thresholds = circadian_config.get("validation", {})
low_threshold = thresholds.get("low_probability_threshold", 0.1)
critical_threshold = thresholds.get("critical_probability_threshold", 0.05)
if probability < critical_threshold:
return {
"valid": False,
"message": f"Activity '{activity}' at {hour:02d}:00 is highly implausible (probability: {probability:.3f})",
}
elif probability < low_threshold:
return {
"valid": True, # Warning, not error
"message": f"Activity '{activity}' at {hour:02d}:00 is unusual (probability: {probability:.3f})",
}
return {
"valid": True,
"message": f"Activity '{activity}' at {hour:02d}:00 is plausible (probability: {probability:.3f})",
}
def create_circadian_context(hour: int, circadian_config: dict) -> "CircadianContext":
"""Create a circadian context for a given hour"""
from schemas import CircadianContext
# Build typical activities dictionary
typical_activities = {}
activity_probs = circadian_config.get("activity_probabilities", {})
for activity, _config in activity_probs.items():
prob = get_activity_probability(hour, activity, circadian_config)
typical_activities[activity] = prob
# Determine ambient conditions based on hour
if 6 <= hour < 12:
ambient_conditions = {"lighting": 0.8, "noise": 0.6, "temperature": 0.7}
social_constraints = ["morning_business", "daylight_activities"]
elif 12 <= hour < 18:
ambient_conditions = {"lighting": 0.9, "noise": 0.7, "temperature": 0.8}
social_constraints = ["afternoon_work", "daylight_social"]
elif 18 <= hour < 22:
ambient_conditions = {"lighting": 0.6, "noise": 0.8, "temperature": 0.6}
social_constraints = ["evening_social", "indoor_activities"]
else: # Night
ambient_conditions = {"lighting": 0.2, "noise": 0.3, "temperature": 0.5}
social_constraints = ["night_rest", "quiet_activities"]
# Calculate fatigue level (simplified)
hours_awake = (hour - 6) if hour >= 6 else (hour + 18)
fatigue_level = min(1.0, max(0.0, (hours_awake - 8) / 16)) # Peak fatigue after 16 hours awake
# Energy penalty based on circadian config
multipliers = circadian_config.get("energy_multipliers", {})
if 22 <= hour or hour < 6:
energy_penalty = multipliers.get("night_penalty", 1.5)
else:
energy_penalty = 1.0
return CircadianContext(
hour=hour,
typical_activities=typical_activities,
ambient_conditions=ambient_conditions,
social_constraints=social_constraints,
fatigue_level=fatigue_level,
energy_penalty=energy_penalty,
)
# ============================================================================
# Mechanism 15: Entity Prospection
# ============================================================================
@Validator.register("prospection_consistency", severity="WARNING")
def validate_prospection_consistency(entity: Entity, context: dict = None) -> dict:
"""Validate that prospective expectations are consistent and realistic"""
if context is None:
context = {}
# Get prospective_state from context
prospective_state = context.get("prospective_state")
if not prospective_state:
return {"valid": True, "message": "No prospective state to validate"}
# Parse expectations
expectations = prospective_state.expectations
if isinstance(expectations, str):
import json
expectations = json.loads(expectations)
from schemas import Expectation
expectation_objects = [
Expectation(**exp) if isinstance(exp, dict) else exp for exp in expectations
]
issues = []
total_probability = 0
# Check for unrealistic probabilities
for exp in expectation_objects:
total_probability += exp.subjective_probability
# Flag extremely low or high probabilities
if exp.subjective_probability < 0.05:
issues.append(
f"Expectation '{exp.predicted_event}' has very low probability ({exp.subjective_probability:.3f})"
)
elif exp.subjective_probability > 0.95:
issues.append(
f"Expectation '{exp.predicted_event}' has very high probability ({exp.subjective_probability:.3f})"
)
# Check confidence vs probability alignment
if exp.confidence > 0.8 and exp.subjective_probability < 0.2:
issues.append(
f"High confidence ({exp.confidence:.2f}) but low probability ({exp.subjective_probability:.3f}) for '{exp.predicted_event}'"
)
# Check total probability isn't unrealistic
if total_probability > 1.5: # Allow some overlap but flag excessive
issues.append(
f"Total expectation probabilities ({total_probability:.2f}) suggest unrealistic optimism"
)
# Check anxiety level reasonableness
anxiety_level = prospective_state.anxiety_level
if anxiety_level > 0.9:
issues.append(
f"Extremely high anxiety level ({anxiety_level:.2f}) may indicate unrealistic expectations"
)
if issues:
return {"valid": False, "message": f"Prospection consistency issues: {'; '.join(issues)}"}
return {
"valid": True,
"message": f"Prospective expectations appear consistent (anxiety: {anxiety_level:.2f})",
}
@Validator.register("prospection_energy_impact", severity="WARNING")
def validate_prospection_energy_impact(entity: "Entity", context: dict = None) -> dict:
"""Validate that prospection doesn't deplete energy unrealistically"""
if context is None:
context = {}
# Get prospective_state from context
prospective_state = context.get("prospective_state")
if not prospective_state:
return {"valid": True, "message": "No prospective state to validate"}
# Parse expectations
expectations = prospective_state.expectations
if isinstance(expectations, str):
import json
expectations = json.loads(expectations)
from schemas import Expectation
expectation_objects = [
Expectation(**exp) if isinstance(exp, dict) else exp for exp in expectations
]
# Calculate preparation energy cost
total_prep_cost = 0
for exp in expectation_objects:
for action in exp.preparation_actions:
from workflows import estimate_energy_cost_for_preparation
total_prep_cost += estimate_energy_cost_for_preparation(action)
# Get config values
config = context.get("prospection_config", {})
preparation_energy_cost = config.get("behavioral_influence", {}).get(
"preparation_energy_cost", 5
)
anxiety_energy_penalty = config.get("behavioral_influence", {}).get(
"anxiety_energy_penalty", 0.2
)
total_energy_cost = (total_prep_cost * preparation_energy_cost) + (
prospective_state.anxiety_level * anxiety_energy_penalty
)
# Check against entity's energy budget
entity_energy = getattr(entity, "cognitive_tensor", None)
if entity_energy and hasattr(entity_energy, "energy_budget"):
if total_energy_cost > entity_energy.energy_budget * 0.8: # More than 80% of budget
return {
"valid": False,
"message": f"Prospection energy cost ({total_energy_cost:.1f}) exceeds 80% of entity budget ({entity_energy.energy_budget})",
}
return {
"valid": True,
"message": f"Prospection energy impact acceptable ({total_energy_cost:.1f} cost)",
}
# ============================================================================
# Mechanism 12: Counterfactual Branching
# ============================================================================
@Validator.register("branch_consistency", severity="WARNING")
def validate_branch_consistency(entity: Entity, context: dict = None) -> dict:
"""Validate that a branch timeline is consistent with its parent"""
if context is None:
context = {}
# Get timelines from context
branch_timeline = context.get("branch_timeline")
baseline_timeline = context.get("baseline_timeline")
if not branch_timeline:
return {"valid": True, "message": "No branch timeline to validate"}
issues = []
# Check that branch has required fields
if not branch_timeline.parent_timeline_id:
return {"valid": False, "message": "Branch timeline missing parent_timeline_id"}
if not branch_timeline.branch_point:
issues.append("Branch timeline missing branch_point")
if not branch_timeline.intervention_description:
issues.append("Branch timeline missing intervention_description")
# If baseline provided, check consistency
if baseline_timeline:
# Branch should diverge at or after the branch point
if branch_timeline.branch_point:
# This would require checking timepoint timestamps
pass
if issues:
return {"valid": False, "message": f"Branch consistency issues: {'; '.join(issues)}"}
return {
"valid": True,
"message": f"Branch timeline consistent with parent {branch_timeline.parent_timeline_id}",
}
@Validator.register("intervention_plausibility", severity="WARNING")
def validate_intervention_plausibility(entity: Entity, context: dict = None) -> dict:
"""Validate that an intervention is plausible and well-formed"""
if context is None:
context = {}
intervention = context.get("intervention")
if not intervention:
return {"valid": True, "message": "No intervention to validate"}
issues = []
# Check intervention type validity
valid_types = [
"entity_removal",
"entity_modification",
"event_cancellation",
"knowledge_alteration",
]
if intervention.type not in valid_types:
issues.append(f"Invalid intervention type: {intervention.type}")
# Check required fields
if not intervention.target:
issues.append("Intervention missing target")
# Type-specific validation
if intervention.type == "entity_modification":
if not intervention.parameters.get("modifications"):
issues.append("Entity modification intervention missing 'modifications' parameter")
elif intervention.type == "knowledge_alteration":
if not intervention.parameters.get("knowledge_changes"):
issues.append("Knowledge alteration intervention missing 'knowledge_changes' parameter")
# Check description
if not intervention.description:
issues.append("Intervention missing description")
if issues:
return {"valid": False, "message": f"Intervention plausibility issues: {'; '.join(issues)}"}
return {"valid": True, "message": f"Intervention '{intervention.description}' is plausible"}
@Validator.register("timeline_divergence", severity="INFO")
def validate_timeline_divergence(entity: Entity, context: dict = None) -> dict:
"""Validate that timeline divergence is meaningful and causal"""
if context is None:
context = {}
comparison = context.get("comparison")
if not comparison:
return {"valid": True, "message": "No comparison to validate"}
# Check that there's actually a divergence
if not comparison.divergence_point:
return {
"valid": True, # Not necessarily invalid, but noteworthy
"message": "No timeline divergence detected - branches may be identical",
}
# Check that divergence is explained
if (
not comparison.causal_explanation
or comparison.causal_explanation == "Timelines are identical - no divergence detected"
):
return {
"valid": False,
"message": f"Timeline diverges at {comparison.divergence_point} but lacks causal explanation",
}
# Check that there are meaningful differences
total_changes = len(comparison.key_events_differed) + len(comparison.entity_states_differed)
if total_changes == 0:
return {
"valid": False,
"message": f"Timeline diverges at {comparison.divergence_point} but no substantive changes detected",
}
return {
"valid": True,
"message": f"Timeline divergence at {comparison.divergence_point} is well-explained with {total_changes} changes",
}
# ============================================================================
# Mechanism 16: Animistic Entity Extension
# ============================================================================
@Validator.register("environmental_constraints", severity="ERROR")
def validate_environmental_constraints(entity: Entity, context: dict = None) -> dict:
"""Validate that actions respect constraints imposed by animistic entities"""
if context is None:
context = {}
action = context.get("action")
environment_entities = context.get("environment_entities", [])
if not action or not environment_entities:
return {"valid": True, "message": "No action or environment entities to validate"}
issues = []
for env_entity in environment_entities:
if env_entity.entity_type == "building":
# Import here to avoid circular imports
from schemas import BuildingEntity
try:
building = BuildingEntity(**env_entity.entity_metadata)
participant_count = action.get("participant_count", 0)