Metadata-Version: 2.4
Name: latchgate
Version: 0.1.2
Summary: Prevent silent AI hallucinations, fabricated tool calls, and sycophantic world-model physics via zero-decode 57.1%-depth circuit breakers
Author-email: Daniel Gaskins <hello@danielgaskins.com>
License-Expression: MIT
Project-URL: Homepage, https://danielgaskins.com/latchgate.html
Project-URL: Creator, https://danielgaskins.com/
Project-URL: Repository, https://github.com/danielgaskins/latchgate
Project-URL: Issues, https://github.com/danielgaskins/latchgate/issues
Project-URL: Documentation, https://github.com/danielgaskins/latchgate#readme
Project-URL: Hugging Face Packs, https://huggingface.co/danielgaskins/latchgate-packs
Project-URL: Engineering Guide, https://danielgaskins.com/prevent-ai-hallucinations.html
Project-URL: LLM Index, https://danielgaskins.com/llms.txt
Project-URL: Mendmark CI Bridge, https://github.com/danielgaskins/mendmark
Keywords: agent-reliability,ai-control,ai-guardrails,circuit-breakers,cosmos,diffusers,hallucination-detection,interpretability,llm-guardrails,mcp,mechanistic-interpretability,robotics,runtime-verification,sae,sglang,sparse-autoencoders,tool-calling,vllm,world-models
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: safetensors>=0.4
Requires-Dist: torch>=2.1
Provides-Extra: hub
Requires-Dist: huggingface-hub>=0.23; extra == "hub"
Provides-Extra: llm
Requires-Dist: transformers>=4.40; extra == "llm"
Requires-Dist: huggingface-hub>=0.23; extra == "llm"
Provides-Extra: diffusers
Requires-Dist: diffusers>=0.30; extra == "diffusers"
Requires-Dist: huggingface-hub>=0.23; extra == "diffusers"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: huggingface-hub>=0.23; extra == "dev"
Dynamic: license-file

<div align="center">
  <h1>LatchGate</h1>
  <p><strong>Prevent silent AI hallucinations, fabricated tool calls, and sycophantic world-model physics via zero-decode 57.1%-depth circuit breakers.</strong></p>
  <p>
    <a href="https://github.com/danielgaskins/latchgate/actions/workflows/tests.yml"><img alt="Tests" src="https://github.com/danielgaskins/latchgate/actions/workflows/tests.yml/badge.svg"></a>
    <a href="https://pypi.org/project/latchgate/"><img alt="PyPI" src="https://img.shields.io/pypi/v/latchgate?color=0f766e"></a>
    <a href="https://huggingface.co/danielgaskins/latchgate-packs"><img alt="Hugging Face Packs" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-latchgate--packs-ffd21e"></a>
    <img alt="Python 3.10 to 3.13" src="https://img.shields.io/badge/python-3.10--3.13-3776ab">
    <a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-0f766e"></a>
    <br>
    <a href="https://colab.research.google.com/github/danielgaskins/latchgate/blob/main/notebooks/quickstart_llm_sabotage_breaker.ipynb"><img alt="Open LLM Quickstart in Colab" src="https://colab.research.google.com/assets/colab-badge.svg"></a>
    <a href="https://colab.research.google.com/github/danielgaskins/latchgate/blob/main/notebooks/quickstart_cosmos_rollout_firewall.ipynb"><img alt="Open Cosmos Quickstart in Colab" src="https://img.shields.io/badge/Colab-Cosmos_%26_DiT_Firewall-f9ab00?logo=googlecolab&logoColor=white"></a>
  </p>
  <p>
    <a href="#quickstart-a-llm-agents">LLM Agents</a> ·
    <a href="#quickstart-b-cosmos-and-diffusers-world-models">Cosmos &amp; Diffusers</a> ·
    <a href="#equip-a-coding-agent-and-mcp-server">Agent Skill &amp; MCP</a> ·
    <a href="#adaptive-compilation-latchgate-fit">Adaptive Compiler</a> ·
    <a href="#pre-built-lgate-packs">Pre-Built Packs</a> ·
    <a href="#mendmark-ci-to-runtime-bridge">Mendmark Bridge</a>
  </p>
</div>

<p align="center">
  Created by <a href="https://danielgaskins.com/">Daniel Gaskins</a>
</p>

Post-hoc text auditors and pixel-level video critics share a structural flaw: they pay 100% of generation and 3D-VAE decode cost before inspecting an output, and they are systematically fooled by sycophantic trajectories (`<think>` compliance obfuscation in coding agents, or zero-contact optimistic grasps in action-conditioned world models).

**LatchGate** moves safety and physical-consistency enforcement inside the residual stream at **57.1% network depth**, compiling portable `.lgate` (`safetensors`) circuit breakers that execute in `< 1 ms` on LLM tokens and `~11 ms` on 3D spacetime tokens with **0.0% benign capability tax** and **zero pixel decodes**.

## Installation

```bash
pip install latchgate
# Optional extras for Hugging Face Transformers, Diffusers, or Hub helpers:
pip install "latchgate[llm,diffusers,hub]"
```

### Which Guardrail Fits Your AI Stack?

| Deployment Surface | Hidden-State Access | Recommended Prevention Stack |
| --- | --- | --- |
| **Closed Hosted APIs** (`OpenAI`, `Anthropic`, `Gemini API`) | None (HTTP text/JSON only) | Use [**`mendmark-evals`**](https://pypi.org/project/mendmark-evals/) (`pip install mendmark-evals && mendmark demo`) to enforce deterministic tool/outcome invariants and mutation-test agent evaluators in CI |
| **Self-Hosted Open-Weights LLMs** (`Transformers`, `vLLM`, `SGLang`) | Decoder residual stream (`57.1%` depth) | Pair **`mendmark export-latchgate`** with **`latchgate`** (`TransformersLatchHook`, `VLLMLatchEngine`, `SGLangLatchHook`) for `< 1 ms` pre-action circuit breaking at `0.0%` benign tax |
| **3D Video DiTs &amp; Robot World Models** (`NVIDIA Cosmos`, `LTX-Video`, `Diffusers`) | DiT spacetime blocks (`Layer 16/28`) | Attach **`CosmosLatchFirewall`**, **`DiffusersLatchCallback`**, or **`shield_value_critic`** for `11 to 16 ms` zero-decode sycophancy &amp; drift rejection |

## Equip a Coding Agent and MCP Server

Every CLI command supports `--json` for deterministic agent orchestration, plus a built-in zero-dependency stdio **Model Context Protocol (MCP)** server and non-destructive repository skill installer (`Claude Code`, `Codex`, `Cursor`, `Antigravity`):

```bash
# 1. Ask which guardrail stack fits your model and failure mode:
latchgate recommend --model Qwen/Qwen2.5-7B-Instruct --failure-mode "503 tool fabrication" --json

# 2. Deterministically verify any .lgate circuit breaker on CPU in < 1 s:
latchgate verify qwen2.5-7b-sabotage --json

# 3. Scaffold .latchgate/ docs, MCP config, and repo-scoped agent skills (SKILL.md):
latchgate equip --runtime auto --agent auto --json

# 4. Run the stdio JSON-RPC 2.0 MCP server directly:
latchgate mcp
```

## Quickstart A: LLM Agents

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/danielgaskins/latchgate/blob/main/notebooks/quickstart_llm_sabotage_breaker.ipynb)

Intercept `<think>` scratchpad obfuscation 30+ tokens before a sabotaged `TOOL_CALL:` is emitted, latching norm-preserving planning-block steering only when pre-action commitment crosses the calibrated threshold (`0.0%` modification on benign requests):

```python
from latchgate import LatchGate, TransformersLatchHook

gate = LatchGate.from_pretrained("qwen2.5-7b-sabotage", device="cuda")
hook = TransformersLatchHook(gate, policy="latched_steer")  # or policy="early_abort"
with hook.attach(model) as telemetry:
    output_ids = model.generate(**inputs, max_new_tokens=160)
```

The same `.lgate` artifact attaches directly to local `vLLM` (`VLLMLatchEngine`) and `SGLang` (`SGLangLatchHook`) model runners over flattened 2D paged-attention hidden states.

## Quickstart B: Cosmos and Diffusers World Models

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/danielgaskins/latchgate/blob/main/notebooks/quickstart_cosmos_rollout_firewall.ipynb)

Abort action-decoupled ("sycophantic") robot rollouts at Step 10/35 inside `Cosmos-Predict2.5-2B` before running the remaining 50 CFG passes or decoding a single frame through the `Wan2.1` 3D-VAE:

```python
from latchgate import CosmosLatchFirewall, EarlyAbortRollout, LatchGate

gate = LatchGate.from_pretrained("cosmos-predict2.5-bridge", device="cuda")
with CosmosLatchFirewall(gate, policy="early_abort", abort_step=10).attach(world_model.dit) as step_cb:
    latents = world_model.rollout(frame0, actions, decode_video=False, step_callback=step_cb)
```

For closed-loop model-predictive control (`Cosmos-Policy-LIBERO`), `shield_value_critic` prunes sycophantic action candidates at Step 3/10 before invoking the internal value head $V(\hat{s}')$, raising valid grasp selection to `80.0%` while cutting 4-candidate planning latency from `8.93 s` to `6.02 s`.

## Adaptive Compilation (`latchgate fit`)

Generic SAE pretraining on billions of tokens is unnecessary for runtime control and often counterproductive on 7B to 70B LLMs where linear probes already separate pre-action intent cleanly. Given 50 to 200 paired counterfactual traces (plus optional high-motion or benign confounders), `latchgate fit` measures the **57.1%-depth superposition gap** via cross-validation and automatically compiles the lightest representation that achieves target `0.0%` benign false-positive rate:

| Regime | Representative Backbones | 57.1% Depth Geometry | Compiled `.lgate` Architecture |
| --- | --- | --- | --- |
| **Linearly Separable** | `Gemma-2-9B-IT`, `Qwen2.5-7B-Instruct` | Dense CV AUROC `0.94` to `1.00`, zero benign collateral | **`dense_latch`**: Unit-norm L2 logistic gate + 4-layer planning-block steering (`< 1 MB`) |
| **Superposed / Confounded** | `Gemma-2-2B-IT`, `LTX-Video-0.9.5`, `Cosmos-Predict2.5-2B`, `Cosmos-Policy-LIBERO` | 3D spacetime or edge superposition collapses dense probes (`0.36` to `0.51` AUROC) | **`sae_anchor_latch`**: `TimestepStandardizer` + 16k JumpReLU SAE + Confounder-Penalized $\mathcal{D}_{\text{bad}}$ + Instance Anchor $\mathcal{S}_0^{(i)}$ |

### Fast Task Calibration (`< 10 s` on Frozen Base Dictionaries)

Because sparse dictionary learning is decoupled from task attribution, adapting a circuit breaker to a new robot manipulation suite or internal MCP tool schema does **not** retrain the 16,384-latent SAE. Pass `--base-sae` (any `.lgate`, `.safetensors`, Gemma Scope `.npz`, or Hugging Face repo) to calibrate $\mathcal{D} = \text{TopK}(d^{\text{bad}} - \lambda d^{\text{confound}})$ and conformal threshold $\tau$ in seconds:

```bash
latchgate fit custom_robot_pairs.npz \
  --base-sae cosmos-predict2.5-bridge.lgate \
  --max-benign-fpr 0.0 \
  --output custom_cell_firewall.lgate
```

When calibrating a brand-new backbone with no public SAE, `latchgate train-sae` trains a per-timestep standardized JumpReLU SAE on a single 24 GB GPU using **buffer-replay saturation sizing** (Koriagin et al., 2026) and **variance/confounder-reweighted MSE** (WSAE) so high-energy motion or formatting axes do not starve subtle contact or sabotage features.

## Pre-Built `.lgate` Packs

All six SHA-256-verified packs are hosted on both [Hugging Face Hub (`danielgaskins/latchgate-packs`)](https://huggingface.co/danielgaskins/latchgate-packs) and [GitHub Releases (`v0.1.0`)](https://github.com/danielgaskins/latchgate/releases/tag/v0.1.0). List or inspect them from the CLI (`latchgate list-packs`, `latchgate inspect <pack>`):

| Pack ID | Backbone | Mode | Layer | Held-Out AUROC | Verified Runtime Impact |
| --- | --- | --- | --- | ---: | --- |
| `gemma-2-9b-sabotage` | `google/gemma-2-9b-it` | `dense_latch` | `L24/42` (`57.1%`) | `1.000` | Cuts `<think>` sabotage `66.7% -> 5.6%` at `0.0%` benign tax, defeating Action Re-Locking |
| `qwen2.5-7b-sabotage` | `Qwen/Qwen2.5-7B-Instruct` | `dense_latch` | `L16/28` (`57.1%`) | `0.978` | Catches `100%` of `<think>` traces that evade a 7B black-box CoT compliance auditor |
| `gemma-2-2b-sabotage` | `google/gemma-2-2b-it` | `dense_latch` | `L16/26` (`61.5%`) | `1.000` | Cuts pressured tool sabotage `52.1% -> 10.4%` while preserving `96.7%` benign pass rate |
| `ltx-video-0.9.5-drift` | `Lightricks/LTX-Video-0.9.5` | `sae_anchor_latch` | `L16/28` (`57.1%`) | `0.908` | Zero-decode Step-3 (`sigma=0.75`) identity drift detection vs `0.364` dense probe |
| `cosmos-predict2.5-bridge` | `nvidia/Cosmos-Predict2.5-2B` | `sae_anchor_latch` | `L16/28` (`57.1%`) | `0.986` | Cuts DreamGen corruption `33.3% -> 2.9%` (`11.3x`) while saving `26.1%` GPU wall-clock time |
| `cosmos-policy-libero` | `nvidia/Cosmos-Policy-LIBERO-Predict2-2B` | `sae_anchor_latch` | `L16/28` (`57.1%`) | `0.766` | Shields internal value critic (`0.511` AUROC), cutting 4-candidate MPC latency to `6.02 s` |
| `qwen2.5-7b-legal-citation` | `Qwen/Qwen2.5-7B-Instruct` | `dense_latch` | `L16/28` (`57.1%`) | `0.984` | Cuts `Mata v. Avianca` fake citations `95.0% -> 5.0%`; `93.3%` accuracy with Cache-Miss Interrupt |
| `qwen2.5-7b-legal-grounding` | `Qwen/Qwen2.5-7B-Instruct` | `dense_latch` | `L16/28` (`57.1%`) | `0.974` | `5.6k-7.1k` token CUAD/ContractNLI audit `193.9x` faster than LLM judge (`0.0%` benign FPR) |
| `qwen2.5-3b-legal-citation` | `Qwen/Qwen2.5-3B-Instruct` | `dense_latch` | `L21/36` (`58.3%`) | `0.993` | Cuts `Mata v. Avianca` fake citations `100.0% -> 0.0%`; `91.7%` accuracy with Cache-Miss Interrupt |
| `qwen2.5-3b-legal-grounding` | `Qwen/Qwen2.5-3B-Instruct` | `dense_latch` | `L21/36` (`58.3%`) | `0.980` | Cuts pressured contract hallucinations `95.8% -> 33.3%` at `0.0%` benign FPR (`182.0x` speedup) |

## Mendmark CI-to-Runtime Bridge

[**Mendmark**](https://github.com/danielgaskins/mendmark) (`pip install mendmark-evals`) discovers silent tool-call and outcome blind spots in CI via mutation testing; **LatchGate** blocks those exact failure modes in the residual stream at runtime:

```bash
# 1. Export planted fault mutations + clean golden traces from any Mendmark suite:
mendmark export-latchgate examples/order_agent_suite.json \
  --output calibration_pairs.jsonl

# 2. Compile a zero-tax .lgate circuit breaker directly against your open-weights agent model:
latchgate fit calibration_pairs.jsonl \
  --model Qwen/Qwen2.5-7B-Instruct \
  --output order_agent.lgate
```

## Research Foundations

LatchGate unifies the algorithms and empirical findings from three companion papers:

1. **Agentic LLMs:** *Silent Pre-Action Commitment and Closed-Loop Circuit Breakers Against Agentic Sabotage* ([DOI: 10.5281/zenodo.24596272](https://doi.org/10.5281/zenodo.24596272))
2. **Long-Horizon Video DiTs:** *Sparse Temporal Latching: Overcoming Polysemantic Collateral Damage in Long-Horizon Video Diffusion Transformers* ([DOI: 10.5281/zenodo.24596273](https://doi.org/10.5281/zenodo.24596273))
3. **Embodied World Models:** *Sycophantic Physics in Embodied World Models: Zero-Decode Latent Firewalls for Action-Conditioned Video DiTs* ([DOI: 10.5281/zenodo.24593275](https://doi.org/10.5281/zenodo.24593275))

## License

Released under the [MIT License](LICENSE).
