Metadata-Version: 2.4
Name: grg
Version: 0.2.5
Summary: Geometric Reasoning Governor (GRG) — Structural Geometry Optimization (SGO), real-time Early Warning System (EWI), and trajectory governance for time series, autonomous agents, and LLM inference
Author-email: Nick Rotich <nick@example.com>
License: MIT
Keywords: llm,governor,structural-integrity,alpha-drift,hallucination-detection,token-monitoring,rag,sgo,geometric-reasoning,early-warning,regime-detection,time-series,agent-governor
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24.0
Requires-Dist: psutil>=5.9.0
Requires-Dist: click>=8.1.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyyaml>=6.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5.0; extra == "docs"
Requires-Dist: mkdocs-material>=9.0.0; extra == "docs"
Dynamic: license-file

# GRG — Geometric Reasoning Governor

[![PyPI version](https://img.shields.io/pypi/v/grg.svg)](https://pypi.org/project/grg/)
[![Python versions](https://img.shields.io/pypi/pyversions/grg.svg)](https://pypi.org/project/grg/)
[![License](https://img.shields.io/pypi/l/grg.svg)](https://opensource.org/licenses/MIT)

**Domain-general library for Structural Geometry Optimization (SGO), streaming Early Warning Systems (EWI), kinematic drift tracking, autonomous agent governance, and LLM inference stability.**

---

## Overview

`grg` detects structural fragility and accelerating collapse in any sequential or outcome-driven system before failure manifests. Instead of tracking averages alone, `grg` models positive vs. negative outcome coupling via the **SGO Moment Matrix** and monitors kinematic first and second derivatives ($v_\alpha$, $m_\alpha$) of a boundary-distance or health coordinate:

| Component | Export | Responsibility |
|-----------|--------|----------------|
| **Early Warning System** | `EarlyWarningSystem`, `EWIReading` | Streaming regime-flip / collapse detector fusing velocity, momentum, and rolling $\rho_{PN}^2$ fragility with rising-edge intervention callbacks |
| **Kinematic Drift Tracker** | `AlphaMomentumTracker` | Real-time EMA-smoothed level ($\alpha$), drift velocity ($v_\alpha$), acceleration ($m_\alpha$), and collapse horizon (`get_structural_horizon`) |
| **SGO Geometry Metrics** | `compute_sgo_matrix`, `calculate_moment_sgo_metrics`, `evaluate_structural_geometry` | Scale-invariant gain-loss coupling ($\rho_{PN}^2 = \cos^2 \theta_{\mathbf{P},\mathbf{N}}$), macro alignment error ($\cos^2 \psi_{\mathbf{a},\mathbf{d}}$), and distributional tail concentration |
| **Agent Trajectory Governor** | `AgentTrajectoryGovernor`, `AgentStepTelemetry`, `GovernorDecision`, `GovernorAction` | Multi-turn loop, error-cascade, and stagnation governance emitting `PROCEED`, `WARN`, `HINT`, `ROLLBACK`, or `ABORT` |
| **LLM Inference Governor** | `InterventionSampler`, `InterventionConfig`, `CandidateBatch`, `GenerationResult` | Token-level decoding intervention combining n-gram blocking, EWI/velocity triggers, and collapse recovery |

### Forecasting vs. Geometric Reasoning Governor (GRG)

| Dimension | Classical Forecasting | Geometric Reasoning Governor (`grg`) |
| :--- | :--- | :--- |
| **Core Question** | *What* value will occur at $t + h$ ($\hat{x}_{t+h}$)? | Is the system's current structural trajectory stable or approaching a critical boundary collapse? |
| **Input Coordinate** | Raw domain state or feature vector $x_t$ | Signed distance to critical boundary $d_t = x_t - x_{\text{crit}}$ and $K$-step $(P_u, N_u)$ outcome units |
| **Historical Data / Warmup** | Requires seasonal/training history or fitted dynamics | Causal warmup in $W \approx 8\text{--}20$ steps with zero prior training data |
| **Opposing Shocks / Volatility** | Averages positive and negative shocks into net mean + residual variance | Isolates within-unit co-occurrence of gains and losses via $\rho_{PN}^2 = \cos^2\theta_{\mathbf{P},\mathbf{N}} \in [0, 1]$ |
| **Behavior at Regime Breaks** | Lags abrupt breaks or hallucinates flips when the fitted curve diverges | Leads boundary crossings via negative kinematics ($-v_\alpha$, $-m_\alpha$) and $\rho_{PN}^2$ fragility pre-charge |
| **Calibration Free Parameters** | Domain-specific lag orders, priors, or model weights | **1 free timescale parameter ($\nu$)** under the 3:1 Universal Calibration Law ($\Theta = 1.0, \lambda = 0.10, \mu = 3\nu$) |
| **Primary Output** | Passive point forecast and prediction interval | Active governance triggers: `EWIReading`, structural `horizon`, and `PROCEED` / `HINT` / `ROLLBACK` / `ABORT` |
| **Complementary Role** | Extrapolates expected future state values | Audits whether an active policy or forecast-implied regime flip is structurally supported |

#### How Forecasting & GRG Work Together (Empirical Pattern from `examples/farm/`)

Rather than replacing your domain forecaster, `grg` forms a closed **detection + prediction** loop with it:

1. **Division of Labor:**
   - **GRG (`EarlyWarningSystem`) answers *WHEN* and *WHETHER*** a regime transition is physically occurring by monitoring causal boundary dominance margin $d_t = c_{(1),t} - c_{(2),t}$. With only a causal $W = 8$-day warmup and no seasonal history, it reaches **ROC-AUC = 0.9311** in Year 1 (cold-start) and **0.9296** in Year 2 with **`avg_lead_time_days = 6.97–7.91`** ahead of an $h = 14$-day horizon.
   - **The Forecaster (`fit_forecast` CLR harmonic regression) answers *WHICH* regime comes next** ($\arg\max \hat{\mathbf{x}}_{t+h}$). In Year 1 (incomplete seasonal cycle), the forecaster lags (`ROC-AUC = 0.7684`, `75.7%` directional accuracy on GRG-flagged transitions); in Year 2 (full 365-day seasonal cycle observed), forecaster alignment rises to **`ROC-AUC = 0.9502`** and **`91.8%` directional accuracy** ($r = 0.9065$, $R^2 = 0.8217$).

2. **Joint Decision Matrix (Forecaster × GRG):**

| GRG Warning (`EWI >= Theta`) | Forecaster Predicts Flip ($\hat{y}_{t+h} \ne y_t$) | Diagnosis | Recommended Action |
| :---: | :---: | :--- | :--- |
| **Yes** | **Yes** | **Confirmed Transition** — Boundary margin $d_t$ is eroding and parametric trajectory crosses zero | **Execute Transition** toward the forecaster-predicted target regime (`75.7%` Y1 / `91.8%` Y2 accuracy) |
| **Yes** | **No** | **Forecaster Cold-Start / Lag** — Real boundary erosion (`ROC-AUC = 0.93`), but parametric model is anchored to stale history (e.g., Year 1 pre-cycle) | **Hedge / De-Risk Immediately**; do not wait for the lagging point forecast |
| **No** | **Yes** | **Model Artifact / False Flip** — Parametric curve overshoots, but boundary health $\alpha_t$ is high and stable ($v_\alpha \ge 0$) | **Suppress False Alarm**; keep current regime until kinematic erosion appears |
| **No** | **No** | **Structurally Stable Regime** — Margin $d_t$ is wide and forecast stays inside current basin | **Proceed Normally** |

3. **Empirical Cold-Start vs. Calibrated Evidence (`examples/farm/proof_metrics.json`):**

| Metric ($h = 14$ days) | Year 1 (Cold-Start Harmonics) | Year 2 (Full-Cycle Harmonics) | Takeaway |
| :--- | :---: | :---: | :--- |
| **GRG vs. True Flip ROC-AUC** | **0.9311** | **0.9296** | GRG tracks the true boundary transition from Year 1 without seasonal history |
| **GRG vs. Forecast Flip ROC-AUC** | `0.7684` | **0.9502** | Forecaster converges to GRG once its seasonal basis is well-sampled |
| **GRG-Gated Forecast Accuracy** | `75.7%` | **91.8%** | Querying the forecaster *when* GRG flags instability yields high-precision target selection |
| **GRG Kinematic Fit to True Margin ($R^2$)** | `0.6192` ($r = 0.7869$) | **0.8217** ($r = 0.9065$) | Kinematic state $(\alpha_t, v_{\alpha,t}, m_{\alpha,t})$ explains future boundary margin directly |

#### Why GRG Excels on Actual Historical Data vs. Parametric Forecasting

1. **Zero Parametric Misspecification Error (Realized Telemetry > Extrapolated Curves):**
   - Parametric forecasters fit an assumed curve (e.g., harmonic regression in `examples/farm/forecast.py`) and extrapolate it forward; when the seasonal or structural basis is under-sampled (Year 1), extrapolation hallucinates flips (`ROC-AUC = 0.7684`, $R^2 = 0.5397$ against GRG signals).
   - `grg` reads **actual realized boundary distance** $d_t$ directly with zero parametric curve-fitting assumptions, reaching **`ROC-AUC = 0.9311`** and **$R^2 = 0.6192$ ($r = 0.7869$)** against true transitions from Year 1.

2. **Three Compounding Gains When Historical Data Is Available (Year 1 $\rightarrow$ Year 2):**
   - **Empirical Calibration of the 1 Free Parameter ($\nu$ via $|v_{\text{crit}}|$):** Historical data lets you measure the exact realized critical velocity $|v_{\text{crit}}|$ across past boundary crossings (or optimize directly on realized L2 streams as in `examples/hft/hyperopt_runner.py`), anchoring $\nu = 0.225 / |v_{\text{crit}}|$ and $\mu = 3\nu$ to empirical truth instead of heuristic priors.
   - **Higher Kinematic Explanatory Power ($R^2$: `0.6192` $\rightarrow$ `0.8217`):** Fitting GRG's kinematic vector $(\alpha_t, v_{\alpha,t}, m_{\alpha,t})$ to actual historical boundary margins explains **82.17% of future boundary variance ($r = 0.9065$, $p = 9.83 \times 10^{-133}$)** in Year 2 (up from `61.92%` in Year 1), while lifting `F1` (`0.6591` $\rightarrow$ `0.6700`) and `precision` (`0.6304` $\rightarrow$ `0.6505`).
   - **High-Precision Target Selection (`75.68%` $\rightarrow$ `91.84%`):** When historical data also calibrates the downstream forecaster or classifier, executing transitions only when GRG flags instability raises target regime accuracy from **`75.68%` (Year 1)** to **`91.84%` (Year 2)**.

### Physical AI & Replacing Watchdog AI Agents

In Physical AI (embodied robotics, autonomous vehicles, drones, BMS/power grids, and industrial control), neural policies suffer from silent out-of-distribution (OOD) failures and cannot run multi-billion-parameter watchdog models at $1\text{ kHz}$ edge control loops.

`grg` runs in $O(1)$ time per step with deterministic, closed-form math and 1-parameter calibration: boundary distance $d_t = x_t - x_{\text{crit}}$ acts as a **Control Barrier Function (CBF) safety margin**, while $\rho_{PN}^2 = \cos^2\theta_{\mathbf{P},\mathbf{N}}$ detects **actuator chattering / control oscillation** (opposing forces fighting inside the same $K$-step window before physical instability).

#### Physical AI Domains (`grg` + AI or `grg` Standalone)

| Physical Domain | Boundary Coordinate $d_t = x_t - x_{\text{crit}}$ | What $\rho_{PN}^2 + (-v_\alpha, -m_\alpha)$ Detects | Mode |
| :--- | :--- | :--- | :--- |
| **Humanoid & Quadruped Robotics** | Zero-Moment Point (ZMP) balance margin; grasp slip force margin | Micro-chattering between motor torque and surface contact before foot slip or object drop | `grg` + VLA/RL Policy (high-rate safety shield) |
| **Autonomous Vehicles & Drones** | Time-to-collision (TTC); aerodynamic stall margin ($\alpha_{\text{stall}} - \alpha_t$); lane boundary margin | Control oscillation (over-correcting steering/pitch in wind shear) while safety margin compresses | `grg` + Neural Planner (Simplex switch to classical controller) |
| **Battery BMS & Power Grids** | Cell voltage/temp margin to thermal runaway; grid frequency margin to $60 \pm 0.5\text{ Hz}$ | Internal impedance spikes (charge/discharge co-occurrence) + accelerating margin erosion | `grg` Standalone (lightweight edge monitor, zero AI) |
| **Industrial CNC & Semiconductor Fab** | Tool-wear vibration margin; plasma chamber pressure/temp tolerance | High-frequency resonance coupling ($\rho_{PN}^2 \to 1$) before wafer defect or spindle fracture | `grg` Standalone or `grg` + Predictive Maintenance Forecaster |
| **Smooth Physical RL Training** | Signed step reward / torque smoothness (`examples/grg_trainers/torch_dual_cosine.py`) | Penalizes oscillatory "bang-bang" actuator policies end-to-end (same `DualCosineSGOLoss` used in `examples/hft/trading_engine.py`) | Differentiable Loss for Physical AI Training |

#### Replacing Watchdog / Critic AI Agents with `grg`

Whenever a monitor or critic agent's sole job is deciding *whether a trajectory is healthy, looping, or approaching failure*, `grg` can replace the extra AI model directly:

| Over-Engineered AI Agent | Direct `grg` Replacement | Why `grg` Wins |
| :--- | :--- | :--- |
| **LLM Supervisor / Critic Agent** watching workers for loops or dead-ends | `AgentTrajectoryGovernor` (`src/grg/agent_governor.py`) | Zero token cost, deterministic `PROCEED` / `HINT` / `ROLLBACK` / `ABORT` decisions |
| **Deep Time-Series Anomaly Agent** (LSTM / Transformer detector) | `EarlyWarningSystem` (`src/grg/early_warning.py`) + 3:1 Law | Zero training data (`ROC-AUC = 0.9311` in Year 1 cold-start in `examples/farm/validation.py`); 1 free parameter ($\nu$) |
| **Edge Safety Watchdog Agent** on robots, vehicles, or medical devices | `EarlyWarningSystem` + `AlphaMomentumTracker` (`src/grg/metrics.py`) | Auditable, certifiable closed-form math (unlike black-box neural watchdogs) |
| **Portfolio / Execution Risk Agent** | Two-sided EWI (`examples/hft/trading_engine.py`) | Sub-millisecond tick reaction with zero model hallucination |

**Core Design Rule:** Keep neural/AI models for high-dimensional perception and candidate proposal, and use `grg` for closed-loop boundary governance, stability auditing, and hardware or trajectory E-stops.

---

## Installation

Install the published package from PyPI:

```bash
pip install grg
```

For local development from source:

```bash
git clone https://github.com/moinonin/grg.git
cd grg
pip install -e ".[dev]"
```

Requires Python $\ge 3.10$ (`numpy`, `psutil`, `click`, `pydantic`, `pyyaml`).

---

## Using `grg` in a Generalized Project

### Pattern 1 — Generalized Regime & Tipping-Point Early Warning (`EarlyWarningSystem`)

To apply `grg` to **any domain** (sensor streams, financial returns, model confidence, ecological indices, or service SLOs):

1. **Map raw telemetry $x_t$ to a signed boundary-distance coordinate** $d_t = x_t - x_{\text{crit}}$ where $d_t \to 0^+$ approaches the critical transition boundary:
   - Pass `input_is_delta=False` (default) when pushing **state levels** $d_t$ (such as a class dominance margin $c_{(1),t} - c_{(2),t}$); `EarlyWarningSystem` computes step differences internally.
   - Pass `input_is_delta=True` when pushing values that are already **step deltas / signed returns** (such as basis-point tick moves).
2. **Apply the Preliminary 3:1 Universal Calibration Law (1 Free Parameter)** — normalize the intervention threshold to $\Theta = 1.0$, cap pure $\rho_{PN}^2$ coupling at $10\%$ ($\lambda = 0.10$), lock $\mu = 3\nu$, and scale the single free timescale parameter $\nu$ to your domain's critical decay rate $|v_{\text{crit}}|$:
   $$\Theta = 1.0, \qquad \lambda = 0.10, \qquad \mu = 3\nu, \qquad \nu \approx \frac{0.90}{4\,|v_{\text{crit}}|} = \frac{0.225}{|v_{\text{crit}}|}$$

```python
from grg import EarlyWarningSystem

# Calibrate from estimated critical velocity scale |v_crit| ~= 0.05 per step
v_crit = 0.05
nu = 0.225 / v_crit  # 4.5 (single free parameter)
mu = 3.0 * nu        # 13.5 (3:1 kinematic ratio)

def on_warning(reading):
    print(f"INTERVENTION at step={reading.step}: EWI={reading.ewi:.3f}, v_alpha={reading.v_alpha:.4f}")

ews = EarlyWarningSystem(
    window_size=16,
    alpha_ema=0.4,
    k=3,
    mu=mu,
    nu=nu,
    lambda_=0.10,
    threshold=1.0,
    input_is_delta=False,  # False for state levels d_t; True for step deltas
    intervention_fn=on_warning,
)

# Stream signed boundary distances d_t = x_t - x_crit approaching 0
for d_t in [0.60, 0.58, 0.55, 0.50, 0.42, 0.31, 0.18, 0.05]:
    reading = ews.push(d_t)
    # reading.warning, reading.collapse, reading.intervention_fired, reading.ewi, reading.rho_pn_sq

print(ews.summary())
```

---

### Pattern 2 — Batch SGO Moment & Decoupling Analysis (`calculate_moment_sgo_metrics`, `evaluate_structural_geometry`)

Group outcomes into coherent $K$-step experience units $u$ to measure **within-unit win/loss coupling** $\rho_{PN}^2 \in [0, 1]$ alongside cross-sectional cofactor geometry:

```python
import numpy as np
from grg import calculate_moment_sgo_metrics, evaluate_structural_geometry

# 1. Trajectory-level Moment SGO analysis across K-step outcome units
outcome_units = [
    [0.04, 0.03, 0.02, -0.01, 0.05],
    [0.02, -0.03, 0.04, -0.02, 0.01],
    [-0.03, 0.01, -0.04, 0.02, -0.02],
]
moment = calculate_moment_sgo_metrics(outcome_units, utility_power=1.1)
print(f"Coupling rho_pn_sq: {moment['rho_pn_sq']:.4f}")
print(f"Moments: E[P]={moment['e_p']:.4f}, E[N]={moment['e_n']:.4f}, E[PN]={moment['e_pn']:.6f}")

# 2. Cross-sectional + Moment SGO geometry evaluation in one call
results = evaluate_structural_geometry(
    positive_outcomes=np.array([0.8, 0.9, 0.7, 0.85]),
    negative_outcomes=np.array([0.2, 0.15, 0.3]),
    outcome_units=outcome_units,
    ranking_profile="conservative",
    regime_aware=True,
)
print(f"Structural Alpha:  {results['structural_alpha']:.4f}")
print(f"norm_alpha_s_sil:  {results['norm_alpha_s_sil']:.4f}")
print(f"Coupling rho_pn_sq:{results['rho_pn_sq']:.4f}")
print(f"Alpha Health:      {results['alpha_health']:.4f}")
print(f"Ranking Score:     {results['ranking_score']:.4f}")
```

---

### Pattern 3 — Autonomous Agent Trajectory Governance (`AgentTrajectoryGovernor`)

Monitor tool-calling agents turn by turn to catch parameter loops, repeated errors, and semantic stalls before exhausting token or step budgets:

```python
from grg import AgentStepTelemetry, AgentTrajectoryGovernor, GovernorAction

gov = AgentTrajectoryGovernor(
    window_size=10,
    safety_floor=0.15,
    panic_threshold=-0.04,
)

turns = [
    AgentStepTelemetry(step_index=0, tool_name="search", tool_args={"q": "grg"}, tool_success=True, semantic_progress=0.4),
    AgentStepTelemetry(step_index=1, tool_name="read", tool_args={"path": "a.py"}, tool_success=True, semantic_progress=0.7),
    AgentStepTelemetry(step_index=2, tool_name="run_test", tool_args={"target": "t"}, tool_success=False, error_message="AssertionError", semantic_progress=0.05),
    AgentStepTelemetry(step_index=3, tool_name="run_test", tool_args={"target": "t"}, tool_success=False, error_message="AssertionError", semantic_progress=0.05),
]

for telemetry in turns:
    decision = gov.step(telemetry)
    if decision.action != GovernorAction.PROCEED:
        print(f"Turn {decision.step_index}: {decision.action.value} — {decision.message}")
        if decision.suggested_hint:
            print(f"  Hint: {decision.suggested_hint}")
```

---

### Pattern 4 — LLM Token-Stream Governance (`AlphaMomentumTracker`, `InterventionSampler`)

Track structural integrity across token streams directly with `AlphaMomentumTracker`, or wrap a token-scoring backend with `InterventionSampler` (defaults to local Ollama HTTP API, or inject any custom `backend(prompt) -> CandidateBatch`):

```python
import math
from grg import (
    AlphaMomentumTracker,
    CandidateBatch,
    InterventionConfig,
    InterventionSampler,
)

# 4a. Direct kinematic tracking of any health score alpha in [0, 1]
tracker = AlphaMomentumTracker(window_size=20, alpha_ema=0.3)
for alpha in [0.92, 0.90, 0.85, 0.72, 0.50, 0.25]:
    tracker.push(alpha)

stats = tracker.get_stats(v_panic=-0.02, floor=0.10)
if stats["is_collapsing"] or tracker.should_stop(safety_floor=0.10, panic_threshold=-0.02):
    print(f"Collapse risk: v_alpha={stats['v_alpha']:.4f}, horizon={stats['horizon']:.2f}")

# 4b. Token-level generation governor with a pluggable backend
step_tokens = [("return ", -0.2), ("x + 1", -0.1), ("<|im_end|>", -0.05)]
call_idx = 0

def custom_backend(prompt: str) -> CandidateBatch:
    global call_idx
    tok, lp = step_tokens[min(call_idx, len(step_tokens) - 1)]
    call_idx += 1
    return CandidateBatch(tokens=[tok, "pass"], logprobs=[lp, math.log(0.1)])

sampler = InterventionSampler(
    config=InterventionConfig(tier="full", max_tokens=8),
    backend=custom_backend,
)
gen = sampler.generate("def add_one(x):\n    ")
print(f"Generated: {gen.text!r} | interventions={gen.n_interventions} | quality={gen.quality:.3f}")
```

---

## Mathematical Summary & The 3:1 Universal Calibration Law

### Moment SGO Matrix & Coupling Identities

Within each $K$-step experience unit $u$, raw outcomes $r_{u,t}$ are warped by a monotone utility transform $g_p(x) = \text{sign}(x)|x|^p$ (default $p = 1.1$) into non-negative gain mass $P_u = \sum_t \max(g_p(r_{u,t}), 0)$ and loss magnitude $N_u = -\sum_t \min(g_p(r_{u,t}), 0)$. With $v_u = [1, P_u, N_u]^\top$, the Moment SGO Matrix is:

$$
S = \mathbb{E}[v_u v_u^\top] =
\begin{bmatrix}
1 & \mathbb{E}[P] & \mathbb{E}[N] \\
\mathbb{E}[P] & \mathbb{E}[P^2] & \mathbb{E}[PN] \\
\mathbb{E}[N] & \mathbb{E}[PN] & \mathbb{E}[N^2]
\end{bmatrix}
$$

Two scale-invariant trigonometric identities follow (see [docs/GRG_ADVANCED.md](docs/GRG_ADVANCED.md)):

1. **Macro Alignment Error ($\cos^2 \psi_{\mathbf{a},\mathbf{d}}$):** $\text{norm\_alpha\_s\_sil} = \frac{(\alpha_{\text{ideal}} + s_{\text{obs}})^2}{2(\alpha_{\text{ideal}}^2 + s_{\text{obs}}^2 + \epsilon)} \in [0, 1]$, giving $\alpha_{\text{health}} = 1 - \text{norm\_alpha\_s\_sil} = \sin^2(\psi_{\mathbf{a},\mathbf{d}})$.
2. **Trajectory Gain-Loss Coupling ($\rho_{PN}^2 = \cos^2 \theta_{\mathbf{P},\mathbf{N}}$):**
   $$\rho_{PN}^2 = \frac{\mathbb{E}[PN]^2}{\mathbb{E}[P^2]\mathbb{E}[N^2] + \epsilon} \in [0, 1]$$
   Quantifies whether gains and losses co-occur inside the same $K$-step unit ($\rho_{PN}^2 \to 1$, fragile) or remain decoupled ($\rho_{PN}^2 \to 0$).

### Early Warning Index (EWI) & Preliminary 3:1 Calibration Rule

`EarlyWarningSystem._push` evaluates:

$$
\text{EWI}_t = \lambda \cdot \rho_{PN, t}^2 + \mu \cdot \max(0, -v_{\alpha, t}) + \nu \cdot \max(0, -m_{\alpha, t}) \ge \Theta
$$

For new case studies, treat the **3:1 Universal Calibration Law** as a preliminary 1-free-parameter baseline:

- **Normalized Threshold & 10% Fragility Pre-Charge:** $\Theta = 1.0$, $\lambda = 0.10\,\Theta = 0.10$. Pure coupling agitation ($\rho_{PN}^2 \le 1$) supplies at most $10\%$ of $\Theta$, requiring negative directional kinematics ($v_\alpha < 0$) to trigger.
- **3:1 Kinematic Ratio:** $\mu = 3\nu$ balances first-derivative EMA velocity ($-v_\alpha$) and second-derivative EMA momentum ($-m_\alpha$) for `alpha_ema` $\in [0.3, 0.4]$.
- **Single Free Timescale Gain:** $\nu \approx \frac{0.90}{4\,|v_{\text{crit}}|} = \frac{0.225}{|v_{\text{crit}}|}$, set from the domain's critical negative velocity scale $|v_{\text{crit}}|$.

| Case Study | Module | Input Stream (`input_is_delta`) | `alpha_ema` | $\mu$ | $\nu$ | $\mu : \nu$ | $\lambda$ | $\Theta$ | $\lambda / \Theta$ |
| :--- | :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| **HFT Microstructure** | `examples/hft/trading_engine.py` | `step_bps` (`True`) | `0.4` | `3.0` | `1.0` | **3.00 : 1** | `0.10` | `1.00` | **0.100** |
| **LLM Token Governor** | `src/grg/intervention.py` | token stream (`False`) | `0.3` | `3.0` | `1.0` | **3.00 : 1** | `0.10` | `0.50` | **0.200** |
| **Farm Ecological Regimes** | `examples/farm/validation.py` | `dominance_margin` (`False`) | `0.4` | `50.0` | `15.0` | **3.33 : 1** | `0.01` | `0.06` | **0.167** |
| **New Case Study (Rule)** | *Preliminary Baseline* | $d_t$ (`False`) or $\Delta d_t$ (`True`) | `0.3–0.4` | $3\nu$ | $\nu$ | **3.00 : 1** | `0.10` | `1.00` | **0.100** |

See [docs/GRG_ADVANCED.md](docs/GRG_ADVANCED.md#6-preliminary-modeling-rule-the-31-universal-calibration-law-1-free-parameter) for the full derivation.

---

## Public API, Configuration & CLI

### Public Exports (`grg.__all__`)

- **Early Warning:** `EarlyWarningSystem`, `EWIReading`
- **Trackers:** `AlphaMomentumTracker`, `StructuralTracker` *(legacy unsmoothed tracker)*
- **Moment & Structural SGO:** `compute_sgo_matrix`, `calculate_moment_sgo_metrics`, `evaluate_structural_geometry`, `compute_structural_alpha`, `calculate_normalized_structure_metrics`, `extract_matrix_alpha`, `calculate_cofactor_matrix`, `calculate_regime_aware_ideal`, `calculate_ranking_score`, `calculate_positive_alpha_penalty`, `evaluate_balance_diagnostics`, `evaluate_cofactors_norm_diff_diagnostics`, `RANKING_PROFILES`
- **Entropy, Probability & Distribution:** `calculate_entropy`, `calculate_probability_sgo_matrix`, `calculate_sgo_divergence`, `evaluate_distributional_geometry`, `compute_distributional_concentration`, `apply_utility_transformation`
- **Agent & LLM Governors:** `AgentTrajectoryGovernor`, `AgentStepTelemetry`, `GovernorDecision`, `GovernorAction`, `InterventionSampler`, `InterventionConfig`, `GenerationResult`, `TokenTelemetry`, `CandidateBatch`
- **Configuration:** `get_config` (`get(key, default)`, `get_profile(name)`, `get_grg_config(profile_name)`)

### Configuration Profiles (`src/grg/config/grg-config.json`)

| Profile | `window_size` | `ema_weight` | `v_alpha_panic_threshold` | `alpha_safety_floor` | `e_stop_horizon` |
| :--- | :---: | :---: | :---: | :---: | :---: |
| `default` | `20` | `0.30` | `-0.02` | `0.10` | `5` |
| `high_sensitivity` | `16` | `0.40` | `-0.01` | `0.15` | `3` |
| `low_latency` | `12` | `0.50` | `-0.03` | `0.08` | `2` |
| `rag_grounded` | `24` | `0.25` | `-0.005` | `0.20` | `8` |

### CLI Commands (`grg`)

```bash
grg analyze --profile default --pretty          # System telemetry SGO + GRG summary
grg simulate --profile high_sensitivity -s 100  # Synthetic alpha-decay simulation
grg config --profile rag_grounded               # Print merged profile configuration
grg profiles                                    # List all built-in GRG profiles
```

---

## Repository Structure & Case Studies

```text
grg/
├── pyproject.toml                   # PyPI metadata, dependencies, ruff/mypy/pytest config
├── Makefile                         # Development, testing, HFT & agent workflows
├── README.md                        # PyPI package guide
├── docs/
│   ├── GRG_ADVANCED.md              # Moment SGO identities & 3:1 Universal Calibration Law
│   └── agent_reviewed_torch.md      # PyTorch DualCosineSGOLoss verification notes
├── src/grg/
│   ├── __init__.py                  # Public package exports
│   ├── early_warning.py             # EarlyWarningSystem & EWIReading
│   ├── metrics.py                   # AlphaMomentumTracker & SGO metrics
│   ├── agent_governor.py            # AgentTrajectoryGovernor
│   ├── intervention.py              # InterventionSampler & InterventionConfig
│   ├── config.py                    # Profile configuration loader
│   ├── config/grg-config.json       # Built-in GRG profiles
│   └── cli.py                       # `grg` CLI entrypoint
├── examples/
│   ├── farm/                        # Ecological regime-flip forecasting & visual proofs
│   ├── hft/                         # Hyperliquid WS trading_engine.py, backtester, hyperopt
│   ├── grg_trainers/                # Differentiable PyTorch DualCosineSGOLoss / SGPO
│   ├── agent_governance/            # AgentTrajectoryGovernor benchmarks & demos
│   ├── grg_agent/                   # GRG-gated coding agent
│   ├── grg_inference/               # Inference-time GRG studies
│   └── llms/                        # LLM intervention experiments
└── tests/                           # Automated pytest suite
```

### Development Commands

```bash
make help        # List all repository targets
make version     # Show current PyPI package version
make bump        # Bump version (PART=patch|minor|major or VERSION=x.y.z)
make test        # Run pytest with coverage
make lint        # Run ruff checks
make typecheck   # Run mypy checks
make check       # Run lint + typecheck + test
make build       # Build wheel and sdist via setuptools
```

---

## License

MIT License — see [LICENSE](LICENSE).

## Citation

```bibtex
@software{grg2024,
  title = {Geometric Reasoning Governor (GRG)},
  author = {Nick Rotich},
  year = {2024},
  url = {https://github.com/moinonin/grg}
}
```
