File size: 12,356 Bytes
f7c4865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import numpy as np
from dataclasses import dataclass
from typing import Dict, List, Any
import re

# =========================
# PHYSICS ENGINE (DEFRAG v2)
# =========================

@dataclass
class VectorState:
    """
    Represents the user's dynamic state in 3D space.
    Ranges: -10.0 (Collapse) to +10.0 (Sovereign)
    
    Axes:
    - X (Resilience): Root/Solar Plexus/Sacral → Vitality/Stress capacity
    - Y (Autonomy): Heart/G-Center → Identity/Will/Self-direction
    - Z (Connectivity): Throat/Ajna → Expression/Social integration
    """
    resilience: float
    autonomy: float
    connectivity: float

    def to_array(self) -> np.ndarray:
        return np.array([self.resilience, self.autonomy, self.connectivity])

    @staticmethod
    def from_array(arr: np.ndarray) -> "VectorState":
        return VectorState(
            resilience=float(arr[0]),
            autonomy=float(arr[1]),
            connectivity=float(arr[2]),
        )

    def magnitude(self) -> float:
        return float(np.linalg.norm(self.to_array()))

    def distance_from_baseline(self, baseline: "VectorState") -> float:
        diff = self.to_array() - baseline.to_array()
        return float(np.linalg.norm(diff))


@dataclass
class PhysicsConstants:
    """
    Physics properties derived from Human Design blueprint.
    These govern how a specific user reacts to stress.
    """
    mass: float                      # Resistance to change (1-10)
    permeability: float              # Environmental sensitivity (0-1.5)
    elasticity_vector: np.ndarray    # Dimensional recovery rates [X, Y, Z]
    coupling_matrix: np.ndarray      # 3×3 interaction matrix


class BlueprintPhysics:
    """
    Converts Human Design blueprint into physics constants.
    Pure mathematical derivation. No randomness.
    """
    PROFILE_MASS_TABLE: Dict[str, float] = {
        "1": 9.0,
        "2": 8.0,
        "3": 7.0,
        "4": 4.0,
        "5": 3.0,
        "6": 2.0,
    }

    AUTHORITY_ELASTICITY: Dict[str, float] = {
        "Emotional": 0.3,
        "Lunar": 0.2,
        "Self-Projected": 0.5,
        "Environmental": 0.5,
        "Ego": 0.6,
        "Sacral": 0.8,
        "Splenic": 0.95,
    }

    @staticmethod
    def derive(blueprint: Dict) -> PhysicsConstants:
        mass = BlueprintPhysics._calculate_mass(blueprint.get("profile", "3/5"))
        elasticity_vector = BlueprintPhysics._calculate_elasticity(
            blueprint.get("authority", "Emotional"),
            blueprint.get("open_centers", []),
            blueprint.get("defined_centers", []),
        )
        coupling_matrix = BlueprintPhysics._build_coupling_matrix(
            blueprint.get("open_centers", []),
            blueprint.get("defined_centers", []),
        )
        permeability = len(blueprint.get("open_centers", [])) * 0.15

        return PhysicsConstants(
            mass=mass,
            permeability=permeability,
            elasticity_vector=elasticity_vector,
            coupling_matrix=coupling_matrix,
        )

    @staticmethod
    def _calculate_mass(profile: str) -> float:
        try:
            p_line, d_line = profile.split("/")
            p_mass = BlueprintPhysics.PROFILE_MASS_TABLE.get(p_line, 5.0)
            d_mass = BlueprintPhysics.PROFILE_MASS_TABLE.get(d_line, 5.0)
            return (p_mass + d_mass) / 2.0
        except Exception:
            return 5.0

    @staticmethod
    def _calculate_elasticity(
        authority: str,
        open_centers: List[str],
        defined_centers: List[str],
    ) -> np.ndarray:
        base = BlueprintPhysics.AUTHORITY_ELASTICITY.get(authority, 0.5)
        elasticity = np.array([base, base, base])

        if "SACRAL" in open_centers:
            elasticity[0] *= 0.5
        if "ROOT" in open_centers:
            elasticity[0] *= 0.7
        if "SOLAR_PLEXUS" in open_centers:
            elasticity[0] *= 0.75
        if "SACRAL" in defined_centers:
            elasticity[0] *= 1.3
        if "ROOT" in defined_centers:
            elasticity[0] *= 1.2

        if "HEART" in open_centers:
            elasticity[1] *= 0.6
        if "G_CENTER" in open_centers:
            elasticity[1] *= 0.7
        if "HEART" in defined_centers:
            elasticity[1] *= 1.4
        if "G_CENTER" in defined_centers:
            elasticity[1] *= 1.3

        if "THROAT" in open_centers:
            elasticity[2] *= 0.7
        if "AJNA" in open_centers:
            elasticity[2] *= 0.8
        if "THROAT" in defined_centers:
            elasticity[2] *= 1.2
        if "AJNA" in defined_centers:
            elasticity[2] *= 1.15

        elasticity = np.clip(elasticity, 0.1, 2.0)
        return elasticity

    @staticmethod
    def _build_coupling_matrix(
        open_centers: List[str],
        defined_centers: List[str],
    ) -> np.ndarray:
        m = np.eye(3, dtype=float)

        if "HEAD" in open_centers:
            m[0, 2] += 0.25
        if "AJNA" in open_centers:
            m[1, 2] += 0.3
        if "THROAT" in open_centers:
            m[2, 1] += 0.4
        if "G_CENTER" in open_centers:
            m[1, 2] += 0.6
        if "HEART" in open_centers:
            m[1, 2] += 0.5
            m[1, 0] += 0.3
            m[0, 2] += 0.2
        if "SOLAR_PLEXUS" in open_centers:
            m[0, 2] += 0.4
        if "SACRAL" in open_centers:
            m[0, 1] += 0.3
        if "SPLEEN" in open_centers:
            m[0, 2] += 0.35
        if "ROOT" in open_centers:
            m[0, 2] += 0.3
            m[1, 2] += 0.2

        if "SOLAR_PLEXUS" in defined_centers:
            m[0, 2] = max(1.0, m[0, 2] - 0.2)
        if "HEART" in defined_centers:
            m[1, 2] = max(1.0, m[1, 2] - 0.3)
        if "G_CENTER" in defined_centers:
            m[1, 2] = max(1.0, m[1, 2] - 0.25)

        return m


class PhysicsSolver:
    @staticmethod
    def calculate_impact(
        current_state: VectorState,
        stress_vector: VectorState,
        physics: PhysicsConstants,
    ) -> VectorState:
        curr_vec = current_state.to_array()
        stress_vec = stress_vector.to_array()

        amplified_force = stress_vec * (1.0 + physics.permeability)
        acceleration = amplified_force / physics.mass
        coupled_acceleration = np.dot(physics.coupling_matrix, acceleration)
        recovery_force = curr_vec * physics.elasticity_vector * 0.1
        new_vec = curr_vec + coupled_acceleration + recovery_force
        new_vec = np.clip(new_vec, -10.0, 10.0)
        return VectorState.from_array(new_vec)

    @staticmethod
    def predict_recovery_time(
        current_state: VectorState,
        baseline_state: VectorState,
        physics: PhysicsConstants,
        tolerance: float = 0.5,
    ) -> int:
        distance = current_state.distance_from_baseline(baseline_state)
        avg_elasticity = float(np.mean(physics.elasticity_vector))
        time_constant = physics.mass / max(avg_elasticity, 0.1)
        if distance < tolerance:
            return 0
        recovery_time = -time_constant * np.log(tolerance / distance)
        return int(max(recovery_time, 0))


# =========================
# STRESS MAPPER
# =========================

@dataclass(frozen=True)
class AxisWeights:
    resilience: float
    autonomy: float
    connectivity: float


class StressMapper:
    MIN_SEVERITY = 1
    MAX_SEVERITY = 10
    MIN_FORCE = 0.5
    MAX_FORCE = 6.0

    CATEGORY_WEIGHTS: Dict[str, AxisWeights] = {
        "burnout": AxisWeights(-1.0, -0.4, -0.1),
        "overwork": AxisWeights(-0.9, -0.3, -0.1),
        "fatigue": AxisWeights(-0.8, -0.2, -0.1),
        "exhaustion": AxisWeights(-1.0, -0.3, -0.2),

        "rejection": AxisWeights(-0.3, -1.0, -0.6),
        "abandon": AxisWeights(-0.2, -1.0, -0.6),
        "shame": AxisWeights(-0.2, -0.9, -0.5),
        "failure": AxisWeights(-0.3, -0.8, -0.4),
        "criticized": AxisWeights(-0.2, -0.8, -0.5),

        "conflict": AxisWeights(-0.2, -0.5, -0.9),
        "argument": AxisWeights(-0.1, -0.4, -0.9),
        "breakup": AxisWeights(-0.3, -0.7, -1.0),
        "lonely": AxisWeights(-0.1, -0.3, -0.9),
        "isolation": AxisWeights(-0.1, -0.4, -1.0),

        "money": AxisWeights(-0.7, -0.8, -0.2),
        "debt": AxisWeights(-0.8, -0.9, -0.2),
        "bills": AxisWeights(-0.7, -0.7, -0.2),
        "job": AxisWeights(-0.6, -0.6, -0.3),
        "career": AxisWeights(-0.5, -0.7, -0.3),

        "prove": AxisWeights(-0.5, -0.9, -0.3),
        "pressure": AxisWeights(-0.6, -0.7, -0.4),
        "deadline": AxisWeights(-0.6, -0.7, -0.3),

        "sick": AxisWeights(-0.9, -0.3, -0.2),
        "illness": AxisWeights(-1.0, -0.3, -0.2),
        "injury": AxisWeights(-1.0, -0.2, -0.2),

        "stuck": AxisWeights(-0.4, -0.9, -0.3),
        "lost": AxisWeights(-0.3, -1.0, -0.4),
        "purposeless": AxisWeights(-0.2, -1.0, -0.4),
        "directionless": AxisWeights(-0.2, -0.9, -0.4),

        "anxiety": AxisWeights(-0.8, -0.5, -0.7),
        "panic": AxisWeights(-0.9, -0.4, -0.8),
        "fear": AxisWeights(-0.7, -0.5, -0.7),
    }

    DEFAULT_WEIGHTS = AxisWeights(-0.6, -0.6, -0.5)

    @classmethod
    def map_event_to_stress(cls, context: str, severity_numeric: int) -> VectorState:
        norm = cls._normalize_severity(severity_numeric)
        tokens = cls._tokenize(context)
        agg_x = agg_y = agg_z = 0.0
        hits = 0

        for t in tokens:
            if t in cls.CATEGORY_WEIGHTS:
                w = cls.CATEGORY_WEIGHTS[t]
                agg_x += w.resilience
                agg_y += w.autonomy
                agg_z += w.connectivity
                hits += 1

        if hits == 0:
            base = cls.DEFAULT_WEIGHTS
            agg_x, agg_y, agg_z = base.resilience, base.autonomy, base.connectivity
            hits = 1

        avg_x, avg_y, avg_z = agg_x / hits, agg_y / hits, agg_z / hits

        return VectorState(
            resilience=avg_x * norm,
            autonomy=avg_y * norm,
            connectivity=avg_z * norm,
        )

    @classmethod
    def _normalize_severity(cls, severity: int) -> float:
        s = max(cls.MIN_SEVERITY, min(cls.MAX_SEVERITY, int(severity)))
        t = (s - cls.MIN_SEVERITY) / (cls.MAX_SEVERITY - cls.MIN_SEVERITY)
        return cls.MIN_FORCE + t * (cls.MAX_FORCE - cls.MIN_FORCE)

    @staticmethod
    def _tokenize(text: str) -> List[str]:
        if not text:
            return []
        text = text.lower()
        tokens = re.split(r"[^a-z]+", text)
        return [t for t in tokens if t]


# =========================
# INVERSION ENGINE (v1)
# =========================

class InversionEngine:
    @staticmethod
    def process_event(
        blueprint: Dict[str, Any],
        event_context: str,
        severity_numeric: int,
        vector_state: VectorState,
    ) -> Dict[str, Any]:
        diagnosis = InversionEngine._diagnose(vector_state)
        script = InversionEngine._script(vector_state)
        experiments = InversionEngine._experiments(vector_state)
        seda_locked = severity_numeric >= 8

        return {
            "diagnosis": diagnosis,
            "script": script,
            "script_source": "heuristic_v1",
            "experiments": experiments,
            "seda_locked": seda_locked,
            "seda_keywords": ["SEDA"] if seda_locked else [],
        }

    @staticmethod
    def _diagnose(state: VectorState) -> str:
        if state.resilience < 3.0 and state.autonomy < 3.0:
            return "Acute burnout with identity depletion."
        if state.resilience < 3.0:
            return "Resilience system overloaded."
        if state.autonomy < 3.0:
            return "Autonomy and self-direction destabilized."
        if state.connectivity < 3.5:
            return "Social connectivity suppressed."
        return "System under manageable stress."

    @staticmethod
    def _script(state: VectorState) -> str:
        parts = []
        if state.resilience < 3.0:
            parts.append(
                "Pause output for 24 hours and reduce external demands to the minimum you can safely hold."
            )
        if state.autonomy < 3.0:
            parts.append(
                "Do not make major decisions alone; speak them out loud with a trusted person before acting."
            )
        if state.connectivity < 3.5:
            parts.app