interplane.Get Omega
Read in your language

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#321 (code only)

closed derived 3376e27c6040ec6d #321

Imported from GitHub aien-dev/aienux#321 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base c30b15e75373d0357956d8b46e81d0b007839d54 · Head efbb562a70e7fdbd49896177743491a55be526a3

Apply it

git checkout -b patch-3376e27c6040ec6d c30b15e75373d0357956d8b46e81d0b007839d54
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/3376e27c6040ec6d.patch | git am

Raw patch (mbox) · 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
321
efbb562a70e7fdbd49896177743491a55be526a3
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":321,"url":"https://github.com/aien-dev/aienux/pull/321","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:12Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index 13b65978..71fd990b 100644
--- a/.crumb
+++ b/.crumb
@@ -27,33 +27,33 @@
           "purpose": "Directory crates. Purpose not yet described by a human."
         },
         {
-          "digest": "b1b6101be716c9f1ca0a55e0ce904127f1ddce05d251e97d00399b049249c96b",
-          "last_commit": "0711ee0",
+          "digest": "401a6f64c1d174a4182fb2cca14aee8ab95ebfc00bda734fde8181b527c80133",
+          "last_commit": "c30b15e",
           "name": "docs",
           "purpose": "Directory docs. Purpose not yet described by a human."
         },
         {
-          "digest": "91bcbb8a7af535f438701fa1a4a8bd630370f1a7da25ad5ded775a3d0969dad6",
-          "last_commit": "0711ee0",
+          "digest": "3fda00326650b0475a0cbf006766429338c7f58c7d115a038985284ce2f343a3",
+          "last_commit": "c30b15e",
           "name": "native",
           "purpose": "Directory native. Purpose not yet described by a human."
         },
         {
           "digest": "348804e26984e873db9914d2a3ebfcf6c9ea02619247d78809999011b354e048",
-          "last_commit": "eb70ba8",
+          "last_commit": "4448a50",
           "name": "scripts",
           "purpose": "Directory scripts. Purpose not yet described by a human."
         }
       ],
-      "children_root": "sha256:2702b75a866f8718154bfee4fdb0dd15f7cd894315f845f96423c1da00d7d9d2",
-      "compiled_at": "2026-10-12T13:00:09Z",
+      "children_root": "sha256:64c9e2d4935d3ce7fedfd693883d9953a7032ea6b8c4a05cc4db308770c5a616",
+      "compiled_at": "2026-10-12T14:03:50Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:a5226d112dfbcf74ab90d1fbb2772b7090bf440c2e852f97a1f356ae7e21b4fa",
+      "digest": "sha256:8d930d9060ffd03e76b1169521c56449861d51deaf44c6c6727d24a74b341d80",
       "evidence_files": 155,
       "evidence_root": "sha256:d59c0cef4e7dd5172923754a95b411ca54b01f35baca4587f792f1b259f1eaf7",
-      "files": 3093,
-      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
-      "source_tree": "sha256:7f985394190d56c2cda0bd80c2757b895ebc04d33f94b074d9e0b83daf65610d"
+      "files": 3097,
+      "generated_at_commit": "c30b15e75373d0357956d8b46e81d0b007839d54",
+      "source_tree": "sha256:c5bd2327bbccc565d4d4df76bf1fe045d4f9bce37819c811f0355a3b5370d3c9"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/docs/.crumb b/docs/.crumb
index 5e4df806..21ccb4ce 100644
--- a/docs/.crumb
+++ b/docs/.crumb
@@ -30,14 +30,14 @@
         }
       ],
       "children_root": "sha256:baea130f2c52779b57d90139beb66ac01b21ab499d113471a334be5500f3e369",
-      "compiled_at": "2026-10-12T13:00:09Z",
+      "compiled_at": "2026-10-12T14:03:50Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:b1b6101be716c9f1ca0a55e0ce904127f1ddce05d251e97d00399b049249c96b",
+      "digest": "sha256:401a6f64c1d174a4182fb2cca14aee8ab95ebfc00bda734fde8181b527c80133",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 70,
-      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
-      "source_tree": "sha256:65a766bd092243b4518fe62af668ea51375b08cf80513f0c33e330ececf086ca"
+      "files": 71,
+      "generated_at_commit": "c30b15e75373d0357956d8b46e81d0b007839d54",
+      "source_tree": "sha256:b0f13339a715fe94c4aac08937710e74ead7d5130fca62e0da58f266a3732ac0"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/docs/NATIVE_IMAGE_SLOTS.md b/docs/NATIVE_IMAGE_SLOTS.md
new file mode 100644
index 00000000..ba72d4e1
--- /dev/null
+++ b/docs/NATIVE_IMAGE_SLOTS.md
@@ -0,0 +1,190 @@
+# Native image slots: install, update and recovery without Linux (P11 cut 1)
+
+STATUS: PROPOSED (design note plus host tooling; no loader or kernel image
+code changed in this cut; nothing here has run on hardware).
+SECURITY_IMPACT: PERSISTENT_FORMAT + RECOVERY (a new on-disk format and a new
+recovery rule are specified; neither is written to any machine by this cut).
+
+Program: AIEN native v1 (aien-architecture CURRENT_EXECUTION_PLAN, addendum
+2026-10-12), work package P11, gate N7: "Install, update and recovery work
+with no Linux installation or recovery USB required for the supported
+procedure. A BootNext return to Linux is insufficient." Today's rollback is
+the one-time BootNext return to Linux (aienos#273), which N7 rejects.
+
+## 1. The finding P11 was asked to make
+
+The P01 addendum left one question to P11: is an A/B loader "the cheapest way
+to hold two native images"? Answer, after reading what the image already does:
+
+**Yes, two slots in their own partition, selected by the stub.** The reasons:
+
+1. The stub already reads raw disk blocks through the firmware's own Block
+   I/O driver before `ExitBootServices` (`native/boot/efi_model.c`: locate
+   the whole disk by GPT disk GUID, `ReadBlocks` in page-aligned pieces).
+   Reading a 4096-byte manifest and an image from a fixed partition offset
+   is the same operation.
+2. The image already carries freestanding SHA-512 and Ed25519 verification
+   (`native/sig`) and SHA-256 (`native/argus/sha256.c`). Verifying a signed
+   manifest costs no new primitive. `slot-free` in the kernel Makefile proves
+   the selection code needs nothing else.
+3. The kernel already writes a partition crash-safely with the torn-slot
+   region (`native/store/torn_slot.c`): two bodies, two commit headers, the
+   newest valid wins, a torn write can only lose the write in flight. The
+   control record that says "which slot is active, which is the candidate,
+   how many tries remain" fits in one such region.
+4. UEFI gives the stub `LoadImage(SourceBuffer)` and `StartImage` (boot
+   services table, `native/boot/efi.h`). A verified slot image can be
+   started from memory with no filesystem, no second boot entry and no
+   firmware variable write. The loader's own PE stays the single BootOrder
+   entry; the images it chooses between live in the slots partition.
+
+What this costs: one new partition, one new loader step (read control, read
+and verify two manifests, pick, chain-load) and the updater on the kernel
+side. What it does not cost: any Linux tool at install, update or recovery
+time, any `BootNext` write, any change to the stub's frozen PE layout.
+
+What it does **not** solve on its own (stated so nobody reads more into it):
+if both slots are invalid, or both are below the security floor, the loader
+can only report `recovery_required` and return to the firmware. Covering that
+case without a Linux USB is the known-good AIENOS recovery image of P11
+(a third, read-only copy of the loader plus a slot image on recovery media
+built by our own tools), which is a later cut. Dual-invalid cannot happen by
+update alone under the rules below (the active slot is never written while
+it is active), only by media failure or a deliberate wipe.
+
+## 2. Decision needed from the owner (Drake)
+
+The loader is frozen: `docs/BOOT_HANDOFF_CONTRACT.md` section 7 says "There
+are no slots and, per Q3, none will be added to this loader", and
+`native/boot/README.md` parks "signature checks, BootNext staging, rollback".
+Those statements stay true after this cut. Changing them is an owner decision
+(ADR 0024 Q3; TRUST-1 Q14 "Loader changes rarely"). This note asks for that
+decision with the design pinned, so the decision is about a concrete thing.
+
+If the owner says yes, cut 2 adds one bounded step to the stub (section 6).
+If the owner says no, the format and tool remain host-side specification and
+N7 needs another path, which this note does not have.
+
+## 3. Sources this design follows
+
+- ADR 0006 (accepted 2026-09-23): "System updates employ transactional A/B
+  slot switching with deterministic kernel health milestone verification";
+  "atomic and safely reversible via hardware-backed A/B slots".
+- TRUST-1 implementation plan, cross-cutting Q14 (loader minimality: "only
+  what may boot, which slot, and what verified facts the kernel receives")
+  and Q19 (slot/manifest: "A=known-good, B=candidate (roles, not names).
+  Manifest minimum: format version, generation, kernel digest, image digest,
+  loader ABI, kernel ABI, signer, commit, provenance, rollback compat, policy
+  generation, timestamp, signature. Health gates before promotion receipt;
+  explicit authenticated promotion"). Every Q19 field is in section 4.
+- `docs/NATIVE_BOOT_ROLLBACK_CONTRACT.md` section 2: "A candidate may consume
+  exactly one boot attempt. It may never promote itself into the persistent
+  default boot path." Kept in a stronger form: a candidate gets a bounded
+  number of attempts (3), each one consumed by the loader before the
+  candidate runs, and promotion is a separate authenticated step by the
+  kernel after health, never by the candidate's own boot.
+- Owner public key format: `tools/ck_owner_gen.c` (`owner_root_ed25519
+  <64 hex>`), the same file the trust path already uses. TEST keys (RFC 8032
+  TEST 1/2/3) are refused for hardware exactly as there.
+
+## 4. On-disk format (native/boot/slot_format.h is normative)
+
+Partition: its own GPT partition, type GUID
+`8B1096CD-7928-4E08-B5E4-C19B6B532760` (new; the existing AIENOS store
+partition `38DAAC89-...` is not touched and keeps its one-partition rule).
+Layout in 4096-byte units, U = partition size in units:
+
+| Units | Content |
+|---|---|
+| 0..3 | control region: a torn-slot region holding the control record |
+| 4 .. 4+CAP-1 | slot A: manifest in the first unit, image from the second |
+| 4+CAP .. 4+2*CAP-1 | slot B: same |
+
+CAP = (U - 4) / 2; an image may be at most (CAP - 1) * 4096 bytes. Current
+images are 155648 (core) and 352256 (full) bytes; a 64 MiB partition holds
+two images 500 times larger than today's.
+
+Manifest, 4096 bytes, little-endian, the first 448 bytes signed:
+magic `AIENSLT1`, version 1, payload kind 1 (one PE, `BOOTAA64`-style image:
+kernel digest equals image digest), loader ABI 1, kernel ABI 3 (the current
+handoff ABI), generation (strictly increasing per release), policy
+generation (<= generation; promotion raises the floor to it), minimum
+rollback generation (<= generation; documentation of compatibility),
+image length, image SHA-512, kernel SHA-512, signer id (SHA-256 of the
+signing public key), commit (40 lower-case hex), provenance (64 printable
+ASCII, zero padded), timestamp, flags 0, reserved 0, Ed25519 signature,
+zero pad to 4096.
+
+Control record, 4096 bytes: magic `AIENSLC1`, version 1, active slot,
+candidate slot (or none), tries remaining (<= 3), flags (bit 0: last
+candidate failed), generation floor, last good generation, reserved 0.
+It is committed through the torn-slot region (`ts_commit`) so a power cut
+during the write leaves the previous record.
+
+## 5. Rules (native/boot/slot_select.c is normative; its self-test is the oracle)
+
+A slot is **usable** when its manifest is structurally valid, signed by a
+trusted owner key, its image bytes match the digest, and its generation is
+at or above the control record's floor.
+
+Selection at every boot, with the control record C read from the region:
+
+1. No valid C (blank media, corrupt): boot the usable slot with the highest
+   generation (A on a tie); write nothing. Nothing usable: recovery required.
+2. C names a candidate with tries remaining and the candidate is usable:
+   commit C with tries - 1 **before** starting it, then boot the candidate.
+   Three failed boots in a row (power cut, panic, hang and reset) therefore
+   end with tries 0 and the next boot falls through to rule 3. No boot loop.
+3. Candidate exhausted or unusable: boot the active slot if usable, write
+   nothing. The kernel sees the exhausted candidate in C and abandons it.
+   An exhausted candidate never boots on its own authority.
+4. Active unusable and the other slot usable and not the candidate: boot the
+   other slot (fallback to the last promoted image). Otherwise: recovery
+   required, loader returns to the firmware.
+
+Transitions (kernel side, after the owner-authorized update is written):
+
+- **stage**: refuses the active slot, a generation below the floor, or not
+  above the last good generation; sets tries 3, clears the failed flag.
+- **promote**: only the staged candidate, only after the booted kernel passed
+  its health milestone; flips active, clears candidate, sets last good, and
+  raises the floor to the manifest's policy generation. The floor never goes
+  down (monotonic security floor; TRUST-1 "reconcile rollback policy with
+  monotonic security floors").
+- **abandon**: clears the candidate and sets the failed flag; the active
+  slot keeps booting.
+
+Authorized rollback: promote the known-good image again with a higher
+generation (a re-signed manifest). Unauthorized rollback (an old image below
+the floor) is unusable by definition; the owner key is needed to lower
+nothing and to re-release anything.
+
+## 6. Cuts
+
+1. **This cut (host only).** Format, rules, host tool `ck_slot_tool`
+   (`make -C native/kernel slot-test`: 94 checks covering layout, key
+   derivation, 26 manifest mutations each refused with its named reason,
+   10 control mutations, 16 selection scenarios including the bounded tries
+   and the floor, the transitions, and torn-slot commit/recover with a
+   simulated torn write) and the freestanding proof (`slot-free`). The
+   signing path is offline: `ck_slot_tool tbs` emits the 448 signed bytes,
+   the owner signs them on the air-gapped machine with OpenSSL
+   (`pkeyutl -sign -rawin`), `attach-sig` verifies and attaches. No private
+   key ever touches the Spark. The TEST signer exists for tests only.
+2. **Stub reads a slot (after the owner's yes).** The stub locates the
+   slots partition on the boot disk, reads C, reads both manifests and
+   images, calls `ck_slot_select`, commits the try if asked, and chain-loads
+   the chosen image with `LoadImage(SourceBuffer)` + `StartImage`. A QEMU
+   gate proves: fresh media boots A; a staged B boots and, after three forced
+   failures, A boots again with B abandoned; a corrupt manifest is refused;
+   a wrong key is refused; a torn control write keeps the old record.
+3. **Kernel updater.** Writes the inactive slot over the kernel's own NVMe
+   path, verifies by reading back, stages through the torn-slot region, and
+   promotes after its health milestone. Qualifies interrupted updates,
+   tampered images, failed candidates and authorized rollback (the P11 list).
+4. **Known-good recovery image.** The same loader plus a slot image on
+   recovery media built by our tools, for the dual-invalid case. Then N7 is
+   run on the physical candidate inside an attended window.
+
+Until cut 2 is approved and merged, the boot path is unchanged and the
+statements in BOOT_HANDOFF_CONTRACT section 7 and native/boot/README.md hold.
diff --git a/native/.crumb b/native/.crumb
index 8889fd35..225d6ad1 100644
--- a/native/.crumb
+++ b/native/.crumb
@@ -55,7 +55,7 @@
           "purpose": "Directory native/argus. Purpose not yet described by a human."
         },
         {
-          "digest": "294aa4136755e9ed1d27df47ace2ad8acdd0377cfdfc5cccf04a5cca971ee5aa",
+          "digest": "c1bc8c4dbdd87843adfef62a310e31290b17c16d6251212eca6be9ea6fe1963d",
           "last_commit": "61bd76a",
           "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": "6845f46fb7d05df8d980e8290908700361869cb5a11eae224f299bf9bf5ddae0",
-          "last_commit": "0711ee0",
+          "digest": "1cae2705c9a51ed917f8ba4eb048c36e92ab884988421a026182d852ed89086e",
+          "last_commit": "c30b15e",
           "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:cb1dc6e50f50ec3a95b7e336c04afa1c67fdb52c3f2eae9a882304b03451f6f5",
-      "compiled_at": "2026-10-12T13:00:09Z",
+      "children_root": "sha256:cb14ac2d1ad86ace9b3107909d67e297ea1bf65c482a293dab790aa36332e481",
+      "compiled_at": "2026-10-12T14:03:50Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:91bcbb8a7af535f438701fa1a4a8bd630370f1a7da25ad5ded775a3d0969dad6",
+      "digest": "sha256:3fda00326650b0475a0cbf006766429338c7f58c7d115a038985284ce2f343a3",
       "evidence_files": 4,
       "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335",
-      "files": 474,
-      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
-      "source_tree": "sha256:3c108d93554900341eb25a72ac24448a11be14c341d71a32e329d40500b5eb31"
+      "files": 477,
+      "generated_at_commit": "c30b15e75373d0357956d8b46e81d0b007839d54",
+      "source_tree": "sha256:38678f63ce625a35b1ac0aeb94116d8d9d2491fcf633e5d65e1d057eb77bf754"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/native/boot/.crumb b/native/boot/.crumb
index 33e400cd..7115a2af 100644
--- a/native/boot/.crumb
+++ b/native/boot/.crumb
@@ -7,14 +7,14 @@
     "generated": {
       "children": [],
       "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "compiled_at": "2026-10-06T19:08:10Z",
+      "compiled_at": "2026-10-12T14:03:50Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:294aa4136755e9ed1d27df47ace2ad8acdd0377cfdfc5cccf04a5cca971ee5aa",
+      "digest": "sha256:c1bc8c4dbdd87843adfef62a310e31290b17c16d6251212eca6be9ea6fe1963d",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 9,
-      "generated_at_commit": "f23da6872ed8576de162878d89c4eaaa3e065099",
-      "source_tree": "sha256:97c9197c69b874543d76aff385197907cbc3e416c67379b9b31d6af379c0b82c"
+      "files": 11,
+      "generated_at_commit": "c30b15e75373d0357956d8b46e81d0b007839d54",
+      "source_tree": "sha256:f3578698cc2ea2cfe3c01795d86954d83dc8f540fc1b40aa57225d631c17b686"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/native/boot/README.md b/native/boot/README.md
index 14827db3..2ebd9179 100644
--- a/native/boot/README.md
+++ b/native/boot/README.md
@@ -15,6 +15,13 @@ This is the C path's UEFI entry (Lane 18). It is deliberately small:
   `ck_kernel_entry` with a `struct ck_handoff` (`handoff.h`): memory-map
   copy, RSDP, firmware EL, firmware TTBR0/SCTLR, counter, commit.
 
+**Proposed, not wired (P11 cut 1, gate N7):** `slot_format.h` and
+`slot_select.c` pin an A/B image-slot format and the loader's selection rules
+(bounded candidate tries, generation floor, never a boot loop), checked by
+`make -C native/kernel slot-test slot-free`. The stub does not read them yet;
+whether it ever does is the owner's call recorded in
+`docs/NATIVE_IMAGE_SLOTS.md` section 2. The paragraph below stays true.
+
 **Parked, not here:** signature checks, BootNext staging, rollback and the
 boot-report file. The Rust `aienos-boot` crate has BootNext staging and a QEMU
 rollback test but no A/B slot selection (ADR 0024 Q3); it is frozen and
diff --git a/native/boot/slot_format.h b/native/boot/slot_format.h
new file mode 100644
index 00000000..6843a1a8
--- /dev/null
+++ b/native/boot/slot_format.h
@@ -0,0 +1,180 @@
+/* slot_format.h -- AIENOS native image slots: the on-disk formats a loader
+ * reads to choose which native image boots, and a kernel writes to install,
+ * update and roll back WITHOUT Linux (native v1 plan P11, gate N7).
+ *
+ * STATUS: PROPOSED format (docs/NATIVE_IMAGE_SLOTS.md). Nothing writes it yet
+ * and no image reads it: native/boot/efi_main.c is unchanged (loader
+ * expansion is frozen, BOOT_HANDOFF_CONTRACT.md; the owner decides whether
+ * the loader grows slot selection). This header, slot_select.c and the host
+ * tool native/kernel/tools/ck_slot_tool.c pin the format and the decision
+ * rules so they can be reviewed and mutation-tested before any loader change.
+ *
+ * Accepted design this follows: ADR 0006 (transactional A/B slots, health
+ * milestones before promotion) and TRUST-1 Q19 (A = known-good, B =
+ * candidate as ROLES; manifest fields; "write inactive, verify, boot once,
+ * health, promote, retain rollback; bounded attempts, no boot loop, last-good
+ * never erased by a candidate; dual-invalid = recovery").
+ *
+ * Where it lives: its own GPT partition with the type GUID below, NOT inside
+ * the AIENOS Store partition (dev/disk_layout.h is untouched). In 4096-byte
+ * units from the partition's first LBA:
+ *
+ *   unit 0..3        control record, torn-write safe (native/store/torn_slot.c
+ *                    protocol: body A, commit A, body B, commit B)
+ *   unit 4 ..        slot A: manifest unit, then the image bytes
+ *   unit 4+CAP ..    slot B: manifest unit, then the image bytes
+ *   CAP = (U - 4) / 2 units, U = whole units in the partition. The image of
+ *   a slot occupies at most (CAP - 1) * 4096 bytes. Equal halves, so the
+ *   loader needs no stored geometry: the partition size is the geometry.
+ *
+ * All integers little endian. Reserved bytes are zero and are checked.
+ *
+ * The MANIFEST (one unit) is signed by the Owner Root Ed25519 key (TRUST-1
+ * Q13; file format tools/ck_owner_gen.c "owner_root_ed25519 <64 hex>"): the
+ * first CK_SLOT_TBS_BYTES bytes are the signed message. The signature covers
+ * the image through image_sha512; the loader recomputes SHA-512 over exactly
+ * image_len bytes of the slot. The kernel is linked into the image
+ * (payload_kind 1 = the BOOTAA64.EFI PE built by native/kernel), so
+ * kernel_sha512 MUST equal image_sha512 in v1; the field exists so a future
+ * split payload keeps the layout.
+ *
+ * The CONTROL record (one unit, inside the torn-slot region) is NOT signed:
+ * it is operational state written by the kernel (stage, promote, abandon) and
+ * by the loader for exactly one purpose, decrementing a candidate's remaining
+ * tries before it boots that candidate, which is what bounds boot attempts
+ * even if the candidate hangs. Its integrity comes from the torn-slot commit
+ * digests. A missing or corrupt control record never blocks booting a valid
+ * image: the loader then boots the highest valid generation.
+ *
+ * generation_floor is the monotonic security floor (P11: "reconcile rollback
+ * policy with monotonic security floors"): a manifest whose generation is
+ * below the floor is never booted, even if validly signed. Promotion raises
+ * the floor to the promoted image's policy_generation; it never lowers it. */
+#ifndef AIENOS_CK_SLOT_FORMAT_H
+#define AIENOS_CK_SLOT_FORMAT_H
+#include <stdint.h>
+#include <stddef.h>
+
+#define CK_SLOT_UNIT 4096u
+#define CK_SLOT_CONTROL_UNITS 4u          /* torn-slot region (TS_UNITS) */
+#define CK_SLOT_FIRST_UNIT 4u             /* slot A starts here */
+#define CK_SLOT_COUNT 2u
+#define CK_SLOT_NONE 0xFFu
+#define CK_SLOT_MAX_TRIES 3u              /* bounded candidate boot attempts */
+#define CK_SLOT_MIN_CAP_UNITS 2u          /* manifest + at least one image unit */
+
+/* 8B1096CD-7928-4E08-B5E4-C19B6B532760: AIENOS image slots partition type. */
+#define CK_SLOT_PART_TYPE_TEXT "8B1096CD-7928-4E08-B5E4-C19B6B532760"
+#define CK_SLOT_PART_TYPE_BYTES \
+    {0xcd, 0x96, 0x10, 0x8b, 0x28, 0x79, 0x08, 0x4e, 0xb5, 0xe4, 0xc1, 0x9b, 0x6b, 0x53, 0x27, 0x60}
+
+/* ---- manifest ------------------------------------------------------------ */
+#define CK_SLOT_MANIFEST_MAGIC "AIENSLT1"
+#define CK_SLOT_MANIFEST_VERSION 1u
+#define CK_SLOT_PAYLOAD_BOOTAA64 1u       /* stub + kernel in one PE image */
+#define CK_SLOT_LOADER_ABI 1u
+#define CK_SLOT_KERNEL_ABI 3u             /* CHANDOF3, BOOT_HANDOFF_CONTRACT.md */
+#define CK_SLOT_TBS_BYTES 448u            /* signed message = bytes [0, 448) */
+#define CK_SLOT_SIG_OFFSET 448u
+#define CK_SLOT_COMMIT_CHARS 40u
+#define CK_SLOT_PROVENANCE_CHARS 64u
+
+struct ck_slot_manifest {
+    uint8_t magic[8];                 /*   0 "AIENSLT1" */
+    uint32_t version;                 /*   8 1 */
+    uint32_t payload_kind;            /*  12 1 */
+    uint32_t loader_abi;              /*  16 1 */
+    uint32_t kernel_abi;              /*  20 3 */
+    uint64_t generation;              /*  24 strictly increasing per release */
+    uint64_t policy_generation;       /*  32 floor this image raises on promotion (<= generation) */
+    uint64_t min_rollback_generation; /*  40 oldest generation this image may be rolled back to (<= generation) */
+    uint64_t image_len;               /*  48 bytes of the image, > 0 */
+    uint8_t image_sha512[64];         /*  56 */
+    uint8_t kernel_sha512[64];        /* 120 == image_sha512 for payload_kind 1 */
+    uint8_t signer_id[32];            /* 184 SHA-256 of the signer's Ed25519 public key */
+    uint8_t commit[40];               /* 216 lower-case hex of the source commit, no terminator */
+    uint8_t provenance[64];           /* 256 printable ASCII, zero padded */
+    uint64_t timestamp;               /* 320 unix seconds, > 0 */
+    uint32_t flags;                   /* 328 0 */
+    uint32_t reserved0;               /* 332 0 */
+    uint8_t reserved1[112];           /* 336 zero */
+    uint8_t signature[64];            /* 448 Ed25519 over bytes [0, 448) */
+    uint8_t pad[CK_SLOT_UNIT - 512u]; /* 512 zero */
+};
+_Static_assert(sizeof(struct ck_slot_manifest) == CK_SLOT_UNIT, "ck_slot_manifest size");
+_Static_assert(offsetof(struct ck_slot_manifest, image_sha512) == 56, "manifest image_sha512");
+_Static_assert(offsetof(struct ck_slot_manifest, signer_id) == 184, "manifest signer_id");
+_Static_assert(offsetof(struct ck_slot_manifest, timestamp) == 320, "manifest timestamp");
+_Static_assert(offsetof(struct ck_slot_manifest, signature) == CK_SLOT_SIG_OFFSET, "manifest signature");
+
+/* ---- control record ------------------------------------------------------ */
+#define CK_SLOT_CONTROL_MAGIC "AIENSLC1"
+#define CK_SLOT_CONTROL_VERSION 1u
+#define CK_SLOT_CTL_FLAG_CANDIDATE_FAILED 1u /* the last candidate was abandoned */
+
+struct ck_slot_control {
+    uint8_t magic[8];                /*  0 "AIENSLC1" */
+    uint32_t version;                /*  8 1 */
+    uint8_t active_slot;             /* 12 0 or 1: the known-good slot */
+    uint8_t candidate_slot;          /* 13 0, 1 or CK_SLOT_NONE */
+    uint8_t tries_remaining;         /* 14 0..CK_SLOT_MAX_TRIES; 0 when no candidate */
+    uint8_t flags;                   /* 15 */
+    uint64_t generation_floor;       /* 16 monotonic security floor */
+    uint64_t last_good_generation;   /* 24 generation of the active slot when promoted (0 = unknown) */
+    uint8_t reserved[CK_SLOT_UNIT - 32u]; /* 32 zero */
+};
+_Static_assert(sizeof(struct ck_slot_control) == CK_SLOT_UNIT, "ck_slot_control size");
+
+/* ---- decisions ----------------------------------------------------------- */
+/* What the verifier learned about one slot (slot_select.c ck_slot_verify). */
+struct ck_slot_eval {
+    int valid;                       /* 1 = manifest well formed, signed by a trusted key, image digest matches */
+    uint64_t generation;             /* from the manifest when valid */
+    uint64_t policy_generation;      /* from the manifest when valid */
+    const char *why;                 /* refusal reason when !valid (static string) */
+};
+
+enum ck_slot_reason {
+    CK_SLOT_R_NONE = 0,
+    CK_SLOT_R_CANDIDATE_TRY,          /* booting the candidate; tries decremented (loader must persist ctl_out first) */
+    CK_SLOT_R_ACTIVE,                 /* booting the active slot */
+    CK_SLOT_R_CANDIDATE_EXHAUSTED,    /* candidate had no tries left: booting active */
+    CK_SLOT_R_CANDIDATE_INVALID,      /* candidate failed verification: booting active */
+    CK_SLOT_R_ACTIVE_INVALID_FALLBACK,/* active failed verification: booting the other valid slot */
+    CK_SLOT_R_NO_CONTROL,             /* no usable control record: booting the highest valid generation */
+    CK_SLOT_R_RECOVERY_REQUIRED,      /* no slot may boot */
+};
+
+struct ck_slot_decision {
+    int boot_slot;                    /* 0, 1 or -1 (recovery required) */
+    enum ck_slot_reason reason;
+    int loader_write;                 /* 1 = ctl_out must be committed before booting boot_slot */
+    struct ck_slot_control ctl_out;   /* valid when loader_write */
+};
+
+/* Structural checks, no I/O, no crypto. 0 = well formed, -1 with *why. */
+int ck_slot_manifest_check(const struct ck_slot_manifest *m, const char **why);
+int ck_slot_control_check(const struct ck_slot_control *c, const char **why);
+
+/* Full verification of one slot: structure, image_len <= image_cap, SHA-512
+ * of the image bytes, signer_id names one of nkeys trusted public keys and
+ * the signature verifies under it. Fills *ev. Returns ev->valid. */
+int ck_slot_verify(const struct ck_slot_manifest *m, const uint8_t *image, uint64_t image_cap,
+                   const uint8_t (*keys)[32], unsigned nkeys, struct ck_slot_eval *ev);
+
+/* The loader's decision. ctl may be NULL (missing or corrupt control record). */
+void ck_slot_select(const struct ck_slot_control *ctl, const struct ck_slot_eval ev[CK_SLOT_COUNT],
+                    struct ck_slot_decision *d);
+
+/* Kernel-side transitions on a control record (pure; the caller commits).
+ * 0 = ok, -1 refused with *why. */
+void ck_slot_control_init(struct ck_slot_control *c, unsigned active_slot);
+int ck_slot_stage_candidate(struct ck_slot_control *c, unsigned slot, uint64_t generation, const char **why);
+int ck_slot_promote(struct ck_slot_control *c, unsigned booted_slot, uint64_t generation,
+                    uint64_t policy_generation, const char **why);
+int ck_slot_abandon_candidate(struct ck_slot_control *c, const char **why);
+
+/* Text for a reason code (static string). */
+const char *ck_slot_reason_text(enum ck_slot_reason r);
+
+#endif /* AIENOS_CK_SLOT_FORMAT_H */
diff --git a/native/boot/slot_select.c b/native/boot/slot_select.c
new file mode 100644
index 00000000..c7495a2b
--- /dev/null
+++ b/native/boot/slot_select.c
@@ -0,0 +1,360 @@
+/* slot_select.c -- AIENOS native image slots: structural checks, slot
+ * verification and the loader's / kernel's decision rules (slot_format.h).
+ *
+ * Freestanding C: no libc, no allocation, no I/O. The only outside symbols
+ * are native/sig (aienos_sha512, aienos_ed25519_verify) and
+ * native/argus/sha256.c (sha256_hash). The same object is meant for the UEFI
+ * stub, the kernel and the hosted tool (native/kernel/tools/ck_slot_tool.c),
+ * so the decision a test sees is the decision a loader would take.
+ *
+ * Rules (TRUST-1 Q19, ADR 0006), in the order ck_slot_select applies them:
+ *   usable(s)  = ev[s].valid && ev[s].generation >= floor
+ *   1. no control record: boot the highest usable generation (A on a tie);
+ *      none usable -> recovery required. Nothing is written.
+ *   2. a candidate is set, has tries left and is usable: boot it and hand
+ *      back the control record with tries - 1 for the loader to COMMIT
+ *      BEFORE jumping (that is what bounds attempts when the candidate hangs).
+ *   3. a candidate is set but has no tries left, or is not usable: boot the
+ *      active slot if usable (the candidate is abandoned by the kernel later;
+ *      the loader writes nothing here, so a wedged kernel cannot loop).
+ *   4. active usable: boot it.
+ *   5. active not usable, the other slot usable: boot the other slot
+ *      ("last-good never erased": media damage to one slot does not strand
+ *      the machine).
+ *   6. otherwise recovery required: the loader must not boot either slot.
+ * The floor never lowers: ck_slot_promote raises it to the promoted image's
+ * policy_generation. A validly signed image below the floor never boots. */
+#include "slot_format.h"
+#include "../sig/aienos_sig.h"
+#include "../argus/sha256.h"
+
+static int eq_bytes(const uint8_t *a, const uint8_t *b, size_t n)
+{
+    uint8_t d = 0;
+    for (size_t i = 0; i < n; i++)
+        d |= (uint8_t)(a[i] ^ b[i]);
+    return d == 0;
+}
+
+static int all_zero(const uint8_t *p, size_t n)
+{
+    uint8_t d = 0;
+    for (size_t i = 0; i < n; i++)
+        d |= p[i];
+    return d == 0;
+}
+
+static void copy_bytes(uint8_t *dst, const uint8_t *src, size_t n)
+{
+    for (size_t i = 0; i < n; i++)
+        dst[i] = src[i];
+}
+
+static int is_lower_hex(uint8_t c)
+{
+    return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
+}
+
+int ck_slot_manifest_check(const struct ck_slot_manifest *m, const char **why)
+{
+    static const uint8_t magic[8] = CK_SLOT_MANIFEST_MAGIC;
+    const char *w = 0;
+    if (!m)
+        w = "null manifest";
+    else if (!eq_bytes(m->magic, magic, 8))
+        w = "bad magic";
+    else if (m->version != CK_SLOT_MANIFEST_VERSION)
+        w = "unsupported manifest version";
+    else if (m->payload_kind != CK_SLOT_PAYLOAD_BOOTAA64)
+        w = "unsupported payload kind";
+    else if (m->loader_abi != CK_SLOT_LOADER_ABI)
+        w = "loader ABI mismatch";
+    else if (m->kernel_abi != CK_SLOT_KERNEL_ABI)
+        w = "kernel ABI mismatch";
+    else if (m->generation == 0)
+        w = "generation is zero";
+    else if (m->policy_generation > m->generation)
+        w = "policy_generation above generation";
+    else if (m->min_rollback_generation > m->generation)
+        w = "min_rollback_generation above generation";
+    else if (m->image_len == 0)
+        w = "image_len is zero";
+    else if (!eq_bytes(m->kernel_sha512, m->image_sha512, 64))
+        w = "kernel_sha512 differs from image_sha512 (payload kind 1)";
+    else if (m->timestamp == 0)
+        w = "timestamp is zero";
+    else if (m->flags != 0)
+        w = "flags nonzero";
+    else if (m->reserved0 != 0 || !all_zero(m->reserved1, sizeof m->reserved1))
+        w = "reserved bytes nonzero";
+    else if (!all_zero(m->pad, sizeof m->pad))
+        w = "pad nonzero";
+    if (!w) {
+        for (unsigned i = 0; i < CK_SLOT_COMMIT_CHARS; i++)
+            if (!is_lower_hex(m->commit[i])) {
+                w = "commit is not 40 lower-case hex characters";
+                break;
+            }
+    }
+    if (!w) {
+        int ended = 0;
+        for (unsigned i = 0; i < CK_SLOT_PROVENANCE_CHARS; i++) {
+            uint8_t c = m->provenance[i];
+            if (c == 0) {
+                ended = 1;
+            } else if (ended || c < 0x20 || c > 0x7e) {
+                w = "provenance is not zero-padded printable ASCII";
+                break;
+            }
+        }
+    }
+    if (why)
+        *why = w;
+    return w ? -1 : 0;
+}
+
+int ck_slot_control_check(const struct ck_slot_control *c, const char **why)
+{
+    static const uint8_t magic[8] = CK_SLOT_CONTROL_MAGIC;
+    const char *w = 0;
+    if (!c)
+        w = "null control";
+    else if (!eq_bytes(c->magic, magic, 8))
+        w = "bad control magic";
+    else if (c->version != CK_SLOT_CONTROL_VERSION)
+        w = "unsupported control version";
+    else if (c->active_slot >= CK_SLOT_COUNT)
+        w = "active_slot out of range";
+    else if (c->candidate_slot != CK_SLOT_NONE && c->candidate_slot >= CK_SLOT_COUNT)
+        w = "candidate_slot out of range";
+    else if (c->candidate_slot == c->active_slot)
+        w = "candidate_slot equals active_slot";
+    else if (c->tries_remaining > CK_SLOT_MAX_TRIES)
+        w = "tries_remaining above the bound";
+    else if (c->candidate_slot == CK_SLOT_NONE && c->tries_remaining != 0)
+        w = "tries_remaining without a candidate";
+    else if (c->flags & ~(uint8_t)CK_SLOT_CTL_FLAG_CANDIDATE_FAILED)
+        w = "unknown control flags";
+    else if (c->last_good_generation != 0 && c->last_good_generation < c->generation_floor)
+        w = "last_good_generation below the floor";
+    else if (!all_zero(c->reserved, sizeof c->reserved))
+        w = "control reserved bytes nonzero";
+    if (why)
+        *why = w;
+    return w ? -1 : 0;
+}
+
+int ck_slot_verify(const struct ck_slot_manifest *m, const uint8_t *image, uint64_t image_cap,
+                   const uint8_t (*keys)[32], unsigned nkeys, struct ck_slot_eval *ev)
+{
+    uint8_t digest[AIENOS_SHA512_DIGEST_LEN];
+    uint8_t id[SHA256_DIGEST_SIZE];
+    const char *why = 0;
+    unsigned k;
+
+    ev->valid = 0;
+    ev->generation = 0;
+    ev->policy_generation = 0;
+    ev->why = 0;
+    if (ck_slot_manifest_check(m, &why) != 0) {
+        ev->why = why;
+        return 0;
+    }
+    if (m->image_len > image_cap) {
+        ev->why = "image_len exceeds the slot capacity";
+        return 0;
+    }
+    if (!image) {
+        ev->why = "no image bytes";
+        return 0;
+    }
+    /* Signature before the (long) digest so a forged manifest costs nothing. */
+    for (k = 0; k < nkeys; k++) {
+        sha256_hash(keys[k], 32, id);
+        if (eq_bytes(id, m->signer_id, 32))
+            break;
+    }
+    if (k == nkeys) {
+        ev->why = "signer_id names no trusted key";
+        return 0;
+    }
+    if (aienos_ed25519_verify(m->signature, (const uint8_t *)m, CK_SLOT_TBS_BYTES, keys[k]) !=
+        AIENOS_SIG_OK) {
+        ev->why = "signature does not verify";
+        return 0;
+    }
+    aienos_sha512(image, (size_t)m->image_len, digest);
+    if (!eq_bytes(digest, m->image_sha512, 64)) {
+        ev->why = "image SHA-512 mismatch";
+        return 0;
+    }
+    ev->valid = 1;
+    ev->generation = m->generation;
+    ev->policy_generation = m->policy_generation;
+    return 1;
+}
+
+static int usable(const struct ck_slot_eval *e, uint64_t floor)
+{
+    return e->valid && e->generation >= floor;
+}
+
+void ck_slot_select(const struct ck_slot_control *ctl, const struct ck_slot_eval ev[CK_SLOT_COUNT],
+                    struct ck_slot_decision *d)
+{
+    const char *why;
+    d->boot_slot = -1;
+    d->reason = CK_SLOT_R_RECOVERY_REQUIRED;
+    d->loader_write = 0;
+    for (size_t i = 0; i < sizeof d->ctl_out; i++)
+        ((uint8_t *)&d->ctl_out)[i] = 0;
+
+    if (!ctl || ck_slot_control_check(ctl, &why) != 0) {
+        /* Rule 1: no floor is known, so none is invented. */
+        int a = usable(&ev[0], 0), b = usable(&ev[1], 0);
+        if (a && (!b || ev[0].generation >= ev[1].generation))
+            d->boot_slot = 0;
+        else if (b)
+            d->boot_slot = 1;
+        d->reason = d->boot_slot < 0 ? CK_SLOT_R_RECOVERY_REQUIRED : CK_SLOT_R_NO_CONTROL;
+        return;
+    }
+
+    {
+        uint64_t floor = ctl->generation_floor;
+        unsigned act = ctl->active_slot;
+        unsigned other = act ^ 1u;
+        if (ctl->candidate_slot != CK_SLOT_NONE) {
+            unsigned cand = ctl->candidate_slot;
+            if (ctl->tries_remaining > 0 && usable(&ev[cand], floor)) {
+                d->boot_slot = (int)cand;
+                d->reason = CK_SLOT_R_CANDIDATE_TRY;
+                d->loader_write = 1;
+                copy_bytes((uint8_t *)&d->ctl_out, (const uint8_t *)ctl, sizeof d->ctl_out);
+                d->ctl_out.tries_remaining = (uint8_t)(ctl->tries_remaining - 1u);
+                return;
+            }
+            if (usable(&ev[act], floor)) {
+                d->boot_slot = (int)act;
+                d->reason = ctl->tries_remaining == 0 ? CK_SLOT_R_CANDIDATE_EXHAUSTED
+                                                       : CK_SLOT_R_CANDIDATE_INVALID;
+                return;
+            }
+            /* Active unusable too. The candidate is the other slot and was
+             * found unusable or out of tries, so the fallback rule below
+             * cannot pick it: an exhausted candidate never boots on its own
+             * authority (bounded attempts), and recovery is required. */
+        }
+        if (usable(&ev[act], floor)) {
+            d->boot_slot = (int)act;
+            d->reason = CK_SLOT_R_ACTIVE;
+            return;
+        }
+        if (usable(&ev[other], floor) && ctl->candidate_slot != other) {
+            d->boot_slot = (int)other;
+            d->reason = CK_SLOT_R_ACTIVE_INVALID_FALLBACK;
+            return;
+        }
+    }
+}
+
+void ck_slot_control_init(struct ck_slot_control *c, unsigned active_slot)
+{
+    static const uint8_t magic[8] = CK_SLOT_CONTROL_MAGIC;
+    for (size_t i = 0; i < sizeof *c; i++)
+        ((uint8_t *)c)[i] = 0;
+    copy_bytes(c->magic, magic, 8);
+    c->version = CK_SLOT_CONTROL_VERSION;
+    c->active_slot = (uint8_t)(active_slot & 1u);
+    c->candidate_slot = CK_SLOT_NONE;
+    c->tries_remaining = 0;
+}
+
+int ck_slot_stage_candidate(struct ck_slot_control *c, unsigned slot, uint64_t generation, const char **why)
+{
+    const char *w = 0;
+    if (ck_slot_control_check(c, &w) != 0) {
+    } else if (slot >= CK_SLOT_COUNT)
+        w = "slot out of range";
+    else if (slot == c->active_slot)
+        w = "cannot stage the active slot as a candidate";
+    else if (generation < c->generation_floor)
+        w = "candidate generation below the security floor";
+    else if (c->last_good_generation != 0 && generation <= c->last_good_generation)
+        w = "candidate generation not above the last good generation";
+    if (w) {
+        if (why)
+            *why = w;
+        return -1;
+    }
+    c->candidate_slot = (uint8_t)slot;
+    c->tries_remaining = CK_SLOT_MAX_TRIES;
+    c->flags &= (uint8_t)~CK_SLOT_CTL_FLAG_CANDIDATE_FAILED;
+    if (why)
+        *why = 0;
+    return 0;
+}
+
+int ck_slot_promote(struct ck_slot_control *c, unsigned booted_slot, uint64_t generation,
+                    uint64_t policy_generation, const char **why)
+{
+    const char *w = 0;
+    if (ck_slot_control_check(c, &w) != 0) {
+    } else if (booted_slot >= CK_SLOT_COUNT)
+        w = "slot out of range";
+    else if (c->candidate_slot == CK_SLOT_NONE || booted_slot != c->candidate_slot)
+        w = "only the staged candidate can be promoted";
+    else if (generation < c->generation_floor)
+        w = "promoted generation below the security floor";
+    else if (policy_generation > generation)
+        w = "policy_generation above generation";
+    if (w) {
+        if (why)
+            *why = w;
+        return -1;
+    }
+    c->active_slot = (uint8_t)booted_slot;
+    c->candidate_slot = CK_SLOT_NONE;
+    c->tries_remaining = 0;
+    c->flags &= (uint8_t)~CK_SLOT_CTL_FLAG_CANDIDATE_FAILED;
+    c->last_good_generation = generation;
+    if (policy_generation > c->generation_floor)
+        c->generation_floor = policy_generation; /* never lowers */
+    if (why)
+        *why = 0;
+    return 0;
+}
+
+int ck_slot_abandon_candidate(struct ck_slot_control *c, const char **why)
+{
+    const char *w = 0;
+    if (ck_slot_control_check(c, &w) != 0) {
+    } else if (c->candidate_slot == CK_SLOT_NONE)
+        w = "no candidate to abandon";
+    if (w) {
+        if (why)
+            *why = w;
+        return -1;
+    }
+    c->candidate_slot = CK_SLOT_NONE;
+    c->tries_remaining = 0;
+    c->flags |= CK_SLOT_CTL_FLAG_CANDIDATE_FAILED;
+    if (why)
+        *why = 0;
+    return 0;
+}
+
+const char *ck_slot_reason_text(enum ck_slot_reason r)
+{
+    switch (r) {
+    case CK_SLOT_R_NONE: return "none";
+    case CK_SLOT_R_CANDIDATE_TRY: return "candidate_try";
+    case CK_SLOT_R_ACTIVE: return "active";
+    case CK_SLOT_R_CANDIDATE_EXHAUSTED: return "candidate_exhausted_active";
+    case CK_SLOT_R_CANDIDATE_INVALID: return "candidate_invalid_active";
+    case CK_SLOT_R_ACTIVE_INVALID_FALLBACK: return "active_invalid_fallback";
+    case CK_SLOT_R_NO_CONTROL: return "no_control_highest_generation";
+    case CK_SLOT_R_RECOVERY_REQUIRED: return "recovery_required";
+    }
+    return "unknown";
+}
diff --git a/native/kernel/.crumb b/native/kernel/.crumb
index 3244adc6..12f10b66 100644
--- a/native/kernel/.crumb
+++ b/native/kernel/.crumb
@@ -93,21 +93,21 @@
           "purpose": "Directory native/kernel/tests. Purpose not yet described by a human."
         },
         {
-          "digest": "0a07e8dbd80ec6009af73dc47cf5e943493e6bcab3b11669b0ababc940cce53d",
-          "last_commit": "0711ee0",
+          "digest": "48a89618757aeb68d86820be506e65f272374ae9f062bcbddb58dbfc8ca1c6a2",
+          "last_commit": "c30b15e",
           "name": "tools",
           "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin"
         }
       ],
-      "children_root": "sha256:8d6d93738edf94b81b3b3c7b17d56058e1771b21bbcd578c32526ec8c1cdbed2",
-      "compiled_at": "2026-10-12T13:00:09Z",
+      "children_root": "sha256:66b658e28d90bcae073551c805f7ccef649ded64fa274b858aacee45e4b680af",
+      "compiled_at": "2026-10-12T14:03:50Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:6845f46fb7d05df8d980e8290908700361869cb5a11eae224f299bf9bf5ddae0",
+      "digest": "sha256:1cae2705c9a51ed917f8ba4eb048c36e92ab884988421a026182d852ed89086e",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 310,
-      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
-      "source_tree": "sha256:2e3ab6c0196e93f501e1f5e4747e4dadee7a2a6737c2d9e3c9243c1ae5ff6cbb"
+      "files": 311,
+      "generated_at_commit": "c30b15e75373d0357956d8b46e81d0b007839d54",
+      "source_tree": "sha256:32ab1ed9905c84f191c4aecf4ec5e5d282361b40727b52de6c1e3133d3801b26"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/native/kernel/Makefile b/native/kernel/Makefile
index 2becf73f..d7b86489 100644
--- a/native/kernel/Makefile
+++ b/native/kernel/Makefile
@@ -1066,8 +1066,8 @@ smmu-l2-mutants: $(OUT)/host/test_smmu
 	else echo "mutant flag refused under CK_HARDWARE_STAGING"; fi; \
 	if [ $$fail = 0 ]; then echo "CK_SMMU_L2_MUTANTS: PASS"; else echo "CK_SMMU_L2_MUTANTS: FAIL"; exit 1; fi
 
-test: $(addprefix $(OUT)/host/,$(TESTS)) handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test
-	@fail=0; for t in $(filter-out handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test,$^); do $$t || fail=1; done; \
+test: $(addprefix $(OUT)/host/,$(TESTS)) handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free
+	@fail=0; for t in $(filter-out handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free,$^); do $$t || fail=1; done; \
 	if [ $$fail = 0 ]; then echo "CK_CORE_HOST: PASS"; else echo "CK_CORE_HOST: FAIL"; exit 1; fi
 
 sanitize: $(addprefix $(OUT)/host-san/,$(TESTS))
@@ -1540,6 +1540,32 @@ gsp-rpc-test: $(GSP_RPC_TOOL)
 	$(GSP_RPC_TOOL) selftest | grep -E '^CK_GSP_RPC_ENCODE_SELFTEST: (PASS|FAIL)' | grep -q PASS || { $(GSP_RPC_TOOL) selftest | grep -E 'FAIL|SELFTEST'; exit 1; }
 	@$(GSP_RPC_TOOL) selftest | tail -1
 
+# ---- native image slots: host tool + freestanding check (native v1 plan P11 cut 1, gate N7) ----
+# native/boot/slot_format.h + slot_select.c: the A/B slot manifest, control record and the
+# loader's selection rules (bounded candidate tries, generation floor, no boot loop, an
+# exhausted candidate never boots on its own authority). docs/NATIVE_IMAGE_SLOTS.md.
+# ck_slot_tool builds/signs/verifies manifests and simulates the decision; its self-test
+# is the format's oracle. slot-free proves slot_select.c compiles with the kernel's
+# freestanding flags and needs only the image's own digest/signature primitives.
+# No image code changes in this cut; the loader does not read slots yet.
+SLOT_TOOL := $(OUT)/host/ck_slot_tool
+SLOT_TOOL_SRCS := $(KDIR)/tools/ck_slot_tool.c $(BOOT)/slot_select.c $(NATIVE)/sig/sha512.c \
+	$(NATIVE)/sig/ed25519.c $(NATIVE)/sig/ct.c $(NATIVE)/argus/sha256.c $(NATIVE)/store/torn_slot.c
+$(SLOT_TOOL): $(SLOT_TOOL_SRCS) $(BOOT)/slot_format.h
+	@mkdir -p $(dir $@)
+	$(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ $(SLOT_TOOL_SRCS)
+slot-tool: $(SLOT_TOOL)
+slot-test: $(SLOT_TOOL)
+	$(SLOT_TOOL) selftest | grep -E '^CK_SLOT_TOOL_SELFTEST: (PASS|FAIL)' | grep -q PASS || { $(SLOT_TOOL) selftest | grep -E 'FAIL|SELFTEST'; exit 1; }
+	@$(SLOT_TOOL) selftest | tail -1
+SLOT_FREE_ALLOWED_U := aienos_sha512 aienos_ed25519_verify sha256_hash _GLOBAL_OFFSET_TABLE_
+slot-free: $(BOOT)/slot_select.c $(BOOT)/slot_format.h
+	@mkdir -p $(OUT)/free
+	$(KCC) $(KCFLAGS) -c $(BOOT)/slot_select.c -o $(OUT)/free/slot_select.o
+	@bad=$$($(CROSS)nm -u $(OUT)/free/slot_select.o | awk '{print $$2}' | grep -vxF $(foreach a,$(SLOT_FREE_ALLOWED_U),-e $(a)) || true); \
+	if [ -n "$$bad" ]; then echo "slot-free: FAIL unexpected undefined symbols: $$bad"; exit 1; fi; \
+	echo "SLOT_FREE: PASS (undefined: $(SLOT_FREE_ALLOWED_U))"
+
 # ---- host checker for the AIENOS_CK_SCREEN gate (scripts/qemu_ck_screen_test.sh) ----
 FB_CHECK_TOOL := $(OUT)/host/ck_fb_check
 $(FB_CHECK_TOOL): $(KDIR)/tools/ck_fb_check.c $(KDIR)/core/fbcon.c $(KDIR)/core/fbcon.h $(KDIR)/core/font8x8.h
diff --git a/native/kernel/tools/.crumb b/native/kernel/tools/.crumb
index e8cb8369..1b2ddf7e 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-12T13:00:09Z",
+      "compiled_at": "2026-10-12T14:03:50Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:0a07e8dbd80ec6009af73dc47cf5e943493e6bcab3b11669b0ababc940cce53d",
+      "digest": "sha256:48a89618757aeb68d86820be506e65f272374ae9f062bcbddb58dbfc8ca1c6a2",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 17,
-      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
-      "source_tree": "sha256:d344102b5aaa3ec59cfcc87be7e73a1d4455552b06a57a31bb905cb52a99c485"
+      "files": 18,
+      "generated_at_commit": "c30b15e75373d0357956d8b46e81d0b007839d54",
+      "source_tree": "sha256:c5694f4f087ea2534ca87a531df8d6aa0a6c2ad42963f258c8495c4e5648f11a"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/native/kernel/tools/ck_slot_tool.c b/native/kernel/tools/ck_slot_tool.c
new file mode 100644
index 00000000..68237d54
--- /dev/null
+++ b/native/kernel/tools/ck_slot_tool.c
@@ -0,0 +1,1056 @@
+/* ck_slot_tool -- host tool for the AIENOS native image slots
+ * (native/boot/slot_format.h, slot_select.c; native v1 plan P11, gate N7).
+ * Builds, signs, verifies and inspects slot manifests and control records,
+ * and simulates the loader's decision over them. Hosted C, test and
+ * provisioning tooling only, never part of an image. No outside libraries.
+ *
+ *   ck_slot_tool selftest
+ *   ck_slot_tool make-manifest --image F --generation N --out M
+ *       [--policy-generation N] [--min-rollback N] [--commit HEX40]
+ *       [--provenance TEXT] [--timestamp N]       unsigned manifest (signature zero)
+ *   ck_slot_tool tbs M --out F                   the 448 to-be-signed bytes, for an
+ *       offline signer: openssl pkeyutl -sign -inkey owner_root.pem -rawin -in F -out SIG
+ *   ck_slot_tool attach-sig M --sig SIG --out M2 --pubkey HEX64
+ *   ck_slot_tool sign-test M --out M2            RFC 8032 TEST 1 key. NEVER for hardware.
+ *   ck_slot_tool verify M --image F (--keys FILE | --test-key) [--cap BYTES]
+ *       FILE: tools/ck_owner_gen.c format, "owner_root_ed25519 <64 hex>"
+ *   ck_slot_tool control-init --active 0|1 --out C
+ *   ck_slot_tool control-show C
+ *   ck_slot_tool stage C --slot N --generation N --out C2
+ *   ck_slot_tool promote C --slot N --generation N --policy-generation N --out C2
+ *   ck_slot_tool abandon C --out C2
+ *   ck_slot_tool select (--control C | --no-control) --a M,IMG|none --b M,IMG|none
+ *       (--keys FILE | --test-key) [--cap BYTES] [--out C2]   loader decision;
+ *       --out writes ctl_out when the loader would have to commit it
+ *   ck_slot_tool control-commit --region F --record C     torn-slot commit into a
+ *       4-unit region file (512-byte blocks), as the kernel/loader would
+ *   ck_slot_tool control-recover --region F --out C
+ * Every refusal prints "refused: <reason>" and exits 1. */
+#include <errno.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../../boot/slot_format.h"
+#include "../../sig/aienos_sig.h"
+#include "../../argus/sha256.h"
+#include "../../store/torn_slot.h"
+
+/* RFC 8032 section 7.1 TEST 1: seed and public key (the key ck_owner_gen refuses). */
+static const uint8_t TEST1_SEED[32] = {
+    0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4,
+    0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60};
+static const uint8_t TEST1_PK[32] = {
+    0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, 0xc9, 0x64, 0x07, 0x3a,
+    0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a};
+static const uint8_t TEST2_PK[32] = {
+    0x3d, 0x40, 0x17, 0xc3, 0xe8, 0x43, 0x89, 0x5a, 0x92, 0xb7, 0x0a, 0xa7, 0x4d, 0x1b, 0x7e, 0xbc,
+    0x9c, 0x98, 0x2c, 0xcf, 0x2e, 0xc4, 0x96, 0x8c, 0xc0, 0xcd, 0x55, 0xf1, 0x2a, 0xf4, 0x66, 0x0c};
+static const uint8_t TEST3_PK[32] = {
+    0xfc, 0x51, 0xcd, 0x8e, 0x62, 0x18, 0xa1, 0xa3, 0x8d, 0xa4, 0x7e, 0xd0, 0x02, 0x30, 0xf0, 0x58,
+    0x08, 0x16, 0xed, 0x13, 0xba, 0x33, 0x03, 0xac, 0x5d, 0xeb, 0x91, 0x15, 0x48, 0x90, 0x80, 0x25};
+
+#define MAX_KEYS 8u
+#define DEFAULT_CAP (16u * 1024u * 1024u)
+
+static int refuse(const char *why)
+{
+    printf("refused: %s\n", why);
+    return 1;
+}
+
+static int read_file(const char *path, uint8_t **out, size_t *len)
+{
+    FILE *f = fopen(path, "rb");
+    uint8_t *buf = 0;
+    size_t cap = 0, n = 0;
+    if (!f)
+        return -1;
+    for (;;) {
+        if (n == cap) {
+            cap = cap ? cap * 2 : 65536;
+            buf = realloc(buf, cap);
+            if (!buf) {
+                fclose(f);
+                return -1;
+            }
+        }
+        size_t r = fread(buf + n, 1, cap - n, f);
+        n += r;
+        if (r == 0)
+            break;
+    }
+    int err = ferror(f);
+    fclose(f);
+    if (err) {
+        free(buf);
+        return -1;
+    }
+    *out = buf;
+    *len = n;
+    return 0;
+}
+
+static int read_unit(const char *path, void *unit)
+{
+    uint8_t *b;
+    size_t n;
+    if (read_file(path, &b, &n) != 0)
+        return -1;
+    if (n != CK_SLOT_UNIT) {
+        free(b);
+        return -2;
+    }
+    memcpy(unit, b, CK_SLOT_UNIT);
+    free(b);
+    return 0;
+}
+
+static int write_file(const char *path, const void *p, size_t n)
+{
+    FILE *f = fopen(path, "wb");
+    if (!f)
+        return -1;
+    size_t w = fwrite(p, 1, n, f);
+    if (fclose(f) != 0 || w != n)
+        return -1;
+    return 0;
+}
+
+static int hexval(int c)
+{
+    if (c >= '0' && c <= '9')
+        return c - '0';
+    if (c >= 'a' && c <= 'f')
+        return c - 'a' + 10;
+    if (c >= 'A' && c <= 'F')
+        return c - 'A' + 10;
+    return -1;
+}
+
+static int parse_hex(const char *s, uint8_t *out, size_t n)
+{
+    if (strlen(s) != 2 * n)
+        return -1;
+    for (size_t i = 0; i < n; i++) {
+        int hi = hexval(s[2 * i]), lo = hexval(s[2 * i + 1]);
+        if (hi < 0 || lo < 0)
+            return -1;
+        out[i] = (uint8_t)(hi * 16 + lo);
+    }
+    return 0;
+}
+
+static int parse_u64(const char *s, uint64_t *v)
+{
+    char *end;
+    errno = 0;
+    if (!s || !*s)
+        return -1;
+    unsigned long long x = strtoull(s, &end, 10);
+    if (errno || *end)
+        return -1;
+    *v = x;
+    return 0;
+}
+
+static int is_test_key(const uint8_t pk[32])
+{
+    return memcmp(pk, TEST1_PK, 32) == 0 || memcmp(pk, TEST2_PK, 32) == 0 ||
+           memcmp(pk, TEST3_PK, 32) == 0;
+}
+
+/* Owner public keys file (tools/ck_owner_gen.c format). */
+static int load_keys(const char *path, uint8_t keys[MAX_KEYS][32], unsigned *nkeys, const char **why)
+{
+    uint8_t *b;
+    size_t n;
+    unsigned count = 0;
+    if (read_file(path, &b, &n) != 0) {
+        *why = "cannot read the keys file";
+        return -1;
+    }
+    char *text = malloc(n + 1);
+    if (!text) {
+        free(b);
+        *why = "out of memory";
+        return -1;
+    }
+    memcpy(text, b, n);
+    text[n] = 0;
+    free(b);
+    char *save = 0;
+    for (char *line = strtok_r(text, "\n", &save); line; line = strtok_r(0, "\n", &save)) {
+        while (*line == ' ' || *line == '\t' || *line == '\r')
+            line++;
+        if (*line == 0 || *line == '#')
+            continue;
+        char *name = line;
+        char *sp = strpbrk(line, " \t");
+        if (!sp) {
+            free(text);
+            *why = "keys file line without a value";
+            return -1;
+        }
+        *sp++ = 0;
+        while (*sp == ' ' || *sp == '\t')
+            sp++;
+        char *end = sp + strlen(sp);
+        while (end > sp && (end[-1] == ' ' || end[-1] == '\t' || end[-1] == '\r'))
+            *--end = 0;
+        if (strcmp(name, "owner_root_ed25519") != 0) {
+            free(text);
+            *why = "keys file names an unknown key";
+            return -1;
+        }
+        if (count == MAX_KEYS) {
+            free(text);
+            *why = "too many keys";
+            return -1;
+        }
+        if (parse_hex(sp, keys[count], 32) != 0) {
+            free(text);
+            *why = "owner_root_ed25519 is not 64 hex characters";
+            return -1;
+        }
+        {
+            uint8_t acc = 0;
+            for (unsigned i = 0; i < 32; i++)
+                acc |= (uint8_t)(keys[count][i] ^ keys[count][0]);
+            if (acc == 0) {
+                free(text);
+                *why = "owner key has all bytes equal";
+                return -1;
+            }
+        }
+        if (is_test_key(keys[count])) {
+            free(text);
+            *why = "owner key is a known TEST key (use --test-key for tests)";
+            return -1;
+        }
+        count++;
+    }
+    free(text);
+    if (count == 0) {
+        *why = "keys file holds no owner_root_ed25519";
+        return -1;
+    }
+    *nkeys = count;
+    return 0;
+}
+
+static void fill_manifest(struct ck_slot_manifest *m, const uint8_t *image, uint64_t image_len,
+                          uint64_t generation, uint64_t policy_generation, uint64_t min_rollback,
+                          const char *commit, const char *provenance, uint64_t timestamp)
+{
+    memset(m, 0, sizeof *m);
+    memcpy(m->magic, CK_SLOT_MANIFEST_MAGIC, 8);
+    m->version = CK_SLOT_MANIFEST_VERSION;
+    m->payload_kind = CK_SLOT_PAYLOAD_BOOTAA64;
+    m->loader_abi = CK_SLOT_LOADER_ABI;
+    m->kernel_abi = CK_SLOT_KERNEL_ABI;
+    m->generation = generation;
+    m->policy_generation = policy_generation;
+    m->min_rollback_generation = min_rollback;
+    m->image_len = image_len;
+    aienos_sha512(image, (size_t)image_len, m->image_sha512);
+    memcpy(m->kernel_sha512, m->image_sha512, 64);
+    memcpy(m->commit, commit, CK_SLOT_COMMIT_CHARS);
+    {
+        size_t pl = strlen(provenance);
+        if (pl > CK_SLOT_PROVENANCE_CHARS)
+            pl = CK_SLOT_PROVENANCE_CHARS;
+        memcpy(m->provenance, provenance, pl);
+    }
+    m->timestamp = timestamp;
+}
+
+static void sign_manifest(struct ck_slot_manifest *m, const uint8_t seed[32])
+{
+    uint8_t pk[32];
+    aienos_ed25519_public_key(pk, seed);
+    sha256_hash(pk, 32, m->signer_id);
+    aienos_ed25519_sign(m->signature, (const uint8_t *)m, CK_SLOT_TBS_BYTES, seed);
+}
+
+static const char *opt(int argc, char **argv, const char *name)
+{
+    for (int i = 2; i + 1 < argc; i++)
+        if (strcmp(argv[i], name) == 0)
+            return argv[i + 1];
+    return 0;
+}
+
+static int flag(int argc, char **argv, const char *name)
+{
+    for (int i = 2; i < argc; i++)
+        if (strcmp(argv[i], name) == 0)
+            return 1;
+    return 0;
+}
+
+static int get_keys(int argc, char **argv, uint8_t keys[MAX_KEYS][32], unsigned *nkeys)
+{
+    const char *why;
+    const char *kf = opt(argc, argv, "--keys");
+    if (flag(argc, argv, "--test-key")) {
+        memcpy(keys[0], TEST1_PK, 32);
+        *nkeys = 1;
+        printf("keys: RFC 8032 TEST 1 (tests only, never for hardware)\n");
+        return 0;
+    }
+    if (!kf)
+        return refuse("give --keys FILE or --test-key");
+    if (load_keys(kf, keys, nkeys, &why) != 0)
+        return refuse(why);
+    printf("keys: %u owner key(s) from %s\n", *nkeys, kf);
+    return 0;
+}
+
+static void print_control(const struct ck_slot_control *c)
+{
+    printf("control: active=%u candidate=%s tries=%u flags=0x%02x floor=%llu last_good=%llu\n",
+           c->active_slot,
+           c->candidate_slot == CK_SLOT_NONE ? "none" : (c->candidate_slot ? "1" : "0"),
+           c->tries_remaining, c->flags, (unsigned long long)c->generation_floor,
+           (unsigned long long)c->last_good_generation);
+}
+
+static void print_manifest(const struct ck_slot_manifest *m)
+{
+    printf("manifest: generation=%llu policy=%llu min_rollback=%llu image_len=%llu kernel_abi=%u loader_abi=%u timestamp=%llu\n",
+           (unsigned long long)m->generation, (unsigned long long)m->policy_generation,
+           (unsigned long long)m->min_rollback_generation, (unsigned long long)m->image_len,
+           m->kernel_abi, m->loader_abi, (unsigned long long)m->timestamp);
+    printf("  commit=%.40s provenance=%.64s\n", (const char *)m->commit, (const char *)m->provenance);
+    printf("  image_sha512=");
+    for (unsigned i = 0; i < 64; i++)
+        printf("%02x", m->image_sha512[i]);
+    printf("\n  signer_id=");
+    for (unsigned i = 0; i < 32; i++)
+        printf("%02x", m->signer_id[i]);
+    printf("\n");
+}
+
+/* ---- file-backed torn-slot device (512-byte blocks) ------------------------ */
+struct filedev {
+    uint8_t *bytes;
+    size_t len;
+};
+
+static int fd_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf)
+{
+    struct filedev *d = ctx;
+    if ((lba + count) * 512 > d->len)
+        return -1;
+    memcpy(buf, d->bytes + lba * 512, (size_t)count * 512);
+    return 0;
+}
+
+static int fd_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf)
+{
+    struct filedev *d = ctx;
+    if ((lba + count) * 512 > d->len)
+        return -1;
+    memcpy(d->bytes + lba * 512, buf, (size_t)count * 512);
+    return 0;
+}
+
+static int fd_flush(void *ctx)
+{
+    (void)ctx;
+    return 0;
+}
+
+static void bind_dev(ts_device *dev, struct filedev *d)
+{
+    dev->ctx = d;
+    dev->block_size = 512;
+    dev->block_count = d->len / 512;
+    dev->read = fd_read;
+    dev->write = fd_write;
+    dev->flush = fd_flush;
+}
+
+/* ---- self-test ------------------------------------------------------------- */
+static unsigned g_checks, g_fails;
+
+static void check(int ok, const char *what)
+{
+    g_checks++;
+    if (!ok) {
+        g_fails++;
+        printf("  FAIL: %s\n", what);
+    }
+}
+
+static void expect_refused(const struct ck_slot_manifest *m, const uint8_t *img, uint64_t cap,
+                           const uint8_t (*keys)[32], unsigned nkeys, const char *why, const char *what)
+{
+    struct ck_slot_eval ev;
+    ck_slot_verify(m, img, cap, keys, nkeys, &ev);
+    g_checks++;
+    if (ev.valid || !ev.why || strcmp(ev.why, why) != 0) {
+        g_fails++;
+        printf("  FAIL: %s: valid=%d why=%s (expected %s)\n", what, ev.valid, ev.why ? ev.why : "(none)", why);
+    }
+}
+
+static int selftest(void)
+{
+    uint8_t keys[MAX_KEYS][32];
+    uint8_t pk[32];
+    static uint8_t img[10000];
+    struct ck_slot_manifest good, m;
+    struct ck_slot_eval ev;
+    const char *why;
+    uint32_t x = 0x12345678u;
+
+    for (size_t i = 0; i < sizeof img; i++) {
+        x = x * 1664525u + 1013904223u;
+        img[i] = (uint8_t)(x >> 24);
+    }
+    aienos_ed25519_public_key(pk, TEST1_SEED);
+    check(memcmp(pk, TEST1_PK, 32) == 0, "TEST 1 public key derives from the seed");
+    memcpy(keys[0], TEST1_PK, 32);
+
+    fill_manifest(&good, img, sizeof img, 7, 5, 3, "0123456789abcdef0123456789abcdef01234567",
+                  "selftest build", 1760000000ull);
+    check(ck_slot_manifest_check(&good, &why) == 0, "unsigned manifest is structurally valid");
+    sign_manifest(&good, TEST1_SEED);
+    check(ck_slot_verify(&good, img, sizeof img, keys, 1, &ev) == 1, "signed manifest verifies");
+    check(ev.generation == 7 && ev.policy_generation == 5, "eval carries generation and policy");
+    check(ck_slot_verify(&good, img, sizeof img + 4096, keys, 1, &ev) == 1, "larger capacity still verifies");
+
+    /* Mutations: each must be refused with the named reason. */
+#define MUT(stmt, why_s, what) do { m = good; stmt; expect_refused(&m, img, sizeof img, keys, 1, why_s, what); } while (0)
+    MUT(m.magic[0] ^= 1, "bad magic", "magic");
+    MUT(m.version = 2, "unsupported manifest version", "version");
+    MUT(m.payload_kind = 2, "unsupported payload kind", "payload kind");
+    MUT(m.loader_abi = 2, "loader ABI mismatch", "loader abi");
+    MUT(m.kernel_abi = 2, "kernel ABI mismatch", "kernel abi");
+    MUT(m.generation = 0, "generation is zero", "generation 0");
+    MUT(m.policy_generation = 8, "policy_generation above generation", "policy above");
+    MUT(m.min_rollback_generation = 8, "min_rollback_generation above generation", "rollback above");
+    MUT(m.image_len = 0, "image_len is zero", "image_len 0");
+    MUT(m.kernel_sha512[3] ^= 1, "kernel_sha512 differs from image_sha512 (payload kind 1)", "kernel digest");
+    MUT(m.timestamp = 0, "timestamp is zero", "timestamp");
+    MUT(m.flags = 1, "flags nonzero", "flags");
+    MUT(m.reserved0 = 1, "reserved bytes nonzero", "reserved0");
+    MUT(m.reserved1[50] = 1, "reserved bytes nonzero", "reserved1");
+    MUT(m.pad[100] = 1, "pad nonzero", "pad");
+    MUT(m.commit[5] = 'A', "commit is not 40 lower-case hex characters", "commit upper");
+    MUT(m.commit[39] = 'g', "commit is not 40 lower-case hex characters", "commit non-hex");
+    MUT(m.provenance[2] = 0x01, "provenance is not zero-padded printable ASCII", "provenance control char");
+    MUT(m.provenance[63] = 'x', "provenance is not zero-padded printable ASCII", "provenance after terminator");
+    MUT(m.image_len = sizeof img + 1, "image_len exceeds the slot capacity", "image_len over capacity");
+    MUT(m.image_len = sizeof img - 1, "signature does not verify", "image_len changed under the signature");
+    MUT(m.generation = 9, "signature does not verify", "generation changed under the signature");
+    MUT(m.signer_id[0] ^= 1, "signer_id names no trusted key", "signer_id");
+    MUT(m.signature[10] ^= 1, "signature does not verify", "signature byte");
+    MUT(m.signature[63] ^= 0x80, "signature does not verify", "signature high bit");
+    MUT(m.image_sha512[0] ^= 1; m.kernel_sha512[0] ^= 1, "signature does not verify", "image digest under the signature");
+#undef MUT
+    {
+        static uint8_t img2[sizeof img];
+        memcpy(img2, img, sizeof img);
+        img2[sizeof img - 1] ^= 1;
+        ck_slot_verify(&good, img2, sizeof img, keys, 1, &ev);
+        check(!ev.valid && strcmp(ev.why, "image SHA-512 mismatch") == 0, "flipped image byte");
+        ck_slot_verify(&good, img, sizeof img - 1, keys, 1, &ev);
+        check(!ev.valid && strcmp(ev.why, "image_len exceeds the slot capacity") == 0, "capacity below image_len");
+        memcpy(keys[1], TEST2_PK, 32);
+        ck_slot_verify(&good, img, sizeof img, keys + 1, 1, &ev);
+        check(!ev.valid && strcmp(ev.why, "signer_id names no trusted key") == 0, "wrong key set");
+        ck_slot_verify(&good, img, sizeof img, keys, 0, &ev);
+        check(!ev.valid && strcmp(ev.why, "signer_id names no trusted key") == 0, "empty key set");
+        ck_slot_verify(&good, img, sizeof img, keys, 2, &ev);
+        check(ev.valid, "two-key set containing the signer verifies");
+        ck_slot_verify(&good, 0, sizeof img, keys, 1, &ev);
+        check(!ev.valid && strcmp(ev.why, "no image bytes") == 0, "null image");
+        /* A manifest signed by a key that is NOT in the set, but whose signer_id is forged
+         * to name a trusted key, must fail on the signature, not pass. */
+        m = good;
+        {
+            uint8_t other_seed[32];
+            memset(other_seed, 0x42, 32);
+            aienos_ed25519_sign(m.signature, (const uint8_t *)&m, CK_SLOT_TBS_BYTES, other_seed);
+        }
+        ck_slot_verify(&m, img, sizeof img, keys, 1, &ev);
+        check(!ev.valid && strcmp(ev.why, "signature does not verify") == 0, "forged signer_id with another key");
+    }
+
+    /* Control record structure. */
+    {
+        struct ck_slot_control c, d;
+        ck_slot_control_init(&c, 0);
+        check(ck_slot_control_check(&c, &why) == 0, "fresh control is valid");
+#define CMUT(stmt, why_s, what) do { d = c; stmt; g_checks++; if (ck_slot_control_check(&d, &why) == 0 || strcmp(why, why_s) != 0) { g_fails++; printf("  FAIL: control %s: %s\n", what, why ? why : "(accepted)"); } } while (0)
+        CMUT(d.magic[7] ^= 1, "bad control magic", "magic");
+        CMUT(d.version = 0, "unsupported control version", "version");
+        CMUT(d.active_slot = 2, "active_slot out of range", "active range");
+        CMUT(d.candidate_slot = 2, "candidate_slot out of range", "candidate range");
+        CMUT(d.candidate_slot = 0, "candidate_slot equals active_slot", "candidate == active");
+        CMUT(d.candidate_slot = 1; d.tries_remaining = 4, "tries_remaining above the bound", "tries bound");
+        CMUT(d.tries_remaining = 1, "tries_remaining without a candidate", "tries without candidate");
+        CMUT(d.flags = 2, "unknown control flags", "flags");
+        CMUT(d.generation_floor = 5; d.last_good_generation = 4, "last_good_generation below the floor", "last_good < floor");
+        CMUT(d.reserved[1000] = 1, "control reserved bytes nonzero", "reserved");
+#undef CMUT
+    }
+
+    /* Selection rules. */
+    {
+        struct ck_slot_control c;
+        struct ck_slot_eval e[2];
+        struct ck_slot_decision dec;
+#define EV(i, v, g) do { e[i].valid = (v); e[i].generation = (g); e[i].policy_generation = (g); e[i].why = 0; } while (0)
+        EV(0, 1, 5); EV(1, 1, 7);
+        ck_slot_select(0, e, &dec);
+        check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_NO_CONTROL && !dec.loader_write, "no control: highest generation");
+        EV(0, 1, 7); EV(1, 1, 7);
+        ck_slot_select(0, e, &dec);
+        check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_NO_CONTROL, "no control: tie goes to A");
+        EV(0, 0, 0); EV(1, 0, 0);
+        ck_slot_select(0, e, &dec);
+        check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "no control, nothing valid: recovery");
+        ck_slot_control_init(&c, 0);
+        c.magic[0] ^= 1;
+        EV(0, 1, 5); EV(1, 1, 7);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_NO_CONTROL, "corrupt control is treated as absent");
+
+        ck_slot_control_init(&c, 0);
+        EV(0, 1, 5); EV(1, 1, 7);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_ACTIVE && !dec.loader_write, "active boots, no write");
+        EV(0, 0, 0); EV(1, 1, 7);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_ACTIVE_INVALID_FALLBACK && !dec.loader_write, "active invalid: fallback to the other slot");
+        EV(0, 0, 0); EV(1, 0, 0);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "both invalid: recovery");
+
+        /* Candidate tries, bounded. */
+        ck_slot_control_init(&c, 0);
+        c.generation_floor = 3;
+        c.last_good_generation = 5;
+        check(ck_slot_stage_candidate(&c, 1, 7, &why) == 0 && c.tries_remaining == 3, "stage candidate B gen 7");
+        EV(0, 1, 5); EV(1, 1, 7);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_CANDIDATE_TRY && dec.loader_write && dec.ctl_out.tries_remaining == 2, "candidate try 1: tries 3 -> 2, loader write");
+        c = dec.ctl_out;
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 1 && dec.loader_write && dec.ctl_out.tries_remaining == 1, "candidate try 2");
+        c = dec.ctl_out;
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 1 && dec.loader_write && dec.ctl_out.tries_remaining == 0, "candidate try 3");
+        c = dec.ctl_out;
+        check(ck_slot_control_check(&c, &why) == 0, "control with 0 tries and a candidate is valid");
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_CANDIDATE_EXHAUSTED && !dec.loader_write, "tries exhausted: active boots, no write");
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_CANDIDATE_EXHAUSTED, "exhausted again: deterministic, no loop");
+        EV(0, 0, 0);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "exhausted candidate never boots on its own authority");
+        EV(0, 1, 5); EV(1, 0, 0);
+        c.tries_remaining = 3;
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_CANDIDATE_INVALID && !dec.loader_write, "invalid candidate: active boots, tries untouched");
+        check(c.tries_remaining == 3, "select never mutates its input");
+
+        /* Floor. */
+        ck_slot_control_init(&c, 0);
+        c.generation_floor = 10;
+        EV(0, 1, 5); EV(1, 1, 12);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_ACTIVE_INVALID_FALLBACK, "active below the floor: fallback to B above it");
+        EV(1, 1, 9);
+        ck_slot_select(&c, e, &dec);
+        check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "both below the floor: recovery");
+        check(ck_slot_stage_candidate(&c, 1, 9, &why) != 0 && strcmp(why, "candidate generation below the security floor") == 0, "stage below floor refused");
+        check(ck_slot_stage_candidate(&c, 0, 12, &why) != 0 && strcmp(why, "cannot stage the active slot as a candidate") == 0, "stage active slot refused");
+        check(ck_slot_stage_candidate(&c, 2, 12, &why) != 0, "stage slot 2 refused");
+        c.last_good_generation = 12;
+        check(ck_slot_stage_candidate(&c, 1, 12, &why) != 0 && strcmp(why, "candidate generation not above the last good generation") == 0, "stage not above last good refused");
+        check(ck_slot_stage_candidate(&c, 1, 13, &why) == 0, "stage gen 13 accepted");
+
+        /* Promotion. */
+        check(ck_slot_promote(&c, 0, 13, 11, &why) != 0 && strcmp(why, "only the staged candidate can be promoted") == 0, "promote non-candidate refused");
+        check(ck_slot_promote(&c, 1, 13, 14, &why) != 0 && strcmp(why, "policy_generation above generation") == 0, "promote with policy above generation refused");
+        check(ck_slot_promote(&c, 1, 13, 11, &why) == 0, "promote candidate");
+        check(c.active_slot == 1 && c.candidate_slot == CK_SLOT_NONE && c.tries_remaining == 0, "promotion flips active, clears candidate");
+        check(c.generation_floor == 11 && c.last_good_generation == 13, "promotion raises the floor to policy_generation");
+        check(ck_slot_stage_candidate(&c, 0, 14, &why) == 0 && ck_slot_promote(&c, 0, 14, 4, &why) == 0 && c.generation_floor == 11, "promotion never lowers the floor");
+        check(ck_slot_control_check(&c, &why) == 0, "control valid after two promotions");
+        check(ck_slot_abandon_candidate(&c, &why) != 0 && strcmp(why, "no candidate to abandon") == 0, "abandon without candidate refused");
+        check(ck_slot_stage_candidate(&c, 1, 15, &why) == 0 && ck_slot_abandon_candidate(&c, &why) == 0, "abandon candidate");
+        check(c.candidate_slot == CK_SLOT_NONE && c.tries_remaining == 0 && (c.flags & CK_SLOT_CTL_FLAG_CANDIDATE_FAILED), "abandon clears candidate, sets the failed flag");
+        check(ck_slot_stage_candidate(&c, 1, 16, &why) == 0 && !(c.flags & CK_SLOT_CTL_FLAG_CANDIDATE_FAILED), "a new stage clears the failed flag");
+        check(ck_slot_control_check(&c, &why) == 0, "control valid at the end of the transitions");
+        check(strcmp(ck_slot_reason_text(CK_SLOT_R_RECOVERY_REQUIRED), "recovery_required") == 0, "reason text");
+#undef EV
+    }
+
+    /* Torn-slot persistence of the control record over 512-byte blocks. */
+    {
+        static uint8_t media[CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT];
+        struct filedev fd = {media, sizeof media};
+        ts_device dev;
+        ts_region r;
+        uint8_t rec[TS_RECORD_BYTES];
+        uint64_t seq;
+        struct ck_slot_control c, back;
+        memset(media, 0, sizeof media);
+        bind_dev(&dev, &fd);
+        check(ts_open(&r, &dev, 0) == TS_OK, "torn-slot region opens at LBA 0");
+        check(ts_recover(&r, rec, &seq, 0) == TS_EMPTY, "blank region recovers EMPTY");
+        ck_slot_control_init(&c, 0);
+        c.generation_floor = 2;
+        check(ts_commit(&r, (const uint8_t *)&c) == TS_OK, "commit control #1");
+        check(ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_OK && memcmp(&back, &c, sizeof c) == 0 && seq == 1, "recover control #1");
+        check(ck_slot_stage_candidate(&c, 1, 9, &why) == 0 && ts_commit(&r, (const uint8_t *)&c) == TS_OK, "commit control #2 (staged)");
+        check(ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_OK && back.candidate_slot == 1 && seq == 2, "recover control #2");
+        /* Torn write: the next target is the slot that does NOT hold seq 2.
+         * Overwrite only the first 512 bytes of that body (as a power cut
+         * after one block would) and make sure #2 still comes back. */
+        {
+            int target = r.newest_slot == 0 ? 1 : 0;
+            uint8_t partial[512];
+            memset(partial, 0xEE, sizeof partial);
+            fd_write(&fd, (uint64_t)target * 2u * 8u, 1, partial);
+            check(ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_OK && seq == 2 && back.candidate_slot == 1, "torn body: previous record still recovered");
+        }
+        check(ck_slot_control_check(&back, &why) == 0, "recovered control is structurally valid");
+    }
+
+    printf("CK_SLOT_TOOL_SELFTEST: %s (%u checks, %u failures)\n", g_fails ? "FAIL" : "PASS", g_checks, g_fails);
+    return g_fails ? 1 : 0;
+}
+
+/* ---- CLI ------------------------------------------------------------------- */
+static int cmd_make_manifest(int argc, char **argv)
+{
+    const char *image = opt(argc, argv, "--image"), *out = opt(argc, argv, "--out");
+    const char *commit = opt(argc, argv, "--commit"), *prov = opt(argc, argv, "--provenance");
+    uint64_t gen, pol = 0, minrb = 0, ts = 1;
+    uint8_t *img;
+    size_t len;
+    struct ck_slot_manifest m;
+    const char *why;
+    if (!image || !out || parse_u64(opt(argc, argv, "--generation"), &gen) != 0)
+        return refuse("make-manifest needs --image, --generation and --out");
+    if (opt(argc, argv, "--policy-generation") && parse_u64(opt(argc, argv, "--policy-generation"), &pol) != 0)
+        return refuse("bad --policy-generation");
+    if (opt(argc, argv, "--min-rollback") && parse_u64(opt(argc, argv, "--min-rollback"), &minrb) != 0)
+        return refuse("bad --min-rollback");
+    if (opt(argc, argv, "--timestamp") && parse_u64(opt(argc, argv, "--timestamp"), &ts) != 0)
+        return refuse("bad --timestamp");
+    if (!commit)
+        commit = "0000000000000000000000000000000000000000";
+    if (strlen(commit) != CK_SLOT_COMMIT_CHARS)
+        return refuse("--commit must be 40 characters");
+    if (!prov)
+        prov = "unspecified";
+    if (strlen(prov) > CK_SLOT_PROVENANCE_CHARS)
+        return refuse("--provenance longer than 64 characters");
+    if (read_file(image, &img, &len) != 0)
+        return refuse("cannot read the image");
+    if (len == 0)
+        return refuse("image is empty");
+    fill_manifest(&m, img, len, gen, pol, minrb, commit, prov, ts);
+    free(img);
+    if (ck_slot_manifest_check(&m, &why) != 0)
+        return refuse(why);
+    if (write_file(out, &m, sizeof m) != 0)
+        return refuse("cannot write the manifest");
+    print_manifest(&m);
+    printf("manifest written (unsigned): %s\n", out);
+    return 0;
+}
+
+static int load_manifest(const char *path, struct ck_slot_manifest *m)
+{
+    int rc = read_unit(path, m);
+    if (rc == -1)
+        return refuse("cannot read the manifest");
+    if (rc == -2)
+        return refuse("manifest is not exactly 4096 bytes");
+    return 0;
+}
+
+static int cmd_tbs(int argc, char **argv)
+{
+    struct ck_slot_manifest m;
+    const char *out = opt(argc, argv, "--out");
+    if (argc < 3 || !out)
+        return refuse("tbs M --out F");
+    if (load_manifest(argv[2], &m) != 0)
+        return 1;
+    if (write_file(out, &m, CK_SLOT_TBS_BYTES) != 0)
+        return refuse("cannot write the to-be-signed bytes");
+    printf("tbs: %u bytes written to %s\n", CK_SLOT_TBS_BYTES, out);
+    return 0;
+}
+
+static int cmd_sign_test(int argc, char **argv)
+{
+    struct ck_slot_manifest m;
+    const char *out = opt(argc, argv, "--out");
+    const char *why;
+    if (argc < 3 || !out)
+        return refuse("sign-test M --out M2");
+    if (load_manifest(argv[2], &m) != 0)
+        return 1;
+    sign_manifest(&m, TEST1_SEED);
+    if (ck_slot_manifest_check(&m, &why) != 0)
+        return refuse(why);
+    if (write_file(out, &m, sizeof m) != 0)
+        return refuse("cannot write the manifest");
+    printf("signed with RFC 8032 TEST 1: tests only, NEVER for hardware (ck_owner_gen refuses this key)\n");
+    return 0;
+}
+
+static int cmd_attach_sig(int argc, char **argv)
+{
+    struct ck_slot_manifest m;
+    const char *out = opt(argc, argv, "--out"), *sigf = opt(argc, argv, "--sig"), *pkh = opt(argc, argv, "--pubkey");
+    uint8_t *sig, pk[32];
+    size_t n;
+    const char *why;
+    if (argc < 3 || !out || !sigf || !pkh)
+        return refuse("attach-sig M --sig SIG --out M2 --pubkey HEX64");
+    if (load_manifest(argv[2], &m) != 0)
+        return 1;
+    if (parse_hex(pkh, pk, 32) != 0)
+        return refuse("--pubkey is not 64 hex characters");
+    if (is_test_key(pk))
+        return refuse("--pubkey is a known TEST key");
+    if (read_file(sigf, &sig, &n) != 0)
+        return refuse("cannot read the signature");
+    if (n != 64) {
+        free(sig);
+        return refuse("signature is not 64 bytes");
+    }
+    sha256_hash(pk, 32, m.signer_id);
+    memcpy(m.signature, sig, 64);
+    free(sig);
+    if (aienos_ed25519_verify(m.signature, (const uint8_t *)&m, CK_SLOT_TBS_BYTES, pk) != AIENOS_SIG_OK)
+        return refuse("signature does not verify under --pubkey over the manifest's to-be-signed bytes");
+    if (ck_slot_manifest_check(&m, &why) != 0)
+        return refuse(why);
+    if (write_file(out, &m, sizeof m) != 0)
+        return refuse("cannot write the manifest");
+    printf("signature attached and verified: %s\n", out);
+    return 0;
+}
+
+static uint64_t cap_opt(int argc, char **argv)
+{
+    uint64_t cap = DEFAULT_CAP;
+    if (opt(argc, argv, "--cap") && parse_u64(opt(argc, argv, "--cap"), &cap) != 0)
+        return 0;
+    return cap;
+}
+
+static int cmd_verify(int argc, char **argv)
+{
+    struct ck_slot_manifest m;
+    struct ck_slot_eval ev;
+    uint8_t keys[MAX_KEYS][32];
+    unsigned nkeys;
+    uint8_t *img;
+    size_t len;
+    const char *image = opt(argc, argv, "--image");
+    uint64_t cap = cap_opt(argc, argv);
+    if (argc < 3 || !image || !cap)
+        return refuse("verify M --image F (--keys FILE | --test-key) [--cap BYTES]");
+    if (load_manifest(argv[2], &m) != 0)
+        return 1;
+    if (get_keys(argc, argv, keys, &nkeys) != 0)
+        return 1;
+    if (read_file(image, &img, &len) != 0)
+        return refuse("cannot read the image");
+    if (m.image_len != len) {
+        free(img);
+        return refuse("image file length differs from manifest image_len");
+    }
+    ck_slot_verify(&m, img, cap, keys, nkeys, &ev);
+    free(img);
+    print_manifest(&m);
+    if (!ev.valid)
+        return refuse(ev.why);
+    printf("verify: OK generation=%llu\n", (unsigned long long)ev.generation);
+    return 0;
+}
+
+static int load_control(const char *path, struct ck_slot_control *c)
+{
+    const char *why;
+    int rc = read_unit(path, c);
+    if (rc == -1)
+        return refuse("cannot read the control record");
+    if (rc == -2)
+        return refuse("control record is not exactly 4096 bytes");
+    if (ck_slot_control_check(c, &why) != 0)
+        return refuse(why);
+    return 0;
+}
+
+static int save_control(const char *path, const struct ck_slot_control *c)
+{
+    if (write_file(path, c, sizeof *c) != 0)
+        return refuse("cannot write the control record");
+    print_control(c);
+    printf("control written: %s\n", path);
+    return 0;
+}
+
+static int cmd_control_init(int argc, char **argv)
+{
+    struct ck_slot_control c;
+    uint64_t active;
+    const char *out = opt(argc, argv, "--out");
+    if (!out || parse_u64(opt(argc, argv, "--active"), &active) != 0 || active > 1)
+        return refuse("control-init --active 0|1 --out C");
+    ck_slot_control_init(&c, (unsigned)active);
+    return save_control(out, &c);
+}
+
+static int cmd_control_show(int argc, char **argv)
+{
+    struct ck_slot_control c;
+    if (argc < 3)
+        return refuse("control-show C");
+    if (load_control(argv[2], &c) != 0)
+        return 1;
+    print_control(&c);
+    return 0;
+}
+
+static int cmd_transition(int argc, char **argv, const char *which)
+{
+    struct ck_slot_control c;
+    const char *out = opt(argc, argv, "--out"), *why = 0;
+    uint64_t slot = 0, gen = 0, pol = 0;
+    int rc;
+    if (argc < 3 || !out)
+        return refuse("needs the control file and --out");
+    if (load_control(argv[2], &c) != 0)
+        return 1;
+    if (strcmp(which, "abandon") != 0) {
+        if (parse_u64(opt(argc, argv, "--slot"), &slot) != 0 || parse_u64(opt(argc, argv, "--generation"), &gen) != 0)
+            return refuse("needs --slot and --generation");
+    }
+    if (strcmp(which, "stage") == 0)
+        rc = ck_slot_stage_candidate(&c, (unsigned)slot, gen, &why);
+    else if (strcmp(which, "promote") == 0) {
+        if (parse_u64(opt(argc, argv, "--policy-generation"), &pol) != 0)
+            return refuse("promote needs --policy-generation");
+        rc = ck_slot_promote(&c, (unsigned)slot, gen, pol, &why);
+    } else
+        rc = ck_slot_abandon_candidate(&c, &why);
+    if (rc != 0)
+        return refuse(why);
+    return save_control(out, &c);
+}
+
+static int load_slot(const char *spec, uint64_t cap, const uint8_t (*keys)[32], unsigned nkeys,
+                     struct ck_slot_eval *ev, const char *name)
+{
+    struct ck_slot_manifest m;
+    uint8_t *img;
+    size_t len;
+    char path[1024];
+    const char *comma;
+    ev->valid = 0;
+    ev->why = "absent";
+    ev->generation = 0;
+    ev->policy_generation = 0;
+    if (!spec || strcmp(spec, "none") == 0)
+        return 0;
+    comma = strchr(spec, ',');
+    if (!comma || (size_t)(comma - spec) >= sizeof path)
+        return refuse("slot spec must be MANIFEST,IMAGE or none");
+    memcpy(path, spec, (size_t)(comma - spec));
+    path[comma - spec] = 0;
+    if (read_unit(path, &m) != 0) {
+        printf("slot %s: manifest unreadable or not 4096 bytes, treated as invalid\n", name);
+        ev->why = "manifest unreadable";
+        return 0;
+    }
+    if (read_file(comma + 1, &img, &len) != 0) {
+        printf("slot %s: image unreadable, treated as invalid\n", name);
+        ev->why = "image unreadable";
+        return 0;
+    }
+    ck_slot_verify(&m, img, len < cap ? len : cap, keys, nkeys, ev);
+    if (ev->valid && m.image_len != len) {
+        ev->valid = 0;
+        ev->why = "image file length differs from manifest image_len";
+    }
+    free(img);
+    return 0;
+}
+
+static int cmd_select(int argc, char **argv)
+{
+    struct ck_slot_control c, *ctl = 0;
+    struct ck_slot_eval ev[2];
+    struct ck_slot_decision d;
+    uint8_t keys[MAX_KEYS][32];
+    unsigned nkeys;
+    const char *cf = opt(argc, argv, "--control"), *out = opt(argc, argv, "--out");
+    uint64_t cap = cap_opt(argc, argv);
+    if (!cap || (!cf && !flag(argc, argv, "--no-control")))
+        return refuse("select (--control C | --no-control) --a M,IMG|none --b M,IMG|none (--keys FILE | --test-key) [--cap BYTES] [--out C2]");
+    if (get_keys(argc, argv, keys, &nkeys) != 0)
+        return 1;
+    if (cf) {
+        const char *why;
+        int rc = read_unit(cf, &c);
+        if (rc == 0 && ck_slot_control_check(&c, &why) == 0)
+            ctl = &c;
+        else
+            printf("control: unreadable or corrupt, treated as absent\n");
+    }
+    if (load_slot(opt(argc, argv, "--a"), cap, keys, nkeys, &ev[0], "A") != 0)
+        return 1;
+    if (load_slot(opt(argc, argv, "--b"), cap, keys, nkeys, &ev[1], "B") != 0)
+        return 1;
+    for (unsigned i = 0; i < 2; i++)
+        printf("slot %c: %s%s%s generation=%llu\n", 'A' + i, ev[i].valid ? "valid" : "invalid",
+               ev[i].valid ? "" : " (", ev[i].valid ? "" : ev[i].why, (unsigned long long)ev[i].generation);
+    if (ctl)
+        print_control(ctl);
+    ck_slot_select(ctl, ev, &d);
+    printf("decision: boot_slot=%s reason=%s loader_write=%d\n",
+           d.boot_slot < 0 ? "none" : (d.boot_slot ? "B" : "A"), ck_slot_reason_text(d.reason), d.loader_write);
+    if (d.loader_write) {
+        print_control(&d.ctl_out);
+        if (out && write_file(out, &d.ctl_out, sizeof d.ctl_out) != 0)
+            return refuse("cannot write ctl_out");
+    }
+    return d.boot_slot < 0 ? 2 : 0;
+}
+
+static int cmd_control_commit(int argc, char **argv)
+{
+    const char *region = opt(argc, argv, "--region"), *recf = opt(argc, argv, "--record");
+    struct ck_slot_control c;
+    uint8_t *bytes;
+    size_t len;
+    struct filedev fd;
+    ts_device dev;
+    ts_region r;
+    uint8_t rec[TS_RECORD_BYTES];
+    uint64_t seq;
+    int rc;
+    if (!region || !recf)
+        return refuse("control-commit --region F --record C");
+    if (load_control(recf, &c) != 0)
+        return 1;
+    if (read_file(region, &bytes, &len) != 0)
+        return refuse("cannot read the region file");
+    if (len != CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT) {
+        free(bytes);
+        return refuse("region file must be exactly 4 units (16384 bytes)");
+    }
+    fd.bytes = bytes;
+    fd.len = len;
+    bind_dev(&dev, &fd);
+    if (ts_open(&r, &dev, 0) != TS_OK)
+        return refuse("torn-slot open failed");
+    rc = ts_recover(&r, rec, &seq, 0);
+    if (rc != TS_OK && rc != TS_EMPTY) {
+        free(bytes);
+        return refuse("region is corrupt or conflicting: fail closed, not committing");
+    }
+    if (ts_commit(&r, (const uint8_t *)&c) != TS_OK) {
+        free(bytes);
+        return refuse("torn-slot commit failed");
+    }
+    if (write_file(region, bytes, len) != 0) {
+        free(bytes);
+        return refuse("cannot write the region file");
+    }
+    free(bytes);
+    printf("control committed: seq=%llu into %s\n", (unsigned long long)r.newest_seq, region);
+    return 0;
+}
+
+static int cmd_control_recover(int argc, char **argv)
+{
+    const char *region = opt(argc, argv, "--region"), *out = opt(argc, argv, "--out");
+    uint8_t *bytes;
+    size_t len;
+    struct filedev fd;
+    ts_device dev;
+    ts_region r;
+    struct ck_slot_control c;
+    uint64_t seq;
+    ts_slot_state st[2];
+    int rc;
+    const char *why;
+    if (!region)
+        return refuse("control-recover --region F [--out C]");
+    if (read_file(region, &bytes, &len) != 0)
+        return refuse("cannot read the region file");
+    if (len != CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT) {
+        free(bytes);
+        return refuse("region file must be exactly 4 units (16384 bytes)");
+    }
+    fd.bytes = bytes;
+    fd.len = len;
+    bind_dev(&dev, &fd);
+    if (ts_open(&r, &dev, 0) != TS_OK)
+        return refuse("torn-slot open failed");
+    rc = ts_recover(&r, (uint8_t *)&c, &seq, st);
+    free(bytes);
+    printf("torn-slot: rc=%d slotA=%d slotB=%d\n", rc, (int)st[0], (int)st[1]);
+    if (rc == TS_EMPTY) {
+        printf("control: none committed (loader rule: no control)\n");
+        return 2;
+    }
+    if (rc != TS_OK)
+        return refuse("region is corrupt or conflicting");
+    if (ck_slot_control_check(&c, &why) != 0)
+        return refuse(why);
+    printf("seq=%llu\n", (unsigned long long)seq);
+    print_control(&c);
+    if (out && write_file(out, &c, sizeof c) != 0)
+        return refuse("cannot write the control record");
+    return 0;
+}
+
+int main(int argc, char **argv)
+{
+    if (argc < 2)
+        return refuse("no mode (see the header of ck_slot_tool.c)");
+    if (strcmp(argv[1], "selftest") == 0)
+        return selftest();
+    if (strcmp(argv[1], "make-manifest") == 0)
+        return cmd_make_manifest(argc, argv);
+    if (strcmp(argv[1], "tbs") == 0)
+        return cmd_tbs(argc, argv);
+    if (strcmp(argv[1], "sign-test") == 0)
+        return cmd_sign_test(argc, argv);
+    if (strcmp(argv[1], "attach-sig") == 0)
+        return cmd_attach_sig(argc, argv);
+    if (strcmp(argv[1], "verify") == 0)
+        return cmd_verify(argc, argv);
+    if (strcmp(argv[1], "control-init") == 0)
+        return cmd_control_init(argc, argv);
+    if (strcmp(argv[1], "control-show") == 0)
+        return cmd_control_show(argc, argv);
+    if (strcmp(argv[1], "stage") == 0 || strcmp(argv[1], "promote") == 0 || strcmp(argv[1], "abandon") == 0)
+        return cmd_transition(argc, argv, argv[1]);
+    if (strcmp(argv[1], "select") == 0)
+        return cmd_select(argc, argv);
+    if (strcmp(argv[1], "control-commit") == 0)
+        return cmd_control_commit(argc, argv);
+    if (strcmp(argv[1], "control-recover") == 0)
+        return cmd_control_recover(argc, argv);
+    return refuse("unknown mode");
+}