Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/patches/88851cbfd1a8a61d # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## Recovery media: package /boot/efi and root repair tools in the initrd (issue #17) merged `88851cbfd1a8a61d` #55 · opened 2026-09-24 12:47 UTC · closed 2026-09-24 14:36 UTC · merged 2026-09-24 14:36 UTC Imported from GitHub aien-dev/aienux#55, by Copilot Base `a1babb4d25544b9b5ab4becd4ba97cf45f42a2c9` · Head `af8ec740c4423aebb1ce84a7f370d6c081981026` Merged on GitHub as `fdff1dbee8586146d5c8680e493acaac184cd186`; reachable from main `d01b2f19cccf3e173a6bdb3541813d467f537a76` (observed 2026-11-18T16:35:40Z) Copilot wrote on 2026-09-24 12:47 UTC Reworked into a small, rule-compliant PR at the maintainer's request (rebase on main, don't replace `scripts/build_recovery_media.sh` or `scripts/build_standalone_recovery_initrd.sh`, keep only what's still missing for issue #17). Verified locally: ``` $ bash scripts/verify_recovery_tools.sh /tmp/aienos-recovery-standalone-initrd.img ... -- required tools for /boot/efi repair -- PASS fsck.vfat present PASS mkfs.vfat present PASS fsck.ext4 present PASS efibootmgr present -- required tools for boot-entry restore -- PASS efibootmgr present (boot entries) PASS chroot present ... RECOVERY_TOOLS: PASS (initrd ships mount, EFI repair, and boot-entry restore capability) $ bash scripts/verify_all.sh ... --- [Recovery Media Tooling Manifest] --- ... RECOVERY_TOOLS: PASS (initrd ships mount, EFI repair, and boot-entry restore capability) RC=0 ``` Full `verify_all.sh` run: all steps PASS, including Gate 1 QEMU zero-disk recovery, Gate 4 security suite (swTPM + 3-run soak + fault injection), and the new Recovery Media Tooling Manifest step. No FAIL anywhere. rc=0. ## What issue #17 still needed The recovery initrd from #53 already boots Machine 1 with Secure Boot on, mounts the driver stack for the NVMe/USB/keyboard, and returns to Linux unattended (Gate 1 selftest evidence ). What it didn't ship yet were the tools issue #17's "done when" clause needs to actually repair `/boot/efi` and check the mounted root: `fsck.vfat`, `mkfs.vfat`, `fsck.ext4`, `chroot`. ## What changed (10 files, +429/-8) - `scripts/build_standalone_recovery_initrd.sh`: minimal, additive patch (+7/-0) to the existing `BINARIES` array -- adds `fsck.vfat`, `mkfs.vfat`, `fsck.ext4`, `chroot` with their shared libraries, following the script's existing copy pattern. No restructuring. - `scripts/verify_recovery_tools.sh` (new): host-only, no real devices, no root. Extracts the built initrd and checks that it ships the mount / EFI-repair / boot-entry-restore tooling and init hooks. Wired into `scripts/verify_all.sh` (step 9) since it needs only `gzip`/`cpio`. - `scripts/collect_recovery_boot_evidence.sh` (new): evidence collector for the attended recovery boot on Machine 1. Read-only -- it inspects mount state, filesystem presence, and firmware variables the kernel already exposes read-only; it never writes to the ESP, the NVMe root, or BootOrder. - `docs/RECOVERY_MEDIA_MACHINE1.md` (new): operator runbook rewritten to match main's actual mechanics post-#53 -- the `AIENOSRECOV` stick name (not the retired `ATLAS_RECOV`), the real script names, and the actual shell-based repair steps (no invented rescue-menu system). States plainly that the stick must be rebuilt with the new tools and the attended boot re-run before issue #17 can close. - `evidence/recovery_boot_machine1.md` (new): honest `PENDING ATTENDED EXERCISE` template. No "merged"/"verified" language and no hardware-boot claim -- the physical repair boot has not happened. - Small pointer edits (`ROADMAP.md`, `docs/MILESTONES.md`, `docs/NATIVE_BOOT_ONE_TIME.md`, `docs/TRUST-1-IMPLEMENTATION-PLAN.md`) linking to the new runbook and correcting stale status text. ## What was dropped from the earlier draft, and why - The ~250-line rewrite of `scripts/build_standalone_recovery_initrd.sh`'s init/menu system (custom `aienos-efi-repair` helper, interactive rescue menu, LVM activation). Out of scope per the maintainer's request; main already has a working shell-based flow from #53, and the operator has full tool access from the plain shell without a bespoke menu layer. - The edit to `evidence/gate1_zero_disk_recovery_receipt.json` -- an existing evidence file that must not change. - The change to `scripts/build_recovery_media.sh` -- not needed for the tooling gap this PR closes. - Deletions of unrelated files (`docs/HARDWARE_TEST_RIG.md`, ADRs 0010/0011, `crates/aienos-kernel/src/usb/hid.rs`, etc.) that were artifacts of the draft branch predating several since-merged PRs (#52-#60). This branch is now rebased cleanly on current `main` (comparing `main...copilot/bootable-recovery-media-machine-1` shows exactly these 10 files, ahead 5 / behind 0). ## What is NOT claimed No hardware boot happened as part of this change. The `AIENOSRECOV` stick as last written (#53) predates these repair tools. The operator must rebuild the stick with `scripts/build_recovery_media.sh` and re-run the attended boot in `docs/RECOVERY_MEDIA_MACHINE1.md` before issue #17 can close -- that is exactly what `evidence/recovery_boot_machine1.md` is a pending template for. 🤖 Generated with Claude Code SECURITY_IMPACT: RECOVERY ### Fetch it A git bundle of the pull request's head, 76306 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aienux/patches/88851cbfd1a8a61d.bundle -o 88851cbfd1a8a61d.bundle git fetch 88851cbfd1a8a61d.bundle refs/pull/55/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 55 af8ec740c4423aebb1ce84a7f370d6c081981026 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":55,"url":"https://github.com/aien-dev/aienux/pull/55","export_sha256":"222ed873664c8b6770fec92487a3521a4b5f81629ee6399038e519facf854bee","imported_utc":"2026-11-18T16:35:40Z"} ``` ### Changes ``` diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 00000000..6217f701 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,63 @@ +# Instructions for coding agents working on AIENOS + +Read `CONTRIBUTING.md`, `CONTEXT.md` (domain language) and `docs/MILESTONES.md` +(gate order and escalation triggers) before starting. They are binding. This +file adds what agents most often get wrong here. + +## Finish line for every pull request + +1. `bash scripts/verify_all.sh` passes. Paste the command and the tail of its + output (the PASS/FAIL lines) at the top of the PR description. +2. On an x86 runner some steps print `SKIPPED` (AArch64-only recovery tests, + KVM). Say which steps skipped; never describe a skipped step as passing. +3. The PR description ends with one line `SECURITY_IMPACT: `, one of + NONE, BOUNDARY, ROOT_OF_TRUST, AUTHORITY, RECOVERY, PERSISTENT_FORMAT. + Anything in the kernel privilege path, capabilities, AEGIS, storage unlock, + crypto or recovery is not NONE. +4. One concern per PR, and keep it reviewable: aim for under 600 changed + lines. Split larger work into a series and say what comes next. + +## Hard rules + +- Rust only (small AArch64 assembly where hardware demands it). No Python, no + shell scripts that fetch from the network, no CUDA or CUDA-shaped APIs. +- No systemd anywhere: no units, no systemd-creds, no journald, no emulation + of them. AIENOS has its own init and supervision. +- No new crates in the kernel, boot or trusted-base crates unless the issue + asks for one. Elsewhere, justify each new dependency in the PR. +- The kernel must work with no AI model loaded. Models never run in the + kernel and never hold authority. +- Never claim hardware behavior. Only QEMU and host-test results can be + claimed; Machine 1 (DGX Spark) evidence is produced by maintainers. +- Do not edit existing files in `evidence/`, the recovery scripts + (`scripts/build_recovery_media.sh`, `scripts/build_standalone_recovery_initrd.sh`, + `scripts/qemu_verify_recovery_media.sh`), signing or key tooling, or + `.github/workflows/`, unless the issue explicitly asks for it. +- No secrets, keys, personal data or photos in the repository. +- Docs and comments: plain language, no em dashes or en dashes. + +## Kernel ordering (Milestone 3) + +ADR 0009 is accepted: the kernel moves from EL2 to EL1h before anything else in +M3. Until that change is on `main`, do not implement MMU page tables, exception +vector changes, interrupt or timer bring-up, task switching or EL0 entry, even +if an issue seems to ask. Host-testable logic (pure Rust with unit tests, no +system registers) is fine and preferred: build it so the EL1 kernel can adopt +it later. + +## ADRs + +Check `docs/adr/` **and open pull requests** for the next free ADR number +before writing one, update `docs/adr/README.md`, and start with +`Status: Proposed.` Only the operator accepts ADRs. + +## Useful commands + +```bash +rustup target add aarch64-unknown-uefi aarch64-unknown-none +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +cargo build -p aienos-kernel --target aarch64-unknown-none --no-default-features +bash scripts/qemu_boot_test.sh # UEFI boot in QEMU, needs qemu-system-aarch64 + AAVMF +bash scripts/verify_all.sh # everything +``` diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml new file mode 100644 index 00000000..fd4c9963 --- /dev/null +++ b/.github/workflows/copilot-setup-steps.yml @@ -0,0 +1,29 @@ +name: Copilot setup steps + +# Prepares the Copilot coding agent's environment with the same toolchain and +# emulator packages as scripts/verify_all.sh needs. Runs only for the agent or +# when started by hand. +on: workflow_dispatch + +jobs: + copilot-setup-steps: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-unknown-none, aarch64-unknown-uefi + components: clippy, rustfmt + + - name: Install QEMU, AAVMF firmware and swtpm + run: | + sudo apt-get update + sudo apt-get install -y qemu-system-arm qemu-efi-aarch64 swtpm swtpm-tools + + - name: Warm the cargo cache + run: cargo fetch --locked diff --git a/ROADMAP.md b/ROADMAP.md index c7e187b7..312bb46a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -12,13 +12,15 @@ M0 PARTIAL Reference freeze reference snapshot PASS benchmark evidence PASS 54.2 tokens/s CPU decode baseline native-boot rollback PASS - bootable recovery media PENDING + bootable recovery media boots on hardware (#53); repair-tool rebuild + + attended repair boot pending (docs/RECOVERY_MEDIA_MACHINE1.md) M1 IN PROGRESS Emulator boot automated QEMU boot IN PROGRESS M2 PASS First native Spark boot (2026-09-24) - follow-ups: observability, console, GB10 discovery, keyboard, test rig + follow-ups: observability, console, GB10 discovery, keyboard, + test rig (design: docs/HARDWARE_TEST_RIG.md) NEXT HARD GATE: recovery media -> QEMU regression boot -> M3 kernel isolation @@ -36,7 +38,9 @@ and returned to Linux undamaged. Full record: M0 Reference freeze -> M1 Emulator boot -> M2 Spark bring-up - -> M3 Kernel isolation + -> SEED-0A Self-construction lab agent-built candidates proven in QEMU, never admitted + -> M3 Kernel isolation the enforcement substrate + -> SEED-0B Native capability admission -> M4 Storage and recovery -> M5 Encryption and identity -> M6 Minimal networking @@ -44,6 +48,12 @@ M0 Reference freeze -> M8 Persistent agent first vision proven ``` +SEED-0A and SEED-0B come from [ADR 0012](docs/adr/0012-self-construction-capability-growth-and-generations.md): +each machine grows the capabilities it needs as reversible, numbered +Generations admitted by deterministic gates. Generated native code reaches the +physical machine only after M3 can confine it. SEED-0A experiment #1 is +`input.keyboard.usb` ([#58](https://github.com/aien-dev/aienos/pull/58)). + The first public demonstration is M8: power on, AIENOS boots, you talk to the local agent, power off, power on, and it remembers. @@ -51,9 +61,9 @@ local agent, power off, power on, and it remembers. | Gate | Milestone (live progress) | Open work | Done so far | | --- | --- | --- | --- | -| M0 Reference freeze | [M0](https://github.com/aien-dev/aienos/milestone/1) | [#17](https://github.com/aien-dev/aienos/issues/17) recovery media | [#12](https://github.com/aien-dev/aienos/pull/12) Rust evidence tooling and clean snapshot ([9bd233d](https://github.com/aien-dev/aienos/commit/9bd233d)) | +| M0 Reference freeze | [M0](https://github.com/aien-dev/aienos/milestone/1) | [#17](https://github.com/aien-dev/aienos/issues/17) recovery media: repair-tool rebuild + attended repair boot pending ([procedure](docs/RECOVERY_MEDIA_MACHINE1.md)) | [#12](https://github.com/aien-dev/aienos/pull/12) Rust evidence tooling and clean snapshot ([9bd233d](https://github.com/aien-dev/aienos/commit/9bd233d)) | | M1 Emulator boot | [M1](https://github.com/aien-dev/aienos/milestone/2) | [#18](https://github.com/aien-dev/aienos/issues/18) QEMU boot, [#19](https://github.com/aien-dev/aienos/issues/19) CI | QEMU 8.2 and AAVMF chosen as the emulator | -| M2 Spark bring-up | [M2](https://github.com/aien-dev/aienos/milestone/3) | [#20](https://github.com/aien-dev/aienos/issues/20) pre-exit file, [#21](https://github.com/aien-dev/aienos/issues/21) screen evidence, [#22](https://github.com/aien-dev/aienos/issues/22) UART via SPCR, [#23](https://github.com/aien-dev/aienos/issues/23) GB10 discovery, [#24](https://github.com/aien-dev/aienos/issues/24) USB keyboard, [#25](https://github.com/aien-dev/aienos/issues/25) test rig | Gate passed: [#10](https://github.com/aien-dev/aienos/pull/10) memory handoff, [#11](https://github.com/aien-dev/aienos/pull/11) GB10 identity, [#13](https://github.com/aien-dev/aienos/pull/13) visible report ([a22b1d8](https://github.com/aien-dev/aienos/commit/a22b1d8)), [#14](https://github.com/aien-dev/aienos/pull/14) CPU topology ([44fcba7](https://github.com/aien-dev/aienos/commit/44fcba7)), [#15](https://github.com/aien-dev/aienos/pull/15) first-boot image ([52109bc](https://github.com/aien-dev/aienos/commit/52109bc)), [#16](https://github.com/aien-dev/aienos/pull/16) evidence ([f376589](https://github.com/aien-dev/aienos/commit/f376589)) | +| M2 Spark bring-up | [M2](https://github.com/aien-dev/aienos/milestone/3) | [#20](https://github.com/aien-dev/aienos/issues/20) pre-exit file, [#21](https://github.com/aien-dev/aienos/issues/21) screen evidence, [#22](https://github.com/aien-dev/aienos/issues/22) UART via SPCR, [#23](https://github.com/aien-dev/aienos/issues/23) GB10 discovery, [#24](https://github.com/aien-dev/aienos/issues/24) USB keyboard, [#25](https://github.com/aien-dev/aienos/issues/25) test rig ([design](docs/HARDWARE_TEST_RIG.md)) | Gate passed: [#10](https://github.com/aien-dev/aienos/pull/10) memory handoff, [#11](https://github.com/aien-dev/aienos/pull/11) GB10 identity, [#13](https://github.com/aien-dev/aienos/pull/13) visible report ([a22b1d8](https://github.com/aien-dev/aienos/commit/a22b1d8)), [#14](https://github.com/aien-dev/aienos/pull/14) CPU topology ([44fcba7](https://github.com/aien-dev/aienos/commit/44fcba7)), [#15](https://github.com/aien-dev/aienos/pull/15) first-boot image ([52109bc](https://github.com/aien-dev/aienos/commit/52109bc)), [#16](https://github.com/aien-dev/aienos/pull/16) evidence ([f376589](https://github.com/aien-dev/aienos/commit/f376589)) | | M3 Kernel isolation | [M3](https://github.com/aien-dev/aienos/milestone/4) | [#26](https://github.com/aien-dev/aienos/issues/26) vectors, [#27](https://github.com/aien-dev/aienos/issues/27) MMU, [#28](https://github.com/aien-dev/aienos/issues/28) timer and GIC, [#29](https://github.com/aien-dev/aienos/issues/29) topology-aware scheduler, [#30](https://github.com/aien-dev/aienos/issues/30) IPC and capabilities | Frame allocator, bounded UART, fault capture used on the first boot | | M4 Storage and recovery | [M4](https://github.com/aien-dev/aienos/milestone/5) | [#31](https://github.com/aien-dev/aienos/issues/31) NVMe and System Store | Host-tested store and WAL recovery | | M5 Encryption and identity | [M5](https://github.com/aien-dev/aienos/milestone/6) | [#32](https://github.com/aien-dev/aienos/issues/32) | Host-tested agent identity (ADR 0007) | @@ -64,7 +74,8 @@ local agent, power off, power on, and it remembers. Separate lanes that never block the critical path: [#36](https://github.com/aien-dev/aienos/issues/36) GB10 characterization (no GPU execution yet) and [#37](https://github.com/aien-dev/aienos/issues/37) Fabric -(after native networking). +(after native networking; early design in +[ADR 0010](docs/adr/0010-fabric-machine-identity-and-capability-advertisement.md)). Related repositories: [aien-sovereign-core](https://github.com/aien-dev/aien-sovereign-core) holds the AIEN runtime, Cortex, AEGIS and `aien-proof`, the shared test board diff --git a/crates/aienos-accel/src/lib.rs b/crates/aienos-accel/src/lib.rs index fe548acb..c112d7a5 100644 --- a/crates/aienos-accel/src/lib.rs +++ b/crates/aienos-accel/src/lib.rs @@ -1,5 +1,7 @@ #![no_std] +use core::fmt::Write; + /// PCI identity observed for the GB10 GPU in the DGX Spark. pub const NVIDIA_VENDOR_ID: u16 = 0x10de; pub const GB10_DEVICE_ID: u16 = 0x2e12; @@ -58,9 +60,72 @@ pub struct Gb10Identity { pub pmc_boot_42: u32, } +/// Outcome for one PCI root bridge during GB10 discovery, carried into the +/// boot reports so a missed discovery says why. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RootBridgeOutcome { + /// The firmware refused the open of `PciRootBridgeIo` (status name). + OpenRefused(&'static str), + Scanned(RootBridgeScan), +} + +/// What the scan of one PCI root bridge observed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RootBridgeScan { + pub segment: u32, + pub devices: u16, + pub bridges: u16, + /// Bridges with a valid secondary..subordinate bus window. + pub windows: u16, + /// A GB10 vendor/device match that failed the BAR check: raw + /// command/status and BAR0 low/high, so the report shows the BAR state. + pub rejected_candidate: Option<(u32, u32, u32)>, +} + +/// Report lines explaining why discovery produced no GB10 identity: +/// bridges seen, opens refused, segments, bridge windows, and BAR state. +/// `handles` is the number of `PciRootBridgeIo` handles, if known. +pub fn write_discovery_diagnostics( + out: &mut impl Write, + handles: Option, + roots: &[Option], +) { + match handles { + Some(n) => { + let _ = writeln!(out, "gb10_pci_root_bridges: {n}"); + } + None => { + let _ = writeln!(out, "gb10_pci_root_bridges: lookup failed"); + return; + } + } + for (index, outcome) in roots.iter().flatten().enumerate() { + match outcome { + RootBridgeOutcome::OpenRefused(status) => { + let _ = writeln!(out, "gb10_pci_root_open[{index}]: refused ({status})"); + } + RootBridgeOutcome::Scanned(scan) => { + let _ = writeln!( + out, + "gb10_pci_root[{index}]: segment {} devices {} bridges {} windows {}", + scan.segment, scan.devices, scan.bridges, scan.windows + ); + if let Some((command_status, bar0_low, bar0_high)) = scan.rejected_candidate { + let _ = writeln!( + out, + "gb10_pci_candidate[{index}]: command_status {command_status:#010x} bar0 {bar0_high:#010x}:{bar0_low:#010x}" + ); + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; + extern crate std; + use std::string::String; #[test] fn validates_gb10_memory_bar() { @@ -76,4 +141,37 @@ mod tests { assert!(Gb10Bar::from_config(location, 0x2e12_10de, 0x4, 0x2400_0004, 0).is_none()); assert!(Gb10Bar::from_config(location, 0x2e12_10de, 0x6, 0x2400_0000, 0).is_none()); } + + #[test] + fn diagnostics_report_refused_opens_segments_and_bar_state() { + let roots = [ + Some(RootBridgeOutcome::OpenRefused("ACCESS_DENIED")), + Some(RootBridgeOutcome::Scanned(RootBridgeScan { + segment: 15, + devices: 4, + bridges: 1, + windows: 1, + rejected_candidate: Some((0x10_0004, 0, 0)), + })), + None, + ]; + let mut text = String::new(); + write_discovery_diagnostics(&mut text, Some(2), &roots); + for line in [ + "gb10_pci_root_bridges: 2", + "gb10_pci_root_open[0]: refused (ACCESS_DENIED)", + "gb10_pci_root[1]: segment 15 devices 4 bridges 1 windows 1", + "gb10_pci_candidate[1]: command_status 0x00100004 bar0 0x00000000:0x00000000", + ] { + assert!(text.lines().any(|l| l == line), "missing {line:?} in:\n{text}"); + } + + let mut text = String::new(); + write_discovery_diagnostics(&mut text, None, &[None]); + assert_eq!(text, "gb10_pci_root_bridges: lookup failed\n"); + + let mut text = String::new(); + write_discovery_diagnostics(&mut text, Some(0), &[None]); + assert_eq!(text, "gb10_pci_root_bridges: 0\n"); + } } diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index bc0b3571..68f02dc8 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -38,6 +38,7 @@ use uefi::mem::memory_map::{MemoryMap, MemoryType}; use uefi::prelude::*; use uefi::proto::console::gop::{GraphicsOutput, PixelFormat}; use uefi::proto::media::file::{File, FileAttribute, FileMode}; +use uefi::proto::pci::configuration::ResourceRangeType; use uefi::proto::pci::root_bridge::PciRootBridgeIo; use uefi::proto::pci::PciIoAddress; use uefi::runtime::{ResetType, VariableAttributes, VariableVendor}; @@ -140,10 +141,55 @@ fn save_report_var(bytes: &[u8]) -> Result { .map_err(|_| "firmware refused the write") } -fn probe_gb10( +type BridgeScan = aienos_accel::RootBridgeScan; +type RootOutcome = aienos_accel::RootBridgeOutcome; + +/// Outcome of pre-exit GB10 discovery: the identity when found, plus a +/// bounded record of why it was not (bridges seen, opens refused, segments, +/// BAR state) so the pre-exit and final reports can say what happened. +struct Gb10Discovery { + identity: Option, + /// Number of handles carrying the `PciRootBridgeIo` protocol, when the + /// handle database answered. + handles: Option, + roots: [Option; MAX_ROOT_BRIDGES], +} + +/// At most this many root bridges are recorded; extras are still searched. +const MAX_ROOT_BRIDGES: usize = 4; + +/// Compact status names for the report (no `Debug` tables in the image). +fn status_name(status: Status) -> &'static str { + match status { + Status::ACCESS_DENIED => "ACCESS_DENIED", + Status::NOT_FOUND => "NOT_FOUND", + Status::INVALID_PARAMETER => "INVALID_PARAMETER", + Status::OUT_OF_RESOURCES => "OUT_OF_RESOURCES", + Status::UNSUPPORTED => "UNSUPPORTED", + _ => "OTHER", + } +} + +impl Gb10Discovery { + /// Record the outcome of one root bridge, bounded by `MAX_ROOT_BRIDGES`. + fn record(&mut self, outcome: RootOutcome) { + if let Some(slot) = self.roots.iter_mut().find(|s| s.is_none()) { + *slot = Some(outcome); + } + } + + /// Report lines explaining why no GB10 identity was produced. + fn write_diagnostics(&self, out: &mut Report) { + aienos_accel::write_discovery_diagnostics(out, self.handles, &self.roots); + } +} + +/// Read the config registers needed for the BAR check. `None` when the +/// vendor/device pair does not match the GB10 or a config read failed. +fn read_candidate( root: &mut PciRootBridgeIo, address: PciIoAddress, -) -> Option { +) -> Option<(u32, u32, u32, u32)> { let config = |offset| address.with_register(offset); let vendor_device = root.pci().read_one::(config(0)).ok()?; if vendor_device != 0x2e12_10de { @@ -152,7 +198,16 @@ fn probe_gb10( let command_status = root.pci().read_one::(config(4)).ok()?; let bar0_low = root.pci().read_one::(config(0x10)).ok()?; let bar0_high = root.pci().read_one::(config(0x14)).ok()?; - let bar = aienos_accel::Gb10Bar::from_config( + Some((vendor_device, command_status, bar0_low, bar0_high)) +} + +fn probe_gb10( + root: &mut PciRootBridgeIo, + address: PciIoAddress, + scan: &mut BridgeScan, +) -> Option { + let (vendor_device, command_status, bar0_low, bar0_high) = read_candidate(root, address)?; + let bar = match aienos_accel::Gb10Bar::from_config( aienos_accel::PciLocation { segment: root.segment_nr(), bus: address.bus, @@ -163,7 +218,15 @@ fn probe_gb10( command_status, bar0_low, bar0_high, - )?; + ) { + Some(bar) => bar, + None => { + // The GB10 was found but its BAR or command register was not + // usable; keep the raw values so the report shows the BAR state. + scan.rejected_candidate = Some((command_status, bar0_low, bar0_high)); + return None; + } + }; let pmc_boot_0 = root .memory() .read_one::(bar.physical_base + aienos_accel::PMC_BOOT_0) @@ -179,31 +242,138 @@ fn probe_gb10( }) } -fn discover_gb10() -> Option { - let handles = uefi::boot::find_handles::().ok()?; - for handle in handles { - let Ok(mut root) = uefi::boot::open_protocol_exclusive::(handle) else { - continue; - }; - // Config A puts GB10 at segment 15, bus 1, device 0, function 0. - // Try that first so the common boot path does not enumerate every bus. - if root.segment_nr() == 15 { - if let Some(identity) = probe_gb10(&mut root, PciIoAddress::new(1, 0, 0)) { - return Some(identity); +/// Walk every function on one bus of this root bridge. +/// Returns the GB10 identity when the GB10 is found here. +fn scan_bus(root: &mut PciRootBridgeIo, bus: u8, scan: &mut BridgeScan) -> Option { + for dev in 0..32u8 { + for fun in 0..8u8 { + let address = PciIoAddress::new(bus, dev, fun); + let config = |offset| address.with_register(offset); + let Ok(vendor_device) = root.pci().read_one::(config(0)) else { + continue; + }; + if vendor_device & 0xffff == 0xffff { + if fun == 0 { + break; // no function 0: no further functions on this device + } + continue; } - } - let Ok(tree) = root.enumerate() else { - continue; - }; - for address in tree { - if let Some(identity) = probe_gb10(&mut root, address) { - return Some(identity); + scan.devices += 1; + if vendor_device == 0x2e12_10de { + if let Some(identity) = probe_gb10(root, address, scan) { + return Some(identity); + } + } + let header_type = root + .pci() + .read_one::(config(0x0c)) + .map(|v| ((v >> 16) & 0xff) as u8) + .unwrap_or(0); + if header_type & 0x7f == 0x01 { + scan.bridges += 1; + let window = root + .pci() + .read_one::(config(0x18)) + .map(|v| (((v >> 8) & 0xff) as u8, ((v >> 16) & 0xff) as u8)) + .unwrap_or((0, 0)); + if window.0 != 0 && window.1 >= window.0 { + scan.windows += 1; + } + } + if fun == 0 && header_type & 0x80 == 0 { + break; // single-function device: skip functions 1..8 } } } None } +/// Read the bus-range resource descriptors of this root bridge, or `None`. +fn bus_ranges(root: &mut PciRootBridgeIo) -> Option<(u8, u8)> { + let mut range: Option<(u8, u8)> = None; + for descriptor in root.configuration().ok()? { + if descriptor.resource_range_type == ResourceRangeType::Bus { + let min = u8::try_from(descriptor.address_min).unwrap_or(u8::MAX); + let max = u8::try_from(descriptor.address_max).unwrap_or(u8::MAX); + range = Some(match range { + Some((lo, hi)) => (lo.min(min), hi.max(max)), + None => (min, max), + }); + } + } + range +} + +/// Scan one root bridge. Returns the GB10 identity and the outcome to record. +fn scan_root(root: &mut PciRootBridgeIo) -> (Option, RootOutcome) { + let mut scan = BridgeScan { + segment: root.segment_nr(), + devices: 0, + bridges: 0, + windows: 0, + rejected_candidate: None, + }; + // Config A puts GB10 at segment 15, bus 1, device 0, function 0. + // Try that first so the common boot path does not walk every bus. + if scan.segment == 15 { + if let Some(identity) = probe_gb10(root, PciIoAddress::new(1, 0, 0), &mut scan) { + return (Some(identity), RootOutcome::Scanned(scan)); + } + } + // No firmware bus descriptors: fall back to the root bus so the scan + // still sees devices whose bus numbers firmware never published. + let (bus_min, bus_max) = bus_ranges(root).unwrap_or((0, 0)); + for bus in bus_min..=bus_max { + if let Some(identity) = scan_bus(root, bus, &mut scan) { + return (Some(identity), RootOutcome::Scanned(scan)); + } + } + (None, RootOutcome::Scanned(scan)) +} + +fn discover_gb10() -> Gb10Discovery { + let mut discovery = Gb10Discovery { + identity: None, + handles: None, + roots: [const { None }; MAX_ROOT_BRIDGES], + }; + let handles = match uefi::boot::find_handles::() { + Ok(handles) => handles, + Err(_) => return discovery, + }; + discovery.handles = Some(u16::try_from(handles.len()).unwrap_or(u16::MAX)); + for handle in handles { + // Shared (GetProtocol) open: the firmware PCI bus driver holds this + // protocol open ByDriver, so an exclusive open is refused with + // ACCESS_DENIED. Shared reads are safe here: this boot code only + // reads through the protocol, and firmware keeps the protocol + // installed until boot services are exited. + let mut root = match unsafe { + uefi::boot::open_protocol::( + OpenProtocolParams { + handle, + agent: uefi::boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) + } { + Ok(root) => root, + Err(e) => { + discovery.record(RootOutcome::OpenRefused(status_name(e.status()))); + continue; + } + }; + let (found, outcome) = scan_root(&mut root); + discovery.record(outcome); + if let Some(identity) = found { + discovery.identity = Some(identity); + return discovery; + } + } + discovery +} + /// Reads a firmware ACPI table whose header is at `addr`. /// /// # Safety @@ -523,7 +693,8 @@ fn main() -> Status { stage(FIRMWARE_ENTRY); stage(GB10_DISCOVERY); - let gb10 = discover_gb10(); + let gb10_discovery = discover_gb10(); + let gb10 = gb10_discovery.identity; stage(ACPI_TOPOLOGY); let boot_midr = midr_el1(); @@ -565,6 +736,7 @@ fn main() -> Status { } None => { let _ = writeln!(pre, "gb10: unavailable"); + gb10_discovery.write_diagnostics(&mut pre); } } write_cpu(&mut pre, cpu, boot_midr, boot_mpidr); @@ -636,6 +808,9 @@ fn main() -> Status { header(&mut report, "final"); write_index_line(&mut report); let _ = write!(report, "{}", kernel_report.as_str()); + if gb10.is_none() { + gb10_discovery.write_diagnostics(&mut report); + } match progress_saved { Ok(_) => { let _ = writeln!(report, "progress_record: saved"); diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs index 07809054..cad61c64 100644 --- a/crates/aienos-kernel/src/lib.rs +++ b/crates/aienos-kernel/src/lib.rs @@ -20,6 +20,7 @@ pub mod recovery; pub mod report; pub mod store; pub mod sync; +pub mod usb; #[cfg(all(target_os = "none", not(feature = "std"), not(test)))] #[panic_handler] diff --git a/crates/aienos-kernel/src/usb/hid.rs b/crates/aienos-kernel/src/usb/hid.rs new file mode 100644 index 00000000..db59e2dd --- /dev/null +++ b/crates/aienos-kernel/src/usb/hid.rs @@ -0,0 +1,299 @@ +//! HID boot-protocol keyboard reports. +//! +//! Pure parsing: an 8-byte boot-protocol report in, key events out. No MMIO +//! and no allocation, so the whole behaviour is host-tested. The decoder is +//! make-only (key releases are ignored), and a fixed-capacity sink keeps the +//! decoded text when the caller wants it as one string. + +/// Modifier bit positions in byte 0 of a boot-protocol report. +pub mod modifier { + pub const LEFT_CTRL: u8 = 1 << 0; + pub const LEFT_SHIFT: u8 = 1 << 1; + pub const LEFT_ALT: u8 = 1 << 2; + pub const RIGHT_CTRL: u8 = 1 << 4; + pub const RIGHT_SHIFT: u8 = 1 << 5; + pub const RIGHT_ALT: u8 = 1 << 6; + pub const ANY_SHIFT: u8 = LEFT_SHIFT | RIGHT_SHIFT; +} + +pub use modifier::{LEFT_ALT, LEFT_CTRL, LEFT_SHIFT, RIGHT_ALT, RIGHT_CTRL, RIGHT_SHIFT}; + +/// One decoded key press. Releases never produce an event. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeyEvent { + /// A printable character, already shifted. + Char(char), + Enter, + Backspace, + Tab, + Escape, + /// Cursor keys arrive as ANSI escape sequences on the early console. + Up, + Down, + Left, + Right, +} + +/// Length of a HID boot-protocol keyboard report. +pub const BOOT_REPORT_LEN: usize = 8; +const MAX_KEYS: usize = 6; + +/// Unshifted and shifted characters per usage ID, starting at usage 0x04: +/// letters first, then digits, each pair unshifted then shifted. +#[rustfmt::skip] +const KEYMAP: &[u8] = b"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ\ + 1!2@3#4$5%6^7&8*9(0)"; + +/// Usage 0x2c (space) and the punctuation row: usages 0x2c..=0x38, each pair +/// unshifted then shifted. Usage 0x32 (non-US `#`/`~`) sits between `\` and `;`. +#[rustfmt::skip] +const PUNCT: &[u8] = b" -_=+[{]}\\|#~;:'\"`~,<.>/?"; + +const USAGE_ENTER: u8 = 0x28; +const USAGE_ESCAPE: u8 = 0x29; +const USAGE_BACKSPACE: u8 = 0x2a; +const USAGE_TAB: u8 = 0x2b; +const USAGE_CAPS_LOCK: u8 = 0x39; +const USAGE_F1: u8 = 0x3a; +const USAGE_F12: u8 = 0x45; +const USAGE_RIGHT_ARROW: u8 = 0x4f; +const USAGE_LEFT_ARROW: u8 = 0x50; +const USAGE_DOWN_ARROW: u8 = 0x51; +const USAGE_UP_ARROW: u8 = 0x52; + +fn decode_usage(usage: u8, shift: bool) -> Option { + let c = match usage { + 0x04..=0x27 => KEYMAP[usize::from(usage - 0x04) * 2 + usize::from(shift)], + USAGE_ENTER => return Some(KeyEvent::Enter), + USAGE_ESCAPE => return Some(KeyEvent::Escape), + USAGE_BACKSPACE => return Some(KeyEvent::Backspace), + USAGE_TAB => return Some(KeyEvent::Tab), + 0x2c..=0x38 => PUNCT[usize::from(usage - 0x2c) * 2 + usize::from(shift)], + // Caps Lock and the function row are not echoed. + USAGE_CAPS_LOCK | USAGE_F1..=USAGE_F12 => return None, + USAGE_RIGHT_ARROW => return Some(KeyEvent::Right), + USAGE_LEFT_ARROW => return Some(KeyEvent::Left), + USAGE_DOWN_ARROW => return Some(KeyEvent::Down), + USAGE_UP_ARROW => return Some(KeyEvent::Up), + _ => return None, + }; + Some(KeyEvent::Char(char::from(c))) +} + +/// Stateless-format decoder: a key press is emitted once, on the first report +/// containing it, and releases are ignored, so a key held across polls does +/// not auto-repeat. +pub struct BootKeyboardDecoder { + previous: [u8; MAX_KEYS], +} + +impl Default for BootKeyboardDecoder { + fn default() -> Self { + Self::new() + } +} + +impl BootKeyboardDecoder { + pub const fn new() -> Self { + Self { + previous: [0; MAX_KEYS], + } + } + + /// Handle one 8-byte boot-protocol report, calling `emit` for every key + /// that is newly pressed relative to the previous report. Reports with a + /// rollover error (all usages 0x01) or a wrong length are ignored. + pub fn handle_report(&mut self, report: &[u8], mut emit: impl FnMut(KeyEvent)) { + if report.len() != BOOT_REPORT_LEN { + return; + } + let usages: [u8; MAX_KEYS] = report[2..8].try_into().unwrap_or([0; MAX_KEYS]); + if usages[0] == 0x01 { + // Phantom state during rollover: ignore this report entirely and + // do not treat it as a release. + return; + } + let shift = report[0] & modifier::ANY_SHIFT != 0; + for usage in usages { + if usage == 0 || self.previous.contains(&usage) { + continue; + } + if let Some(event) = decode_usage(usage, shift) { + emit(event); + } + } + self.previous = usages; + } +} + +/// Fixed-capacity text collector for decoded keystrokes, heap-free. +pub struct TextSink { + bytes: [u8; N], + len: usize, +} + +impl Default for TextSink { + fn default() -> Self { + Self::new() + } +} + +impl TextSink { + pub const fn new() -> Self { + Self { + bytes: [0; N], + len: 0, + } + } + + pub fn as_str(&self) -> &str { + // Only ASCII is ever pushed. + core::str::from_utf8(&self.bytes[..self.len]).unwrap_or("") + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + fn push(&mut self, byte: u8) { + if self.len < N { + self.bytes[self.len] = byte; + self.len += 1; + } + } + + /// Record one event; cursor keys become their ANSI escape sequences. + pub fn record(&mut self, event: KeyEvent) { + match event { + KeyEvent::Char(c) => self.push(c as u8), + KeyEvent::Enter => self.push(b'\n'), + KeyEvent::Backspace => self.push(0x08), + KeyEvent::Tab => self.push(b'\t'), + KeyEvent::Escape => self.push(0x1b), + KeyEvent::Up => [0x1b, b'[', b'A'].iter().for_each(|b| self.push(*b)), + KeyEvent::Down => [0x1b, b'[', b'B'].iter().for_each(|b| self.push(*b)), + KeyEvent::Right => [0x1b, b'[', b'C'].iter().for_each(|b| self.push(*b)), + KeyEvent::Left => [0x1b, b'[', b'D'].iter().for_each(|b| self.push(*b)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn report(modifiers: u8, usages: [u8; MAX_KEYS]) -> [u8; BOOT_REPORT_LEN] { + let mut r = [0u8; BOOT_REPORT_LEN]; + r[0] = modifiers; + r[2..8].copy_from_slice(&usages); + r + } + + fn decode( + decoder: &mut BootKeyboardDecoder, + report: &[u8; BOOT_REPORT_LEN], + ) -> TextSink<16> { + let mut sink = TextSink::new(); + decoder.handle_report(report, |e| sink.record(e)); + sink + } + + #[test] + fn letter_make_and_release_produces_one_character() { + let mut d = BootKeyboardDecoder::new(); + assert_eq!(decode(&mut d, &report(0, [0x04, 0, 0, 0, 0, 0])).as_str(), "a"); + assert_eq!(decode(&mut d, &report(0, [0; 6])).as_str(), ""); + // Held keys do not repeat: same usage in consecutive reports is quiet. + assert_eq!(decode(&mut d, &report(0, [0x04, 0, 0, 0, 0, 0])).as_str(), "a"); + assert_eq!(decode(&mut d, &report(0, [0x04, 0, 0, 0, 0, 0])).as_str(), ""); + } + + #[test] + fn shift_and_digits_use_the_shifted_column() { + let mut d = BootKeyboardDecoder::new(); + assert_eq!( + decode(&mut d, &report(LEFT_SHIFT, [0x04, 0x1e, 0, 0, 0, 0])).as_str(), + "A!" + ); + // Right shift works the same. + let mut d = BootKeyboardDecoder::new(); + assert_eq!( + decode(&mut d, &report(RIGHT_SHIFT, [0x27, 0x28, 0, 0, 0, 0])).as_str(), + ")\n" + ); + } + + #[test] + fn punctuation_and_space_decode() { + let mut d = BootKeyboardDecoder::new(); + assert_eq!( + decode(&mut d, &report(0, [0x2c, 0x2d, 0x36, 0x37, 0x38, 0])).as_str(), + " -,./" + ); + let mut d = BootKeyboardDecoder::new(); + assert_eq!( + decode(&mut d, &report(LEFT_SHIFT, [0x2f, 0x30, 0x31, 0x33, 0x34, 0x35])) + .as_str(), + "{}|:\"~" + ); + let mut d = BootKeyboardDecoder::new(); + assert_eq!( + decode(&mut d, &report(LEFT_SHIFT, [0x2d, 0x2e, 0x32, 0x36, 0x37, 0x38])) + .as_str(), + "_+~<>?" + ); + } + + #[test] + fn control_keys_and_arrows() { + let mut d = BootKeyboardDecoder::new(); + let mut sink = TextSink::<32>::new(); + d.handle_report(&report(0, [0x2a, 0x2b, 0x29, 0, 0, 0]), |e| sink.record(e)); + d.handle_report(&report(0, [0; 6]), |e| sink.record(e)); + d.handle_report(&report(0, [USAGE_UP_ARROW, 0, 0, 0, 0, 0]), |e| { + sink.record(e) + }); + assert_eq!(sink.as_str(), "\x08\t\x1b\x1b[A"); + } + + #[test] + fn rollover_error_and_wrong_length_are_ignored() { + let mut d = BootKeyboardDecoder::new(); + let phantom = report(0, [0x01, 0x01, 0x01, 0x01, 0x01, 0x01]); + assert_eq!(decode(&mut d, &phantom).as_str(), ""); + // A rollover report does not count as a release. + d.handle_report(&report(0, [0x04, 0, 0, 0, 0, 0]), |_| {}); + let mut sink = TextSink::<8>::new(); + d.handle_report(&phantom, |e| sink.record(e)); + d.handle_report(&report(0, [0x04, 0, 0, 0, 0, 0]), |e| sink.record(e)); + assert!(sink.is_empty()); + // Wrong length never decodes. + d.handle_report(&[0u8; 4], |_| panic!("no event")); + } + + #[test] + fn unmapped_usages_are_dropped() { + let mut d = BootKeyboardDecoder::new(); + assert_eq!( + decode(&mut d, &report(0, [USAGE_CAPS_LOCK, 0, 0, 0, 0, 0])).as_str(), + "" + ); + assert_eq!( + decode(&mut d, &report(0, [USAGE_F1, USAGE_F12, 0, 0, 0, 0])).as_str(), + "" + ); + } + + #[test] + fn sink_truncates_instead_of_overflowing() { + let mut sink = TextSink::<4>::new(); + for c in "hello".chars() { + sink.record(KeyEvent::Char(c)); + } + assert_eq!(sink.as_str(), "hell"); + } +} diff --git a/crates/aienos-kernel/src/usb/mod.rs b/crates/aienos-kernel/src/usb/mod.rs new file mode 100644 index 00000000..cb36343e --- /dev/null +++ b/crates/aienos-kernel/src/usb/mod.rs @@ -0,0 +1,10 @@ +//! USB support for the early console. +//! +//! After `ExitBootServices` the firmware's USB keyboard support is gone, so +//! AIENOS must drive the keyboard itself. This module starts with the part +//! that needs no hardware: decoding HID boot-protocol keyboard reports into +//! key events and text. The polled xHCI controller driver that delivers those +//! reports follows separately (ADR 0012, SEED-0A experiment #1 +//! `input.keyboard.usb`). + +pub mod hid; diff --git a/docs/GB10_NATIVE_STATUS.md b/docs/GB10_NATIVE_STATUS.md index 2a0fb184..b103d4f0 100644 --- a/docs/GB10_NATIVE_STATUS.md +++ b/docs/GB10_NATIVE_STATUS.md @@ -1,16 +1,32 @@ # GB10 native execution status The `aienos-handoff` AArch64 UEFI image now checks the DGX Spark's observed -GB10 PCI location first, then searches other root bridges if needed. It accepts -only NVIDIA `10de:2e12` with a programmed 64-bit memory BAR and PCI memory +GB10 PCI location first, then walks every bus in each root bridge's +firmware-declared bus range. It opens the UEFI PCI root bridge protocol with a +shared (`GetProtocol`) open. The leading hypothesis for the first native +boot's `gb10: unavailable` is that the firmware PCI bus driver holds the +protocol `ByDriver` and refuses an exclusive open with `ACCESS_DENIED`; this is +unconfirmed on hardware, and the next native boot's `gb10_pci_root_open[..]` +lines will confirm or rule it out. It accepts only +NVIDIA `10de:2e12` with a programmed 64-bit memory BAR and PCI memory decoding enabled. Through the UEFI PCI root bridge protocol, it reads the read-only PMC `BOOT_0` and `BOOT_42` registers from BAR0. It carries the location, BAR address, and register values across `ExitBootServices` into the AIENOS kernel's serial boot report. No Linux service is involved in that image. -This image has been built but **has not been booted on hardware**. These -register reads still use firmware services before handoff. They establish a -device identity path; they do not initialize the GPU or execute a GPU command. +When the GB10 is not found, the pre-exit report and the final +firmware-variable report record why: how many root bridges carry the protocol +(`gb10_pci_root_bridges`), any refused opens (`gb10_pci_root_open[i]`), and +per scanned bridge the segment number, device count, bridge count, and valid +bridge bus windows (`gb10_pci_root[i]`). If the GB10 vendor/device pair was +seen but rejected, its command/status and BAR0 values are recorded +(`gb10_pci_candidate[i]`), distinguishing an unprogrammed BAR from a missed +match. + +This image has been built but the fixed discovery path **has not been booted +on hardware**. These register reads still use firmware services before +handoff. They establish a device identity path; they do not initialize the +GPU or execute a GPU command. To reach independent GPU execution, AIENOS still needs a native MMU mapping for GPU MMIO, GPU resource and interrupt management, GB10/GSP firmware loading and diff --git a/docs/HARDWARE_TEST_RIG.md b/docs/HARDWARE_TEST_RIG.md new file mode 100644 index 00000000..64192b29 --- /dev/null +++ b/docs/HARDWARE_TEST_RIG.md @@ -0,0 +1,194 @@ +# Machine 1 hardware test rig + +**Status: proposed design (2026-09-24). Nothing is wired or enabled yet. The +operator chooses and approves the parts; maintainers wire it up. Until then, +M2C power, capture and input stay pending and boots stay attended.** + +Governing: [ADR 0011](adr/0011-machine-1-hardware-test-rig.md), +[MILESTONES.md gate M2C](MILESTONES.md), [NATIVE_BOOT_ONE_TIME.md](NATIVE_BOOT_ONE_TIME.md), +issue [#25](https://github.com/aien-dev/aienos/issues/25). + +## Why + +Every Spark boot currently needs a person at the machine: someone holds the +power button when a boot hangs, photographs the screen because the post-exit +report has no other record, and types at the firmware menus. That does not +scale, and it cannot run unattended. The rig gives three **independent** +functions for Machine 1, all serialized through +`aien-proof hold --resource machine-1` (see +[Serialization](#serialization-through-aien-proof)): + +1. **Power and reset control**: momentary press, long press (force off), + and a hard power cut that always works. +2. **Display or console capture**: the screen from cold boot through the + post-exit report, replacing the operator photograph. +3. **Deterministic input and boot selection**: scripted keystrokes into the + firmware boot menu, the firmware setup screen, and later the AIENOS early + console, so the same image boot can be driven the same way every time. + +Independence matters: a hung capture dongle must not block a power cut, and a +dead HID gadget must not trap the machine with no way to reboot it. Each +function below fails without breaking the other two. + +A Raspberry Pi is already cabled to the Spark and acts as the rig controller: +USB keyboard gadget, capture host, relay driver, and the place `aien-proof` +runs. + +## Parts list + +Prices are approximate, one unit each, 2026. Nothing here is proprietary; every +part is replaceable with an equivalent. + +| Function | Part | Role | Approx. cost | +| --- | --- | --- | --- | +| Controller | Raspberry Pi 5 (already cabled to the Spark) | Runs `aien-proof`, the gadget stack, capture and relay control | owned | +| Power sense | Spark ATX 24-pin sense lead (`PWR_OK`, green wire `PS_ON`) tapped at the PSU connector | Ground `PS_ON` to force the PSU on; read `PWR_OK` to know the board has power | cable only | +| Power cut | SPDT relay board, 5 V coil, 10 A mains-rated contacts (for example an opto-isolated Songle SRD-05VDC module) | Inline with the mains feed or the PSU enable; drops power unconditionally | ~5 USD | +| Power/reset buttons | 2x reed or opto-isolated reed relays (for example Omron G3VM SIP MOSFET relays) | One across the Spark front-panel power-header pins, one across the reset-header pins; momentary closure only | ~4 USD | +| Display capture | USB 3 HDMI capture dongle, UVC class, 1080p60 (for example an MS2109 or MS2130 based dongle) | Spark HDMI out to dongle input; appears as a webcam on the Pi; loop-through port passes the desk monitor | ~20 to 40 USD | +| Input emulation | The Pi itself, USB OTG port in HID gadget mode (Linux `configfs`, `dwc2` overlay) | Presents a standard USB boot-protocol keyboard to the Spark | included | +| Console capture | Pi GPIO UART (TX/RX) wired to the Spark UART at `0x16A00000` | Bounded serial console once [#22](https://github.com/aien-dev/aienos/issues/22) lands; 3.3 V levels only | jumper wires | +| Enclosure and safety | Fused mains inlet box for the relay, insulated standoffs, labeled header leads | Mains stays in a closed, fused box; low voltage leaves it | ~20 USD | + +Total new spend is roughly 50 to 70 USD. No part is on the Spark's boot +critical path except by explicit command: with every relay at rest and every +cable disconnected, the Spark boots exactly as it does today. + +## Function 1: power and reset control + +The Spark exposes standard PC-style front-panel pins. Shorting the power pins +briefly is a press; shorting them for about five seconds forces power off. The +relay board gives a hard cut that works even when the board is wedged. + +- `power.press` and `reset.press`: close the matching reed relay for about + 500 ms, then open. Reed relays are used for the button lines because they are + isolated, polarity-tolerant and cannot drive the header. +- `power.forceoff`: hold the power relay closed for 5 s. +- `power.cut` / `power.restore`: energize or release the mains relay. This is + the last resort and the recovery path for every wedged state. +- `power.status`: read the PSU `PWR_OK` sense line, so a script can wait for + power-good instead of sleeping a fixed time. + +Safety invariants (enforced by the control scripts, reviewed in the ledger): + +- The mains relay is **fail-on**: power flows when the relay is at rest, so a + dead Pi or a crashed script never holds the machine dark. +- The button relays are **momentary-only**: the driver enforces a maximum + closure time in software and the hardware timer on the relay board enforces + it if the Pi hangs. +- `power.cut` is the only destructive action, and it is always available to + the operator and to a failing script. + +## Function 2: display and console capture + +Two capture paths, both terminating on the Pi: + +- **HDMI**: the Spark's display output goes through the capture dongle's + loop-through port to the desk monitor, and the dongle's USB side lands on + the Pi as a UVC webcam. A capture run records video from before power-on + until the machine is back in Linux, plus a still frame at each stage gate + (firmware logo, pre-exit report, post-exit report, countdown). This replaces + the "photograph the screen" step in + [NATIVE_BOOT_ONE_TIME.md](NATIVE_BOOT_ONE_TIME.md) and records the post-exit + drawing that the M2 evidence + ([evidence/m2_first_boot_2026-09-24.md](../evidence/m2_first_boot_2026-09-24.md)) + lists as a gap. +- **UART**: the kernel already has a bounded 16550-style UART writer at + `0x16A00000`, 921600 baud (`crates/aienos-kernel/src/arch/aarch64.rs`), + skipped on the first boot because GB10 discovery failed. Once [#22](https://github.com/aien-dev/aienos/issues/22) + (SPCR-based discovery) lands, the Pi's GPIO UART records it at 3.3 V + levels. Until then, HDMI capture is the only post-exit record and stays + mandatory. + +Capture is read-only: nothing in this function can change what the machine +does. A failed capture never blocks power control. + +## Function 3: deterministic input and boot selection + +The Pi's OTG port runs the Linux HID gadget (`configfs` + `dwc2`) and appears +to the Spark as a plain USB keyboard. The gadget implements the HID boot +protocol, so it works in the firmware setup screen and boot menu where no OS +driver exists, and later against the native xHCI/HID driver from +[#24](https://github.com/aien-dev/aienos/issues/24). + +Boot selection is deterministic: the rig never types blind. Each scripted +sequence is a list of (wait for capture frame matching X, send keystrokes Y) +steps. Examples: + +- Boot menu: `power.press`, wait for the firmware logo frame, send `Esc`, + wait for the boot-menu frame, send the arrow-key count for the `ubuntu` + entry, send `Enter`. +- Firmware setup: the documented `systemctl reboot --firmware-setup` path is + preferred; the gadget is the fallback when Linux is not running. +- AIENOS console: once the early console takes keyboard input, sequences come + from the same runner. + +The keystroke sets, frame references and expected end states are versioned in +this repository next to the scripts that use them, so a boot sequence maps to +one exact commit, same rule as the staged image. + +## Serialization through `aien-proof` + +`aien-proof` and its `machine-1` resource lock live in the +[aien-sovereign-core](https://github.com/aien-dev/aien-sovereign-core) +repository; this repository holds the rig design and the contract the control +surface must meet. The contract is the one already used for staging: + +```text +aien-proof hold --resource machine-1 --job -- +``` + +Rules: + +- Every rig function, including capture, runs only inside a + `machine-1` hold. The hold's full output becomes the ledger event, exactly + as `stage_one_time_boot.sh` and `collect_boot_report.sh` already work. +- A hold runs one rig command. The rig never acts outside a hold; an attended + boot by the operator is recorded as one too. +- `power.cut` is the single exception reachable in an emergency and is still + wrapped by the hold when scripted; physically, the operator can always cut + power by hand. +- Scripts that run under the hold get no stdin, so anything privileged is + pre-authorized (`sudo -v`) before the hold, as in + [NATIVE_BOOT_ONE_TIME.md](NATIVE_BOOT_ONE_TIME.md). + +The M2 evidence flow changes in one place: the photograph rows +(`framebuffer:` line and post-exit drawing) come from capture stills named in +the ledger payload, and the collector checks them the way it checks the +firmware-variable report today. + +## Attended-to-unattended boot contract + +The current attended procedure ([NATIVE_BOOT_ONE_TIME.md](NATIVE_BOOT_ONE_TIME.md)) +maps onto the rig without changing the image: + +| Attended step today | With the rig | +| --- | --- | +| Operator holds power button after a hang | `power.forceoff`, then `power.press` | +| Monitor attached; operator photographs the screen | HDMI capture stills and video, recorded in the ledger payload | +| Keyboard attached; operator picks entries in firmware | HID gadget sequences, matched against capture frames | +| Recovery USB stick chosen from the boot menu by hand | Boot-menu sequence against the same capture frames | + +Until the owner-controlled boot chain exists (see the Secure Boot note in +[MILESTONES.md](MILESTONES.md)), the rig changes how boots are driven, not +what is booted: Secure Boot stays on, native AIENOS boots stay paused, and the +rig's first job is running attended flows like recovery-media testing and the +TRUST-1 100-boot campaign without a person in front of the machine. + +## Wiring checklist (maintainers) + +1. Bench-test the relay board on a lamp before touching the Spark. +2. Tap `PS_ON`/`PWR_OK` at the ATX connector; verify sense reads on the Pi. +3. Identify the Spark front-panel header; wire the two reed relays; verify a + 500 ms closure powers the machine on and off. +4. Route HDMI through the capture dongle to the desk monitor; verify the Pi + sees a UVC device and a frame. +5. Enable the HID gadget on the Pi OTG port; verify the Spark firmware sees a + keyboard (boot-menu navigation by script). +6. Wire the UART (3.3 V only); leave it disconnected until [#22](https://github.com/aien-dev/aienos/issues/22) + makes the Spark side real. +7. Run the attended procedure once under the rig, end to end, and record the + ledger events as the rig's commissioning evidence. + +Each step is independently verifiable and independently reversible; a step +that fails leaves the previous functions working. diff --git a/docs/MILESTONES.md b/docs/MILESTONES.md index 2d9e50de..8901cbb4 100644 --- a/docs/MILESTONES.md +++ b/docs/MILESTONES.md @@ -35,7 +35,7 @@ only at M8. Status words: **done** = verified on this repository's evidence; | **M0** Close Config A (**partial**) | Clean reference snapshot | done | PR #12: schema 3.0.0 bundle, all repositories clean | | | Benchmark evidence | done | CPU baseline: Llama-3.2-1B Q4_K_M on 20 Arm cores, 256-token samples, mean decode 54.2 tokens/s | | | Native-boot rollback | done | First native boot returned to Linux on its own; BootNext consumed, Linux entry and kernel unchanged ([M2 evidence](../evidence/m2_first_boot_2026-09-24.md)) | -| | Bootable recovery media | pending | The only USB stick holds a key backup, not a recovery system | +| | Bootable recovery media | done on hardware; repair tooling added, attended repair boot pending | AIENOSRECOV boots with Secure Boot on and returns unattended (#53, [Gate 1 evidence](../evidence/gate1_machine1_selftest_2026-09-24.md)); `fsck.vfat`/`mkfs.vfat`/`fsck.ext4`/`chroot` added to the initrd, stick rebuild and attended `/boot/efi` repair + boot-entry restore still needed ([procedure](RECOVERY_MEDIA_MACHINE1.md), [evidence](../evidence/recovery_boot_machine1.md)) | | **M1** UEFI/QEMU substrate | Automated emulator boot proof | done | PR #42 (SPCR/boot harness) and PR #44 (CI automation). Reaches EL2, discovers MADT/SPCR, reports kernel alive. (Note: distinct from TRUST-1 Gate 4 security test suite) | | **M2A** Spark firmware handoff | Memory map into early allocator | done on hardware | PR #10; 184 descriptors, 36 conventional regions, 0 rejected ([M2 evidence](../evidence/m2_first_boot_2026-09-24.md)) | | | GB10 PCI identity, BAR0, PMC_BOOT registers | built, not found on hardware | PR #11; pre-exit discovery reported `gb10: unavailable` although Linux sees it at `000f:01:00.0` | @@ -45,7 +45,7 @@ only at M8. Status words: **done** = verified on this repository's evidence; | | UART at `0x16A00000` (bounded, Spark only) | built, not attempted | PR #13; skipped on the first boot because GB10 discovery failed | | | USB keyboard (xHCI + HID) | pending | | | **M2C** Hardware test automation | Exclusive Machine 1 key and ledger records in `aien-proof` | done on hardware | aien-sovereign-core PR #126; first boot staged and collected under `machine-1` (ledger events 83 to 85) | -| | Power/reset control, HDMI capture, USB input emulation | pending | Needs hardware chosen by the operator | +| | Power/reset control, HDMI capture, USB input emulation | design proposed, wiring pending | [HARDWARE_TEST_RIG.md](HARDWARE_TEST_RIG.md) and [ADR 0011](adr/0011-machine-1-hardware-test-rig.md); Raspberry Pi controller, parts chosen, operator approval and wiring pending | | **M3** Kernel isolation | MMU, exceptions, interrupts, timer, scheduler, IPC/capabilities | pending | Scheduler consumes M2A CPU topology | | **M4** Storage and recovery | | pending | Host crates exist (`recovery`, `store`) | | **M5** Encryption and identity | | pending | | @@ -56,14 +56,14 @@ only at M8. Status words: **done** = verified on this repository's evidence; **Overall gate status (2026-09-24):** ```text -M0 PARTIAL snapshot PASS, benchmark PASS, rollback PASS, recovery media PENDING +M0 PARTIAL snapshot PASS, benchmark PASS, rollback PASS, recovery media boots on Machine 1; Config A recovery_procedure stays documented_only until restore (Gate 1 items 12-14) is exercised M1 (QEMU substrate) PASS automated QEMU boot in CI (PR #42, #44) M2 PASS first native Spark boot Machine 1 core PASS core operational baseline recorded (PR #41) TRUST-1 Gate 0 DECLARED baseline recorded (PR #46); independent key access pending attended proof -TRUST-1 Gate 1 TOOLING PASS RAM-only recovery builder + QEMU zero-disk proof; physical USB boot pending +TRUST-1 Gate 1 PARTIAL stick boots on Machine 1 with Secure Boot on, inspects SB/PCRs/disks, returns (items 1-5, 7, 8, 15, 16 PASS; 6 partial); repair tooling added ([procedure](RECOVERY_MEDIA_MACHINE1.md)); items 9-14 + artifact round trip pending TRUST-1 Gate 4 TOOLING PASS swTPM + soak + fault injection (PR #48); 100-boot campaign pending -NEXT HARD GATE: Physical Gate 1 USB boot on Spark -> Gate 2 TPM campaign -> Gate 3 owner keys -> M3 +NEXT HARD GATE: Gate 0 key proof (decrypt on MacBook) + Gate 1 items 9-14 -> Gate 2 TPM campaign -> Gate 3 owner keys -> M3 ``` Public roadmap and contributor entry points: [ROADMAP.md](../ROADMAP.md). @@ -98,7 +98,7 @@ evidence that it did so, and returns to the existing system without damaging it. `scripts/collect_boot_report.sh` prints `M2_GATE: PASS` only when all of those checks hold. -**Result 2026-09-24: `M2_GATE: PASS`** on the first attended boot ([evidence](../evidence/m2_first_boot_2026-09-24.md)). Open items: GB10 discovery before firmware exit, the pre-exit report file, recording post-exit screen drawing, UART output, and bootable recovery media. +**Result 2026-09-24: `M2_GATE: PASS`** on the first attended boot ([evidence](../evidence/m2_first_boot_2026-09-24.md)). Open items: GB10 discovery before firmware exit, the pre-exit report file, recording post-exit screen drawing (covered by rig HDMI capture once wired, see [HARDWARE_TEST_RIG.md](HARDWARE_TEST_RIG.md)), UART output, and bootable recovery media. --- diff --git a/docs/NATIVE_BOOT_ONE_TIME.md b/docs/NATIVE_BOOT_ONE_TIME.md index 4eaca2c3..9d67ce18 100644 --- a/docs/NATIVE_BOOT_ONE_TIME.md +++ b/docs/NATIVE_BOOT_ONE_TIME.md @@ -28,10 +28,11 @@ The image does not touch the Linux installation, its partitions, or BootOrder. ## Before you start (at the machine) -1. **Recovery media:** plug in a bootable Linux USB stick. As of 2026-09-24 no - removable media was attached. The internal fallbacks are present: the - `ubuntu` boot entry (shim + GRUB), the firmware fallback loader - `\EFI\BOOT\BOOTAA64.EFI`, and three installed kernels. +1. **Recovery media:** plug in the `AIENOSRECOV` recovery USB stick, built + and proved per [RECOVERY_MEDIA_MACHINE1.md](RECOVERY_MEDIA_MACHINE1.md). + The internal fallbacks are also present: the `ubuntu` boot entry + (shim + GRUB), the firmware fallback loader `\EFI\BOOT\BOOTAA64.EFI`, and + three installed kernels. 2. **Monitor and keyboard** attached to the Spark. 3. **Everything on this Linux install stops** for each reboot: agents, model servers, the aienos.com waitlist API, and remote access. diff --git a/docs/RECOVERY_MEDIA_MACHINE1.md b/docs/RECOVERY_MEDIA_MACHINE1.md new file mode 100644 index 00000000..048d8e5a --- /dev/null +++ b/docs/RECOVERY_MEDIA_MACHINE1.md @@ -0,0 +1,164 @@ +# Bootable recovery media for Machine 1 + +This procedure builds and proves the bootable recovery USB that closes +[issue #17](https://github.com/aien-dev/aienos/issues/17) and advances +TRUST-1 Gate 1 items 12-14. The physical boot is operator-run (physical +access, Secure Boot custody); everything up to the boot and everything after +it is scripted here so one attended exercise produces a recorded verdict. + +**Done when (issue #17):** a USB drive boots the Spark into a rescue +environment that can mount the NVMe root, repair `/boot/efi`, and restore +boot entries, and that boot is recorded as evidence. + +**Where this stands (2026-09-24):** the stick (`AIENOSRECOV`) already boots +on Machine 1 with Secure Boot on, runs entirely from RAM, and returns to +Linux on its own ([#53](https://github.com/aien-dev/aienos/pull/53), +[Gate 1 selftest evidence](../evidence/gate1_machine1_selftest_2026-09-24.md)). +What was still missing from the initrd were the tools to actually repair +`/boot/efi` and check the mounted root: `fsck.vfat`, `mkfs.vfat`, +`fsck.ext4`, and `chroot`. This change adds them. **The stick must be +rebuilt with `scripts/build_recovery_media.sh` and the attended boot below +re-run before issue #17 can close** -- the currently-written stick predates +this change and does not have these tools yet. + +## What ships + +- `scripts/build_recovery_media.sh /dev/sdX1` writes a Secure Boot-compatible + recovery USB (signed shim + GRUB fallback, signed production kernel, and a + standalone RAM initrd). It refuses to overwrite the internal NVMe or + anything currently mounted. Unchanged by this PR. +- `scripts/build_standalone_recovery_initrd.sh` builds the 100% RAM rescue + environment: busybox, cryptsetup, blkid, lsblk, mount, efibootmgr, the + xHCI/HID/USB-storage/NVMe/dm-crypt kernel modules Machine 1 needs, and (new + in this change) `fsck.vfat`, `mkfs.vfat`, `fsck.ext4`, and `chroot` for + repairing `/boot/efi` and the mounted root. Internal storage stays + unmounted until the operator mounts it by hand from the shell. +- `scripts/verify_recovery_tools.sh` (new) checks on any host, without real + devices or root, that the built initrd ships every tool the "done when" + clause needs. It is wired into `scripts/verify_all.sh`. +- `scripts/qemu_verify_recovery_media.sh` proves the environment boots with + zero disks attached (existing Gate 1 invariant, unchanged). +- `scripts/collect_recovery_boot_evidence.sh` (new) runs on Machine 1 during + the attended recovery boot and prints `RECOVERY_BOOT_GATE: PASS` once the + media booted from removable storage, the NVMe root is mounted, `/boot/efi` + is accessible, and boot entries are readable. It is strictly read-only: it + never writes to the ESP, the NVMe root, or BootOrder. + +## Step 0: build host preparation (on Machine 1, Linux up) + +Use the existing `AIENOSRECOV` stick, or another dedicated USB stick. Do not +target the internal NVMe or EFI system partition; the builder refuses both. + +```bash +cd ~/workspace/hive-worktrees/aienos-main && git pull --ff-only +lsblk -f # identify the target stick +bash scripts/verify_recovery_tools.sh # initrd ships the required tools +``` + +## Step 1: rebuild the media with the new tools (operator) + +```bash +sudo -v +aien-proof hold --resource machine-1 --job build-recovery-media -- \ + sudo bash scripts/build_recovery_media.sh /dev/sdX1 +``` + +The builder mounts the target, copies the signed shim and GRUB, the newest +signed production kernel, the freshly built standalone initrd (now including +`fsck.vfat`, `mkfs.vfat`, `fsck.ext4`, `chroot`), and a GRUB config, then +unmounts. + +## Step 2: verify before booting (no reboot needed) + +```bash +bash scripts/qemu_verify_recovery_media.sh # zero-disk RAM boot proof (aarch64 host) +``` + +## Step 3: boot the recovery USB once (operator, at the machine) + +Monitor and keyboard attached. Boot the stick once without changing the +default boot order, either from the firmware boot menu or with a one-time +BootNext: + +```bash +sudo efibootmgr --bootnext "$(efibootmgr | sed -n 's/^Boot\([0-9A-Fa-f]\{4\}\).*\(USB\|UEFI OS\).*/\1/p' | head -1)" +sudo reboot +``` + +Expect the AIENOS GRUB menu, then the rescue banner: `AIENOS Standalone +Hardware Recovery Core`, `Root filesystem: 100% RAM disk`. The environment +loads its kernel modules, prints a report (Secure Boot state, TPM PCRs, +block devices, firmware boot entries) to the screen, then drops into an +interactive shell. Internal NVMe is still unmounted at this point. + +## Step 4: exercise the three "done when" capabilities (operator, from the shell) + +All the tools below are on `PATH` inside the recovery shell. + +1. **Mount the NVMe root.** Identify the root partition (Machine 1's is + `UUID=d27bfd26-ff30-400e-9eca-9cdf73de9406`, ext4), check it, then mount + it read-only: + ```sh + blkid | grep d27bfd26-ff30-400e-9eca-9cdf73de9406 + fsck.ext4 -n /dev/nvme0n1pN # replace N; -n: check only, no repair + mkdir -p /mnt/root + mount -o ro /dev/nvme0n1pN /mnt/root + ``` +2. **Repair `/boot/efi`.** Identify and check the EFI system partition + (Machine 1's is `UUID=9DA2-3597`, vfat), then mount it: + ```sh + blkid | grep 9DA2-3597 + fsck.vfat -a /dev/nvme0n1pM # replace M; -a: auto-repair + mkdir -p /mnt/esp + mount /dev/nvme0n1pM /mnt/esp + ``` + `mkfs.vfat` is available if the ESP needs to be rebuilt from scratch + (destructive; only with explicit operator authorization per the TRUST-1 + plan). +3. **Restore boot entries.** With `/mnt/root` mounted, `chroot /mnt/root` + gives access to the installed `grub-install`/`update-grub` and to + `efibootmgr` running against the real installation, so a missing boot + entry can be re-created from the chroot. `efibootmgr` (no chroot needed) + lists and edits boot entries directly against `/sys/firmware/efi/efivars`. + +## Step 5: record the evidence (operator, still in the recovery boot) + +With the NVMe root mounted at `/mnt/root`: + +```bash +aien-proof hold --resource machine-1 --job recovery-boot-evidence -- \ + bash scripts/collect_recovery_boot_evidence.sh /mnt/root +``` + +The collector performs read-only checks only: it never writes to the ESP, +the NVMe root, or BootOrder. `RECOVERY_BOOT_GATE: PASS` requires all of: +booted from removable media, Secure Boot state recorded, NVMe root mounted +from internal storage, `/boot/efi` accessible with the fallback bootloader +present, EFI variables present, `efibootmgr` lists entries. + +## Step 6: return to Linux and file the record + +`exit` the chroot if used, unmount `/mnt/esp` and `/mnt/root`, then `reboot` +or `poweroff`; the machine returns to the normal BootOrder (Linux). Copy the +collector output into `evidence/recovery_boot_machine1.md`, set the gate row +to PASS, and close issue #17. + +## Mapping to the gates + +| Issue #17 "done when" | Where it is proven | +| --- | --- | +| USB boots the Spark into a rescue environment | Step 3 banner; collector `booted_from_removable_media` | +| Mount the NVMe root | Step 4.1; collector `nvme_root_mounted` + `nvme_root_is_internal` | +| Repair `/boot/efi` | Step 4.2; collector `esp_mounted` + `esp_fallback_bootloader_present` | +| Restore boot entries | Step 4.3; collector `efibootmgr_readable` | +| Boot recorded as evidence | Step 5 ledger event + Step 6 `evidence/recovery_boot_machine1.md` | + +TRUST-1 Gate 1 acceptance tests this procedure exercises: firmware accepts +the image (already PASS, #53), environment starts without internal Linux +(already PASS), no network/model/Cortex required (already PASS), identifies +NVMe and encrypted volumes (already PASS/PARTIAL), inspects Secure Boot +state and PCRs (already PASS), mounts recovered storage safely (Step 4.1, +new), restores documented boot config (Step 4.2-4.3, new), returns the +machine to known-good Linux (Step 6, already PASS), and no destructive +overwrite without explicit operator choice (`mkfs.vfat`/`chroot` are present +but never invoked automatically). diff --git a/docs/TRUST-1-IMPLEMENTATION-PLAN.md b/docs/TRUST-1-IMPLEMENTATION-PLAN.md index b6f16a7e..c73e57ed 100644 --- a/docs/TRUST-1-IMPLEMENTATION-PLAN.md +++ b/docs/TRUST-1-IMPLEMENTATION-PLAN.md @@ -47,6 +47,13 @@ Stop condition: If Spark does not unlock tomorrow we must know what protects dat Objective: Dedicated recovery USB proven on the real Spark before any trust change. +Runbook: [docs/RECOVERY_MEDIA_MACHINE1.md](RECOVERY_MEDIA_MACHINE1.md). The +stick boots and returns unattended (#53); `scripts/build_standalone_recovery_initrd.sh` +now also packages `fsck.vfat`, `mkfs.vfat`, `fsck.ext4`, and `chroot` for +items 12-14 (mount recovered storage, repair `/boot/efi`, restore boot +entries); `scripts/verify_recovery_tools.sh` is the pre-boot host proof; +`scripts/collect_recovery_boot_evidence.sh` records the attended boot. + Preconditions: Gate 0 PASS. Permitted mutations: Create recovery image on build host; write to separate physical USB (not ATLAS_RECOV); boot it once via operator-attended boot with Secure Boot enabled. No internal trust, TPM, or slot mutation. diff --git a/docs/adr/0010-fabric-machine-identity-and-capability-advertisement.md b/docs/adr/0010-fabric-machine-identity-and-capability-advertisement.md new file mode 100644 index 00000000..70ed0a4d --- /dev/null +++ b/docs/adr/0010-fabric-machine-identity-and-capability-advertisement.md @@ -0,0 +1,167 @@ +# ADR 0010: Fabric Machine Identity and Capability Advertisement + +Status: Proposed. + +Open for early discussion per +[issue #37](https://github.com/aien-dev/aienos/issues/37). Not yet accepted. +Nothing in this record is active before native networking +([M6](../MILESTONES.md)) and the preconditions below are met. No code is +mandated by this record. + +Governing: [ARCHITECTURE.md section 2](../ARCHITECTURE.md) (Personal Fabric), +[BLUEPRINT.md section 25](../BLUEPRINT.md) (Phase 8 Personal Fabric), +[BLUEPRINT.md section 26](../BLUEPRINT.md) (state mobility), +[BLUEPRINT.md section 21](../BLUEPRINT.md) (Machine Capsule), +[MILESTONES.md Phase 8](../MILESTONES.md), [ADR 0004](0004-reversibility-definition-and-network-effect-boundary.md), +[ADR 0007](0007-continuous-existence-provisioning-once.md). + +## Context + +The architecture already fixes the endpoint: a given computer is Machine N, +not "the AIEN computer"; hardware and vendor details are capabilities, not +identities (ARCHITECTURE.md section 2). One logical AIEN spans several +machines, and the machines are resources of the operator's environment +(BLUEPRINT.md section 25). Phase 8 assigns this work to a future +`crates/aienos-fabric/` crate covering peer-to-peer capability discovery, +state synchronization, and RPC. + +Issue #37 asks for early design discussion on the two questions that precede +everything else in the fabric: + +1. Under what identity does a machine join the fabric. +2. What a joining machine advertises about itself, and how that advertisement + is represented, authorized, bounded, and kept current. + +Deciding these two points early keeps M6 networking work from accidentally +hardening brand-based identity, unsolicited broadcast behaviour, or an +advertisement format that bypasses AEGIS. This record captures the design +constraints so that early work can proceed in parallel with the M0 to M6 +critical path without premature protocol commitment. + +## Decision + +### Identity: machines join under a Machine ID, never a brand + +1. A machine joins the fabric under a `MachineId`: a stable, opaque, + operator-provisioned identifier generated locally at provisioning time and + bound to the operator's AIEN environment. Following the continuous-existence + rule (ADR 0007), a `MachineId` is created once per physical machine at + provisioning; boot, reboot, kernel restart, and model reload resume it and + never mint a replacement. +2. Vendor, brand, model name, and marketing identifiers ("NVIDIA", "DGX + Spark") are capability data, never identity. A replacement machine with the + same brand is a different `MachineId`; the same machine with replaced parts + keeps its `MachineId`. The DGX Spark is the reference machine, not AIEN's + identity (BLUEPRINT.md section 24). +3. The machine's hardware description is a Machine Capsule (BLUEPRINT.md + section 21): CPU, accelerator, memory, storage, network, display, audio, + USB, Bluetooth, input, known drivers, and compatibility requirements. + The capsule is a property of the machine record, not of the identity. +4. The `MachineId` is distinct from the `LogicalAgentId`. The agent identity + exists above machines (Blueprint section 25); a machine never impersonates + the agent, and agent migration between machines is an execution-state + transition recorded with a continuity receipt, not a new agent. + +### Advertisement: declared capability set + +5. A joining machine advertises exactly the categories named in issue #37: + - **CPU**: topology, architecture, efficiency classes, frequency + envelopes, as discovered by native topology discovery (M2 already + provides the baseline). + - **Memory**: total and available capacity, unified-memory properties and + block budgets per ADR 0005. + - **Accelerators**: presence, class, and driver status (for example the + GB10 GPU as a characterized capability, per issue #36 work; accelerator + presence is capability data even before accelerator execution exists). + - **Models**: model identities and versions currently loadable on this + machine, behind the Model ABI; a model is a replaceable component, never + an identity. + - **Tools**: the capability surface the machine can execute, in the same + vocabulary AEGIS uses for capability scope (`fs.write`, `code.build`, + and similar names), so placement decisions and authorization decisions + read the same data. + - **Load**: current dynamic pressure (scheduler occupancy, memory + pressure, thermal and power state where measurable), advertised as a + separate, short-lived class of data from the static capability set. +6. Static capabilities and dynamic load are distinct records with distinct + lifetimes. Static data changes only on provisioning, hardware change, or + software update and is signed once per change; load data is unsigned + telemetry-grade information refreshed periodically and never used for + authorization decisions. +7. Advertisement is pull-or-respond within the operator's own fabric, not + open broadcast. A machine answers capability queries from machines it has + been provisioned to trust; it does not announce itself to the local + network at large, and it does not respond to unprovisioned requesters. +8. Every advertisement exchange is an outbound network effect and therefore + crosses the AEGIS boundary (ADR 0004): even read-only capability queries + are `EffectIntent`s evaluated against capability grants. Fabric + participation never bypasses AEGIS under the label of discovery or + research. + +### Representation and scope + +9. The capability advertisement derives from the Machine Capsule and reuses + the machine's existing discovered evidence (CPU topology, memory map, + identity reports) rather than introducing a parallel inventory path. +10. Advertisements are bounded in size, versioned in schema, and validated on + receipt. A received advertisement grants the sender nothing; it is input + to the receiving machine's own placement and scheduling decisions. +11. Partition sovereignty (MILESTONES.md Phase 8) applies to identity: + disconnection never invalidates a `MachineId` or an advertised + capability record; a disconnected machine falls back to autonomous local + operation with its last committed records. + +### Activation boundary (post-M6) + +12. This design activates only after M6 minimal networking provides the + secure control transport. Until then, no crate implements this record; + host-side prototypes may model the data structures for discussion, but + nothing ships in the trusted base. + +## Preconditions + +Before any implementation of this record may merge: + +1. M6 minimal networking (DHCP/static IP, ARP/NDP, IP, UDP/TCP, secure + control transport) is complete and evidenced. +2. The `MachineId` provisioning flow is defined with the same + provisioning-once discipline as `LogicalAgentId` (ADR 0007), including + Recovery Core behaviour when machine identity state cannot be verified. +3. The advertisement wire format is specified with its schema version, + size bounds, signature scheme, and validation rules, and reviewed as an + irreversible data format per CONTRIBUTING.md. +4. Operator approval per the governance rule in this directory, since this + record touches persistent identity and a security boundary. + +## Invariants + +1. **Identity above machines**: the `LogicalAgentId` never depends on any + `MachineId`; machines are replaceable substrate. +2. **Brand is not identity**: no protocol field, log line, or proof receipt + may use vendor or product names where a `MachineId` belongs. +3. **AEGIS boundary**: all fabric traffic, including read-only capability + advertisement, is an external effect under AEGIS evaluation (ADR 0004). +4. **Capsule-derived advertisement**: the advertised static capability set is + derived from the Machine Capsule and native discovery evidence, not from + hand-maintained configuration. +5. **Partition sovereignty**: loss of fabric connectivity never blocks local + core operation or corrupts identity state. +6. **Secrets invariant**: NO PLAINTEXT SECRETS IN REPOSITORY OR BUILD + ARTIFACTS. +7. **Unslop standard**: zero em dashes, zero en dashes, and direct technical + documentation. + +## Consequences + +- M6 networking work can proceed knowing the fabric will use + operator-scoped pull-or-respond discovery, avoiding accidental broadcast + protocol commitments. +- Issue #36 (GB10 characterization) output feeds the accelerator entry of + the capability advertisement when the fabric activates. +- The future `crates/aienos-fabric/` crate starts from a defined identity + model and capability vocabulary rather than inventing them during Phase 8. +- State mobility (Blueprint section 26) and the heterogeneous compute + scheduler (MILESTONES.md Phase 8) consume the capability advertisement as + their placement input. +- This record remains a design record until the operator accepts it; early + discussion continues on issue #37. diff --git a/docs/adr/0011-machine-1-hardware-test-rig.md b/docs/adr/0011-machine-1-hardware-test-rig.md new file mode 100644 index 00000000..d7d2de9b --- /dev/null +++ b/docs/adr/0011-machine-1-hardware-test-rig.md @@ -0,0 +1,77 @@ +# ADR 0011: Machine 1 Hardware Test Rig (Power, Capture, Input) + +Status: proposed, 2026-09-24. Requires operator approval of the parts list +before maintainers wire anything. It does not change the boot architecture. +Governing: [MILESTONES.md gate M2C](../MILESTONES.md), +[HARDWARE_TEST_RIG.md](../HARDWARE_TEST_RIG.md), +[NATIVE_BOOT_ONE_TIME.md](../NATIVE_BOOT_ONE_TIME.md), +issue [#25](https://github.com/aien-dev/aienos/issues/25). + +## Context + +Every Spark boot needs a person at the machine: power and reset by hand, +screen evidence by photograph, and firmware interaction by keyboard. Gate M2C +requires power/reset control, HDMI capture and USB input emulation before +hardware testing can run unattended or at any cadence. A Raspberry Pi is +already cabled to the Spark and can host all three functions. + +## Decision + +Build the Machine 1 test rig as three **independent** functions on the +existing Raspberry Pi controller, with the parts list and wiring in +[HARDWARE_TEST_RIG.md](../HARDWARE_TEST_RIG.md): + +1. **Power and reset control**: reed relays across the front-panel power and + reset pins, a fail-on mains relay for hard power cut, and a `PWR_OK` sense + line for power state. +2. **Display and console capture**: a UVC HDMI capture dongle with + loop-through on the Spark's display output, and the Pi GPIO UART for the + Spark console once SPCR-based UART discovery + ([#22](https://github.com/aien-dev/aienos/issues/22)) exists. +3. **Deterministic input and boot selection**: the Pi USB OTG port as an HID + boot-protocol keyboard gadget, driven by scripted, capture-verified + keystroke sequences. + +All three functions are serialized through +`aien-proof hold --resource machine-1`, whose implementation and ledger live +in the [aien-sovereign-core](https://github.com/aien-dev/aien-sovereign-core) +repository. This repository holds the design, the operating contract and the +versioned boot sequences. + +## Invariants + +1. **Independence.** Each function fails without breaking the other two. A + failed capture never blocks power control; a dead keyboard gadget never + traps the machine. +2. **Fail-on power.** The mains relay passes power at rest, so a dead or hung + controller cannot hold the machine dark. The operator can always cut power + by hand. +3. **Momentary-only buttons.** Button relays close only for bounded intervals, + enforced in software and by the relay hardware. +4. **Read-only capture.** Capture observes; it never alters the machine. +5. **Serialized control.** Every rig function runs only inside an + `aien-proof hold --resource machine-1`; the hold output is the ledger + event. Deterministic sequences are versioned in this repository so a boot + maps to one exact commit, same rule as the staged image. +6. **No trust change.** The rig drives boots; it does not change what boots. + Secure Boot stays on and native AIENOS boots stay paused until the + owner-controlled boot chain exists. The rig adds no credentials, network + services or privileged host state to the trusted base. +7. **Off the critical path at rest.** With every relay at rest the Spark + behaves exactly as it does unwired. + +## Consequences + +- Screen evidence for boots stops depending on an operator photograph; the + post-exit drawing gap in the M2 evidence becomes a capture artifact named + in the ledger payload. +- Recovery-media testing + ([#17](https://github.com/aien-dev/aienos/issues/17)) and the TRUST-1 + 100-boot campaign can run without a person at the machine. +- The HID gadget becomes the hardware test target for the native xHCI/HID + keyboard driver ([#24](https://github.com/aien-dev/aienos/issues/24)). +- `aien-proof` gains rig commands under the existing `machine-1` resource + lock; that work lands in aien-sovereign-core, not here. +- The rig is removed piece by piece only if a native path replaces it (for + example native network control after M6); the capture and input functions + are expected to stay through the M8 demonstration. diff --git a/docs/adr/0012-self-construction-capability-growth-and-generations.md b/docs/adr/0012-self-construction-capability-growth-and-generations.md new file mode 100644 index 00000000..0a49e6e8 --- /dev/null +++ b/docs/adr/0012-self-construction-capability-growth-and-generations.md @@ -0,0 +1,189 @@ +# ADR 0012: Self-Construction, Capability Growth, and Reversible System Generations + +Status: Accepted by the operator, 2026-09-24. +Governing: [ADR 0002](0002-incumbent-os-as-migration-environment.md), [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md), [ADR 0007](0007-continuous-existence-provisioning-once.md), [ADR 0009](0009-el2-bootstrap-to-el1h-kernel-transition.md). +Roadmap: inserts SEED-0A before M3 and SEED-0B after the M3 isolation work ([`ROADMAP.md`](../../ROADMAP.md)). + +## Context + +The roadmap builds AIENOS the conventional way: a general-purpose kernel, +then storage, identity, networking, inference, and the agent. Two things +changed that. + +1. **The engineer is now an AI.** Kernel and driver work on this repository is + increasingly proposed by AI agents. On 2026-09-24 an agent produced a + 1,234-line USB keyboard driver (#58) against a ~600-line limit, and another + agent wrote an unobserved root cause into an evidence file (#56). The + deterministic gates (`scripts/verify_all.sh`, the repository rules) caught + both. The pattern is: the engineer proposes, a separate deterministic + mechanism decides. +2. **Continuity is already settled.** ADR 0007 makes AIEN provisioned once; + power-on is reconstruction, not creation. What remains open is how the + *machine around* AIEN comes to exist and change over time. + +The operator settled this through three design-interview rounds on +2026-09-24. This ADR records the result. + +## Decision + +AIEN is not distributed as a finished, universal, general-purpose operating +system. The trusted base supplies mechanisms; each machine grows the +capabilities it and its owner need, and every accepted change is a numbered, +reversible Generation admitted by deterministic gates. + +### The three pieces + +```text +AIEN SEED Continuity and recovery root. Tiny, boring, deterministic. + Establishes owner trust, identifies the machine, locates and + verifies the accepted Generation, recovers, rolls back. + Contains no model and needs none. + +AIEN FORGE The self-construction machinery: the engineering agent, + reproducible builds, Worlds, tests, proofs, benchmarks. + +AIEN GENERATION The current accepted expression of one machine: + capabilities + policies + interface + state. +``` + +The Seed and Forge machinery may have versioned releases. A person's complete +AIEN is never a universal release; each machine evolves through its own +Generations. + +### Rules + +1. **Prove locally, design generally.** Machine 1 (the Spark) is the proving + ground. Nothing fundamental is Spark-specific unless it sits behind a + machine/BSP boundary. +2. **Survival kit, then growth.** Every AIEN has what it needs to exist and + recover: console/display, input, storage, networking, time, recovery, + identity, and the Forge machinery. Everything else is grown when required. +3. **The agent is an untrusted proposer.** The model may write, adapt, + diagnose, and optimize. Candidate code never authorizes itself; every + candidate passes deterministic admission gates. +4. **Admission is not permission.** A verified, reversible capability (for + example a camera driver) may be admitted automatically. Using it for + privacy, external communication, destructive storage changes, security + roots, encryption, credentials, identity, or other irreversible effects + still requires owner policy through AEGIS. The owner approves durable + policies rather than individual interruptions. +5. **No native admission without enforcement.** Generated native components + run on the physical machine only after enforceable memory, DMA (SMMU), and + capability isolation exist (M3). Before that, a candidate can prove only + that it passed every test we know how to run. +6. **Generations.** Every accepted system state is an immutable, numbered + Generation recording: parent, source provenance, build provenance, code + hashes, tests, proof receipts, capability grants, hardware target, + benchmark evidence, and rollback target. Activation is inactive-slot plus + canary promotion. Failure never destroys the previous accepted Generation. + Recovery never requires a model. +7. **Two records per capability.** + + ```text + Capability Artifact what was built: source and provenance, supported + hardware constraints, tests, known proofs and failures + Capability Admission this MachineId, this firmware/hardware state, the + local verification receipt, the granted resource + envelope, the Generation it entered + ``` + +8. **Knowledge is shareable; trust is not transferable.** Artifacts move + freely between the owner's machines and, later, through a public + content-addressed commons between people. A proof on machine A is evidence, + not authority, for machine B: every receiving machine rebuilds or + reproduces where practical, checks hardware/firmware prerequisites, reruns + the deterministic tests, runs its own constrained canary, and issues its + own admission. Exact hardware/firmware matches may shorten validation. + Source is preferred; prebuilt binaries are caches that must trace back to + source and build provenance. +9. **Outside code enters as source.** Externally sourced code enters as + auditable source with provenance. Runtime dependence on arbitrary Internet + code is forbidden. +10. **Rollback first, repair second.** When a live capability violates its + health contract, AIEN quarantines it and restores the most recent + known-good Generation without waiting for the owner, preserves the + evidence, diagnoses in an isolated World, and promotes a repair only + through the normal proof pipeline and canary. Repeated failed repairs stop + and are reported; there is no endless self-modification loop. For + security-sensitive anomalies: revoke access first, investigate second. +11. **Honest failure, then compatibility, then optional escalation.** When AIEN + cannot build a capability it says so plainly and why. If the owner allows + it, a sealed incumbent-OS island may provide the capability temporarily + (e.g. `camera.native unavailable`, `camera.compat.win available`). With + explicit permission only, AIEN may publish a sanitized failure package to + the commons. Compatibility fills gaps; it never becomes a hidden permanent + dependency and stays visible as debt Forge keeps working to remove. +12. **Incumbent OS as scaffolding.** Per ADR 0002, an `aien-bootstrap` path may + start inside Windows, macOS, or Linux as the normal entry for new machines: + inspect the machine, build the Machine Capsule, allocate AIEN storage, run + Forge, import data, and prepare the first native Generation. The Seed must + boot independently and survive deletion of the incumbent OS. Machine 1 has + already crossed into native execution and does not regress to this path. +13. **Owner-priority resource budget.** Forge runs any time but yields to the + person immediately, under an explicit compute budget: small while the + owner is active, larger while idle, temporarily raised (with visible + status) for an urgent request. Values are learned per owner and machine, + not hard-coded. Natural statements ("use everything overnight", "not while + I'm gaming") compile into explicit resource policy. +14. **Execution state is bounded; provenance is permanent.** + + ```text + PERMANENT Generation manifests, provenance, hashes, + proof receipts, security events, + migration/identity history, + owner-important records + PINNED UNTIL OWNER RELEASES preserved Generations, major migration and + recovery checkpoints + FULLY RESTORABLE WINDOW current Generation + the most recent + known-good Generations (e.g. 3-5) + RECLAIMABLE superseded binaries, duplicate build outputs, + test environments, caches, model + reconstruction state, abandoned candidates + ``` + + Storage is content-addressed: shared objects are stored once and collected + only when nothing retained references them. Security rollback history and + identity continuity records are never collected for age. + +### Roadmap + +```text +M0 / M1 / M2 + -> SEED-0A Self-construction lab (now) + -> M3 Kernel isolation: the enforcement substrate + -> SEED-0B Native capability admission + -> M4+ +``` + +**SEED-0A** can run now: the agent observes the machine, writes or adapts +code, builds reproducibly, runs the deterministic checks, tests in QEMU, +benchmarks, produces a proof receipt, and creates an *inactive* candidate +Generation. It does not claim the candidate is safe to run unrestricted on +hardware. Experiment #1 is `input.keyboard.usb` (#58). The Machine 1 hardware +test rig (ADR 0011) is the physical admission lab that later closes the loop: +candidate, proof, QEMU canary, Machine 1 lock, staged one-time boot, HDMI and +UART capture, automated verdict, automatic rollback. + +**SEED-0B** follows the M3 isolation pieces (MMU, SMMU/DMA isolation, +exception boundaries, interrupt ownership, capability handles, task isolation, +resource accounting): generated code is admitted into a constrained world on +the physical machine, canaried, and promoted or destroyed. + +## Consequences + +- M3 is built as the enforcement substrate for generated code, not only as a + conventional kernel milestone. Its acceptance should include "a candidate + component can be confined to named pages, DMA windows, and devices". +- Every later milestone delivers mechanisms plus the capabilities of the + survival kit, not a universal feature set. +- Evidence rules tighten for agents: a candidate's proof states what was + tested (QEMU, host, hardware) and never implies hardware behavior it did not + observe. +- The hardware test rig (ADR 0011) becomes a priority, since it turns the + physical step from an operator task into an automated gate. +- Capability records, Generation manifests, and the retention tiers become + persistent formats; their concrete schemas need their own ADRs before M4 + storage work fixes them. +- The owner is not the system administrator: AIEN is highly autonomous about + engineering, conservative about authority, and nearly invisible about + maintenance. diff --git a/docs/adr/README.md b/docs/adr/README.md index 1c72ebf5..b0677e2b 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -15,6 +15,9 @@ This directory documents the key architectural decisions and formal technical sp | [ADR 0007](0007-continuous-existence-provisioning-once.md) | Continuous Existence and Provisioning-Once | Accepted | 2026-09-23 | [`CONTINUOUS_EXISTENCE_AMENDMENT.md`](../CONTINUOUS_EXISTENCE_AMENDMENT.md); [`ARCHITECTURE.md` §1, §10](../ARCHITECTURE.md); [`SYSTEMS_INTEGRATION_SEQUENCE.md` Steps 1–10](../SYSTEMS_INTEGRATION_SEQUENCE.md); [`MILESTONES.md` Phase 3, 6, 8](../MILESTONES.md); [ADR 0005](0005-unified-memory-c1-cow-and-reservation-accounting.md); [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md) | | [ADR 0008](0008-temporary-bring-up-firmware-report-exception.md) | Temporary bring-up exception: post-handoff firmware report (trigger 11) | Accepted (temporary) | 2026-09-24 | [ADR 0003](0003-bootstrap-firmware-handoff-and-minimal-object-store.md); [`MILESTONES.md` section 0](../MILESTONES.md); [`NATIVE_BOOT_ONE_TIME.md`](../NATIVE_BOOT_ONE_TIME.md) | | [ADR 0009](0009-el2-bootstrap-to-el1h-kernel-transition.md) | Two-Stage Exception Level Architecture (EL2 Bootstrap to EL1h Kernel) | Accepted | 2026-09-24 | [`ARCHITECTURE.md` §3, §6](../ARCHITECTURE.md); [`BLUEPRINT.md` §8, §15](../BLUEPRINT.md); [`MILESTONES.md` Phase 2, 3](../MILESTONES.md) | +| [ADR 0010](0010-fabric-machine-identity-and-capability-advertisement.md) | Fabric Machine Identity and Capability Advertisement | Proposed (post-M6) | 2026-09-24 | [`ARCHITECTURE.md` §2](../ARCHITECTURE.md); [`BLUEPRINT.md` §21, §25, §26](../BLUEPRINT.md); [`MILESTONES.md` Phase 8](../MILESTONES.md); [ADR 0004](0004-reversibility-definition-and-network-effect-boundary.md); [ADR 0007](0007-continuous-existence-provisioning-once.md); [issue #37](https://github.com/aien-dev/aienos/issues/37) | +| [ADR 0011](0011-machine-1-hardware-test-rig.md) | Machine 1 Hardware Test Rig (Power, Capture, Input) | Proposed | 2026-09-24 | [`MILESTONES.md` section 0, gate M2C](../MILESTONES.md); [`HARDWARE_TEST_RIG.md`](../HARDWARE_TEST_RIG.md); [`NATIVE_BOOT_ONE_TIME.md`](../NATIVE_BOOT_ONE_TIME.md) | +| [ADR 0012](0012-self-construction-capability-growth-and-generations.md) | Self-Construction, Capability Growth, and Reversible System Generations | Accepted | 2026-09-24 | [ADR 0002](0002-incumbent-os-as-migration-environment.md); [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md); [ADR 0007](0007-continuous-existence-provisioning-once.md); [`ROADMAP.md`](../../ROADMAP.md) (SEED-0A, SEED-0B) | --- diff --git a/evidence/gate1_machine1_selftest_2026-09-24.md b/evidence/gate1_machine1_selftest_2026-09-24.md new file mode 100644 index 00000000..aa82223e --- /dev/null +++ b/evidence/gate1_machine1_selftest_2026-09-24.md @@ -0,0 +1,86 @@ +# TRUST-1 Gate 1: recovery stick boots on Machine 1 (2026-09-24) + +Result: **partial PASS on hardware.** The dedicated recovery stick boots on +Machine 1 with Secure Boot on, runs entirely from RAM, finds the keyboard, +the stick and the internal NVMe, reads Secure Boot state and TPM PCRs, saves +its report, and returns to Linux on its own. The unlock, reinstall and +restore items (9 to 14) and the test-artifact round trip are not done yet. + +## What ran + +- Media: `AIENOSRECOV` (1 GB USB stick, USB serial 5D0344B4, vfat UUID + 3511-E686, GPT PARTUUID f227357c-1e80-4fd0-a55e-2efbef1dd25c), written by + `scripts/build_recovery_media.sh` at main 0379b2f (#53). This is the former + ATLAS_RECOV stick; the operator authorized wiping it on 2026-09-24. +- Trigger: `aienos-selftest-once` flag on the stick, `efibootmgr -n 0004`, + `shutdown -r` at 08:07:31 CDT. No keyboard input. +- Boot chain: firmware -> `EFI/BOOT/BOOTAA64.EFI` (Ubuntu shim, identical to + the internal `EFI/ubuntu/shimaa64.efi`) -> signed GRUB -> signed kernel + 7.0.0-1019-nvidia -> RAM initrd. + +| File on the stick | SHA-256 | +|---|---| +| `EFI/BOOT/BOOTAA64.EFI` | `706f15b9578f780a2fddda8ee0806cd15b59124692cc297db320414a5a40fe44` | +| `EFI/BOOT/grubaa64.efi` | `b9d9dd81845d68a1f1867b5bcf26393908a9a349e749ce8ea944a1066d9abfcc` | +| `EFI/BOOT/mmaa64.efi` | `afc533e2ccc208cd1fa6e1e88a3d6a79faa1de5eb0f2d58eab2fdd228b0021df` | +| `EFI/BOOT/grub.cfg`, `EFI/ubuntu/grub.cfg` | `e551c5175c8b62de98cf6fbffb11c8702d451c751060062b92eff8123c9b7b91` | +| `aienos-recovery/vmlinuz` | `ddd5a25c2326fbfdf7e03809c614fafe5a953416bbb1b80f9c2258f7260e44e3` | +| `aienos-recovery/initrd.img` | `d04ede86813c347a41ec7f24674c3a07555fae5719c0202c0361b5c0b3f2b390` | + +## Evidence + +- Report written by the recovery environment to the stick, copied verbatim: + [gate1_machine1_selftest_report_2026-09-24.txt](gate1_machine1_selftest_report_2026-09-24.txt) + (SHA-256 `3a4a6deb894e61527557968c3591fbfb31029779921d428921235caca7b89486`). +- Operator photograph of the Machine 1 screen at 13:09:48Z showing the same + report and the self-test countdown. Kept offline because phone photos carry + location metadata; SHA-256 + `01f77ba2a06620de2ceaab9d196b1948d3063f907a67f65ef69222fa39e0dfa6`. +- After return: `BootCurrent: 0001`, BootNext consumed, BootOrder unchanged + (`0001,0003,0004`), flag removed from the stick, `mokutil --sb-state` + enabled, `atlas-private-storage` active. + +## Gate 1 acceptance (TRUST-1 plan, all with Secure Boot on) + +| # | Test | Result | +|---|---|---| +| 1 | Firmware accepts recovery image | PASS: `BootCurrent: 0004` inside the recovery report | +| 2 | Starts without internal Linux | PASS: RAM root, internal NVMe never mounted | +| 3 | No network required | PASS: the image has no network configuration or network tools | +| 4 | No model required | PASS | +| 5 | No Cortex required | PASS | +| 6 | Identifies NVMe and encrypted volumes | PARTIAL: NVMe and partitions identified; the gocryptfs private store lives inside the ext4 root and is not identified | +| 7 | Inspects Secure Boot state | PASS: `Secure Boot: enabled`, lockdown `integrity` | +| 8 | Inspects PCRs | PASS: PCR 0 and 7 equal the Gate 0 baseline values | +| 9 | Shows AIENOS A/B slots and manifests | PENDING: A/B slots do not exist yet | +| 10 | Verifies signatures/hashes | PENDING | +| 11 | Independent recovery only when authorized | PENDING | +| 12 | Mounts recovered storage safely | PENDING | +| 13 | Reinstalls known-good loader/slot | PENDING | +| 14 | Restores documented boot config | PENDING (boot entries are read; efivarfs is mounted read-only) | +| 15 | Returns to known-good Linux | PASS: restarted unattended, Linux default boot | +| 16 | No destructive overwrite | PASS: the only write was the report and flag removal on the stick | +| - | Test-artifact round trip | PENDING | +| - | Keyboard | PASS for detection (HP Wired Desktop 320K and Logitech devices bound); typing not exercised in this unattended run | + +## Findings + +- **First attempt failed with "Secure Boot Violation".** A firmware boot entry + `Boot0000 "AIENOS"` had been created outside Linux pointing directly at + `\aienos-recovery\vmlinuz`, bypassing shim; the firmware db does not trust + the Ubuntu kernel signature directly. The stick itself was not at fault. + The entry was deleted with operator approval. +- **Existing Linux boot race.** On this boot and the previous normal boot, + the first `atlas-private-storage` unseal failed with TPM error 0x128 + (`TPM_RC_PCR_CHANGED`) and the automatic retry succeeded. It predates the + recovery boot; PCR 7 is unchanged. +- **Tooling defects fixed in #53:** no kernel modules in the initrd (no USB, + keyboard or NVMe), shell on the unreachable serial console, and `/bin/blkid` + silently missing from the initrd (the earlier Gate 1 receipt lists it). + +## Offline key custody (Gate 0 follow-up) + +`atlas-forge-state-luks-recovery-key.txt.age` (age recipient tag `+4nykQ`, +the operator's MacBook SSH key) now exists as ciphertext on Machine 1 and on +the operator MacBook. Decryption has still not been exercised; Gate 0's +independent-access proof remains open. diff --git a/evidence/gate1_machine1_selftest_report_2026-09-24.txt b/evidence/gate1_machine1_selftest_report_2026-09-24.txt new file mode 100755 index 00000000..368fddef --- /dev/null +++ b/evidence/gate1_machine1_selftest_report_2026-09-24.txt @@ -0,0 +1,40 @@ +============================================================ +AIENOS Standalone Hardware Recovery Core +Root filesystem: 100% RAM disk (Self-contained) +Internal NVMe status: UNMOUNTED +============================================================ + +Secure Boot: enabled +Kernel lockdown: none [integrity] confidentiality +Kernel modules loaded: 16/16 +Input devices: 7 + Power Button + Lid Switch + Sleep Button + Logitech M510 + Chicony HP Wired Desktop 320K Keyboard + Chicony HP Wired Desktop 320K Keyboard Consumer Control + Chicony HP Wired Desktop 320K Keyboard System Control +Kernel: 7.0.0-1019-nvidia Clock (UTC): 2026-09-24T13:09:45Z +TPM PCR 0 (sha256): 3D458CFE55CC03EA1F443F1562BEEC8DF51C75E14A9FCF9A7234A13F198E7969 +TPM PCR 7 (sha256): D76B3540204A6CE15763B17036028603ADF9774A03D91BFDA2792D8E91CF3046 + +Block device topology: +NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS +sda 8:0 1 960M 0 disk +`-sda1 8:1 1 958M 0 part +nvme0n1 259:0 0 3.7T 0 disk +|-nvme0n1p1 259:1 0 298M 0 part +`-nvme0n1p2 259:2 0 3.7T 0 part + /dev/sda1: DEVNAME=/dev/sda1 LABEL=AIENOSRECOV UUID=3511-E686 TYPE=vfat + /dev/nvme0n1p1: DEVNAME=/dev/nvme0n1p1 LABEL=EFI UUID=9DA2-3597 TYPE=vfat + /dev/nvme0n1p2: DEVNAME=/dev/nvme0n1p2 LABEL=root UUID=d27bfd26-ff30-400e-9eca-9cdf73de9406 TYPE=ext4 + +Firmware boot entries: + BootCurrent: 0004 + Timeout: 1 seconds + BootOrder: 0001,0003,0004 + Boot0001* ubuntu HD(1,GPT,7c2b24e9-0ceb-4ad7-a401-9bf3c92c26ee,0x800,0x95000)/File(\EFI\ubuntu\shimaa64.efi) File(.) + Boot0003* UEFI: PXE IPv4 Realtek PCIe 10 GBE Family Controller PcieRoot(0x7)/Pci(0x0,0x0)/Pci(0x0,0x0)/MAC(4cbb472bb87b,0)/IPv4(0.0.0.00.0.0.0,0,0)0000424f + Boot0004* UEFI: USB USB Hard Drive, Partition 1 VenHw(0d51905b-b77e-452a-a2c0-eca0cc8d514a,0000b91d0000000000)/USB(1,0)/USB(1,0)/HD(1,GPT,f227357c-1e80-4fd0-a55e-2efbef1dd25c,0x800,0x1df000)0000424f + diff --git a/evidence/recovery_boot_machine1.md b/evidence/recovery_boot_machine1.md new file mode 100644 index 00000000..4666eba1 --- /dev/null +++ b/evidence/recovery_boot_machine1.md @@ -0,0 +1,57 @@ +# Recovery media boot on Machine 1: evidence + +**Status: PENDING ATTENDED EXERCISE.** The repair-tool additions to the +recovery initrd, the tooling check, and the read-only evidence collector are +merged and host-verified (QEMU, no real devices). No hardware boot with +these tools has happened yet. The physical USB boot on the DGX Spark +(spark-b87b) is an operator-run, physical-access step scheduled under +TRUST-1 Gate 1. **The `AIENOSRECOV` stick must be rebuilt with +`scripts/build_recovery_media.sh` first** -- the stick as last written (#53) +predates the repair tools this record is about. This file becomes the +record of that boot; nothing below is a claim that it already happened. + +Procedure: [docs/RECOVERY_MEDIA_MACHINE1.md](../docs/RECOVERY_MEDIA_MACHINE1.md). +Gate: [issue #17](https://github.com/aien-dev/aienos/issues/17), +TRUST-1 Gate 1 ([docs/TRUST-1-IMPLEMENTATION-PLAN.md](../docs/TRUST-1-IMPLEMENTATION-PLAN.md)). + +## What is already proven (no hardware) + +| Proof | Where | Result | +| --- | --- | --- | +| Zero-disk RAM boot (no internal storage dependency) | `scripts/qemu_verify_recovery_media.sh` | PASS (QEMU, aarch64 host) | +| Initrd ships mount / EFI repair / boot-entry restore tooling | `scripts/verify_recovery_tools.sh` | PASS (host, static check) | +| Recovery stick boots on Machine 1 with Secure Boot on, returns unattended (previous initrd, without repair tools) | [gate1_machine1_selftest_2026-09-24.md](gate1_machine1_selftest_2026-09-24.md) | PASS on hardware (#53) | +| Internal NVMe / active-mount overwrite guards | `scripts/build_recovery_media.sh` identity checks | enforced at build (unchanged by this PR) | + +## What the attended exercise must record + +Run under `aien-proof hold --resource machine-1 --job recovery-boot-evidence`. +`scripts/collect_recovery_boot_evidence.sh` must print +`RECOVERY_BOOT_GATE: PASS`, which requires all of: + +- `booted_from_removable_media`: the running root is the USB, not the NVMe. +- `secure_boot_state_recorded`: Secure Boot byte read from efivars. +- `nvme_root_mounted` + `nvme_root_is_internal`: internal NVMe root mounted + by the operator from the recovery shell (Step 4.1 of the runbook). +- `esp_mounted` + `esp_fallback_bootloader_present`: `/boot/efi` mounted and + the shim/GRUB fallback chain confirmed present (Step 4.2). +- `efi_variables_present` + `efibootmgr_readable`: boot entries restorable + (Step 4.3). + +The collector is read-only; it never writes to the ESP, the NVMe root, or +BootOrder. + +## Boot record (fill in after the exercise) + +| Item | Value | +| --- | --- | +| Date (UTC) | _pending_ | +| Operator | _pending_ | +| aien-proof ledger events | _pending_ | +| Media device | _pending_ | +| Kernel booted | _pending_ | +| Secure Boot during boot | _pending_ | +| NVMe root device mounted | _pending_ | +| `/boot/efi` fallback bootloader present | _pending_ | +| Boot entries after inspection/restore | _pending_ | +| `RECOVERY_BOOT_GATE` | _pending_ | diff --git a/funding.json b/funding.json new file mode 100644 index 00000000..1f3a3385 --- /dev/null +++ b/funding.json @@ -0,0 +1 @@ +{"$schema":"https://fundingjson.org/schema/v1.1.0.json","entity":{"description":"Solo founder of AIENOS, building nights and weekends alongside full-time work as a product engineer at 3M in Springfield, Missouri. Not a programmer by training: everything technical in AIENOS was built by conducting AI models, describing the goal and testing the result against reality. No company, no team, no outside funding. Project contact: aien@aienos.com.","email":"drake@aienos.com","name":"Drake Stapleton","phone":"1-270-872-3784","role":"owner","type":"individual","webpageUrl":{"url":"https://aienos.com"}},"funding":{"channels":[{"address":"drake@aienos.com","description":"Contact to arrange a transfer. GitHub Sponsors profile is being set up; no payment details are published in this manifest.","guid":"contact-email","type":"other"}],"plans":[{"amount":0,"channels":["contact-email"],"currency":"USD","description":"A one-time grant toward independent security review of the UEFI boot chain and reproducible-build plus continuous-benchmark infrastructure, so every AIENOS claim ships with a receipt anyone can re-run.","frequency":"one-time","guid":"one-time-grant","name":"One-time grant or donation","status":"active"},{"amount":0,"channels":["contact-email"],"currency":"USD","description":"Recurring monthly support for ongoing solo development of AIENOS.","frequency":"monthly","guid":"monthly-support","name":"Monthly supporter","status":"active"}]},"projects":[{"description":"AIENOS is an agent-first operating system that boots bare metal into its own deterministic kernel, independent of Linux, Windows, and macOS. The AI agent is a first-class citizen of the OS: persistent, private, yours, on hardware you hold, in software you can read. Thesis: intelligence should be property, not rent. Measured receipts (public in the repo): native boot on an NVIDIA DGX Spark on 2026-09-24 with AIENOS code running at EL2 and no Linux underneath (console: kernel: alive, machine returned to Linux undamaged); 553 tokens/sec inference (TinyLlama 1.1B BF16, concurrency 16, zero fallback); 500 reasoning branches forked in 1.20 ms using 704 MB instead of a 343 GB unshared-copy baseline (500x saving). Pre-alpha and experimental. License: Apache-2.0 WITH LLVM-exception (SPDX: Apache-2.0 WITH LLVM-exception), an OSI-approved open source license.","guid":"aienos","licenses":["Apache-2.0 WITH LLVM-exception"],"name":"AIENOS","repositoryUrl":{"url":"https://github.com/aien-dev/aienos"},"tags":["operating-system","inference","local-ai","gpu","ai-agents","self-hosted","arm","systems","open-weights","kernel"],"webpageUrl":{"url":"https://aienos.com"}}],"version":"v1.1.0"} \ No newline at end of file diff --git a/scripts/build_recovery_media.sh b/scripts/build_recovery_media.sh index 4439191e..7c916ef5 100755 --- a/scripts/build_recovery_media.sh +++ b/scripts/build_recovery_media.sh @@ -93,14 +93,16 @@ echo "Copying standalone recovery initrd to media..." sudo cp "${INITRD_TMP}" "${MOUNT_POINT}/aienos-recovery/initrd.img" rm -f "${INITRD_TMP}" -# Create standalone recovery GRUB config that boots directly to RAM maintenance shell +# Create standalone recovery GRUB config that boots directly to RAM maintenance shell. +# The last console= is /dev/console, where the shell runs: tty0 (the screen), +# because Machine 1 has no reachable serial console. cat << "GRUB_EOF" | sudo tee "${MOUNT_POINT}/EFI/BOOT/grub.cfg" > /dev/null set timeout=5 set default=0 menuentry "AIENOS Standalone Recovery System (RAM Maintenance Core)" { search --no-floppy --file --set=root /aienos-recovery/vmlinuz - linux /aienos-recovery/vmlinuz rdinit=/init console=tty0 console=ttyAMA0,115200n8 quiet + linux /aienos-recovery/vmlinuz rdinit=/init console=ttyAMA0,115200n8 console=tty0 quiet initrd /aienos-recovery/initrd.img } @@ -108,6 +110,10 @@ menuentry "Reboot to Incumbent Linux" { exit } GRUB_EOF +# Ubuntu's signed GRUB reads $prefix/grub.cfg (/EFI/ubuntu) before the copy +# next to itself, so both must carry the same menu. +sudo mkdir -p "${MOUNT_POINT}/EFI/ubuntu" +sudo cp "${MOUNT_POINT}/EFI/BOOT/grub.cfg" "${MOUNT_POINT}/EFI/ubuntu/grub.cfg" sync echo "AIENOS standalone recovery media build complete on ${TARGET_DEV}." diff --git a/scripts/build_standalone_recovery_initrd.sh b/scripts/build_standalone_recovery_initrd.sh index e4d4c402..44628147 100755 --- a/scripts/build_standalone_recovery_initrd.sh +++ b/scripts/build_standalone_recovery_initrd.sh @@ -23,7 +23,7 @@ BINARIES=( /bin/sh /bin/bash /bin/lsblk - /bin/blkid + /sbin/blkid /bin/mount /bin/umount /bin/mkdir @@ -35,6 +35,13 @@ BINARIES=( /usr/bin/tpm2_pcrread /usr/bin/efibootmgr /sbin/cryptsetup + # Repair tools for issue #17: repair /boot/efi (fsck.vfat, mkfs.vfat), + # check the NVMe root filesystem (fsck.ext4), and chroot into it to + # restore boot entries from the installed bootloader. + /usr/sbin/fsck.vfat + /usr/sbin/mkfs.vfat + /usr/sbin/fsck.ext4 + /usr/sbin/chroot ) for bin in "${BINARIES[@]}"; do @@ -49,6 +56,9 @@ for bin in "${BINARIES[@]}"; do fi done fi + else + echo "Error: required recovery binary $bin not found on the build host" >&2 + exit 1 fi done @@ -66,6 +76,46 @@ if [[ -f "$GOCRYPTFS_BIN" ]]; then fi fi +# Kernel drivers the recovery shell needs on Machine 1 that the Ubuntu kernel +# builds as modules: the ACPI xHCI controllers (NVDA8000), USB and Logitech +# keyboards, USB sticks, the internal NVMe, dm-crypt and FAT text encodings. +# Modules must match the kernel the callers copy: the newest /boot/vmlinuz-*. +KVER="${AIENOS_RECOVERY_KVER:-$(basename "$(ls -1t /boot/vmlinuz-* | head -n 1)" | sed 's/^vmlinuz-//')}" +RECOVERY_MODULES=( + xhci-plat-hcd + usbhid hid-generic hid-logitech-dj hid-logitech-hidpp + usb-storage uas + nvme + dm-crypt + nls_iso8859-1 nls_utf8 +) + +mkdir -p "$WORK_DIR/lib/modules/aienos" "$WORK_DIR/etc" +: > "$WORK_DIR/etc/aienos-modules.order" +for mod in "${RECOVERY_MODULES[@]}"; do + deps=$(modprobe -S "$KVER" --show-depends "$mod") || { + echo "Error: module $mod not found for kernel $KVER" >&2 + exit 1 + } + # Dependencies come first; builtin lines need nothing copied. + while read -r kind path _; do + [[ "$kind" == "insmod" ]] || continue + name=$(basename "$path") + name="${name%.zst}" + name="${name%.xz}" + grep -qxF "$name" "$WORK_DIR/etc/aienos-modules.order" && continue + # Decompress so busybox insmod can load it; the signature appended + # before compression is kept, so Secure Boot lockdown still accepts it. + case "$path" in + *.zst) zstd -q -d -c "$path" > "$WORK_DIR/lib/modules/aienos/$name" ;; + *.xz) xz -d -c "$path" > "$WORK_DIR/lib/modules/aienos/$name" ;; + *) cp -p "$path" "$WORK_DIR/lib/modules/aienos/$name" ;; + esac + echo "$name" >> "$WORK_DIR/etc/aienos-modules.order" + done <<< "$deps" +done +echo "Packaged $(wc -l < "$WORK_DIR/etc/aienos-modules.order") kernel modules for $KVER" + # Create standalone init script cat << 'INIT_EOF' > "$WORK_DIR/init" #!/bin/busybox sh @@ -77,23 +127,116 @@ cat << 'INIT_EOF' > "$WORK_DIR/init" mount -t proc proc /proc mount -t sysfs sysfs /sys mount -t devtmpfs devtmpfs /dev +mount -t securityfs securityfs /sys/kernel/security 2>/dev/null +# Read-only: recovery must opt in explicitly before changing firmware variables. +mount -t efivarfs -o ro efivarfs /sys/firmware/efi/efivars 2>/dev/null + +secure_boot="unknown (no EFI variables)" +sb_var=/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c +if [ -r "$sb_var" ]; then + # 4 attribute bytes, then 1 data byte. busybox od ignores -j with -N, + # so read the last byte with tail. + case "$(tail -c1 "$sb_var" | od -An -tu1 | tr -d ' ')" in + 1) secure_boot="enabled" ;; + 0) secure_boot="disabled" ;; + *) secure_boot="unreadable" ;; + esac +fi +lockdown=$(cat /sys/kernel/security/lockdown 2>/dev/null || echo "unavailable") + +loaded=0 +failed="" +while read -r mod; do + if insmod "/lib/modules/aienos/$mod" 2>/dev/null; then + loaded=$((loaded + 1)) + else + failed="$failed $mod" + fi +done < /etc/aienos-modules.order +total=$(wc -l < /etc/aienos-modules.order) +# Give USB and NVMe time to enumerate before listing disks. +sleep 3 + +{ + echo "============================================================" + echo "AIENOS Standalone Hardware Recovery Core" + echo "Root filesystem: 100% RAM disk (Self-contained)" + echo "Internal NVMe status: UNMOUNTED" + echo "============================================================" + echo "" + echo "Secure Boot: $secure_boot" + echo "Kernel lockdown: $lockdown" + echo "Kernel modules loaded: $loaded/$total" + [ -n "$failed" ] && echo "Kernel modules failed:$failed" + echo "Input devices: $(ls /sys/class/input 2>/dev/null | grep -c '^input')" + cat /sys/class/input/input*/name 2>/dev/null | sed 's/^/ /' + echo "Kernel: $(uname -r) Clock (UTC): $(date -u +%Y-%m-%dT%H:%M:%SZ)" + for pcr in 0 7; do + echo "TPM PCR $pcr (sha256): $(cat /sys/class/tpm/tpm0/pcr-sha256/$pcr 2>/dev/null || echo unavailable)" + done + echo "" + echo "Block device topology:" + lsblk 2>/dev/null || true + for part in /dev/sd*[0-9] /dev/nvme*n*p*; do + [ -b "$part" ] && echo " $part: $(blkid -p -o export -s LABEL -s TYPE -s UUID "$part" 2>/dev/null | tr "\n" " ")" + done + echo "" + echo "Firmware boot entries:" + efibootmgr 2>/dev/null | sed 's/^/ /' || echo " unavailable" + echo "" +} > /tmp/recovery-report 2>&1 + +# One-shot unattended self-test: Linux leaves aienos-selftest-once on the +# stick. Only then is the stick mounted read-write, the flag removed and the +# report saved; an ordinary recovery boot never writes anywhere. +selftest=0 +# Probe partitions directly: without udev, blkid -L and lsblk see no labels. +stick="" +for part in /dev/sd*[0-9] /dev/nvme*n*p*; do + [ -b "$part" ] || continue + if [ "$(blkid -p -o value -s LABEL "$part" 2>/dev/null)" = AIENOSRECOV ]; then + stick="$part" + break + fi +done +if [ -n "$stick" ]; then + mkdir -p /mnt/stick + if mount -t vfat -o ro "$stick" /mnt/stick 2>/dev/null; then + if [ -f /mnt/stick/aienos-selftest-once ] && mount -o remount,rw /mnt/stick 2>/dev/null; then + selftest=1 + rm -f /mnt/stick/aienos-selftest-once + mkdir -p /mnt/stick/aienos-evidence + cp /tmp/recovery-report "/mnt/stick/aienos-evidence/selftest-$(date -u +%Y%m%dT%H%M%SZ).txt" + sync + fi + umount /mnt/stick + fi +fi clear -echo "============================================================" -echo "AIENOS Standalone Hardware Recovery Core" -echo "Root filesystem: 100% RAM disk (Self-contained)" -echo "Internal NVMe status: UNMOUNTED" -echo "============================================================" -echo "" -echo "Block device topology:" -lsblk -f 2>/dev/null || blkid 2>/dev/null || true -echo "" +cat /tmp/recovery-report +# The shell lives on /dev/console (the screen on Machine 1). Mirror the report +# to the serial port too, so emulator tests can read it; bounded so a serial +# port with no carrier can never delay the shell. +if [ -c /dev/ttyAMA0 ]; then + timeout 2 sh -c 'cat /tmp/recovery-report > /dev/ttyAMA0' 2>/dev/null & +fi if grep -q "aienos.test=1" /proc/cmdline 2>/dev/null; then echo "TEST MODE DETECTED: automated recovery verification complete." poweroff -f 2>/dev/null || reboot -f 2>/dev/null || exit 0 fi +if [ "$selftest" = 1 ]; then + echo "SELF-TEST: report saved to the recovery stick (aienos-evidence/)." + echo "Press Enter within 60 s to stay in the recovery shell; otherwise the machine restarts." + if ! read -t 60 _; then + echo "SELF-TEST: restarting." + sync + reboot -f + fi +fi + echo "Dropping into standalone maintenance shell." echo "Type 'reboot' or 'poweroff' when recovery verification completes." echo "" diff --git a/scripts/collect_recovery_boot_evidence.sh b/scripts/collect_recovery_boot_evidence.sh new file mode 100755 index 00000000..ea6cfc09 --- /dev/null +++ b/scripts/collect_recovery_boot_evidence.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# collect_recovery_boot_evidence.sh: Record evidence that the AIENOS recovery +# USB actually booted Machine 1 into a rescue environment that can mount the +# NVMe root, repair /boot/efi, and restore boot entries (issue #17). +# +# Run this on Machine 1 (spark-b87b), booted from the recovery USB, under: +# aien-proof hold --resource machine-1 --job recovery-boot-evidence -- \ +# bash scripts/collect_recovery_boot_evidence.sh /mnt/root +# +# Optional first argument: where the NVMe root is already mounted (default +# /mnt/root). This script is READ-ONLY: it never formats, never deletes, +# never writes to the ESP or the NVMe root, and never changes BootOrder. It +# only inspects mount state, filesystem presence, and firmware variables +# that are already exposed read-only by the kernel. +set -uo pipefail + +ROOT_MNT="${1:-/mnt/root}" +ESP_MNT="${AIENOS_ESP_MNT:-${ROOT_MNT}/boot/efi}" +FAILED=0 + +check() { # name, pass(0/1), detail + if [[ "$2" == 1 ]]; then + echo "PASS $1: $3" + else + echo "FAIL $1: $3" + FAILED=1 + fi +} + +echo "== recovery environment identity" +echo "captured_utc: $(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown)" +echo "kernel: $(uname -r 2>/dev/null || echo unknown)" +echo "cmdline: $(cat /proc/cmdline 2>/dev/null || echo unknown)" +echo "hostname: $(cat /proc/sys/kernel/hostname 2>/dev/null || echo unknown)" + +echo "== media identity (this boot's root)" +root_src="$(findmnt -no SOURCE / 2>/dev/null || echo unknown)" +echo "root_source: ${root_src}" +check "booted_from_removable_media" \ + "$(findmnt -no SOURCE / 2>/dev/null | grep -qE 'sd|usb|mapper|/dev/ram|rootfs|tmpfs' && echo 1 || echo 0)" \ + "root is ${root_src} (not the internal NVMe)" + +echo "== secure boot state" +sb="unknown" +sb_var="/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c" +if [[ -r "${sb_var}" ]]; then + sb="$(od -An -t u1 -j 4 -N 1 "${sb_var}" 2>/dev/null | tr -d ' ')" +fi +echo "secure_boot_byte: ${sb}" +check "secure_boot_state_recorded" "$([[ "${sb}" == "0" || "${sb}" == "1" ]] && echo 1 || echo 0)" \ + "byte=${sb} (1=enabled)" + +echo "== NVMe root mount" +check "nvme_root_mounted" "$(findmnt "${ROOT_MNT}" >/dev/null 2>&1 && echo 1 || echo 0)" \ + "findmnt ${ROOT_MNT}" +root_dev="$(findmnt -no SOURCE "${ROOT_MNT}" 2>/dev/null || echo unknown)" +echo "nvme_root_device: ${root_dev}" +check "nvme_root_is_internal" \ + "$(echo "${root_dev}" | grep -qE 'nvme|mapper' && echo 1 || echo 0)" \ + "source ${root_dev}" + +echo "== /boot/efi access (read-only inspection; nothing is written here)" +esp_ok=0 +if findmnt "${ESP_MNT}" >/dev/null 2>&1 || mountpoint -q "${ESP_MNT}" 2>/dev/null; then + esp_ok=1 +fi +check "esp_mounted" "${esp_ok}" "findmnt ${ESP_MNT}" + +esp_fallback_present=0 +if [[ "${esp_ok}" == 1 && -f "${ESP_MNT}/EFI/BOOT/BOOTAA64.EFI" ]]; then + esp_fallback_present=1 +fi +check "esp_fallback_bootloader_present" "${esp_fallback_present}" \ + "${ESP_MNT}/EFI/BOOT/BOOTAA64.EFI" + +esp_writable=0 +if [[ "${esp_ok}" == 1 ]]; then + esp_opts="$(findmnt -no OPTIONS "${ESP_MNT}" 2>/dev/null || echo "")" + [[ "${esp_opts}" == *"rw"* ]] && esp_writable=1 +fi +check "esp_mounted_rw_capable" "${esp_writable}" \ + "mount options: $(findmnt -no OPTIONS "${ESP_MNT}" 2>/dev/null || echo unknown) (repair capability observed, not exercised)" + +echo "== boot entry restore capability" +efi_vars=0 +[[ -d /sys/firmware/efi/efivars ]] && efi_vars=1 +check "efi_variables_present" "${efi_vars}" "/sys/firmware/efi/efivars" +entries="$(efibootmgr 2>/dev/null || true)" +echo "${entries}" | sed -n '1,6p' +check "efibootmgr_readable" "$(grep -q '^Boot' <<<"${entries}" && echo 1 || echo 0)" \ + "efibootmgr lists boot entries" + +echo "== verdict" +if [[ "${FAILED}" == 0 ]]; then + echo "RECOVERY_BOOT_GATE: PASS" +else + echo "RECOVERY_BOOT_GATE: FAIL" + exit 1 +fi diff --git a/scripts/qemu_verify_recovery_media.sh b/scripts/qemu_verify_recovery_media.sh index 3ac54a07..d3189878 100755 --- a/scripts/qemu_verify_recovery_media.sh +++ b/scripts/qemu_verify_recovery_media.sh @@ -78,3 +78,61 @@ if [[ "${failed}" != 0 ]]; then fi echo "RECOVERY_ZERO_DISK: PASS (verified standalone RAM recovery with zero attached storage)" + +# Second boot: the packaged drivers must find a USB stick, an NVMe drive and a +# USB keyboard. The disks are blank scratch images, never host storage. +DEV_LOG="${WORK_DIR}/recovery_devices.log" +truncate -s 64M "${WORK_DIR}/usb.img" "${WORK_DIR}/nvme.img" +ACCEL=(-cpu max) +DEV_TIMEOUT=120 +if [[ -w /dev/kvm ]]; then + ACCEL=(-accel kvm -cpu host) + DEV_TIMEOUT=60 +fi + +echo "Booting recovery kernel with a scratch USB stick, NVMe drive and USB keyboard..." +set +e +timeout "${DEV_TIMEOUT}" qemu-system-aarch64 \ + -M virt "${ACCEL[@]}" -smp 2 -m 1024 \ + -kernel "${KERNEL_IMAGE}" \ + -initrd "${INITRD_TMP}" \ + -append "rdinit=/init aienos.test=1 console=ttyAMA0 panic=1" \ + -device qemu-xhci -device usb-kbd \ + -drive if=none,id=usbstick,format=raw,file="${WORK_DIR}/usb.img" -device usb-storage,drive=usbstick \ + -drive if=none,id=nvme0,format=raw,file="${WORK_DIR}/nvme.img" -device nvme,drive=nvme0,serial=aienos-test \ + -display none -nic none \ + -serial file:"${DEV_LOG}" -no-reboot +DEV_STATUS=$? +set -e + +tr -d '\r' <"${DEV_LOG}" >"${WORK_DIR}/recovery_devices.txt" +echo "qemu exit ${DEV_STATUS}" + +failed=0 +check_devices() { + if grep -qE -- "$2" "${WORK_DIR}/recovery_devices.txt"; then + echo "PASS $1" + else + echo "FAIL $1" + failed=1 + fi +} +modules_line=$(grep -m1 'Kernel modules loaded:' "${WORK_DIR}/recovery_devices.txt" || true) +if [[ "${modules_line}" =~ loaded:\ ([0-9]+)/([0-9]+) ]] && [[ "${BASH_REMATCH[1]}" == "${BASH_REMATCH[2]}" ]] && [[ "${BASH_REMATCH[2]}" -gt 0 ]]; then + echo "PASS All packaged kernel modules loaded (${BASH_REMATCH[1]}/${BASH_REMATCH[2]})" +else + echo "FAIL All packaged kernel modules loaded (${modules_line:-no report})" + failed=1 +fi +check_devices "USB keyboard detected" "Input devices: [1-9]" +check_devices "USB stick visible" "^sda" +check_devices "NVMe drive visible" "^nvme0n1" + +if [[ "${failed}" != 0 ]]; then + echo "---- recovery device console log ----" + cat "${WORK_DIR}/recovery_devices.txt" + echo "RECOVERY_DEVICES: FAIL" + exit 1 +fi + +echo "RECOVERY_DEVICES: PASS (packaged drivers found USB keyboard, USB stick and NVMe)" diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index 17e49376..7a48b90c 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -81,3 +81,13 @@ if command -v qemu-system-aarch64 >/dev/null; then else echo "SKIPPED: qemu-system-aarch64 not present on host." fi + +# Step 9: Recovery Media Tooling Manifest (issue #17; host-side, no real +# devices, no root -- extracts the built initrd and checks file presence). +echo "" +echo "--- [Recovery Media Tooling Manifest] ---" +if command -v gzip >/dev/null && command -v cpio >/dev/null; then + ./scripts/verify_recovery_tools.sh +else + echo "SKIPPED: gzip or cpio not present on host." +fi diff --git a/scripts/verify_recovery_tools.sh b/scripts/verify_recovery_tools.sh new file mode 100755 index 00000000..56d08651 --- /dev/null +++ b/scripts/verify_recovery_tools.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# verify_recovery_tools.sh: Verify that the standalone recovery initrd ships +# the tooling issue #17 requires: mount the NVMe root, repair /boot/efi, and +# restore boot entries. Host-side, static check only: extracts the built +# initrd and greps for files and init hooks. No real devices, no root, no +# QEMU boot (qemu_verify_recovery_media.sh already covers the boot itself). +# Zero Disk Secrets and Unslop compliant. + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${REPO_ROOT}" + +INITRD_IMG="${1:-/tmp/aienos-recovery-standalone-initrd.img}" + +if [[ ! -f "${INITRD_IMG}" ]]; then + echo "Building standalone recovery initrd..." + bash "${REPO_ROOT}/scripts/build_standalone_recovery_initrd.sh" "${INITRD_IMG}" +fi + +WORK_DIR=$(mktemp -d) +trap 'rm -rf "${WORK_DIR}"' EXIT + +echo "Extracting ${INITRD_IMG}..." +gzip -dc "${INITRD_IMG}" | (cd "${WORK_DIR}" && cpio -idm --quiet) + +FAILED=0 +check() { + if [[ "$2" == 1 ]]; then + echo "PASS $1" + else + echo "FAIL $1" + FAILED=1 + fi +} + +have_file() { [[ -f "${WORK_DIR}/$1" || -x "${WORK_DIR}/$1" || -L "${WORK_DIR}/$1" ]] && echo 1 || echo 0; } +init_has() { grep -q -- "$1" "${WORK_DIR}/init" 2>/dev/null && echo 1 || echo 0; } +module_packaged() { grep -qxF "$1.ko" "${WORK_DIR}/etc/aienos-modules.order" 2>/dev/null && echo 1 || echo 0; } + +echo "" +echo "-- required tools for NVMe root mount --" +check "busybox present" "$(have_file bin/busybox)" +check "mount present" "$(have_file bin/mount)" +check "lsblk present" "$(have_file bin/lsblk)" +check "blkid present" "$(have_file bin/blkid)" +check "cryptsetup present" "$(have_file bin/cryptsetup)" +check "nvme kernel module packaged" "$(module_packaged nvme)" +check "dm-crypt kernel module packaged" "$(module_packaged dm-crypt)" + +echo "" +echo "-- required tools for /boot/efi repair --" +check "fsck.vfat present" "$(have_file bin/fsck.vfat)" +check "mkfs.vfat present" "$(have_file bin/mkfs.vfat)" +check "fsck.ext4 present" "$(have_file bin/fsck.ext4)" +check "efibootmgr present" "$(have_file bin/efibootmgr)" + +echo "" +echo "-- required tools for boot-entry restore --" +check "efibootmgr present (boot entries)" "$(have_file bin/efibootmgr)" +check "chroot present" "$(have_file bin/chroot)" + +echo "" +echo "-- init hooks --" +check "init is executable" "$([[ -x "${WORK_DIR}/init" ]] && echo 1 || echo 0)" +check "init keeps zero-disk test mode (aienos.test=1)" "$(init_has 'aienos.test=1')" +check "init reports EFI boot entries (efibootmgr)" "$(init_has 'efibootmgr')" +check "init drops into an interactive maintenance shell" "$(init_has 'exec /bin/sh')" + +echo "" +if [[ "${FAILED}" != 0 ]]; then + echo "RECOVERY_TOOLS: FAIL" + exit 1 +fi +echo "RECOVERY_TOOLS: PASS (initrd ships mount, EFI repair, and boot-entry restore capability)" ```