aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#331 (code only)
Apply it
git checkout -b patch-71d5aa6fc39f0eec 3647654c43207386c08c57ff5341965091e9d90c curl -fsSL https://interplane.io/drakestapleton/aienux/patches/71d5aa6fc39f0eec.patch | git am
Provenance
github-import 1
aien-dev/aienux
331
f512b731753dd1e8d0507bbe09b6698acfb15bf6
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":331,"url":"https://github.com/aien-dev/aienux/pull/331","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:13Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 6e21ddcc..e67ef952 100644 --- a/.crumb +++ b/.crumb @@ -28,32 +28,32 @@ }, { "digest": "8297c9aa81a1feb24ac4beb4ecca58003f3bec5b7f475e40ad237da2868caf01", - "last_commit": "44dc7ee", + "last_commit": "3647654", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "6e15607b232b76b439aa7f8c01de4d7f856d010713cd3f4b651ee43e62b24efe", - "last_commit": "44dc7ee", + "digest": "c8bdee2362c57e35e83ede896d04990a8bf52975aa22d4fb0d57cc4855b7391e", + "last_commit": "50546b6", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "90ed142e7c24f44a6635cddb089b6e8b0ccdd3b6914f9992cab7635a82ab24a8", - "last_commit": "44dc7ee", + "digest": "e35f107caf8f963b07c4c8885278702812e3af2af5451b6b47793c58890d18a0", + "last_commit": "cf5b432", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:acc1913fb996e199512ca693d81248f8594ed62f2c41bb5eedf45f0ce03bc55f", - "compiled_at": "2026-10-12T19:04:55Z", + "children_root": "sha256:040ce2ca531f850fab8748870c4e4d7aa5274e2ceb91e9c029c91358401dbc05", + "compiled_at": "2026-10-12T20:24:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:86ddfd1168530ca1766052a44c4e77f594d80df792db0b4db1ccee8527784855", + "digest": "sha256:119ee1e24071dfb90ade0dad3d84aadac6a70ea401811096425b14c23f3bc443", "evidence_files": 156, "evidence_root": "sha256:cd53ab119be9de6ce28c4f5949b106c9622f1fe105611de3de21c3bce7932694", - "files": 3113, - "generated_at_commit": "44dc7ee624d1b72eb3930cd35f55629c2c12a008", - "source_tree": "sha256:94cb7135c411c7a6cac83fbe03dc60a9834c249e0125e444eea160c0013d9abf" + "files": 3115, + "generated_at_commit": "cf5b432a7ffe41864750ff433acf7aa89cf67f0f", + "source_tree": "sha256:b4ec1b4f4fbe1755f9848dc4c603a70b8d92e16290ed6e09bf97fb657c492603" }, "owner_lane": "", "provenance": { diff --git a/.github/workflows/ck-kernel.yml b/.github/workflows/ck-kernel.yml index 33bc2abf..927d87be 100644 --- a/.github/workflows/ck-kernel.yml +++ b/.github/workflows/ck-kernel.yml @@ -104,6 +104,9 @@ jobs: AIENOS_GATE_LOCK: ${{ runner.temp }}/qemu-gate-lock run: bash scripts/ck_owner_keys_check.sh + - name: Hardware inference service image make refusals and the supported line (build only, aienos#34 gate N3) + run: bash scripts/qemu_ck_service_disk_test.sh --build-only + - name: Check the host tests left the tree clean (the gate runner refuses a dirty tree) run: | git status --porcelain --untracked-files=normal diff --git a/native/.crumb b/native/.crumb index af232b98..82f82b67 100644 --- a/native/.crumb +++ b/native/.crumb @@ -56,7 +56,7 @@ }, { "digest": "0b5769362a82f2b2d66ef490df93fc79eff8829ed6ee933bdedae2adecb8b240", - "last_commit": "44dc7ee", + "last_commit": "3647654", "name": "boot", "purpose": "Directory native/boot. Purpose not yet described by a human." }, @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "23f775c1088273409ab37249362083b84c3fea65cc0178e9ac39dcd9abf3add2", - "last_commit": "44dc7ee", + "digest": "85bc49d4e8d7d16a24ba3b095076c1187da66f23de8416b68f7d42cd0776095a", + "last_commit": "50546b6", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, @@ -109,15 +109,15 @@ "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:80b59a95a0eff1e198e8589417029c194341bf67bdbb9e4a65b0c50a10aae49a", - "compiled_at": "2026-10-12T19:04:55Z", + "children_root": "sha256:574b81970e341fc76d5af24f7e2690bc431521c7a447a45e2af87ef81c372f78", + "compiled_at": "2026-10-12T20:24:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:6e15607b232b76b439aa7f8c01de4d7f856d010713cd3f4b651ee43e62b24efe", + "digest": "sha256:c8bdee2362c57e35e83ede896d04990a8bf52975aa22d4fb0d57cc4855b7391e", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", "files": 486, - "generated_at_commit": "44dc7ee624d1b72eb3930cd35f55629c2c12a008", - "source_tree": "sha256:d6a0e29a0dfe978e87db2f3e5041dff070f666d8f60dadd0d1431c11c8c14506" + "generated_at_commit": "cf5b432a7ffe41864750ff433acf7aa89cf67f0f", + "source_tree": "sha256:68b0e08270c02d99a700008302efdec6dd5c1504e78ce28e8f18b853ec72c98b" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 4215a9f6..e58e08fc 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -57,20 +57,20 @@ "purpose": "Directory native/kernel/artifact. Purpose not yet described by a human." }, { - "digest": "1b408f5480b06385d8b4a11af66e90314ec075a906e70faa0947c78564e8c012", - "last_commit": "44dc7ee", + "digest": "8f639eb89b1c234e186ed3ec0d6cf3bf22cc63af2264dd287aca9eb62c5c27ff", + "last_commit": "66bd299", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, { "digest": "04dc7faae4e24952ed8c1b46c83a346f0be5a84828ea9e53c76611eec228bf45", - "last_commit": "44dc7ee", + "last_commit": "3647654", "name": "dev", "purpose": "Directory native/kernel/dev. Purpose not yet described by a human." }, { "digest": "283a167327166bcfd270869cc04a1a03ea21366248471464db7ef1cf37058ada", - "last_commit": "44dc7ee", + "last_commit": "3647654", "name": "include", "purpose": "Directory native/kernel/include. Purpose not yet described by a human." }, @@ -82,7 +82,7 @@ }, { "digest": "1bac580f6739048716c499c005fba3b85be0092bbdef5ee37b3e32c72a878024", - "last_commit": "44dc7ee", + "last_commit": "3647654", "name": "svc", "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, @@ -93,21 +93,21 @@ "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, { - "digest": "45a1ebe4171bdacbfcf2b5a4e5ed93702953a91599cd216740a2f070a314d5a8", - "last_commit": "44dc7ee", + "digest": "55e46a8f9efc987be206a64cc6c1085ac3ff9092d2f3ce4e490ce404785b19a4", + "last_commit": "66bd299", "name": "tools", "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:d65d85e110fe43eb1f3a9ecf9d628c1b7d5646289972cf7e4fb8d3918ed7b27e", - "compiled_at": "2026-10-12T19:04:55Z", + "children_root": "sha256:776233e69bb669107a9239b75a3130af7554dbcfe070cc499d5e0aebe4724791", + "compiled_at": "2026-10-12T20:24:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:23f775c1088273409ab37249362083b84c3fea65cc0178e9ac39dcd9abf3add2", + "digest": "sha256:85bc49d4e8d7d16a24ba3b095076c1187da66f23de8416b68f7d42cd0776095a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 317, - "generated_at_commit": "44dc7ee624d1b72eb3930cd35f55629c2c12a008", - "source_tree": "sha256:522b71bab49eed64e19b91ede94444a357325aac1ba385c5f187fe0bb04ef780" + "generated_at_commit": "cf5b432a7ffe41864750ff433acf7aa89cf67f0f", + "source_tree": "sha256:8fc16b028f631ce40b2fd680b273c9005413f4490b28292f3b2fec518558fe45" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 41df025f..d43e963c 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -650,9 +650,9 @@ golden prompt stepped to its end (its ids must equal the one-shot reply and the the cache reset after a cancel), "Say hello." cancelled again after one step, close, every frame returned, `AIENOS_CK_INFER_SESSION: PASS|FAIL`. The lifecycle `prompt` verb (operator prompt -> bounded output -> approve -> Store, P06 cut 2) runs the same session resident in a `CK_SERVICE=1 CK_INFER_LIB=...` image (LIFECYCLE rows -174-176). Limits: `CK_INFER_LIB` cannot combine with `CK_HARDWARE_STAGING` or `CK_RUST_LIBS` and the QEMU model -source is TEST-ONLY fw_cfg, so the hardware service image has no inference yet (the MODEL.MAP boot-disk source -is the hardware path); the bump allocator never frees, so each prompt costs a few KiB until close +174-176). Limits: `CK_INFER_LIB` cannot combine with `CK_RUST_LIBS`, and with `CK_HARDWARE_STAGING` only in the +service image (`CK_SERVICE=1`), which compiles no fw_cfg reader and takes the model only from the boot disk +(MODEL.MAP; SERVICE_DISK rows 200-210); the QEMU probe and test-keys images keep the TEST-ONLY fw_cfg source; the bump allocator never frees, so each prompt costs a few KiB until close (`heap_used_kib` per line). | # | check | gate | status | @@ -891,3 +891,21 @@ Owner decision 2026-10-12 (Drake): slot loader approved, narrowly scoped to sign | 197 | P11 cut 2b, negative control: the TEST-key service image started directly (no SLOTLDR.EFI) over a disk with B staged: `slot: no boot record (not started by SLOTLDR.EFI): slot service idle, nothing written`, healthy (`lifecycle: ready state=ready store=open`) yet no `slot: promoted`, control untouched (`seq=1 ... candidate=1 tries=3`). Both slots invalid stays row 192 (no image started, nothing written). Host side (`make slot-test`, in `make test`): boot record mutations each refused with its reason, kernel-action scenarios (promote, wait, abandon, refuse on no control, corrupt control, unreadable manifest, manifest digest or generation differing from the record, damaged record; none on steady boots and on the non-active slot) and the shared control-commit routine | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | Run (2026-10-12, code commit bff20a1 on main ff5da2d, QEMU 8.2 aarch64 virt + AAVMF, TCG): `AIENOS_CK_SLOT_LOADER: PASS (8 rows, 11 boots, 76 checks; QEMU, not hardware)`, 126 s; each slot boot about 6 s, row 7 stopped at 60 s. SLOTLDR.EFI is 36864 bytes. The core `BOOTAA64.EFI` built from this tree is byte-identical to the one built from main ff5da2d (same `AIENOS_COMMIT`, sha256 643fdb5991cfe261). Also PASS in CI (aienos#326, ARM64 job of run 38274680333, `required gate SLOT_LOADER: PASS`). After the rebase onto main 22157e1 (aienos#324 and #325) neither the loader nor the gate script changed, so the gate was not rerun locally (the lock was held by another gate); CI reran it on the final tree. Hardware NOT_RUN. + +## SERVICE_DISK: hardware service image with resident inference, model from the boot disk (native v1 P06, gate N3, aienos#34; C-only) -> CK `SERVICE_DISK` (scripts/qemu_ck_service_disk_test.sh) + +The production service image built exactly as for the machine (`make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS=<file> CK_MACHINE_ID=<file> CK_INFER_LIB=<lib>`, `CK_FB_HOLD_S=120`; `core/infer.c` with `CK_INFER_DISK_ONLY`, no fw_cfg reader compiled in), staged by `scripts/stage_one_time_boot_ck_service.sh --target-image` onto ONE emulated NVMe disk holding the ESP (image + MODEL.MAP), the model bytes in three out-of-order extents (`ck_gpt_image ... esp-model-aienos`) and an all-zero AIENOS partition for the sealed Store. Owner files (fresh Ed25519 public key, private half discarded; random machine id and Store uuid) and both 32-byte recovery secrets are generated for the run and never stored: no CK_TEST_* flag, no test-keys image, no fw_cfg model in the main boots. Not in `ck_gates.sh` (needs the 807 MB model); CI runs `--build-only` (rows 200-201). Limits: QEMU only; the Spark NVMe, the Spark console input path and the owner key ceremony are separate items; int8 stays off. + +| # | Check | CK gate | Status | +|---|---|---|---| +| 200 | `make -n` refuses each hardware inference line that is not the service image, with its message: `CK_INFER_LIB` + staging without `CK_SERVICE` (full and core probe images: "needs CK_SERVICE=1"); + `CK_SERVICE_TEST_KEYS`; + `CK_TEST_FWCFG_ARTIFACTS`; + `CK_RUST_LIBS`; + `CK_QEMU_UNSAFE_DMA`; + `CK_CONSOLE_SESSION`; + `CK_TEST_STORE_CRASH` and + `CK_TEST_CONTINUITY` ("CK_SERVICE cannot be combined with a CK_TEST_* flag"); staging without owner files | SERVICE_DISK (build) | PASS (2026-10-12, 10 of 10 refused; also in CI `--build-only`; hardware NOT_RUN) | +| 201 | the supported line is accepted and compiles with `-DCK_INFER_DISK_ONLY=1 -DCK_INFER_RESIDENT=1`; the QEMU test-keys inference image is unchanged (no `CK_INFER_DISK_ONLY`, keeps the TEST-ONLY fw_cfg source) | SERVICE_DISK (build) | PASS (2026-10-12, 2 of 2) | +| 202 | the staging script builds the image twice in clean folders with equal digests; the staged `BOOTAA64.EFI` carries `infer: resident open` and `infer_source_mode: boot-disk model` and none of `fw_cfg`, `opt/aienos/model`, `QEMU0002`, `TEST-ONLY`, `TEST Store`, `TEST machine id`; the ELF has no `fw_select/fw_read/fw_find/fw_dma_read/fwcfg_from_dsdt` or TEST key symbol (Makefile `fwcfg_check` and `owner_check` also refuse such an image at link time) | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; image sha256 6c594324ba3ac3bf (716800 bytes) for that run's generated owner files; hardware NOT_RUN) | +| 203 | `--dry-run --target-image`: "nothing touched", 4 `write ESP:/EFI/... bytes=N sha256=H` lines, the scratch image byte-identical (`cmp`); `--apply` writes and reads back the 4 files, changes the image (the `cmp` is not vacuous) and writes exactly the digests the dry run announced (image and MODEL.MAP) | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; 7 of 7; hardware NOT_RUN) | +| 204 | boot 1 (blank Store): `model_map: ok len=807694368 extents=3 sector=512`, `infer_source_mode: boot-disk model`, `infer: disk ... extents=3`, the pinned sha256 recomputed by the kernel, no fw_cfg line, `infer: resident open rc=0 tensors=147 ...` before `lifecycle: ready state=locked store=locked`; Store stage refuses the production key source; `unlock <secret>` formats the production Store (`formatted production store`, recovery keyslot genesis, `unlock ok ... genesis=1 generation=2 boot_count=1`), continuity `genesis source=operator provenance=owner-root-pk+store-uuid`, `PROVISIONED` | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; 16 of 16; hardware NOT_RUN) | +| 205 | boot 1: `prompt What is the capital of France?` -> `reply ids=791 6864 315 9822 374 12366 13 128009 tokens=8` (golden), pending proposal, `approve committed gen=4`, `remembered id=1 t=1 store_gen=6`, `facts records=1 ... chain=ok`, evidence `approved=1 prompts=1 replies=1 inference=resident remembers=1`, resident close, every frame returned on unload (823683 = 823683), stop order closes the Store, no console-input refusal, QEMU exit 0, M1 checks | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; 14 of 14; boot 977 s TCG; hardware NOT_RUN) | +| 206 | boot 2 = cold restart of QEMU on the SAME disk image file (same NVRAM): model from the disk again, resident open; a wrong secret refused by the keyslot tag (still LOCKED, not reformatted); the right one opens `generation=6`, `unlock ok ... genesis=0 generation=7 boot_count=2`; continuity RESUMES the same agent (incarnation 2), no second genesis; `recall` returns the approved reply at gen 4 and `facts` the fact at store_gen 6 from the disk, neither retyped; evidence `refused=1 recalls=1 facts=1 prompts=0`; every frame returned; stop order; QEMU exit 0; M1 checks | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; 21 of 21; boot 144 s TCG; hardware NOT_RUN) | +| 207 | secret hygiene in all 4 boots: neither secret's hex in any serial log; no `TEST-ONLY`, `TEST machine id` or `formatted TEST store` line | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; 12 of 12; hardware NOT_RUN) | +| 208 | negative control A: the same image with MODEL.MAP deleted and the model OFFERED on QEMU fw_cfg (`-fw_cfg name=opt/aienos/model`): `model_map: absent`, `infer: ingest REFUSED (no boot-disk model ...; this image has no other model source)`, no fw_cfg ingest and no resident session; `unlock` still works; `prompt` refused "no inference unit in this image"; evidence `inference=none`; QEMU exit 0 | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; 8 of 8; hardware NOT_RUN) | +| 209 | negative control B: MODEL.MAP whose declared sha256 is corrupted (`ck_model_map --corrupt-sha`): the stub reads the bytes, the kernel refuses to decode (`infer: sha256 mismatch declared=...`), no resident session, `prompt` refused; QEMU exit 0 | SERVICE_DISK | QEMU PASS (2026-10-12, code commit 0022b01 on main 3c07242: AIENOS_CK_SERVICE_DISK PASS, 100 checks, 0 FAIL; 6 of 6; hardware NOT_RUN) | +| 210 | limits (declared, not a check): QEMU TCG only; the physical Spark boot, its NVMe AIENOS partition, the Spark console receive path and the owner key ceremony are separate gated items; int8 decode stays off by default | SERVICE_DISK | hardware NOT_RUN | diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 510e69c5..3ee8b9c4 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -17,6 +17,12 @@ # both files; tools/ck_owner_gen.c checks them); its # Store stage refuses (production key source is # BLOCKED_OPERATOR). scripts/ck_owner_keys_check.sh +# make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS=<file> CK_MACHINE_ID=<file> CK_INFER_LIB=<lib> +# the production service image with resident inference, +# model from the boot disk only (MODEL.MAP, no fw_cfg code): +# $(OUT)/full-service-hardware-staging/. Staged by +# scripts/stage_one_time_boot_ck_service.sh; proof +# scripts/qemu_ck_service_disk_test.sh (aienos#34, gate N3) # make full CK_TEST_XHCI_MUTATION=bm-left-on|no-revoke|grant-no-smmu|no-sweep # TEST-ONLY image that breaks one xHCI DMA fence row on # purpose: $(OUT)/full-test-xhci-<name>/ (only @@ -287,15 +293,29 @@ endif # Inference ingest probe (aienos#34 lane 4): CK_INFER_LIB=<path to # libaienos_infer_kernel.a> links that Rust no_std staticlib (aienos-infer + # bump allocator) and compiles core/infer.c (-DCK_INFER_PROBE=1): the kernel -# ingests a GGUF from QEMU fw_cfg and calls the Rust unit. C flags stay -# -mgeneral-regs-only. QEMU gate only; not combinable with CK_RUST_LIBS (two -# Rust staticlibs would duplicate compiler_builtins) nor hardware staging. +# ingests a GGUF from the boot disk (MODEL.MAP, read by the UEFI stub) or, in +# the QEMU images only, from fw_cfg, and calls the Rust unit. C flags stay +# -mgeneral-regs-only. Not combinable with CK_RUST_LIBS (two Rust staticlibs +# would duplicate compiler_builtins). # The same image then runs the bounded session API (native v1 P06: # open/prompt/step/cancel/close in crates/aienos-infer-kernel/src/session.rs). +# +# Hardware staging (native v1 P06 / gate N3, aienos#34): exactly one inference +# image may be built with CK_HARDWARE_STAGING, the resident production service +# image +# make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS=<file> +# CK_MACHINE_ID=<file> CK_INFER_LIB=<lib> +# It gets -DCK_INFER_DISK_ONLY=1: the QEMU fw_cfg ingest is compiled out (the +# fwcfg_check below requires no fw_cfg code or string in the image), and with +# no MODEL.MAP the kernel refuses instead of looking anywhere else. The +# one-shot probe image (no CK_SERVICE) stays QEMU only. CK_INFER_LIB ?= ifneq ($(strip $(CK_INFER_LIB)),) ifneq ($(strip $(CK_HARDWARE_STAGING)),) -$(error CK_INFER_LIB (inference probe, QEMU gate only) cannot be combined with CK_HARDWARE_STAGING) +ifneq ($(strip $(CK_SERVICE)),1) +$(error CK_INFER_LIB with CK_HARDWARE_STAGING needs CK_SERVICE=1: only the resident service image (boot-disk model, MODEL.MAP) is a hardware inference image; the one-shot probe stays QEMU only) +endif +CK_EXTRA_CFLAGS += -DCK_INFER_DISK_ONLY=1 endif ifneq ($(strip $(CK_RUST_LIBS)),) $(error CK_INFER_LIB and CK_RUST_LIBS cannot be combined: two Rust staticlibs duplicate compiler_builtins) @@ -303,7 +323,8 @@ endif CK_EXTRA_CFLAGS += -DCK_INFER_PROBE=1 # native v1 P06 cut 2: in a service image the model and one bounded session # stay resident for the lifecycle's `prompt` verb (core/lifecycle.c) instead -# of running the one-shot probe. QEMU gate only (fw_cfg TEST-ONLY source). +# of running the one-shot probe. Model source: the boot disk (MODEL.MAP); the +# QEMU test images also keep the TEST-ONLY fw_cfg fallback. ifeq ($(strip $(CK_SERVICE)),1) CK_EXTRA_CFLAGS += -DCK_INFER_RESIDENT=1 endif @@ -787,17 +808,25 @@ $(foreach s,$(STAGE_SRCS),$(eval $(call stage_rule,$(s)))) # fwcfg_check(elf): a default image (no CK_TEST_FWCFG_ARTIFACTS) must carry no # fw_cfg artifact code or strings; a test image must carry its announcement. -# The inference probe image (CK_INFER_LIB, aienos#34 lane 4) reads its model over -# fw_cfg by design: it must carry its own TEST-ONLY announcement instead. +# The QEMU inference images (CK_INFER_LIB without hardware staging, aienos#34 +# lane 4) read their model over fw_cfg when no MODEL.MAP is found: they must +# carry their own TEST-ONLY announcement instead. The hardware service image +# with inference (CK_INFER_LIB + CK_HARDWARE_STAGING, boot-disk only) must +# carry the boot-disk source line, the resident session, and no fw_cfg code. define fwcfg_check - @if [ -n "$(strip $(CK_INFER_LIB))" ]; then \ + @if [ -n "$(strip $(CK_INFER_LIB))" ] && [ -z "$(strip $(CK_HARDWARE_STAGING))" ]; then \ grep -aqF "TEST-ONLY QEMU fw_cfg model ingest" $(1) || { echo "inference probe image lacks its TEST-ONLY fw_cfg announcement"; rm -f $(1); exit 1; }; \ elif [ "$(strip $(CK_TEST_FWCFG_ARTIFACTS))" = 1 ]; then \ grep -aqF "TEST-ONLY QEMU fw_cfg side channel" $(1) || { echo "test fw_cfg image lacks its TEST-ONLY announcement"; rm -f $(1); exit 1; }; \ else \ - s=$$(grep -aoE "opt/aienos/artifacts|fw_cfg|QEMU0002" $(1) | sort -u | tr "\n" " "); \ - y=$$($(KNM) $(1) | grep -E " (fw_select|fw_read|fw_skip|fw_find|fwcfg_from_dsdt|fwcfg_source|fwcfg)$$" | tr "\n" " "); \ + s=$$(grep -aoE "opt/aienos/artifacts|opt/aienos/model|fw_cfg|QEMU0002" $(1) | sort -u | tr "\n" " "); \ + y=$$($(KNM) $(1) | grep -E " (fw_select|fw_read|fw_skip|fw_find|fw_dma_read|fwcfg_from_dsdt|fwcfg_source|fwcfg)$$" | tr "\n" " "); \ if [ -n "$$s$$y" ]; then echo "default image carries fw_cfg artifact code: $$s$$y"; rm -f $(1); exit 1; fi; \ + if [ -n "$(strip $(CK_INFER_LIB))" ]; then \ + grep -aqF "infer_source_mode: boot-disk model" $(1) || { echo "hardware inference image lacks the boot-disk model source"; rm -f $(1); exit 1; }; \ + grep -aqF "infer: resident open" $(1) || { echo "hardware inference image lacks the resident session"; rm -f $(1); exit 1; }; \ + echo "hardware inference image: boot-disk model source only, no fw_cfg code in $(1)"; \ + fi; \ echo "no fw_cfg artifact code in $(1)"; \ fi endef diff --git a/native/kernel/README.md b/native/kernel/README.md index 94320caa..802d357c 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -99,6 +99,37 @@ of them: Cortex record yet (P06); no Recovery Core, no TPM; aienos#285 not triggered; physical disk qualification NOT_RUN (host test `test_continuity_service`; QEMU rows 171-173). +- **Resident inference in the hardware service image (aienos#34, gate N3).** + The one supported hardware inference build is the service image with the + model from the verified boot disk: + + cargo build --release --target aarch64-unknown-none --manifest-path crates/aienos-infer-kernel/Cargo.toml + make -C native/kernel full CK_SERVICE=1 CK_HARDWARE_STAGING=1 \ + CK_OWNER_PUBKEYS=<owner public keys file> CK_MACHINE_ID=<machine id file> \ + CK_INFER_LIB=<path to libaienos_infer_kernel.a> CK_FB_HOLD_S=120 + # -> target/native-kernel/full-service-hardware-staging/BOOTAA64.EFI + + It compiles `core/infer.c` with `CK_INFER_DISK_ONLY`: the fw_cfg model + reader is not compiled in (Makefile `fwcfg_check` greps the image for + `fw_cfg`, `opt/aienos/model` and the `fw_dma_read` symbol), the model comes + only from `MODEL.MAP` read by the UEFI stub (`native/boot/efi_model.c`), + the kernel recomputes the pinned SHA-256 before decoding, and with no map + it prints `infer: ingest REFUSED (no boot-disk model ...)` and the + lifecycle refuses `prompt` ("no inference unit"). The Makefile still + refuses with hardware staging: `CK_INFER_LIB` without `CK_SERVICE` (the + one-shot probe image), `CK_SERVICE_TEST_KEYS`, `CK_TEST_FWCFG_ARTIFACTS`, + every other `CK_TEST_*` flag, `CK_RUST_LIBS`, `CK_QEMU_UNSAFE_DMA`, + `CK_CONSOLE_SESSION` and missing owner files. The QEMU inference images + (probe, test-keys service) keep their TEST-ONLY fw_cfg source unchanged. + Staging: `scripts/stage_one_time_boot_ck_service.sh --dry-run|--apply` + builds the image twice in clean folders, makes `MODEL.MAP` against the + pinned model, prints every write with its SHA-256 and (dry run) writes + nothing; `--target-image IMG --extents ...` stages a disk image instead of + the machine. Proof: `scripts/qemu_ck_service_disk_test.sh` (GATES.md + SERVICE_DISK rows 200-210: refusals, dry run byte-identical, two cold boots + on one emulated disk with generated owner files and secrets, two negative + controls); `--build-only` runs the `make` refusals alone. Limits: QEMU + only; Spark NVMe, Spark console input and the owner key ceremony NOT_RUN. - Proof: `scripts/ck_owner_keys_check.sh` (build only, takes the quiet flag) checks the refusals, the generator refusals, and builds the hardware staging image from the labelled TEST-fixture files in `tests/fixtures/owner/` diff --git a/native/kernel/core/.crumb b/native/kernel/core/.crumb index 9d81fa20..12561dce 100644 --- a/native/kernel/core/.crumb +++ b/native/kernel/core/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T19:04:55Z", + "compiled_at": "2026-10-12T20:24:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:1b408f5480b06385d8b4a11af66e90314ec075a906e70faa0947c78564e8c012", + "digest": "sha256:8f639eb89b1c234e186ed3ec0d6cf3bf22cc63af2264dd287aca9eb62c5c27ff", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 45, - "generated_at_commit": "44dc7ee624d1b72eb3930cd35f55629c2c12a008", - "source_tree": "sha256:8d5d029934305b49495e5b78fedd6eb8a4ef7883f549fda0ccf1171cec774386" + "generated_at_commit": "cf5b432a7ffe41864750ff433acf7aa89cf67f0f", + "source_tree": "sha256:f5d9c30ab3c57068be624be5333ac50772f0093a0f9c9b598d5a80c197460520" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/core/infer.c b/native/kernel/core/infer.c index 2f8aba77..32f37f84 100644 --- a/native/kernel/core/infer.c +++ b/native/kernel/core/infer.c @@ -37,6 +37,9 @@ #ifdef CK_INFER_PROBE #include "sha256.h" +#if defined(CK_INFER_DISK_ONLY) && !defined(CK_INFER_RESIDENT) +#error "CK_INFER_DISK_ONLY is the hardware service image (CK_SERVICE=1 + CK_INFER_LIB + CK_HARDWARE_STAGING) only" +#endif extern void aienos_infer_heap_init(uintptr_t base, uintptr_t len); /* Mirror of crates/aienos-infer-kernel/src/lib.rs `InferResult` (#[repr(C)]). */ @@ -82,8 +85,10 @@ extern void aienos_infer_heap_stats(uint64_t *used, uint64_t *peak); #define CPACR_FPEN_SHIFT 20 #define PAGE 4096ull #define HEAP_BYTES (256ull << 20) /* bump-allocator region for the Rust unit */ +#ifndef CK_INFER_DISK_ONLY #define DMA_CHUNK (64ull << 20) /* fw_cfg DMA length is 32 bit; read in chunks */ #define MODEL_FILE "opt/aienos/model" +#endif /* The prompt's expected first four ids (crates/aienos-infer/tests/fixtures/ref_fr.txt). */ static const uint32_t expect_ids[4] = {128000, 128006, 882, 128007}; @@ -109,6 +114,10 @@ static void escape(char *out, const uint8_t *b, uint32_t n) *out = 0; } +#ifndef CK_INFER_DISK_ONLY +/* QEMU fw_cfg ingest (TEST-ONLY). Compiled out of the hardware service image + * (CK_INFER_DISK_ONLY, Makefile: CK_INFER_LIB + CK_HARDWARE_STAGING), whose + * only model source is the boot disk (MODEL.MAP). */ static volatile uint8_t *fwcfg; static uint32_t be32(const uint8_t *b) @@ -218,6 +227,7 @@ static int fw_dma_read(int sel, uint64_t pa, uint32_t len) } return -2; } +#endif /* !CK_INFER_DISK_ONLY */ /* The Rust unit's panic handler lands here: report and stop, never return. */ __attribute__((noreturn)) void aienos_infer_panic(void) { ck_panic("infer: Rust unit panicked or ran out of heap"); } @@ -469,15 +479,24 @@ void ck_infer_resident_close(void) void ck_infer_run(void) { - const char *why = 0; /* Source 1, the boot disk: the UEFI stub read the model through the * firmware's Block I/O driver before ExitBootServices and recorded it in * CHANDOF2 (native/boot/efi_model.c, native/boot/model_map.h). The bytes * live in EfiLoaderData the frame allocator never hands out (mm/mmu.c * reserves the range). This is the path that exists on hardware. - * Source 2, QEMU fw_cfg: TEST-ONLY, below, when the stub found no map. */ + * Source 2, QEMU fw_cfg: TEST-ONLY, below, when the stub found no map; + * compiled out of the hardware service image (CK_INFER_DISK_ONLY). */ const struct ck_handoff *h = ck_handoff_get(); int from_disk = h && (h->model_flags & CK_HANDOFF_MODEL_PRESENT); +#ifdef CK_INFER_DISK_ONLY + uint32_t size = 0; + if (!from_disk) { + ck_puts("infer: ingest REFUSED (no boot-disk model: MODEL.MAP absent or refused by the stub; " + "this image has no other model source)\n"); + return; + } +#else + const char *why = 0; uint64_t base = from_disk ? 0 : fwcfg_from_dsdt(&why); uint16_t sel = 0; uint32_t size = 0; @@ -511,6 +530,7 @@ void ck_infer_run(void) MODEL_FILE, size); } +#endif /* CK_INFER_DISK_ONLY */ uint64_t msize = from_disk ? h->model_len : (uint64_t)size; uint64_t mpa = from_disk ? h->model_base : 0, hpa = 0, mpages = 0; if (from_disk) { @@ -542,6 +562,7 @@ void ck_infer_run(void) return; } +#ifndef CK_INFER_DISK_ONLY if (!from_disk) { uint64_t t0 = ck_time_us(); int rc = 0; @@ -556,6 +577,7 @@ void ck_infer_run(void) ck_printf("infer: ingest bytes=%llu dma_us=%llu\n", (unsigned long long)msize, (unsigned long long)(ck_time_us() - t0)); } +#endif uint64_t t1 = ck_time_us(); sha256_ctx ctx; diff --git a/native/kernel/tools/.crumb b/native/kernel/tools/.crumb index c47abe59..080f2056 100644 --- a/native/kernel/tools/.crumb +++ b/native/kernel/tools/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T19:04:55Z", + "compiled_at": "2026-10-12T20:24:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:45a1ebe4171bdacbfcf2b5a4e5ed93702953a91599cd216740a2f070a314d5a8", + "digest": "sha256:55e46a8f9efc987be206a64cc6c1085ac3ff9092d2f3ce4e490ce404785b19a4", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 18, - "generated_at_commit": "44dc7ee624d1b72eb3930cd35f55629c2c12a008", - "source_tree": "sha256:1f863d5dcc33d9b1bf0781d0c6b3a6ecae3c889291a6934945670723834fb91f" + "generated_at_commit": "cf5b432a7ffe41864750ff433acf7aa89cf67f0f", + "source_tree": "sha256:caeecf0f379baac93db02234e7f87577b3cd5ca7a4132fef9747e1ea90604f1f" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tools/ck_gpt_image.c b/native/kernel/tools/ck_gpt_image.c index ce329de4..4c0d3de5 100644 --- a/native/kernel/tools/ck_gpt_image.c +++ b/native/kernel/tools/ck_gpt_image.c @@ -20,6 +20,9 @@ * slots_last_lba=L" (slot loader gate) * aienos-slots AIENOS [1,41) all zero + slots [41,M-1) (MIB >= 48; * P11 cut 2b service boot disk); prints both ranges + * esp-model-aienos ESP_MIB MODEL_FILE STORE_MIB esp-model plus an + * all-zero AIENOS partition of STORE_MIB at the end: + * one disk with ESP, model and Store (service gate) * CORRUPTION: bad-primary-crc bad-backup-crc bad-primary-entries * bad-backup-entries no-pmbr * Prints one line: "gpt_image bs=B blocks=N aienos_first_lba=F @@ -57,11 +60,16 @@ static int usage(void) * model_len=M model_extents=LBA:COUNT,LBA:COUNT,LBA:COUNT" (file order). */ static int esp_model(int argc, char **argv, uint32_t bs, uint64_t blocks, uint64_t per, unsigned flags) { - if (argc != 8) return usage(); + /* esp-model-aienos (argc 9): the model-home partition ends STORE_MIB + * earlier and an all-zero AIENOS partition takes [M-1-STORE_MIB, M-1). */ + int with_store = argc == 9; + if (argc != 8 && !with_store) return usage(); uint64_t esp_mib = strtoull(argv[6], NULL, 10); const char *mpath = argv[7]; uint64_t mib = blocks / per; - if (esp_mib < 16 || esp_mib + 4 >= mib) return usage(); + uint64_t store_mib = with_store ? strtoull(argv[8], NULL, 10) : 0; + if (with_store && store_mib < 16) return usage(); + if (esp_mib < 16 || esp_mib + 4 + store_mib >= mib) return usage(); FILE *mf = fopen(mpath, "rb"); if (!mf) { fprintf(stderr, "cannot open %s\n", mpath); return 1; } fseeko(mf, 0, SEEK_END); @@ -69,7 +77,7 @@ static int esp_model(int argc, char **argv, uint32_t bs, uint64_t blocks, uint64 fseeko(mf, 0, SEEK_SET); uint64_t sectors = (mlen + bs - 1) / bs, gap = (1u << 20) / bs; uint64_t a = sectors / 3, b = sectors / 3, c = sectors - a - b; - uint64_t p1_first = (1 + esp_mib) * per, p1_last = (mib - 1u) * per - 1u; + uint64_t p1_first = (1 + esp_mib) * per, p1_last = (mib - 1u - store_mib) * per - 1u; if (p1_first + 3 * gap + sectors > p1_last + 1) { fprintf(stderr, "image too small for the model: need %llu more MiB\n", (unsigned long long)((p1_first + 3 * gap + sectors - p1_last) / per + 1)); @@ -78,10 +86,11 @@ static int esp_model(int argc, char **argv, uint32_t bs, uint64_t blocks, uint64 } /* disk order: C, A, B */ uint64_t lba_c = p1_first + gap, lba_a = lba_c + c + gap, lba_b = lba_a + a + gap; - gw_part p[2]; + gw_part p[3]; p[0] = (gw_part){gw_esp_type, 1 * per, (1 + esp_mib) * per - 1u, "ESP", 0}; p[1] = (gw_part){gw_linux_type, p1_first, p1_last, "model-home", 0}; - if (gw_write(argv[2], bs, blocks, p, 2, flags)) { fclose(mf); return 1; } + p[2] = (gw_part){ck_aienos_part_type, p1_last + 1u, (mib - 1u) * per - 1u, "AIENOS", 0}; + if (gw_write(argv[2], bs, blocks, p, with_store ? 3 : 2, flags)) { fclose(mf); return 1; } int fd = open(argv[2], O_WRONLY); if (fd < 0) { fclose(mf); fprintf(stderr, "cannot reopen %s\n", argv[2]); return 1; } struct { uint64_t lba, count; } ext[3] = {{lba_a, a}, {lba_b, b}, {lba_c, c}}; @@ -107,6 +116,9 @@ static int esp_model(int argc, char **argv, uint32_t bs, uint64_t blocks, uint64 bs, (unsigned long long)blocks, (unsigned long long)p[0].first, (unsigned long long)p[0].last, (unsigned long long)mlen, (unsigned long long)lba_a, (unsigned long long)a, (unsigned long long)lba_b, (unsigned long long)b, (unsigned long long)lba_c, (unsigned long long)c); + if (with_store) + printf("gpt_image aienos_first_lba=%llu aienos_last_lba=%llu\n", (unsigned long long)p[2].first, + (unsigned long long)p[2].last); return 0; } @@ -119,7 +131,8 @@ static int cmd_create(int argc, char **argv) uint64_t per = (1024u * 1024u) / bs, blocks = mib * per; const char *lay = argv[5]; unsigned flags = 0; - if (!strcmp(lay, "esp-model")) return esp_model(argc, argv, bs, blocks, per, flags); + if (!strcmp(lay, "esp-model") && argc == 8) return esp_model(argc, argv, bs, blocks, per, flags); + if (!strcmp(lay, "esp-model-aienos") && argc == 9) return esp_model(argc, argv, bs, blocks, per, flags); if (!strcmp(lay, "slots")) { static const uint8_t slots_type[16] = CK_SLOT_PART_TYPE_BYTES; gw_part sp = {slots_type, 1 * per, (mib - 1u) * per - 1u, "AIENOS-SLOTS", 0}; diff --git a/scripts/.crumb b/scripts/.crumb index 1d5a41dc..dabea57b 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T19:04:55Z", + "compiled_at": "2026-10-12T20:24:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:90ed142e7c24f44a6635cddb089b6e8b0ccdd3b6914f9992cab7635a82ab24a8", + "digest": "sha256:e35f107caf8f963b07c4c8885278702812e3af2af5451b6b47793c58890d18a0", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 87, - "generated_at_commit": "44dc7ee624d1b72eb3930cd35f55629c2c12a008", - "source_tree": "sha256:e846f35d34899aa68198d89cd93d8a1194c137c3617635d554b08b81ab5e72c2" + "files": 89, + "generated_at_commit": "cf5b432a7ffe41864750ff433acf7aa89cf67f0f", + "source_tree": "sha256:9c05c1257ecb21e4bc140cc337509ad262a199035d8b15f42f53b119f541d454" }, "owner_lane": "", "provenance": { diff --git a/scripts/native_package_test.sh b/scripts/native_package_test.sh index 314c932e..f75fc8af 100755 --- a/scripts/native_package_test.sh +++ b/scripts/native_package_test.sh @@ -126,11 +126,12 @@ tamper() { # name, sed expression, needle, extra verify args... cp -r "$T/p1" "$d"; sed -i "$e" "$d/PACKAGE.txt"; remake_all "$d" expect_refused "record check: $name" "$needle" "$np" verify --package "$d" --test-key "$@" } +# digest tampers flip the first hex digit to a different one (f becomes 0), so they never leave the record unchanged tamper tree-clean-no 's/^tree_clean .*/tree_clean no/' "dirty tree (tree_clean no)" -tamper makefile-digest 's/^input_makefile_sha256 ./input_makefile_sha256 f/' "input_makefile_sha256 does not match" "${dirty[@]}" -tamper image-ld-digest 's/^input_image_ld_sha256 ./input_image_ld_sha256 f/' "input_image_ld_sha256 does not match" "${dirty[@]}" +tamper makefile-digest 's/^input_makefile_sha256 f/input_makefile_sha256 0/;t;s/^input_makefile_sha256 ./input_makefile_sha256 f/' "input_makefile_sha256 does not match" "${dirty[@]}" +tamper image-ld-digest 's/^input_image_ld_sha256 f/input_image_ld_sha256 0/;t;s/^input_image_ld_sha256 ./input_image_ld_sha256 f/' "input_image_ld_sha256 does not match" "${dirty[@]}" tamper commit-time 's/^commit_time .*/commit_time 1/' "commit_time does not match" "${dirty[@]}" -tamper image-sha512 's/^image_sha512 ./image_sha512 f/' "image_sha512 does not match" "${dirty[@]}" +tamper image-sha512 's/^image_sha512 f/image_sha512 0/;t;s/^image_sha512 ./image_sha512 f/' "image_sha512 does not match" "${dirty[@]}" tamper image-bytes 's/^image_bytes .*/image_bytes 1/' "image_bytes does not match" "${dirty[@]}" tamper make-vars 's/^input_make_vars .*/input_make_vars CK_SERVICE=1/' "input_make_vars does not match" "${dirty[@]}" tamper make-goal 's/^input_make_goal .*/input_make_goal all/' "input_make_goal does not match" "${dirty[@]}" diff --git a/scripts/qemu_ck_service_disk_test.sh b/scripts/qemu_ck_service_disk_test.sh new file mode 100644 index 00000000..0269dc43 --- /dev/null +++ b/scripts/qemu_ck_service_disk_test.sh @@ -0,0 +1,421 @@ +#!/usr/bin/env bash +# SERVICE_DISK gate for the AIENOS C kernel (native v1 P06 / gate N3, +# aienos#34): rows 200-211 of native/kernel/GATES.md "SERVICE_DISK". C-only. +# QEMU is not hardware: a PASS here qualifies nothing physical. +# +# The production service image with resident CPU inference, exactly as built +# for the machine (make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 +# CK_OWNER_PUBKEYS= CK_MACHINE_ID= CK_INFER_LIB=, CK_FB_HOLD_S=120), staged by +# scripts/stage_one_time_boot_ck_service.sh onto ONE emulated NVMe disk that +# holds the ESP (image + MODEL.MAP), the model bytes (three out-of-order +# extents) and the all-zero AIENOS partition for the sealed Store. No fw_cfg +# model, no CK_TEST_* flag, no test-keys image: the owner files (a fresh +# Ed25519 public key, a random machine id and Store uuid) and the 32-byte +# recovery secrets are generated for this run and never stored. +# +# bash scripts/qemu_ck_service_disk_test.sh the whole gate (~30-45 min TCG) +# bash scripts/qemu_ck_service_disk_test.sh --build-only rows 200-201 only (make refusals +# and the accepted line, no QEMU, +# no Rust target needed) +# +# row 200 build refusals: each `make` line must FAIL with its message: +# CK_INFER_LIB + CK_HARDWARE_STAGING without CK_SERVICE (the one-shot +# probe); + CK_SERVICE_TEST_KEYS; + CK_TEST_FWCFG_ARTIFACTS; + CK_RUST_LIBS; +# + CK_QEMU_UNSAFE_DMA; + CK_CONSOLE_SESSION; + CK_TEST_STORE_CRASH; +# + CK_TEST_CONTINUITY; staging without owner files +# row 201 the supported line is accepted by make (parse, make -n) +# row 202 the built image (twice, equal digests, by the staging script) carries +# the resident session and the boot-disk source and no fw_cfg code, +# fw_cfg symbol, TEST Store marker or TEST-ONLY banner; the QEMU +# inference images keep their TEST-ONLY fw_cfg announcement +# row 203 staging --dry-run against the scratch image: every write printed with +# its sha256, "nothing touched", the image byte-identical (cmp); +# --apply then changes it (cmp differs: the check is not vacuous) and +# writes exactly the digests the dry run announced +# row 204 boot 1 (blank Store): the stub reads MODEL.MAP from the ESP and the +# model by firmware Block I/O, the kernel recomputes the pinned +# sha256, `infer: resident open`, no fw_cfg line; the Store stage +# refuses the production key source (LOCKED, owner provisioned at +# build time); `unlock <secret>` formats the production Store with +# the recovery keyslot (genesis) and continuity provisions with +# source=operator and the owner root key +# row 205 boot 1: `prompt What is the capital of France?` -> golden reply ids +# -> `approve` commits it; `remember prefer short notes` -> record 1; +# `facts` lists it; evidence counters; stop order closes the session +# (every frame returned) and the Store; QEMU exit 0; M1 checks +# row 206 boot 2 = cold restart of QEMU on the SAME disk image file: a wrong +# secret is refused, the right one opens the Store (no reformat), +# continuity RESUMES the same agent, `recall` returns the approved +# reply and `facts` the fact from the disk (neither retyped), QEMU +# exit 0, M1 checks +# row 207 secret hygiene: neither secret's hex in any serial log; no TEST +# banner or TEST machine id line in any boot +# row 208 negative control A: the same image with MODEL.MAP deleted and the +# model OFFERED on fw_cfg: `model_map: absent`, `infer: ingest REFUSED +# (no boot-disk model`, no fw_cfg ingest; after unlock `prompt` is +# refused ("no inference unit"), evidence inference=none +# row 209 negative control B: MODEL.MAP with a corrupted declared sha256: the +# stub reads the bytes, the kernel refuses to decode (`sha256 +# mismatch`), no resident session, prompt refused +# row 210 limits (declared): QEMU only; the Spark console receive path, the +# AIENOS partition on the Spark NVMe and the owner key ceremony are +# separate items; int8 stays off +# Final line: AIENOS_CK_SERVICE_DISK: PASS|FAIL|NOT_RUN. No Python. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" +final_tag="AIENOS_CK_SERVICE_DISK" +build_only=0 +case "${1:-}" in + "") ;; + --build-only) build_only=1 ;; + *) echo "usage: $0 [--build-only]" >&2; exit 2 ;; +esac + +fail=0 +ok() { echo "ROW $1 PASS $2"; } +bad() { echo "ROW $1 FAIL $2"; fail=1; } +cross="" +if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +top="$(mktemp -d)" +qemu_pid="" +drain_pid="" +locked=0 +cleanup() { + [[ -z "${qemu_pid}" ]] || kill "${qemu_pid}" 2>/dev/null || true + [[ -z "${drain_pid}" ]] || kill "${drain_pid}" 2>/dev/null || true + exec 4>&- 2>/dev/null || true + rm -rf "${top}" + [[ "${locked}" == 0 ]] || gh_lock_release +} +trap cleanup EXIT +trap 'echo "${final_tag}: FAIL (script stopped at line ${LINENO})"' ERR + +# --- rows 200-201: build refusals and the accepted line (make -n: parse only) --- +fix="${repo_root}/native/kernel/tests/fixtures/owner" +own_fx="${fix}/TEST-FIXTURE-owner-pubkeys.txt" +mach_fx="${fix}/TEST-FIXTURE-machine-id.txt" +lib_any="${top}/libaienos_infer_kernel.a" # make -n never reads it +prod=(full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS="${own_fx}" CK_MACHINE_ID="${mach_fx}" CK_INFER_LIB="${lib_any}") +refused() { # label, expected message, make args... + local label="$1" want="$2" msg st; shift 2 + set +e; msg="$(make -s -n -C native/kernel OUT="${top}/refuse" "$@" 2>&1)"; st=$?; set -e + if [[ "${st}" != 0 ]] && grep -qF -- "${want}" <<<"${msg}"; then ok 200 "refused: ${label}" + else bad 200 "NOT refused (status ${st}): ${label}: $(tail -c 200 <<<"${msg}")"; fi +} +refused "inference + staging without CK_SERVICE (one-shot probe)" \ + "CK_INFER_LIB with CK_HARDWARE_STAGING needs CK_SERVICE=1" \ + full CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS="${own_fx}" CK_MACHINE_ID="${mach_fx}" CK_INFER_LIB="${lib_any}" +refused "core probe image + staging" "CK_INFER_LIB with CK_HARDWARE_STAGING needs CK_SERVICE=1" \ + CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS="${own_fx}" CK_MACHINE_ID="${mach_fx}" CK_INFER_LIB="${lib_any}" +refused "+ CK_SERVICE_TEST_KEYS" "CK_SERVICE_TEST_KEYS (TEST keys) cannot be combined with CK_HARDWARE_STAGING" \ + "${prod[@]}" CK_SERVICE_TEST_KEYS=1 +refused "+ CK_TEST_FWCFG_ARTIFACTS (fw_cfg test source)" \ + "CK_TEST_FWCFG_ARTIFACTS (QEMU fw_cfg test source) cannot be combined with CK_HARDWARE_STAGING" \ + "${prod[@]}" CK_TEST_FWCFG_ARTIFACTS=1 +refused "+ CK_RUST_LIBS" "CK_RUST_LIBS (FP probe, QEMU gate only) cannot be combined with CK_HARDWARE_STAGING" \ + "${prod[@]}" CK_RUST_LIBS="${top}/libfpu.a" +refused "+ CK_QEMU_UNSAFE_DMA" "CK_QEMU_UNSAFE_DMA (unconfined DMA, QEMU debug only) cannot be combined with CK_HARDWARE_STAGING" \ + "${prod[@]}" CK_QEMU_UNSAFE_DMA=1 +refused "+ CK_CONSOLE_SESSION" "CK_CONSOLE_SESSION (QEMU test console session) cannot be combined with CK_HARDWARE_STAGING" \ + "${prod[@]}" CK_CONSOLE_SESSION=1 +refused "+ CK_TEST_STORE_CRASH" "CK_SERVICE cannot be combined with a CK_TEST_* flag" \ + "${prod[@]}" CK_TEST_STORE_CRASH=1 +refused "+ CK_TEST_CONTINUITY" "CK_SERVICE cannot be combined with a CK_TEST_* flag" \ + "${prod[@]}" CK_TEST_CONTINUITY=1 +refused "staging without owner files" "CK_HARDWARE_STAGING refuses the TEST Store keys and TEST machine id" \ + full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_INFER_LIB="${lib_any}" +set +e; msg="$(make -s -n -C native/kernel OUT="${top}/accept" "${prod[@]}" 2>&1)"; st=$?; set -e +if [[ "${st}" == 0 ]] && grep -qF -- "-DCK_INFER_DISK_ONLY=1" <<<"${msg}" && grep -qF -- "-DCK_INFER_RESIDENT=1" <<<"${msg}"; then + ok 201 "accepted: make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS CK_MACHINE_ID CK_INFER_LIB (-DCK_INFER_DISK_ONLY=1 -DCK_INFER_RESIDENT=1)" +else + bad 201 "the supported line was not accepted with the disk-only flags (status ${st}): $(grep -m1 -i error <<<"${msg}" || true)" +fi +set +e; msg="$(make -s -n -C native/kernel OUT="${top}/accept2" full CK_SERVICE=1 CK_SERVICE_TEST_KEYS=1 CK_INFER_LIB="${lib_any}" 2>&1)"; st=$?; set -e +if [[ "${st}" == 0 ]] && ! grep -qF -- "-DCK_INFER_DISK_ONLY" <<<"${msg}"; then ok 201 "QEMU test-keys inference image unchanged (accepted, keeps the fw_cfg source)" +else bad 201 "QEMU test-keys inference image changed (status ${st})"; fi + +if [[ "${build_only}" == 1 ]]; then + if [[ "${fail}" == 0 ]]; then echo "${final_tag}_BUILD: PASS (make only; nothing booted)"; exit 0; fi + echo "${final_tag}_BUILD: FAIL"; exit 1 +fi + +# --- prerequisites (NOT_RUN, never a silent pass) --- +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +model="${AIENOS_MODEL:-${HOME}/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf}" +notrun="" +command -v qemu-system-aarch64 >/dev/null || notrun="qemu-system-aarch64 missing" +[[ -n "${notrun}" || ( -r "${code_fd}" && -r "${vars_fd}" ) ]] || notrun="AAVMF missing" +[[ -n "${notrun}" || -r "${model}" ]] || notrun="model file ${model} missing" +for t in cargo openssl mkfs.vfat mcopy mmd mdel; do [[ -n "${notrun}" ]] || command -v "${t}" >/dev/null || notrun="${t} missing"; done +if [[ -z "${notrun}" ]] && { ! rustc --print target-list 2>/dev/null | grep -qx aarch64-unknown-none \ + || ! [[ -d "$(rustc --print sysroot)/lib/rustlib/aarch64-unknown-none/lib" ]]; }; then + notrun="Rust target aarch64-unknown-none not installed" +fi +if [[ -n "${notrun}" ]]; then echo "NOT_RUN ${notrun}"; echo "${final_tag}: NOT_RUN (${notrun})"; exit 2; fi + +. "${repo_root}/scripts/lib_gate_hold.sh" +if ! gh_quiet_check; then echo "NOT_RUN ${gh_why}"; echo "${final_tag}: NOT_RUN (quiet flag held)"; exit 3; fi +if ! gh_lock_take qemu_ck_service_disk_test "${AIENOS_GATE_MINUTES:-120}"; then echo "NOT_RUN ${gh_why}"; echo "${final_tag}: NOT_RUN (QEMU gate lock held)"; exit 3; fi +locked=1 +source "${repo_root}/scripts/lib_ck_m1_checks.sh" + +# --- generated owner files and recovery secrets (this run only) --- +own="${top}/owner" +mkdir -p "${own}" +openssl genpkey -algorithm ed25519 -out "${own}/k.pem" 2>/dev/null +pk="$(openssl pkey -in "${own}/k.pem" -pubout -outform DER | tail -c 32 | od -An -tx1 | tr -d ' \n')" +rm -f "${own}/k.pem" # the private half is never kept: nothing in this gate signs +rnd() { od -An -tx1 -N "$1" /dev/urandom | tr -d ' \n'; } +printf '# owner file generated by scripts/qemu_ck_service_disk_test.sh for one QEMU run (private half discarded)\nowner_root_ed25519 %s\n' "${pk}" >"${own}/owner-pubkeys.txt" +printf '# machine file generated by scripts/qemu_ck_service_disk_test.sh for one QEMU run\nmachine_id %s\nstore_uuid %s\n' "$(rnd 32)" "$(rnd 16)" >"${own}/machine-id.txt" +secret_ok="$(rnd 32)" +secret_bad="$(rnd 32)" +[[ "${secret_ok}" != "${secret_bad}" && ${#secret_ok} == 64 ]] || { echo "${final_tag}: FAIL (secret generation)"; exit 1; } + +# --- scratch disk: ESP + model (3 out-of-order extents) + AIENOS partition --- +make -s -C native/kernel OUT="${top}/host" gpt-image model-map >/dev/null +img="${top}/disk.img" +model_bytes="$(stat -c %s "${model}")" +esp_mib=64 store_mib=64 +total_mib=$(( (model_bytes + 1048575) / 1048576 + esp_mib + store_mib + 16 )) +gpt_out="$("${top}/host/host/ck_gpt_image" create "${img}" 512 "${total_mib}" esp-model-aienos "${esp_mib}" "${model}" "${store_mib}")" +esp_first="$(sed -nE '1s/.* esp_first_lba=([0-9]+).*/\1/p' <<<"${gpt_out}")" +extents="$(sed -nE '1s/.* model_extents=([0-9:,]+).*/\1/p' <<<"${gpt_out}")" +[[ -n "${esp_first}" && -n "${extents}" ]] || { echo "ck_gpt_image esp-model-aienos gave no geometry"; echo "${final_tag}: FAIL"; exit 1; } +"${top}/host/host/ck_gpt_image" find "${img}" 512 | grep -q '^aienos first_lba=' || { echo "kernel GPT parser found no AIENOS partition"; echo "${final_tag}: FAIL"; exit 1; } +mkfs.vfat -F 32 -s 1 -S 512 --offset "${esp_first}" "${img}" $(( esp_mib * 1024 )) >/dev/null 2>&1 +echo "disk: ${img} ${total_mib} MiB, ESP at LBA ${esp_first}, model extents ${extents}, AIENOS ${store_mib} MiB" + +# --- rows 202-203: staging dry run (cmp) then apply --- +stage=(env AIENOS_OWNER_PUBKEYS="${own}/owner-pubkeys.txt" AIENOS_MACHINE_ID="${own}/machine-id.txt" AIENOS_MODEL="${model}" + bash scripts/stage_one_time_boot_ck_service.sh) +dirty=() +[[ -z "$(git status --porcelain)" ]] || dirty=(--allow-dirty) +cp --sparse=always "${img}" "${top}/disk.before" +set +e +"${stage[@]}" --dry-run --target-image "${img}" --extents "${extents}" "${dirty[@]}" >"${top}/dry.txt" 2>&1; st=$? +set -e +if [[ "${st}" == 0 ]] && grep -q '^Dry run: nothing touched. Pre-flight clean' "${top}/dry.txt"; then ok 203 "dry run completed, pre-flight clean"; else bad 203 "dry run status ${st}: $(tail -3 "${top}/dry.txt" | tr '\n' ' ')"; fi +n_writes="$(grep -cE '^write ESP:/EFI/(AIENOS|BOOT)/[A-Za-z0-9._-]+ bytes=[0-9]+ sha256=[0-9a-f]{64}$' "${top}/dry.txt" || true)" +if [[ "${n_writes}" == 4 ]]; then ok 203 "dry run printed 4 writes, each with bytes and sha256"; else bad 203 "dry run printed ${n_writes} well-formed writes (want 4)"; fi +if cmp -s "${img}" "${top}/disk.before"; then ok 203 "dry run left the scratch image byte-identical (cmp)"; else bad 203 "dry run CHANGED the scratch image"; fi +grep -E '^(image sha256|write )' "${top}/dry.txt" | sed 's/^/ dry: /' +set +e +"${stage[@]}" --apply --target-image "${img}" --extents "${extents}" "${dirty[@]}" >"${top}/apply.txt" 2>&1; st=$? +set -e +if [[ "${st}" == 0 ]] && grep -q '^staged: 4 files written to the ESP' "${top}/apply.txt"; then ok 203 "apply staged 4 files and read them back equal"; else bad 203 "apply status ${st}: $(tail -3 "${top}/apply.txt" | tr '\n' ' ')"; fi +if cmp -s "${img}" "${top}/disk.before"; then bad 203 "apply left the image unchanged (the cmp check would be vacuous)"; else ok 203 "apply changed the image (the dry-run cmp is not vacuous)"; fi +rm -f "${top}/disk.before" +for f in aienos-ck-service.efi MODEL.MAP; do + d="$(grep -E "^write ESP:/EFI/AIENOS/${f} " "${top}/dry.txt" | sed -nE 's/.* sha256=([0-9a-f]{64})$/\1/p')" + a="$(grep -E "^write ESP:/EFI/AIENOS/${f} " "${top}/apply.txt" | sed -nE 's/.* sha256=([0-9a-f]{64})$/\1/p')" + if [[ -n "${d}" && "${d}" == "${a}" ]]; then ok 203 "${f}: apply wrote the digest the dry run announced (${d:0:16})"; else bad 203 "${f}: dry ${d:-none} vs apply ${a:-none}"; fi +done +mt="${img}@@$(( esp_first * 512 ))" +staged_efi="${top}/staged.efi" +mcopy -n -i "${mt}" ::/EFI/BOOT/BOOTAA64.EFI "${staged_efi}" +if grep -q "build A and build B equal" "${top}/apply.txt"; then ok 202 "built twice in clean folders, equal digests"; else bad 202 "no reproducibility line from the staging script"; fi +if grep -aqF "infer: resident open" "${staged_efi}" && grep -aqF "infer_source_mode: boot-disk model" "${staged_efi}"; then ok 202 "staged image carries the resident session and the boot-disk source"; else bad 202 "staged image lacks the resident session or the boot-disk source"; fi +s="$(grep -aoE "fw_cfg|opt/aienos/model|QEMU0002|TEST-ONLY|TEST Store|TEST machine id|AIEN-TEST-BOOT01" "${staged_efi}" | sort -u | tr '\n' ' ' || true)" +if [[ -z "${s}" ]]; then ok 202 "staged image carries no fw_cfg, TEST-ONLY or TEST Store marker"; else bad 202 "staged image carries: ${s}"; fi +staged_elf="${repo_root}/target/native-kernel-service-staging/full-service-hardware-staging/aienos-ck.elf" +y="$("${cross}nm" "${staged_elf}" | grep -E ' (fw_select|fw_read|fw_find|fw_dma_read|fwcfg_from_dsdt|ck_store_test_keys|ck_store_test_uuid)$' | tr '\n' ' ' || true)" +if [[ -z "${y}" ]]; then ok 202 "no fw_cfg or TEST key symbol in the ELF"; else bad 202 "symbols present: ${y}"; fi + +# --- QEMU: one NVMe disk (ESP + model + Store), PL011 serial from outside --- +ser_line() { printf '%s\r' "$1" >&4; sleep 1.2; } +serial_has() { tr -d '\r' 2>/dev/null <"${work}/serial.log" | grep -qE -- "$1"; } +wait_for() { local deadline=$(( $(date +%s) + $1 )); shift + while (( $(date +%s) < deadline )); do for p in "$@"; do serial_has "${p}" && return 0; done + kill -0 "${qemu_pid}" 2>/dev/null || break; sleep 1; done + for p in "$@"; do serial_has "${p}" && return 0; done; return 1; } +ser_wait() { wait_for "${2:-300}" "$1" '^report_kind: (panic|fault|final)' || true; } +has() { grep -qE -- "$1" "${work}/serial.txt"; } +rcheck() { if has "$3"; then ok "$1" "$2"; else bad "$1" "$2"; fi; } +rabsent() { if has "$3"; then bad "$1" "$2 (present)"; else ok "$1" "$2"; fi; } +line_of() { { grep -nE -m1 -- "$1" "${work}/serial.txt" || true; } | cut -d: -f1; } +before() { local a b; a="$(line_of "$3")"; b="$(line_of "$4")" + if [[ -n "${a}" && -n "${b}" && "${a}" -lt "${b}" ]]; then ok "$1" "$2 (lines ${a} < ${b})"; else bad "$1" "$2 (lines ${a:-none} ${b:-none})"; fi; } +boot_to="${AIENOS_QEMU_INFER_TIMEOUT:-2700}" +cp "${vars_fd}" "${top}/vars.fd" # one machine: the same NVRAM file for both main boots +boot() { # name disk-image driver [extra qemu args...] + local name="$1" disk="$2" drv="$3"; shift 3 + work="${top}/${name}" + mkdir -p "${work}" + mkfifo "${work}/ser.in" "${work}/ser.out" + : >"${work}/serial.log" + local vars="${BOOT_VARS:-${top}/vars.fd}" + timeout "${boot_to}" qemu-system-aarch64 \ + -M virt,virtualization=on,gic-version=3,iommu=smmuv3 -accel tcg,thread=single -cpu max -smp 4 -m 4096 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${vars}" \ + -drive if=none,id=nvme0,format=raw,file="${disk}" \ + -device nvme,drive=nvme0,serial=aienos-service-disk \ + -device ramfb -display none -nic none -monitor none \ + -chardev pipe,id=ser,path="${work}/ser" -serial chardev:ser -no-reboot "$@" 2>"${work}/qemu.err" & + qemu_pid=$! + cat "${work}/ser.out" >>"${work}/serial.log" & + drain_pid=$! + exec 4>"${work}/ser.in" + local t0; t0=$(date +%s) + if wait_for "${boot_to}" '^lifecycle: ready state=' '^report_kind: (panic|fault|final)' && serial_has '^lifecycle: ready state='; then + sleep 1 + "${drv}" + fi + wait_for 600 '^report_kind: (panic|fault|final)' || true + set +e; wait "${qemu_pid}"; qemu_status=$?; set -e + qemu_pid="" + exec 4>&- 2>/dev/null || true + wait "${drain_pid}" 2>/dev/null || true + drain_pid="" + tr -d '\r' <"${work}/serial.log" >"${work}/serial.txt" + [[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/serial.txt" "${AIENOS_LOG_DIR}/qemu_ck_service_disk_${name}.log" + echo "== boot $(basename "${work}"): qemu exit ${qemu_status} after $(( $(date +%s) - t0 )) s" +} +m1() { + failed=0 + ck_m1_checks >"${work}/m1.txt" 2>&1 || true + if [[ "${failed}" == 0 ]]; then ok "$1" "M1 checks"; else bad "$1" "M1 checks: $(grep -E "^FAIL" "${work}/m1.txt" | head -3 | tr "\n" " ")"; fi +} +infer_wait="${AIENOS_QEMU_INFER_WAIT:-1800}" +drive_main1() { + ser_line status + ser_line "unlock ${secret_ok}"; ser_wait '^(lifecycle: unlock ok|lifecycle: REFUSED verb=unlock)' + ser_line status + ser_line "prompt What is the capital of France?" + wait_for "${infer_wait}" '^lifecycle: (reply pending|generation cancelled|REFUSED verb=prompt)' '^report_kind: (panic|fault|final)' || true + ser_line approve; ser_wait '^lifecycle: (approve committed|REFUSED verb=approve)' + ser_line "remember prefer short notes"; ser_wait '^lifecycle: (remembered|REFUSED verb=remember)' + ser_line facts; ser_wait '^lifecycle: (facts records=|facts none|REFUSED verb=facts)' + ser_line evidence + ser_line shutdown +} +drive_main2() { + ser_line "unlock ${secret_bad}"; ser_wait '^(lifecycle: unlock ok|lifecycle: REFUSED verb=unlock)' + ser_line "unlock ${secret_ok}"; ser_wait '^(lifecycle: unlock ok|lifecycle: REFUSED verb=unlock)' + ser_line status + ser_line recall; ser_wait '^lifecycle: recall' + ser_line facts; ser_wait '^lifecycle: (facts records=|facts none|REFUSED verb=facts)' + ser_line evidence + ser_line shutdown +} +drive_neg() { + ser_line "unlock ${secret_ok}"; ser_wait '^(lifecycle: unlock ok|lifecycle: REFUSED verb=unlock)' + ser_line "prompt What is the capital of France?"; ser_wait '^lifecycle: (REFUSED verb=prompt|reply pending|generating)' + ser_line evidence + ser_line shutdown +} +re_open='^infer: resident open rc=0 tensors=147 vocab=128256 layers=16 kv_capacity=64 max_new=16 max_prompt_bytes=256 heap_reserve_kib=64 heap_used_kib=[0-9]+ open_us=[0-9]+$' +re_recall='^lifecycle: recall gen=4 kind=reply id=[0-9a-f]{8} bytes=[0-9]+ text="aienos\.reply\.v1.prompt: What is the capital of France\?.reply: The capital of France is Paris\.' +frames_kept() { + local l b a; l="$(grep -E -m1 '^infer: unloaded ' "${work}/serial.txt" || true)" + b="$(sed -nE 's/.* frames_free_before=([0-9]+).*/\1/p' <<<"${l}")"; a="$(sed -nE 's/.* frames_free_after=([0-9]+).*/\1/p' <<<"${l}")" + if [[ -n "${b}" && "${b}" == "${a}" ]] && grep -qE '^infer: unloaded .* rc=0,0$' <<<"${l}"; then ok "$1" "$2 (${b} = ${a})"; else bad "$1" "$2 (before=${b:-none} after=${a:-none})"; fi; } +disk_model_rows() { # row: the model came from the disk, by the map, with the pinned digest + rcheck "$1" "stub read MODEL.MAP from the ESP" "^model_map: ok len=${model_bytes} extents=3 sector=512 disk=[0-9a-f]{32}\$" + rcheck "$1" "boot-disk source declared" '^infer_source_mode: boot-disk model \(MODEL\.MAP read by the UEFI stub' + rcheck "$1" "model handed over from the disk (3 extents)" "^infer: disk base=0x[0-9a-f]+ size=${model_bytes} extents=3 read_us=[0-9]+ block_size=512\$" + rcheck "$1" "kernel recomputed the pinned sha256" '^infer: sha256=3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1 ' + rabsent "$1" "no fw_cfg ingest line" '^(infer_source_mode: TEST-ONLY|infer: fw_cfg|infer: ingest bytes=)' +} + +# --- negative control A: no MODEL.MAP, the model offered on fw_cfg (row 208) --- +neg_img="${top}/neg.img" +cp --sparse=always "${img}" "${neg_img}" +mdel -i "${neg_img}@@$(( esp_first * 512 ))" ::/EFI/AIENOS/MODEL.MAP +cp "${vars_fd}" "${top}/vars.neg" +BOOT_VARS="${top}/vars.neg" boot neg-nomap "${neg_img}" drive_neg -fw_cfg "name=opt/aienos/model,file=${model}" +rcheck 208 "stub found no MODEL.MAP" '^model_map: absent' +rcheck 208 "kernel refused: no boot-disk model, no other source" '^infer: ingest REFUSED \(no boot-disk model: MODEL\.MAP absent or refused by the stub; this image has no other model source\)$' +rabsent 208 "the fw_cfg model was NOT ingested although QEMU offered it" '^(infer_source_mode|infer: fw_cfg|infer: ingest bytes=|infer: resident open)' +rcheck 208 "unlock ok (the Store path is unaffected)" '^lifecycle: unlock ok state=ready$' +rcheck 208 "prompt refused: no inference unit" '^lifecycle: REFUSED verb=prompt state=ready reason="no inference unit in this image"$' +rcheck 208 "evidence inference=none" '^lifecycle: evidence .* inference=none ' +rabsent 208 "no panic or fault" '^report_kind: (panic|fault)' +if [[ "${qemu_status}" == 0 ]]; then ok 208 "QEMU exit 0"; else bad 208 "QEMU exit ${qemu_status}"; fi + +# --- negative control B: MODEL.MAP with a corrupted declared sha256 (row 209) --- +cp --sparse=always "${img}" "${neg_img}" +"${top}/host/host/ck_model_map" make "${top}/BAD.MAP" --file "${model}" --disk "${neg_img}" \ + $(IFS=,; for e in ${extents}; do printf -- '--extent %s ' "${e}"; done) --corrupt-sha >/dev/null +mcopy -o -i "${neg_img}@@$(( esp_first * 512 ))" "${top}/BAD.MAP" ::/EFI/AIENOS/MODEL.MAP +cp "${vars_fd}" "${top}/vars.neg" +BOOT_VARS="${top}/vars.neg" boot neg-badsha "${neg_img}" drive_neg +rcheck 209 "stub accepted the map and read the bytes" "^model_map: ok len=${model_bytes} extents=3 " +rcheck 209 "kernel refused to decode: sha256 mismatch" '^infer: sha256 mismatch declared=[0-9a-f]{64}$' +rabsent 209 "no resident session" '^infer: resident open' +rcheck 209 "prompt refused: no inference unit" '^lifecycle: REFUSED verb=prompt state=ready reason="no inference unit in this image"$' +rabsent 209 "no panic or fault" '^report_kind: (panic|fault)' +if [[ "${qemu_status}" == 0 ]]; then ok 209 "QEMU exit 0"; else bad 209 "QEMU exit ${qemu_status}"; fi +rm -f "${neg_img}" + +# --- boot 1: the staged disk, blank Store (rows 204-205) --- +boot main-1 "${img}" drive_main1 +disk_model_rows 204 +rcheck 204 "resident session open" "${re_open}" +before 204 "resident open < lifecycle ready" '^infer: resident open rc=0' '^lifecycle: ready state=locked' +rcheck 204 "owner provisioned at build time (public only)" '^owner: provisioned at build time \(public only\): owner_root_ed25519 sha256=[0-9a-f]{16} store_uuid=' +rcheck 204 "Store stage refused the production key source: LOCKED" '^store: REFUSED proof=keyed step="production Store key source" rc=-?[0-9]+ ' +rcheck 204 "lifecycle came up locked" '^lifecycle: ready state=locked store=locked' +rcheck 204 "blank AIENOS partition formatted as a production store" '^store: blank disk \(all-zero anchor \+ Store head\): formatted production store$' +rcheck 204 "recovery keyslot genesis" '^store: key source=recovery-keyslot genesis=1 ' +rcheck 204 "unlock ok, genesis, generation 2 boot 1" '^store: unlock ok source=recovery-keyslot slot=1 genesis=1 generation=2 boot_count=1$' +rcheck 204 "continuity genesis from the owner root key (operator source)" '^continuity: genesis source=operator provenance=owner-root-pk\+store-uuid ' +rcheck 204 "identity PROVISIONED" '^continuity: PROVISIONED agent=[0-9a-f]{64} incarnation=1 ' +rcheck 204 "lifecycle unlocked to ready" '^lifecycle: unlock ok state=ready$' +rcheck 205 "golden reply ids" '^lifecycle: reply ids=791 6864 315 9822 374 12366 13 128009 tokens=8 prompt_ids=17 steps=25 us=[0-9]+$' +rcheck 205 "reply is the pending proposal" '^lifecycle: reply pending state=serve proposed="reply: The capital of France is Paris\.\??" \(approve \| deny \| cancel\)$' +rcheck 205 "approve committed the reply at generation 4" '^lifecycle: approve committed gen=4 id=[0-9a-f]{8} state=ready$' +rcheck 205 "remembered as record 1 at generation 6" '^lifecycle: remembered id=1 t=1 store_gen=6 bytes=18 text="prefer short notes"$' +rcheck 205 "facts lists it, chain verified" '^lifecycle: facts records=1 shown=1 journal_bytes=192 chain=ok$' +rcheck 205 "evidence counters" '^lifecycle: evidence requests=[0-9]+ refused=0 invalid=0 tasks=0 approved=1 denied=0 cancelled=0 overlong=0 last_commit_gen=4 last_id=[0-9a-f]{8} prompts=1 replies=1 gen_cancelled=0 gen_failed=0 recalls=0 inference=resident remembers=1 facts=1 cortex=open records=1$' +rcheck 205 "resident close" '^infer: resident close rc=0 ' +frames_kept 205 "unload returned every frame" +before 205 "unload < stop order" '^infer: unloaded ' '^lifecycle: stop order store=closed' +rcheck 205 "stop order closed the Store" '^lifecycle: stop order store=closed nvme=released state=stop requests=[0-9]+$' +rabsent 205 "operator input accepted (no console-input refusal)" '^lifecycle: REFUSED console input' +rabsent 205 "no panic or fault" '^report_kind: (panic|fault)' +if [[ "${qemu_status}" == 0 ]]; then ok 205 "QEMU exit 0"; else bad 205 "QEMU exit ${qemu_status}"; fi +m1 205 +agent="$(grep -oE '^continuity: PROVISIONED agent=[0-9a-f]{64}' "${work}/serial.txt" | head -1 | sed 's/.*agent=//')" +[[ -n "${agent}" ]] || agent="NO_AGENT" + +# --- boot 2: cold restart, SAME disk image file (row 206) --- +boot main-2 "${img}" drive_main2 +disk_model_rows 206 +rcheck 206 "resident session open again" "${re_open}" +rcheck 206 "wrong secret refused by the keyslot tag, still locked" '^store: unlock REFUSED proof=keyed step="recovery secret rejected \(K_vol unwrap tag failed\); disk not opened" rc=-?[0-9]+ \([A-Za-z_]+\); still LOCKED, disk not reformatted$' +rabsent 206 "not reformatted" '^store: blank disk' +rcheck 206 "Store opened at generation 6 (no genesis)" '^store: opened generation=6 boot_count=1 prev_commit=[0-9a-f]+ anchor=[a-z_-]+$' +rcheck 206 "unlock ok, no genesis" '^store: unlock ok source=recovery-keyslot slot=1 genesis=0 generation=7 boot_count=2$' +rcheck 206 "continuity RESUMED the same agent" "^continuity: RESUMED agent=${agent} incarnation=2 " +rabsent 206 "no second genesis" '^continuity: (PROVISIONED|genesis)' +rcheck 206 "recall returns the approved reply from the disk" "${re_recall}" +rcheck 206 "facts answers the fact from the disk" '^lifecycle: fact id=1 t=1 store_gen=6 text="prefer short notes"$' +rabsent 206 "neither the prompt nor the fact retyped" '^> (prompt|remember) ' +rcheck 206 "evidence: one refused unlock, one recall, facts, nothing generated" '^lifecycle: evidence requests=[0-9]+ refused=1 invalid=0 tasks=0 approved=0 denied=0 cancelled=0 overlong=0 last_commit_gen=0 last_id=00000000 prompts=0 replies=0 gen_cancelled=0 gen_failed=0 recalls=1 inference=resident remembers=0 facts=1 cortex=open records=1$' +frames_kept 206 "unload returned every frame" +rcheck 206 "stop order closed the Store" '^lifecycle: stop order store=closed nvme=released state=stop requests=[0-9]+$' +rabsent 206 "no panic or fault" '^report_kind: (panic|fault)' +if [[ "${qemu_status}" == 0 ]]; then ok 206 "QEMU exit 0"; else bad 206 "QEMU exit ${qemu_status}"; fi +m1 206 + +# --- row 207: secret hygiene, no TEST markers, across every boot --- +for b in neg-nomap neg-badsha main-1 main-2; do + work="${top}/${b}" + rabsent 207 "${b}: right secret hex never in the serial log" "${secret_ok}" + rabsent 207 "${b}: wrong secret hex never in the serial log" "${secret_bad}" + rabsent 207 "${b}: no TEST banner, TEST machine id or TEST Store line" '(TEST-ONLY|TEST machine id|formatted TEST store)' +done + +if [[ "${fail}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + for b in neg-nomap neg-badsha main-1 main-2; do echo "---- ${b} serial (selected lines) ----" + grep -E '^(model_map|infer|lifecycle|store|continuity|owner|report_kind|> )' "${top}/${b}/serial.txt" | head -60 || true; done +fi +echo "ROW 210 LIMIT QEMU only (hardware NOT_RUN); Spark console input, the AIENOS partition on the Spark NVMe and the owner key ceremony are separate items; int8 off" +if [[ "${fail}" == 0 ]]; then echo "${final_tag}: PASS (QEMU only; hardware NOT_RUN)"; exit 0; fi +echo "${final_tag}: FAIL"; exit 1 diff --git a/scripts/stage_one_time_boot_ck_service.sh b/scripts/stage_one_time_boot_ck_service.sh new file mode 100755 index 00000000..19f177f6 --- /dev/null +++ b/scripts/stage_one_time_boot_ck_service.sh @@ -0,0 +1,399 @@ +#!/usr/bin/env bash +# Stage the C kernel PRODUCTION SERVICE image with resident CPU inference +# (native v1 P06 / gate N3, aienos#34; docs/ATTENDED_SESSION_N1.md item B2) +# plus its MODEL.MAP for exactly one attended boot. Same shape as +# scripts/stage_one_time_boot_ck_b7b.sh (build twice, compare, stage once, +# BootNext once); the image is the one supported hardware inference build +# (docs/NATIVE_PACKAGE.md, "Service image with inference"): +# +# make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS=<file> +# CK_MACHINE_ID=<file> CK_INFER_LIB=<libaienos_infer_kernel.a> +# CK_FB_HOLD_S=120 +# +# Its only model source is the boot disk (MODEL.MAP read by the UEFI stub +# through the firmware's Block I/O); the QEMU fw_cfg ingest is compiled out. +# +# scripts/stage_one_time_boot_ck_service.sh --dry-run [TARGET] +# scripts/stage_one_time_boot_ck_service.sh --apply [TARGET] +# +# Exactly one of --dry-run / --apply is required; there is no default mode. +# TARGET (optional): --target-image IMG --extents LBA:COUNT[,LBA:COUNT...] +# [--allow-dirty]. Stage a GPT disk IMAGE instead of this machine (desk and +# QEMU use: scripts/qemu_ck_service_disk_test.sh). IMG must already hold an +# ESP (FAT, EFI System type) and the model bytes at the listed extents (file +# order, 512-byte LBAs; ck_gpt_image esp-model-aienos prints them). The +# files go into the image's ESP with mtools; the image's removable-media +# path \EFI\BOOT\BOOTAA64.EFI stands in for BootNext. No sudo, no +# efibootmgr, no chattr. --allow-dirty is accepted only with --target-image. +# Without TARGET it stages this machine: /dev/nvme0n1, the ESP at /boot/efi, +# BootNext (needs sudo; operator only). +# +# Owner files (the hardware staging image refuses the TEST Store keys and the +# TEST machine id; native/kernel/README.md, "Owner provisioning"): +# AIENOS_OWNER_PUBKEYS=<owner public keys file> AIENOS_MACHINE_ID=<machine id file> +# The labelled TEST-FIXTURE files under native/kernel/tests/fixtures/owner/ +# are refused. AIENOS_MODEL overrides the model path (pinned sha256 below). +# +# --dry-run prints every write --apply would do, in order, each with its +# destination, size and SHA-256, and performs none of them: nothing is written +# to the target disk or image, the ESP, the model file (no chattr) or the +# firmware boot variables, and no sudo is called. To know those digests it +# builds the image twice into its own folders under target/ (the same two +# builds --apply makes) and makes MODEL.MAP in a temporary folder; with +# --target-image both are exact, on this machine the MODEL.MAP digest needs a +# raw read of /dev/nvme0n1 (root) and is printed as "at --apply". The QEMU +# gate checks that a dry run leaves a scratch image byte-identical (cmp). +# +# --apply, in order: +# 1. builds the service image TWICE in two clean folders with CK_FB_HOLD_S=120 +# and STOPs unless the digests are equal; checks it carries the resident +# session, the boot-disk model source and no fw_cfg / TEST marker; +# 2. (machine) sudo chattr +i on the model, FIRST, so its blocks cannot move; +# 3. ck_model_map make + check (reads every extent back by LBA and +# recomputes the SHA-256: the bytes the firmware will read); STOP unless +# the map declares the pinned model hash; +# 4. (machine) sudo scripts/verify_native_rollback.sh --capture-pre; +# 5. writes the image, MODEL.MAP and a STAGED-CK-SERVICE.TXT record to +# \EFI\AIENOS on the ESP (image mode: also \EFI\BOOT\BOOTAA64.EFI); +# 6. (machine) creates a boot entry WITHOUT adding it to BootOrder, checks +# Boot0004 AIENOSRECOV is still there, sets BootNext once. +# It never reboots. The attended session (docs/ATTENDED_SESSION_N1.md) then +# types `unlock <64-hex recovery secret>`, `prompt ...`, `approve`, `remember +# ...`, `shutdown`, and after the cold restart `unlock`, `recall`, `facts`. +# Hardware: NOT_RUN. No Python. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +usage() { echo "usage: $0 --dry-run|--apply [--target-image IMG --extents LBA:COUNT[,...] [--allow-dirty]]" >&2; exit 2; } +mode="" +case "${1:-}" in + --dry-run) mode=dry ;; + --apply) mode=apply ;; + *) usage ;; +esac +shift +target_img="" extents="" allow_dirty=0 +while [[ $# -gt 0 ]]; do + case "$1" in + --target-image) [[ $# -ge 2 ]] || usage; target_img="$2"; shift 2 ;; + --extents) [[ $# -ge 2 ]] || usage; extents="$2"; shift 2 ;; + --allow-dirty) allow_dirty=1; shift ;; + *) usage ;; + esac +done +if [[ -z "${target_img}" ]]; then + [[ -z "${extents}" && "${allow_dirty}" == 0 ]] || { echo "--extents and --allow-dirty need --target-image" >&2; exit 2; } +else + [[ -n "${extents}" ]] || { echo "--target-image needs --extents" >&2; exit 2; } + [[ "${extents}" =~ ^[0-9]+:[0-9]+(,[0-9]+:[0-9]+)*$ ]] || { echo "--extents must be LBA:COUNT[,LBA:COUNT...]" >&2; exit 2; } +fi + +disk="/dev/nvme0n1" +esp="/boot/efi" +owner_pubkeys="${AIENOS_OWNER_PUBKEYS:-}" +machine_id="${AIENOS_MACHINE_ID:-}" +model="${AIENOS_MODEL:-${HOME}/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf}" +pinned_sha=3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1 +out="${repo_root}/target/native-kernel-service-staging" +out_b="${out}-build-b" +image="${out}/full-service-hardware-staging/BOOTAA64.EFI" +image_b="${out_b}/full-service-hardware-staging/BOOTAA64.EFI" +lib="${repo_root}/target/infer-kernel/aarch64-unknown-none/release/libaienos_infer_kernel.a" +map_tool="${out}/host/ck_model_map" +loader='\EFI\AIENOS\aienos-ck-service.efi' +label="AIENOS C kernel service (one-time)" +recov_entry="0004" +recov_label="AIENOSRECOV" +hold_s=120 +secure_boot_var="/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c" +stamp="$(date -u +%Y%m%dT%H%M%SZ)" +evidence_dir="${AIENOS_STAGE_OUT:-${HOME}/workspace/evidence-out/N3/staging}/${stamp}" +tmp="$(mktemp -d)" +trap 'rm -rf "${tmp}"' EXIT + +stops=() +stop() { stops+=("$*"); echo "STOP: $*"; } + +# Print a command; run it only with --apply. +run() { + printf '+' + printf ' %q' "$@" + printf '\n' + [[ "${mode}" == apply ]] || return 0 + "$@" +} +sha() { sha256sum "$1" | cut -d' ' -f1; } +# One line per write: what, where, how many bytes, which digest. +announce() { # dest src + printf 'write %s bytes=%s sha256=%s\n' "$1" "$(stat -c %s "$2")" "$(sha "$2")" +} + +echo "mode: ${mode}${target_img:+ (target image ${target_img})}" + +# ---- read-only pre-flight ---- +if [[ -n "$(git status --porcelain)" ]]; then + if [[ "${allow_dirty}" == 1 ]]; then + echo "tree: DIRTY, allowed (--allow-dirty, target image only: a desk or QEMU stage, never a boot)" + else + stop "the checkout has uncommitted changes; the boot must map to one exact commit" + fi +fi +commit="$(git rev-parse HEAD)" +echo "commit: ${commit}" + +for f in owner_pubkeys machine_id; do + v="${!f}" + if [[ -z "${v}" ]]; then + stop "${f} file not given (set AIENOS_OWNER_PUBKEYS and AIENOS_MACHINE_ID)" + elif [[ ! -f "${v}" ]]; then + stop "${f} file not found: ${v}" + elif [[ "$(basename "${v}")" == TEST-FIXTURE* ]]; then + stop "${f} is a labelled TEST-FIXTURE file (${v}); a stage needs the operator's own file" + else + v="$(realpath -- "${v}")" # make -C native/kernel resolves relative paths from there + printf -v "${f}" %s "${v}" + echo "${f}: ${v} sha256=$(sha "${v}")" + fi +done +[[ -f "${model}" ]] || stop "model file not found: ${model}" + +esp_off="" esp_part="" current_before="" order_before="" existing="" +if [[ -n "${target_img}" ]]; then + [[ -f "${target_img}" ]] || stop "target image not found: ${target_img}" + command -v mcopy >/dev/null && command -v mmd >/dev/null || stop "mtools (mcopy, mmd) not installed" + # The ESP from the image's own primary GPT (512-byte LBAs): header at LBA 1, + # partition entries at the LBA it names; type C12A7328-F81F-11D2-BA4B-00A0C93EC93B. + if [[ -f "${target_img}" && "$(od -An -c -j 512 -N 8 "${target_img}" | tr -d ' ')" == "EFIPART" ]]; then + ent_lba="$(od -An -tu8 -j $((512 + 72)) -N 8 "${target_img}" | tr -d ' ')" + n_ent="$(od -An -tu4 -j $((512 + 80)) -N 4 "${target_img}" | tr -d ' ')" + ent_sz="$(od -An -tu4 -j $((512 + 84)) -N 4 "${target_img}" | tr -d ' ')" + for ((i = 0; i < n_ent && i < 128; i++)); do + o=$((ent_lba * 512 + i * ent_sz)) + if [[ "$(od -An -tx1 -j "${o}" -N 16 "${target_img}" | tr -d ' \n')" == 28732ac11ff8d211ba4b00a0c93ec93b ]]; then + esp_first="$(od -An -tu8 -j $((o + 32)) -N 8 "${target_img}" | tr -d ' ')" + esp_off=$((esp_first * 512)) + esp_part=$((i + 1)) + break + fi + done + [[ -n "${esp_off}" ]] || stop "the target image has no EFI System partition" + echo "esp: partition ${esp_part:-?} of ${target_img} at byte ${esp_off:-?} (mtools)" + else + stop "the target image has no primary GPT (no EFI PART at LBA 1)" + fi + echo "boot: image mode: \\EFI\\BOOT\\BOOTAA64.EFI (removable-media path) stands in for BootNext; no NVRAM write" +else + [[ "${allow_dirty}" == 0 ]] || stop "--allow-dirty is refused without --target-image" + model_dev="$(findmnt -no SOURCE -T "${model}" 2>/dev/null || true)" + model_disk="/dev/$(lsblk -no PKNAME "${model_dev}" 2>/dev/null | head -1)" + echo "model: ${model} on ${model_dev:-?} (disk ${model_disk})" + [[ "${model_disk}" == "${disk}" ]] || stop "the model's filesystem is not a plain partition of ${disk} (got '${model_dev}' on '${model_disk}'): the firmware reads raw LBAs" + echo "model attrs: $(lsattr "${model}" 2>/dev/null | cut -d' ' -f1 || echo '?')" + esp_dev="$(findmnt -no SOURCE "${esp}" 2>/dev/null || true)" + esp_opts="$(findmnt -no OPTIONS "${esp}" 2>/dev/null || true)" + [[ -n "${esp_dev}" ]] || stop "the ESP is not mounted at ${esp}" + esp_disk="/dev/$(lsblk -no PKNAME "${esp_dev}" 2>/dev/null | head -1)" + esp_part="$(cat "/sys/class/block/$(basename "${esp_dev:-none}")/partition" 2>/dev/null || true)" + echo "esp: ${esp_dev:-?} partition ${esp_part:-?} of ${esp_disk} (${esp_opts%%,*})" + [[ "${esp_disk}" == "${disk}" ]] || stop "the ESP is not on ${disk} (MODEL.MAP is read from the boot volume, the model from ${disk})" + [[ ",${esp_opts}," == *",rw,"* ]] || stop "the ESP is not mounted read-write" + if [[ -r "${secure_boot_var}" ]] && [[ "$(od -An -t u1 -j 4 -N 1 "${secure_boot_var}" | tr -d ' ')" == "1" ]]; then + stop "Secure Boot is enabled; the firmware will refuse the unsigned C image" + else + echo "secure boot: off or unreadable (recorded only; development decision 2026-10-01)" + fi + boot_state="$(efibootmgr 2>/dev/null || true)" + [[ -n "${boot_state}" ]] || stop "efibootmgr gave no output" + order_before="$(sed -n 's/^BootOrder: //p' <<<"${boot_state}")" + current_before="$(sed -n 's/^BootCurrent: //p' <<<"${boot_state}")" + next_before="$(sed -n 's/^BootNext: //p' <<<"${boot_state}")" + recov_line="$(grep -E "^Boot${recov_entry}\*? " <<<"${boot_state}" || true)" + echo "BootCurrent: ${current_before}" + echo "BootOrder: ${order_before} (never changed)" + [[ -z "${next_before}" ]] || stop "BootNext is already set (${next_before}); another staging is pending" + if [[ "${recov_line}" == *"${recov_label}"* ]]; then + echo "recovery: Boot${recov_entry} ${recov_label} present (kept untouched)" + else + stop "Boot${recov_entry} ${recov_label} not present: insert the recovery stick and check docs/RECOVERY_MEDIA_MACHINE1.md (got: '${recov_line:-none}')" + fi + existing="$(sed -n "s/^Boot\([0-9A-F]\{4\}\)\*\{0,1\} ${label}.*/\1/p" <<<"${boot_state}" | head -1)" + echo "boot entry: '${label}' ${existing:+exists as Boot${existing}}${existing:-will be created (create-only, not in BootOrder)}" + echo "evidence: ${evidence_dir}" +fi +echo "screen hold: ${hold_s} s before the reset (CK_FB_HOLD_S)" + +if [[ ${#stops[@]} -gt 0 ]]; then + if [[ "${mode}" == apply ]]; then + echo "STOPPED before touching anything: ${#stops[@]} pre-flight problem(s) above." + exit 1 + fi + echo + echo "Dry run: nothing touched. --apply would STOP now on ${#stops[@]} pre-flight problem(s) above." + exit 0 +fi + +# ---- 1. build twice in clean folders, compare, check the image (both modes: +# the dry run needs the digests; it writes only under target/) ---- +echo +echo "build (both modes; writes only under ${repo_root}/target):" +cross="" +[[ "$(uname -m)" == aarch64 ]] || cross="aarch64-linux-gnu-" +echo "+ cargo build --release --target aarch64-unknown-none -p aienos-infer-kernel (crates/aienos-infer-kernel)" +CARGO_TARGET_DIR="${repo_root}/target/infer-kernel" cargo build -q --release --target aarch64-unknown-none \ + --manifest-path crates/aienos-infer-kernel/Cargo.toml +for o in "${out}" "${out_b}"; do + rm -rf "${o}" + echo "+ make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS=${owner_pubkeys} CK_MACHINE_ID=${machine_id} CK_INFER_LIB=${lib} CK_FB_HOLD_S=${hold_s} OUT=${o}" + make -s -C native/kernel CROSS="${cross}" OUT="${o}" AIENOS_COMMIT="${commit}" full \ + CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_OWNER_PUBKEYS="${owner_pubkeys}" CK_MACHINE_ID="${machine_id}" \ + CK_INFER_LIB="${lib}" CK_FB_HOLD_S="${hold_s}" >"${tmp}/make.log" 2>&1 \ + || { tail -20 "${tmp}/make.log"; echo "STOP: the service image did not build"; exit 1; } +done +make -s -C native/kernel OUT="${out}" model-map >/dev/null +digest="$(sha "${image}")" +digest_b="$(sha "${image_b}")" +[[ "${digest}" == "${digest_b}" ]] \ + || { echo "STOP: the two service builds differ (${digest} vs ${digest_b}); the image is not reproducible"; exit 1; } +grep -aqF "infer: resident open" "${image}" || { echo "STOP: the image carries no resident inference session"; exit 1; } +grep -aqF "infer_source_mode: boot-disk model" "${image}" || { echo "STOP: the image has no boot-disk model source"; exit 1; } +grep -aqF "lifecycle: ready" "${image}" || { echo "STOP: the image carries no resident lifecycle"; exit 1; } +for m in "fw_cfg" "opt/aienos/model" "TEST-ONLY" "TEST Store" "TEST machine id" "AIENCONT"; do + if grep -aqF "${m}" "${image}"; then echo "STOP: the image carries a QEMU or TEST marker (${m})"; exit 1; fi +done +echo "image sha256: ${digest} (build A and build B equal; resident session, boot-disk model only, no fw_cfg or TEST marker)" +echo "lib sha256: $(sha "${lib}")" + +# ---- 3. MODEL.MAP (image mode: in a temporary folder, exact in both modes) ---- +map="${tmp}/MODEL.MAP" +if [[ -n "${target_img}" ]]; then + map_args=() + IFS=, read -ra exts <<<"${extents}" + for e in "${exts[@]}"; do map_args+=(--extent "${e}"); done + "${map_tool}" make "${map}" --file "${model}" --disk "${target_img}" "${map_args[@]}" >/dev/null + "${map_tool}" check "${map}" --disk "${target_img}" >/dev/null \ + || { echo "STOP: MODEL.MAP check failed against ${target_img} (the extents do not hold the model)"; exit 1; } + "${map_tool}" show "${map}" | grep -q "${pinned_sha}" \ + || { echo "STOP: MODEL.MAP does not declare the pinned model hash ${pinned_sha}"; exit 1; } + echo "model map: extents ${extents} checked against ${target_img} (read back, sha256 = pinned ${pinned_sha:0:16}...)" +else + run sudo chattr +i "${model}" + if [[ "${mode}" == apply ]]; then + run sudo "${map_tool}" make "${map}" --file "${model}" --disk "${disk}" --fiemap --part-start auto + run sudo chown "$(id -u):$(id -g)" "${map}" + run sudo "${map_tool}" check "${map}" --disk "${disk}" + "${map_tool}" show "${map}" | grep -q "${pinned_sha}" \ + || { echo "STOP: MODEL.MAP does not declare the pinned model hash ${pinned_sha}"; exit 1; } + else + echo "+ sudo ${map_tool} make MODEL.MAP --file ${model} --disk ${disk} --fiemap --part-start auto" + echo "+ sudo ${map_tool} check MODEL.MAP --disk ${disk} (STOP unless it declares ${pinned_sha})" + fi +fi + +# ---- 4. pre-boot capture (machine only; BootNext still absent) ---- +if [[ -z "${target_img}" ]]; then + run mkdir -p "${evidence_dir}" + run sudo scripts/verify_native_rollback.sh --capture-pre "${evidence_dir}/pre_boot_capture.json" +fi + +# ---- 5. the record and the ESP writes ---- +record="${tmp}/STAGED-CK-SERVICE.TXT" +map_digest="$([[ -f "${map}" ]] && sha "${map}" || echo "at --apply (needs a raw read of ${disk})")" +cat >"${record}" <<EOF +aienos_commit: ${commit} +image: C kernel production service image with resident CPU inference (make full CK_SERVICE=1 CK_HARDWARE_STAGING=1 CK_INFER_LIB=..), CK_FB_HOLD_S=${hold_s} +image_sha256: ${digest} +image_sha256_build_b: ${digest_b} +infer_lib_sha256: $(sha "${lib}") +model: ${model} +model_sha256_pinned: ${pinned_sha} +model_map_sha256: ${map_digest} +owner_pubkeys_sha256: $(sha "${owner_pubkeys}") +machine_id_sha256: $(sha "${machine_id}") +target: ${target_img:-${disk} (ESP ${esp})} +staged_by: ${AIEN_AGENT_ID:-${USER:-unknown}} +staged_at_utc: ${stamp} +boot_current_before: ${current_before:-n/a (image)} +boot_order_before: ${order_before:-n/a (image)} +EOF +echo +echo "writes (--apply performs them in this order; --dry-run performs none):" +if [[ -n "${target_img}" ]]; then + mt="${target_img}@@${esp_off}" + echo "mkdir ESP:/EFI/AIENOS and ESP:/EFI/BOOT in ${target_img} (when absent)" + announce "ESP:/EFI/AIENOS/aienos-ck-service.efi" "${image}" + announce "ESP:/EFI/AIENOS/MODEL.MAP" "${map}" + announce "ESP:/EFI/AIENOS/STAGED-CK-SERVICE.TXT" "${record}" + announce "ESP:/EFI/BOOT/BOOTAA64.EFI" "${image}" + if [[ "${mode}" == apply ]]; then + mdir -i "${mt}" ::/EFI >/dev/null 2>&1 || mmd -i "${mt}" ::/EFI + mdir -i "${mt}" ::/EFI/AIENOS >/dev/null 2>&1 || mmd -i "${mt}" ::/EFI/AIENOS + mdir -i "${mt}" ::/EFI/BOOT >/dev/null 2>&1 || mmd -i "${mt}" ::/EFI/BOOT + mcopy -o -i "${mt}" "${image}" ::/EFI/AIENOS/aienos-ck-service.efi + mcopy -o -i "${mt}" "${map}" ::/EFI/AIENOS/MODEL.MAP + mcopy -o -i "${mt}" "${record}" ::/EFI/AIENOS/STAGED-CK-SERVICE.TXT + mcopy -o -i "${mt}" "${image}" ::/EFI/BOOT/BOOTAA64.EFI + # Read back: every staged file equals what was announced. + for p in "EFI/AIENOS/aienos-ck-service.efi:${image}" "EFI/AIENOS/MODEL.MAP:${map}" \ + "EFI/AIENOS/STAGED-CK-SERVICE.TXT:${record}" "EFI/BOOT/BOOTAA64.EFI:${image}"; do + mcopy -n -i "${mt}" "::/${p%%:*}" "${tmp}/readback" + cmp -s "${tmp}/readback" "${p#*:}" || { echo "STOP: ${p%%:*} read back differs"; exit 1; } + rm -f "${tmp}/readback" + done + echo "staged: 4 files written to the ESP of ${target_img} and read back equal" + fi +else + announce "${esp}/EFI/AIENOS/aienos-ck-service.efi" "${image}" + if [[ -f "${map}" ]]; then announce "${esp}/EFI/AIENOS/MODEL.MAP" "${map}" + else echo "write ${esp}/EFI/AIENOS/MODEL.MAP bytes=4096 sha256=(at --apply: needs a raw read of ${disk})"; fi + announce "${esp}/EFI/AIENOS/STAGED-CK-SERVICE.TXT" "${record}" + echo "write ${evidence_dir}/STAGED-CK-SERVICE.TXT (the same record)" + echo "write NVRAM Boot#### '${label}' -> ${loader} (create-only, not in BootOrder) and BootNext once" + if [[ "${mode}" == apply ]]; then + cp "${record}" "${evidence_dir}/STAGED-CK-SERVICE.TXT" + run sudo install -D -m 0644 "${image}" "${esp}/EFI/AIENOS/aienos-ck-service.efi" + run sudo install -D -m 0644 "${map}" "${esp}/EFI/AIENOS/MODEL.MAP" + fi + # ---- 6. one-time boot entry ---- + entry="${existing}" + if [[ -z "${entry}" ]]; then + run sudo efibootmgr --quiet --create-only --disk "${disk}" --part "${esp_part:-<esp partition>}" \ + --label "${label}" --loader "${loader}" + if [[ "${mode}" == apply ]]; then + entry="$(efibootmgr | sed -n "s/^Boot\([0-9A-F]\{4\}\)\*\{0,1\} ${label}.*/\1/p" | head -1)" + [[ -n "${entry}" ]] || { echo "STOP: the boot entry was not created"; exit 1; } + fi + fi + entry="${entry:-NNNN}" + [[ "${entry}" != "${recov_entry}" ]] || { echo "STOP: the new entry took the recovery entry's number"; exit 1; } + if [[ "${mode}" == apply ]]; then + order_after="$(efibootmgr | sed -n 's/^BootOrder: //p')" + if [[ "${order_after}" != "${order_before}" ]]; then + run sudo efibootmgr --quiet --bootorder "${order_before}" + fi + efibootmgr | grep -qE "^Boot${recov_entry}\*? .*${recov_label}" \ + || { echo "STOP: Boot${recov_entry} ${recov_label} is gone; BootNext NOT set"; exit 1; } + echo "aienos_boot_entry: ${entry}" >>"${evidence_dir}/STAGED-CK-SERVICE.TXT" + else + echo "+ (only if BootOrder changed: sudo efibootmgr --quiet --bootorder ${order_before})" + echo "+ (check Boot${recov_entry} ${recov_label} still present, else stop before BootNext)" + fi + run sudo install -m 0644 "${evidence_dir}/STAGED-CK-SERVICE.TXT" "${esp}/EFI/AIENOS/STAGED-CK-SERVICE.TXT" + run sudo efibootmgr --quiet --bootnext "${entry}" +fi + +echo +if [[ "${mode}" == dry ]]; then + echo "Dry run: nothing touched. Pre-flight clean; --apply would perform the writes above." + exit 0 +fi +if [[ -n "${target_img}" ]]; then + echo "Staged image ${target_img}: boot it with the ESP's removable path; nothing else was touched." + exit 0 +fi +cat "${evidence_dir}/STAGED-CK-SERVICE.TXT" +efibootmgr | sed -n '1,4p' +echo "Staged: the next boot runs Boot${entry} once. Nothing was rebooted." +echo "Reboot only with the operator at the machine and the ${recov_label} stick inserted." +echo "After the return to Linux: sudo scripts/verify_native_rollback.sh --capture-post, then sudo chattr -i ${model}."