-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmrh_graph.py
More file actions
745 lines (601 loc) · 25.5 KB
/
mrh_graph.py
File metadata and controls
745 lines (601 loc) · 25.5 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
"""
Web4 MRH (Markov Relevancy Horizon) Graph Implementation
=========================================================
Implements RDF-based knowledge graphs for Web4 entity relationships.
The MRH graph captures:
- Entity relationships (bound, paired, witnessed)
- Role-contextual trust (T3 tensors)
- Authorization decisions
- Law/society membership
- Delegation chains
Key Features:
- RDF triple storage
- SPARQL-like queries (simplified)
- Trust propagation through graph
- Automatic updates from events
- Role-contextual trust binding
Integration:
- LCT Registry → Identity triples
- Law Oracle → Authority/law triples
- Authorization → Decision triples
- Reputation → T3/V3 tensor triples
"""
from dataclasses import dataclass, field
from typing import Dict, List, Set, Optional, Tuple, Any
from enum import Enum
import time
import hashlib
class RelationType(Enum):
"""Web4 relationship types"""
# Binding relationships (permanent)
BOUND_TO = "web4:boundTo"
PARENT_BINDING = "web4:parentBinding"
CHILD_BINDING = "web4:childBinding"
SIBLING_BINDING = "web4:siblingBinding"
# Pairing relationships (session-based)
PAIRED_WITH = "web4:pairedWith"
ENERGY_PAIRING = "web4:energyPairing"
DATA_PAIRING = "web4:dataPairing"
SERVICE_PAIRING = "web4:servicePairing"
# Witness relationships (trust-building)
WITNESSED_BY = "web4:witnessedBy"
TIME_WITNESS = "web4:timeWitness"
AUDIT_WITNESS = "web4:auditWitness"
ORACLE_WITNESS = "web4:oracleWitness"
# Identity/Society relationships
MEMBER_OF = "web4:memberOf"
HAS_ROLE = "web4:hasRole"
PAIRED_WITH_ROLE = "web4:pairedWithRole"
# Authority/Law relationships
HAS_AUTHORITY = "web4:hasAuthority"
HAS_LAW_ORACLE = "web4:hasLawOracle"
DELEGATES_TO = "web4:delegatesTo"
# Trust/Reputation relationships
HAS_T3_TENSOR = "web4:hasT3Tensor"
HAS_V3_TENSOR = "web4:hasV3Tensor"
HAS_DIMENSION_SCORE = "web4:hasDimensionScore"
AUTHORIZED_ACTION = "web4:authorizedAction"
# Ontological relationships
SUB_DIMENSION_OF = "web4:subDimensionOf"
@dataclass
class RDFTriple:
"""
Basic RDF triple: subject-predicate-object
Example:
Triple(
subject="lct:alice",
predicate="web4:boundTo",
object="lct:hardware1"
)
"""
subject: str
predicate: str
object: str
timestamp: float = field(default_factory=time.time)
metadata: Dict[str, Any] = field(default_factory=dict)
def __hash__(self):
return hash((self.subject, self.predicate, self.object))
def to_turtle(self) -> str:
"""Export as Turtle notation"""
return f"<{self.subject}> <{self.predicate}> <{self.object}> ."
def matches(self, subject: Optional[str] = None,
predicate: Optional[str] = None,
object_: Optional[str] = None) -> bool:
"""Check if triple matches pattern (None = wildcard)"""
if subject and self.subject != subject:
return False
if predicate and self.predicate != predicate:
return False
if object_ and self.object != object_:
return False
return True
@dataclass
class MRHNode:
"""
Entity node in MRH graph
"""
lct_id: str
entity_type: str # HUMAN, AI, ORGANIZATION, etc.
roles: Set[str] = field(default_factory=set)
metadata: Dict[str, Any] = field(default_factory=dict)
created: float = field(default_factory=time.time)
@dataclass
class MRHEdge:
"""
Relationship edge in MRH graph
Wraps RDF triple with additional MRH-specific metadata
"""
triple: RDFTriple
relation_type: RelationType
weight: float = 1.0 # Edge weight for trust propagation
distance: int = 1 # Hop distance from origin
@property
def source(self) -> str:
return self.triple.subject
@property
def target(self) -> str:
return self.triple.object
@dataclass
class DimensionScore:
"""
A scored observation linking a tensor to a specific dimension.
Mirrors web4:DimensionScore from t3v3-ontology.ttl.
"""
dimension: str # e.g. "web4:Talent" or "analytics:StatisticalModeling"
score: float
observed_at: float = field(default_factory=time.time)
witnessed_by: Optional[str] = None # LCT of witness
@dataclass
class T3Tensor:
"""
Role-contextual Trust tensor with fractal sub-dimensions.
CRITICAL: T3 is always bound to (entity, role) pair!
The 3 root dimensions (talent/training/temperament) are aggregate scores.
Each can be refined by open-ended sub-dimensions linked via
web4:subDimensionOf in the RDF graph. See t3v3-ontology.ttl.
"""
entity_lct: str
role_lct: str
talent: float = 0.5 # Natural capability (root aggregate)
training: float = 0.5 # Acquired skill (root aggregate)
temperament: float = 0.5 # Reliability/consistency (root aggregate)
sub_dimensions: Dict[str, List[DimensionScore]] = field(default_factory=dict)
def average(self) -> float:
"""Simple average of root trust scores"""
return (self.talent + self.training + self.temperament) / 3.0
def weighted(self, talent_w=0.4, training_w=0.3, temperament_w=0.3) -> float:
"""Weighted trust score from root dimensions"""
return (self.talent * talent_w +
self.training * training_w +
self.temperament * temperament_w)
def add_sub_dimension_score(self, parent_dim: str, score: DimensionScore):
"""Add a sub-dimension score under a root dimension."""
if parent_dim not in self.sub_dimensions:
self.sub_dimensions[parent_dim] = []
self.sub_dimensions[parent_dim].append(score)
def aggregate_root(self, root_dim: str) -> Optional[float]:
"""Recompute root dimension as average of sub-dimension scores."""
scores = self.sub_dimensions.get(root_dim, [])
if not scores:
return None
return sum(s.score for s in scores) / len(scores)
class MRHGraph:
"""
MRH Graph Manager
Maintains RDF knowledge graph of Web4 entity relationships.
Provides triple storage, query, and trust propagation.
"""
def __init__(self):
self.triples: Set[RDFTriple] = set()
self.nodes: Dict[str, MRHNode] = {}
self.edges_by_source: Dict[str, List[MRHEdge]] = {}
self.edges_by_target: Dict[str, List[MRHEdge]] = {}
# T3/V3 tensors (role-contextual)
self.t3_tensors: Dict[Tuple[str, str], T3Tensor] = {} # (entity, role) → T3
# Index for fast queries
self.predicate_index: Dict[str, Set[RDFTriple]] = {}
self.subject_index: Dict[str, Set[RDFTriple]] = {}
self.object_index: Dict[str, Set[RDFTriple]] = {}
def add_node(self, lct_id: str, entity_type: str, metadata: Dict = None) -> MRHNode:
"""Add entity node to graph"""
if lct_id in self.nodes:
return self.nodes[lct_id]
node = MRHNode(
lct_id=lct_id,
entity_type=entity_type,
metadata=metadata or {}
)
self.nodes[lct_id] = node
return node
def add_triple(self, subject: str, predicate: str, object_: str,
metadata: Dict = None) -> RDFTriple:
"""Add RDF triple to graph"""
triple = RDFTriple(
subject=subject,
predicate=predicate,
object=object_,
metadata=metadata or {}
)
if triple in self.triples:
return triple
self.triples.add(triple)
# Update indices
if predicate not in self.predicate_index:
self.predicate_index[predicate] = set()
self.predicate_index[predicate].add(triple)
if subject not in self.subject_index:
self.subject_index[subject] = set()
self.subject_index[subject].add(triple)
if object_ not in self.object_index:
self.object_index[object_] = set()
self.object_index[object_].add(triple)
return triple
def add_edge(self, source: str, target: str, relation: RelationType,
weight: float = 1.0, metadata: Dict = None) -> MRHEdge:
"""Add relationship edge to graph"""
triple = self.add_triple(source, relation.value, target, metadata)
edge = MRHEdge(
triple=triple,
relation_type=relation,
weight=weight
)
# Update edge indices
if source not in self.edges_by_source:
self.edges_by_source[source] = []
self.edges_by_source[source].append(edge)
if target not in self.edges_by_target:
self.edges_by_target[target] = []
self.edges_by_target[target].append(edge)
return edge
def query_triples(self, subject: Optional[str] = None,
predicate: Optional[str] = None,
object_: Optional[str] = None) -> List[RDFTriple]:
"""
Query triples matching pattern.
None = wildcard.
Examples:
query(subject="lct:alice") # All triples about alice
query(predicate="web4:boundTo") # All binding relationships
query(subject="lct:alice", predicate="web4:hasRole") # Alice's roles
"""
# Use indices for efficiency
if subject:
candidates = self.subject_index.get(subject, set())
elif predicate:
candidates = self.predicate_index.get(predicate, set())
elif object_:
candidates = self.object_index.get(object_, set())
else:
candidates = self.triples
return [t for t in candidates if t.matches(subject, predicate, object_)]
def get_outgoing_edges(self, lct_id: str,
relation: Optional[RelationType] = None) -> List[MRHEdge]:
"""Get edges emanating from entity"""
edges = self.edges_by_source.get(lct_id, [])
if relation:
edges = [e for e in edges if e.relation_type == relation]
return edges
def get_incoming_edges(self, lct_id: str,
relation: Optional[RelationType] = None) -> List[MRHEdge]:
"""Get edges pointing to entity"""
edges = self.edges_by_target.get(lct_id, [])
if relation:
edges = [e for e in edges if e.relation_type == relation]
return edges
def get_neighbors(self, lct_id: str,
relation: Optional[RelationType] = None,
direction: str = "outgoing") -> List[str]:
"""Get neighboring entities"""
if direction == "outgoing":
edges = self.get_outgoing_edges(lct_id, relation)
return [e.target for e in edges]
elif direction == "incoming":
edges = self.get_incoming_edges(lct_id, relation)
return [e.source for e in edges]
else: # both
out = self.get_neighbors(lct_id, relation, "outgoing")
inc = self.get_neighbors(lct_id, relation, "incoming")
return list(set(out + inc))
def traverse(self, start: str, max_depth: int = 3,
relation: Optional[RelationType] = None) -> Dict[int, Set[str]]:
"""
Traverse graph from starting entity up to max_depth hops.
Returns: {depth: {entities at that depth}}
This implements the "Markov Relevancy Horizon" - entities
beyond max_depth are outside the horizon and irrelevant.
"""
result = {0: {start}}
visited = {start}
frontier = {start}
for depth in range(1, max_depth + 1):
next_frontier = set()
for entity in frontier:
neighbors = self.get_neighbors(entity, relation, "both")
for neighbor in neighbors:
if neighbor not in visited:
visited.add(neighbor)
next_frontier.add(neighbor)
if not next_frontier:
break
result[depth] = next_frontier
frontier = next_frontier
return result
def find_paths(self, start: str, end: str, max_depth: int = 3) -> List[List[str]]:
"""
Find all paths from start to end within max_depth hops.
Used for trust propagation calculations.
"""
if start == end:
return [[start]]
paths = []
def dfs(current: str, target: str, path: List[str], depth: int):
if depth > max_depth:
return
if current == target:
paths.append(path.copy())
return
for neighbor in self.get_neighbors(current):
if neighbor not in path: # Avoid cycles
path.append(neighbor)
dfs(neighbor, target, path, depth + 1)
path.pop()
dfs(start, end, [start], 0)
return paths
def register_sub_dimension(self, child_dim: str, parent_dim: str):
"""
Register a sub-dimension relationship in the graph.
Example: register_sub_dimension("analytics:StatisticalModeling", "web4:Talent")
This adds: analytics:StatisticalModeling web4:subDimensionOf web4:Talent .
"""
self.add_triple(child_dim, RelationType.SUB_DIMENSION_OF.value, parent_dim)
def get_sub_dimensions(self, parent_dim: str, recursive: bool = True) -> List[str]:
"""
Get all sub-dimensions of a parent dimension.
If recursive=True, traverses the full sub-graph (equivalent to
SPARQL: ?dim web4:subDimensionOf* parent_dim).
"""
direct = [t.subject for t in
self.query_triples(predicate=RelationType.SUB_DIMENSION_OF.value,
object_=parent_dim)]
if not recursive:
return direct
all_dims = list(direct)
frontier = list(direct)
while frontier:
next_frontier = []
for dim in frontier:
children = [t.subject for t in
self.query_triples(predicate=RelationType.SUB_DIMENSION_OF.value,
object_=dim)]
for child in children:
if child not in all_dims:
all_dims.append(child)
next_frontier.append(child)
frontier = next_frontier
return all_dims
def set_t3_tensor(self, entity_lct: str, role_lct: str, t3: T3Tensor):
"""
Set T3 trust tensor for (entity, role) pair.
CRITICAL: Trust is role-contextual!
Emits both shorthand triples (web4:talent 0.95) and full-form
triples (web4:hasDimensionScore) for sub-dimensions.
"""
key = (entity_lct, role_lct)
self.t3_tensors[key] = t3
# Shorthand triples (backward-compatible)
tensor_id = f"tensor:t3:{entity_lct}:{role_lct}"
self.add_triple(entity_lct, RelationType.HAS_T3_TENSOR.value, tensor_id)
self.add_triple(tensor_id, "web4:role", role_lct)
self.add_triple(tensor_id, "web4:talent", str(t3.talent))
self.add_triple(tensor_id, "web4:training", str(t3.training))
self.add_triple(tensor_id, "web4:temperament", str(t3.temperament))
# Full-form triples for sub-dimension scores
for parent_dim, scores in t3.sub_dimensions.items():
for ds in scores:
score_id = f"score:{tensor_id}:{ds.dimension}:{ds.observed_at}"
self.add_triple(tensor_id, RelationType.HAS_DIMENSION_SCORE.value, score_id)
self.add_triple(score_id, "web4:dimension", ds.dimension)
self.add_triple(score_id, "web4:score", str(ds.score))
if ds.witnessed_by:
self.add_triple(score_id, "web4:witnessedBy", ds.witnessed_by)
def get_t3_tensor(self, entity_lct: str, role_lct: str) -> Optional[T3Tensor]:
"""Get T3 trust tensor for (entity, role) pair"""
key = (entity_lct, role_lct)
return self.t3_tensors.get(key)
def propagate_trust(self, start: str, end: str, role_lct: str,
decay_rate: float = 0.9) -> float:
"""
Calculate trust from start to end entity in role context.
Trust propagates through graph paths with decay.
"""
paths = self.find_paths(start, end, max_depth=3)
if not paths:
return 0.0
# Calculate trust for each path
path_trusts = []
for path in paths:
trust = 1.0
for i in range(len(path) - 1):
# Get T3 for entity in role
entity = path[i]
t3 = self.get_t3_tensor(entity, role_lct)
if t3:
# Multiply by entity trust and decay
trust *= t3.average() * (decay_rate ** i)
else:
# No trust tensor = default low trust
trust *= 0.5 * (decay_rate ** i)
path_trusts.append(trust)
# Combine multiple paths (take max for now, could do probabilistic)
return max(path_trusts) if path_trusts else 0.0
def export_turtle(self) -> str:
"""Export graph as Turtle RDF"""
lines = [
"@prefix web4: <https://web4.io/ontology#> .",
"@prefix lct: <https://web4.io/lct/> .",
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .",
""
]
for triple in sorted(self.triples, key=lambda t: (t.subject, t.predicate)):
lines.append(triple.to_turtle())
return "\n".join(lines)
def get_stats(self) -> Dict:
"""Get graph statistics"""
return {
"nodes": len(self.nodes),
"triples": len(self.triples),
"edges": sum(len(e) for e in self.edges_by_source.values()),
"t3_tensors": len(self.t3_tensors),
"predicates": len(self.predicate_index),
"avg_outgoing_degree": (
sum(len(e) for e in self.edges_by_source.values()) / len(self.nodes)
if self.nodes else 0
)
}
class MRHEventIntegration:
"""
Automatically updates MRH graph from Web4 events.
Integration points:
- LCT minting → Identity triples
- Delegation creation → Authority triples
- Authorization decision → Action triples
- Reputation update → T3/V3 tensor triples
"""
def __init__(self, graph: MRHGraph):
self.graph = graph
def on_lct_minted(self, lct_id: str, entity_type: str, society_id: str,
witnesses: List[str], birth_cert_hash: str):
"""Update graph when new LCT minted"""
# Add entity node
self.graph.add_node(lct_id, entity_type)
# Add society membership
self.graph.add_edge(lct_id, society_id, RelationType.MEMBER_OF)
# Add witness relationships
for witness in witnesses:
self.graph.add_edge(lct_id, witness, RelationType.WITNESSED_BY,
metadata={"event": "birth", "cert_hash": birth_cert_hash})
# Add birth certificate triple
self.graph.add_triple(lct_id, "web4:birthCertificate", birth_cert_hash)
def on_delegation_created(self, delegation_id: str, client_lct: str,
agent_lct: str, role_lct: str):
"""Update graph when delegation created"""
# Add delegation edge
self.graph.add_edge(client_lct, agent_lct, RelationType.DELEGATES_TO,
metadata={"delegation_id": delegation_id, "role": role_lct})
# Add role pairing
self.graph.add_edge(agent_lct, role_lct, RelationType.HAS_ROLE)
self.graph.add_triple(agent_lct, RelationType.PAIRED_WITH_ROLE.value, role_lct,
metadata={"delegation_id": delegation_id})
# Add agent to node roles
if agent_lct in self.graph.nodes:
self.graph.nodes[agent_lct].roles.add(role_lct)
def on_authorization_granted(self, decision_id: str, agent_lct: str,
action: str, resource: str, atp_cost: int,
law_hash: str):
"""Update graph when authorization granted"""
# Add authorization action triple
action_id = f"action:{decision_id}"
self.graph.add_triple(agent_lct, RelationType.AUTHORIZED_ACTION.value, action_id)
self.graph.add_triple(action_id, "web4:actionType", action)
self.graph.add_triple(action_id, "web4:resource", resource)
self.graph.add_triple(action_id, "web4:atpCost", str(atp_cost))
self.graph.add_triple(action_id, "web4:lawHash", law_hash)
def on_reputation_update(self, entity_lct: str, role_lct: str, t3: T3Tensor):
"""Update graph when reputation changes"""
self.graph.set_t3_tensor(entity_lct, role_lct, t3)
# Example usage and testing
if __name__ == "__main__":
print("=" * 70)
print(" Web4 MRH Graph - Implementation Test")
print("=" * 70)
# Create graph
graph = MRHGraph()
event_integration = MRHEventIntegration(graph)
print("\n✅ MRH Graph created")
# Simulate LCT minting events
print("\n👤 Simulating Entity Creation:")
event_integration.on_lct_minted(
lct_id="lct:alice",
entity_type="HUMAN",
society_id="society:research_lab",
witnesses=["witness:hr", "witness:security"],
birth_cert_hash="abc123"
)
print(" ✅ Alice LCT minted")
event_integration.on_lct_minted(
lct_id="lct:ai_agent",
entity_type="AI",
society_id="society:research_lab",
witnesses=["witness:supervisor"],
birth_cert_hash="def456"
)
print(" ✅ AI Agent LCT minted")
# Create delegation
print("\n📋 Simulating Delegation:")
event_integration.on_delegation_created(
delegation_id="deleg:001",
client_lct="lct:alice",
agent_lct="lct:ai_agent",
role_lct="role:researcher"
)
print(" ✅ Delegation created: alice → ai_agent (researcher)")
# Set T3 tensors
print("\n📊 Setting Trust Tensors:")
# Register domain sub-dimensions
graph.register_sub_dimension("research:LiteratureReview", "web4:Talent")
graph.register_sub_dimension("research:ExperimentalDesign", "web4:Talent")
graph.register_sub_dimension("research:StatisticalAnalysis", "web4:Training")
print(" ✅ Registered research domain sub-dimensions")
# Create T3 with sub-dimension scores
t3 = T3Tensor(
entity_lct="lct:ai_agent",
role_lct="role:researcher",
talent=0.8,
training=0.7,
temperament=0.9
)
t3.add_sub_dimension_score("web4:Talent", DimensionScore(
dimension="research:LiteratureReview", score=0.85, witnessed_by="lct:alice"))
t3.add_sub_dimension_score("web4:Talent", DimensionScore(
dimension="research:ExperimentalDesign", score=0.75, witnessed_by="lct:alice"))
t3.add_sub_dimension_score("web4:Training", DimensionScore(
dimension="research:StatisticalAnalysis", score=0.72, witnessed_by="lct:alice"))
event_integration.on_reputation_update(
entity_lct="lct:ai_agent",
role_lct="role:researcher",
t3=t3
)
print(" ✅ T3 tensor set for ai_agent as researcher (with sub-dimensions)")
# Query graph
print("\n🔍 Querying Graph:")
# Find Alice's relationships
alice_triples = graph.query_triples(subject="lct:alice")
print(f"\n Alice has {len(alice_triples)} relationships:")
for triple in alice_triples[:5]: # Show first 5
print(f" {triple.predicate} → {triple.object}")
# Find society members
members = graph.query_triples(predicate="web4:memberOf",
object_="society:research_lab")
print(f"\n Research lab has {len(members)} members:")
for triple in members:
print(f" {triple.subject}")
# Find delegations
delegations = graph.query_triples(predicate="web4:delegatesTo")
print(f"\n {len(delegations)} delegations:")
for triple in delegations:
print(f" {triple.subject} → {triple.object}")
# Traverse from Alice
print("\n🌐 Traversing from Alice (max depth 3):")
horizon = graph.traverse("lct:alice", max_depth=3)
for depth, entities in horizon.items():
print(f" Depth {depth}: {entities}")
# Find paths
print("\n🛤️ Paths from alice to ai_agent:")
paths = graph.find_paths("lct:alice", "lct:ai_agent", max_depth=3)
for i, path in enumerate(paths):
print(f" Path {i+1}: {' → '.join(path)}")
# Sub-dimension queries
print("\n🌿 Sub-Dimension Queries:")
talent_subs = graph.get_sub_dimensions("web4:Talent")
print(f" Talent sub-dimensions: {talent_subs}")
t3_retrieved = graph.get_t3_tensor("lct:ai_agent", "role:researcher")
if t3_retrieved:
agg = t3_retrieved.aggregate_root("web4:Talent")
print(f" Talent aggregate from sub-dims: {agg:.3f}" if agg else " No sub-dim scores")
print(f" Talent root score: {t3_retrieved.talent}")
# Trust propagation
print("\n🔐 Trust Propagation:")
trust = graph.propagate_trust("lct:alice", "lct:ai_agent", "role:researcher")
print(f" Trust from alice to ai_agent (researcher): {trust:.3f}")
# Export Turtle
print("\n📄 Turtle RDF Export (first 10 lines):")
turtle = graph.export_turtle()
for line in turtle.split("\n")[:10]:
print(f" {line}")
# Statistics
print("\n📊 Graph Statistics:")
stats = graph.get_stats()
for key, value in stats.items():
print(f" {key}: {value}")
print("\n✅ MRH Graph implementation complete and tested!")
print("✅ Ready for integration with LCT/Law/Auth systems")