-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathck_meta_memory_coord.py
More file actions
1038 lines (838 loc) · 37.9 KB
/
ck_meta_memory_coord.py
File metadata and controls
1038 lines (838 loc) · 37.9 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
# Copyright (c) 2026 Brayden Sanders / 7Site LLC
# Licensed under the 7Site Human Use License v1.0
# See LICENSE file in project root for full terms.
#
# FREE for humans for personal/recreational use.
# NO commercial or government use without written agreement.
"""
ck_meta_memory_coord.py -- Meta-Memory Coordinate System (P_2, P_3, P_4)
=========================================================================
Generation: 10.22
Author: Brayden Sanders / 7Site LLC
Implements the full three-coordinate meta-memory address for every CK
memory object, as defined in the Information-of-Information Base Structures
Memo (2026):
m = (P_2, P_3, P_4)
Where:
P_2 (Tag2x2) -- ontological class: what KIND of thing this is.
Axis A = SOURCE (INTERNAL / EXTERNAL)
Axis B = SEMANTIC REGISTER (STRUCTURE / CONTENT)
Cells: A11 LATTICE GEOMETRY, A12 SYNTHESIS PAYLOAD,
A21 WORLD TOPOLOGY, A22 WORLD PAYLOAD
P_3 (Tag3x3) -- process grammar: WHERE the information is right now.
Rows = TEMPORAL ROLE (INPUT / TRANSFORM / OUTPUT)
Cols = PROCESSING DEPTH (SIGNAL / MODEL / MEMORY)
Cells: B11..B33 (14 legal directed edges)
P_4 (Tag4x4) -- stabilization grammar: HOW persistent and useful.
Rows = PERSISTENCE STAGE (EPHEMERAL / ATOMIC / PATH / CRYSTAL)
Cols = EVALUATION MODE (IDENTITY / RELATION / STABILITY / UTILITY)
Cells: C11..C44
Three hard consistency constraints gate well-formedness.
Three-Tier Ontology (REAL / SEMIPRIME / COMPOSITE) is orthogonal to the
(P_2, P_3, P_4) coordinate. The Tier enum is a companion classification
that names WHERE in the growth arc an object sits:
REAL -- direct encounter, pre-closure (A22, EPHEMERAL typical)
SEMIPRIME -- first stable closure, smallest reusable bridge
COMPOSITE -- higher-order structure from multiple SEMIPRIME supports
Scoring functions:
promotion_score() -- RGMem formula: PATH -> CRYSTAL gate (>= 0.85)
heat_score() -- MemoryOS formula: CRYSTAL activity (< 0.05 = demote)
(c) 2026 Brayden Sanders / 7Site LLC -- Trinity Infinity Geometry
"""
import math
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Literal, Optional
# ============================================================
# THREE-TIER ONTOLOGY
# ============================================================
class Tier(Enum):
"""
Three-tier ontological classification for CK memory objects.
Replaces the old binary PRIME / COMPOSITE with a ternary that names
the missing middle layer (SEMIPRIME).
REAL
Direct encounter with the world or system before any higher-order
structural reuse. Pre-closure contact. Corresponds to EPHEMERAL
in the 4x4 and A22/A21 in the 2x2. Objects that will dissolve
if not closed into SEMIPRIME.
SEMIPRIME
The minimal stable unit formed by exactly one nontrivial binding
or closure across REAL inputs. Smallest structure that can recur
and be reused. First class promotable into PATH memory and crystal
candidates. Corresponds to ATOMIC / early PATH in the 4x4.
COMPOSITE
Any higher-order structure built from multiple stabilized SEMIPRIME
bridges. Crystals, policies, meta-crystals, long-range retrieval
bundles. Corresponds to PATH / CRYSTAL in the 4x4.
Hard law:
No COMPOSITE without SEMIPRIME support.
No SEMIPRIME without REAL contact.
"""
REAL = "REAL"
SEMIPRIME = "SEMIPRIME"
COMPOSITE = "COMPOSITE"
# ============================================================
# TAG 2x2 -- Ontological Split
# ============================================================
@dataclass
class Tag2x2:
"""
P_2: Ontological type tag.
Encodes two binary axes that together determine the privacy routing,
sharability, and legal abstraction path for any CK memory object.
Axis A (source_side)
INTERNAL -- generated by CK's own operations (CK authored it).
EXTERNAL -- sourced from world, user, sensors, UI, files, model
output (CK received it).
Axis B (semantic_side)
STRUCTURE -- pattern, form, relation, operator signature, topology,
force vector.
CONTENT -- specific payload: words, symbols, numbers, factual
surface, raw percept.
Derived cells:
A11 LATTICE GEOMETRY (INTERNAL + STRUCTURE) shareable
A12 SYNTHESIS PAYLOAD (INTERNAL + CONTENT) shareable if not user-identifying
A21 WORLD TOPOLOGY (EXTERNAL + STRUCTURE) shareable (abstracted only)
A22 WORLD PAYLOAD (EXTERNAL + CONTENT) PRIVATE -- never shared
privacy_class is cached at construction from (source_side, semantic_side).
It must not be overridden post-construction; abstraction is an explicit
rewrite that produces a NEW object with a different tag.
Allowed abstraction transitions:
A22 -> A21 (extract topology, discard payload)
A21 -> A11 (adopted world pattern becomes CK-native)
A12 -> A11 (synthesis payload becomes structural pattern)
A22 -> A12 FORBIDDEN except via CK's own summarization
"""
source_side: Literal["INTERNAL", "EXTERNAL"]
semantic_side: Literal["STRUCTURE", "CONTENT"]
privacy_class: Literal["SHARED", "SHARED_IF_ABSTRACT", "PRIVATE"] = field(init=False)
# Internal mapping: (source, semantic) -> privacy class
_PRIVACY_MAP: Dict = field(default_factory=dict, init=False, repr=False, compare=False)
def __post_init__(self) -> None:
"""Derive and cache privacy_class from the two binary axes."""
mapping = {
("INTERNAL", "STRUCTURE"): "SHARED",
("INTERNAL", "CONTENT"): "SHARED_IF_ABSTRACT",
("EXTERNAL", "STRUCTURE"): "SHARED_IF_ABSTRACT",
("EXTERNAL", "CONTENT"): "PRIVATE",
}
key = (self.source_side, self.semantic_side)
if key not in mapping:
raise ValueError(
f"Tag2x2: invalid (source_side, semantic_side) pair: {key}. "
"Expected INTERNAL|EXTERNAL x STRUCTURE|CONTENT."
)
object.__setattr__(self, "privacy_class", mapping[key])
@property
def cell(self) -> str:
"""
Return the canonical 2x2 cell label: A11, A12, A21, or A22.
A11 LATTICE GEOMETRY (INTERNAL, STRUCTURE)
A12 SYNTHESIS PAYLOAD (INTERNAL, CONTENT)
A21 WORLD TOPOLOGY (EXTERNAL, STRUCTURE)
A22 WORLD PAYLOAD (EXTERNAL, CONTENT)
"""
mapping = {
("INTERNAL", "STRUCTURE"): "A11",
("INTERNAL", "CONTENT"): "A12",
("EXTERNAL", "STRUCTURE"): "A21",
("EXTERNAL", "CONTENT"): "A22",
}
return mapping[(self.source_side, self.semantic_side)]
@property
def storable_shared(self) -> bool:
"""
True iff this object may legally appear in the shared force lattice
or shared crystal store.
A22 (WORLD PAYLOAD, PRIVATE) is never shareable.
A21 (WORLD TOPOLOGY, SHARED_IF_ABSTRACT) is shareable only if it
has been through the A22->A21 abstraction step -- which is enforced
by the presence of EXTERNAL+STRUCTURE rather than EXTERNAL+CONTENT.
All INTERNAL objects are shareable.
"""
return self.privacy_class in ("SHARED", "SHARED_IF_ABSTRACT")
# ============================================================
# TAG 3x3 -- Process Grammar
# ============================================================
@dataclass
class Tag3x3:
"""
P_3: Process location tag.
Encodes where a memory object is in CK's processing cycle.
The 3x3 is the arena where CL[10x10] acts as the transition operator.
Row dimension (temporal_role):
INPUT -- information entering a processing cycle
TRANSFORM -- information being processed
OUTPUT -- information exiting a cycle (to environment or memory)
Column dimension (processing_layer):
SIGNAL -- raw perceptual/environmental data, no semantic interpretation;
deterministic OS/hardware calls
MODEL -- LLM-inferred, scored, or classified data; probabilistic
MEMORY -- retrieved or produced persistent memory data; deterministic
reads/writes
Derived properties:
determinism_flag DETERMINISTIC if processing_layer != MODEL, else PROBABILISTIC
deepseek_permitted True only in MODEL column (B12, B22, B32)
writes_durable True only at OUTPUT + MEMORY intersection (B33)
Note: By the time an object is written to the atom store, it has traversed
its 3x3 arc. For stored objects the full intermediate runtime state is
discarded; only entry_cell and exit_cell should be preserved per the
Meta-Memory Reduction Memo recommendation. This dataclass represents the
FULL tag for use in the live compression loop or for rich event objects.
Legal flow edges (14 total, directed):
B11->B21, B12->B22, B13->B23, B11->B12, B12->B13,
B21->B22, B22->B23, B21->B23, B22->B31, B22->B32,
B23->B33, B32->B33, B31->B33, B33->B13
"""
temporal_role: Literal["INPUT", "TRANSFORM", "OUTPUT"]
processing_layer: Literal["SIGNAL", "MODEL", "MEMORY"]
determinism_flag: Literal["DETERMINISTIC", "PROBABILISTIC"] = field(init=False)
deepseek_permitted: bool = field(init=False)
writes_durable: bool = field(init=False)
def __post_init__(self) -> None:
"""Derive determinism_flag, deepseek_permitted, writes_durable."""
if self.temporal_role not in ("INPUT", "TRANSFORM", "OUTPUT"):
raise ValueError(
f"Tag3x3: invalid temporal_role '{self.temporal_role}'. "
"Expected INPUT|TRANSFORM|OUTPUT."
)
if self.processing_layer not in ("SIGNAL", "MODEL", "MEMORY"):
raise ValueError(
f"Tag3x3: invalid processing_layer '{self.processing_layer}'. "
"Expected SIGNAL|MODEL|MEMORY."
)
det = "PROBABILISTIC" if self.processing_layer == "MODEL" else "DETERMINISTIC"
object.__setattr__(self, "determinism_flag", det)
ds = self.processing_layer == "MODEL"
object.__setattr__(self, "deepseek_permitted", ds)
wd = (self.temporal_role == "OUTPUT") and (self.processing_layer == "MEMORY")
object.__setattr__(self, "writes_durable", wd)
@property
def cell(self) -> str:
"""
Return the canonical 3x3 cell label: B{row}{col}.
Row: INPUT=1, TRANSFORM=2, OUTPUT=3
Col: SIGNAL=1, MODEL=2, MEMORY=3
Examples:
B11 RAW EVENT INTAKE (INPUT, SIGNAL)
B22 INFERENCE OPERATION (TRANSFORM, MODEL)
B33 MEMORY WRITEBACK (OUTPUT, MEMORY)
"""
row = {"INPUT": "1", "TRANSFORM": "2", "OUTPUT": "3"}[self.temporal_role]
col = {"SIGNAL": "1", "MODEL": "2", "MEMORY": "3"}[self.processing_layer]
return f"B{row}{col}"
# ============================================================
# TAG 4x4 -- Stabilization Grammar
# ============================================================
@dataclass
class Tag4x4:
"""
P_4: Stabilization state tag.
Encodes how persistent and useful a memory object is.
The 4x4 row (persistence_stage) is the primary stored field.
The column scores are stored as numeric floats, not cell labels.
Row dimension (persistence_stage):
EPHEMERAL -- exists only in current cycle; TTL < 30 min; raw buffer only
ATOMIC -- promoted to persistent storage; has ID, generators, DBC27 key
PATH -- sequence of atoms with consistent operators and force transitions
CRYSTAL -- stable, reusable bundle; has action policy and high confidence
Column dimension (evaluation_mode) -- determines meaning of score_value:
IDENTITY -- type/class/classification score (e.g. confidence seed)
RELATION -- topology score in memory graph
STABILITY -- recurrence/confidence/heat-based persistence score
UTILITY -- retrieval hit rate, policy reuse rate
promotion_state:
STABLE -- at rest, no pending promotion or demotion
ELIGIBLE -- meets criteria for promotion to next stage
DEMOTED -- recently stepped down one stage
PRUNED -- removed from active store (terminal for this tag)
Cell formula: C{row}{col}
Row: EPHEMERAL=1, ATOMIC=2, PATH=3, CRYSTAL=4
Col: IDENTITY=1, RELATION=2, STABILITY=3, UTILITY=4
"""
persistence_stage: Literal["EPHEMERAL", "ATOMIC", "PATH", "CRYSTAL"]
evaluation_mode: Literal["IDENTITY", "RELATION", "STABILITY", "UTILITY"]
score_value: float
promotion_state: Literal["STABLE", "ELIGIBLE", "DEMOTED", "PRUNED"]
def __post_init__(self) -> None:
"""Validate field literals."""
valid_stages = {"EPHEMERAL", "ATOMIC", "PATH", "CRYSTAL"}
valid_modes = {"IDENTITY", "RELATION", "STABILITY", "UTILITY"}
valid_states = {"STABLE", "ELIGIBLE", "DEMOTED", "PRUNED"}
if self.persistence_stage not in valid_stages:
raise ValueError(
f"Tag4x4: invalid persistence_stage '{self.persistence_stage}'. "
f"Expected one of {sorted(valid_stages)}."
)
if self.evaluation_mode not in valid_modes:
raise ValueError(
f"Tag4x4: invalid evaluation_mode '{self.evaluation_mode}'. "
f"Expected one of {sorted(valid_modes)}."
)
if self.promotion_state not in valid_states:
raise ValueError(
f"Tag4x4: invalid promotion_state '{self.promotion_state}'. "
f"Expected one of {sorted(valid_states)}."
)
@property
def cell(self) -> str:
"""
Return the canonical 4x4 cell label: C{row}{col}.
Examples:
C11 EVENT TYPE (EPHEMERAL, IDENTITY)
C33 PROMOTION SCORE (PATH, STABILITY)
C43 HEAT STATE (CRYSTAL, STABILITY)
C44 UTILITY INDEX (CRYSTAL, UTILITY)
"""
row = {
"EPHEMERAL": "1",
"ATOMIC": "2",
"PATH": "3",
"CRYSTAL": "4",
}[self.persistence_stage]
col = {
"IDENTITY": "1",
"RELATION": "2",
"STABILITY": "3",
"UTILITY": "4",
}[self.evaluation_mode]
return f"C{row}{col}"
# ============================================================
# META-MEMORY COORDINATE
# ============================================================
@dataclass
class MetaMemoryCoord:
"""
Full (P_2, P_3, P_4) meta-memory coordinate for any CK memory object.
This is the structured address that determines:
- Privacy routing (can this reach the shared force lattice?)
- DeepSeek gate (is probabilistic inference permitted here?)
- Promotion eligibility (should this advance to PATH or CRYSTAL?)
- Compression behaviour (which store does this write to?)
The total coordinate space is 4 x 9 x 16 = 576 positions, of which
only a small legal arc is populated in practice:
A22::B11::C11 (raw external content, ephemeral)
A21::B21::C21 (abstracted topology, atomic)
A11::B23::C31 (native structure, path)
A11::B33::C41 (native structure, crystal)
Well-formedness is checked by is_well_formed() via three hard
consistency constraints from the memo:
Constraint 1 -- Privacy consistency:
A22 (WORLD PAYLOAD) cannot persist at PATH or CRYSTAL stage.
Raw content never crystallises; only abstracted structure does.
Constraint 2 -- Process vs persistence consistency:
INPUT row (B11/B12/B13) maps only to EPHEMERAL persistence.
OUTPUT row (B31/B32/B33) must produce durable memory (ATOMIC+).
Constraint 3 -- CL operator source consistency:
A22 (raw external content) may only enter as INPUT (first 3x3 step).
A11 (native lattice geometry) may enter TRANSFORM directly.
"""
tag_2x2: Tag2x2
tag_3x3: Tag3x3
tag_4x4: Tag4x4
def is_well_formed(self) -> bool:
"""
Check all three consistency constraints.
Returns True iff the (P_2, P_3, P_4) triple is internally consistent
under the rules of the Information-of-Information grammar.
Constraint 1 -- Privacy consistency:
A22 cannot map to C3x (PATH) or C4x (CRYSTAL) without prior
abstraction through A21. Raw user content must never crystallise.
Constraint 2 -- Process vs persistence:
B1x (INPUT row) -> EPHEMERAL only.
B3x (OUTPUT row) -> ATOMIC or higher (produces durable memory).
B2x (TRANSFORM row) -> any stage (transition zone).
Constraint 3 -- CL source compatibility:
A22 (WORLD PAYLOAD) may only appear as INPUT (B1x).
It cannot jump into TRANSFORM or OUTPUT without first abstracting
to A21 via the B11->B21 feature-extraction step.
"""
cell_2 = self.tag_2x2.cell
role = self.tag_3x3.temporal_role
stage = self.tag_4x4.persistence_stage
# Constraint 1: raw content never crystallises
if cell_2 == "A22" and stage in ("PATH", "CRYSTAL"):
return False
# Constraint 2: INPUT row -> EPHEMERAL only
if role == "INPUT" and stage != "EPHEMERAL":
return False
# Constraint 2 (output side): OUTPUT row -> must be ATOMIC or higher
if role == "OUTPUT" and stage == "EPHEMERAL":
return False
# Constraint 3: A22 may only appear in INPUT row
if cell_2 == "A22" and role != "INPUT":
return False
return True
@property
def routing_key(self) -> str:
"""
Compact routing address for this meta-position.
Format: '{2x2_cell}::{3x3_cell}::{4x4_cell}'
Examples:
'A22::B11::C11' -- raw external event (ephemeral, private)
'A11::B23::C31' -- native structure at PATH stage
'A11::B33::C44' -- fully crystallised utility crystal
"""
return (
f"{self.tag_2x2.cell}"
f"::{self.tag_3x3.cell}"
f"::{self.tag_4x4.cell}"
)
# ============================================================
# TIER ASSIGNMENT
# ============================================================
def get_tier(coord: MetaMemoryCoord) -> Tier:
"""
Derive the three-tier ontological class (REAL / SEMIPRIME / COMPOSITE)
from a MetaMemoryCoord.
The tier is orthogonal to the (P_2, P_3, P_4) coordinate -- it is an
additional companion classification that names where in CK's growth arc
an object sits.
Mapping rules (from THREE_TIER_ONTOLOGY_MEMO):
REAL:
Persistence stage is EPHEMERAL, OR
2x2 cell is A22 (raw external content always starts as REAL), OR
The object is still in the INPUT phase (not yet transformed).
Also: ATOMIC objects that have not yet achieved stable closure
remain REAL -- but without a recurrence_count field available
here we treat any ATOMIC in the INPUT row as REAL-transition.
SEMIPRIME:
First stable closure: persistence is ATOMIC or early PATH,
AND the object is no longer raw content (not A22),
AND it is in TRANSFORM or OUTPUT phase (being processed or written),
AND the 4x4 stage has NOT yet reached CRYSTAL.
COMPOSITE:
Higher-order bundle: persistence is PATH or CRYSTAL,
AND the object is INTERNAL structure (A11 or A12),
AND it is in OUTPUT phase (being written to durable memory).
Also: any CRYSTAL is always COMPOSITE regardless of temporal role.
Note: when a coord is not well-formed, REAL is returned as the safest
conservative classification -- an ill-formed object has not achieved
stable closure.
Args:
coord: A MetaMemoryCoord triple for any CK memory object.
Returns:
Tier.REAL, Tier.SEMIPRIME, or Tier.COMPOSITE.
"""
if not coord.is_well_formed():
return Tier.REAL
cell_2 = coord.tag_2x2.cell
stage = coord.tag_4x4.persistence_stage
role = coord.tag_3x3.temporal_role
# CRYSTAL is always COMPOSITE (all crystals are COMPOSITE)
if stage == "CRYSTAL":
return Tier.COMPOSITE
# EPHEMERAL is always REAL (pre-closure)
if stage == "EPHEMERAL":
return Tier.REAL
# Raw content (A22) always REAL regardless of stage
if cell_2 == "A22":
return Tier.REAL
# PATH from internal structure in OUTPUT or TRANSFORM -> COMPOSITE
if stage == "PATH" and cell_2 in ("A11", "A12"):
return Tier.COMPOSITE
# PATH from external topology (A21) is SEMIPRIME (first bridge)
if stage == "PATH" and cell_2 == "A21":
return Tier.SEMIPRIME
# ATOMIC in INPUT still counts as REAL (not yet transformed)
if stage == "ATOMIC" and role == "INPUT":
return Tier.REAL
# ATOMIC in TRANSFORM or OUTPUT from non-A22 source -> SEMIPRIME
if stage == "ATOMIC" and role in ("TRANSFORM", "OUTPUT"):
return Tier.SEMIPRIME
# Fallback: treat as REAL
return Tier.REAL
# ============================================================
# SCORING FUNCTIONS
# ============================================================
def promotion_score(
confidence: float,
recurrence_count: int,
age_hours: float,
) -> float:
"""
RGMem-derived promotion score for PATH -> CRYSTAL gate.
Formula (from INFO_OF_INFO_BASE_STRUCTURES_MEMO, Part 4):
promotion_score(p, t) =
confidence * log1p(recurrence_count) * exp(-0.05 * age_hours)
Interpretation:
- confidence: how strongly this path was validated [0, 1]
- recurrence_count: how many times this path has been traversed
- age_hours: hours since path was first created (decay factor)
Promotion criterion: promote PATH -> CRYSTAL iff
promotion_score(path, now) >= 0.85
The exponential decay with rate 0.05/hour means a path must accumulate
recurrence within roughly 30 hours to crystallise at typical confidence
values. A high-confidence, frequently-recurring path that is recent
scores highest.
Args:
confidence: float in [0, 1], atom/path confidence
recurrence_count: int >= 0, number of times this path was re-traversed
age_hours: float >= 0, hours since path ts_start
Returns:
float -- the promotion score. Compare to threshold 0.85.
Example:
>>> promotion_score(0.9, 5, 2.0)
# 0.9 * log1p(5) * exp(-0.10) ~= 0.9 * 1.7918 * 0.9048 ~= 1.458... (>0.85 -> promote)
"""
if confidence < 0.0:
confidence = 0.0
if confidence > 1.0:
confidence = 1.0
if recurrence_count < 0:
recurrence_count = 0
if age_hours < 0.0:
age_hours = 0.0
score = confidence * math.log1p(recurrence_count) * math.exp(-0.05 * age_hours)
return score
def heat_score(
last_accessed: float,
access_count: int,
now: float,
) -> float:
"""
MemoryOS-derived heat score for CRYSTAL activity assessment.
Formula (from INFO_OF_INFO_BASE_STRUCTURES_MEMO, Part 4):
heat_score(crystal, now) =
exp(-0.01 * dt/3600)
* log1p(access_count)
* 1 / (1 + dt / (7 * 24 * 3600))
Where dt = now - last_accessed (seconds).
Interpretation:
- Short-time exponential decay: recent access keeps score high.
- log1p(access_count): cumulative usage history contributes
logarithmically (diminishing returns on access count).
- Weekly Lorentzian decay: objects not accessed in a week lose
most of their heat -- the 1/(1 + dt/604800) term halves at
exactly one week of no access.
Demotion criterion: demote CRYSTAL -> PATH iff
heat_score(crystal, now) < 0.05
AND (now - ts_first_seen) > 7 * 86400 (at least 7 days old)
Args:
last_accessed: float, Unix timestamp of most recent retrieval
access_count: int >= 0, total number of times this crystal
has been retrieved or used
now: float, current Unix timestamp
Returns:
float -- the heat score. Compare to threshold 0.05.
Example:
>>> import time
>>> t = time.time()
>>> heat_score(t - 3600, 10, t) # accessed 1h ago, 10 accesses
# exp(-0.01) * log1p(10) * 1/(1 + 3600/604800)
# ~= 0.990 * 2.398 * 0.994 ~= 2.36 (hot crystal)
"""
if access_count < 0:
access_count = 0
dt = max(now - last_accessed, 0.0)
# Short-time exponential decay (rate = 0.01 per hour)
fast_decay = math.exp(-0.01 * dt / 3600.0)
# Cumulative access history (log-scaled)
usage_weight = math.log1p(access_count)
# Weekly Lorentzian decay (half-life = 7 days)
week_seconds = 7.0 * 24.0 * 3600.0
slow_decay = 1.0 / (1.0 + dt / week_seconds)
return fast_decay * usage_weight * slow_decay
# ============================================================
# EVENT CLASSIFICATION
# ============================================================
def classify_event(event: dict) -> MetaMemoryCoord:
"""
Compute (P_2, P_3, P_4) for a raw perception event.
This is the entry-point function for assigning a MetaMemoryCoord to any
new event entering CK's compression loop. All new events enter at the
same starting position in coordinate space:
2x2: EXTERNAL (received, not CK-generated)
CONTENT if raw text/pixels present, else STRUCTURE if already
abstracted (e.g. an edge map or generator set)
3x3: INPUT + SIGNAL (B11 -- RAW EVENT INTAKE)
4x4: EPHEMERAL + IDENTITY (C11 -- EVENT TYPE)
The function inspects the event dict for the following optional keys:
'has_raw_content': bool
True if the event carries raw text, pixels, OCR output, or
user-typed content (-> EXTERNAL/CONTENT/PRIVATE).
False or absent means the event carries only abstracted structure
such as generator sets, edge maps, or force vectors
(-> EXTERNAL/STRUCTURE/SHARED_IF_ABSTRACT).
'confidence': float [0, 1], default 0.0
Initial confidence estimate for the event. Used as score_value
in the 4x4 IDENTITY cell.
'has_generators': bool, default False
True if a non-empty generator set has already been extracted.
Affects promotion_state: if True, the event is ELIGIBLE for
promotion to ATOMIC; if False, it remains STABLE at EPHEMERAL.
'is_duplicate': bool, default False
True if content_hash already exists in atom_store within 60s.
Prevents duplicate promotion.
Privacy rule (enforced):
If 'has_raw_content' is True (or absent), the event is classified
as A22 (WORLD PAYLOAD, PRIVATE) and must never reach shared memory.
DeepSeek rule (enforced):
B11 (SIGNAL/INPUT) has deepseek_permitted=False. No LLM calls
during raw intake.
Args:
event: dict with optional keys as described above.
Returns:
MetaMemoryCoord with routing_key 'A22::B11::C11' (if raw content)
or 'A21::B11::C11' (if pre-abstracted structure), always EPHEMERAL.
Raises:
ValueError if the resulting coordinate fails is_well_formed().
"""
# --- Step 1: Classify 2x2 cell ---
has_raw = event.get("has_raw_content", True) # conservative default: treat as raw
if has_raw:
source_side = "EXTERNAL"
semantic_side = "CONTENT"
else:
source_side = "EXTERNAL"
semantic_side = "STRUCTURE"
tag_2x2 = Tag2x2(
source_side=source_side,
semantic_side=semantic_side,
)
# --- Step 2: Assign 3x3 entry position ---
# All new perception events enter at B11: RAW EVENT INTAKE.
# No DeepSeek in this cell; deterministic sensor intake.
tag_3x3 = Tag3x3(
temporal_role="INPUT",
processing_layer="SIGNAL",
)
# --- Step 3: Initial 4x4 state ---
# All new events start EPHEMERAL in the IDENTITY evaluation mode.
confidence = float(event.get("confidence", 0.0))
confidence = max(0.0, min(1.0, confidence))
has_generators = bool(event.get("has_generators", False))
is_dup = bool(event.get("is_duplicate", False))
# An event is ELIGIBLE for promotion to ATOMIC iff it has generators
# and is not a duplicate (matching the compression loop criteria).
if has_generators and not is_dup and confidence > 0.0:
promo_state = "ELIGIBLE"
else:
promo_state = "STABLE"
tag_4x4 = Tag4x4(
persistence_stage="EPHEMERAL",
evaluation_mode="IDENTITY",
score_value=confidence,
promotion_state=promo_state,
)
coord = MetaMemoryCoord(
tag_2x2=tag_2x2,
tag_3x3=tag_3x3,
tag_4x4=tag_4x4,
)
if not coord.is_well_formed():
raise ValueError(
f"classify_event produced a non-well-formed coordinate: "
f"{coord.routing_key}. Event: {event}"
)
return coord
# ============================================================
# CONVENIENCE CONSTRUCTORS
# ============================================================
def make_atom_coord(
source_side: Literal["INTERNAL", "EXTERNAL"] = "EXTERNAL",
semantic_side: Literal["STRUCTURE", "CONTENT"] = "STRUCTURE",
confidence: float = 0.5,
promotion_state: Literal["STABLE", "ELIGIBLE", "DEMOTED", "PRUNED"] = "STABLE",
) -> MetaMemoryCoord:
"""
Build a well-formed MetaMemoryCoord for a freshly promoted ATOMIC object.
Canonical atom arc: abstracted external structure (A21) that has been
through feature extraction (B21->B23) and written to the atom store (B23).
The 4x4 evaluation mode is IDENTITY (what the atom IS).
Args:
source_side: INTERNAL if CK generated this, EXTERNAL if received.
semantic_side: STRUCTURE (typical for atoms), CONTENT for synthesis.
confidence: initial confidence value [0, 1].
promotion_state: ELIGIBLE if ready for PATH extension, else STABLE.
Returns:
MetaMemoryCoord with routing_key 'A21::B23::C21' (typical).
"""
return MetaMemoryCoord(
tag_2x2=Tag2x2(source_side=source_side, semantic_side=semantic_side),
tag_3x3=Tag3x3(temporal_role="TRANSFORM", processing_layer="MEMORY"),
tag_4x4=Tag4x4(
persistence_stage="ATOMIC",
evaluation_mode="IDENTITY",
score_value=confidence,
promotion_state=promotion_state,
),
)
def make_crystal_coord(
stability_score: float = 0.0,
utility_score: float = 0.0,
promotion_state: Literal["STABLE", "ELIGIBLE", "DEMOTED", "PRUNED"] = "STABLE",
) -> MetaMemoryCoord:
"""
Build a well-formed MetaMemoryCoord for a CRYSTAL at full stability.
Canonical crystal arc: CK-native structure (A11) at memory writeback
(B33), CRYSTAL persistence stage, STABILITY evaluation mode.
Args:
stability_score: current heat_score value for this crystal.
utility_score: current retrieval utility score (ignored here,
used by callers who need the UTILITY cell -- see
make_crystal_utility_coord).
promotion_state: DEMOTED if heat < 0.05, else STABLE.
Returns:
MetaMemoryCoord with routing_key 'A11::B33::C43'.
"""
return MetaMemoryCoord(
tag_2x2=Tag2x2(source_side="INTERNAL", semantic_side="STRUCTURE"),
tag_3x3=Tag3x3(temporal_role="OUTPUT", processing_layer="MEMORY"),
tag_4x4=Tag4x4(
persistence_stage="CRYSTAL",
evaluation_mode="STABILITY",
score_value=stability_score,
promotion_state=promotion_state,
),
)
# ============================================================
# SELF-TEST
# ============================================================
def _self_test() -> None:
"""
Minimal self-test: exercise every major class and function.
Raises AssertionError on any failure.
"""
import time
# --- Tag2x2 construction and cells ---
t = Tag2x2("INTERNAL", "STRUCTURE")
assert t.cell == "A11"
assert t.storable_shared is True
assert t.privacy_class == "SHARED"
t2 = Tag2x2("EXTERNAL", "CONTENT")
assert t2.cell == "A22"
assert t2.storable_shared is False
assert t2.privacy_class == "PRIVATE"
t3 = Tag2x2("EXTERNAL", "STRUCTURE")
assert t3.cell == "A21"
assert t3.storable_shared is True
t4 = Tag2x2("INTERNAL", "CONTENT")
assert t4.cell == "A12"
assert t4.storable_shared is True
# --- Tag3x3 derivations ---
b11 = Tag3x3("INPUT", "SIGNAL")
assert b11.cell == "B11"
assert b11.determinism_flag == "DETERMINISTIC"
assert b11.deepseek_permitted is False
assert b11.writes_durable is False
b22 = Tag3x3("TRANSFORM", "MODEL")
assert b22.cell == "B22"
assert b22.determinism_flag == "PROBABILISTIC"
assert b22.deepseek_permitted is True
assert b22.writes_durable is False
b33 = Tag3x3("OUTPUT", "MEMORY")
assert b33.cell == "B33"
assert b33.writes_durable is True
assert b33.deepseek_permitted is False
# --- Tag4x4 cells ---
c11 = Tag4x4("EPHEMERAL", "IDENTITY", 0.3, "STABLE")
assert c11.cell == "C11"
c43 = Tag4x4("CRYSTAL", "STABILITY", 0.9, "STABLE")
assert c43.cell == "C43"
c44 = Tag4x4("CRYSTAL", "UTILITY", 0.8, "STABLE")
assert c44.cell == "C44"
# --- MetaMemoryCoord routing_key and well-formedness ---
coord = MetaMemoryCoord(
tag_2x2=Tag2x2("EXTERNAL", "CONTENT"),
tag_3x3=Tag3x3("INPUT", "SIGNAL"),
tag_4x4=Tag4x4("EPHEMERAL", "IDENTITY", 0.1, "STABLE"),
)
assert coord.routing_key == "A22::B11::C11"
assert coord.is_well_formed() is True
# Constraint 1 violation: A22 at CRYSTAL
bad1 = MetaMemoryCoord(
tag_2x2=Tag2x2("EXTERNAL", "CONTENT"),
tag_3x3=Tag3x3("OUTPUT", "MEMORY"),
tag_4x4=Tag4x4("CRYSTAL", "STABILITY", 0.9, "STABLE"),
)
assert bad1.is_well_formed() is False
# Constraint 2 violation: INPUT row at ATOMIC
bad2 = MetaMemoryCoord(
tag_2x2=Tag2x2("EXTERNAL", "STRUCTURE"),
tag_3x3=Tag3x3("INPUT", "SIGNAL"),
tag_4x4=Tag4x4("ATOMIC", "IDENTITY", 0.5, "STABLE"),
)
assert bad2.is_well_formed() is False
# Constraint 2 (output side): OUTPUT at EPHEMERAL
bad3 = MetaMemoryCoord(
tag_2x2=Tag2x2("INTERNAL", "STRUCTURE"),
tag_3x3=Tag3x3("OUTPUT", "MEMORY"),
tag_4x4=Tag4x4("EPHEMERAL", "IDENTITY", 0.0, "STABLE"),
)
assert bad3.is_well_formed() is False
# Constraint 3 violation: A22 at TRANSFORM
bad4 = MetaMemoryCoord(
tag_2x2=Tag2x2("EXTERNAL", "CONTENT"),
tag_3x3=Tag3x3("TRANSFORM", "SIGNAL"),
tag_4x4=Tag4x4("EPHEMERAL", "IDENTITY", 0.0, "STABLE"),
)
assert bad4.is_well_formed() is False
# --- classify_event ---
raw_event = {"has_raw_content": True, "confidence": 0.4}
c = classify_event(raw_event)
assert c.routing_key == "A22::B11::C11"
assert c.is_well_formed() is True
assert c.tag_4x4.promotion_state == "STABLE" # no generators
eligible_event = {
"has_raw_content": False,
"confidence": 0.7,
"has_generators": True,
"is_duplicate": False,
}
c2 = classify_event(eligible_event)
assert c2.routing_key == "A21::B11::C11"
assert c2.tag_4x4.promotion_state == "ELIGIBLE"
# --- promotion_score ---
ps = promotion_score(confidence=0.9, recurrence_count=5, age_hours=0.0)
assert ps > 0.85, f"Expected promotion at conf=0.9, recur=5, age=0: got {ps}"
ps_old = promotion_score(confidence=0.9, recurrence_count=5, age_hours=100.0)
assert ps_old < ps, "Older path should score lower"
ps_zero = promotion_score(confidence=0.9, recurrence_count=0, age_hours=0.0)
assert ps_zero == 0.0, "Zero recurrence -> log1p(0)=0 -> score=0"
# --- heat_score ---
now = time.time()
hs_hot = heat_score(last_accessed=now - 60, access_count=20, now=now)
hs_cold = heat_score(last_accessed=now - 30 * 86400, access_count=1, now=now)
assert hs_hot > hs_cold, "Recent crystal should be hotter"
assert hs_cold < 0.05, f"Month-old, rarely-accessed crystal should be cold: {hs_cold}"
# --- Tier classification ---
ephemeral_raw = MetaMemoryCoord(
tag_2x2=Tag2x2("EXTERNAL", "CONTENT"),
tag_3x3=Tag3x3("INPUT", "SIGNAL"),
tag_4x4=Tag4x4("EPHEMERAL", "IDENTITY", 0.1, "STABLE"),
)
assert get_tier(ephemeral_raw) == Tier.REAL
atomic_semi = MetaMemoryCoord(
tag_2x2=Tag2x2("EXTERNAL", "STRUCTURE"),