# mgf-hrb — Phases 1–7 Skeleton (constellation + Python SDK + fd-passing + S1 trust gate + S2 deadlines)

The seam and the reliability heart, proven in running Zig. From the mgf-hrb
design (`hrb/mgf-hrb-complete-design.md`): Phase 1 = the seam; Phase 2 = the
lease engine. **136 Zig tests + 7 Python↔Zig E2E checks.** Live constellation;
Python SDK over a socket with ZERO FFI; ring @ 822M items/sec; **the S1 trust
gate** (Part 12 §3.2) — no client byte panics the broker, fuzz-verified;
**deadlines on every kabi op** (D-029 / Part 12 §2.2) — `Err.Timeout` is a
typed outcome and atomicity holds through the timeout path. The architecture
is validated end-to-end before any hardware is touched.

## What's here

| File | Sibling | Role |
|------|---------|------|
| _(carved)_ `mgf-hrb-model` | `mgf-hrb-model` | Resource algebra. Depends on nothing (Part 2). **Now its own repo** — consumed as a package dep (E2); see "Carved dependencies" below. |
| `src/kabi.zig` | `mgf-hrb-kabi` | Abstract kernel seam — 9 operations (Part 6.2). No Linux noun. |
| `src/core.zig` | `mgf-hrb-core` | **The lease engine** — ownership truth, claim lattice, atomic grant, liveness reclamation (Part 3). |
| `src/cap.zig` | `mgf-hrb-cap` | **The capability engine** — unforgeable attenuable rights; attenuation only ever shrinks (Part 4). |
| `src/cap_test.zig` | suite | Capability-model tests: monotone attenuation, `raw`-as-its-own-right, end-to-end. |
| `src/liveness.zig` | `mgf-hrb-rt` | **The LivenessSource** — connection-death + heartbeat, the signal that makes G3 real (Part 5.5). |
| `src/liveness_test.zig` | suite | Liveness tests using REAL sockets: a closed socket drives lease reclamation. |
| `src/linux_backend.zig` | `mgf-hrb-linux` | **The real backend** — genuine sysfs PCI enumeration via raw syscalls; honest-Unsupported acquire without VFIO (Part 6.5). |
| `src/linux_test.zig` | suite | Tests against REAL hardware: enumerates this machine's actual PCI devices through the same seam. |
| `src/facade.zig` | `mgf-hrb-facade` | **Router + supervisor** — routes by scope to per-bus workers; cross-worker reclamation (Part 7). |
| `src/facade_test.zig` | suite | THE CONSTELLATION: 2 workers + facade + caps + real-socket liveness, end to end. |
| `src/server.zig` | broker exe | Listens on a Unix socket, drives the facade — the Zig side of the no-FFI boundary. |
| `src/fdpass.zig` | `mgf-hrb-rt` | **SCM_RIGHTS fd-passing** — how authority/raw-channels cross the boundary (Part 5.4). |
| `src/fdpass_test.zig` | suite | Real fd transfer + the SURVIVABILITY dividend: an fd works after the sender closes its copy. |

| `src/fake_backend.zig` | (test) | In-memory, contract-conformant backend (Part 6.4). No hardware. |
| `src/conformance.zig` | suite | Behavioral seam-contract tests, runnable against ANY backend (Part 6.4). |
| `src/core_test.zig` | suite | Lease-engine reliability tests (the priority-#1 guarantees). |
| `src/request.zig` | broker (trust gate) | **The S1 hardened decode layer** (Part 12 §3.2): bytes → typed `Request` via typed extractors; nothing past the gate ever reads `std.json.Value`. |
| `src/request_test.zig` | suite | The **S1 conformance suite**: type-confusion, missing-field, oversized-input cases + a 7 000-iteration fuzzer asserting random bytes only ever yield `BadRequest` or a valid `Request` — never a panic. |
| `src/identity.zig` | `mgf-hrb-model` (identity) | The **runtime identity-continuity comparator** (FEEDBACK MODEL-01): `Snapshot` + `sameLikely()` → `{SAME, LIKELY_SAME, AMBIGUOUS, DIFFERENT}`. Per `hrb-design/mgf-hrb-usb-worker.md` §4.3; weights validated against the `mgf-usb` v0.2.5 iFig DFU sequence. |
| `src/identity_test.zig` | suite | Pins the comparator against the spec's three named scores (Recovery↔DFU = 11, Normal→Recovery = 15, identical = 13) + boundary cases for serial asymmetry, port mismatch, debounce window, and the explained-form transparency. |

## Carved dependencies (E2)

Some siblings have been carved into their own Codeberg repos and are
consumed as Zig package dependencies (pinned by commit + content hash in
`build.zig.zon`): currently **`mgf-hrb-model`**.

Those repos are PRIVATE (under the limited-visibility `magogi-admin`
account) and zig's git client ignores `~/.netrc`, so a **cold-cache build
cannot fetch them from the clean URLs**. Populate zig's global cache
first:

```bash
scripts/zig-fetch-deps     # injects a token, fetches each dep by hash
```

Token source: `$CODEBERG_TOKEN` (set this as a **CI secret**), else the
gitignored `my_stuff/ssh_key/codeberg_token.txt` for local dev. The token
is never written to a committed file. Once the cache is warm, `zig build`
resolves every dep by hash with no network.

## Run it

```bash
# from the repo root:
source .venv/bin/activate
alias zig='python3 -m ziglang'    # the binary ships inside the venv

scripts/zig-fetch-deps            # one-time: cache the carved deps (see above)
cd hrb-code
zig build test --summary all     # Zig test suite (incl. S1 fuzz + MODEL-01 + S2 deadlines + USB U1/U2a)
zig test -OReleaseFast src/ring_test.zig   # ring benchmark (~822M items/sec)

zig build                         # builds mgf-hrb-server + mgf-hrb-usb-scan
./zig-out/bin/mgf-hrb-usb-scan    # walk /sys/bus/usb/devices, print the live tree
```

(Zig 0.16. No system zig needed — the `ziglang` package ships the binary.)

The Python ↔ Zig end-to-end check (7 checks in one process) lives at
[`tests/e2e/test_e2e.py`](../tests/e2e/test_e2e.py); see "no-FFI boundary" below.

> **`failed command:` noise.** Zig sometimes prints `failed command: …`
> lines for individual test sub-processes whose stderr matched certain
> patterns, even when the test itself passed. The final `Build Summary:
> N/N steps succeeded; X/X tests passed` line is authoritative.

## What's proven (each test = a guarantee from the design, in code)

Conformance (the seam contract — your future kernel's acceptance test):
- enumerate respects scope; missing scope → empty not error
- acquire all-or-nothing; double-exclusive conflicts; observe never conflicts
- release total + idempotent; G3 safe-reset on release; atomicity on failed acquire
- reset achieves safe state or fails honestly (G2); G1 raw-only-when-owned

Core lease engine (the reliability heart — priority #1):
- claim creates a live lease; the claim lattice (exclusive/shared/observe) holds
- **G3: client death reclaims ALL its leases — ghost ownership is impossible**
- G3: one client's death never touches another's leases (isolation)
- **atomicity: a failed hardware acquire leaves zero leases and a safe resource**
- release idempotent; G1/G4: raw channel only for the holder, gone after release

## The atomicity design, made real

`Core.claim` (core.zig) reserves table capacity BEFORE touching hardware, so the
commit after a successful acquire is infallible. Result: there is no error window
between "hardware acquired" and "lease committed" — the ownership table can never
claim a device the backend doesn't hold. Reliability (#1) over a micro-optimization,
exactly as the design's priority order dictates. The test
`core atomicity: a failed hardware acquire leaves no lease` proves it.


Capability model (the security spine — Part 4):
- a capability permits exactly its scope, rights, and mode ceiling — nothing ambient
- **attenuation only ever SHRINKS** — widening scope, rights, or ceiling is refused (the monotone invariant)
- `raw` is a SEPARATE right from claim — controlling a device ≠ poking its registers directly
- end-to-end: the core enforces capabilities on the grant path BEFORE touching hardware;
  a claim-only cap is refused `raw` even while holding the lease


Liveness (the G3 chain, end-to-end with REAL sockets — Part 5.5):
- a CLOSED socket (a dead client) is detected by the kernel and drives the core
  to reclaim ALL that client's leases and safe-reset the devices — no mocks
- a LIVE socket is never reclaimed (no false positives)
- pending protocol data is peeked, not consumed, so it doesn't look like death
- heartbeat backstop reclaims a HUNG client (connection open, but wedged)
- a heartbeat resets the miss counter, so healthy clients survive

This closes the one hand-waved seam from Phase 2: `holderDied` is no longer just
called directly in a test — it is driven by genuine kernel-sourced connection
death. The future kernel makes signal (1) total and retires the heartbeat
(kernel-design-brief Feature 2).


Linux backend (the seam meets REAL hardware — Part 6.5):
- `enumerate` reads this machine's ACTUAL /sys/bus/pci/devices via raw syscalls
  (openat + getdents64 + read) — the "Level 2: direct syscalls, no libpci" path.
  In this sandbox it found 7 real PCI devices, each with a `live` fidelity tag.
- it plugs into the EXACT SAME `KernelBackend` seam the fake implements — the
  core cannot tell them apart (LSP/substitutability proven in code)
- `acquire`/`reset` return **Unsupported** (honest, G2) when /dev/vfio is absent —
  never a fake success. The VFIO bind path is structurally written but needs a
  host with real IOMMU to exercise.

What this proves: the seam abstraction holds against genuine hardware facts, not
just the fake. The conformance suite (which CAN exercise acquire) runs against
the fake today and would run UNCHANGED against this backend on a VFIO-capable host.


The CONSTELLATION (everything composed, Part 7):
- two per-bus workers (PCI + USB) behind one facade; claims routed by URN scope
- a client's death reclaims its leases across BOTH workers; other clients untouched (failure isolation)
- capability-gated, routed, lease-enforced — all proven pieces running as one system
- **real client-socket death drives reclamation across the whole constellation**

The no-FFI boundary, PROVEN end-to-end (Part 8.1):
- a real Python client (`src/mgf/hrb/` — the `mgf.hrb` package) talks to the real Zig broker over a Unix socket
- Python links ZERO Zig, shares no memory — just bytes on the socket
- list / claim / raw / release all work; a Zig-side Conflict surfaces as a clean Python exception
- run it:  `zig build && python ../tests/e2e/test_e2e.py`


fd-passing & the survivability dividend (Part 5.4 / 7.4):
- a real fd is sent over a socket via SCM_RIGHTS and arrives as a usable handle
- **the fd keeps working after the sender (broker) closes its copy and vanishes**
  — proving "mediate ownership, delegate usage": once granted, use is broker-independent (G4)
- the receiver gets an independent fd number (the kernel duplicated it)

## Next

- VFIO `acquire` on a real host — `linux_backend.zig` returns honest `Unsupported` today; needs `/dev/vfio` + IOMMU to exercise.
- `mgf-hrb-usb` worker — designed in [`hrb-design/mgf-hrb-usb-worker.md`](../hrb-design/mgf-hrb-usb-worker.md), not yet coded.
- netlink `watch` — currently an honest stub; needs the broker-side subscription protocol.
- Remaining Tier-0 survivability passes (Part 12): unforgeable + connection-bound capabilities (§3.3), per-worker watchdog (§2.2), `revoke()` below the fd (§3.4), asymmetric shm trust (§3.5).
- `mgf-hrb-youros`: your kernel's backend. When the conformance suite passes
  against it, the whole userspace lifts over unchanged (`hrb-design/kernel-design-brief.md`).
