# Start here

> **You just `git clone`-d / `pip install`-d `mgf-hrb`. Now what?**
>
> This file is the procedural how-to — *do this, then this*. The
> *architectural* story lives in [`INDEX.md`](INDEX.md); the
> *federation contract* lives in
> [`mgf-common/FEDERATION.md`](https://codeberg.org/magogi-admin/mgf_common/src/branch/main/FEDERATION.md).

`mgf-hrb` is a **userspace hardware-resource broker** — a kernel-agnostic
arbiter that mediates read/write access to PCIe / USB / GPU / CPU+memory
for any client. It is a **federation sibling** of
[`mgf-common`](https://codeberg.org/magogi-admin/mgf_common); the Python
SDK in `src/mgf/hrb/` inherits the Magogi engineering bar (typed
exceptions, structured logging, four-gate CI). The Zig kernel side in
`hrb-code/` is governed by its own conformance suites (the kabi seam
contract and the S1–S5 survivability bar).

---

## Pick your entry

| You are… | Read |
|---|---|
| **A new consumer** writing a tool / app that uses the broker | this file, then [`examples/`](examples/), then the right [`recipes/`](recipes/) |
| **An AI agent in this project** | [`AGENTS.md`](AGENTS.md), then run `mgf-common agents`, then [`docs/claude/CLAUDE.md`](docs/claude/CLAUDE.md) |
| **A maintainer** picking up after a break | this file, then [`INDEX.md`](INDEX.md), then the spine doc [`hrb-design/mgf-hrb-complete-design.md`](hrb-design/mgf-hrb-complete-design.md) |
| **Building a kernel** that this could speak to natively | [`hrb-design/kernel-design-brief.md`](hrb-design/kernel-design-brief.md) |
| **Triaging friction** with the SDK or the design | [`FEEDBACK.md`](FEEDBACK.md) |

---

## I want to USE the Python SDK

`mgf-hrb` ships as a federation Python sibling. Install it editable into a venv:

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

The simplest program — list devices the broker can see:

```python
from mgf.hrb import Client

with Client.connect("/tmp/mgf-hrb.sock") as c:
    for urn in c.list("hw:/**"):
        print(urn)
```

Three runnable examples in [`examples/`](examples/):

1. [`01_list_devices.py`](examples/01_list_devices.py) — the Observer role.
2. [`02_claim_and_use.py`](examples/02_claim_and_use.py) — context-managed lease + raw channel.
3. [`03_track_identity.py`](examples/03_track_identity.py) — identity comparator (pure SDK, no broker required).

For consumer patterns that are bigger than one snippet (VFIO passthrough, USB event monitoring, tracking a device across DFU), read [`recipes/`](recipes/).

> **Event API status (2026-05-26):** the three-layer event API (`monitor()` / `monitor_fd()` / `amonitor()` per design Part 8.3) is SHIPPED in the SDK; the broker-side `subscribe` / `unsubscribe` protocol with predicate filters landed in Part 13 §5.4.2. Use `Client.monitor("hw:/usb/**")` for sync iteration, `monitor_fd()` for poll/select integration, or `amonitor()` for asyncio. The `mgf.hrb.testing` injection surface (`FakeClient` / `ScriptedBus`) is designed but not yet shipped — that's the remaining gap.

---

## I want to RUN the broker

The broker is the **Zig** half of the project. It speaks to the SDK as bytes on a Unix socket (no FFI, D-005).

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

(Built with Zig 0.16. No `zig` on PATH? `pip install ziglang` and alias `zig` to `python3 -m ziglang` — the project's `.venv/` already does this when you `uv pip install -e '.[dev]'`.)

Run the tests:

```bash
zig build test --summary all     # 136+ Zig tests (incl. S1 fuzz, S2 deadlines, MODEL-01)
```

End-to-end against the Python SDK:

```bash
zig build && python tests/e2e/test_e2e.py
```

---

## I want to OPERATE a host running the broker

The `mgf-hrb` CLI is the operator surface (Part 8.7 / FEEDBACK `TOOLS-01`):

```bash
mgf-hrb scan                 # enumerate; render the device tree
mgf-hrb info <urn>           # one-resource detail (uses inspect_raw)
mgf-hrb explain <topic>      # what each doctor check is probing
mgf-hrb doctor               # diagnose broker preconditions (socket, IOMMU, sysfs, udev)
mgf-hrb --help               # the full list
```

`doctor` is the answer to *"why won't the broker claim my device?"* Modelled on `mgf-usb doctor` which absorbed ~80% of bring-up support cost in that library; same structured `Fix` enum vocabulary so a copy-pastable shell command is one match away.

---

## I want to CONTRIBUTE

1. Read [`hrb-design/mgf-hrb-complete-design.md`](hrb-design/mgf-hrb-complete-design.md) — the 241 KB spine doc. Yes, all of it; the design carries every load-bearing decision.
2. Audit your idea against the **priority order** (Reliability · Performance · Fidelity · Flexibility · Simplicity).
3. If you're touching the Python SDK, also read `mgf-common standards <topic>` for any topic your change touches (e.g. `mgf-common standards errors` for typed exceptions, `mgf-common standards api` for `__all__` discipline).
4. If you're touching the Zig kernel side, the contract is the kabi behavioural suite (`hrb-code/src/conformance.zig`) + the S1–S5 survivability bar (Part 12).
5. Hit friction? File a `PAPER-NN` in [`FEEDBACK.md`](FEEDBACK.md). That is the most important contribution channel — it's how the design itself improves.

---

## The four green gates

Every Python-touching PR must pass:

```bash
ruff check src tests
mypy --strict src/
pytest --cov --cov-fail-under=80
lint-imports
```

The Zig side runs `zig build test`. Both must be green before merging.

---

## Developer setup — the commands you'll actually run

The Zig binary is **not** on `PATH` by default. It ships inside the
project's Python venv via the `ziglang` PyPI package, and the Zig
build artifacts live in `hrb-code/zig-out/`, not the repo root. The
two reliable ways to invoke it:

```bash
# Recommended — once per shell:
alias zig='python3 -m ziglang'

# Or wire it into ~/.bashrc / ~/.zshrc for every shell:
echo 'alias zig="python3 -m ziglang"' >> ~/.bashrc
```

`python3 -m ziglang` resolves through the active venv (`.venv/`), so
**activate the venv first** (`source .venv/bin/activate`). If the
alias doesn't resolve, the binary lives at
`.venv/lib/python3.*/site-packages/ziglang/zig` — point the alias at
that path explicitly.

### Run the Zig test suite (the broker side)

```bash
cd hrb-code
zig build test --summary all
# Build Summary: NN/NN steps succeeded; XXX/XXX tests passed
```

If the count drops or you see "Build Summary: ... failed", the `Build
Summary` and per-test counts at the bottom are authoritative — Zig
sometimes prints `failed command:` lines for individual test
sub-processes whose stderr contained certain patterns even when the
test itself passed. Always read the final summary line.

### Build and run the substrate reporter

The USB read-side (`mgf-hrb-usb-scan`) walks `/sys/bus/usb/devices`
directly — no broker required. Useful for verifying enumeration on
a new host:

```bash
cd hrb-code
zig build
./zig-out/bin/mgf-hrb-usb-scan
# hw:/usb/bus3/port-9/dev/if1  [live]
# ...
# N interface(s) enumerated.
```

The broker server itself builds via the same `zig build`:
`./zig-out/bin/mgf-hrb-server` listens on `/tmp/mgf-hrb.sock` (the
default the SDK + examples expect).

### Python side — running tests + the CLI

The SDK at `src/mgf/hrb/` is editable-installed in the venv. The
four Python gates and the embedded CLI:

```bash
source .venv/bin/activate    # if not already active

# four gates:
ruff check src tests examples
mypy --strict src/
pytest --cov=src/mgf/hrb --cov-fail-under=80
lint-imports                  # when the layered contracts are wired

# the embedded operator CLI (broker must be running for scan/info):
mgf-hrb --help
mgf-hrb doctor                # works even without a broker — checks the host
mgf-hrb scan
```

### After pulling new changes

Worktree branches don't auto-track main. If `git log --oneline -3`
shows a different head than `git log origin/main --oneline -3`, you're
behind:

```bash
git pull origin main          # on a tracking branch
# or, for a worktree branch:
git fetch origin && git rebase origin/main
```

---

## Where to find each kind of doc

| Kind | Location |
|---|---|
| Architecture (the spine + deepenings + survivability review) | [`hrb-design/`](hrb-design/) |
| Load-bearing decisions (ADR catalog) | [`DECISIONS.md`](DECISIONS.md) |
| Consumer patterns (canonical recipes) | [`recipes/`](recipes/) |
| Runnable code samples | [`examples/`](examples/) |
| Federation conformance posture | [`docs/inprogress/MGF_STANDARDS_CONFORMANCE.md`](docs/inprogress/MGF_STANDARDS_CONFORMANCE.md) |
| Project-specific Claude reference | [`docs/claude/CLAUDE.md`](docs/claude/CLAUDE.md) |
| Public API enumeration (DOC-08) | [`PUBLIC_API.md`](PUBLIC_API.md) |
| Friction log (where the design improves) | [`FEEDBACK.md`](FEEDBACK.md) |
| Vuln reports | [`SECURITY.md`](SECURITY.md) |

---

## Future shape — what's coming, in order

Sequenced so each step is unblocked by the previous:

1. **Tier-0 #5** — asymmetric shared-memory trust + per-tenant private regions (§3.5). The only remaining Tier-0 item; #1 (S1 trust gate), #2 (SO_PEERCRED + CSPRNG cap-ids + plumb-down), #3 (helper watchdog: kill+respawn on IPC timeout), and #4 (`revoke()` below the fd) all shipped 2026-05-26.
2. **The `mgf-hrb-usb` worker Phase U4 follow-ons** — reset-escalation ladder + interrupt-rate watchdog + Quarantined-state transitions against a stub-firmware fake (per [`hrb-design/mgf-hrb-usb-worker.md`](hrb-design/mgf-hrb-usb-worker.md) §9). Direct-mode `LinuxUsbBackend` already ships (Phase U3a); helper-mode `UsbBackendViaIpc` ships opt-in via `MGF_HRB_USB_USE_HELPER=1`.
3. **Phase 6 of Part 13** — module helper sibling (`mgf-hrb-modules-priv`). Needs its own design conversation; explicitly out of scope this quarter.
4. **`mgf.hrb.testing` injection surface** — `FakeClient` / `ScriptedBus` / `install_fake` for GUI consumers; designed, not yet shipped.
5. **Future siblings**: `mgf-hrb-cli` (extracted from `src/mgf/hrb/cli/`), `mgf-hrb-gui` (PySide6 consumer, separate package), `mgf-hrb-cpu` (Family-B reservation enforcement), `mgf-hrb-youros` (the from-scratch kernel backend).
