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

closed derived 45fe09aeec7358d3 #227

Imported from GitHub aien-dev/aienux#227 (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 899ef3f84472370878c7a4da5da8547b4920d991 · Head 4d238185545231f04b49950694debe529554abd9

Fetch it

A git bundle of the pull request's head, 20718 bytes.

curl -fsSL https://interplane.io/drakestapleton/aienux/patches/45fe09aeec7358d3.bundle -o 45fe09aeec7358d3.bundle
git fetch 45fe09aeec7358d3.bundle refs/pull/227/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aienux
227
4d238185545231f04b49950694debe529554abd9
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":227,"url":"https://github.com/aien-dev/aienux/pull/227","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:00Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/native/kernel/Makefile b/native/kernel/Makefile
index f9c89be9..675e2dce 100644
--- a/native/kernel/Makefile
+++ b/native/kernel/Makefile
@@ -30,6 +30,9 @@
 #                        (also builds the handoff_check reserved0 mutant
 #                        and requires test_handoff to FAIL against it)
 #   make sanitize        same under ASan + UBSan    -> CK_CORE_HOST: PASS
+#   make continuity-mutants
+#                        TEST-only -D mutants of svc/continuity_codec.c must
+#                        each fail test_continuity_codec -> CK_CONTINUITY_CODEC_MUTANTS: PASS
 #   make stage-test | stage-sanitize | stage-free   stage host tests (stage.mk)
 #   make print-kcflags   flags stage code must be built with
 #   make udp-echo        host UDP echo helper for scripts/qemu_ck_net_test.sh:
@@ -321,7 +324,8 @@ $(FULL_EFI): $(FULL_ELF)
 HOST_SRCS := $(KDIR)/core/fmt.c $(KDIR)/core/acpi.c $(KDIR)/core/smmu.c $(KDIR)/mm/frames.c \
 	$(KDIR)/mm/pt.c $(KDIR)/mm/heap.c $(KDIR)/core/sched.c $(KDIR)/core/ipc.c $(KDIR)/core/entropy.c \
 	$(KDIR)/core/handoff_check.c
-TESTS := test_fmt test_frames test_pt test_acpi test_heap test_smmu test_sched test_ipc test_artifact test_entropy test_handoff
+TESTS := test_fmt test_frames test_pt test_acpi test_heap test_smmu test_sched test_ipc test_artifact test_entropy test_handoff \
+	test_continuity_codec
 HCFLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -I$(KDIR)/core -I$(KDIR)/mm -I$(KDIR)/tests -I$(BOOT)
 SANFLAGS := -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer
 
@@ -374,6 +378,43 @@ $(OUT)/host-san/test_artifact: $(KDIR)/tests/test_artifact.c $(ART_HOST_DEPS) $(
 	@mkdir -p $(dir $@)
 	$(HOSTCC) $(HCFLAGS) $(SANFLAGS) $(ART_HOST_INC) -o $@ $< $(ART_HOST_SRCS)
 
+# Continuity codec (C port cut 1, contract CONTINUITY_RECOVERY_CONTRACT.md,
+# aienos#222): host test plus TEST-only -D mutants, each of which must make
+# the test print its FAIL verdict. Mutant flags are refused under
+# CK_HARDWARE_STAGING (svc/continuity_codec.h).
+CC_HOST_SRCS := $(KDIR)/svc/continuity_codec.c $(NATIVE)/argus/sha256.c $(NATIVE)/store/store_v1.c
+CC_HOST_INC := -I$(KDIR)/svc -I$(NATIVE)/argus -I$(NATIVE)/store
+CC_HOST_DEPS := $(CC_HOST_SRCS) $(KDIR)/svc/continuity_codec.h $(NATIVE)/argus/sha256.h \
+	$(NATIVE)/store/store_v1.h $(KDIR)/tests/ck_test.h
+CC_MUTANTS := CC_MUTANT_SKIP_TAKE_BOUND CC_MUTANT_ACCEPT_RESERVED CC_MUTANT_CHILD_INDEX_LE \
+	CC_MUTANT_TRUNCATE_AT_CAP
+
+$(OUT)/host/test_continuity_codec: $(KDIR)/tests/test_continuity_codec.c $(CC_HOST_DEPS)
+	@mkdir -p $(dir $@)
+	$(HOSTCC) $(HCFLAGS) $(CC_HOST_INC) -o $@ $< $(CC_HOST_SRCS)
+
+$(OUT)/host-san/test_continuity_codec: $(KDIR)/tests/test_continuity_codec.c $(CC_HOST_DEPS)
+	@mkdir -p $(dir $@)
+	$(HOSTCC) $(HCFLAGS) $(SANFLAGS) $(CC_HOST_INC) -o $@ $< $(CC_HOST_SRCS)
+
+continuity-mutants: $(OUT)/host/test_continuity_codec
+	@mkdir -p $(OUT)/host-mut; fail=0; \
+	$(OUT)/host/test_continuity_codec > $(OUT)/host-mut/base.log 2>&1 || { echo "unmutated test_continuity_codec fails"; fail=1; }; \
+	for m in $(CC_MUTANTS); do \
+	  b=$(OUT)/host-mut/test_continuity_codec_$$m; \
+	  if ! $(HOSTCC) $(HCFLAGS) $(CC_HOST_INC) -D$$m -o $$b $(KDIR)/tests/test_continuity_codec.c $(CC_HOST_SRCS); then \
+	    echo "mutant $$m: does not build (FAIL)"; fail=1; continue; fi; \
+	  if $$b > $$b.log 2>&1; then echo "mutant $$m: SURVIVED (FAIL)"; fail=1; \
+	  elif grep -q "^test_continuity_codec: FAIL" $$b.log; then \
+	    echo "mutant $$m: killed ($$(grep -c '^  FAIL ' $$b.log) checks failed)"; \
+	  else echo "mutant $$m: no FAIL verdict (crashed?) (FAIL)"; fail=1; fi; \
+	done; \
+	if $(HOSTCC) $(HCFLAGS) $(CC_HOST_INC) -DCK_HARDWARE_STAGING=1 -DCC_MUTANT_SKIP_TAKE_BOUND \
+	    -fsyntax-only $(KDIR)/svc/continuity_codec.c 2>/dev/null; then \
+	  echo "mutant flag accepted under CK_HARDWARE_STAGING (FAIL)"; fail=1; \
+	else echo "mutant flag refused under CK_HARDWARE_STAGING"; fi; \
+	if [ $$fail = 0 ]; then echo "CK_CONTINUITY_CODEC_MUTANTS: PASS"; else echo "CK_CONTINUITY_CODEC_MUTANTS: FAIL"; exit 1; fi
+
 ART_TOOL := $(OUT)/host/ck_artifact_tool
 $(ART_TOOL): $(KDIR)/tools/ck_artifact_tool.c $(ART_HOST_DEPS)
 	@mkdir -p $(dir $@)
@@ -408,4 +449,4 @@ clean:
 	rm -rf $(OUT)
 
 FORCE:
-.PHONY: all full test sanitize handoff-mutant clean print-kcflags udp-echo tool store-image owner-gen FORCE
+.PHONY: all full test sanitize handoff-mutant clean print-kcflags udp-echo tool store-image owner-gen continuity-mutants FORCE
diff --git a/native/kernel/svc/continuity_codec.c b/native/kernel/svc/continuity_codec.c
new file mode 100644
index 00000000..b7791096
--- /dev/null
+++ b/native/kernel/svc/continuity_codec.c
@@ -0,0 +1,667 @@
+/* continuity_codec.c -- see continuity_codec.h. Oracle: continuity.rs =
+ * crates/aienos-kernel/src/continuity.rs at aienos 4a116e5. Contract:
+ * native/kernel/CONTINUITY_RECOVERY_CONTRACT.md (aienos#222) sections 1-2.
+ * No allocation, no libc, no Store dependency. */
+#include "continuity_codec.h"
+#include "sha256.h" /* native/argus */
+
+static const uint8_t MAGIC_ROOT[8] = {'A', 'I', 'E', 'N', 'R', 'O', 'O', 'T'};     /* :34 */
+static const uint8_t MAGIC_MANIFEST[8] = {'A', 'I', 'E', 'N', 'M', 'A', 'N', 'I'}; /* :35 */
+static const uint8_t MAGIC_BRANCHES[8] = {'A', 'I', 'E', 'N', 'B', 'R', 'A', 'N'}; /* :36 */
+static const uint8_t MAGIC_WAL[8] = {'A', 'I', 'E', 'N', 'C', 'W', 'A', 'L'};      /* :37 */
+
+/* Fixed body sizes (bytes after the 16-byte header). */
+#define ROOT_BODY 96u          /* 32+16+32+8+1+7, continuity.rs:202 */
+#define MANIFEST_FIXED 120u    /* 32+32+8+8+32+2+6, continuity.rs:268 */
+#define STATE_FIXED 48u        /* 32+8+4+4, continuity.rs:394 */
+#define WAL_FIXED 16u          /* 8+4+4, continuity.rs:533 */
+
+/* K-1 reason text (PROPOSED; no Rust counterpart, contract 5.3). */
+static const char WHY_CAP[] = "continuity object exceeds the 16384-byte sealed Store cap";
+
+static int fail(const char **why, int cls, const char *w)
+{
+    if (why)
+        *why = w;
+    return cls;
+}
+
+/* ---- small byte helpers (no libc) ---- */
+static void cp(uint8_t *d, const uint8_t *s, size_t n)
+{
+    for (size_t i = 0; i < n; i++)
+        d[i] = s[i];
+}
+static int eq(const uint8_t *a, const uint8_t *b, size_t n)
+{
+    uint8_t x = 0;
+    for (size_t i = 0; i < n; i++)
+        x |= (uint8_t)(a[i] ^ b[i]);
+    return x == 0;
+}
+static int is_zero(const uint8_t *a, size_t n)
+{
+    uint8_t x = 0;
+    for (size_t i = 0; i < n; i++)
+        x |= a[i];
+    return x == 0;
+}
+/* Lexicographic order of two ids, as Rust [u8; 32] Ord (continuity.rs:361). */
+static int cmp32(const uint8_t *a, const uint8_t *b)
+{
+    for (size_t i = 0; i < 32; i++)
+        if (a[i] != b[i])
+            return a[i] < b[i] ? -1 : 1;
+    return 0;
+}
+static void put16(uint8_t *p, uint16_t v)
+{
+    p[0] = (uint8_t)v;
+    p[1] = (uint8_t)(v >> 8);
+}
+static void put32(uint8_t *p, uint32_t v)
+{
+    for (int i = 0; i < 4; i++)
+        p[i] = (uint8_t)(v >> (8 * i));
+}
+static void put64(uint8_t *p, uint64_t v)
+{
+    for (int i = 0; i < 8; i++)
+        p[i] = (uint8_t)(v >> (8 * i));
+}
+static uint64_t get_le(const uint8_t *p, int n)
+{
+    uint64_t v = 0;
+    for (int i = n - 1; i >= 0; i--)
+        v = (v << 8) | p[i];
+    return v;
+}
+
+/* ---- derivations ---- */
+void cc_root_branch_id(const uint8_t agent[32], uint8_t out[32])
+{
+    static const char D[] = "AIENOS_ROOT_BRANCH_v1:"; /* continuity.rs:72 */
+    sha256_ctx h;
+    sha256_init(&h);
+    sha256_update(&h, (const uint8_t *)D, sizeof D - 1);
+    sha256_update(&h, agent, 32);
+    sha256_final(&h, out);
+}
+
+void cc_child_branch_id(const uint8_t parent[32], uint64_t index, uint8_t out[32])
+{
+    static const char D[] = "AIENOS_CHILD_BRANCH_v1:"; /* continuity.rs:80 */
+    uint8_t ix[8];
+    for (int i = 0; i < 8; i++)
+#ifdef CC_MUTANT_CHILD_INDEX_LE
+        ix[i] = (uint8_t)(index >> (8 * i)); /* MUTANT MC-6: little-endian */
+#else
+        ix[i] = (uint8_t)(index >> (56 - 8 * i)); /* big-endian, continuity.rs:82 */
+#endif
+    sha256_ctx h;
+    sha256_init(&h);
+    sha256_update(&h, (const uint8_t *)D, sizeof D - 1);
+    sha256_update(&h, parent, 32);
+    sha256_update(&h, ix, 8);
+    sha256_final(&h, out);
+}
+
+int cc_object_id(uint16_t kind, const uint8_t *bytes, size_t len, uint8_t out[32])
+{
+    /* store/v1.rs:27 OBJECT_DOMAIN = b"AIENOS-STORE-OBJECT-V1\0" (23 bytes). */
+    static const char D[] = "AIENOS-STORE-OBJECT-V1";
+    if (!bytes || !out || kind == 0 || len == 0) /* v1.rs:64 */
+        return CC_E_ARG;
+    if ((uint64_t)len > 67108864u) /* MAX_OBJECT_BYTES, v1.rs:15, :67 */
+        return CC_E_ARG;
+    uint8_t d[12];
+    put16(d, kind);                     /* v1.rs:74 */
+    put16(d + 2, CC_STORE_OBJECT_VERSION); /* v1.rs:75 */
+    put64(d + 4, (uint64_t)len);        /* v1.rs:76 */
+    sha256_ctx h;
+    sha256_init(&h);
+    sha256_update(&h, (const uint8_t *)D, sizeof D); /* includes the NUL */
+    sha256_update(&h, d, sizeof d);
+    sha256_update(&h, bytes, len);
+    sha256_final(&h, out);
+    return CC_OK;
+}
+
+/* ---- strict reader (continuity.rs:97-166) ---- */
+struct rd {
+    const uint8_t *b;
+    size_t len, at;
+    const char *why;
+};
+
+/* Reader::take (continuity.rs:123-132): the one bounds check. */
+static int take(struct rd *r, size_t n, const uint8_t **p)
+{
+#ifndef CC_MUTANT_SKIP_TAKE_BOUND
+    if (n > r->len - r->at) { /* r->at <= r->len always holds here */
+        r->why = "truncated object";
+        return CC_E_CORRUPT;
+    }
+#endif
+    *p = r->b + r->at;
+    r->at += n;
+    return CC_OK;
+}
+static int rd_id(struct rd *r, uint8_t out[32])
+{
+    const uint8_t *p = 0;
+    int e = take(r, 32, &p);
+    if (!e)
+        cp(out, p, 32);
+    return e;
+}
+static int rd_uint(struct rd *r, int n, uint64_t *v)
+{
+    const uint8_t *p = 0;
+    int e = take(r, (size_t)n, &p);
+    if (!e)
+        *v = get_le(p, n);
+    return e;
+}
+/* Reader::zeros (continuity.rs:154-159). */
+static int rd_zeros(struct rd *r, size_t n)
+{
+    const uint8_t *p = 0;
+    int e = take(r, n, &p);
+    if (e)
+        return e;
+#ifndef CC_MUTANT_ACCEPT_RESERVED
+    if (!is_zero(p, n)) {
+        r->why = "nonzero reserved";
+        return CC_E_CORRUPT;
+    }
+#endif
+    return CC_OK;
+}
+/* Reader::finish (continuity.rs:160-165). */
+static int rd_finish(struct rd *r)
+{
+    if (r->at != r->len) {
+        r->why = "trailing bytes";
+        return CC_E_CORRUPT;
+    }
+    return CC_OK;
+}
+
+/* K-1 cap (PROPOSED) first, then Reader::open (continuity.rs:105-122). */
+static int rd_open(struct rd *r, const uint8_t *in, size_t len, const uint8_t magic[8])
+{
+    const uint8_t *p = 0;
+    uint64_t v = 0;
+    int e;
+    r->b = in;
+    r->len = len;
+    r->at = 0;
+    r->why = 0;
+    if (len > CC_MAX_OBJECT_BYTES) {
+        r->why = WHY_CAP;
+        return CC_E_LIMIT;
+    }
+    if ((e = take(r, 8, &p)))
+        return e;
+    if (!eq(p, magic, 8)) {
+        r->why = "bad magic";
+        return CC_E_CORRUPT;
+    }
+    if ((e = rd_uint(r, 2, &v)))
+        return e;
+    if (v != CC_FORMAT_VERSION) {
+        r->why = "unsupported continuity format version";
+        return CC_E_CORRUPT;
+    }
+    if ((e = rd_uint(r, 2, &v)))
+        return e;
+#ifndef CC_MUTANT_ACCEPT_RESERVED
+    if (v != 0) {
+        r->why = "nonzero header reserved";
+        return CC_E_CORRUPT;
+    }
+#endif
+    if ((e = rd_uint(r, 4, &v)))
+        return e;
+    if (v != (uint64_t)(len - CC_HEADER_BYTES)) {
+        r->why = "body length mismatch";
+        return CC_E_CORRUPT;
+    }
+    return CC_OK;
+}
+
+/* ---- writer: callers size-check first, so writes never overrun ---- */
+struct wr {
+    uint8_t *b;
+    size_t at;
+};
+static void w_bytes(struct wr *w, const uint8_t *s, size_t n)
+{
+    cp(w->b + w->at, s, n);
+    w->at += n;
+}
+static void w_zeros(struct wr *w, size_t n)
+{
+    for (size_t i = 0; i < n; i++)
+        w->b[w->at + i] = 0;
+    w->at += n;
+}
+static void w_u8(struct wr *w, uint8_t v)
+{
+    w->b[w->at++] = v;
+}
+static void w_u16(struct wr *w, uint16_t v)
+{
+    put16(w->b + w->at, v);
+    w->at += 2;
+}
+static void w_u32(struct wr *w, uint32_t v)
+{
+    put32(w->b + w->at, v);
+    w->at += 4;
+}
+static void w_u64(struct wr *w, uint64_t v)
+{
+    put64(w->b + w->at, v);
+    w->at += 8;
+}
+/* header() (continuity.rs:90-95). */
+static void w_header(struct wr *w, const uint8_t magic[8], size_t body)
+{
+    w_bytes(w, magic, 8);
+    w_u16(w, CC_FORMAT_VERSION);
+    w_u16(w, 0);
+    w_u32(w, (uint32_t)body);
+}
+
+/* Common encoder prologue: K-1 cap (PROPOSED), then the caller's buffer. */
+static int enc_begin(struct wr *w, uint8_t *out, size_t cap, size_t total,
+                     const char **why)
+{
+    if (total > CC_MAX_OBJECT_BYTES)
+        return fail(why, CC_E_LIMIT, WHY_CAP);
+    if (!out || cap < total)
+        return fail(why, CC_E_ARG, "output buffer too small");
+    w->b = out;
+    w->at = 0;
+    return CC_OK;
+}
+
+/* ---- AgentRoot (continuity.rs:204-247) ---- */
+int cc_root_encode(const struct cc_root *v, uint8_t *out, size_t cap, size_t *len,
+                   const char **why)
+{
+    struct wr w;
+    int e;
+    if (!v || !len)
+        return fail(why, CC_E_ARG, "null argument");
+    *len = 0;
+    /* ProvisionSource is a Rust enum (continuity.rs:186-191): no other value
+     * exists there, so another value is a caller bug here. */
+    if (v->source != CC_SOURCE_OPERATOR && v->source != CC_SOURCE_QUALIFICATION)
+        return fail(why, CC_E_ARG, "unknown provisioning source");
+    if ((e = enc_begin(&w, out, cap, CC_ROOT_BYTES, why)))
+        return e;
+    w_header(&w, MAGIC_ROOT, ROOT_BODY);   /* :207 */
+    w_bytes(&w, v->agent_id, 32);          /* :208 */
+    w_bytes(&w, v->store_uuid, 16);        /* :209 */
+    w_bytes(&w, v->root_branch, 32);       /* :210 */
+    w_u64(&w, v->provisioned_generation);  /* :211 */
+    w_u8(&w, v->source);                   /* :212 */
+    w_zeros(&w, 7);                        /* :213 */
+    *len = w.at;
+    return CC_OK;
+}
+
+int cc_root_decode(const uint8_t *in, size_t len, struct cc_root *v, const char **why)
+{
+    struct rd r;
+    uint64_t x = 0;
+    const uint8_t *p = 0;
+    int e;
+    uint8_t rb[32];
+    if (!in || !v)
+        return fail(why, CC_E_ARG, "null argument");
+    if ((e = rd_open(&r, in, len, MAGIC_ROOT)) || (e = rd_id(&r, v->agent_id)) || /* :218-219 */
+        (e = take(&r, 16, &p)))                                                   /* :221 */
+        return fail(why, e, r.why);
+    cp(v->store_uuid, p, 16);
+    if ((e = rd_id(&r, v->root_branch)) || (e = rd_uint(&r, 8, &x))) /* :222-223 */
+        return fail(why, e, r.why);
+    v->provisioned_generation = x;
+    if ((e = rd_uint(&r, 1, &x))) /* :224 */
+        return fail(why, e, r.why);
+    if (x != CC_SOURCE_OPERATOR && x != CC_SOURCE_QUALIFICATION) /* :224-228 */
+        return fail(why, CC_E_CORRUPT, "unknown provisioning source");
+    v->source = (uint8_t)x;
+    if ((e = rd_zeros(&r, 7)) || (e = rd_finish(&r))) /* :229-230 */
+        return fail(why, e, r.why);
+    if (is_zero(v->agent_id, 32)) /* :231-233 */
+        return fail(why, CC_E_CORRUPT, "zero agent id");
+    cc_root_branch_id(v->agent_id, rb);
+    if (!eq(rb, v->root_branch, 32)) /* :234-238 */
+        return fail(why, CC_E_CORRUPT, "root branch does not derive from agent");
+    return CC_OK;
+}
+
+/* ---- ContinuityManifest (continuity.rs:263-315) ---- */
+int cc_manifest_encode(const struct cc_manifest *v, uint8_t *out, size_t cap, size_t *len,
+                       const char **why)
+{
+    struct wr w;
+    int e;
+    if (!v || !len)
+        return fail(why, CC_E_ARG, "null argument");
+    *len = 0;
+    if (v->n_wal > CC_MAX_WAL_SEGMENTS) /* :265-267 */
+        return fail(why, CC_E_LIMIT, "too many cortex WAL segments");
+    size_t body = MANIFEST_FIXED + 32u * v->n_wal; /* :268 */
+    if ((e = enc_begin(&w, out, cap, CC_HEADER_BYTES + body, why)))
+        return e;
+    w_header(&w, MAGIC_MANIFEST, body);   /* :270 */
+    w_bytes(&w, v->root, 32);             /* :271 */
+    w_bytes(&w, v->previous, 32);         /* :272 (None = zero, :177-179) */
+    w_u64(&w, v->sequence);               /* :273 */
+    w_u64(&w, v->incarnation);            /* :274 */
+    w_bytes(&w, v->agent_state, 32);      /* :275 */
+    w_u16(&w, (uint16_t)v->n_wal);        /* :276 */
+    w_zeros(&w, 6);                       /* :277 */
+    for (uint32_t i = 0; i < v->n_wal; i++)
+        w_bytes(&w, v->wal[i], 32);       /* :278-280 */
+    *len = w.at;
+    return CC_OK;
+}
+
+int cc_manifest_decode(const uint8_t *in, size_t len, struct cc_manifest *v, const char **why)
+{
+    struct rd r;
+    uint64_t x = 0;
+    int e;
+    if (!in || !v)
+        return fail(why, CC_E_ARG, "null argument");
+    if ((e = rd_open(&r, in, len, MAGIC_MANIFEST)) || (e = rd_id(&r, v->root)) || /* :285-286 */
+        (e = rd_id(&r, v->previous)) || (e = rd_uint(&r, 8, &v->sequence)) ||     /* :287-288 */
+        (e = rd_uint(&r, 8, &v->incarnation)) || (e = rd_id(&r, v->agent_state)) || /* :289-290 */
+        (e = rd_uint(&r, 2, &x)) || (e = rd_zeros(&r, 6)))                       /* :291-292 */
+        return fail(why, e, r.why);
+    if (x > CC_MAX_WAL_SEGMENTS) /* :293-295 */
+        return fail(why, CC_E_CORRUPT, "too many cortex WAL segments");
+    v->n_wal = (uint32_t)x;
+    for (uint32_t i = 0; i < v->n_wal; i++)
+        if ((e = rd_id(&r, v->wal[i]))) /* :297-299 */
+            return fail(why, e, r.why);
+    if ((e = rd_finish(&r))) /* :300 */
+        return fail(why, e, r.why);
+    /* :301-305: sequence 0, or "sequence 1" differs from "no previous". */
+    if (v->sequence == 0 || (v->sequence == 1) != is_zero(v->previous, 32))
+        return fail(why, CC_E_CORRUPT, "manifest sequence/previous mismatch");
+    return CC_OK;
+}
+
+/* ---- AgentState branch table (continuity.rs:342-482) ---- */
+/* binary_search_by on the sorted ids (continuity.rs:358-362): index of id, or
+ * -1 with *ins = insertion point. */
+static long find_branch(const struct cc_state *s, const uint8_t id[32], uint32_t *ins)
+{
+    uint32_t lo = 0, hi = s->n;
+    while (lo < hi) {
+        uint32_t mid = lo + (hi - lo) / 2;
+        int c = cmp32(s->br[mid].id, id);
+        if (c == 0)
+            return (long)mid;
+        if (c < 0)
+            lo = mid + 1;
+        else
+            hi = mid;
+    }
+    if (ins)
+        *ins = lo;
+    return -1;
+}
+
+void cc_state_genesis(struct cc_state *s, const uint8_t agent[32], uint64_t written_at)
+{
+    cp(s->agent_id, agent, 32);
+    s->written_at = written_at;
+    s->n = 1;
+    cc_root_branch_id(agent, s->br[0].id);
+    for (int i = 0; i < 32; i++)
+        s->br[0].parent[i] = 0;
+    s->br[0].depth = 0;
+    s->br[0].forks = 0;
+}
+
+int cc_state_validate(const struct cc_state *s, const char **why)
+{
+    const char *bad = 0;
+    if (!s)
+        return fail(why, CC_E_ARG, "null argument");
+    if (s->n == 0 || s->n > CC_MAX_BRANCHES) /* :449-451 */
+        return fail(why, CC_E_CORRUPT, "branch count out of range");
+    for (uint32_t i = 0; i + 1 < s->n; i++) /* :452-454 */
+        if (cmp32(s->br[i].id, s->br[i + 1].id) >= 0)
+            return fail(why, CC_E_CORRUPT, "branches not strictly sorted");
+    uint8_t root[32], cid[32];
+    cc_root_branch_id(s->agent_id, root); /* :455 */
+    uint32_t roots = 0;
+    uint64_t children = 0;
+    for (uint32_t i = 0; i < s->n && !bad; i++) {
+        const struct cc_branch *b = &s->br[i];
+        if (is_zero(b->parent, 32)) { /* :460-465 */
+            if (!eq(b->id, root, 32) || b->depth != 0)
+                bad = "unexpected root branch";
+            roots++;
+            continue;
+        }
+        long pi = find_branch(s, b->parent, 0); /* :467 */
+        if (pi < 0) {
+            bad = "parent branch is absent";
+            break;
+        }
+        const struct cc_branch *p = &s->br[pi];
+        /* :468: any index in 0..parent.forks derives this id. The scan is
+         * capped at CC_MAX_BRANCHES: a table that passes the fork-sum check
+         * below has every forks <= 255, so the cap changes no accept/refuse
+         * outcome, only bounds the work (Rust scans up to forks, which an
+         * input controls; see the PR's oracle notes). */
+        uint64_t lim = p->forks < CC_MAX_BRANCHES ? p->forks : CC_MAX_BRANCHES;
+        int index_ok = 0;
+        for (uint64_t k = 0; k < lim && !index_ok; k++) {
+            cc_child_branch_id(b->parent, k, cid);
+            index_ok = eq(cid, b->id, 32);
+        }
+        if (!index_ok || p->depth == UINT32_MAX || b->depth != p->depth + 1) /* :469-471 */
+            bad = "branch lineage is inconsistent";
+        children++;
+    }
+    if (bad)
+        return fail(why, CC_E_CORRUPT, bad);
+    /* :476-479: sum of forks == number of children, exactly one root. The
+     * sum is checked: an overflowing sum can never equal children (<= 255). */
+    uint64_t forks = 0;
+    int over = 0;
+    for (uint32_t i = 0; i < s->n; i++) {
+        if (s->br[i].forks > UINT64_MAX - forks)
+            over = 1;
+        else
+            forks += s->br[i].forks;
+    }
+    if (roots != 1 || over || forks != children)
+        return fail(why, CC_E_CORRUPT, "fork indexes are not contiguous");
+    return CC_OK;
+}
+
+int cc_state_fork(struct cc_state *s, const uint8_t parent[32], uint8_t child_out[32],
+                  const char **why)
+{
+    if (!s || !parent || !child_out)
+        return fail(why, CC_E_ARG, "null argument");
+    if (s->n >= CC_MAX_BRANCHES) /* :366-368 */
+        return fail(why, CC_E_LIMIT, "too many branches");
+    long i = find_branch(s, parent, 0); /* :369-372 */
+    if (i < 0)
+        return fail(why, CC_E_CORRUPT, "fork parent is absent");
+    uint64_t index = s->br[i].forks; /* :373 */
+    uint32_t depth = s->br[i].depth;
+    struct cc_branch c;
+    cc_child_branch_id(parent, index, c.id); /* :375 */
+    cp(c.parent, parent, 32);
+    if (depth == UINT32_MAX) /* :377-379 */
+        return fail(why, CC_E_LIMIT, "branch depth");
+    c.depth = depth + 1;
+    c.forks = 0;
+    /* :382: the parent's fork count advances before the collision check, as
+     * in Rust (a collision leaves it advanced and returns Corrupt). */
+    s->br[i].forks = index + 1;
+    uint32_t at = 0;
+    if (find_branch(s, c.id, &at) >= 0) /* :383-387 */
+        return fail(why, CC_E_CORRUPT, "child branch id collision");
+    for (uint32_t k = s->n; k > at; k--) /* :388 insert keeps order */
+        s->br[k] = s->br[k - 1];
+    s->br[at] = c;
+    s->n++;
+    cp(child_out, c.id, 32);
+    return CC_OK;
+}
+
+int cc_state_encode(const struct cc_state *v, uint8_t *out, size_t cap, size_t *len,
+                    const char **why)
+{
+    struct wr w;
+    int e;
+    if (!v || !len)
+        return fail(why, CC_E_ARG, "null argument");
+    *len = 0;
+    if ((e = cc_state_validate(v, why))) /* :393 */
+        return e;
+    size_t body = STATE_FIXED + (size_t)CC_BRANCH_BYTES * v->n; /* :394 */
+    if ((e = enc_begin(&w, out, cap, CC_HEADER_BYTES + body, why)))
+        return e;
+    w_header(&w, MAGIC_BRANCHES, body); /* :396 */
+    w_bytes(&w, v->agent_id, 32);       /* :397 */
+    w_u64(&w, v->written_at);           /* :398 */
+    w_u32(&w, v->n);                    /* :399 */
+    w_zeros(&w, 4);                     /* :400 */
+    for (uint32_t i = 0; i < v->n; i++) {
+        w_bytes(&w, v->br[i].id, 32);     /* :402 */
+        w_bytes(&w, v->br[i].parent, 32); /* :403 */
+        w_u32(&w, v->br[i].depth);        /* :404 */
+        w_zeros(&w, 4);                   /* :405 */
+        w_u64(&w, v->br[i].forks);        /* :406 */
+    }
+    *len = w.at;
+    return CC_OK;
+}
+
+int cc_state_decode(const uint8_t *in, size_t len, struct cc_state *v, const char **why)
+{
+    struct rd r;
+    uint64_t x = 0;
+    int e;
+    if (!in || !v)
+        return fail(why, CC_E_ARG, "null argument");
+    if ((e = rd_open(&r, in, len, MAGIC_BRANCHES)) || (e = rd_id(&r, v->agent_id)) || /* :412-413 */
+        (e = rd_uint(&r, 8, &v->written_at)) || (e = rd_uint(&r, 4, &x)) ||           /* :414-415 */
+        (e = rd_zeros(&r, 4)))                                                         /* :416 */
+        return fail(why, e, r.why);
+    if (x == 0 || x > CC_MAX_BRANCHES) /* :417-419 */
+        return fail(why, CC_E_CORRUPT, "branch count out of range");
+    v->n = (uint32_t)x;
+    for (uint32_t i = 0; i < v->n; i++) {
+        struct cc_branch *b = &v->br[i];
+        uint64_t d = 0;
+        if ((e = rd_id(&r, b->id)) || (e = rd_id(&r, b->parent)) || /* :422-423 */
+            (e = rd_uint(&r, 4, &d)) || (e = rd_zeros(&r, 4)) ||    /* :424-425 */
+            (e = rd_uint(&r, 8, &b->forks)))                        /* :426 */
+            return fail(why, e, r.why);
+        b->depth = (uint32_t)d;
+    }
+    if ((e = rd_finish(&r))) /* :434 */
+        return fail(why, e, r.why);
+    return cc_state_validate(v, why); /* :440 */
+}
+
+/* ---- CortexWalSegment (continuity.rs:527-582) ---- */
+int cc_wal_encode(const struct cc_wal *v, uint8_t *out, size_t cap, size_t *len,
+                  const char **why)
+{
+    struct wr w;
+    int e;
+    if (!v || !len)
+        return fail(why, CC_E_ARG, "null argument");
+    *len = 0;
+    if (v->n == 0 || v->n > CC_MAX_WAL_RECORDS) /* :529-531 */
+        return fail(why, CC_E_LIMIT, "WAL segment record count");
+    size_t body = WAL_FIXED; /* :532 */
+    for (uint32_t i = 0; i < v->n; i++) {
+        const struct cc_record *rec = &v->rec[i];
+        if (rec->len == 0 || rec->len > CC_MAX_STATEMENT_BYTES) /* :534-536 */
+            return fail(why, CC_E_LIMIT, "statement length");
+        /* Epistemic is a Rust enum (:490-511): other values are a caller bug. */
+        if (rec->status < CC_EPI_DIRECT_OBSERVATION || rec->status > CC_EPI_OPERATOR_DECISION ||
+            !rec->statement)
+            return fail(why, CC_E_ARG, "bad record");
+        body += CC_WAL_RECORD_FIXED + rec->len; /* :537 */
+    }
+    uint32_t n = v->n;
+#ifdef CC_MUTANT_TRUNCATE_AT_CAP
+    /* MUTANT MC-11: silently drop records to fit the K-1 cap. */
+    while (n > 1 && CC_HEADER_BYTES + body > CC_MAX_OBJECT_BYTES) {
+        n--;
+        body -= CC_WAL_RECORD_FIXED + v->rec[n].len;
+    }
+#endif
+    if ((e = enc_begin(&w, out, cap, CC_HEADER_BYTES + body, why)))
+        return e;
+    w_header(&w, MAGIC_WAL, body); /* :540 */
+    w_u64(&w, v->sequence);        /* :541 */
+    w_u32(&w, n);                  /* :542 */
+    w_zeros(&w, 4);                /* :543 */
+    for (uint32_t i = 0; i < n; i++) {
+        const struct cc_record *rec = &v->rec[i];
+        w_u8(&w, rec->status);              /* :545 */
+        w_u8(&w, 0);                        /* :546 */
+        w_u16(&w, rec->len);                /* :547 */
+        w_bytes(&w, rec->evidence_hash, 32); /* :548 */
+        w_bytes(&w, rec->statement, rec->len); /* :549 */
+    }
+    *len = w.at;
+    return CC_OK;
+}
+
+int cc_wal_decode(const uint8_t *in, size_t len, struct cc_wal *v, const char **why)
+{
+    struct rd r;
+    uint64_t x = 0;
+    int e;
+    if (!in || !v)
+        return fail(why, CC_E_ARG, "null argument");
+    if ((e = rd_open(&r, in, len, MAGIC_WAL)) || (e = rd_uint(&r, 8, &v->sequence)) || /* :555-556 */
+        (e = rd_uint(&r, 4, &x)) || (e = rd_zeros(&r, 4)))                              /* :557-558 */
+        return fail(why, e, r.why);
+    if (x == 0 || x > CC_MAX_WAL_RECORDS) /* :559-561 */
+        return fail(why, CC_E_CORRUPT, "WAL segment record count");
+    v->n = (uint32_t)x;
+    for (uint32_t i = 0; i < v->n; i++) {
+        struct cc_record *rec = &v->rec[i];
+        uint64_t st = 0, l = 0;
+        const uint8_t *p = 0;
+        if ((e = rd_uint(&r, 1, &st))) /* :564 */
+            return fail(why, e, r.why);
+        if (st < CC_EPI_DIRECT_OBSERVATION || st > CC_EPI_OPERATOR_DECISION) /* :564-565 */
+            return fail(why, CC_E_CORRUPT, "unknown epistemic status");
+        if ((e = rd_zeros(&r, 1)) || (e = rd_uint(&r, 2, &l))) /* :566-567 */
+            return fail(why, e, r.why);
+        if (l == 0 || l > CC_MAX_STATEMENT_BYTES) /* :568-570 */
+            return fail(why, CC_E_CORRUPT, "statement length");
+        if ((e = rd_id(&r, rec->evidence_hash)) || (e = take(&r, (size_t)l, &p))) /* :571-572 */
+            return fail(why, e, r.why);
+        rec->status = (uint8_t)st;
+        rec->len = (uint16_t)l;
+        rec->statement = p;
+    }
+    if ((e = rd_finish(&r))) /* :579 */
+        return fail(why, e, r.why);
+    return CC_OK;
+}
diff --git a/native/kernel/svc/continuity_codec.h b/native/kernel/svc/continuity_codec.h
new file mode 100644
index 00000000..71c2c710
--- /dev/null
+++ b/native/kernel/svc/continuity_codec.h
@@ -0,0 +1,173 @@
+/* continuity_codec.h -- C port, cut 1: canonical encodings of the four M4
+ * continuity objects (AgentRoot, ContinuityManifest, AgentState branch table,
+ * CortexWalSegment), the branch-id derivations and the logical ObjectId.
+ *
+ * Contract: native/kernel/CONTINUITY_RECOVERY_CONTRACT.md (aienos#222,
+ * SPEC/PROPOSED), sections 1.1-1.7 and INV-1..INV-3. Oracle: the Rust kernel,
+ * crates/aienos-kernel/src/continuity.rs at aienos 4a116e5 ("continuity.rs"
+ * below). Every layout here cites the Rust line it must match byte for byte.
+ *
+ * Properties:
+ * - No allocation, no globals, no libc: caller-owned structs and buffers.
+ *   Needs only native/argus/sha256.{c,h}.
+ * - No dependence on the Store. The logical ObjectId is computed here with the
+ *   Store v1 rule (crates/aienos-kernel/src/store/v1.rs:27, :63-78); the host
+ *   test cross-checks it against sv1_object_id (native/store/store_v1.h:132).
+ * - Strict decoders (continuity.rs:97-166): every read bounds checked
+ *   ("truncated object"), reserved bytes zero ("nonzero reserved"), the whole
+ *   input consumed ("trailing bytes"). The error class and the Rust "why" text
+ *   are both returned.
+ * - K-1 (contract 5.3, PROPOSED): no continuity object larger than
+ *   CC_MAX_OBJECT_BYTES (16384, SS_MAX_PLAINTEXT, native/store/store_sealed.h:46)
+ *   is encoded or decoded; both refuse with CC_E_LIMIT, never truncate.
+ *
+ * QEMU and hardware: nothing here is wired into the kernel yet (cut 1). */
+#ifndef CK_CONTINUITY_CODEC_H
+#define CK_CONTINUITY_CODEC_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* TEST-only mutants for the host mutation run (Makefile continuity-mutants).
+ * A mutant build exists only to prove the host test fails; it must never be
+ * part of a hardware staging image. */
+#if defined(CK_HARDWARE_STAGING) && \
+    (defined(CC_MUTANT_SKIP_TAKE_BOUND) || defined(CC_MUTANT_ACCEPT_RESERVED) || \
+     defined(CC_MUTANT_CHILD_INDEX_LE) || defined(CC_MUTANT_TRUNCATE_AT_CAP))
+#error "continuity codec mutants are TEST-only and refused under CK_HARDWARE_STAGING"
+#endif
+
+/* Store kinds (continuity.rs:19-22) and versions (:24, :26). */
+#define CC_KIND_AGENT_ROOT 16u
+#define CC_KIND_MANIFEST 17u
+#define CC_KIND_AGENT_STATE 18u
+#define CC_KIND_CORTEX_WAL 20u
+#define CC_STORE_OBJECT_VERSION 1u
+#define CC_FORMAT_VERSION 0u
+
+/* Rust bounds (continuity.rs:28-31). */
+#define CC_MAX_WAL_SEGMENTS 64u
+#define CC_MAX_BRANCHES 256u
+#define CC_MAX_WAL_RECORDS 64u
+#define CC_MAX_STATEMENT_BYTES 1024u
+
+#define CC_HEADER_BYTES 16u                       /* continuity.rs:33 */
+#define CC_ROOT_BYTES (CC_HEADER_BYTES + 96u)     /* ROOT_BODY, continuity.rs:202 */
+#define CC_BRANCH_BYTES 80u                       /* BRANCH_BYTES, continuity.rs:340 */
+#define CC_WAL_RECORD_FIXED 36u                   /* status, reserved, len, hash: :545-548 */
+/* K-1 (PROPOSED): the sealed Store's plaintext cap. */
+#define CC_MAX_OBJECT_BYTES 16384u
+/* Largest branch table that fits K-1: (16384 - 64) / 80 = 204. */
+#define CC_MAX_BRANCHES_IN_CAP ((CC_MAX_OBJECT_BYTES - CC_HEADER_BYTES - 48u) / CC_BRANCH_BYTES)
+
+/* Error classes (ContinuityError, continuity.rs:40-55; only those a codec
+ * can return). CC_E_ARG is C-only: a caller bug (NULL, output buffer too
+ * small, a value Rust's types cannot hold); nothing is written. */
+enum {
+    CC_OK = 0,
+    CC_E_CORRUPT = 1, /* ContinuityError::Corrupt(why) */
+    CC_E_LIMIT = 2,   /* ContinuityError::Limit(why) */
+    CC_E_ARG = 3,
+};
+
+/* ProvisionSource (continuity.rs:186-191). */
+#define CC_SOURCE_OPERATOR 1u
+#define CC_SOURCE_QUALIFICATION 2u
+
+/* Epistemic (continuity.rs:490-511). */
+#define CC_EPI_DIRECT_OBSERVATION 1u
+#define CC_EPI_OPERATOR_DECISION 6u
+
+/* An absent optional id (Option<ObjectId> None, parent None) is all zero,
+ * exactly as Rust encodes it (continuity.rs:38, :173-179, :403). */
+
+struct cc_root { /* AgentRoot, continuity.rs:194-200 */
+    uint8_t agent_id[32];
+    uint8_t store_uuid[16];
+    uint8_t root_branch[32];
+    uint64_t provisioned_generation;
+    uint8_t source; /* CC_SOURCE_* */
+};
+
+struct cc_manifest { /* Manifest, continuity.rs:254-261 */
+    uint8_t root[32];
+    uint8_t previous[32];    /* zero = none */
+    uint64_t sequence;
+    uint64_t incarnation;
+    uint8_t agent_state[32]; /* zero = none */
+    uint32_t n_wal;          /* <= CC_MAX_WAL_SEGMENTS */
+    uint8_t wal[CC_MAX_WAL_SEGMENTS][32];
+};
+
+struct cc_branch { /* Branch, continuity.rs:322-329 */
+    uint8_t id[32];
+    uint8_t parent[32]; /* zero = root branch */
+    uint32_t depth;
+    uint64_t forks;
+};
+
+struct cc_state { /* AgentState, continuity.rs:332-338; ~20 KiB, caller owned */
+    uint8_t agent_id[32];
+    uint64_t written_at;
+    uint32_t n; /* 1..CC_MAX_BRANCHES */
+    struct cc_branch br[CC_MAX_BRANCHES]; /* strictly ascending by id */
+};
+
+struct cc_record { /* CortexRecord, continuity.rs:514-518 */
+    uint8_t status; /* CC_EPI_* 1..6 */
+    uint8_t evidence_hash[32];
+    uint16_t len;   /* 1..CC_MAX_STATEMENT_BYTES */
+    /* Decode: points into the decoded input buffer (no copy, no
+     * allocation); valid only while that buffer is. Encode: read only. */
+    const uint8_t *statement;
+};
+
+struct cc_wal { /* WalSegment, continuity.rs:521-525 */
+    uint64_t sequence;
+    uint32_t n; /* 1..CC_MAX_WAL_RECORDS */
+    struct cc_record rec[CC_MAX_WAL_RECORDS];
+};
+
+/* ---- derivations (contract 1.7, INV-3) ---- */
+/* SHA-256("AIENOS_ROOT_BRANCH_v1:" || agent), continuity.rs:69-75. */
+void cc_root_branch_id(const uint8_t agent[32], uint8_t out[32]);
+/* SHA-256("AIENOS_CHILD_BRANCH_v1:" || parent || index u64 BIG-endian),
+ * continuity.rs:77-84. */
+void cc_child_branch_id(const uint8_t parent[32], uint64_t index, uint8_t out[32]);
+/* Logical ObjectId = ObjectId::calculate(kind, 1, bytes), store/v1.rs:63-78
+ * (contract P-2). CC_E_ARG for kind 0 or len 0 (v1.rs:64). */
+int cc_object_id(uint16_t kind, const uint8_t *bytes, size_t len, uint8_t out[32]);
+
+/* ---- codecs ----
+ * Encoders write the canonical bytes into out[0..cap) and set *len. On any
+ * error nothing useful is in out and *len is 0; an object that would exceed
+ * CC_MAX_OBJECT_BYTES is CC_E_LIMIT (K-1), an out buffer smaller than the
+ * object is CC_E_ARG. Decoders write *v as they read; on error *v holds
+ * no meaningful value (no copy: AgentState is ~20 KiB). *why (may be NULL)
+ * gets the Rust reason text on CC_E_CORRUPT / CC_E_LIMIT. */
+int cc_root_encode(const struct cc_root *v, uint8_t *out, size_t cap, size_t *len,
+                   const char **why);
+int cc_root_decode(const uint8_t *in, size_t len, struct cc_root *v, const char **why);
+
+int cc_manifest_encode(const struct cc_manifest *v, uint8_t *out, size_t cap, size_t *len,
+                       const char **why);
+int cc_manifest_decode(const uint8_t *in, size_t len, struct cc_manifest *v, const char **why);
+
+int cc_state_encode(const struct cc_state *v, uint8_t *out, size_t cap, size_t *len,
+                    const char **why);
+int cc_state_decode(const uint8_t *in, size_t len, struct cc_state *v, const char **why);
+
+int cc_wal_encode(const struct cc_wal *v, uint8_t *out, size_t cap, size_t *len,
+                  const char **why);
+int cc_wal_decode(const uint8_t *in, size_t len, struct cc_wal *v, const char **why);
+
+/* ---- branch table (continuity.rs:342-482) ---- */
+/* AgentState::genesis: only the root branch (continuity.rs:344-355). */
+void cc_state_genesis(struct cc_state *s, const uint8_t agent[32], uint64_t written_at);
+/* AgentState::validate (continuity.rs:447-481). */
+int cc_state_validate(const struct cc_state *s, const char **why);
+/* AgentState::fork (continuity.rs:365-390): child id into child_out. */
+int cc_state_fork(struct cc_state *s, const uint8_t parent[32], uint8_t child_out[32],
+                  const char **why);
+
+#endif /* CK_CONTINUITY_CODEC_H */
diff --git a/native/kernel/tests/test_continuity_codec.c b/native/kernel/tests/test_continuity_codec.c
new file mode 100644
index 00000000..b9070237
--- /dev/null
+++ b/native/kernel/tests/test_continuity_codec.c
@@ -0,0 +1,550 @@
+/* test_continuity_codec.c -- host tests of svc/continuity_codec.c (C
+ * continuity port, cut 1; contract native/kernel/CONTINUITY_RECOVERY_CONTRACT.md,
+ * aienos#222). Oracle: crates/aienos-kernel/src/continuity.rs at 4a116e5
+ * ("rs:" below).
+ *
+ * 1. Known answers. Expected bytes are written out by hand from the Rust
+ *    encoders, each piece citing the Rust line that emits it. Hash values
+ *    (root/child branch ids, logical ObjectIds) were computed outside this
+ *    code with coreutils sha256sum over printf-built inputs, not with the C
+ *    code under test. A Rust-generated vector emitter is a later cut (D-1).
+ * 2. Round trips (twin of rs tests continuity_tests.rs:286, 87h).
+ * 3. One refusal per rule, with the Rust error class and reason text.
+ * 4. Branch-table lineage (twin of continuity_tests.rs:328, 87i).
+ * 5. K-1 (PROPOSED): 16384-byte cap on encode and decode.
+ * Mutants (make continuity-mutants) must each turn this test FAIL. */
+#include <stdint.h>
+#include <string.h>
+#include "ck_test.h"
+#include "continuity_codec.h"
+#include "store_v1.h" /* sv1_object_id: independent C twin of ObjectId::calculate */
+
+static const char *why;
+static uint8_t buf[CC_MAX_OBJECT_BYTES + 1024]; /* decoders read from here */
+static uint8_t out[CC_MAX_OBJECT_BYTES + 1024];
+static struct cc_state st, st2;
+static struct cc_wal wal, wal2;
+static struct cc_manifest man, man2;
+static uint8_t stmt[CC_MAX_WAL_RECORDS][CC_MAX_STATEMENT_BYTES];
+
+/* ---- known-answer builder ---- */
+static uint8_t kat[4096];
+static size_t kn;
+static void k_str(const char *s) { size_t n = strlen(s); memcpy(kat + kn, s, n); kn += n; }
+static void k_rep(uint8_t b, size_t n) { memset(kat + kn, b, n); kn += n; }
+static void k_le(uint64_t v, int n) { for (int i = 0; i < n; i++) kat[kn++] = (uint8_t)(v >> (8 * i)); }
+static int hexv(char c) { return c <= '9' ? c - '0' : c - 'a' + 10; }
+static void unhex(const char *h, uint8_t *o) { for (size_t i = 0; h[2 * i]; i++) o[i] = (uint8_t)(hexv(h[2 * i]) << 4 | hexv(h[2 * i + 1])); }
+static void k_hex(const char *h) { unhex(h, kat + kn); kn += strlen(h) / 2; }
+
+/* sha256sum("AIENOS_ROOT_BRANCH_v1:" || 0x11 x 32) */
+#define RB_HEX "89f5fd9d69301a1ab4cce49d57b3f711fb9c36524807ef53fada8119ac24f803"
+/* sha256sum("AIENOS_CHILD_BRANCH_v1:" || RB || index u64 BE) for index 0, 1, 2^32, 2^64-1 */
+#define C0_HEX "0be1954eac96e977c2eabee2a079600ad249b7c46b4f07910089098041f55785"
+#define C1_HEX "909874bd0bd38ea9b278982665b3f33ed29b5c76340719bccf030bc59bebcc55"
+#define C32_HEX "35b2e2d23d315594bfdb01277cdce8ad5aedf79641e11b7a82c9d08a6c5e669a"
+#define CMAX_HEX "d9716d516fb3c31b21dc4e9a9e748a928a5a53d60642c0251094e47aeb8d22fd"
+/* sha256sum("AIENOS-STORE-OBJECT-V1\0" || kind u16 LE || 1 u16 LE || len u64 LE || bytes)
+ * over the four known-answer objects below (store/v1.rs:63-78). */
+#define ID_ROOT_HEX "d231e0aaba16e227a5330c590d60f0367d42930593bca2092df9fe3ae23f6bf7"
+#define ID_MANI_HEX "e8ba64304b22ed1f65c810a6735420dca321b42b6136caddc5214c5e0a509287"
+#define ID_BRAN_HEX "561ec891c466d831b187ad19016c2800e56aa9947dfb356792c127e003682b20"
+#define ID_WAL_HEX "1e6f48f3e32c1dbc13b200f112deae41668f0b5048e17578d99fe1583d344faf"
+
+static uint8_t AGENT[32]; /* 0x11 x 32, as continuity_tests.rs:8 */
+
+static int is(int got, int cls, const char *w)
+{
+    return got == cls && why && strcmp(why, w) == 0;
+}
+
+static int id_matches(uint16_t kind, const uint8_t *b, size_t n, const char *hex)
+{
+    uint8_t a[32], c[32], e[32];
+    unhex(hex, e);
+    if (cc_object_id(kind, b, n, a) != CC_OK || sv1_object_id(kind, 1, b, n, c) != 0)
+        return 0;
+    return memcmp(a, e, 32) == 0 && memcmp(c, e, 32) == 0;
+}
+
+/* ---- 1. derivations ---- */
+static void test_branch_ids(void)
+{
+    uint8_t rb[32], c[32], e[32];
+    cc_root_branch_id(AGENT, rb);
+    unhex(RB_HEX, e);
+    CHECK(memcmp(rb, e, 32) == 0);
+    static const struct { uint64_t ix; const char *hex; } v[] = {
+        {0, C0_HEX}, {1, C1_HEX}, {0x100000000ull, C32_HEX}, {UINT64_MAX, CMAX_HEX}};
+    for (size_t i = 0; i < sizeof v / sizeof v[0]; i++) {
+        cc_child_branch_id(rb, v[i].ix, c);
+        unhex(v[i].hex, e);
+        CHECK(memcmp(c, e, 32) == 0); /* index big-endian, rs:82 (MC-6) */
+    }
+    CHECK(cc_object_id(0, AGENT, 32, c) == CC_E_ARG); /* v1.rs:64 */
+    CHECK(cc_object_id(CC_KIND_AGENT_ROOT, AGENT, 0, c) == CC_E_ARG);
+}
+
+/* ---- AgentRoot ---- */
+static void root_kat(void) /* rs:205-215, total 112 */
+{
+    kn = 0;
+    k_str("AIENROOT");               /* rs:91 MAGIC_ROOT (:34) */
+    k_le(0, 2);                      /* rs:92 FORMAT_VERSION 0 */
+    k_le(0, 2);                      /* rs:93 reserved */
+    k_le(96, 4);                     /* rs:94 body_len = ROOT_BODY (:202) */
+    k_rep(0x11, 32);                 /* rs:208 agent_id */
+    k_rep(0x5a, 16);                 /* rs:209 store_uuid */
+    k_hex(RB_HEX);                   /* rs:210 root_branch */
+    k_le(0x0102030405060708ull, 8);  /* rs:211 provisioned_generation LE */
+    k_le(2, 1);                      /* rs:212 source Qualification (:190) */
+    k_rep(0, 7);                     /* rs:213 reserved */
+}
+static void root_val(struct cc_root *r)
+{
+    memset(r, 0, sizeof *r);
+    memcpy(r->agent_id, AGENT, 32);
+    memset(r->store_uuid, 0x5a, 16);
+    unhex(RB_HEX, r->root_branch);
+    r->provisioned_generation = 0x0102030405060708ull;
+    r->source = CC_SOURCE_QUALIFICATION;
+}
+static int root_eq(const struct cc_root *a, const struct cc_root *b)
+{
+    return !memcmp(a->agent_id, b->agent_id, 32) && !memcmp(a->store_uuid, b->store_uuid, 16) &&
+           !memcmp(a->root_branch, b->root_branch, 32) &&
+           a->provisioned_generation == b->provisioned_generation && a->source == b->source;
+}
+/* Decode n bytes copied to buf (buf is larger, so a broken bound check reads
+ * inside the array and the test reports instead of crashing). */
+static int dec_root(const uint8_t *b, size_t n, struct cc_root *r)
+{
+    memmove(buf, b, n);
+    why = 0;
+    return cc_root_decode(buf, n, r, &why);
+}
+
+static void test_root(void)
+{
+    struct cc_root v, d;
+    size_t n = 0;
+    root_val(&v);
+    root_kat();
+    CHECK(kn == CC_ROOT_BYTES);
+    CHECK(cc_root_encode(&v, out, sizeof out, &n, &why) == CC_OK && n == kn && !memcmp(out, kat, kn));
+    CHECK(id_matches(CC_KIND_AGENT_ROOT, kat, kn, ID_ROOT_HEX));
+    CHECK(dec_root(kat, kn, &d) == CC_OK && root_eq(&d, &v));
+
+    /* 87h: every single-bit flip is refused or changes the decoded value. */
+    int unnoticed = 0;
+    for (size_t i = 0; i < kn * 8; i++) {
+        uint8_t t[CC_ROOT_BYTES];
+        memcpy(t, kat, kn);
+        t[i / 8] ^= (uint8_t)(1u << (i % 8));
+        if (dec_root(t, kn, &d) == CC_OK && root_eq(&d, &v))
+            unnoticed++;
+    }
+    CHECK(unnoticed == 0);
+
+    uint8_t t[CC_ROOT_BYTES + 8];
+    /* truncated: last byte cut, body_len says 95 so the header agrees (rs:123-132) */
+    memcpy(t, kat, kn); t[12] = 95;
+    CHECK(is(dec_root(t, kn - 1, &d), CC_E_CORRUPT, "truncated object"));
+    /* truncated inside the header (rs:107-118) */
+    CHECK(is(dec_root(kat, 10, &d), CC_E_CORRUPT, "truncated object"));
+    CHECK(is(dec_root(kat, 0, &d), CC_E_CORRUPT, "truncated object"));
+    /* trailing: one extra byte, body_len says 97 (rs:160-165) */
+    memcpy(t, kat, kn); t[kn] = 0; t[12] = 97;
+    CHECK(is(dec_root(t, kn + 1, &d), CC_E_CORRUPT, "trailing bytes"));
+    /* plain extra byte: body length mismatch (rs:118) */
+    memcpy(t, kat, kn); t[kn] = 0;
+    CHECK(is(dec_root(t, kn + 1, &d), CC_E_CORRUPT, "body length mismatch"));
+    CHECK(is(dec_root(kat, kn - 1, &d), CC_E_CORRUPT, "body length mismatch"));
+    memcpy(t, kat, kn); t[0] ^= 0x20;
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "bad magic")); /* rs:107 */
+    memcpy(t, kat, kn); t[8] = 1;
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "unsupported continuity format version")); /* rs:110 */
+    memcpy(t, kat, kn); t[9] = 1;
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "unsupported continuity format version"));
+    memcpy(t, kat, kn); t[11] = 0x80;
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "nonzero header reserved")); /* rs:115 */
+    memcpy(t, kat, kn); t[111] = 1;
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "nonzero reserved")); /* rs:229 */
+    memcpy(t, kat, kn); t[104] = 3;
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "unknown provisioning source")); /* rs:227 */
+    memcpy(t, kat, kn); t[104] = 0;
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "unknown provisioning source"));
+    /* zero agent: checked before the derivation (rs:231 before :234) */
+    struct cc_root z = v;
+    memset(z.agent_id, 0, 32);
+    cc_root_branch_id(z.agent_id, z.root_branch);
+    CHECK(cc_root_encode(&z, out, sizeof out, &n, &why) == CC_OK);
+    CHECK(is(dec_root(out, n, &d), CC_E_CORRUPT, "zero agent id"));
+    z = v;
+    memset(z.root_branch, 0x99, 32); /* as continuity_tests.rs:313 */
+    CHECK(cc_root_encode(&z, out, sizeof out, &n, &why) == CC_OK);
+    CHECK(is(dec_root(out, n, &d), CC_E_CORRUPT, "root branch does not derive from agent"));
+    /* the right magic for another kind is refused (kind check by magic) */
+    memcpy(t, kat, kn); memcpy(t, "AIENMANI", 8);
+    CHECK(is(dec_root(t, kn, &d), CC_E_CORRUPT, "bad magic"));
+
+    /* encoder: caller bugs, nothing truncated */
+    z = v; z.source = 0;
+    CHECK(cc_root_encode(&z, out, sizeof out, &n, &why) == CC_E_ARG && n == 0);
+    memset(out, 0xee, 16);
+    CHECK(cc_root_encode(&v, out, CC_ROOT_BYTES - 1, &n, &why) == CC_E_ARG && n == 0 && out[0] == 0xee);
+}
+
+/* ---- ContinuityManifest ---- */
+static void mani_kat(void) /* rs:264-282, total 168 */
+{
+    kn = 0;
+    k_str("AIENMANI"); k_le(0, 2); k_le(0, 2); /* rs:91-93, MAGIC_MANIFEST (:35) */
+    k_le(120 + 32, 4);                         /* rs:94 body (:268) */
+    k_rep(0xa1, 32);                           /* rs:271 root */
+    k_rep(0x00, 32);                           /* rs:272 previous None = zero */
+    k_le(1, 8);                                /* rs:273 sequence */
+    k_le(1, 8);                                /* rs:274 incarnation */
+    k_rep(0xb2, 32);                           /* rs:275 agent_state */
+    k_le(1, 2);                                /* rs:276 cortex_wal count */
+    k_rep(0, 6);                               /* rs:277 reserved */
+    k_rep(0xc3, 32);                           /* rs:279 cortex_wal[0] */
+}
+static void mani_val(struct cc_manifest *m)
+{
+    memset(m, 0, sizeof *m);
+    memset(m->root, 0xa1, 32);
+    m->sequence = 1;
+    m->incarnation = 1;
+    memset(m->agent_state, 0xb2, 32);
+    m->n_wal = 1;
+    memset(m->wal[0], 0xc3, 32);
+}
+static int mani_eq(const struct cc_manifest *a, const struct cc_manifest *b)
+{
+    return !memcmp(a->root, b->root, 32) && !memcmp(a->previous, b->previous, 32) &&
+           a->sequence == b->sequence && a->incarnation == b->incarnation &&
+           !memcmp(a->agent_state, b->agent_state, 32) && a->n_wal == b->n_wal &&
+           !memcmp(a->wal, b->wal, 32 * (size_t)a->n_wal);
+}
+static int dec_mani(const uint8_t *b, size_t n)
+{
+    memmove(buf, b, n);
+    why = 0;
+    return cc_manifest_decode(buf, n, &man2, &why);
+}
+
+static void test_manifest(void)
+{
+    size_t n = 0;
+    mani_val(&man);
+    mani_kat();
+    CHECK(kn == 168);
+    CHECK(cc_manifest_encode(&man, out, sizeof out, &n, &why) == CC_OK && n == kn && !memcmp(out, kat, kn));
+    CHECK(id_matches(CC_KIND_MANIFEST, kat, kn, ID_MANI_HEX));
+    CHECK(dec_mani(kat, kn) == CC_OK && mani_eq(&man2, &man));
+
+    uint8_t t[256];
+    memcpy(t, kat, kn); t[130] = 1;
+    CHECK(is(dec_mani(t, kn), CC_E_CORRUPT, "nonzero reserved")); /* rs:292 */
+    /* count 2 with only one id present, body_len unchanged: truncated (rs:298) */
+    memcpy(t, kat, kn); t[128] = 2;
+    CHECK(is(dec_mani(t, kn), CC_E_CORRUPT, "truncated object"));
+    memcpy(t, kat, kn); t[128] = 65;
+    CHECK(is(dec_mani(t, kn), CC_E_CORRUPT, "too many cortex WAL segments")); /* rs:293-295 */
+    memcpy(t, kat, kn); t[80] = 0;
+    CHECK(is(dec_mani(t, kn), CC_E_CORRUPT, "manifest sequence/previous mismatch")); /* seq 0, rs:301 */
+    memcpy(t, kat, kn); t[80] = 2;
+    CHECK(is(dec_mani(t, kn), CC_E_CORRUPT, "manifest sequence/previous mismatch")); /* seq 2, no previous */
+    memcpy(t, kat, kn); t[48] = 1;
+    CHECK(is(dec_mani(t, kn), CC_E_CORRUPT, "manifest sequence/previous mismatch")); /* seq 1 with previous */
+    memcpy(t, kat, kn); t[48] = 1; t[80] = 2;
+    CHECK(dec_mani(t, kn) == CC_OK && man2.sequence == 2 && man2.previous[0] == 1);
+
+    /* 64 WAL ids is the largest manifest (2184 bytes); 65 is Limit (rs:265-267) */
+    man.n_wal = CC_MAX_WAL_SEGMENTS;
+    CHECK(cc_manifest_encode(&man, out, sizeof out, &n, &why) == CC_OK && n == 2184);
+    CHECK(dec_mani(out, n) == CC_OK && man2.n_wal == 64);
+    man.n_wal = CC_MAX_WAL_SEGMENTS + 1;
+    CHECK(is(cc_manifest_encode(&man, out, sizeof out, &n, &why), CC_E_LIMIT, "too many cortex WAL segments") && n == 0);
+}
+
+/* ---- AgentState ---- */
+static void bran_kat(void) /* genesis(AGENT, 1) + fork(root): rs:392-409, total 224 */
+{
+    kn = 0;
+    k_str("AIENBRAN"); k_le(0, 2); k_le(0, 2); /* rs:91-93, MAGIC_BRANCHES (:36) */
+    k_le(48 + 2 * 80, 4);                      /* rs:94 body (:394) */
+    k_rep(0x11, 32);                           /* rs:397 agent_id */
+    k_le(1, 8);                                /* rs:398 written_at */
+    k_le(2, 4);                                /* rs:399 branch count */
+    k_rep(0, 4);                               /* rs:400 reserved */
+    /* sorted by id (rs:387-388): C0 (0x0b..) < RB (0x89..) */
+    k_hex(C0_HEX);                             /* rs:402 id = child_branch_id(RB, 0) */
+    k_hex(RB_HEX);                             /* rs:403 parent */
+    k_le(1, 4);                                /* rs:404 depth */
+    k_rep(0, 4);                               /* rs:405 reserved */
+    k_le(0, 8);                                /* rs:406 forks */
+    k_hex(RB_HEX);                             /* rs:402 root id */
+    k_rep(0, 32);                              /* rs:403 parent None = zero */
+    k_le(0, 4);                                /* rs:404 depth 0 */
+    k_rep(0, 4);                               /* rs:405 */
+    k_le(1, 8);                                /* rs:406 forks 1 (rs:382) */
+}
+static int dec_state(const uint8_t *b, size_t n)
+{
+    memmove(buf, b, n);
+    why = 0;
+    return cc_state_decode(buf, n, &st2, &why);
+}
+static int state_eq(const struct cc_state *a, const struct cc_state *b)
+{
+    if (memcmp(a->agent_id, b->agent_id, 32) || a->written_at != b->written_at || a->n != b->n)
+        return 0;
+    for (uint32_t i = 0; i < a->n; i++)
+        if (memcmp(a->br[i].id, b->br[i].id, 32) || memcmp(a->br[i].parent, b->br[i].parent, 32) ||
+            a->br[i].depth != b->br[i].depth || a->br[i].forks != b->br[i].forks)
+            return 0;
+    return 1;
+}
+static long idx_of(const struct cc_state *s, const uint8_t id[32])
+{
+    for (uint32_t i = 0; i < s->n; i++)
+        if (!memcmp(s->br[i].id, id, 32))
+            return (long)i;
+    return -1;
+}
+
+static void test_state(void)
+{
+    size_t n = 0;
+    uint8_t rb[32], child[32], gchild[32], e[32];
+    cc_root_branch_id(AGENT, rb);
+    cc_state_genesis(&st, AGENT, 1);
+    CHECK(st.n == 1 && cc_state_validate(&st, &why) == CC_OK);
+    CHECK(cc_state_fork(&st, rb, child, &why) == CC_OK);
+    unhex(C0_HEX, e);
+    CHECK(memcmp(child, e, 32) == 0);
+    bran_kat();
+    CHECK(kn == 224);
+    CHECK(cc_state_encode(&st, out, sizeof out, &n, &why) == CC_OK && n == kn && !memcmp(out, kat, kn));
+    CHECK(id_matches(CC_KIND_AGENT_STATE, kat, kn, ID_BRAN_HEX));
+    CHECK(dec_state(kat, kn) == CC_OK && state_eq(&st2, &st));
+
+    /* second fork of the root takes index 1 (rs:373, :382) */
+    st2 = st;
+    CHECK(cc_state_fork(&st2, rb, gchild, &why) == CC_OK);
+    unhex(C1_HEX, e);
+    CHECK(memcmp(gchild, e, 32) == 0 && st2.n == 3);
+    /* 87h tail: fork of a fork (depth 2) round-trips */
+    CHECK(cc_state_fork(&st2, child, gchild, &why) == CC_OK);
+    CHECK(st2.br[idx_of(&st2, gchild)].depth == 2);
+    CHECK(cc_state_encode(&st2, out, sizeof out, &n, &why) == CC_OK);
+    static struct cc_state keep;
+    keep = st2;
+    CHECK(dec_state(out, n) == CC_OK && state_eq(&st2, &keep));
+
+    uint8_t t[256];
+    memcpy(t, kat, kn); t[60] = 1;
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "nonzero reserved")); /* rs:416 */
+    memcpy(t, kat, kn); t[64 + 68] = 1;
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "nonzero reserved")); /* rs:425 */
+    memcpy(t, kat, kn); t[56] = 0;
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "branch count out of range")); /* rs:417 */
+    memcpy(t, kat, kn); t[56] = 3;
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "truncated object")); /* rs:422 */
+    memcpy(t, kat, kn); t[56] = 0x01; t[57] = 0x01; /* 257 */
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "branch count out of range"));
+    memcpy(t, kat, kn); t[56] = 1; t[12] = 48 + 80; /* header length disagrees with the input length */
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "body length mismatch"));
+    memcpy(t, kat, kn); t[56] = 1;
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "trailing bytes"));
+    /* swap the two branches: not strictly sorted (rs:452-454) */
+    memcpy(t, kat, kn); memcpy(t + 64, kat + 144, 80); memcpy(t + 144, kat + 64, 80);
+    CHECK(is(dec_state(t, kn), CC_E_CORRUPT, "branches not strictly sorted"));
+
+    /* 87i twins (continuity_tests.rs:328-346) through validate */
+    long ci = idx_of(&st, child), ri = idx_of(&st, rb);
+    st2 = st; st2.br[ci].depth = 5;
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "branch lineage is inconsistent"));
+    st2 = st; st2.br[ri].forks = 2;
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "fork indexes are not contiguous"));
+    st2 = st; st2.br[ri] = st2.br[ci]; st2.n = 1; /* root removed */
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "parent branch is absent"));
+    cc_state_genesis(&st2, AGENT, 1); st2.br[0].depth = 1;
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "unexpected root branch"));
+    st2 = st; st2.agent_id[0] ^= 1; /* root id no longer derives from the agent */
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "unexpected root branch"));
+    st2 = st; st2.br[ci].id[31] ^= 1; /* child id not derived from its parent */
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "branch lineage is inconsistent"));
+    st2 = st; st2.br[ci].depth = UINT32_MAX;
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "branch lineage is inconsistent"));
+    /* encode runs validate first (rs:393) */
+    st2 = st; st2.br[ri].forks = 2;
+    CHECK(is(cc_state_encode(&st2, out, sizeof out, &n, &why), CC_E_CORRUPT, "fork indexes are not contiguous") && n == 0);
+    /* Hostile fork counts: terminates, refused. Child index 0 under a parent
+     * claiming 2^64-1 forks with a sum that would wrap to the child count. */
+    st2 = st; st2.br[ri].forks = UINT64_MAX; st2.br[ci].forks = 2;
+    CHECK(is(cc_state_validate(&st2, &why), CC_E_CORRUPT, "fork indexes are not contiguous"));
+    st2 = st; st2.br[ri].forks = UINT64_MAX; st2.br[ci].id[31] ^= 1;
+    CHECK(cc_state_validate(&st2, &why) == CC_E_CORRUPT);
+
+    /* fork refusals (rs:366-387) */
+    st2 = st; memset(e, 0x77, 32);
+    CHECK(is(cc_state_fork(&st2, e, gchild, &why), CC_E_CORRUPT, "fork parent is absent"));
+    st2 = st; st2.n = CC_MAX_BRANCHES;
+    CHECK(is(cc_state_fork(&st2, rb, gchild, &why), CC_E_LIMIT, "too many branches"));
+    st2 = st; st2.br[ci].depth = UINT32_MAX;
+    CHECK(is(cc_state_fork(&st2, child, gchild, &why), CC_E_LIMIT, "branch depth"));
+    /* collision: parent forks rewound to 0 re-derives the existing child; the
+     * parent's count still advances, as in Rust (rs:382 before :383-387) */
+    st2 = st; st2.br[ri].forks = 0;
+    CHECK(is(cc_state_fork(&st2, rb, gchild, &why), CC_E_CORRUPT, "child branch id collision"));
+    CHECK(st2.n == 2 && st2.br[ri].forks == 1);
+
+    /* K-1 (PROPOSED): 204 branches = exactly 16384 bytes; 205 is Limit. */
+    cc_state_genesis(&st2, AGENT, 1);
+    int ok = 1;
+    while (st2.n < CC_MAX_BRANCHES_IN_CAP)
+        ok &= cc_state_fork(&st2, rb, gchild, &why) == CC_OK;
+    CHECK(ok && st2.n == 204);
+    CHECK(cc_state_encode(&st2, out, sizeof out, &n, &why) == CC_OK && n == CC_MAX_OBJECT_BYTES);
+    CHECK(dec_state(out, n) == CC_OK && st2.n == 204);
+    CHECK(cc_state_fork(&st2, rb, gchild, &why) == CC_OK && st2.n == 205); /* Rust bound is 256 */
+    memset(out, 0xee, 64);
+    CHECK(cc_state_encode(&st2, out, sizeof out, &n, &why) == CC_E_LIMIT && n == 0 && out[0] == 0xee);
+}
+
+/* ---- CortexWalSegment ---- */
+static void wal_kat(void) /* rs:528-552, total 107 */
+{
+    kn = 0;
+    k_str("AIENCWAL"); k_le(0, 2); k_le(0, 2); /* rs:91-93, MAGIC_WAL (:37) */
+    k_le(16 + 37 + 38, 4);                     /* rs:94 body (:532, :537) */
+    k_le(3, 8);                                /* rs:541 sequence */
+    k_le(2, 4);                                /* rs:542 record count */
+    k_rep(0, 4);                               /* rs:543 reserved */
+    k_le(6, 1); k_le(0, 1); k_le(1, 2);        /* rs:545-547 OperatorDecision, reserved, len */
+    k_rep(0x42, 32); k_str("a");               /* rs:548-549 */
+    k_le(2, 1); k_le(0, 1); k_le(2, 2);        /* rs:545-547 VerifiedFact */
+    k_rep(0x42, 32); k_str("bb");              /* rs:548-549 */
+}
+static int dec_wal(const uint8_t *b, size_t n)
+{
+    memmove(buf, b, n);
+    why = 0;
+    return cc_wal_decode(buf, n, &wal2, &why);
+}
+
+static void test_wal(void)
+{
+    size_t n = 0;
+    memset(&wal, 0, sizeof wal);
+    wal.sequence = 3;
+    wal.n = 2;
+    wal.rec[0].status = 6; memset(wal.rec[0].evidence_hash, 0x42, 32); wal.rec[0].len = 1; wal.rec[0].statement = (const uint8_t *)"a";
+    wal.rec[1].status = 2; memset(wal.rec[1].evidence_hash, 0x42, 32); wal.rec[1].len = 2; wal.rec[1].statement = (const uint8_t *)"bb";
+    wal_kat();
+    CHECK(kn == 107);
+    CHECK(cc_wal_encode(&wal, out, sizeof out, &n, &why) == CC_OK && n == kn && !memcmp(out, kat, kn));
+    CHECK(id_matches(CC_KIND_CORTEX_WAL, kat, kn, ID_WAL_HEX));
+    CHECK(dec_wal(kat, kn) == CC_OK && wal2.sequence == 3 && wal2.n == 2);
+    CHECK(wal2.rec[0].status == 6 && wal2.rec[0].len == 1 && wal2.rec[0].statement == buf + 68 &&
+          wal2.rec[0].statement[0] == 'a' && wal2.rec[0].evidence_hash[31] == 0x42);
+    CHECK(wal2.rec[1].status == 2 && wal2.rec[1].len == 2 && wal2.rec[1].statement == buf + 105 &&
+          !memcmp(wal2.rec[1].statement, "bb", 2));
+
+    uint8_t t[256];
+    memcpy(t, kat, kn); t[28] = 1;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "nonzero reserved")); /* rs:558 */
+    memcpy(t, kat, kn); t[33] = 1;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "nonzero reserved")); /* rs:566 */
+    memcpy(t, kat, kn); t[24] = 0;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "WAL segment record count")); /* rs:559 */
+    memcpy(t, kat, kn); t[24] = 65;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "WAL segment record count"));
+    memcpy(t, kat, kn); t[32] = 7;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "unknown epistemic status")); /* rs:564-565 */
+    memcpy(t, kat, kn); t[32] = 0;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "unknown epistemic status"));
+    memcpy(t, kat, kn); t[34] = 0;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "statement length")); /* rs:568 */
+    memcpy(t, kat, kn); t[34] = 0x01; t[35] = 0x04; /* 1025 */
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "statement length"));
+    /* last statement claims 3 bytes, header agrees with the real length:
+     * the statement read runs past the end (rs:572) */
+    memcpy(t, kat, kn); t[71] = 3;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "truncated object"));
+    /* count 3, only two records present */
+    memcpy(t, kat, kn); t[24] = 3;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "truncated object"));
+    memcpy(t, kat, kn); t[71] = 1;
+    CHECK(is(dec_wal(t, kn), CC_E_CORRUPT, "trailing bytes"));
+
+    /* encoder bounds (rs:529-536) */
+    struct cc_wal w = wal;
+    w.n = 0;
+    CHECK(is(cc_wal_encode(&w, out, sizeof out, &n, &why), CC_E_LIMIT, "WAL segment record count") && n == 0);
+    w = wal; w.rec[1].len = 0;
+    CHECK(is(cc_wal_encode(&w, out, sizeof out, &n, &why), CC_E_LIMIT, "statement length"));
+    w = wal; w.rec[1].len = CC_MAX_STATEMENT_BYTES + 1; w.rec[1].statement = stmt[0];
+    CHECK(is(cc_wal_encode(&w, out, sizeof out, &n, &why), CC_E_LIMIT, "statement length"));
+    w = wal; w.rec[0].status = 9;
+    CHECK(cc_wal_encode(&w, out, sizeof out, &n, &why) == CC_E_ARG);
+
+    /* every status 1..6 and statement lengths 1 and 1024 round-trip */
+    memset(&w, 0, sizeof w);
+    w.sequence = 9;
+    w.n = 7;
+    for (uint32_t i = 0; i < 7; i++) {
+        w.rec[i].status = (uint8_t)(i % 6 + 1);
+        memset(w.rec[i].evidence_hash, (int)i, 32);
+        memset(stmt[i], 'A' + (int)i, CC_MAX_STATEMENT_BYTES);
+        w.rec[i].len = i == 6 ? CC_MAX_STATEMENT_BYTES : 1;
+        w.rec[i].statement = stmt[i];
+    }
+    CHECK(cc_wal_encode(&w, out, sizeof out, &n, &why) == CC_OK && n == 16 + 16 + 7 * 36 + 6 + 1024);
+    CHECK(dec_wal(out, n) == CC_OK && wal2.n == 7 && wal2.rec[6].len == 1024 && wal2.rec[5].status == 6 &&
+          wal2.rec[6].statement[1023] == 'G');
+
+    /* K-1 (PROPOSED, MC-11): a Rust-legal 64 x 1024 segment (67872 bytes)
+     * is Limit, never truncated, nothing written. */
+    memset(&w, 0, sizeof w);
+    w.sequence = 1;
+    w.n = CC_MAX_WAL_RECORDS;
+    for (uint32_t i = 0; i < CC_MAX_WAL_RECORDS; i++) {
+        w.rec[i].status = 1;
+        w.rec[i].len = CC_MAX_STATEMENT_BYTES;
+        w.rec[i].statement = stmt[i];
+    }
+    memset(out, 0xee, 64);
+    n = 123;
+    CHECK(is(cc_wal_encode(&w, out, sizeof out, &n, &why), CC_E_LIMIT,
+             "continuity object exceeds the 16384-byte sealed Store cap") && n == 0 && out[0] == 0xee);
+}
+
+/* K-1 on decode (PROPOSED): more than 16384 bytes is Limit before parsing. */
+static void test_decode_cap(void)
+{
+    memset(buf, 0, sizeof buf);
+    memcpy(buf, "AIENCWAL", 8);
+    CHECK(cc_wal_decode(buf, CC_MAX_OBJECT_BYTES + 1, &wal2, &why) == CC_E_LIMIT);
+    CHECK(cc_state_decode(buf, CC_MAX_OBJECT_BYTES + 1, &st2, &why) == CC_E_LIMIT);
+    struct cc_root r;
+    CHECK(cc_root_decode(buf, CC_MAX_OBJECT_BYTES + 1, &r, &why) == CC_E_LIMIT);
+    CHECK(cc_manifest_decode(buf, CC_MAX_OBJECT_BYTES + 1, &man2, &why) == CC_E_LIMIT);
+    /* exactly 16384 is parsed (refused here only as Corrupt) */
+    CHECK(cc_wal_decode(buf, CC_MAX_OBJECT_BYTES, &wal2, &why) == CC_E_CORRUPT);
+}
+
+int main(void)
+{
+    memset(AGENT, 0x11, 32);
+    test_branch_ids();
+    test_root();
+    test_manifest();
+    test_state();
+    test_wal();
+    test_decode_cap();
+    return ck_t_verdict("test_continuity_codec");
+}