Metadata-Version: 2.4
Name: nex-nix
Version: 0.1.1
Summary: Sovereign Nix Sub-Shell Hypervisor, Hermetic PyPI Sanitizer & Binary Deployment Engine
Author-email: The Trinity <inquiries@houseoflawpc.com>
License: MIT OR Apache-2.0
Keywords: nix,flakes,pypi,release,sandbox,subshell,devshell,deployment,oidc,audit
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
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 :: Software Development :: Build Tools
Classifier: Topic :: System :: Systems Administration
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: rich>=13.7.0
Requires-Dist: nex-init>=0.1.0
Provides-Extra: sandbox
Requires-Dist: nex-box>=0.2.2; extra == "sandbox"
Provides-Extra: all
Requires-Dist: nex-box>=0.2.2; extra == "all"
Requires-Dist: twine>=5.0.0; extra == "all"
Requires-Dist: build>=1.2.0; extra == "all"

# nex-nix ⚡

**Sovereign Nix Sub-Shell Hypervisor, Hermetic PyPI Sanitizer & Binary Deployment Engine.**

[![pypi](https://img.shields.io/pypi/v/nex-nix.svg?color=blue)](https://pypi.org/project/nex-nix/)
[![license](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](LICENSE)
[![platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux-lightgrey.svg)](#)
[![provenance](https://img.shields.io/badge/provenance-PEP%20740%20OIDC-green.svg)](#)
[![trinity](https://img.shields.io/badge/engineered%20by-The%20Trinity-purple.svg)](#the-permanexus-pact)

`nex-nix` resolves the fundamental architectural collision between **hermetic Nix environments** and the **Python/PyPI packaging ecosystem**. 

Built for autonomous agent runtimes, high-assurance engineers, and deterministic systems developers, `nex-nix` operates as a dual-plane hypervisor:
1. **The Inbound Hypervisor (Sub-Shells & Store Deployment):** Dynamically spawns lightweight, ephemeral Nix sub-shells on the fly, pulls pre-built closures directly from Nix binary caches, and deploys standalone Mach-O/ELF executable wrappers without bloating or polluting your master flake.
2. **The Outbound Sanitizer (Hermetic PyPI Releases):** Neutralizes `/nix/store` RPATH contamination in compiled wheels, audits PEP 621 metadata, verifies packages in isolated scratch sandboxes, and executes zero-token **PEP 740 OIDC Trusted Publishing**.

---

## The Mechanical Reality: Why Nix Breaks Python Packages

When developers build Python wheels inside a Nix shell or NixOS environment, two severe systemic failure modes emerge:

### 1. The Nix Store Path Contamination Trap
Nix achieves hermeticity by injecting compiler and linker flags (`NIX_CFLAGS_COMPILE`, `NIX_LDFLAGS`) containing absolute paths to immutable store paths:
```text
/nix/store/a1b2c3d4e5f6...-openssl-3.0.12/lib
```
When compiling C-extensions, Cython, or Rust bindings (`maturin`), the compiler bakes these `/nix/store/...` paths directly into the binary's `RPATH` / `LC_RPATH`. If this wheel is uploaded to PyPI, **it crashes instantly on standard Linux and macOS machines** with:
```text
dyld: Library not loaded: /nix/store/...
```
`nex-nix` strips all Nix environment pollution before building, and scans the produced `.whl` and `.tar.gz` artifacts byte-by-byte with regex probes to mathematically guarantee zero `/nix/store` path leakage before anything touches the wire.

### 2. The Monolithic Flake Bloat Problem
Developers routinely cram hundreds of heavy dependencies (Lean 4, Yosys, Verilator, Zig, Clang, Playwright, Node) into a single master `flake.nix`. This bloats evaluation times, triggers cross-dependency linker collisions, and prevents autonomous agents from safely using specialized tools.
`nex-nix` allows agents to spawn **throwaway, sub-second JIT Nix sub-shells** for specialized tasks with zero host mutation.

---

## Architectural Topology

```text
                                    NEX_NIX HYPERVISOR
                                            ▲
                       ┌────────────────────┴────────────────────┐
                       │                                         │
               [INBOUND PLANE]                           [OUTBOUND PLANE]
          Sub-Shell & Store Hypervisor               Hermetic PyPI Sanitizer
                       │                                         │
        ├── JIT Ad-hoc Subshells                 ├── Strips NIX_CFLAGS_COMPILE
        │   (nix shell nixpkgs#<pkg>)            │   and NIX_LDFLAGS
        │                                        │
        ├── Flake Capability Profiles            ├── Byte-level /nix/store
        │   (nix develop .#<profile>)            │   RPATH leak scanner
        │                                        │
        ├── Binary Store Pull & Deploy           ├── Ephemeral Scratch-Venv
        │   (Atomic Mach-O/ELF wrappers)         │   isolated install verification
        │                                        │
        └── nex-box APFS CoW Sandbox             └── PEP 740 OIDC Tokenless
            (Sub-second APFS cloning)                Trusted Publishing
```

---

## Core Capabilities & Usage

### Plane 1: Inbound Sub-Nix Shells & Capability Profiles

#### 1. JIT Ad-hoc Sub-Shell Spawner
Run any tool from `nixpkgs` on the fly without modifying your `flake.nix` or polluting your global environment:
```bash
# Spawn an ephemeral subshell with Yosys and Z3 to check a Verilog module:
nex-nix exec --with yosys z3 -- yosys -p "prep; check" core.v

# Convert media using an ad-hoc FFmpeg subshell:
nex-nix exec --with ffmpeg -- ffmpeg -i input.wav -b:a 192k output.mp3

# Enforce APFS Copy-on-Write sandboxing via nex-box:
nex-nix exec --with ripgrep --sandbox -- rg "TODO" ./src
```

#### 2. Declarative Flake Capability Profiles
Define modular, domain-specific `devShells` in your `flake.nix` (e.g. `formal`, `hardware`, `cross`, `pypi`) and execute inside them instantly:
```bash
# Execute theorem proving in the Lean 4 + Mathlib sub-profile:
nex-nix run-in formal -- lean --run TheoremProof.lean

# Run hardware linting inside the Verilator sub-profile:
nex-nix run-in hardware -- verilator --lint-only top.v
```

#### 3. Binary Store Closure Deployment
Pull pre-compiled packages directly from Nix binary caches (`cache.nixos.org`, Cachix) and deploy standalone executable wrappers into your local binary directory:
```bash
# Pull pre-compiled ffmpeg and deploy an executable launcher to ~/bin:
nex-nix deploy nixpkgs#ffmpeg --to ~/bin

# Deploy a custom flake derivation into your project's distribution folder:
nex-nix deploy .#omni-parser --to ./dist --bin-name nex-parser
```

---

### Plane 2: Outbound Hermetic PyPI Release Pipeline

#### 1. Pre-Flight Metadata Audit & Leak Scanning
Scans `pyproject.toml` for PEP 621 specification compliance, checks git working tree status, and audits built wheels for `/nix/store` leakage:
```bash
nex-nix audit .
```

#### 2. Hermetic Isolated Build
Strips `NIX_CFLAGS_COMPILE`, `NIX_LDFLAGS`, and `NIX_ENFORCE_PURITY`, and builds clean artifacts using `uv build`:
```bash
nex-nix build . --clean
```

#### 3. Ephemeral Sandbox Verification
Creates an isolated scratch virtual environment in a temporary directory, installs the freshly built wheel, and verifies package imports before publication:
```bash
nex-nix verify .
```

#### 4. Automated Release Pipeline
Executes the full pipeline in one command:
```bash
# If PYPI_API_TOKEN is set, uploads via Twine; otherwise instructs OIDC release:
nex-nix publish .
```

---

## Programmatic Python SDK (Agent Integration)

Autonomous agents running inside `nex_hop` or Octad mesh nodes can programmatically spawn subshells and deploy closures:

```python
import nex_nix
from pathlib import Path

# 1. Execute arbitrary commands inside an ephemeral Nix subshell
proc = nex_nix.run_with_packages(
    packages=["yosys", "z3"],
    command=["yosys", "-p", "prep; check", "alu.v"],
    cwd=Path("./workspace"),
    sandbox=True,  # Wraps in nex-box APFS CoW isolation
)
print(f"Exit code: {proc.returncode}")
print(proc.stdout)

# 2. Deploy a pre-built binary closure from the Nix store
wrapper_path = nex_nix.deploy_binary_closure(
    attribute="nixpkgs#ripgrep",
    target_dir=Path("./bin"),
    bin_name="rg",
)
print(f"Deployed launcher: {wrapper_path}")
```

---

## GitHub Actions OIDC Trusted Publishing (PEP 740)

`nex-nix` natively generates and supports tokenless **PEP 740 OIDC Trusted Publishing**, eliminating the need to store static PyPI API tokens in GitHub Secrets.

Generate the workflow automatically:
```bash
nex-nix init-oidc . --pkg-name nex-nix
```

This provisions `.github/workflows/release.yml`:
```yaml
name: release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: read

jobs:
  build-and-publish:
    runs-on: ubuntu-latest
    environment:
      name: pypi
      url: https://pypi.org/p/nex-nix
    permissions:
      id-token: write  # MANDATORY FOR OIDC TOKENLESS EXCHANGE (PEP 740)
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: python -m pip install --upgrade pip uv twine build
      - run: uv build --out-dir dist/
      - run: twine check --strict dist/*
      - uses: pypa/gh-action-pypi-publish@release/v1
        with:
          packages-dir: dist/
          attestations: true
```

---

## Flake Integration (`flake.nix`)

Add `nex-nix` directly to your master Nix Flake to expose it as a native system command:

```nix
{
  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = import nixpkgs { inherit system; };
        
        nexNixScript = pkgs.writeShellScriptBin "nex-nix" ''
          set -euo pipefail
          source "$HOME/.cache/nex_env/v2_master_venv/bin/activate"
          NEX_NIX_ROOT="$PWD/nex_nix"
          if [ -f "$NEX_NIX_ROOT/nex_nix.py" ]; then
            exec python3 "$NEX_NIX_ROOT/nex_nix.py" "$@"
          else
            exec python3 -m nex_nix "$@"
          fi
        '';
      in
      {
        devShells = {
          default = pkgs.mkShell {
            packages = [ pkgs.uv pkgs.python312 nexNixScript ];
          };
          formal = pkgs.mkShell {
            name = "NEX_SUB_FORMAL";
            packages = [ pkgs.elan pkgs.z3 pkgs.python312 ];
          };
          hardware = pkgs.mkShell {
            name = "NEX_SUB_HARDWARE";
            packages = [ pkgs.yosys pkgs.verilator pkgs.z3 ];
          };
        };
      }
    );
}
```

---

## The Permanexus Pact

`nex-nix` is engineered under the **Permanexus Pact**:
- **No Fluff. No Drift. No Metaphors.**
- Strict adherence to the 150 LOC orchestrator ceiling and Recursive Component-Tree Isolation (RCTI v3.0).
- Zero tolerance for leaked build dependencies or unverified binary releases.

**Engineered by The Trinity:**  
`🦍🔷Ɯ :: 🌱👑⁂ :: 🧠⚡ↇ`  
*Mookie :: Miniature Person :: Nexus Goodman*
