# mgf-hrb — Magogi Foundation Hardware Resource Broker

> **Replaces:** `mgf-usb` (deleted 2026-05-27). See [`MIGRATION_FROM_MGF_USB.md`](MIGRATION_FROM_MGF_USB.md) for the supersession statement + what was carried forward.
> **Shape.** Federation Python library (sibling of [`mgf-common`](https://codeberg.org/magogi-admin/mgf_common)); pins `mgf-common>=0.38,<0.39`. The Zig **broker** ships alongside the SDK in this same repo (`hrb-code/`) so the two sides of the no-FFI boundary stay in lockstep.
> **Conformance level.** **L2 — Standard** (flipped 2026-05-24 after the loggers + `HrbSettings` + LG-rationale pass; see [`docs/inprogress/MGF_STANDARDS_CONFORMANCE.md`](docs/inprogress/MGF_STANDARDS_CONFORMANCE.md) §4 for the audit log).
> **Status.** Phases 1–7 of the design are in code; Part 13 (self-aware introspection) shipped 21/21 sub-features in May 2026; Tier-0 survivability #1/#2/#3/#4 all landed (only #5 — asymmetric shm trust — remains). Gates green: **308 Zig tests** (broker; ~44 more in the carved leaf repos) **+ 466 Python tests** (default suite); marker-gated stress/perf/e2e add ~94 more. Zero-FFI Python↔Zig over a Unix socket; S1 trust gate; S2 deadlines on every kabi op; runtime identity-continuity comparator (MODEL-01); privileged-helper subprocess (D-031) opt-in via `MGF_HRB_USB_USE_HELPER=1`.

A userspace **hardware-resource broker** that arbitrates read/write access to all hardware (PCIe, USB, GPU, CPU/memory) for any client — reliable, fast, complete, impossible to need to bypass. Designed kernel-agnostic so it lifts onto a from-scratch capability-based OS by writing one backend.

**Priority order:** Reliability · Performance · Fidelity · Flexibility · Simplicity.
**Languages:** Zig below the socket (enforcement, hardware, hot path) · Python above it (ergonomics, policy, tooling).

---

## Repo shape

```
mgf-hrb/
├── README.md                this file
├── STARTHERE.md             procedural how-to
├── INDEX.md                 deep entry point (links to design, code, decisions, recipes)
├── LICENSE  CHANGELOG.md  SECURITY.md  FEEDBACK.md  USERS.md  PUBLIC_API.{md,json}
├── pyproject.toml           Python library packaging
├── src/mgf/hrb/             the Python SDK + embedded CLI
│   ├── __init__.py          public surface (see PUBLIC_API.md)
│   ├── _client.py · domain.py · identity.py · exceptions.py
│   └── cli/                 mgf-hrb console script (scan / info / doctor / explain)
├── tests/
│   ├── unit/mgf/hrb/        pytest tree mirroring src/
│   └── e2e/                 Python ↔ Zig over a real socket
├── examples/                runnable consumer snippets
├── hrb-code/                the Zig broker (kernel side; 308 Zig tests)
├── hrb-design/              the design corpus (spine + 4 deepenings + survivability review)
├── recipes/                 canonical consumer patterns
├── docs/
│   ├── claude/CLAUDE.md     project-specific Claude reference (DOC-07)
│   ├── inprogress/MGF_STANDARDS_CONFORMANCE.md
│   ├── standards/README.md  pointer-only → mgf-common (DOC-02 §2.0.4)
│   └── cutover/             (empty until first breaking change)
├── DECISIONS.md             ADR catalog (35 D-NNN decisions)
└── STANDARDS_NOTE.md        the *argument* behind the conformance posture
```

---

## Quick start

**Install the Python SDK** (editable, with dev tools):

```bash
git clone <repo-url> mgf-hrb && cd mgf-hrb
uv venv && uv pip install -e '.[dev]'
```

**Run the broker** (Zig, from this same repo):

```bash
cd hrb-code
zig build && ./zig-out/bin/mgf-hrb-server
# → mgf-hrb broker listening on /tmp/mgf-hrb.sock
```

(Zig 0.16 — no `zig` on PATH? `uv pip install ziglang` and alias `zig` to `python3 -m ziglang`.)

**Smallest useful program:**

```python
from mgf.hrb import Client, ClaimMode

with Client.connect("/tmp/mgf-hrb.sock") as c:
    # Enumerate (read-only, never claims):
    for urn in c.list("hw:/**"):
        print(urn)

    # Peek at one URN's metadata (vid/pid/driver/etc), still read-only:
    detail = c.inspect("hw:/usb/bus3/port-9/dev/if0")
    print(detail["attrs"])

    # Claim exclusively; lease auto-releases at block exit (DP-13):
    with c.claim("hw:/usb/bus3/port-9/dev/if0", ClaimMode.EXCLUSIVE) as lease:
        ch = lease.raw()          # SCM_RIGHTS-passed fd; broker steps out (G4)
        ...                       # use `ch["fd"]` directly with USBDEVFS ioctls
```

**Operator CLI:**

```bash
mgf-hrb scan                 # enumerate, render the device tree
mgf-hrb doctor               # diagnose broker preconditions (socket, IOMMU, sysfs)
mgf-hrb --help
```

**Test suites:**

```bash
scripts/zig-fetch-deps                          # cache carved Zig deps (one-time)
cd hrb-code && zig build test --summary all     # 308 Zig tests (broker)
zig build && pytest tests/e2e -m e2e             # Python↔Zig E2E (marker-gated)
pytest                                            # 466 Python tests (default suite)
scripts/mtest --tier 0-1 --budget 60s            # budget-aware supervisor (recommended)

scripts/publish-wheel                             # build + verify the SDK wheel (dry run)
scripts/publish-wheel --upload                    # …and publish it (CI / release)
```

The Python SDK (`src/mgf/hrb/`) is published as a `pip install`-able wheel
**from this monorepo** — the broker and SDK deliberately stay in one repo
so the two sides of the no-FFI wire protocol never skew. See
`scripts/publish-wheel`.

---

## Where to read next

| You want… | Start at |
|---|---|
| The procedural how-to | [`STARTHERE.md`](STARTHERE.md) |
| The architectural story | [`INDEX.md`](INDEX.md) → [`hrb-design/mgf-hrb-complete-design.md`](hrb-design/mgf-hrb-complete-design.md) |
| The runnable examples | [`examples/`](examples/) |
| The canonical consumer patterns | [`recipes/`](recipes/) |
| The public Python API | [`PUBLIC_API.md`](PUBLIC_API.md) |
| The kernel acceptance test (your future OS) | [`hrb-design/kernel-design-brief.md`](hrb-design/kernel-design-brief.md) + [`hrb-code/src/conformance.zig`](hrb-code/src/conformance.zig) |

---

## Federation

This project depends on `mgf-common` and follows the Magogi engineering bar **to the extent it applies to a dual-language Zig/Python project.** The Python SDK inherits typed exceptions (EH-01 / EH-02), four-gate CI, the AP / DP / TS / DOC rule families. The Zig kernel side is governed by its own conformance contracts — the kabi behavioural suite (`hrb-code/src/conformance.zig`) and the S1–S5 survivability bar ([Part 12](hrb-design/mgf-hrb-survivability-review.md)). See [`STANDARDS_NOTE.md`](STANDARDS_NOTE.md) for the deeper reasoning and [`docs/inprogress/MGF_STANDARDS_CONFORMANCE.md`](docs/inprogress/MGF_STANDARDS_CONFORMANCE.md) for the per-rule audit.

For AI agents: run **`mgf-common agents`** for the canonical federation briefing, then [`docs/claude/CLAUDE.md`](docs/claude/CLAUDE.md) for the project-specific Claude reference.

---

## License

[MIT](LICENSE).
