-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlct_capability_levels.py
More file actions
1053 lines (888 loc) · 36.5 KB
/
lct_capability_levels.py
File metadata and controls
1053 lines (888 loc) · 36.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
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
"""
LCT Capability Levels - Reference Implementation
=================================================
Implements the LCT Capability Levels specification for Web4.
Provides:
- Capability level definitions (0-5)
- Entity type registry
- Capability query protocol
- Stub generators for reduced implementations
- Level validation and upgrade paths
Usage:
from core.lct_capability_levels import (
CapabilityLevel,
EntityType,
LCTCapabilities,
create_minimal_lct,
query_capabilities,
validate_lct_level
)
# Create a Level 2 plugin LCT
lct = create_minimal_lct(
entity_type=EntityType.PLUGIN,
level=CapabilityLevel.BASIC,
parent_lct="lct:web4:agent:orchestrator"
)
# Query capabilities
caps = query_capabilities(lct)
print(f"Level: {caps.capability_level}, T3: {caps.t3_supported}")
Author: CBP Session (Dennis + Claude)
Date: 2026-01-03
"""
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Optional, Any, Set, Tuple
from enum import Enum, IntEnum
from datetime import datetime, timezone
import hashlib
import json
# =============================================================================
# Capability Levels
# =============================================================================
class CapabilityLevel(IntEnum):
"""
LCT Capability Levels (0-5).
Each level builds on the previous, adding required components.
"""
STUB = 0 # Placeholder reference, pending entity
MINIMAL = 1 # Self-issued bootstrap, basic plugin identity
BASIC = 2 # Operational plugins, simple agents with relationships
STANDARD = 3 # Autonomous agents, federated entities with full tensors
FULL = 4 # Society-issued identities, core infrastructure
HARDWARE = 5 # Physical devices with hardware attestation
# =============================================================================
# Entity Types
# =============================================================================
class EntityType(str, Enum):
"""
LCT Entity Types - what kind of entity this LCT represents.
Core types from Web4 spec plus extended types for fractal use.
"""
# Core types (from spec)
HUMAN = "human"
AI = "ai"
ORGANIZATION = "organization"
ROLE = "role"
TASK = "task"
RESOURCE = "resource"
DEVICE = "device"
SERVICE = "service"
ORACLE = "oracle"
ACCUMULATOR = "accumulator"
DICTIONARY = "dictionary"
HYBRID = "hybrid"
# Extended types (for fractal use)
PLUGIN = "plugin"
SESSION = "session"
RELATIONSHIP = "relationship"
PATTERN = "pattern"
SOCIETY = "society"
WITNESS = "witness"
PENDING = "pending"
# Typical capability level ranges for each entity type
ENTITY_LEVEL_RANGES: Dict[EntityType, Tuple[CapabilityLevel, CapabilityLevel]] = {
EntityType.HUMAN: (CapabilityLevel.FULL, CapabilityLevel.HARDWARE),
EntityType.AI: (CapabilityLevel.BASIC, CapabilityLevel.FULL),
EntityType.ORGANIZATION: (CapabilityLevel.FULL, CapabilityLevel.FULL),
EntityType.ROLE: (CapabilityLevel.MINIMAL, CapabilityLevel.STANDARD),
EntityType.TASK: (CapabilityLevel.MINIMAL, CapabilityLevel.BASIC),
EntityType.RESOURCE: (CapabilityLevel.MINIMAL, CapabilityLevel.STANDARD),
EntityType.DEVICE: (CapabilityLevel.STANDARD, CapabilityLevel.HARDWARE),
EntityType.SERVICE: (CapabilityLevel.BASIC, CapabilityLevel.FULL),
EntityType.ORACLE: (CapabilityLevel.STANDARD, CapabilityLevel.FULL),
EntityType.ACCUMULATOR: (CapabilityLevel.BASIC, CapabilityLevel.STANDARD),
EntityType.DICTIONARY: (CapabilityLevel.STANDARD, CapabilityLevel.FULL),
EntityType.HYBRID: (CapabilityLevel.MINIMAL, CapabilityLevel.HARDWARE),
EntityType.PLUGIN: (CapabilityLevel.MINIMAL, CapabilityLevel.BASIC),
EntityType.SESSION: (CapabilityLevel.MINIMAL, CapabilityLevel.BASIC),
EntityType.RELATIONSHIP: (CapabilityLevel.MINIMAL, CapabilityLevel.BASIC),
EntityType.PATTERN: (CapabilityLevel.MINIMAL, CapabilityLevel.STANDARD),
EntityType.SOCIETY: (CapabilityLevel.FULL, CapabilityLevel.HARDWARE),
EntityType.WITNESS: (CapabilityLevel.STANDARD, CapabilityLevel.FULL),
EntityType.PENDING: (CapabilityLevel.STUB, CapabilityLevel.STUB),
}
# =============================================================================
# T3 Tensor (3 canonical root dimensions)
# =============================================================================
@dataclass
class T3Tensor:
"""
Trust Tensor with 3 canonical root dimensions.
Dimensions (all 0.0-1.0):
- talent: Natural aptitude / capability for a specific role
- training: Learned skills, certifications, experience
- temperament: Behavioral consistency, reliability, ethical disposition
Each root dimension is a node in an open-ended RDF sub-graph.
Domain-specific sub-dimensions refine roots via web4:subDimensionOf.
"""
talent: Optional[float] = None
training: Optional[float] = None
temperament: Optional[float] = None
# Metadata (not T3 dimensions, but useful context)
witness_count: Optional[int] = None # How many entities witness this entity
composite_score: Optional[float] = None
last_computed: Optional[str] = None
computation_witnesses: List[str] = field(default_factory=list)
stub: bool = False
reason: Optional[str] = None
def recompute_composite(self) -> float:
"""Recompute composite score from dimensions."""
dims = [
self.talent,
self.training,
self.temperament
]
valid = [d for d in dims if d is not None]
if not valid:
self.composite_score = None
return 0.0
self.composite_score = sum(valid) / len(valid)
self.last_computed = datetime.now(timezone.utc).isoformat()
return self.composite_score
def is_stub(self) -> bool:
"""Check if this is a stub tensor."""
return self.stub or all(d is None for d in [
self.talent, self.training, self.temperament
])
@classmethod
def create_stub(cls, reason: str = "Not implemented") -> 'T3Tensor':
"""Create a stub T3 tensor."""
return cls(stub=True, reason=reason)
@classmethod
def create_minimal(cls) -> 'T3Tensor':
"""Create minimal T3 tensor for Level 1."""
t3 = cls(
talent=0.1,
training=0.1,
temperament=0.1,
stub=False
)
t3.recompute_composite()
return t3
def to_dict(self) -> Dict:
"""Convert to dictionary."""
d = {
"dimensions": {
"talent": self.talent,
"training": self.training,
"temperament": self.temperament
},
"composite_score": self.composite_score,
"last_computed": self.last_computed,
"computation_witnesses": self.computation_witnesses,
"stub": self.stub if self.stub else None,
"reason": self.reason
}
if self.witness_count is not None:
d["metadata"] = {"witness_count": self.witness_count}
return d
# =============================================================================
# V3 Tensor (3 canonical root dimensions)
# =============================================================================
@dataclass
class V3Tensor:
"""
Value Tensor with 3 canonical root dimensions.
Dimensions:
- valuation: Subjective worth as perceived by recipients (0.0-1.0+)
- veracity: Truthfulness, accuracy of claims (0.0-1.0)
- validity: Soundness of reasoning, confirmed value delivery (0.0-1.0)
Each root dimension is a node in an open-ended RDF sub-graph.
Domain-specific sub-dimensions refine roots via web4:subDimensionOf.
"""
valuation: Optional[float] = None
veracity: Optional[float] = None
validity: Optional[float] = None
# ATP metadata (not a V3 dimension, but tracked alongside)
energy_balance: Optional[int] = None # ATP/ADP balance
composite_score: Optional[float] = None
last_computed: Optional[str] = None
computation_witnesses: List[str] = field(default_factory=list)
stub: bool = False
reason: Optional[str] = None
def recompute_composite(self) -> float:
"""Recompute composite score from dimensions."""
dims = [
self.valuation,
self.veracity,
self.validity
]
valid = [d for d in dims if d is not None]
if not valid:
self.composite_score = None
return 0.0
self.composite_score = sum(valid) / len(valid)
self.last_computed = datetime.now(timezone.utc).isoformat()
return self.composite_score
def is_stub(self) -> bool:
"""Check if this is a stub tensor."""
return self.stub
@classmethod
def create_stub(cls, reason: str = "Not implemented") -> 'V3Tensor':
"""Create a stub V3 tensor."""
return cls(stub=True, reason=reason)
@classmethod
def create_zero(cls) -> 'V3Tensor':
"""Create zero V3 tensor for Level 1."""
v3 = cls(
energy_balance=0,
valuation=0.0,
veracity=0.0,
validity=0.0,
stub=False
)
v3.recompute_composite()
return v3
def to_dict(self) -> Dict:
"""Convert to dictionary."""
d = {
"dimensions": {
"valuation": self.valuation,
"veracity": self.veracity,
"validity": self.validity
},
"composite_score": self.composite_score,
"last_computed": self.last_computed,
"computation_witnesses": self.computation_witnesses,
"stub": self.stub if self.stub else None,
"reason": self.reason
}
if self.energy_balance is not None:
d["atp_metadata"] = {"energy_balance": self.energy_balance}
return d
# =============================================================================
# MRH Relationships
# =============================================================================
@dataclass
class MRHRelationship:
"""A single MRH relationship."""
lct_id: str
relationship_type: str # "bound", "paired", "witnessing"
subtype: Optional[str] = None # e.g., "parent", "operational", "time"
permanent: bool = False
timestamp: Optional[str] = None
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict:
"""Convert to dictionary."""
d = {
"lct_id": self.lct_id,
"type": self.subtype or self.relationship_type,
"ts": self.timestamp
}
if self.relationship_type == "paired":
d["permanent"] = self.permanent
d["pairing_type"] = self.subtype or "operational"
if self.relationship_type == "witnessing":
d["role"] = self.subtype or "existence"
d["witness_count"] = self.metadata.get("witness_count", 1)
if self.relationship_type == "bound":
d["binding_context"] = self.metadata.get("binding_context", "deployment")
return d
@dataclass
class MRH:
"""Markov Relevancy Horizon - relationship container."""
bound: List[MRHRelationship] = field(default_factory=list)
paired: List[MRHRelationship] = field(default_factory=list)
witnessing: List[MRHRelationship] = field(default_factory=list)
horizon_depth: int = 3
last_updated: Optional[str] = None
def add_bound(self, lct_id: str, subtype: str = "parent", **kwargs) -> None:
"""Add binding relationship."""
self.bound.append(MRHRelationship(
lct_id=lct_id,
relationship_type="bound",
subtype=subtype,
timestamp=datetime.now(timezone.utc).isoformat(),
metadata=kwargs
))
self.last_updated = datetime.now(timezone.utc).isoformat()
def add_paired(self, lct_id: str, subtype: str = "operational",
permanent: bool = False, **kwargs) -> None:
"""Add pairing relationship."""
self.paired.append(MRHRelationship(
lct_id=lct_id,
relationship_type="paired",
subtype=subtype,
permanent=permanent,
timestamp=datetime.now(timezone.utc).isoformat(),
metadata=kwargs
))
self.last_updated = datetime.now(timezone.utc).isoformat()
def add_witnessing(self, lct_id: str, role: str = "existence", **kwargs) -> None:
"""Add witnessing relationship."""
self.witnessing.append(MRHRelationship(
lct_id=lct_id,
relationship_type="witnessing",
subtype=role,
timestamp=datetime.now(timezone.utc).isoformat(),
metadata=kwargs
))
self.last_updated = datetime.now(timezone.utc).isoformat()
def has_relationships(self) -> bool:
"""Check if MRH has any relationships."""
return bool(self.bound or self.paired or self.witnessing)
def relationship_types(self) -> List[str]:
"""Get list of relationship types present."""
types = []
if self.bound:
types.append("bound")
if self.paired:
types.append("paired")
if self.witnessing:
types.append("witnessing")
return types
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return {
"bound": [r.to_dict() for r in self.bound],
"paired": [r.to_dict() for r in self.paired],
"witnessing": [r.to_dict() for r in self.witnessing],
"horizon_depth": self.horizon_depth,
"last_updated": self.last_updated
}
# =============================================================================
# LCT Structure
# =============================================================================
@dataclass
class LCTBinding:
"""Cryptographic binding section."""
entity_type: str
public_key: Optional[str] = None
hardware_anchor: Optional[str] = None
hardware_type: Optional[str] = None # tpm2, trustzone, secure_element
created_at: Optional[str] = None
binding_proof: Optional[str] = None
def is_hardware_bound(self) -> bool:
"""Check if binding is hardware-anchored."""
return self.hardware_anchor is not None
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return {
"entity_type": self.entity_type,
"public_key": self.public_key,
"hardware_anchor": self.hardware_anchor,
"hardware_type": self.hardware_type,
"created_at": self.created_at,
"binding_proof": self.binding_proof
}
@dataclass
class LCTPolicy:
"""Policy section with capabilities and constraints."""
capabilities: List[str] = field(default_factory=list)
constraints: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return {
"capabilities": self.capabilities,
"constraints": self.constraints
}
@dataclass
class BirthCertificate:
"""Birth certificate section (Level 4+)."""
issuing_society: Optional[str] = None
citizen_role: Optional[str] = None
birth_timestamp: Optional[str] = None
birth_witnesses: List[str] = field(default_factory=list)
genesis_block_hash: Optional[str] = None
birth_context: Optional[str] = None
stub: bool = False
reason: Optional[str] = None
def is_stub(self) -> bool:
"""Check if this is a stub."""
return self.stub or self.issuing_society is None
@classmethod
def create_stub(cls, reason: str = "Self-issued entity") -> 'BirthCertificate':
"""Create a stub birth certificate."""
return cls(stub=True, reason=reason)
def to_dict(self) -> Dict:
"""Convert to dictionary."""
if self.stub:
return {
"issuing_society": None,
"citizen_role": None,
"birth_witnesses": [],
"stub": True,
"reason": self.reason
}
return {
"issuing_society": self.issuing_society,
"citizen_role": self.citizen_role,
"birth_timestamp": self.birth_timestamp,
"birth_witnesses": self.birth_witnesses,
"genesis_block_hash": self.genesis_block_hash,
"birth_context": self.birth_context
}
@dataclass
class LCT:
"""
Complete LCT structure with capability level support.
Implements the LCT Capability Levels specification.
"""
lct_id: str
capability_level: CapabilityLevel
entity_type: EntityType
subject: Optional[str] = None
binding: Optional[LCTBinding] = None
mrh: Optional[MRH] = None
policy: Optional[LCTPolicy] = None
t3_tensor: Optional[T3Tensor] = None
v3_tensor: Optional[V3Tensor] = None
birth_certificate: Optional[BirthCertificate] = None
attestations: List[Dict] = field(default_factory=list)
lineage: List[Dict] = field(default_factory=list)
revocation: Optional[Dict] = None
def __post_init__(self):
"""Initialize stubs based on capability level."""
if self.mrh is None:
self.mrh = MRH()
if self.policy is None:
self.policy = LCTPolicy()
if self.t3_tensor is None:
if self.capability_level >= CapabilityLevel.MINIMAL:
self.t3_tensor = T3Tensor.create_minimal()
else:
self.t3_tensor = T3Tensor.create_stub("Level 0 entity")
if self.v3_tensor is None:
if self.capability_level >= CapabilityLevel.MINIMAL:
self.v3_tensor = V3Tensor.create_zero()
else:
self.v3_tensor = V3Tensor.create_stub("Level 0 entity")
if self.birth_certificate is None:
self.birth_certificate = BirthCertificate.create_stub()
def to_dict(self) -> Dict:
"""Convert to canonical dictionary format."""
d = {
"lct_id": self.lct_id,
"capability_level": self.capability_level.value,
"entity_type": self.entity_type.value,
}
if self.subject:
d["subject"] = self.subject
if self.binding:
d["binding"] = self.binding.to_dict()
if self.mrh:
d["mrh"] = self.mrh.to_dict()
if self.policy:
d["policy"] = self.policy.to_dict()
if self.t3_tensor:
d["t3_tensor"] = self.t3_tensor.to_dict()
if self.v3_tensor:
d["v3_tensor"] = self.v3_tensor.to_dict()
if self.birth_certificate:
d["birth_certificate"] = self.birth_certificate.to_dict()
if self.attestations:
d["attestations"] = self.attestations
if self.lineage:
d["lineage"] = self.lineage
if self.revocation:
d["revocation"] = self.revocation
return d
def to_json(self, indent: int = 2) -> str:
"""Convert to JSON string."""
return json.dumps(self.to_dict(), indent=indent)
# =============================================================================
# Capability Query Protocol
# =============================================================================
@dataclass
class CapabilityQueryResponse:
"""Response to a capability discovery query."""
source_lct: str
capability_level: CapabilityLevel
entity_type: EntityType
# Component support
binding_implemented: bool = False
binding_hardware_anchored: bool = False
binding_key_algorithm: Optional[str] = None
mrh_implemented: bool = False
mrh_relationship_types: List[str] = field(default_factory=list)
mrh_horizon_depth: int = 0
t3_implemented: bool = False
t3_dimensions: int = 0
t3_oracle_computed: bool = False
v3_implemented: bool = False
v3_dimensions: int = 0
v3_oracle_computed: bool = False
birth_certificate_implemented: bool = False
attestations_count: int = 0
lineage_implemented: bool = False
# Relationship support
can_be_bound_by: List[str] = field(default_factory=list)
can_pair_with: List[str] = field(default_factory=list)
can_witness: List[str] = field(default_factory=list)
can_be_witnessed_by: List[str] = field(default_factory=list)
# Trust summary
trust_tier: str = "unknown"
composite_t3: Optional[float] = None
composite_v3: Optional[float] = None
timestamp: Optional[str] = None
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return {
"response_type": "capability_discovery",
"source_lct": self.source_lct,
"capability_level": self.capability_level.value,
"entity_type": self.entity_type.value,
"supported_components": {
"binding": {
"implemented": self.binding_implemented,
"hardware_anchored": self.binding_hardware_anchored,
"key_algorithm": self.binding_key_algorithm
},
"mrh": {
"implemented": self.mrh_implemented,
"relationship_types": self.mrh_relationship_types,
"horizon_depth": self.mrh_horizon_depth
},
"t3_tensor": {
"implemented": self.t3_implemented,
"dimensions": self.t3_dimensions,
"oracle_computed": self.t3_oracle_computed
},
"v3_tensor": {
"implemented": self.v3_implemented,
"dimensions": self.v3_dimensions,
"oracle_computed": self.v3_oracle_computed
},
"birth_certificate": {
"implemented": self.birth_certificate_implemented,
"stub": not self.birth_certificate_implemented
},
"attestations": {
"implemented": self.attestations_count > 0,
"count": self.attestations_count
},
"lineage": {
"implemented": self.lineage_implemented,
"stub": not self.lineage_implemented
}
},
"relationship_support": {
"can_be_bound_by": self.can_be_bound_by,
"can_pair_with": self.can_pair_with,
"can_witness": self.can_witness,
"can_be_witnessed_by": self.can_be_witnessed_by
},
"trust_tier": self.trust_tier,
"composite_t3": self.composite_t3,
"composite_v3": self.composite_v3,
"timestamp": self.timestamp
}
def query_capabilities(lct: LCT) -> CapabilityQueryResponse:
"""
Query an LCT's capabilities.
Returns a CapabilityQueryResponse with full capability information.
"""
response = CapabilityQueryResponse(
source_lct=lct.lct_id,
capability_level=lct.capability_level,
entity_type=lct.entity_type,
timestamp=datetime.now(timezone.utc).isoformat()
)
# Binding
if lct.binding:
response.binding_implemented = lct.binding.public_key is not None
response.binding_hardware_anchored = lct.binding.is_hardware_bound()
response.binding_key_algorithm = "Ed25519" if lct.binding.public_key else None
# MRH
if lct.mrh:
response.mrh_implemented = lct.mrh.has_relationships()
response.mrh_relationship_types = lct.mrh.relationship_types()
response.mrh_horizon_depth = lct.mrh.horizon_depth
# T3 Tensor
if lct.t3_tensor and not lct.t3_tensor.is_stub():
response.t3_implemented = True
# Count non-None dimensions
dims = [lct.t3_tensor.talent, lct.t3_tensor.training,
lct.t3_tensor.temperament]
response.t3_dimensions = sum(1 for d in dims if d is not None)
response.t3_oracle_computed = bool(lct.t3_tensor.computation_witnesses)
response.composite_t3 = lct.t3_tensor.composite_score
# V3 Tensor
if lct.v3_tensor and not lct.v3_tensor.is_stub():
response.v3_implemented = True
dims = [lct.v3_tensor.valuation, lct.v3_tensor.veracity,
lct.v3_tensor.validity]
response.v3_dimensions = sum(1 for d in dims if d is not None)
response.v3_oracle_computed = bool(lct.v3_tensor.computation_witnesses)
response.composite_v3 = lct.v3_tensor.composite_score
# Birth certificate
if lct.birth_certificate and not lct.birth_certificate.is_stub():
response.birth_certificate_implemented = True
# Attestations and lineage
response.attestations_count = len(lct.attestations)
response.lineage_implemented = len(lct.lineage) > 0
# Relationship support (based on entity type and level)
response.can_be_bound_by = _get_bindable_types(lct.entity_type)
response.can_pair_with = _get_pairable_types(lct.entity_type, lct.capability_level)
response.can_witness = _get_witnessable_types(lct.entity_type, lct.capability_level)
response.can_be_witnessed_by = _get_witness_sources(lct.entity_type)
# Trust tier
response.trust_tier = _compute_trust_tier(response.composite_t3)
return response
def _get_bindable_types(entity_type: EntityType) -> List[str]:
"""Get entity types that can bind to this entity."""
binding_rules = {
EntityType.PLUGIN: ["ai", "device", "service"],
EntityType.SESSION: ["ai", "human"],
EntityType.AI: ["device", "organization"],
EntityType.DEVICE: ["organization"],
EntityType.SERVICE: ["device", "organization"],
}
return binding_rules.get(entity_type, [])
def _get_pairable_types(entity_type: EntityType, level: CapabilityLevel) -> List[str]:
"""Get entity types that can pair with this entity."""
if level < CapabilityLevel.BASIC:
return []
pairing_rules = {
EntityType.PLUGIN: ["ai", "plugin", "service"],
EntityType.AI: ["plugin", "service", "ai", "human", "device"],
EntityType.HUMAN: ["ai", "service", "organization"],
EntityType.SERVICE: ["ai", "plugin", "service", "human"],
EntityType.DEVICE: ["ai", "service", "device"],
}
return pairing_rules.get(entity_type, ["ai", "service"])
def _get_witnessable_types(entity_type: EntityType, level: CapabilityLevel) -> List[str]:
"""Get entity types this entity can witness."""
if level < CapabilityLevel.STANDARD:
return []
witness_rules = {
EntityType.ORACLE: ["ai", "device", "service", "human"],
EntityType.AI: ["plugin", "task", "session"],
EntityType.HUMAN: ["ai", "service", "organization"],
EntityType.WITNESS: ["ai", "device", "service", "human", "organization"],
}
return witness_rules.get(entity_type, [])
def _get_witness_sources(entity_type: EntityType) -> List[str]:
"""Get entity types that can witness this entity."""
return ["oracle", "human", "ai", "witness", "society"]
def _compute_trust_tier(composite_t3: Optional[float]) -> str:
"""Compute trust tier from T3 composite score."""
if composite_t3 is None:
return "unknown"
elif composite_t3 < 0.2:
return "untrusted"
elif composite_t3 < 0.4:
return "low"
elif composite_t3 < 0.6:
return "medium"
elif composite_t3 < 0.8:
return "high"
else:
return "exceptional"
# =============================================================================
# LCT Creation Helpers
# =============================================================================
def generate_lct_id(entity_type: EntityType, name: str) -> str:
"""Generate a canonical LCT ID."""
# Create hash from name and timestamp
content = f"{entity_type.value}:{name}:{datetime.now(timezone.utc).isoformat()}"
hash_bytes = hashlib.sha256(content.encode()).hexdigest()[:16]
return f"lct:web4:{entity_type.value}:{hash_bytes}"
def create_minimal_lct(
entity_type: EntityType,
level: CapabilityLevel = CapabilityLevel.MINIMAL,
name: Optional[str] = None,
parent_lct: Optional[str] = None,
public_key: Optional[str] = None
) -> LCT:
"""
Create an LCT at the specified capability level.
Args:
entity_type: Type of entity
level: Capability level (0-5)
name: Entity name (used in ID generation)
parent_lct: Parent LCT for binding relationship
public_key: Public key for binding (generated if None)
Returns:
LCT instance
"""
name = name or f"{entity_type.value}-{datetime.now().strftime('%H%M%S')}"
lct_id = generate_lct_id(entity_type, name)
# Create LCT
lct = LCT(
lct_id=lct_id,
capability_level=level,
entity_type=entity_type,
subject=f"did:web4:key:{lct_id.split(':')[-1]}"
)
# Add binding for Level 1+
if level >= CapabilityLevel.MINIMAL:
lct.binding = LCTBinding(
entity_type=entity_type.value,
public_key=public_key or f"mb64:ed25519:{lct_id.split(':')[-1]}",
created_at=datetime.now(timezone.utc).isoformat()
)
# Add parent binding for Level 2+
if level >= CapabilityLevel.BASIC and parent_lct:
lct.mrh.add_bound(parent_lct, subtype="parent", binding_context="deployment")
return lct
# =============================================================================
# Level Validation
# =============================================================================
@dataclass
class ValidationResult:
"""Result of LCT level validation."""
valid: bool
current_level: CapabilityLevel
claimed_level: CapabilityLevel
errors: List[str] = field(default_factory=list)
warnings: List[str] = field(default_factory=list)
def validate_lct_level(lct: LCT) -> ValidationResult:
"""
Validate that an LCT meets the requirements for its claimed level.
Returns ValidationResult with any errors/warnings.
"""
result = ValidationResult(
valid=True,
current_level=CapabilityLevel.STUB,
claimed_level=lct.capability_level
)
# Level 0: Just needs lct_id
if not lct.lct_id or not lct.lct_id.startswith("lct:web4:"):
result.errors.append("Invalid lct_id format")
result.valid = False
return result
result.current_level = CapabilityLevel.STUB
# Level 1: Needs binding with public key, T3/V3 tensors
if lct.capability_level >= CapabilityLevel.MINIMAL:
if not lct.binding or not lct.binding.public_key:
result.errors.append("Level 1+ requires binding with public_key")
result.valid = False
else:
result.current_level = CapabilityLevel.MINIMAL
if lct.t3_tensor is None or lct.t3_tensor.is_stub():
result.errors.append("Level 1+ requires non-stub T3 tensor")
result.valid = False
if lct.v3_tensor is None or lct.v3_tensor.is_stub():
result.errors.append("Level 1+ requires non-stub V3 tensor")
result.valid = False
# Level 2: Needs at least one MRH relationship
if lct.capability_level >= CapabilityLevel.BASIC:
if not lct.mrh or not lct.mrh.has_relationships():
result.errors.append("Level 2+ requires at least one MRH relationship")
result.valid = False
else:
result.current_level = CapabilityLevel.BASIC
if not lct.policy or not lct.policy.capabilities:
result.warnings.append("Level 2+ should have at least one policy capability")
# Level 3: Needs witnessing, oracle-computed tensors, attestations
if lct.capability_level >= CapabilityLevel.STANDARD:
if not lct.mrh.witnessing:
result.warnings.append("Level 3+ should have witnessing relationships")
if lct.t3_tensor and not lct.t3_tensor.computation_witnesses:
result.warnings.append("Level 3+ should have oracle-computed T3")
if lct.v3_tensor and (lct.v3_tensor.energy_balance is None or
lct.v3_tensor.energy_balance == 0):
result.warnings.append("Level 3+ should have non-zero ATP energy balance")
if not lct.attestations:
result.warnings.append("Level 3+ should have at least one attestation")
if result.valid:
result.current_level = CapabilityLevel.STANDARD
# Level 4: Needs birth certificate with witnesses
if lct.capability_level >= CapabilityLevel.FULL:
if not lct.birth_certificate or lct.birth_certificate.is_stub():
result.errors.append("Level 4+ requires birth certificate")
result.valid = False
elif len(lct.birth_certificate.birth_witnesses) < 3:
result.errors.append("Level 4+ requires minimum 3 birth witnesses")
result.valid = False
else:
result.current_level = CapabilityLevel.FULL
# Check for permanent citizen pairing
has_citizen_pairing = any(
p.subtype == "birth_certificate" and p.permanent
for p in lct.mrh.paired
)
if not has_citizen_pairing:
result.errors.append("Level 4+ requires permanent citizen pairing")
result.valid = False
# Level 5: Needs hardware binding
if lct.capability_level >= CapabilityLevel.HARDWARE:
if not lct.binding or not lct.binding.is_hardware_bound():
result.errors.append("Level 5 requires hardware-anchored binding")
result.valid = False
else:
result.current_level = CapabilityLevel.HARDWARE
return result
# =============================================================================
# Demo
# =============================================================================
def demo():
"""Demonstrate LCT capability levels."""
print("=" * 70)
print("LCT CAPABILITY LEVELS DEMONSTRATION")
print("=" * 70)
print()
# Create Level 1 plugin
print("Creating Level 1 Plugin LCT...")
plugin_lct = create_minimal_lct(
entity_type=EntityType.PLUGIN,
level=CapabilityLevel.MINIMAL,
name="vision-irp"
)
print(f" LCT ID: {plugin_lct.lct_id}")
print(f" Level: {plugin_lct.capability_level.name}")
print(f" T3 composite: {plugin_lct.t3_tensor.composite_score:.3f}")
print()
# Validate
result = validate_lct_level(plugin_lct)
print(f" Validation: {'PASS' if result.valid else 'FAIL'}")
if result.errors:
for e in result.errors:
print(f" ERROR: {e}")
print()
# Create Level 2 plugin with parent binding
print("Creating Level 2 Plugin LCT with parent binding...")
plugin_lct2 = create_minimal_lct(
entity_type=EntityType.PLUGIN,
level=CapabilityLevel.BASIC,
name="audio-irp",
parent_lct="lct:web4:agent:sage-orchestrator"
)
plugin_lct2.policy.capabilities = ["execute:irp", "read:patterns"]
print(f" LCT ID: {plugin_lct2.lct_id}")
print(f" Level: {plugin_lct2.capability_level.name}")