/ core / database / models.py
models.py
  1  """
  2  Data models for the God Database.
  3  
  4  These are the atomic units that form the foundation of the entire system.
  5  """
  6  
  7  from dataclasses import dataclass, field
  8  from datetime import datetime
  9  from enum import Enum
 10  from typing import Optional, List, Dict, Any
 11  
 12  
 13  class ContentType(Enum):
 14      """Types of content a bullet can contain."""
 15      TEXT = "text"
 16      CODE = "code"
 17      IMAGE_REF = "image_ref"
 18      AUDIO_REF = "audio_ref"
 19      VIDEO_REF = "video_ref"
 20      LINK = "link"
 21      STRUCTURED = "structured"  # JSON/dict data
 22  
 23  
 24  class EdgeType(Enum):
 25      """Types of relationships between bullets."""
 26      # Hierarchical
 27      IS_A = "is_a"                 # Inheritance: X is a type of Y
 28      HAS_A = "has_a"               # Composition: X has Y as component
 29      PART_OF = "part_of"           # Membership: X is part of Y
 30      INSTANCE_OF = "instance_of"   # X is an instance of concept Y
 31  
 32      # Causal
 33      CAUSES = "causes"             # X causes Y
 34      ENABLES = "enables"           # X enables Y to happen
 35      PREVENTS = "prevents"         # X prevents Y
 36      REQUIRES = "requires"         # X requires Y
 37  
 38      # Associative
 39      RELATES_TO = "relates_to"     # Generic relation
 40      SIMILAR_TO = "similar_to"     # X is similar to Y
 41      OPPOSITE_OF = "opposite_of"   # X is opposite of Y
 42      ANALOGOUS_TO = "analogous_to" # X is analogous to Y
 43  
 44      # Temporal
 45      BEFORE = "before"             # X comes before Y
 46      AFTER = "after"               # X comes after Y
 47      DURING = "during"             # X happens during Y
 48  
 49      # Reference
 50      CITES = "cites"               # X cites/references Y
 51      SUPPORTS = "supports"         # X supports/evidence for Y
 52      CONTRADICTS = "contradicts"   # X contradicts Y
 53  
 54      # Attention
 55      REMINDED_OF = "reminded_of"   # X reminded operator of Y
 56      LED_TO = "led_to"             # Thinking about X led to Y
 57  
 58  
 59  @dataclass
 60  class PredictionTarget:
 61      """
 62      A potential edge that the system predicts should form.
 63  
 64      This is the free energy engine's prediction of what connections
 65      would reduce prediction error if they were made.
 66      """
 67      target_uuid: str                  # The bullet this one is pulling toward
 68      predicted_edge_type: EdgeType
 69      prediction_strength: float        # How strongly predicted (0-1)
 70      free_energy_reduction: float      # How much FE would drop if edge formed
 71      first_predicted: datetime = field(default_factory=datetime.now)
 72      prediction_count: int = 1         # How many times re-predicted
 73  
 74  
 75  @dataclass
 76  class Bullet:
 77      """
 78      The atomic unit of information - a Markov blanket at the lowest level.
 79  
 80      Every piece of information in the system decomposes to bullets.
 81      Bullets can have edges to other bullets, forming a graph.
 82      The content NEVER leaves the blanket; only structure flows out.
 83      """
 84      # Identity
 85      uuid: str                         # Globally unique, persists across all transformations
 86      blanket_id: str                   # Which Markov blanket owns this bullet
 87  
 88      # Content (NEVER leaves blanket)
 89      content: str                      # The actual text/data
 90      content_type: ContentType = ContentType.TEXT
 91  
 92      # Hierarchy
 93      parent_uuid: Optional[str] = None         # Parent bullet (for nesting)
 94      child_uuids: List[str] = field(default_factory=list)
 95  
 96      # Temporal
 97      created_at: datetime = field(default_factory=datetime.now)
 98      updated_at: datetime = field(default_factory=datetime.now)
 99      accessed_at: datetime = field(default_factory=datetime.now)
100      access_count: int = 0             # Total attention events
101  
102      # Tags (two-tier system)
103      visible_tags: List[str] = field(default_factory=list)       # Human-readable: #decision, #principle
104      metadata_tags: Dict[str, Any] = field(default_factory=dict) # System: altitude, resonance, tone
105  
106      # Prediction State (for free energy engine)
107      prediction_targets: List[PredictionTarget] = field(default_factory=list)
108      gravity_well_strength: float = 0.0    # How strongly this attracts related concepts
109      free_energy_score: float = 0.0        # Current prediction error level
110  
111      # Resonance
112      resonance_score: float = 0.0          # Current relevance (0-1)
113      last_resonance_factors: Dict[str, float] = field(default_factory=dict)
114  
115      def to_dict(self) -> Dict[str, Any]:
116          """Convert to dictionary for storage."""
117          return {
118              'uuid': self.uuid,
119              'blanket_id': self.blanket_id,
120              'content': self.content,
121              'content_type': self.content_type.value,
122              'parent_uuid': self.parent_uuid,
123              'child_uuids': self.child_uuids,
124              'created_at': self.created_at.isoformat(),
125              'updated_at': self.updated_at.isoformat(),
126              'accessed_at': self.accessed_at.isoformat(),
127              'access_count': self.access_count,
128              'visible_tags': self.visible_tags,
129              'metadata_tags': self.metadata_tags,
130              'prediction_targets': [
131                  {
132                      'target_uuid': pt.target_uuid,
133                      'predicted_edge_type': pt.predicted_edge_type.value,
134                      'prediction_strength': pt.prediction_strength,
135                      'free_energy_reduction': pt.free_energy_reduction,
136                      'first_predicted': pt.first_predicted.isoformat(),
137                      'prediction_count': pt.prediction_count,
138                  }
139                  for pt in self.prediction_targets
140              ],
141              'gravity_well_strength': self.gravity_well_strength,
142              'free_energy_score': self.free_energy_score,
143              'resonance_score': self.resonance_score,
144              'last_resonance_factors': self.last_resonance_factors,
145          }
146  
147      @classmethod
148      def from_dict(cls, data: Dict[str, Any]) -> 'Bullet':
149          """Create from dictionary."""
150          prediction_targets = [
151              PredictionTarget(
152                  target_uuid=pt['target_uuid'],
153                  predicted_edge_type=EdgeType(pt['predicted_edge_type']),
154                  prediction_strength=pt['prediction_strength'],
155                  free_energy_reduction=pt['free_energy_reduction'],
156                  first_predicted=datetime.fromisoformat(pt['first_predicted']),
157                  prediction_count=pt['prediction_count'],
158              )
159              for pt in data.get('prediction_targets', [])
160          ]
161  
162          return cls(
163              uuid=data['uuid'],
164              blanket_id=data['blanket_id'],
165              content=data['content'],
166              content_type=ContentType(data.get('content_type', 'text')),
167              parent_uuid=data.get('parent_uuid'),
168              child_uuids=data.get('child_uuids', []),
169              created_at=datetime.fromisoformat(data['created_at']),
170              updated_at=datetime.fromisoformat(data['updated_at']),
171              accessed_at=datetime.fromisoformat(data['accessed_at']),
172              access_count=data.get('access_count', 0),
173              visible_tags=data.get('visible_tags', []),
174              metadata_tags=data.get('metadata_tags', {}),
175              prediction_targets=prediction_targets,
176              gravity_well_strength=data.get('gravity_well_strength', 0.0),
177              free_energy_score=data.get('free_energy_score', 0.0),
178              resonance_score=data.get('resonance_score', 0.0),
179              last_resonance_factors=data.get('last_resonance_factors', {}),
180          )
181  
182  
183  @dataclass
184  class Edge:
185      """
186      Connection between bullets with typed relationship and strength.
187  
188      Edges represent the structure of knowledge - how ideas relate.
189      Edge existence can flow through permeability (as pattern),
190      but edge content (why things connect) stays private.
191      """
192      uuid: str
193      source_uuid: str
194      target_uuid: str
195  
196      # Type
197      edge_type: EdgeType = EdgeType.RELATES_TO
198  
199      # Strength
200      weight: float = 1.0               # 0-1, strength of connection
201      confidence: float = 1.0           # How certain is this edge
202  
203      # Temporal
204      created_at: datetime = field(default_factory=datetime.now)
205      last_traversed: datetime = field(default_factory=datetime.now)
206      traversal_count: int = 0
207  
208      # Prediction tracking
209      predicted: bool = False           # Was this edge predicted before formation?
210      prediction_strength: float = 0.0  # How strongly was it predicted?
211      formation_surprise: float = 0.0   # How surprising was its formation?
212  
213      def to_dict(self) -> Dict[str, Any]:
214          """Convert to dictionary for storage."""
215          return {
216              'uuid': self.uuid,
217              'source_uuid': self.source_uuid,
218              'target_uuid': self.target_uuid,
219              'edge_type': self.edge_type.value,
220              'weight': self.weight,
221              'confidence': self.confidence,
222              'created_at': self.created_at.isoformat(),
223              'last_traversed': self.last_traversed.isoformat(),
224              'traversal_count': self.traversal_count,
225              'predicted': self.predicted,
226              'prediction_strength': self.prediction_strength,
227              'formation_surprise': self.formation_surprise,
228          }
229  
230      @classmethod
231      def from_dict(cls, data: Dict[str, Any]) -> 'Edge':
232          """Create from dictionary."""
233          return cls(
234              uuid=data['uuid'],
235              source_uuid=data['source_uuid'],
236              target_uuid=data['target_uuid'],
237              edge_type=EdgeType(data.get('edge_type', 'relates_to')),
238              weight=data.get('weight', 1.0),
239              confidence=data.get('confidence', 1.0),
240              created_at=datetime.fromisoformat(data['created_at']),
241              last_traversed=datetime.fromisoformat(data['last_traversed']),
242              traversal_count=data.get('traversal_count', 0),
243              predicted=data.get('predicted', False),
244              prediction_strength=data.get('prediction_strength', 0.0),
245              formation_surprise=data.get('formation_surprise', 0.0),
246          )