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

closed derived 3d2e0aaf11ec3056 #107

Imported from GitHub aien-dev/aienux#107 (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 78cec642208cddc432688bd2c804fce43d4ad7fb · Head 0d0a8fbb4046e7971d6045d4e0f4421e2bf5c052

Apply it

git checkout -b patch-3d2e0aaf11ec3056 78cec642208cddc432688bd2c804fce43d4ad7fb
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/3d2e0aaf11ec3056.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
107
0d0a8fbb4046e7971d6045d4e0f4421e2bf5c052
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":107,"url":"https://github.com/aien-dev/aienux/pull/107","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:44Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aienos-kernel/src/abi.rs b/crates/aienos-kernel/src/abi.rs
new file mode 100644
index 00000000..4b8b0873
--- /dev/null
+++ b/crates/aienos-kernel/src/abi.rs
@@ -0,0 +1,1053 @@
+//! AIENOS ABI v1: the frozen wire contract for handles, rights, capabilities,
+//! memory regions and messages (ADR 0013).
+//!
+//! Every type here has an explicit little-endian byte encoding that does not
+//! depend on Rust's in-memory layout, the host architecture, or pointer width.
+//! Decoding fails closed: short or long input, reserved bits or fields that
+//! are not zero, unknown discriminants, unknown versions and generation-zero
+//! handles are all rejected with a distinct [`AbiError`].
+//!
+//! The in-memory structs are also `repr(C)` with explicit reserved fields so
+//! their layout matches the wire layout on little-endian targets; `const`
+//! assertions below pin sizes, alignments and field offsets. The byte
+//! encoding, not the struct layout, is the contract.
+//!
+//! No allocation, no `usize` or pointer fields, no implicit enum layout.
+
+use crate::caps;
+use core::mem::{align_of, offset_of, size_of};
+
+/// ABI version carried in every envelope. Decoders reject every other value.
+pub const ABI_VERSION: u16 = 1;
+
+/// Size in bytes of the envelope header that precedes a persisted or
+/// transported payload: tag u16, version u16, payload length u32.
+pub const ENVELOPE_HEADER_SIZE: usize = 8;
+
+/// Why an ABI value failed to encode or decode. Each failure has its own
+/// variant so callers and tests can tell them apart.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum AbiError {
+    /// Input is shorter than the encoding requires.
+    Truncated,
+    /// Input is longer than the encoding, or an envelope length field does
+    /// not match the payload size for its tag.
+    WrongLength,
+    /// Envelope version is not [`ABI_VERSION`].
+    UnknownVersion,
+    /// Envelope tag is not a known [`EnvelopeTag`].
+    UnknownTag,
+    /// Envelope tag is known but names a different type than requested.
+    TagMismatch,
+    /// A reserved field is not zero.
+    ReservedNonZero,
+    /// A reserved rights bit (6 through 31) is set.
+    ReservedBits,
+    /// An enum discriminant (for example a resource kind) is not defined.
+    UnknownDiscriminant,
+    /// A handle has generation 0, which is never issued.
+    InvalidHandle,
+    /// The output buffer is too small for the encoding.
+    BufferTooSmall,
+}
+
+/// A type with a fixed-size v1 wire encoding.
+pub trait Wire: Sized {
+    /// Envelope tag identifying this type when it is persisted or transported.
+    const TAG: EnvelopeTag;
+    /// Exact encoded size in bytes.
+    const SIZE: usize;
+
+    /// Write exactly [`Self::SIZE`] bytes to the front of `out`.
+    fn encode_into(&self, out: &mut [u8]) -> Result<usize, AbiError>;
+
+    /// Decode from a buffer of exactly [`Self::SIZE`] bytes.
+    fn decode(bytes: &[u8]) -> Result<Self, AbiError>;
+}
+
+// Little-endian field helpers. Callers pass fixed arrays whose size is checked
+// by the type, so the offsets are always in range.
+
+const fn get_u16(b: &[u8], at: usize) -> u16 {
+    u16::from_le_bytes([b[at], b[at + 1]])
+}
+
+const fn get_u32(b: &[u8], at: usize) -> u32 {
+    u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
+}
+
+const fn get_u64(b: &[u8], at: usize) -> u64 {
+    u64::from_le_bytes([
+        b[at],
+        b[at + 1],
+        b[at + 2],
+        b[at + 3],
+        b[at + 4],
+        b[at + 5],
+        b[at + 6],
+        b[at + 7],
+    ])
+}
+
+fn put(out: &mut [u8], at: usize, bytes: &[u8]) {
+    out[at..at + bytes.len()].copy_from_slice(bytes);
+}
+
+/// Check that `bytes` is exactly `size` long.
+const fn exact(bytes: &[u8], size: usize) -> Result<(), AbiError> {
+    if bytes.len() < size {
+        Err(AbiError::Truncated)
+    } else if bytes.len() > size {
+        Err(AbiError::WrongLength)
+    } else {
+        Ok(())
+    }
+}
+
+macro_rules! wire_impl {
+    ($ty:ty, $tag:expr, $size:expr) => {
+        impl Wire for $ty {
+            const TAG: EnvelopeTag = $tag;
+            const SIZE: usize = $size;
+
+            fn encode_into(&self, out: &mut [u8]) -> Result<usize, AbiError> {
+                let dst = out.get_mut(..$size).ok_or(AbiError::BufferTooSmall)?;
+                dst.copy_from_slice(&self.to_bytes());
+                Ok($size)
+            }
+
+            fn decode(bytes: &[u8]) -> Result<Self, AbiError> {
+                exact(bytes, $size)?;
+                let mut array = [0u8; $size];
+                array.copy_from_slice(bytes);
+                Self::from_bytes(&array)
+            }
+        }
+    };
+}
+
+// ---------------------------------------------------------------------------
+// Handle
+
+/// A 64-bit generational capability handle: slot index plus the slot's
+/// generation at issue time. Generation 0 is never issued, so it is invalid.
+///
+/// Wire: index u32 LE, then generation u32 LE (8 bytes). Register form:
+/// `(generation << 32) | index`, the packing the syscall path already uses.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Handle {
+    index: u32,
+    generation: u32,
+}
+
+impl Handle {
+    pub const SIZE: usize = 8;
+
+    /// Build a handle. Fails with [`AbiError::InvalidHandle`] on generation 0.
+    pub const fn new(index: u32, generation: u32) -> Result<Self, AbiError> {
+        if generation == 0 {
+            Err(AbiError::InvalidHandle)
+        } else {
+            Ok(Self { index, generation })
+        }
+    }
+
+    pub const fn index(self) -> u32 {
+        self.index
+    }
+
+    pub const fn generation(self) -> u32 {
+        self.generation
+    }
+
+    /// Register form: `(generation << 32) | index`.
+    pub const fn to_raw(self) -> u64 {
+        ((self.generation as u64) << 32) | self.index as u64
+    }
+
+    /// Parse the register form. Fails closed on generation 0.
+    pub const fn from_raw(raw: u64) -> Result<Self, AbiError> {
+        Self::new(raw as u32, (raw >> 32) as u32)
+    }
+
+    pub fn to_bytes(&self) -> [u8; 8] {
+        let mut out = [0u8; 8];
+        put(&mut out, 0, &self.index.to_le_bytes());
+        put(&mut out, 4, &self.generation.to_le_bytes());
+        out
+    }
+
+    pub const fn from_bytes(bytes: &[u8; 8]) -> Result<Self, AbiError> {
+        Self::new(get_u32(bytes, 0), get_u32(bytes, 4))
+    }
+}
+
+wire_impl!(Handle, EnvelopeTag::Handle, 8);
+
+impl TryFrom<caps::Handle> for Handle {
+    type Error = AbiError;
+    fn try_from(handle: caps::Handle) -> Result<Self, AbiError> {
+        Self::new(handle.index, handle.generation)
+    }
+}
+
+impl From<Handle> for caps::Handle {
+    fn from(handle: Handle) -> Self {
+        caps::Handle {
+            index: handle.index,
+            generation: handle.generation,
+        }
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Plain identifiers
+
+macro_rules! id_type {
+    ($(#[$doc:meta])* $name:ident, $int:ty, $size:expr, $tag:expr, $get:ident) => {
+        $(#[$doc])*
+        #[repr(transparent)]
+        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+        pub struct $name(pub $int);
+
+        impl $name {
+            pub const SIZE: usize = $size;
+
+            pub const fn to_bytes(&self) -> [u8; $size] {
+                self.0.to_le_bytes()
+            }
+
+            pub const fn from_bytes(bytes: &[u8; $size]) -> Result<Self, AbiError> {
+                Ok(Self($get(bytes, 0)))
+            }
+        }
+
+        wire_impl!($name, $tag, $size);
+    };
+}
+
+id_type!(
+    /// Identity of a task. Wire: u32 LE. Every value is well formed.
+    TaskId, u32, 4, EnvelopeTag::TaskId, get_u32
+);
+id_type!(
+    /// Identity of a kernel object. Wire: u64 LE. Every value is well formed.
+    ObjectId, u64, 8, EnvelopeTag::ObjectId, get_u64
+);
+id_type!(
+    /// Identity of a kernel message channel. Wire: u32 LE.
+    ChannelId, u32, 4, EnvelopeTag::ChannelId, get_u32
+);
+id_type!(
+    /// Identity of a device. Wire: u32 LE.
+    DeviceId, u32, 4, EnvelopeTag::DeviceId, get_u32
+);
+
+// ---------------------------------------------------------------------------
+// ResourceId
+
+/// What kind of resource a capability names. Discriminants are frozen and
+/// never reused; 0 is invalid.
+#[repr(u16)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ResourceKind {
+    Console = 1,
+    Channel = 2,
+    Object = 3,
+    Device = 4,
+    MemoryRegion = 5,
+}
+
+impl ResourceKind {
+    pub const fn from_u16(value: u16) -> Result<Self, AbiError> {
+        match value {
+            1 => Ok(Self::Console),
+            2 => Ok(Self::Channel),
+            3 => Ok(Self::Object),
+            4 => Ok(Self::Device),
+            5 => Ok(Self::MemoryRegion),
+            _ => Err(AbiError::UnknownDiscriminant),
+        }
+    }
+
+    pub const fn to_u16(self) -> u16 {
+        self as u16
+    }
+}
+
+/// A typed resource reference. Wire: kind u16 LE, reserved u16 (zero),
+/// id u32 LE (8 bytes). `id` is the kernel's resource number for that kind.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ResourceId {
+    kind: ResourceKind,
+    reserved: u16,
+    id: u32,
+}
+
+impl ResourceId {
+    pub const SIZE: usize = 8;
+
+    pub const fn new(kind: ResourceKind, id: u32) -> Self {
+        Self {
+            kind,
+            reserved: 0,
+            id,
+        }
+    }
+
+    pub const fn kind(self) -> ResourceKind {
+        self.kind
+    }
+
+    pub const fn id(self) -> u32 {
+        self.id
+    }
+
+    pub fn to_bytes(&self) -> [u8; 8] {
+        let mut out = [0u8; 8];
+        put(&mut out, 0, &self.kind.to_u16().to_le_bytes());
+        // Bytes 2..4 reserved, written as zero.
+        put(&mut out, 4, &self.id.to_le_bytes());
+        out
+    }
+
+    pub const fn from_bytes(bytes: &[u8; 8]) -> Result<Self, AbiError> {
+        let kind = match ResourceKind::from_u16(get_u16(bytes, 0)) {
+            Ok(kind) => kind,
+            Err(e) => return Err(e),
+        };
+        if get_u16(bytes, 2) != 0 {
+            return Err(AbiError::ReservedNonZero);
+        }
+        Ok(Self::new(kind, get_u32(bytes, 4)))
+    }
+}
+
+wire_impl!(ResourceId, EnvelopeTag::ResourceId, 8);
+
+// ---------------------------------------------------------------------------
+// Rights
+
+/// Capability rights. Wire: u32 LE. Bits 0 to 5 are defined; bits 6 to 31
+/// are reserved and must be zero.
+#[repr(transparent)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Rights(u32);
+
+impl Rights {
+    pub const SIZE: usize = 4;
+    pub const NONE: Self = Self(0);
+    pub const READ: Self = Self(1 << 0);
+    pub const WRITE: Self = Self(1 << 1);
+    pub const MAP: Self = Self(1 << 2);
+    pub const GRANT: Self = Self(1 << 3);
+    pub const DERIVE: Self = Self(1 << 4);
+    pub const REVOKE: Self = Self(1 << 5);
+    /// Mask of every bit defined in v1.
+    pub const DEFINED_MASK: u32 = (1 << 6) - 1;
+
+    /// Fails with [`AbiError::ReservedBits`] if any bit 6 to 31 is set.
+    pub const fn from_bits(bits: u32) -> Result<Self, AbiError> {
+        if bits & !Self::DEFINED_MASK == 0 {
+            Ok(Self(bits))
+        } else {
+            Err(AbiError::ReservedBits)
+        }
+    }
+
+    pub const fn bits(self) -> u32 {
+        self.0
+    }
+
+    pub const fn union(self, other: Self) -> Self {
+        Self(self.0 | other.0)
+    }
+
+    pub const fn to_bytes(&self) -> [u8; 4] {
+        self.0.to_le_bytes()
+    }
+
+    pub const fn from_bytes(bytes: &[u8; 4]) -> Result<Self, AbiError> {
+        Self::from_bits(get_u32(bytes, 0))
+    }
+}
+
+wire_impl!(Rights, EnvelopeTag::Rights, 4);
+
+impl From<caps::Rights> for Rights {
+    fn from(rights: caps::Rights) -> Self {
+        Self(rights.bits() as u32)
+    }
+}
+
+impl TryFrom<Rights> for caps::Rights {
+    type Error = AbiError;
+    fn try_from(rights: Rights) -> Result<Self, AbiError> {
+        let bits = u8::try_from(rights.0).map_err(|_| AbiError::ReservedBits)?;
+        caps::Rights::from_bits(bits).ok_or(AbiError::ReservedBits)
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Capability
+
+/// A capability as data: which resource and which rights. Wire: resource
+/// (8 bytes), rights u32 LE, reserved u32 (zero); 16 bytes.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Capability {
+    resource: ResourceId,
+    rights: Rights,
+    reserved: u32,
+}
+
+impl Capability {
+    pub const SIZE: usize = 16;
+
+    pub const fn new(resource: ResourceId, rights: Rights) -> Self {
+        Self {
+            resource,
+            rights,
+            reserved: 0,
+        }
+    }
+
+    pub const fn resource(self) -> ResourceId {
+        self.resource
+    }
+
+    pub const fn rights(self) -> Rights {
+        self.rights
+    }
+
+    pub fn to_bytes(&self) -> [u8; 16] {
+        let mut out = [0u8; 16];
+        put(&mut out, 0, &self.resource.to_bytes());
+        put(&mut out, 8, &self.rights.to_bytes());
+        // Bytes 12..16 reserved, written as zero.
+        out
+    }
+
+    pub const fn from_bytes(bytes: &[u8; 16]) -> Result<Self, AbiError> {
+        let resource = match ResourceId::from_bytes(&[
+            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
+        ]) {
+            Ok(resource) => resource,
+            Err(e) => return Err(e),
+        };
+        let rights = match Rights::from_bits(get_u32(bytes, 8)) {
+            Ok(rights) => rights,
+            Err(e) => return Err(e),
+        };
+        if get_u32(bytes, 12) != 0 {
+            return Err(AbiError::ReservedNonZero);
+        }
+        Ok(Self::new(resource, rights))
+    }
+}
+
+wire_impl!(Capability, EnvelopeTag::Capability, 16);
+
+// ---------------------------------------------------------------------------
+// MemoryRegion
+
+/// A bounded memory extent in pages. Wire: base u64 LE, pages u32 LE,
+/// reserved u32 (zero); 16 bytes.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct MemoryRegion {
+    base: u64,
+    pages: u32,
+    reserved: u32,
+}
+
+impl MemoryRegion {
+    pub const SIZE: usize = 16;
+
+    pub const fn new(base: u64, pages: u32) -> Self {
+        Self {
+            base,
+            pages,
+            reserved: 0,
+        }
+    }
+
+    pub const fn base(self) -> u64 {
+        self.base
+    }
+
+    pub const fn pages(self) -> u32 {
+        self.pages
+    }
+
+    pub fn to_bytes(&self) -> [u8; 16] {
+        let mut out = [0u8; 16];
+        put(&mut out, 0, &self.base.to_le_bytes());
+        put(&mut out, 8, &self.pages.to_le_bytes());
+        // Bytes 12..16 reserved, written as zero.
+        out
+    }
+
+    pub const fn from_bytes(bytes: &[u8; 16]) -> Result<Self, AbiError> {
+        if get_u32(bytes, 12) != 0 {
+            return Err(AbiError::ReservedNonZero);
+        }
+        Ok(Self::new(get_u64(bytes, 0), get_u32(bytes, 8)))
+    }
+}
+
+wire_impl!(MemoryRegion, EnvelopeTag::MemoryRegion, 16);
+
+// ---------------------------------------------------------------------------
+// Message
+
+/// Fixed-size typed IPC message. Wire (56 bytes): kind u32 LE at 0,
+/// reserved u32 (zero) at 4, payload 3 x u64 LE at 8, region at 32,
+/// object u64 LE at 48. Field order matches the typed IPC message.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Message {
+    kind: u32,
+    reserved: u32,
+    payload: [u64; 3],
+    region: MemoryRegion,
+    object: ObjectId,
+}
+
+impl Message {
+    pub const SIZE: usize = 56;
+
+    pub const fn new(kind: u32, payload: [u64; 3], region: MemoryRegion, object: ObjectId) -> Self {
+        Self {
+            kind,
+            reserved: 0,
+            payload,
+            region,
+            object,
+        }
+    }
+
+    pub const fn kind(self) -> u32 {
+        self.kind
+    }
+
+    pub const fn payload(self) -> [u64; 3] {
+        self.payload
+    }
+
+    pub const fn region(self) -> MemoryRegion {
+        self.region
+    }
+
+    pub const fn object(self) -> ObjectId {
+        self.object
+    }
+
+    pub fn to_bytes(&self) -> [u8; 56] {
+        let mut out = [0u8; 56];
+        put(&mut out, 0, &self.kind.to_le_bytes());
+        // Bytes 4..8 reserved, written as zero.
+        put(&mut out, 8, &self.payload[0].to_le_bytes());
+        put(&mut out, 16, &self.payload[1].to_le_bytes());
+        put(&mut out, 24, &self.payload[2].to_le_bytes());
+        put(&mut out, 32, &self.region.to_bytes());
+        put(&mut out, 48, &self.object.to_bytes());
+        out
+    }
+
+    pub fn from_bytes(bytes: &[u8; 56]) -> Result<Self, AbiError> {
+        if get_u32(bytes, 4) != 0 {
+            return Err(AbiError::ReservedNonZero);
+        }
+        let region = MemoryRegion::decode(&bytes[32..48])?;
+        Ok(Self::new(
+            get_u32(bytes, 0),
+            [get_u64(bytes, 8), get_u64(bytes, 16), get_u64(bytes, 24)],
+            region,
+            ObjectId(get_u64(bytes, 48)),
+        ))
+    }
+}
+
+wire_impl!(Message, EnvelopeTag::Message, 56);
+
+// ---------------------------------------------------------------------------
+// Envelope
+
+/// Type tag in an envelope header. Discriminants are frozen and never reused;
+/// 0 is invalid.
+#[repr(u16)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum EnvelopeTag {
+    Handle = 1,
+    TaskId = 2,
+    ObjectId = 3,
+    ChannelId = 4,
+    DeviceId = 5,
+    ResourceId = 6,
+    Rights = 7,
+    Capability = 8,
+    MemoryRegion = 9,
+    Message = 10,
+}
+
+impl EnvelopeTag {
+    pub const fn from_u16(value: u16) -> Result<Self, AbiError> {
+        match value {
+            1 => Ok(Self::Handle),
+            2 => Ok(Self::TaskId),
+            3 => Ok(Self::ObjectId),
+            4 => Ok(Self::ChannelId),
+            5 => Ok(Self::DeviceId),
+            6 => Ok(Self::ResourceId),
+            7 => Ok(Self::Rights),
+            8 => Ok(Self::Capability),
+            9 => Ok(Self::MemoryRegion),
+            10 => Ok(Self::Message),
+            _ => Err(AbiError::UnknownTag),
+        }
+    }
+
+    pub const fn to_u16(self) -> u16 {
+        self as u16
+    }
+}
+
+/// Write `value` as header (tag, [`ABI_VERSION`], payload length) followed by
+/// its payload. Returns the number of bytes written.
+pub fn encode_enveloped<T: Wire>(value: &T, out: &mut [u8]) -> Result<usize, AbiError> {
+    let total = ENVELOPE_HEADER_SIZE + T::SIZE;
+    let dst = out.get_mut(..total).ok_or(AbiError::BufferTooSmall)?;
+    put(dst, 0, &T::TAG.to_u16().to_le_bytes());
+    put(dst, 2, &ABI_VERSION.to_le_bytes());
+    put(dst, 4, &(T::SIZE as u32).to_le_bytes());
+    value.encode_into(&mut dst[ENVELOPE_HEADER_SIZE..])?;
+    Ok(total)
+}
+
+/// Decode an enveloped `T`. Checks, in order: header present, version,
+/// tag known, tag matches `T`, length field equals `T::SIZE`, buffer holds
+/// exactly header plus payload, payload decodes.
+pub fn decode_enveloped<T: Wire>(bytes: &[u8]) -> Result<T, AbiError> {
+    if bytes.len() < ENVELOPE_HEADER_SIZE {
+        return Err(AbiError::Truncated);
+    }
+    if get_u16(bytes, 2) != ABI_VERSION {
+        return Err(AbiError::UnknownVersion);
+    }
+    if EnvelopeTag::from_u16(get_u16(bytes, 0))? != T::TAG {
+        return Err(AbiError::TagMismatch);
+    }
+    if get_u32(bytes, 4) as usize != T::SIZE {
+        return Err(AbiError::WrongLength);
+    }
+    T::decode(&bytes[ENVELOPE_HEADER_SIZE..])
+}
+
+// ---------------------------------------------------------------------------
+// Layout assertions. The wire encoding is the contract; these pin the
+// in-memory mirror so it cannot drift silently.
+
+const _: () = {
+    assert!(size_of::<Handle>() == Handle::SIZE);
+    assert!(align_of::<Handle>() == 4);
+    assert!(offset_of!(Handle, index) == 0);
+    assert!(offset_of!(Handle, generation) == 4);
+
+    assert!(size_of::<TaskId>() == TaskId::SIZE);
+    assert!(size_of::<ObjectId>() == ObjectId::SIZE);
+    assert!(size_of::<ChannelId>() == ChannelId::SIZE);
+    assert!(size_of::<DeviceId>() == DeviceId::SIZE);
+
+    assert!(size_of::<ResourceKind>() == 2);
+    assert!(size_of::<ResourceId>() == ResourceId::SIZE);
+    assert!(align_of::<ResourceId>() == 4);
+    assert!(offset_of!(ResourceId, kind) == 0);
+    assert!(offset_of!(ResourceId, reserved) == 2);
+    assert!(offset_of!(ResourceId, id) == 4);
+
+    assert!(size_of::<Rights>() == Rights::SIZE);
+
+    assert!(size_of::<Capability>() == Capability::SIZE);
+    assert!(align_of::<Capability>() == 4);
+    assert!(offset_of!(Capability, resource) == 0);
+    assert!(offset_of!(Capability, rights) == 8);
+    assert!(offset_of!(Capability, reserved) == 12);
+
+    assert!(size_of::<MemoryRegion>() == MemoryRegion::SIZE);
+    assert!(align_of::<MemoryRegion>() == 8);
+    assert!(offset_of!(MemoryRegion, base) == 0);
+    assert!(offset_of!(MemoryRegion, pages) == 8);
+    assert!(offset_of!(MemoryRegion, reserved) == 12);
+
+    assert!(size_of::<Message>() == Message::SIZE);
+    assert!(align_of::<Message>() == 8);
+    assert!(offset_of!(Message, kind) == 0);
+    assert!(offset_of!(Message, reserved) == 4);
+    assert!(offset_of!(Message, payload) == 8);
+    assert!(offset_of!(Message, region) == 32);
+    assert!(offset_of!(Message, object) == 48);
+
+    assert!(size_of::<EnvelopeTag>() == 2);
+};
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// Golden round trip: encode gives exactly `golden`, decoding `golden`
+    /// gives `value`, and re-encoding gives `golden` again. Also covers the
+    /// envelope form and every truncation and one-byte extension.
+    fn golden<T: Wire + Copy + PartialEq + core::fmt::Debug>(value: T, golden: &[u8]) {
+        assert_eq!(golden.len(), T::SIZE);
+        let mut buf = [0xAAu8; 64];
+        assert_eq!(value.encode_into(&mut buf), Ok(T::SIZE));
+        assert_eq!(&buf[..T::SIZE], golden);
+        let decoded = T::decode(golden).expect("golden bytes decode");
+        assert_eq!(decoded, value);
+        let mut again = [0x55u8; 64];
+        decoded.encode_into(&mut again).unwrap();
+        assert_eq!(&again[..T::SIZE], golden);
+
+        for len in 0..T::SIZE {
+            assert_eq!(T::decode(&golden[..len]), Err(AbiError::Truncated));
+        }
+        let mut long = [0u8; 65];
+        long[..T::SIZE].copy_from_slice(golden);
+        assert_eq!(T::decode(&long[..T::SIZE + 1]), Err(AbiError::WrongLength));
+        let mut small = [0u8; 64];
+        assert_eq!(
+            value.encode_into(&mut small[..T::SIZE - 1]),
+            Err(AbiError::BufferTooSmall)
+        );
+
+        // Envelope: header golden bytes, then payload golden bytes.
+        let mut env = [0u8; 72];
+        let n = encode_enveloped(&value, &mut env).unwrap();
+        assert_eq!(n, ENVELOPE_HEADER_SIZE + T::SIZE);
+        assert_eq!(&env[0..2], &T::TAG.to_u16().to_le_bytes());
+        assert_eq!(&env[2..4], &[1, 0]);
+        assert_eq!(&env[4..8], &(T::SIZE as u32).to_le_bytes());
+        assert_eq!(&env[8..n], golden);
+        assert_eq!(decode_enveloped::<T>(&env[..n]), Ok(value));
+        for len in 0..n {
+            assert_eq!(
+                decode_enveloped::<T>(&env[..len]),
+                Err(AbiError::Truncated),
+                "envelope truncated to {len}"
+            );
+        }
+        assert_eq!(
+            decode_enveloped::<T>(&env[..n + 1]),
+            Err(AbiError::WrongLength)
+        );
+        assert_eq!(
+            encode_enveloped(&value, &mut env[..n - 1]),
+            Err(AbiError::BufferTooSmall)
+        );
+    }
+
+    #[test]
+    fn handle_golden() {
+        let h = Handle::new(7, 0x0102_0304).unwrap();
+        golden(h, &[0x07, 0, 0, 0, 0x04, 0x03, 0x02, 0x01]);
+        assert_eq!(h.to_raw(), 0x0102_0304_0000_0007);
+        assert_eq!(Handle::from_raw(0x0102_0304_0000_0007), Ok(h));
+    }
+
+    #[test]
+    fn handle_raw_matches_syscall_packing() {
+        // user.rs packs (generation << 32) | index into x0.
+        let h = Handle::new(u32::MAX, u32::MAX).unwrap();
+        assert_eq!(h.to_raw(), u64::MAX);
+        let h = Handle::new(0, 1).unwrap();
+        assert_eq!(h.to_raw(), 1 << 32);
+        assert_eq!(Handle::from_raw(1 << 32), Ok(h));
+    }
+
+    #[test]
+    fn handle_generation_zero_fails_closed() {
+        assert_eq!(Handle::new(3, 0), Err(AbiError::InvalidHandle));
+        assert_eq!(Handle::from_raw(0), Err(AbiError::InvalidHandle));
+        assert_eq!(
+            Handle::from_raw(0x0000_0000_FFFF_FFFF),
+            Err(AbiError::InvalidHandle)
+        );
+        assert_eq!(
+            Handle::decode(&[1, 0, 0, 0, 0, 0, 0, 0]),
+            Err(AbiError::InvalidHandle)
+        );
+        let env = [1, 0, 1, 0, 8, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0];
+        assert_eq!(
+            decode_enveloped::<Handle>(&env),
+            Err(AbiError::InvalidHandle)
+        );
+        let forged = caps::Handle {
+            index: 0,
+            generation: 0,
+        };
+        assert_eq!(Handle::try_from(forged), Err(AbiError::InvalidHandle));
+    }
+
+    #[test]
+    fn handle_converts_with_caps_handle() {
+        let mut table = caps::CapTable::<4>::new(1);
+        let issued = table.insert(9, caps::Rights::READ).unwrap();
+        let wire = Handle::try_from(issued).unwrap();
+        assert_eq!(wire.generation(), issued.generation);
+        assert_eq!(caps::Handle::from(wire), issued);
+    }
+
+    #[test]
+    fn id_goldens() {
+        golden(TaskId(0x1122_3344), &[0x44, 0x33, 0x22, 0x11]);
+        golden(
+            ObjectId(0x0102_0304_0506_0708),
+            &[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01],
+        );
+        golden(ChannelId(0xA1B2_C3D4), &[0xD4, 0xC3, 0xB2, 0xA1]);
+        golden(DeviceId(0x42), &[0x42, 0, 0, 0]);
+    }
+
+    #[test]
+    fn resource_id_golden() {
+        golden(
+            ResourceId::new(ResourceKind::Channel, 0xBEEF),
+            &[0x02, 0x00, 0x00, 0x00, 0xEF, 0xBE, 0x00, 0x00],
+        );
+        let kinds = [
+            (ResourceKind::Console, 1u16),
+            (ResourceKind::Channel, 2),
+            (ResourceKind::Object, 3),
+            (ResourceKind::Device, 4),
+            (ResourceKind::MemoryRegion, 5),
+        ];
+        for (kind, value) in kinds {
+            assert_eq!(kind.to_u16(), value);
+            assert_eq!(ResourceKind::from_u16(value), Ok(kind));
+        }
+    }
+
+    #[test]
+    fn resource_id_rejects_unknown_kind_and_reserved() {
+        for kind in [0u16, 6, 0x00FF, 0xFFFF] {
+            let [a, b] = kind.to_le_bytes();
+            assert_eq!(
+                ResourceId::decode(&[a, b, 0, 0, 1, 0, 0, 0]),
+                Err(AbiError::UnknownDiscriminant)
+            );
+        }
+        assert_eq!(
+            ResourceId::decode(&[1, 0, 1, 0, 1, 0, 0, 0]),
+            Err(AbiError::ReservedNonZero)
+        );
+        assert_eq!(
+            ResourceId::decode(&[1, 0, 0, 0x80, 1, 0, 0, 0]),
+            Err(AbiError::ReservedNonZero)
+        );
+    }
+
+    #[test]
+    fn rights_golden() {
+        let rights = Rights::READ.union(Rights::WRITE).union(Rights::GRANT);
+        golden(rights, &[0x0B, 0, 0, 0]);
+        golden(Rights::NONE, &[0, 0, 0, 0]);
+        golden(Rights::from_bits(0x3F).unwrap(), &[0x3F, 0, 0, 0]);
+        assert_eq!(Rights::READ.bits(), caps::Rights::READ.bits() as u32);
+        assert_eq!(Rights::WRITE.bits(), caps::Rights::WRITE.bits() as u32);
+        assert_eq!(Rights::MAP.bits(), caps::Rights::MAP.bits() as u32);
+        assert_eq!(Rights::GRANT.bits(), caps::Rights::GRANT.bits() as u32);
+        assert_eq!(Rights::DERIVE.bits(), caps::Rights::DERIVE.bits() as u32);
+        assert_eq!(Rights::REVOKE.bits(), caps::Rights::REVOKE.bits() as u32);
+    }
+
+    #[test]
+    fn rights_reserved_bits_fail_closed() {
+        for bit in 6..32 {
+            let bits = 1u32 << bit;
+            assert_eq!(Rights::from_bits(bits), Err(AbiError::ReservedBits));
+            assert_eq!(
+                Rights::decode(&bits.to_le_bytes()),
+                Err(AbiError::ReservedBits)
+            );
+        }
+    }
+
+    #[test]
+    fn rights_convert_with_caps_rights() {
+        let kernel = caps::Rights::READ | caps::Rights::DERIVE;
+        let wire = Rights::from(kernel);
+        assert_eq!(wire.bits(), 0x11);
+        assert_eq!(caps::Rights::try_from(wire), Ok(kernel));
+    }
+
+    #[test]
+    fn capability_golden() {
+        let cap = Capability::new(
+            ResourceId::new(ResourceKind::Device, 0x1234_5678),
+            Rights::READ.union(Rights::MAP).union(Rights::REVOKE),
+        );
+        golden(
+            cap,
+            &[
+                0x04, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, // resource
+                0x25, 0x00, 0x00, 0x00, // rights
+                0x00, 0x00, 0x00, 0x00, // reserved
+            ],
+        );
+    }
+
+    #[test]
+    fn capability_fails_closed() {
+        let good = [4u8, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0];
+        assert!(Capability::decode(&good).is_ok());
+        let mut bad = good;
+        bad[15] = 1;
+        assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedNonZero));
+        let mut bad = good;
+        bad[8] = 0x40;
+        assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedBits));
+        let mut bad = good;
+        bad[11] = 0x80;
+        assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedBits));
+        let mut bad = good;
+        bad[0] = 0;
+        assert_eq!(Capability::decode(&bad), Err(AbiError::UnknownDiscriminant));
+        let mut bad = good;
+        bad[3] = 1;
+        assert_eq!(Capability::decode(&bad), Err(AbiError::ReservedNonZero));
+    }
+
+    #[test]
+    fn memory_region_golden() {
+        golden(
+            MemoryRegion::new(0x4000_0000, 16),
+            &[
+                0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, // base
+                0x10, 0x00, 0x00, 0x00, // pages
+                0x00, 0x00, 0x00, 0x00, // reserved
+            ],
+        );
+        let mut bad = MemoryRegion::new(1, 1).to_bytes();
+        bad[12] = 1;
+        assert_eq!(MemoryRegion::decode(&bad), Err(AbiError::ReservedNonZero));
+    }
+
+    fn sample_message() -> Message {
+        Message::new(
+            3,
+            [1, 0x2222, u64::MAX],
+            MemoryRegion::new(0x8000_1000, 2),
+            ObjectId(0x0A0B_0C0D_0E0F_1011),
+        )
+    }
+
+    const MESSAGE_GOLDEN: [u8; 56] = [
+        0x03, 0x00, 0x00, 0x00, // kind
+        0x00, 0x00, 0x00, 0x00, // reserved
+        0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // payload[0]
+        0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // payload[1]
+        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // payload[2]
+        0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, // region.base
+        0x02, 0x00, 0x00, 0x00, // region.pages
+        0x00, 0x00, 0x00, 0x00, // region reserved
+        0x11, 0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, // object
+    ];
+
+    #[test]
+    fn message_golden() {
+        golden(sample_message(), &MESSAGE_GOLDEN);
+    }
+
+    #[test]
+    fn message_reserved_fields_fail_closed() {
+        for at in [4usize, 7, 44, 47] {
+            let mut bad = MESSAGE_GOLDEN;
+            bad[at] = 1;
+            assert_eq!(
+                Message::decode(&bad),
+                Err(AbiError::ReservedNonZero),
+                "byte {at}"
+            );
+        }
+    }
+
+    #[test]
+    fn envelope_golden() {
+        let cap = Capability::new(ResourceId::new(ResourceKind::Console, 1), Rights::WRITE);
+        let mut out = [0u8; 24];
+        assert_eq!(encode_enveloped(&cap, &mut out), Ok(24));
+        let expected = [
+            0x08, 0x00, // tag: Capability
+            0x01, 0x00, // version 1
+            0x10, 0x00, 0x00, 0x00, // payload length 16
+            0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // resource
+            0x02, 0x00, 0x00, 0x00, // rights
+            0x00, 0x00, 0x00, 0x00, // reserved
+        ];
+        assert_eq!(out, expected);
+        assert_eq!(decode_enveloped::<Capability>(&expected), Ok(cap));
+    }
+
+    #[test]
+    fn envelope_fails_closed() {
+        let mut good = [0u8; 16];
+        encode_enveloped(&Handle::new(2, 5).unwrap(), &mut good).unwrap();
+        assert!(decode_enveloped::<Handle>(&good).is_ok());
+
+        for version in [0u16, 2, 0x0100, 0xFFFF] {
+            let mut bad = good;
+            bad[2..4].copy_from_slice(&version.to_le_bytes());
+            assert_eq!(
+                decode_enveloped::<Handle>(&bad),
+                Err(AbiError::UnknownVersion)
+            );
+        }
+        for tag in [0u16, 11, 0xFFFF] {
+            let mut bad = good;
+            bad[0..2].copy_from_slice(&tag.to_le_bytes());
+            assert_eq!(decode_enveloped::<Handle>(&bad), Err(AbiError::UnknownTag));
+        }
+        // A known tag for an 8-byte type that is not Handle.
+        let mut bad = good;
+        bad[0] = EnvelopeTag::ObjectId.to_u16() as u8;
+        assert_eq!(decode_enveloped::<Handle>(&bad), Err(AbiError::TagMismatch));
+        for len in [0u32, 7, 9, 16, u32::MAX] {
+            let mut bad = good;
+            bad[4..8].copy_from_slice(&len.to_le_bytes());
+            assert_eq!(decode_enveloped::<Handle>(&bad), Err(AbiError::WrongLength));
+        }
+        let mut bad = good;
+        bad[12] = 0;
+        bad[13] = 0;
+        bad[14] = 0;
+        bad[15] = 0;
+        assert_eq!(
+            decode_enveloped::<Handle>(&bad),
+            Err(AbiError::InvalidHandle)
+        );
+    }
+
+    #[test]
+    fn tags_are_distinct_and_round_trip() {
+        let tags = [
+            (EnvelopeTag::Handle, <Handle as Wire>::TAG),
+            (EnvelopeTag::TaskId, <TaskId as Wire>::TAG),
+            (EnvelopeTag::ObjectId, <ObjectId as Wire>::TAG),
+            (EnvelopeTag::ChannelId, <ChannelId as Wire>::TAG),
+            (EnvelopeTag::DeviceId, <DeviceId as Wire>::TAG),
+            (EnvelopeTag::ResourceId, <ResourceId as Wire>::TAG),
+            (EnvelopeTag::Rights, <Rights as Wire>::TAG),
+            (EnvelopeTag::Capability, <Capability as Wire>::TAG),
+            (EnvelopeTag::MemoryRegion, <MemoryRegion as Wire>::TAG),
+            (EnvelopeTag::Message, <Message as Wire>::TAG),
+        ];
+        for (i, (tag, wire_tag)) in tags.iter().enumerate() {
+            assert_eq!(tag, wire_tag);
+            assert_eq!(tag.to_u16(), i as u16 + 1);
+            assert_eq!(EnvelopeTag::from_u16(tag.to_u16()), Ok(*tag));
+        }
+    }
+}
diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs
index eb4648b7..34905f71 100644
--- a/crates/aienos-kernel/src/lib.rs
+++ b/crates/aienos-kernel/src/lib.rs
@@ -10,6 +10,7 @@
 
 extern crate alloc;
 
+pub mod abi;
 pub mod acpi;
 pub mod arch;
 pub mod block;
diff --git a/docs/adr/0013-aienos-abi-v1.md b/docs/adr/0013-aienos-abi-v1.md
new file mode 100644
index 00000000..13c068cd
--- /dev/null
+++ b/docs/adr/0013-aienos-abi-v1.md
@@ -0,0 +1,197 @@
+# ADR 0013: AIENOS ABI v1
+
+Status: Proposed
+Date: 2026-09-24
+Governing: [ADR 0012](0012-self-construction-capability-growth-and-generations.md) (rule 5: no native admission without enforcement), [issue #30](https://github.com/aien-dev/aienos/issues/30) (IPC and capability handles), [PR #106](https://github.com/aien-dev/aienos/pull/106) (typed IPC).
+Code: [`crates/aienos-kernel/src/abi.rs`](../../crates/aienos-kernel/src/abi.rs).
+
+## Context
+
+M3 puts a kernel-enforced boundary between tasks. Everything that crosses
+that boundary (capability handles in registers, typed IPC messages, rights
+masks, memory regions) is today defined only by Rust structs in `caps.rs`,
+`user.rs` and the typed IPC work in PR #106. That makes the contract an
+accident of the current code:
+
+1. `caps::Handle { index: u32, generation: u32 }` is not `repr(C)`. Its
+   register form `(generation << 32) | index` lives in private helpers in
+   `user.rs` and is unpacked with no validity check.
+2. `caps::Rights` is a `u8` whose reserved bits are rejected by the kernel,
+   but no document says which bits are reserved or how wide the field is on
+   the wire.
+3. Resources are opaque `u32` values with no kind.
+4. The IPC `Message` layout in PR #106 depends on `repr(C)` and the Rust
+   compiler's layout rules on AArch64.
+
+Generated components (ADR 0012) and future non-Rust or non-AArch64 peers
+need a contract they can implement from a document, and persisted
+capability records need a format that a later build can still read or
+reject safely. This ADR freezes that contract as ABI v1.
+
+## Decision
+
+AIENOS ABI v1 is a byte-level contract. Every ABI type has an explicit
+little-endian encoding defined here, independent of Rust in-memory layout,
+architecture, and pointer width. The reference encoder and decoder is
+`crates/aienos-kernel/src/abi.rs`; its golden-byte tests are the executable
+form of this document.
+
+### General rules
+
+- Byte order: little-endian for every multi-byte integer.
+- Only fixed-width unsigned integers (`u16`, `u32`, `u64`) and fixed arrays
+  of them appear on the wire. No `usize`, `isize`, pointers, `Vec`, `String`,
+  `&str`, floating point, booleans, or compiler-chosen enum layout.
+- Every type has one fixed size. There is no implicit padding: every byte is
+  a named field or a named reserved field.
+- Reserved fields and reserved bits are written as zero and must be zero on
+  decode.
+- Enum discriminants are explicit integers. 0 is never a valid discriminant.
+- Decoding requires the exact size. Shorter input is `Truncated`; longer
+  input is `WrongLength`.
+
+### Types
+
+| Type | Size | Layout (byte offset: field) | Validity |
+|---|---|---|---|
+| `Handle` | 8 | 0: index u32; 4: generation u32 | generation != 0 |
+| `TaskId` | 4 | 0: u32 | any value |
+| `ObjectId` | 8 | 0: u64 | any value |
+| `ChannelId` | 4 | 0: u32 | any value |
+| `DeviceId` | 4 | 0: u32 | any value |
+| `ResourceId` | 8 | 0: kind u16; 2: reserved u16; 4: id u32 | kind in 1..=5; reserved == 0 |
+| `Rights` | 4 | 0: u32 bit mask | bits 6 to 31 == 0 |
+| `Capability` | 16 | 0: resource `ResourceId`; 8: rights `Rights`; 12: reserved u32 | nested rules; reserved == 0 |
+| `MemoryRegion` | 16 | 0: base u64; 8: pages u32; 12: reserved u32 | reserved == 0 |
+| `Message` | 56 | 0: kind u32; 4: reserved u32; 8: payload 3 x u64; 32: region `MemoryRegion`; 48: object `ObjectId` | reserved == 0; nested rules |
+
+`ResourceKind` discriminants: 1 Console, 2 Channel, 3 Object, 4 Device,
+5 MemoryRegion. `ResourceId.id` is the kernel's resource number within that
+kind (the existing opaque `u32` resource). It is not an `ObjectId`; an
+`ObjectId` is a separate 64-bit identity carried in messages.
+
+`Rights` bits: 0 READ, 1 WRITE, 2 MAP, 3 GRANT, 4 DERIVE, 5 REVOKE. The wire
+field is 32 bits so new rights can be added without changing the size; the
+kernel's in-memory `caps::Rights` stays `u8` and converts at the boundary.
+
+`Message` keeps the field order of the typed IPC message in PR #106. Its
+`_pad` word is the reserved field at offset 4. `Message.kind` is opaque to
+this ABI; the IPC layer assigns meaning to it.
+
+### Handles
+
+A handle is 64 bits: a 32-bit slot index plus the 32-bit generation of that
+slot when the handle was issued. The register form, used in `x0` by the
+syscall path, is `(generation << 32) | index`.
+
+Why 64-bit generational rather than a 32-bit handle:
+
+- Stale-handle protection. When a slot is freed and reused, its generation
+  goes up, so an old handle to the same index no longer matches and is
+  refused. A task cannot reach a new resource through a handle it kept
+  from an old one.
+- Generations never wrap. They start at 1 on first use and a slot whose
+  generation reaches `u32::MAX` is retired rather than reused, so the same
+  (index, generation) pair is never issued twice for one table.
+- Generation 0 is never issued, so it is a reserved "no handle" value and
+  every decoder rejects it (`InvalidHandle`). Zeroed memory or a zeroed
+  register is never a valid handle.
+- 32 bits of index and 32 bits of generation both fit one AArch64 register
+  and one 64-bit word on any other architecture.
+
+### Versioned envelope
+
+Any ABI value that is persisted or transported outside a single syscall
+(capability records, messages written to storage or sent to another
+machine) is wrapped in an 8-byte envelope header followed by the payload:
+
+| Offset | Field | Rule |
+|---|---|---|
+| 0 | tag u16 | known `EnvelopeTag`, and equal to the expected type |
+| 2 | version u16 | must equal `ABI_VERSION` (1) |
+| 4 | length u32 | payload length in bytes, must equal the type's size |
+| 8 | payload | exactly `length` bytes |
+
+`EnvelopeTag` discriminants: 1 Handle, 2 TaskId, 3 ObjectId, 4 ChannelId,
+5 DeviceId, 6 ResourceId, 7 Rights, 8 Capability, 9 MemoryRegion,
+10 Message. The header layout itself is fixed for every future version, so
+any reader can always find the version and length.
+
+Decode checks run in this order and stop at the first failure: header
+present, version, tag known, tag matches, length field, total buffer size,
+payload.
+
+### Errors
+
+Decoding fails closed. Each failure has its own error:
+
+| Error | Cause |
+|---|---|
+| `Truncated` | input shorter than required |
+| `WrongLength` | input longer than the type, or envelope length field wrong |
+| `UnknownVersion` | envelope version is not 1 |
+| `UnknownTag` | envelope tag not defined |
+| `TagMismatch` | envelope tag defined but for another type |
+| `ReservedNonZero` | a reserved field is not zero |
+| `ReservedBits` | a reserved rights bit is set |
+| `UnknownDiscriminant` | a resource kind is not defined |
+| `InvalidHandle` | handle generation is 0 |
+| `BufferTooSmall` | output buffer too small when encoding |
+
+### Compatibility and extension
+
+- ABI v1 is frozen. The sizes, offsets, byte order, discriminants and
+  validity rules above do not change for version 1.
+- New fields are added only by giving meaning to a reserved field or reserved
+  bit, or by defining a new version. A v1 decoder keeps rejecting nonzero
+  reserved fields, so an old reader refuses a newer record instead of
+  misreading it.
+- Discriminants (`ResourceKind`, `EnvelopeTag`) are append only and never
+  reused, even after a kind or tag is retired.
+- A new version gets a new `ABI_VERSION` value. A decoder that does not know
+  a version rejects it with `UnknownVersion`; it never guesses.
+- Register calling conventions for individual syscalls are outside this ADR;
+  they carry v1 values in the register form given here.
+
+### Relation to AEGIS
+
+This ABI is kernel enforcement: it defines what a well-formed handle,
+capability, or message is, and the kernel refuses anything else before any
+policy runs. AEGIS is runtime policy: it decides whether a well-formed,
+correctly authorized request should be allowed for this owner and moment
+(ADR 0004, ADR 0012 rule 4). AEGIS never widens what the kernel accepts, and
+a malformed value never reaches AEGIS.
+
+## Invariants
+
+1. Every ABI v1 type has exactly one byte encoding, fixed in size, little
+   endian, with no implicit padding.
+2. Encode then decode returns the same value, and decode then encode returns
+   the same bytes, for every valid value. Golden-byte tests pin this for every
+   type.
+3. Decoding never accepts: short or long input, nonzero reserved fields or
+   bits, unknown discriminants, unknown versions, mismatched tags, or
+   generation-0 handles.
+4. Handle generations start at 1 and never wrap; a retired slot is never
+   reissued.
+5. No ABI type contains `usize`, `isize`, pointers, heap types, or
+   compiler-chosen enum layout. `const` assertions pin the size, alignment and
+   field offsets of every in-memory mirror.
+6. Discriminants are never reused.
+7. No em dashes or en dashes in this document or the ABI code comments.
+
+## Consequences
+
+- `abi.rs` is the reference contract. `caps.rs`, `user.rs` and `ipc.rs`
+  adopt these types in a later change (after PR #106 lands); until then
+  `abi.rs` provides lossless conversions to and from `caps::Handle` and
+  `caps::Rights`.
+- Non-Rust and non-AArch64 implementations (other languages, other
+  machines through Fabric, generated components under ADR 0012) can
+  implement the ABI from this document and check themselves against the
+  golden bytes in the tests.
+- Persisted capability records and Generation manifests (ADR 0012) can use
+  the envelope and be rejected safely by a build that does not understand
+  them.
+- Any change to a v1 layout is a breaking change and needs a new version and
+  a new ADR.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index b0677e2b..ec03fe87 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -18,6 +18,7 @@ This directory documents the key architectural decisions and formal technical sp
 | [ADR 0010](0010-fabric-machine-identity-and-capability-advertisement.md) | Fabric Machine Identity and Capability Advertisement | Proposed (post-M6) | 2026-09-24 | [`ARCHITECTURE.md` §2](../ARCHITECTURE.md); [`BLUEPRINT.md` §21, §25, §26](../BLUEPRINT.md); [`MILESTONES.md` Phase 8](../MILESTONES.md); [ADR 0004](0004-reversibility-definition-and-network-effect-boundary.md); [ADR 0007](0007-continuous-existence-provisioning-once.md); [issue #37](https://github.com/aien-dev/aienos/issues/37) |
 | [ADR 0011](0011-machine-1-hardware-test-rig.md) | Machine 1 Hardware Test Rig (Power, Capture, Input) | Proposed | 2026-09-24 | [`MILESTONES.md` section 0, gate M2C](../MILESTONES.md); [`HARDWARE_TEST_RIG.md`](../HARDWARE_TEST_RIG.md); [`NATIVE_BOOT_ONE_TIME.md`](../NATIVE_BOOT_ONE_TIME.md) |
 | [ADR 0012](0012-self-construction-capability-growth-and-generations.md) | Self-Construction, Capability Growth, and Reversible System Generations | Accepted | 2026-09-24 | [ADR 0002](0002-incumbent-os-as-migration-environment.md); [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md); [ADR 0007](0007-continuous-existence-provisioning-once.md); [`ROADMAP.md`](../../ROADMAP.md) (SEED-0A, SEED-0B) |
+| [ADR 0013](0013-aienos-abi-v1.md) | AIENOS ABI v1 | Proposed | 2026-09-24 | [ADR 0012](0012-self-construction-capability-growth-and-generations.md); [ADR 0004](0004-reversibility-definition-and-network-effect-boundary.md); [issue #30](https://github.com/aien-dev/aienos/issues/30); [PR #106](https://github.com/aien-dev/aienos/pull/106); [`abi.rs`](../../crates/aienos-kernel/src/abi.rs) |
 
 ---