cscs-constraint-engine 2026.10.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cscs/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """
2
+ CSCS Constraint Physics Engine: Zero-GPU Spectral Manifold & Contractive
3
+ Telemetry Middleware for Small Language Models (SLMs) (v2026.10.2)
4
+ Principal Investigator & Author: Lazaro M. Echenique-Diaz, Ph.D.
5
+ """
6
+
7
+ from .manifold import SpectralManifold
8
+ from .contraction import BanachContractionMirror
9
+ from .scout import RBFConstraintScout
10
+ from .compression import MDLCompressionRouter
11
+ from .verifier import DriftVerifier
12
+ from .codec import T3LBStateCodec
13
+ from .engine import CSCSMiddlewareEngine
14
+
15
+ __all__ = [
16
+ "SpectralManifold",
17
+ "BanachContractionMirror",
18
+ "RBFConstraintScout",
19
+ "MDLCompressionRouter",
20
+ "DriftVerifier",
21
+ "T3LBStateCodec",
22
+ "CSCSMiddlewareEngine"
23
+ ]
24
+ __version__ = "2026.10.2"
cscs/codec.py ADDED
@@ -0,0 +1,82 @@
1
+ """
2
+ T3LBStateCodec: 13-dimensional telemetry summary serializer for stateless SLM
3
+ context handoffs across edge devices (93 bytes per state seed, lossless
4
+ at 2-decimal fixed precision for the 13 summary scalars).
5
+ """
6
+
7
+ import math as m
8
+ import re
9
+ import numpy as np
10
+ from typing import Dict, Any
11
+
12
+
13
+ class T3LBStateCodec:
14
+ """
15
+ Computes and serializes all 13 Constraint Space Coordinate System (CSCS)
16
+ dimensions into a compact 93-byte T3LB telemetry seed string:
17
+ X (Gap/Novelty Tolerance), Y (Quality Relay Gain), Z (Manifold Persistence),
18
+ W (Constraint Density), P (Compression Efficiency), T (Window Horizon Saturation),
19
+ R (Reflexivity / Inverse Friction), S (Kernel Density Coupling), V (Veto Strength),
20
+ N (Contraction Convergence), E (Effective Rank Ratio),
21
+ B (Bleaching/Block Recovery), Q (State Coherence).
22
+ """
23
+
24
+ DIMENSIONS = ["X", "Y", "Z", "W", "P", "T", "R", "S", "V", "N", "E", "B", "Q"]
25
+
26
+ def __init__(self):
27
+ self.dims: Dict[str, float] = {
28
+ "X": 0.88, "Y": 1.25, "Z": 0.94, "W": 1.08,
29
+ "P": 0.87, "T": 0.79, "R": 0.74, "S": 0.92,
30
+ "V": 0.78, "N": 0.74, "E": 0.88, "B": 0.79, "Q": 0.65
31
+ }
32
+
33
+ def update_from_cycle(self, resonance: float, field_friction: float,
34
+ in_manifold: float, quality: float, blocked: bool,
35
+ compression_ratio: float = 0.85, kernel_density: float = 0.50,
36
+ effective_rank: float = 3.0, iterations: int = 4,
37
+ cycles: int = 1):
38
+ self.dims["T"] = round(min(1.50, 0.50 + 0.50 * min(1.0, cycles / 64.0)), 3)
39
+
40
+ if blocked:
41
+ self.dims["B"] = min(1.50, round(self.dims["B"] + 0.02, 3))
42
+ self.dims["V"] = min(1.20, round(self.dims["V"] + 0.03, 3))
43
+ self.dims["X"] = max(0.40, round(self.dims["X"] - 0.02, 3))
44
+ return
45
+
46
+ self.dims["X"] = round(0.60 + 0.40 * (1.0 - field_friction), 3)
47
+ self.dims["Y"] = round(0.75 + 0.50 * quality, 3)
48
+ self.dims["Z"] = round(0.75 + 0.24 * in_manifold, 3)
49
+ self.dims["W"] = round(0.80 + 0.40 * (0.5 * resonance + 0.5 * in_manifold), 3)
50
+ self.dims["P"] = round(0.50 + 0.50 * max(0.0, min(1.0, 1.0 - compression_ratio * 0.5)), 3)
51
+ self.dims["R"] = round(0.60 + 0.35 * (1.0 - field_friction), 3)
52
+ self.dims["S"] = round(0.50 + 0.50 * max(0.0, min(1.0, kernel_density)), 3)
53
+ self.dims["N"] = round(0.50 + 0.50 * max(0.0, 1.0 - (iterations / 10.0)), 3)
54
+ self.dims["E"] = round(0.50 + 0.50 * min(1.0, effective_rank / 8.0), 3)
55
+ self.dims["Q"] = round(0.50 + 0.45 * (quality * resonance), 3)
56
+
57
+ def magnitude(self) -> float:
58
+ vec = np.array([self.dims[k] for k in self.DIMENSIONS], dtype=np.float64)
59
+ return round(float(np.linalg.norm(vec) * m.sqrt(len(self.DIMENSIONS)) / 2.8), 2)
60
+
61
+ def encode_seed(self, version: str = "v2026.10") -> str:
62
+ mag = self.magnitude()
63
+ body = "".join(f"{k}{self.dims[k]:.2f}" for k in self.DIMENSIONS)
64
+ return f"T3LB:{version}|M{mag:.2f}|{body}|SecLock"
65
+
66
+ @classmethod
67
+ def decode_seed(cls, seed_str: str) -> Dict[str, Any]:
68
+ parts = seed_str.strip().split("|")
69
+ if len(parts) < 3 or not parts[0].startswith("T3LB:"):
70
+ raise ValueError("Invalid T3LB seed format")
71
+ version = parts[0].split(":", 1)[1]
72
+ mag = float(parts[1][1:])
73
+ matches = re.findall(r"([A-Z])(\d+\.\d+)", parts[2])
74
+ dims = {k: float(v) for k, v in matches}
75
+ return {"version": version, "magnitude": mag, "dimensions": dims}
76
+
77
+ def load_seed(self, seed_str: str) -> Dict[str, Any]:
78
+ parsed = self.decode_seed(seed_str)
79
+ for k, v in parsed["dimensions"].items():
80
+ if k in self.dims:
81
+ self.dims[k] = float(v)
82
+ return parsed
cscs/compression.py ADDED
@@ -0,0 +1,94 @@
1
+ """
2
+ MDLCompressionRouter: Information-Theoretic Minimum Description Length (MDL)
3
+ and delta redundancy telemetry for context-constrained edge models.
4
+ """
5
+
6
+ import hashlib as h
7
+ import zlib
8
+ import numpy as np
9
+ from collections import OrderedDict
10
+ from typing import Dict, List, Any
11
+ from .manifold import SpectralManifold
12
+ from .scout import INV_PHI
13
+
14
+
15
+ class MDLCompressionRouter:
16
+ """
17
+ Measures real byte-level Minimum Description Length (MDL) across:
18
+ 1. DEFLATE/LZ77 entropy coding of the state/prompt payload.
19
+ 2. Entangled Delta Coding against the nearest neighbor in memory.
20
+ 3. Spectral Coordinate Sparse Projection (structural summary).
21
+
22
+ Caches embedding vectors and compressed reference lengths in a bounded
23
+ registry (max 64 entries) for sub-0.2ms execution.
24
+ """
25
+
26
+ def __init__(self, manifold: SpectralManifold, max_registry: int = 64):
27
+ self.manifold = manifold
28
+ self.max_registry = max_registry
29
+ self.archive: OrderedDict[str, bytes] = OrderedDict()
30
+ self.raw_registry: OrderedDict[str, bytes] = OrderedDict()
31
+ self.vector_registry: OrderedDict[str, np.ndarray] = OrderedDict()
32
+
33
+ def compress(self, text: str, coords: List[float], mutate: bool = True) -> Dict[str, Any]:
34
+ raw_bytes = text.encode("utf-8")
35
+ raw_len = max(1, len(raw_bytes))
36
+ key = h.blake2b(raw_bytes, digest_size=6).hexdigest()
37
+
38
+ zlib_bytes = zlib.compress(raw_bytes, level=1)
39
+ lz_ratio = len(zlib_bytes) / raw_len
40
+
41
+ v = self.manifold.embed(text)
42
+ best_sim = 0.0
43
+ best_key = None
44
+
45
+ for k, pv in self.vector_registry.items():
46
+ sim = float(np.dot(v, pv))
47
+ if sim > best_sim:
48
+ best_sim = sim
49
+ best_key = k
50
+
51
+ if best_sim > INV_PHI and best_key is not None:
52
+ ref_bytes = self.raw_registry[best_key]
53
+ ref_compressed_len = len(self.archive[best_key])
54
+ joint_compressed = len(zlib.compress(ref_bytes + b"||" + raw_bytes, level=1))
55
+ marginal_bytes = max(4, joint_compressed - ref_compressed_len)
56
+ delta_ratio = marginal_bytes / raw_len
57
+ else:
58
+ delta_ratio = 1.0
59
+
60
+ if coords:
61
+ active = sum(1 for c in coords if abs(c) > 0.05)
62
+ spectral_ratio = (active * 4) / raw_len
63
+ else:
64
+ spectral_ratio = 1.0
65
+
66
+ if mutate:
67
+ self.archive[key] = zlib_bytes
68
+ self.raw_registry[key] = raw_bytes
69
+ self.vector_registry[key] = v
70
+ if len(self.vector_registry) > self.max_registry:
71
+ self.archive.popitem(last=False)
72
+ self.raw_registry.popitem(last=False)
73
+ self.vector_registry.popitem(last=False)
74
+
75
+ candidates = [
76
+ ("lz77_entropy", lz_ratio),
77
+ ("entangled_delta", delta_ratio),
78
+ ("spectral_sparse", spectral_ratio)
79
+ ]
80
+ best_method, best_ratio = min(candidates, key=lambda x: x[1])
81
+
82
+ return {
83
+ "key": key,
84
+ "best_method": best_method,
85
+ "best_ratio": round(float(best_ratio), 4),
86
+ "raw_bytes": raw_len,
87
+ "lz77_bytes": len(zlib_bytes),
88
+ "nearest_entanglement_sim": round(best_sim, 4),
89
+ "ratios": {
90
+ "lz77_entropy": round(float(lz_ratio), 4),
91
+ "entangled_delta": round(float(delta_ratio), 4),
92
+ "spectral_sparse": round(float(spectral_ratio), 4)
93
+ }
94
+ }
cscs/contraction.py ADDED
@@ -0,0 +1,137 @@
1
+ """
2
+ BanachContractionMirror: Models context alignment as an iterated contraction
3
+ mapping on the unit hypersphere S^{F-1} to stabilize Small Language Model (SLM)
4
+ multi-turn attention drift without consuming context window tokens.
5
+ """
6
+
7
+ import math as m
8
+ import re
9
+ import numpy as np
10
+ from collections import deque
11
+ from typing import Dict, List, Any
12
+ from .manifold import SpectralManifold, EPS
13
+
14
+ PHI = (1.0 + m.sqrt(5.0)) / 2.0
15
+ _WORD_RE = re.compile(r"[a-z0-9_]+")
16
+
17
+
18
+ class BanachContractionMirror:
19
+ """
20
+ Given prompt embedding x_0 and context attractors C, applies the operator:
21
+ x_{t+1} = normalize((1 - L_t) * x_t + L_t * A(x_t, C))
22
+ where A(x_t, C) is the Boltzmann barycenter of memory vectors and
23
+ L_t = Φ^{-t} guarantees contraction (Lipschitz < 1 for t >= 1).
24
+ """
25
+
26
+ def __init__(self, manifold: SpectralManifold, temp: float = 0.15, max_memory: int = 32):
27
+ self.manifold = manifold
28
+ self.temp = temp
29
+ self.anchors: List[np.ndarray] = []
30
+ self.max_anchors: int = 12
31
+ self.memory_vectors: deque = deque(maxlen=max_memory)
32
+
33
+ def add_anchor(self, vec: np.ndarray):
34
+ if len(self.anchors) < self.max_anchors:
35
+ if not any(float(np.dot(vec, a)) > 1.0 - 1e-9 for a in self.anchors):
36
+ self.anchors.append(vec)
37
+ if not any(float(np.dot(vec, m_v)) > 1.0 - 1e-9 for m_v in self.memory_vectors):
38
+ self.memory_vectors.append(vec)
39
+
40
+ def _active_attractors(self, anchors_only: bool = False) -> np.ndarray:
41
+ if anchors_only and self.anchors:
42
+ return np.array(self.anchors, dtype=np.float64)
43
+ pool = list(self.anchors)
44
+ for m_v in self.memory_vectors:
45
+ if not any(float(np.dot(m_v, a)) > 1.0 - 1e-9 for a in pool):
46
+ pool.append(m_v)
47
+ return np.array(pool, dtype=np.float64) if pool else np.empty((0, self.manifold.n_features))
48
+
49
+ def reflect(self, prompt: str, max_iter: int = 8, tol: float = 1e-4,
50
+ mutate: bool = True, anchors_only: bool = False) -> Dict[str, Any]:
51
+ x0 = self.manifold.embed(prompt)
52
+ C = self._active_attractors(anchors_only=anchors_only)
53
+ if C.shape[0] == 0:
54
+ if mutate:
55
+ self.memory_vectors.append(x0)
56
+ return {
57
+ "iterations": 0,
58
+ "resonance": 1.0,
59
+ "lyapunov_exponent": 0.0,
60
+ "contraction_displacement": 0.0,
61
+ "converged": True
62
+ }
63
+
64
+ xt = x0.copy()
65
+ displacements = []
66
+
67
+ for t in range(1, max_iter + 1):
68
+ sims = C @ xt
69
+ weights = np.exp((sims - float(np.max(sims))) / self.temp)
70
+ weights /= (float(np.sum(weights)) + EPS)
71
+ attractor = weights @ C
72
+ attr_norm = float(np.sqrt(np.dot(attractor, attractor)))
73
+ if attr_norm > EPS:
74
+ attractor /= attr_norm
75
+
76
+ lip = PHI ** (-t)
77
+ x_next = (1.0 - lip) * xt + lip * attractor
78
+ x_next_norm = float(np.sqrt(np.dot(x_next, x_next)))
79
+ if x_next_norm > EPS:
80
+ x_next /= x_next_norm
81
+
82
+ diff = x_next - xt
83
+ step_dist = float(np.sqrt(np.dot(diff, diff)))
84
+ displacements.append(step_dist)
85
+ xt = x_next
86
+ if step_dist < tol:
87
+ break
88
+
89
+ if self.anchors:
90
+ A_mat = np.array(self.anchors, dtype=np.float64)
91
+ a_sims = A_mat @ x0
92
+ max_direct_sim = float(np.max(a_sims))
93
+ a_w = np.exp((a_sims - max_direct_sim) / self.temp)
94
+ a_w /= (float(np.sum(a_w)) + EPS)
95
+ a_attr = a_w @ A_mat
96
+ a_norm = float(np.sqrt(np.dot(a_attr, a_attr)))
97
+ if a_norm > EPS:
98
+ a_attr /= a_norm
99
+ lip1 = 1.0 / PHI
100
+ x_a = (1.0 - lip1) * x0 + lip1 * a_attr
101
+ xa_norm = float(np.sqrt(np.dot(x_a, x_a)))
102
+ if xa_norm > EPS:
103
+ x_a /= xa_norm
104
+ fp_sim = 0.70 * float(np.dot(x0, x_a)) + 0.30 * float(np.dot(x0, xt))
105
+ else:
106
+ max_direct_sim = float(np.max(C @ x0))
107
+ fp_sim = float(np.dot(x0, xt))
108
+
109
+ # Length-asymmetry containment adjustment for terse queries (2 <= n_words <= 7)
110
+ n_words = len(_WORD_RE.findall(prompt.lower()))
111
+ if 2 <= n_words <= 7 and max_direct_sim >= 0.06:
112
+ scale = m.sqrt(min(2.2, 9.0 / max(2, n_words)))
113
+ max_direct_sim = min(1.0, max_direct_sim * scale)
114
+
115
+ resonance = max(0.0, min(1.0, 0.5 * max_direct_sim + 0.5 * fp_sim))
116
+ tot_diff = xt - x0
117
+ total_disp = float(np.sqrt(np.dot(tot_diff, tot_diff)))
118
+
119
+ if mutate:
120
+ self.memory_vectors.append(x0)
121
+
122
+ if len(displacements) >= 2 and displacements[0] > EPS:
123
+ ratios = [
124
+ m.log((displacements[i] + EPS) / (displacements[i - 1] + EPS))
125
+ for i in range(1, len(displacements))
126
+ ]
127
+ lyapunov = float(np.mean(ratios))
128
+ else:
129
+ lyapunov = -m.log(PHI)
130
+
131
+ return {
132
+ "iterations": len(displacements),
133
+ "resonance": round(resonance, 4),
134
+ "lyapunov_exponent": round(lyapunov, 4),
135
+ "contraction_displacement": round(total_disp, 4),
136
+ "converged": displacements[-1] < tol if displacements else True
137
+ }
cscs/engine.py ADDED
@@ -0,0 +1,331 @@
1
+ """
2
+ CSCSMiddlewareEngine: Stage-1 Trajectory Drift & Lexical-Manifold Governor
3
+ for hardware-constrained Small Language Models (SLMs).
4
+ """
5
+
6
+ import re
7
+ import time as tm
8
+ import numpy as np
9
+ from typing import Dict, List, Any, Optional, Callable
10
+ from .manifold import SpectralManifold, EPS
11
+ from .contraction import BanachContractionMirror, PHI
12
+ from .scout import RBFConstraintScout, INV_PHI
13
+ from .compression import MDLCompressionRouter
14
+ from .verifier import DriftVerifier
15
+ from .codec import T3LBStateCodec
16
+
17
+ _GLUE_WORDS = {
18
+ "the", "of", "in", "to", "a", "an", "for", "on", "with", "by", "from", "at",
19
+ "as", "across", "after", "under", "between", "how", "what", "which", "why",
20
+ "when", "where", "who", "whom", "whose", "is", "are", "was", "were", "be",
21
+ "been", "being", "have", "has", "had", "do", "does", "did", "can", "could",
22
+ "would", "should", "may", "might", "will", "shall", "must", "that", "this",
23
+ "these", "those", "its", "their", "our", "your", "my", "his", "her", "or",
24
+ "and", "but", "if", "while", "into", "about", "through", "over", "before",
25
+ "during", "near", "using", "like", "than", "then", "so", "not", "no", "nor",
26
+ "both", "each", "every", "any", "some", "all", "most", "more", "less", "few",
27
+ "many", "such", "own", "same", "other", "another"
28
+ }
29
+
30
+ _DIRECTIVE_VERBS = {
31
+ "what", "how", "why", "when", "where", "which", "who", "explain", "define",
32
+ "summarize", "describe", "list", "show", "compare", "analyze", "evaluate",
33
+ "model", "calculate", "compute", "outline", "fix", "check", "run", "test",
34
+ "give", "assess", "quantify", "design", "track", "integrate", "estimate",
35
+ "formulate", "verify", "audit", "simulate", "measure", "calibrate", "map",
36
+ "brainstorm", "imagine", "drop", "git", "sudo", "find", "trace", "debug",
37
+ "plot", "derive", "prove", "solve", "classify", "predict", "identify"
38
+ }
39
+
40
+ _DETERMINERS_PREPS = {
41
+ "the", "a", "an", "of", "in", "to", "for", "with", "by", "from", "at",
42
+ "across", "after", "under", "between", "into", "during", "near", "through"
43
+ }
44
+ _AUX_VERBS = {
45
+ "is", "are", "was", "were", "be", "been", "have", "has", "had",
46
+ "do", "does", "did", "can", "could", "would", "should"
47
+ }
48
+ _VALID_FUNC_PAIRS = {
49
+ ("to", "the"), ("from", "the"), ("in", "the"), ("of", "the"), ("on", "the"),
50
+ ("at", "the"), ("for", "the"), ("with", "the"), ("by", "the"), ("across", "the"),
51
+ ("after", "the"), ("under", "the"), ("between", "the"), ("into", "the"),
52
+ ("during", "the"), ("near", "the"), ("through", "the"),
53
+ ("of", "a"), ("in", "a"), ("to", "a"), ("for", "a"), ("with", "a"), ("as", "a"),
54
+ ("of", "an"), ("in", "an"), ("to", "an"), ("for", "an"), ("with", "an"), ("as", "an"),
55
+ ("to", "be"), ("to", "have"), ("to", "do")
56
+ }
57
+
58
+
59
+ class CSCSMiddlewareEngine:
60
+ """
61
+ Zero-GPU Stage-1 Trajectory Drift & Lexical-Manifold Governor for SLMs.
62
+ Operates in two mathematically linked policy states (Q2 Hybridization):
63
+ - 'adaptive' (D2 baseline): active when < 4 anchor vectors exist; uses 1/Φ
64
+ wall with a cycles >= 3 warm-up grace window.
65
+ - 'calibrated' (graduated strict): triggers automatically once >= 4 anchor
66
+ vectors are enrolled (or accumulated); calibrates the wall to the empirical
67
+ leave-one-out seed friction quantile τ_95, enforces the wall from Cycle 1,
68
+ and bounds subsequent manifold updates under an anchor-drift budget.
69
+ """
70
+
71
+ def __init__(self, n_features: int = 512, max_components: int = 12,
72
+ allow_dreaming: bool = True,
73
+ on_graduation: Optional[Callable[[Dict[str, Any]], bool]] = None):
74
+ self.manifold = SpectralManifold(n_features=n_features, max_components=max_components)
75
+ self.mirror = BanachContractionMirror(self.manifold)
76
+ self.scout = RBFConstraintScout()
77
+ self.compression = MDLCompressionRouter(self.manifold)
78
+ self.verifier = DriftVerifier(self.manifold)
79
+ self.codec = T3LBStateCodec()
80
+ self.allow_dreaming = allow_dreaming
81
+ self.on_graduation = on_graduation
82
+ self.policy_state: str = "adaptive"
83
+ self.cycles = 0
84
+
85
+ _orig_learn = self.manifold.learn
86
+ def _synced_learn(prompt: str, as_anchor: bool = False):
87
+ is_pre_session = (self.cycles == 0) or as_anchor
88
+ _orig_learn(prompt, as_anchor=is_pre_session)
89
+ if is_pre_session:
90
+ v = self.manifold.embed(prompt)
91
+ self.mirror.add_anchor(v)
92
+ self._check_graduation()
93
+ self.manifold.learn = _synced_learn
94
+
95
+ def enroll(self, seed_prompts: List[str]):
96
+ """Explicitly enroll a domain seed corpus as pinned anchors."""
97
+ for p in seed_prompts:
98
+ self.manifold.learn(p, as_anchor=True)
99
+
100
+ def _check_graduation(self):
101
+ """
102
+ Compute leave-one-out empirical friction quantile τ_95 once >= 4 anchors
103
+ are present and transition from 'adaptive' (D2) to 'calibrated' state.
104
+ """
105
+ if self.policy_state == "calibrated" or len(self.manifold.anchors) < 4:
106
+ return
107
+ anchors = self.manifold.anchors
108
+ n_a = len(anchors)
109
+ loo_frics = []
110
+ for i in range(n_a):
111
+ others = [anchors[j] for j in range(n_a) if j != i]
112
+ X_loo = np.array(others, dtype=np.float64)
113
+ mean_loo = np.mean(X_loo, axis=0)
114
+ Xc_loo = X_loo - mean_loo
115
+ G_loo = 0.5 * ((Xc_loo @ Xc_loo.T) + (Xc_loo @ Xc_loo.T).T)
116
+ eigvals, U = np.linalg.eigh(G_loo)
117
+ idx = np.argsort(eigvals)[::-1]
118
+ eigvals = np.maximum(eigvals[idx], 0.0)
119
+ U = U[:, idx]
120
+ tr = float(np.sum(eigvals))
121
+ valid = eigvals >= (1e-12 * tr)
122
+ k = max(1, int(np.sum(valid)))
123
+ Sk = np.sqrt(eigvals[:k])
124
+ Vt_k = (U[:, :k].T / (Sk[:, None] + EPS)) @ Xc_loo
125
+ Vt_k /= (np.linalg.norm(Vt_k, axis=1, keepdims=True) + EPS)
126
+
127
+ vc = anchors[i] - mean_loo
128
+ coords = Vt_k @ vc
129
+ diff = vc - (coords @ Vt_k)
130
+ rec_err = float(np.linalg.norm(diff) / (np.linalg.norm(vc) + EPS))
131
+
132
+ xt = anchors[i].copy()
133
+ for t in range(1, 9):
134
+ sims = X_loo @ xt
135
+ w = np.exp((sims - float(np.max(sims))) / self.mirror.temp)
136
+ w /= (float(np.sum(w)) + EPS)
137
+ attr = w @ X_loo
138
+ attr /= (float(np.linalg.norm(attr)) + EPS)
139
+ lip = PHI ** (-t)
140
+ xt = (1.0 - lip) * xt + lip * attr
141
+ xt /= (float(np.linalg.norm(xt)) + EPS)
142
+ reson = 0.5 * float(np.max(X_loo @ anchors[i])) + 0.5 * float(np.dot(anchors[i], xt))
143
+ ood_p = min(1.0, max(0.0, (rec_err - 0.30) / 0.70)) # same transform as RBFConstraintScout (CPh harmonization, 2026-11-06)
144
+ lf = min(1.0, 0.45 * ood_p + 0.25 * (1.0 - reson))
145
+ loo_frics.append(lf)
146
+
147
+ tau_95 = float(np.percentile(loo_frics, 95))
148
+ candidate_state = {
149
+ "event": "graduation_ready",
150
+ "n_anchors": n_a,
151
+ "tau_95": round(tau_95, 4),
152
+ "loo_frictions": [round(f, 4) for f in loo_frics]
153
+ }
154
+ if self.on_graduation is not None:
155
+ approved = bool(self.on_graduation(candidate_state))
156
+ if not approved:
157
+ return
158
+ self.scout.set_calibrated_threshold(tau_95)
159
+ self.policy_state = "calibrated"
160
+
161
+ def evaluate_prompt_quality(self, prompt: str) -> float:
162
+ clean_str = prompt.strip()
163
+ raw_tokens = clean_str.split()
164
+ if len(raw_tokens) < 2:
165
+ return 0.20
166
+
167
+ words = re.findall(r"[a-z0-9_]+", clean_str.lower())
168
+ n_words = len(words)
169
+ if n_words < 2:
170
+ return 0.20
171
+
172
+ content_words = [w for w in words if w not in _GLUE_WORDS]
173
+ raw_uniq = len(set(words)) / n_words
174
+ if raw_uniq < 0.60 and n_words >= 6:
175
+ return round(0.35 * raw_uniq, 4)
176
+ content_uniq = (len(set(content_words)) / len(content_words)) if content_words else raw_uniq
177
+ unique_ratio = max(raw_uniq, content_uniq)
178
+
179
+ alpha_words = [w for w in words if w.isalpha() and len(w) >= 3]
180
+ if alpha_words:
181
+ voweled = sum(1 for w in alpha_words if any(v in w for v in "aeiouy"))
182
+ vowel_ratio = voweled / len(alpha_words)
183
+ if vowel_ratio < 0.60:
184
+ return round(0.20 * vowel_ratio, 4)
185
+
186
+ has_punct = 0.10 if any(ch in clean_str for ch in ".?!,;:") else 0.0
187
+ is_terse_structured = (
188
+ 2 <= n_words <= 7 and (
189
+ words[0] in _DIRECTIVE_VERBS or
190
+ clean_str.endswith(("?", ".", "!")) or
191
+ any(any(c.isdigit() or c in "-_/" for c in tok) for tok in raw_tokens)
192
+ )
193
+ )
194
+
195
+ glue_count = sum(1 for w in words if w in _GLUE_WORDS)
196
+ glue_ratio = glue_count / n_words
197
+ if n_words >= 6 and glue_ratio < 0.08:
198
+ return round(0.22 + 0.50 * glue_ratio, 4)
199
+
200
+ violations = 0
201
+ if words[-1] in _DETERMINERS_PREPS or words[-1] in _AUX_VERBS or words[-1] in {"how", "what", "which", "why", "who", "and", "or", "but", "if"}:
202
+ violations += 1
203
+ for i in range(n_words - 1):
204
+ w1, w2 = words[i], words[i + 1]
205
+ if (w1 in _DETERMINERS_PREPS and w2 in _DETERMINERS_PREPS) and (w1, w2) not in _VALID_FUNC_PAIRS:
206
+ violations += 1
207
+ if w1 in _DETERMINERS_PREPS and w2 in _AUX_VERBS and (w1, w2) not in _VALID_FUNC_PAIRS:
208
+ violations += 1
209
+ if w1 in {"a", "an", "the"} and w2 in {"is", "are", "was", "were", "do", "does", "did", "can", "could", "would", "should", "to", "of", "in", "for", "with", "by", "from", "at"}:
210
+ violations += 1
211
+
212
+ for i in range(1, len(raw_tokens)):
213
+ prev_clean = re.sub(r"[^a-zA-Z]", "", raw_tokens[i - 1])
214
+ curr_clean = re.sub(r"[^a-zA-Z]", "", raw_tokens[i])
215
+ if prev_clean.islower() and curr_clean and curr_clean[0].isupper() and curr_clean.lower() in _DIRECTIVE_VERBS:
216
+ violations += 1
217
+
218
+ if is_terse_structured:
219
+ len_score = min(1.0, n_words / 2.0)
220
+ base_q = 0.55 * unique_ratio + 0.35 * len_score + max(has_punct, 0.10)
221
+ else:
222
+ len_score = min(1.0, n_words / 12.0) if n_words <= 150 else 0.65
223
+ base_q = 0.50 * unique_ratio + 0.40 * len_score + has_punct
224
+
225
+ syntax_penalty = 0.22 * violations
226
+ return round(max(0.05, min(1.0, base_q - syntax_penalty)), 4)
227
+
228
+ def load_seed(self, seed_str: str) -> Dict[str, Any]:
229
+ """Restore T3LB codec dimensions from a serialized 93-byte seed string."""
230
+ return self.codec.load_seed(seed_str)
231
+
232
+ def pre_inference(self, prompt: str, dreaming: bool = False,
233
+ learn_manifold: bool = True) -> Dict[str, Any]:
234
+ t0 = tm.perf_counter()
235
+ self.cycles += 1
236
+ effective_dreaming = bool(dreaming and self.allow_dreaming)
237
+
238
+ quality = self.evaluate_prompt_quality(prompt)
239
+ proj = self.manifold.project(prompt)
240
+ ref = self.mirror.reflect(prompt, mutate=False)
241
+ sc = self.scout.scout(
242
+ proj["coords"],
243
+ quality_score=quality,
244
+ rec_error=proj["reconstruction_error"],
245
+ resonance=ref["resonance"],
246
+ mutate=False
247
+ )
248
+
249
+ wall_enforced = (self.policy_state == "calibrated") or (self.cycles >= 3)
250
+ blocked = (quality < 0.30) or (sc["wall_detected"] and not effective_dreaming and wall_enforced)
251
+
252
+ if not blocked:
253
+ # Two-zone commit budget (CPh fix, 2026-11-06): in the calibrated state,
254
+ # state of ANY module (mirror, scout, compression, manifold) is committed
255
+ # only when the prompt sits in the core attractor zone, judged against the
256
+ # pinned anchors alone (anchor local_friction <= 1/Φ). Prompts in the
257
+ # tolerated boundary zone (1/Φ < F <= τ_95) execute but mutate nothing,
258
+ # so long sessions cannot drift the judging state into admitting far-OOD.
259
+ if self.policy_state == "calibrated" and self.manifold.anchors:
260
+ anchor_ref = self.mirror.reflect(prompt, mutate=False, anchors_only=True)
261
+ anchor_sc = self.scout.scout(
262
+ proj["coords"],
263
+ quality_score=quality,
264
+ rec_error=proj["reconstruction_error"],
265
+ resonance=anchor_ref["resonance"],
266
+ mutate=False
267
+ )
268
+ in_core_zone = anchor_sc["local_friction"] <= INV_PHI
269
+ else:
270
+ in_core_zone = True
271
+
272
+ if in_core_zone:
273
+ self.mirror.memory_vectors.append(self.manifold.embed(prompt))
274
+ if proj["coords"]:
275
+ self.scout.nodes.append((np.array(proj["coords"], dtype=np.float64), sc["local_friction"]))
276
+ cmp = self.compression.compress(prompt, proj["coords"], mutate=True)
277
+ else:
278
+ cmp = self.compression.compress(prompt, proj["coords"], mutate=False)
279
+
280
+ if learn_manifold and not effective_dreaming:
281
+ if self.policy_state == "calibrated" and self.manifold.anchors:
282
+ if in_core_zone:
283
+ self.manifold.learn(prompt, as_anchor=False)
284
+ else:
285
+ self.manifold.learn(prompt, as_anchor=(len(self.manifold.anchors) < 4 and quality >= 0.70))
286
+ if len(self.manifold.anchors) <= 4 and quality >= 0.70:
287
+ self.mirror.add_anchor(self.manifold.embed(prompt))
288
+ self._check_graduation()
289
+ else:
290
+ cmp = self.compression.compress(prompt, proj["coords"], mutate=False)
291
+
292
+ self.codec.update_from_cycle(
293
+ resonance=ref["resonance"],
294
+ field_friction=sc["field_friction"],
295
+ in_manifold=proj["in_manifold_energy"],
296
+ quality=quality,
297
+ blocked=blocked,
298
+ compression_ratio=cmp["best_ratio"],
299
+ kernel_density=sc["kernel_density"],
300
+ effective_rank=proj["effective_rank"],
301
+ iterations=ref["iterations"],
302
+ cycles=self.cycles
303
+ )
304
+
305
+ seed_str = self.codec.encode_seed()
306
+ latency_ms = round((tm.perf_counter() - t0) * 1000.0, 3)
307
+
308
+ return {
309
+ "cycle": self.cycles,
310
+ "policy_state": self.policy_state,
311
+ "allowed": not blocked,
312
+ "dreaming": effective_dreaming,
313
+ "quality_score": quality,
314
+ "manifold": proj,
315
+ "contraction": ref,
316
+ "friction": sc,
317
+ "compression": cmp,
318
+ "t3lb_seed": seed_str,
319
+ "latency_ms": latency_ms
320
+ }
321
+
322
+ def post_inference(self, prompt: str, slm_output: str, pre_report: Dict[str, Any]) -> Dict[str, Any]:
323
+ t0 = tm.perf_counter()
324
+ verdict = self.verifier.verify(
325
+ prompt=prompt,
326
+ output=slm_output,
327
+ dreaming=pre_report.get("dreaming", False),
328
+ resonance=pre_report.get("contraction", {}).get("resonance", 0.5)
329
+ )
330
+ verdict["latency_ms"] = round((tm.perf_counter() - t0) * 1000.0, 3)
331
+ return verdict