diff --git a/.crumb b/.crumb index 9fa5ea94..4164c4f0 100644 --- a/.crumb +++ b/.crumb @@ -33,27 +33,27 @@ "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "b31f2fbe0098a7147db621948947a4f65981798cd8f38dfb90f2925bdf923534", - "last_commit": "101c710", + "digest": "9bd3a5424bd1bb24ec9bf14a01fdaf11ee5b88e669438863e7a84018947e1f38", + "last_commit": "453f41e", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "87981170f9983b962d7b2c8ea7f2f4811b354e13514dcb6365f0cc7a49cb1e9f", - "last_commit": "101c710", + "digest": "eecc6309e4e429e5236cbf29a3593351f5bd5b2cb2daf6cd36c73fc96c9b0a61", + "last_commit": "453f41e", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:eef5b71658818e8bf015518ee54e49bfb131d7b684900c605feff63bc34a501e", - "compiled_at": "2026-10-12T06:35:59Z", + "children_root": "sha256:750e6b10e42abcb4c01f0a3f6bcb1442bb028a6bd191702788ec364f6baec055", + "compiled_at": "2026-10-12T07:42:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:2886dcfc976f771e9c109ff4f00d6ca5d3e497df71dfbef80551615edd80cf42", + "digest": "sha256:44caf9772cbe90d6f6ad9a5320cf1e08f3f91e67369299fb99c9baadc93a2b95", "evidence_files": 155, "evidence_root": "sha256:d59c0cef4e7dd5172923754a95b411ca54b01f35baca4587f792f1b259f1eaf7", - "files": 3075, - "generated_at_commit": "101c710b24fad41fc9a8797222e366ed71e6b6f2", - "source_tree": "sha256:fd7bfde997ed3035059431248fbf4c14c71413507be0b2674cf9d8a0a70f13ee" + "files": 3084, + "generated_at_commit": "453f41e7fca07a97ee52db3a125d106dfaf17ff5", + "source_tree": "sha256:87d540c3d77ba7a4e5132528af84b717cac3606a87a272e5f994d4a0d204fdad" }, "owner_lane": "", "provenance": { diff --git a/.github/workflows/ck-kernel.yml b/.github/workflows/ck-kernel.yml index 7b914a42..f9f05a87 100644 --- a/.github/workflows/ck-kernel.yml +++ b/.github/workflows/ck-kernel.yml @@ -86,6 +86,12 @@ jobs: - name: Stage host tests (plain and ASan + UBSan) run: make -C native/kernel stage-test stage-sanitize + - name: Vendored Omega Cortex store matches omega.lock (P06 cut 3; shallow fetch of the pinned omega commit) + run: bash scripts/omega_lock_check.sh + + - name: Stage sources compile freestanding (nm -u: ck.h services only) + run: make -C native/kernel stage-free + - name: Gate runner self-test run: bash scripts/ck_gates.sh --self-test diff --git a/native/.crumb b/native/.crumb index 33c8793d..cf8ff5dc 100644 --- a/native/.crumb +++ b/native/.crumb @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "169522946ffcd95a36106c1d8a0f6bdba1130e97a5b8dad204696a7245de1948", - "last_commit": "101c710", + "digest": "4cbfcc2d3ce9c2956be80604f8c41d1eb0e87d06d20a999fc8ebe579d95dfb8b", + "last_commit": "453f41e", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, @@ -109,15 +109,15 @@ "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:bf53e2b5d96c2ab47143ebc4bb6d1864f1116a267bc9fe10abc549c25b5de3ad", - "compiled_at": "2026-10-12T06:35:59Z", + "children_root": "sha256:162ac2426b94dbcda2d0c26dcdbd407750737911191f9a643ee93610d085326d", + "compiled_at": "2026-10-12T07:42:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:b31f2fbe0098a7147db621948947a4f65981798cd8f38dfb90f2925bdf923534", + "digest": "sha256:9bd3a5424bd1bb24ec9bf14a01fdaf11ee5b88e669438863e7a84018947e1f38", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", - "files": 462, - "generated_at_commit": "101c710b24fad41fc9a8797222e366ed71e6b6f2", - "source_tree": "sha256:d45042e6d50a30dd9e6c8929ede1c45208c05d61ddead84bf1fba932f1ebbdd2" + "files": 469, + "generated_at_commit": "453f41e7fca07a97ee52db3a125d106dfaf17ff5", + "source_tree": "sha256:b4123b259e0bc63e39da5f9b3ec724ec27467e9976900129563ec5d54c32f961" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 9ac008e1..0a0284b6 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -58,7 +58,7 @@ }, { "digest": "438c62d03d5cc14b9d2b663dbdd54dbd4153124e759bd3a97467e8dc0f5a6f74", - "last_commit": "101c710", + "last_commit": "a8bf02b", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, @@ -81,8 +81,8 @@ "purpose": "Directory native/kernel/mm. Purpose not yet described by a human." }, { - "digest": "5901ee6ca8dd0417ed55c72cc01cb3c2e9d55d71cd91d89f9cad9e6901e7a64e", - "last_commit": "101c710", + "digest": "7d18df01ff7941ffed2ed82d18fed6ab5b635156333da8ae33d698756bf15e14", + "last_commit": "453f41e", "name": "svc", "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, @@ -99,15 +99,15 @@ "purpose": "Directory native/kernel/tools. Purpose not yet described by a human." } ], - "children_root": "sha256:dcf283b3305e4989150c05c97b1dd3fac672a0112769ddc7adab58e773bbc806", - "compiled_at": "2026-10-12T06:35:59Z", + "children_root": "sha256:49fd3831250168da5ac9a5e1d4066b65af70cc1780e3547b9c5f974f2dbb0a2d", + "compiled_at": "2026-10-12T07:42:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:169522946ffcd95a36106c1d8a0f6bdba1130e97a5b8dad204696a7245de1948", + "digest": "sha256:4cbfcc2d3ce9c2956be80604f8c41d1eb0e87d06d20a999fc8ebe579d95dfb8b", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 298, - "generated_at_commit": "101c710b24fad41fc9a8797222e366ed71e6b6f2", - "source_tree": "sha256:1b874766907d3cf7dab922682886f87da433f84c1b2622334df9f30b405636a0" + "files": 305, + "generated_at_commit": "453f41e7fca07a97ee52db3a125d106dfaf17ff5", + "source_tree": "sha256:3f01b77765ab6778ee9fc8e79002e2258ea8a9ec11be41d09753b4824b0946be" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 96d1af59..0561227e 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -806,7 +806,7 @@ are this adapter's choices (UNVERIFIED against a frozen contract). (5) The reque bytes; the contract's exact digest input is not defined (UNVERIFIED). (6) The "task" is the adapter's session; the EL0 shell units hold no capability (caps=0) and the check is made by the kernel-side adapter. -## LIFECYCLE: resident production lifecycle (native v1 plan P03, C-only) -> CK `LIFECYCLE` (scripts/qemu_ck_lifecycle_test.sh) +## LIFECYCLE: resident production lifecycle (native v1 plan P03, P06 cut 3 host rows 177-178, C-only) -> CK `LIFECYCLE` (scripts/qemu_ck_lifecycle_test.sh) The product boundary. A `CK_SERVICE=1` image (`full-service/`, allowed with `CK_HARDWARE_STAGING`, refused with every TEST-only flag) links `core/lifecycle.c` + `core/lifecycle_fsm.c`: after every boot stage the kernel serves bounded operator requests on the serial console (states init, locked, ready, serve, quiesce, stop; verbs status, unlock, task , approve, deny, cancel, evidence, help, shutdown; one 64-byte line, one 48-byte task, one pending task at a time) until `shutdown`, then runs the stop order (Store closed, NVMe normal shutdown + bus master off + SMMU stream to abort, final report, reset) instead of resetting at once. The diagnostic images are unchanged (the weak `ck_lifecycle_run` is absent). The production key source still refuses (no in-kernel K_vol unwrap, P04), so the production service image comes up LOCKED. The TEST-ONLY `CK_SERVICE_TEST_KEYS=1` image (`full-service-testkeys/`, refused with `CK_HARDWARE_STAGING`) opens the Store with the TEST keys so the ready/serve/commit paths run in QEMU. Host test: `tests/test_lifecycle.c` (`make test`, 41 checks on the state machine and decoder). QEMU qualifies nothing physical. @@ -828,3 +828,5 @@ The product boundary. A `CK_SERVICE=1` image (`full-service/`, allowed with `CK_ | 171 | P05 cut 1, production continuity GENESIS (unlock boot, after `store: unlock ok`): `svc/continuity_service.c` (linked only into `CK_SERVICE` images; the TEST-ONLY mode selection `continuity_boot.c`, the `AIENCONT` plan line and the Recovery Core are not) finds the Store unprovisioned and mints the identity (AgentRoot, genesis AgentState, Manifest incarnation 1) and the ALLEN subject (kind 24, sequence 1) in ONE sealed transaction (`svc/continuity_subject_provision.c`, generation 3) with entropy from the kernel RNDR service: `continuity: genesis source=qualification provenance=store-uuid-only`, `continuity: PROVISIONED agent=<64 hex> incarnation=1 sequence=1 cortex=0 branches=1`, `allen: GENESIS subject=<64 hex> sequence=1 lineage=<64 hex> intents=0 active=0 knowledge=0`; order `unlock ok` < `PROVISIONED` < `lifecycle: unlock ok`; `status` reports `continuity=provisioned agent=<16 hex> incarnation=1 subject_seq=1`. Genesis inputs are public and deterministic: provenance = SHA-256("AIENOS/ALLEN/PROVENANCE-V1" \|\| owner root public key (hardware staging image) \|\| store uuid), cortex lineage = SHA-256("AIENOS/ALLEN/CORTEX-LINEAGE-V1" \|\| store uuid): the Cortex of this subject is the sealed Store on this disk (CURRENT_EXECUTION_PLAN addendum, conflict 3). A hardware staging service image uses `source=operator` and the owner root key (`ck_owner_root_pk`) | LIFECYCLE / M4_CONTINUITY / M4_ALLEN | QEMU PASS (hardware NOT_RUN) | | 172 | P05 cut 1, production continuity RESUME (relock boot, cold start of the same disk): the ALLEN subject is restored read-only first (`allen: RESTORED ... sequence=1`; absent, corrupt, forked or foreign: REFUSED, nothing written, never minted over), then `cr_resume` commits incarnation 2 (generation 6): `continuity: RESUMED agent= incarnation=2 sequence=2 cortex=0 branches=1`; no second genesis, no degraded mount; order `unlock ok` < `RESUMED` < `lifecycle: unlock ok`; `status` reports `continuity=resumed ... incarnation=2 subject_seq=1`; after the wrong secret `status` reports `continuity=none`. Host rig (`stage_test` `test_continuity_service`): provisioned at generation 3, resumed at incarnation 2 then 3 on the same agent, an entropy refusal on a fresh Store leaves the disk byte-identical and the state `refused` (not writable) | LIFECYCLE / M4_CONTINUITY / M4_ALLEN | QEMU PASS (hardware NOT_RUN) | | 173 | shape and refusal path: the locked service boot prints no `continuity:` or `allen:` line (nothing runs before the Store opens); the test-keys image provisions at boot before `store: service lifetime: Store open`; the service EFI carries `continuity: REFUSED` and neither `AIENCONT` nor `RECOVERY_OPERATOR_KEY` (Makefile `cont_check` for `CK_SERVICE` images: `cr_provision`/`cr_resume` allowed, `ck_cont_boot_stage`/`rc_inspect` and the uppercase `CONTINUITY: ` markers refused; the markers are fenced out of `continuity_commit.c` under `CK_SERVICE`). A refusal (`continuity: REFUSED step=... outcome=... store_rc=...`) erases the Store keys, leaves the disk as found and keeps the lifecycle LOCKED with the NVMe bound for the stop order (`store: service lifetime: continuity REFUSED ...`, `ContinuityRefused rc=-2007`); `approve` is refused on a degraded (read-only) mount. Limits: the approved note is a plain Store object, not yet a continuity WAL / Cortex record (P06 CxStore adapter); no Recovery Core in the service image (its operator key is TEST-only); aienos#285 resource incarnations are NOT triggered (continuity objects are Store objects, not ADR 0013 domain-1 channels/objects); physical NVMe geometry, confined DMA, flush, shutdown and interrupted-transaction qualification (aienos#31) NOT_RUN | LIFECYCLE / M4_CONTINUITY | QEMU PASS + LIMIT (declared) | +| 177 | P06 cut 3, canonical Omega Cortex store over the sealed Store (`third_party/omega/rx_cortex.c` at omega `362c9ab`, built freestanding by `svc/cortex_store.c`; journal = `svc/cortex_journal.c`, kind `0x434a` 'CJ' chunks of <= 16 KiB, one Cortex record = one sealed transaction, truncate only at the current length): host test `test_cortex_journal` in `svc/tests/stage_test.c`: a blank Store gets the 32-byte header as one generation; three records are three generations and `cx_verify_chain` passes; a second writable open is `CX_ERR_WRITER` while read-only opens are served; `truncate(len)` OK and `truncate(len-1)` `CX_ERR_IO`; a record above 128 KiB is refused (`CX_ERR_IO`) with memory and Store generation unchanged; a 40000-byte payload is three chunks of one transaction; reopen on the same mount and after a cold start replays all five records (40760 bytes, 8 chunks, heap peak 287 KiB); another subject count is `CX_ERR_FORMAT`; an in-memory edit is `CX_ERR_DIGEST`; a 256-byte heap makes the open `CX_ERR_NOMEM` without a write | LIFECYCLE (host, `make stage-test` and `stage-sanitize`) | PASS (host test, 2026-10-12, `CK_STAGE_HOST: PASS checks=772`, ASan + UBSan clean; kernel use of the journal is the next P06 cut; hardware NOT_RUN) | +| 178 | the vendored files equal omega `362c9ab50c8ecc3012dd2e3ac20329865ba80982` (`omega.lock`, `scripts/omega_lock_check.sh`: offline sha256 always, the omega blob when reachable; an edited copy FAILs) and the adapter compiles freestanding (`make stage-free`: `CK_STAGE_FREE: PASS objects=45`, undefined symbols are ck.h services only); the `CK_SERVICE` image links `cx_open_with`, `cx_append`, `ck_cj_init`, `ck_cx_heap_init` and no `malloc`/`open`/`fsync` | LIFECYCLE (host) | PASS (host, 2026-10-12; both checks run in CI from this cut) | diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 51f21ecc..3f58626a 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -653,6 +653,8 @@ FULL_NAME := full-service$(if $(strip $(CK_HARDWARE_STAGING)),-hardware-staging, STAGE_DMA_FLAGS += -DCK_SERVICE=1 endif STAGE_SRCS += $(KDIR)/core/lifecycle.c $(KDIR)/core/lifecycle_fsm.c +# P06 cut 3: the canonical Omega Cortex store over the sealed Store (svc/cortex_journal.c). +STAGE_SRCS += $(STAGE_CORTEX_SRCS) # P05 cut 1: production continuity on the service lifecycle (svc/continuity_service.c): # the continuity layer without its TEST-ONLY mode selection (continuity_boot.c) # and without the Recovery Core (continuity_recovery.c, TEST operator key). diff --git a/native/kernel/README.md b/native/kernel/README.md index dbe11c2f..1ec8e948 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -13,6 +13,7 @@ QEMU qualifies nothing physical: a PASS here says nothing about real hardware. | `mm/` | Frame allocator (UEFI map), 4 KiB-granule page-table builder, heap, the kernel address space (`mmu.c`). | | `core/` | Console, printf, ACPI, reports/panic/PSCI reset, M3 (threads, scheduler, EL0, capabilities, IPC), `kmain.c`. | | `tests/` | Host unit tests. | +| `third_party/omega/` | The canonical Omega Cortex store, byte for byte from the omega commit in `omega.lock` (checked by `scripts/omega_lock_check.sh`); built freestanding by `svc/cortex_store.c` over the sealed Store through `svc/cortex_journal.c` (native v1 plan P06). | | `../boot/` | Minimal UEFI entry stub (one image with the kernel). | ## Build and test diff --git a/native/kernel/stage.mk b/native/kernel/stage.mk index f1cd1808..37faf5ce 100644 --- a/native/kernel/stage.mk +++ b/native/kernel/stage.mk @@ -41,6 +41,11 @@ STAGE_NATIVE_SRCS := \ STAGE_KERNEL_SRCS := $(STAGE_DIR)/svc/ck_compat.c STAGE_SRCS := $(STAGE_OWN_SRCS) $(STAGE_NATIVE_SRCS) $(STAGE_KERNEL_SRCS) +# P06 cut 3: the canonical Omega Cortex store (third_party/omega, pinned by +# omega.lock) over the sealed Store. Linked into the CK_SERVICE image by the +# kernel Makefile; compiled freestanding here so stage-free proves the link. +STAGE_CORTEX_SRCS := $(STAGE_DIR)/svc/cortex_store.c $(STAGE_DIR)/svc/cortex_journal.c +STAGE_FREE_SRCS := $(STAGE_SRCS) $(STAGE_CORTEX_SRCS) STAGE_INC := -I$(STAGE_DIR)/include -I$(STAGE_DIR)/dev -I$(STAGE_DIR)/svc \ -I$(STAGE_NATIVE)/disk -I$(STAGE_NATIVE)/store -I$(STAGE_NATIVE)/m5 -I$(STAGE_NATIVE)/crypto \ @@ -67,14 +72,14 @@ STAGE_ALLOWED_U := ck_puts ck_printf ck_vprintf ck_panic ck_alloc ck_free ck_dma ck_entropy_fill ck_entropy_status ck_entropy_reason \ ck_console_rx_ready ck_console_rx_poll ck_console_uart_name ck_console_uart_base -STAGE_FREE_OBJS := $(foreach s,$(STAGE_SRCS),$(STAGE_OUT)/free/$(subst /,_,$(subst $(STAGE_NATIVE)/,,$(s:.c=.o)))) +STAGE_FREE_OBJS := $(foreach s,$(STAGE_FREE_SRCS),$(STAGE_OUT)/free/$(subst /,_,$(subst $(STAGE_NATIVE)/,,$(s:.c=.o)))) define stage_free_rule $(STAGE_OUT)/free/$(subst /,_,$(subst $(STAGE_NATIVE)/,,$(1:.c=.o))): $(1) @mkdir -p $$(@D) $$(STAGE_CC) $$(STAGE_FREE_FLAGS) $$(STAGE_CFLAGS) -c -o $$@ $$< endef -$(foreach s,$(STAGE_SRCS),$(eval $(call stage_free_rule,$(s)))) +$(foreach s,$(STAGE_FREE_SRCS),$(eval $(call stage_free_rule,$(s)))) $(STAGE_OUT)/stage_all.o: $(STAGE_FREE_OBJS) $(STAGE_LD) -r -o $@ $^ @@ -96,7 +101,7 @@ STAGE_CONT_SRCS := $(STAGE_DIR)/svc/continuity_codec.c $(STAGE_DIR)/svc/continui $(STAGE_DIR)/svc/continuity_subject.c $(STAGE_DIR)/svc/continuity_subject_provision.c $(STAGE_DIR)/svc/continuity_service.c \ $(STAGE_DIR)/core/entropy.c $(STAGE_DIR)/core/fmt.c STAGE_HOST_SRCS := $(STAGE_OWN_SRCS) $(STAGE_DIR)/core/ipc.c $(STAGE_NATIVE_SRCS) $(STAGE_NATIVE)/disk/disk_file.c \ - $(STAGE_CONT_SRCS) $(STAGE_DIR)/svc/tests/ck_host.c $(STAGE_DIR)/svc/tests/stage_test.c + $(STAGE_CONT_SRCS) $(STAGE_CORTEX_SRCS) $(STAGE_DIR)/svc/tests/ck_host.c $(STAGE_DIR)/svc/tests/stage_test.c STAGE_HOST_FLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -pthread -DCK_ART_STORE_WRITER -DCK_HOST_TEST \ -DCK_CONT_SERVICE_HOST_TEST -I$(STAGE_DIR)/core STAGE_SAN_FLAGS := -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer diff --git a/native/kernel/svc/.crumb b/native/kernel/svc/.crumb index 2d338c75..99964ed4 100644 --- a/native/kernel/svc/.crumb +++ b/native/kernel/svc/.crumb @@ -23,21 +23,21 @@ "purpose": "Directory native/kernel/svc/compat. Purpose not yet described by a human." }, { - "digest": "4e044d7fe1d514bd13baa4e84872a66e46f96b86c7a7589d14489aec0978e366", - "last_commit": "101c710", + "digest": "88c4fc1ed3ed47dc767deb9c59923934ca9b73b66aabec84a2c3e19cebdf8283", + "last_commit": "453f41e", "name": "tests", "purpose": "Directory native/kernel/svc/tests. Purpose not yet described by a human." } ], - "children_root": "sha256:e44defe690939de314fec75a24c9369748bd9153c9511478d13fb58173a1ea74", - "compiled_at": "2026-10-12T06:35:59Z", + "children_root": "sha256:c08ae620be123d4ae06a01d1830984c81570c3c44fc528987cee2ad37c3c2ca9", + "compiled_at": "2026-10-12T07:42:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:5901ee6ca8dd0417ed55c72cc01cb3c2e9d55d71cd91d89f9cad9e6901e7a64e", + "digest": "sha256:7d18df01ff7941ffed2ed82d18fed6ab5b635156333da8ae33d698756bf15e14", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 37, - "generated_at_commit": "101c710b24fad41fc9a8797222e366ed71e6b6f2", - "source_tree": "sha256:b38670ec128a2b278c0e948e306d7aa50e4b350e3d0aa35f1efaf94658813624" + "files": 41, + "generated_at_commit": "453f41e7fca07a97ee52db3a125d106dfaf17ff5", + "source_tree": "sha256:f5ce71ef8038e16c2de685108d74a32c41ee82205eae65a77aa3b8301f3ada77" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/svc/cortex_config.h b/native/kernel/svc/cortex_config.h new file mode 100644 index 00000000..18b98760 --- /dev/null +++ b/native/kernel/svc/cortex_config.h @@ -0,0 +1,14 @@ +/* cortex_config.h -- CX_CONFIG_H for the vendored Omega Cortex store + * (third_party/omega/rx_cortex.c) inside AIENOS. The kernel has no general + * heap: the store's allocations come from one bounded region handed over + * by ck_cx_heap_init (svc/cortex_journal.c). */ +#ifndef AIENOS_CORTEX_CONFIG_H +#define AIENOS_CORTEX_CONFIG_H +#include +void *ck_cx_alloc(size_t n); +void *ck_cx_realloc(void *p, size_t n); +void ck_cx_free(void *p); +#define CX_MALLOC(n) ck_cx_alloc(n) +#define CX_REALLOC(p, n) ck_cx_realloc((p), (n)) +#define CX_FREE(p) ck_cx_free(p) +#endif diff --git a/native/kernel/svc/cortex_journal.c b/native/kernel/svc/cortex_journal.c new file mode 100644 index 00000000..533836ca --- /dev/null +++ b/native/kernel/svc/cortex_journal.c @@ -0,0 +1,192 @@ +/* cortex_journal.c -- CxJournalOps over the sealed Store, and the bounded + * Cortex heap. See cortex_journal.h. No I/O except through ss_read / + * ss_transact; no libc beyond the four memory routines. */ +#include "cortex_journal.h" + +#include + +/* ---- heap ---------------------------------------------------------------- */ +static struct { + uint8_t *base; + size_t size, used, peak; +} g_h; + +void ck_cx_heap_init(void *base, size_t size) +{ + g_h.base = base; + g_h.size = base ? size : 0; + g_h.used = 0; + g_h.peak = 0; +} + +void ck_cx_heap_stats(size_t *used, size_t *peak, size_t *size) +{ + if (used) *used = g_h.used; + if (peak) *peak = g_h.peak; + if (size) *size = g_h.size; +} + +/* Each block carries its size in the 16 bytes before it (16-byte alignment). */ +void *ck_cx_alloc(size_t n) +{ + size_t need = (n + 15u) & ~(size_t)15u; + if (!g_h.base || need > g_h.size - g_h.used || g_h.size - g_h.used - need < 16u) return 0; + uint8_t *p = g_h.base + g_h.used + 16u; + ((size_t *)(p - 16u))[0] = n; + g_h.used += need + 16u; + if (g_h.used > g_h.peak) g_h.peak = g_h.used; + return p; +} + +void *ck_cx_realloc(void *p, size_t n) +{ + if (!p) return ck_cx_alloc(n); + size_t old = ((size_t *)((uint8_t *)p - 16u))[0]; + if (n <= old) return p; + void *q = ck_cx_alloc(n); + if (!q) return 0; + memcpy(q, p, old); + return q; +} + +void ck_cx_free(void *p) { (void)p; } + +/* ---- journal ------------------------------------------------------------- */ +void ck_cj_init(ck_cj *j, ss_store *s) +{ + memset(j, 0, sizeof *j); + j->s = s; +} + +/* Rebuild the chunk index from the Store's verified claims, ordered by + * (store generation, object sequence): the order the chunks were committed. */ +static int cj_index(ck_cj *j) +{ + uint32_t k, i; + j->nchunks = 0; + j->len = 0; + for (k = 0; k < j->s->nclaims; k++) { + const ss_claim *c = &j->s->ws->claims[k]; + if (c->c.obj.object_kind != CK_CJ_KIND) continue; + if (j->nchunks >= CK_CJ_MAX_CHUNKS) return CX_ERR_IO; + ck_cj_chunk e; + memcpy(e.sid, c->sid, 32); + e.gen = c->c.store_generation; + e.seq = c->c.object_sequence; + e.len = 0; + for (i = j->nchunks; i > 0; i--) { + const ck_cj_chunk *p = &j->chunks[i - 1]; + if (p->gen < e.gen || (p->gen == e.gen && p->seq < e.seq)) break; + j->chunks[i] = *p; + } + j->chunks[i] = e; + j->nchunks++; + } + /* Lengths come from the envelopes themselves (one decrypt per chunk). */ + for (k = 0; k < j->nchunks; k++) { + size_t n = 0; + uint16_t kind = 0; + if (ss_read(j->s, j->chunks[k].sid, j->buf, sizeof j->buf, &n, &kind) != 0 || kind != CK_CJ_KIND) return CX_ERR_IO; + j->chunks[k].len = (uint32_t)n; + j->len += n; + } + return CX_OK; +} + +static int cj_open(void *ctx, const char *name, int ro, void **h) +{ + ck_cj *j = ctx; + if (!j || !j->s || !name || !h) return CX_ERR_ARG; + if (!ro && j->writer) { j->refused++; return CX_ERR_WRITER; } + int rc = cj_index(j); + if (rc != CX_OK) return rc; + if (ro) { j->ro_handles++; *h = &j->ro_handles; } + else { j->writer = 1; *h = j; } + return CX_OK; +} + +static int cj_size(void *ctx, void *h, size_t *len) +{ + (void)h; + *len = ((ck_cj *)ctx)->len; + return CX_OK; +} + +static int cj_read(void *ctx, void *h, size_t off, uint8_t *out, size_t n) +{ + ck_cj *j = ctx; + (void)h; + if (off + n > j->len) return CX_ERR_IO; + size_t pos = 0; + uint32_t k; + j->reads++; + for (k = 0; k < j->nchunks && n; k++) { + size_t cl = j->chunks[k].len; + if (off >= pos + cl) { pos += cl; continue; } + size_t got = 0; + uint16_t kind = 0; + if (ss_read(j->s, j->chunks[k].sid, j->buf, sizeof j->buf, &got, &kind) != 0 || got != cl) return CX_ERR_IO; + size_t start = off - pos, take = cl - start; + if (take > n) take = n; + memcpy(out, j->buf + start, take); + out += take; + off += take; + n -= take; + pos += cl; + } + return n ? CX_ERR_IO : CX_OK; +} + +/* One append = one sealed transaction: all chunks durable or none. sync is + * implied (ss_transact returns after the generation is durable). */ +static int cj_append(void *ctx, void *h, const uint8_t *b, size_t n, int sync) +{ + ck_cj *j = ctx; + (void)sync; + if (h != (void *)j) return CX_ERR_IO; /* read-only handle */ + if (n == 0) return CX_OK; + if (n > CK_CJ_MAX_RECORD) { j->refused++; return CX_ERR_IO; } + size_t k = (n + SS_MAX_PLAINTEXT - 1) / SS_MAX_PLAINTEXT; + if (j->nchunks + k > CK_CJ_MAX_CHUNKS) { j->refused++; return CX_ERR_IO; } + ss_object objs[SS_MAX_OBJECTS]; + uint8_t ids[SS_MAX_OBJECTS][32]; + size_t i, left = n; + for (i = 0; i < k; i++) { + size_t cl = left > SS_MAX_PLAINTEXT ? SS_MAX_PLAINTEXT : left; + objs[i].kind = CK_CJ_KIND; + objs[i].version = 1; + objs[i].bytes = b + i * SS_MAX_PLAINTEXT; + objs[i].len = cl; + left -= cl; + } + if (ss_transact(j->s, objs, k, 0, 0, ids) != 0) return CX_ERR_IO; + uint64_t gen = ss_generation(j->s); + for (i = 0; i < k; i++) { + ck_cj_chunk *e = &j->chunks[j->nchunks++]; + memcpy(e->sid, ids[i], 32); + e->gen = gen; + e->seq = i; + e->len = (uint32_t)objs[i].len; + j->len += objs[i].len; + } + j->appends++; + return CX_OK; +} + +/* Appends are atomic, so the journal never holds a torn tail: only the + * current length is accepted. */ +static int cj_truncate(void *ctx, void *h, size_t len) +{ + ck_cj *j = ctx; + if (h != (void *)j) return CX_ERR_IO; + return len == j->len ? CX_OK : CX_ERR_IO; +} + +static void cj_close(void *ctx, void *h) +{ + ck_cj *j = ctx; + if (h == (void *)j) j->writer = 0; + else if (j->ro_handles) j->ro_handles--; +} + +const CxJournalOps ck_cx_journal_store = { cj_open, cj_size, cj_read, cj_append, cj_truncate, cj_close }; diff --git a/native/kernel/svc/cortex_journal.h b/native/kernel/svc/cortex_journal.h new file mode 100644 index 00000000..7447f74f --- /dev/null +++ b/native/kernel/svc/cortex_journal.h @@ -0,0 +1,69 @@ +/* cortex_journal.h -- the Omega Cortex journal over the AIENOS sealed Store + * (native v1 plan P06: "an AIENOS persistence adapter for canonical Omega + * CxStore"; CURRENT_EXECUTION_PLAN addendum conflict 3: the native + * continuity record of N2/N3 is the sealed C Store written and read through + * this adapter). + * + * The Cortex store (third_party/omega/rx_cortex.c, built by svc/cortex_store.c) + * reaches its journal only through CxJournalOps: a byte stream it appends + * records to and reads back whole at open. Here the stream is the ordered + * sequence of sealed Store objects of kind CK_CJ_KIND ('CJ'): one append is + * ONE sealed transaction of 1..SS_MAX_OBJECTS chunks of <= SS_MAX_PLAINTEXT + * bytes, so a record is on the disk entirely (generation G+1 durable, anchor + * advanced) or not at all. That is the durability-before-success rule and + * why a torn tail cannot exist: truncate accepts only the current length. + * One semantic writer: the kernel's single ck_cj context; a second writable + * open while one is held is CX_ERR_WRITER. Chain verification, digests and + * replay are Omega's, unchanged: the backend stores bytes and never + * interprets them. There is no second Cortex: the sealed Store on the disk + * IS the Cortex of this subject. + * + * Declared limits (v1): a journal of at most CK_CJ_MAX_CHUNKS chunks + * (CK_CJ_MAX_CHUNKS * 16 KiB), one record of at most SS_MAX_OBJECTS * + * SS_MAX_PLAINTEXT bytes (larger: CX_ERR_IO, nothing written), replay reads + * the whole journal into the Cortex heap, the heap is a bump allocator that + * frees nothing until ck_cx_heap_init is called again (sized by the caller; + * the kernel hands over CK_CX_HEAP_PAGES frames). Kernel use (the + * lifecycle's remembered facts) is the next P06 cut. */ +#ifndef AIENOS_CORTEX_JOURNAL_H +#define AIENOS_CORTEX_JOURNAL_H + +#include +#include + +#include "../third_party/omega/rx_cortex.h" +#include "store_sealed.h" + +#define CK_CJ_KIND 0x434au /* 'CJ': one journal chunk, sealed */ +#define CK_CJ_MAX_CHUNKS 64u /* 1 MiB of journal */ +#define CK_CJ_MAX_RECORD (SS_MAX_OBJECTS * SS_MAX_PLAINTEXT) /* 128 KiB per append */ +#define CK_CX_HEAP_PAGES 1024u /* 4 MiB: the whole journal plus its replay */ + +typedef struct { + uint8_t sid[32]; + uint64_t gen, seq; + uint32_t len; +} ck_cj_chunk; + +typedef struct { + ss_store *s; + int writer; /* 1 while a writable handle is open */ + int ro_handles; + size_t len; /* journal bytes = sum of chunk lengths */ + uint32_t nchunks; + ck_cj_chunk chunks[CK_CJ_MAX_CHUNKS]; + uint8_t buf[SS_MAX_PLAINTEXT]; + uint32_t appends, reads, refused; /* evidence */ +} ck_cj; + +/* Bind the context to an open sealed Store (the index is rebuilt at every + * journal open from the Store's verified claims). */ +void ck_cj_init(ck_cj *j, ss_store *s); +extern const CxJournalOps ck_cx_journal_store; + +/* The Cortex heap (CX_MALLOC of cortex_config.h): one region, bump + * allocation, realloc copies, free is a no-op. Re-init forgets everything. */ +void ck_cx_heap_init(void *base, size_t size); +void ck_cx_heap_stats(size_t *used, size_t *peak, size_t *size); + +#endif /* AIENOS_CORTEX_JOURNAL_H */ diff --git a/native/kernel/svc/cortex_store.c b/native/kernel/svc/cortex_store.c new file mode 100644 index 00000000..5710df59 --- /dev/null +++ b/native/kernel/svc/cortex_store.c @@ -0,0 +1,9 @@ +/* cortex_store.c -- the canonical Omega Cortex store (CxStore) built + * freestanding inside AIENOS: no POSIX journal, no libc allocation. The + * source is vendored byte for byte from the omega.lock commit + * (third_party/omega/rx_cortex.c, checked by scripts/omega_lock_check.sh); + * this wrapper only sets the build switches so the vendored file stays + * identical to Omega's. The journal backend is svc/cortex_journal.c. */ +#define CX_NO_POSIX 1 +#define CX_CONFIG_H "cortex_config.h" +#include "../third_party/omega/rx_cortex.c" diff --git a/native/kernel/svc/tests/.crumb b/native/kernel/svc/tests/.crumb index 6b5a9665..08eb60a6 100644 --- a/native/kernel/svc/tests/.crumb +++ b/native/kernel/svc/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T06:35:59Z", + "compiled_at": "2026-10-12T07:42:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:4e044d7fe1d514bd13baa4e84872a66e46f96b86c7a7589d14489aec0978e366", + "digest": "sha256:88c4fc1ed3ed47dc767deb9c59923934ca9b73b66aabec84a2c3e19cebdf8283", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 3, - "generated_at_commit": "101c710b24fad41fc9a8797222e366ed71e6b6f2", - "source_tree": "sha256:4596e6dfcbec6b205ed0d7563bf337e369f97bc54428471b4754ee91d9957bc4" + "generated_at_commit": "453f41e7fca07a97ee52db3a125d106dfaf17ff5", + "source_tree": "sha256:73a6938e36e2d95d4f34a467b57ae383849f960dd994adc0c75d1a396140f6bb" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/svc/tests/stage_test.c b/native/kernel/svc/tests/stage_test.c index fafbf8e8..e201c2d2 100644 --- a/native/kernel/svc/tests/stage_test.c +++ b/native/kernel/svc/tests/stage_test.c @@ -22,6 +22,7 @@ #include "store_boot.h" #include "continuity_service.h" #include "artifact_store.h" +#include "cortex_journal.h" #include "sha256.h" #include "net_bind.h" #include "net_udp.h" @@ -2318,6 +2319,137 @@ static void test_mmio_stage_report(void) munmap(regs, WIN_BYTES); } +/* ---- P06 cut 3: the Omega Cortex journal over the sealed Store ---------- */ +#define CJ_UNITS 1024u +static int cj_dopen(int create) +{ + if (create) unlink(img); + return disk_file_open(&g_f, &g_d, img, T_BS, (uint64_t)CJ_UNITS * T_BPU, create); +} +static uint8_t cj_heap[4u << 20]; +static ck_cj cj_ctx; +static uint64_t cj_mid[5000]; /* 40000-byte payload: three sealed chunks */ + +static void test_cortex_journal(void) +{ + printf(" [cortex journal: canonical Omega CxStore records over the sealed Store]\n"); + snprintf(img, sizeof img, "/tmp/ck_stage_cj_%d.img", (int)getpid()); + ss_keys k; + ck_store_test_keys(&k); + ck_store_report r; + CxStore cx, cx2; + CxHeader h; + uint64_t id = 0, ids[3] = { 0, 0, 0 }, pay[2]; + size_t i; + for (i = 0; i < 5000; i++) cj_mid[i] = 0x9e3779b97f4a7c15ull * (i + 1); + + CHECK(cj_dopen(1) == 0); + CHECK(store_boot_run(&g_d, &k, ck_store_test_uuid, "cj-1", &r) == 0 && r.formatted == 1); + ss_store *s = store_boot_store(); + uint64_t g0 = ss_generation(s); + ck_cx_heap_init(cj_heap, sizeof cj_heap); + ck_cj_init(&cj_ctx, s); + + /* a blank Store holds no journal: the first writable open writes the + * 32-byte header as one sealed transaction */ + CHECK(cx_open_with(&cx, &ck_cx_journal_store, &cj_ctx, "cortex", 4, 0) == CX_OK); + CHECK(ss_generation(s) == g0 + 1 && cj_ctx.len == 32 && cj_ctx.nchunks == 1 && cx.n == 0); + /* one semantic writer: a second writable open is refused, read-only is not */ + CHECK(cx_open_with(&cx2, &ck_cx_journal_store, &cj_ctx, "cortex", 4, 0) == CX_ERR_WRITER && cj_ctx.refused == 1); + CHECK(cx_open_with(&cx2, &ck_cx_journal_store, &cj_ctx, "cortex", 0, CX_OPEN_READONLY) == CX_OK && cx2.n == 0); + cx_close(&cx2); + CHECK(cj_ctx.writer == 1 && cj_ctx.ro_handles == 0); + + /* three records: each is exactly one Store generation */ + memset(&h, 0, sizeof h); + h.cls = CX_CLAIM; + h.kind = CX_K_CLAIM; + h.subject = 1; + h.generation = 1; + for (i = 0; i < 3; i++) { + h.t = i + 1; + pay[0] = 0x100 + i; + pay[1] = ~(uint64_t)i; + CHECK(cx_append(&cx, &h, pay, 2, &ids[i]) == CX_OK && ids[i] == i + 1); + CHECK(ss_generation(s) == g0 + 2 + i); + } + CHECK(cx.n == 3 && cx_verify_chain(&cx) == CX_OK && cj_ctx.nchunks == 4 && cj_ctx.appends == 4); + size_t len3 = cj_ctx.len; + /* no torn tail can exist: truncate accepts only the current length */ + CHECK(ck_cx_journal_store.truncate(&cj_ctx, cx.jh, len3) == CX_OK); + CHECK(ck_cx_journal_store.truncate(&cj_ctx, cx.jh, len3 - 1) == CX_ERR_IO); + /* a record above CK_CJ_MAX_RECORD is refused before any write; memory and + * the Store are unchanged */ + { + uint64_t gb = ss_generation(s); + h.t = 10; + CHECK(cx_append(&cx, &h, cj_mid, 0, &id) == CX_OK && id == 4); /* empty payload is fine */ + gb = ss_generation(s); + static uint64_t big[CK_CJ_MAX_RECORD / 8 + 16]; + h.t = 11; + id = 0; + CHECK(cx_append(&cx, &h, big, (uint32_t)(CK_CJ_MAX_RECORD / 8), &id) == CX_ERR_IO && id == 0); + CHECK(cx.n == 4 && ss_generation(s) == gb && cj_ctx.refused == 2 && cx_verify_chain(&cx) == CX_OK); + } + /* a 40000-byte payload spans three sealed chunks of one transaction */ + { + uint64_t gb = ss_generation(s); + uint32_t nb = cj_ctx.nchunks; + h.t = 12; + CHECK(cx_append(&cx, &h, cj_mid, 5000, &id) == CX_OK && id == 5); + CHECK(ss_generation(s) == gb + 1 && cj_ctx.nchunks == nb + 3); + } + cx_close(&cx); + CHECK(cj_ctx.writer == 0); + + /* reopen on the same mount: replay, digests and chain are Omega's checks */ + CHECK(cx_open_with(&cx, &ck_cx_journal_store, &cj_ctx, "cortex", 4, 0) == CX_OK && cx.n == 5); + CHECK(cx_verify_chain(&cx) == CX_OK); + { + const CxObject *o = cx_get(&cx, 5); + CHECK(o && o->n == 5000 && o->t == 12 && memcmp(cx_payload(&cx, o), cj_mid, 40000) == 0); + o = cx_get(&cx, 2); + CHECK(o && o->t == 2 && cx_payload(&cx, o)[0] == 0x101); + } + cx_close(&cx); + /* another subject count is another journal */ + CHECK(cx_open_with(&cx, &ck_cx_journal_store, &cj_ctx, "cortex", 5, 0) == CX_ERR_FORMAT && cj_ctx.writer == 0); + dclose(); + + /* cold start: a fresh mount, a fresh heap, the same five records */ + CHECK(cj_dopen(0) == 0); + CHECK(store_boot_run(&g_d, &k, ck_store_test_uuid, "cj-2", &r) == 0 && r.formatted == 0); + s = store_boot_store(); + ck_cx_heap_init(cj_heap, sizeof cj_heap); + ck_cj_init(&cj_ctx, s); + CHECK(cx_open_with(&cx, &ck_cx_journal_store, &cj_ctx, "cortex", 4, 0) == CX_OK && cx.n == 5); + CHECK(cx_verify_chain(&cx) == CX_OK && cj_ctx.appends == 0 && cj_ctx.reads >= 1 && cj_ctx.nchunks == 8); + { + const CxObject *o = cx_get(&cx, 5); + CHECK(o && memcmp(cx_payload(&cx, o), cj_mid, 40000) == 0); + /* an in-memory edit is caught by Omega's digest check */ + cx_tamper(&cx, 3, 0, 77); + CHECK(cx_verify(&cx, 3) == CX_ERR_DIGEST && cx_verify(&cx, 2) == CX_OK); + } + { + size_t used = 0, peak = 0, size = 0; + ck_cx_heap_stats(&used, &peak, &size); + CHECK(used > 0 && peak <= size && size == sizeof cj_heap); + printf(" cortex journal: bytes=%zu chunks=%u heap_peak_kib=%zu\n", cj_ctx.len, cj_ctx.nchunks, peak / 1024); + } + cx_close(&cx); + /* a heap too small for the replay: refused, nothing written */ + { + uint64_t gb = ss_generation(s); + ck_cx_heap_init(cj_heap, 256); + ck_cj_init(&cj_ctx, s); + CHECK(cx_open_with(&cx, &ck_cx_journal_store, &cj_ctx, "cortex", 4, 0) == CX_ERR_NOMEM); + CHECK(ss_generation(s) == gb && cj_ctx.writer == 0); + } + dclose(); + unlink(img); +} + int main(void) { setvbuf(stdout, NULL, _IOLBF, 0); @@ -2341,6 +2473,7 @@ int main(void) test_store(); test_unlock_recovery(); test_continuity_service(); + test_cortex_journal(); test_artifact_store(); test_security(); test_nvme_shutdown(); diff --git a/native/kernel/third_party/omega/README.md b/native/kernel/third_party/omega/README.md new file mode 100644 index 00000000..39f40643 --- /dev/null +++ b/native/kernel/third_party/omega/README.md @@ -0,0 +1,16 @@ +# Vendored Omega sources + +`rx_cortex.c` and `rx_cortex.h` are the canonical Omega Cortex store +(`src/runtime/` of https://github.com/aien-dev/omega), copied byte for byte +from the commit named on line 1 of `omega.lock` at the repository root. +Both repositories are AGPL-3.0; the copyright stays with the Omega authors. + +Rules: +- Never edit these files here. A change goes to Omega first; then the copy is + refreshed and `omega.lock` updated (commit sha and sha256 lines). +- `scripts/omega_lock_check.sh` (CI, workflow ck-kernel.yml) fails when a + file differs from its recorded sha256, and when it can reach the omega + commit, when the recorded sha256 differs from that commit's file. +- AIENOS builds them through `svc/cortex_store.c` (`CX_NO_POSIX`, + `CX_CONFIG_H` = `svc/cortex_config.h`) and backs the journal with + `svc/cortex_journal.c` over the sealed Store. Native v1 plan P06. diff --git a/native/kernel/third_party/omega/rx_cortex.c b/native/kernel/third_party/omega/rx_cortex.c new file mode 100644 index 00000000..d3f42df0 --- /dev/null +++ b/native/kernel/third_party/omega/rx_cortex.c @@ -0,0 +1,616 @@ +/* + * rx_cortex.c -- Cortex, canonical (M20). See rx_cortex.h. + */ +#include "rx_cortex.h" + +#include "sha256.h" + +#include + +/* Allocation hooks: a freestanding host names a config header through + * CX_CONFIG_H that defines CX_MALLOC(n), CX_REALLOC(p, n) and CX_FREE(p). */ +#ifdef CX_CONFIG_H +#include CX_CONFIG_H +#endif +#ifndef CX_MALLOC +#include +#define CX_MALLOC(n) malloc(n) +#define CX_REALLOC(p, n) realloc((p), (n)) +#define CX_FREE(p) free(p) +#endif + +#ifndef CX_NO_POSIX +#include +#include +#include +#include +#include +#endif + +static void put_u64(sha256_ctx *c, uint64_t v) { + uint8_t b[8]; + for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i)); + sha256_update(c, b, 8); +} + +void cx_digest(const CxObject *o, const uint64_t *payload, uint8_t out[32]) { + static const uint8_t domain[] = "AIEN.CORTEX.OBJECT.V1"; + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, domain, sizeof domain - 1); + put_u64(&c, o->id); + put_u64(&c, ((uint64_t)o->cls << 32) | o->kind); + put_u64(&c, o->subject); + put_u64(&c, o->t); + put_u64(&c, o->generation); + put_u64(&c, ((uint64_t)o->branch << 32) | o->protect); + put_u64(&c, o->tag); + for (uint32_t i = 0; i < CX_LINKS; i++) put_u64(&c, o->links[i]); + put_u64(&c, o->n); + for (uint32_t i = 0; i < o->n; i++) put_u64(&c, payload[i]); + sha256_final(&c, out); +} + +static void chain_step(uint8_t chain[32], const uint8_t digest[32]) { + uint8_t buf[64]; + memcpy(buf, chain, 32); + memcpy(buf + 32, digest, 32); + sha256_hash(buf, sizeof buf, chain); +} + +int cx_init(CxStore *s, uint64_t n_subjects) { + memset(s, 0, sizeof(*s)); + size_t nb = (size_t)(n_subjects ? n_subjects : 1) * sizeof(CxIdList); + s->by_subject = CX_MALLOC(nb); + if (!s->by_subject) return CX_ERR_NOMEM; + memset(s->by_subject, 0, nb); + s->n_subjects = n_subjects; + return CX_OK; +} + +void cx_free(CxStore *s) { + for (uint64_t i = 0; i < s->n_subjects && s->by_subject; i++) CX_FREE(s->by_subject[i].ids); + CX_FREE(s->by_subject); + CX_FREE(s->obj); + CX_FREE(s->arena); + if (s->jops) s->jops->close(s->jctx, s->jh); /* closing drops the writer lock */ + memset(s, 0, sizeof(*s)); +} + +void cx_close(CxStore *s) { cx_free(s); } + +static int grow(void **p, uint64_t *cap, uint64_t need, size_t elem) { + if (need <= *cap) return 0; + uint64_t c = *cap ? *cap : 1024; + while (c < need) c *= 2; + void *q = CX_REALLOC(*p, c * elem); + if (!q) return -1; + *p = q; + *cap = c; + return 0; +} + +/* ---- journal encoding ---------------------------------------------------- */ + +#define CX_J_MAGIC 0x0131584e45494141ull /* journal magic */ +#define CX_J_VERSION 1ull +#define CX_J_HDR_WORDS 4u +#define CX_R_MAGIC 0x4443524f43584355ull /* record marker */ +#define CX_R_FIXED 13u /* marker + 12 header words */ +#define CX_R_DIGEST 4u + +static void le_put(uint8_t *p, uint64_t v) { + for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); +} +static uint64_t le_get(const uint8_t *p) { + uint64_t v = 0; + for (int i = 0; i < 8; i++) v |= (uint64_t)p[i] << (8 * i); + return v; +} + +/* Encode one object as a journal record into a fresh buffer. */ +static uint8_t *encode_record(const CxObject *o, const uint64_t *payload, size_t *out_len) { + size_t words = CX_R_FIXED + o->n + CX_R_DIGEST; + uint8_t *b = CX_MALLOC(words * 8); + if (!b) return NULL; + uint64_t w[CX_R_FIXED] = { + CX_R_MAGIC, o->id, ((uint64_t)o->cls << 32) | o->kind, o->subject, o->t, + o->generation, ((uint64_t)o->branch << 32) | o->protect, o->tag, + o->links[0], o->links[1], o->links[2], o->links[3], o->n + }; + size_t k = 0; + for (uint32_t i = 0; i < CX_R_FIXED; i++, k += 8) le_put(b + k, w[i]); + for (uint32_t i = 0; i < o->n; i++, k += 8) le_put(b + k, payload[i]); + memcpy(b + k, o->digest, 32); + *out_len = words * 8; + return b; +} + +/* ---- append -------------------------------------------------------------- */ + +/* Append into memory. `expect_id` nonzero: replay, the id must match. */ +static int append_mem(CxStore *s, const CxHeader *h, const uint64_t *payload, uint32_t n, + uint64_t expect_id, uint64_t *out_id) { + if (!h || h->cls == 0 || h->cls >= CX_CLASS_END || h->subject >= s->n_subjects || + (n && !payload)) + return CX_ERR_ARG; + if (expect_id && expect_id != s->n + 1) return CX_ERR_FORMAT; + CxIdList *l = &s->by_subject[h->subject]; + if (l->n && s->obj[l->ids[l->n - 1] - 1].t > h->t) return CX_ERR_ORDER; + if (grow((void **)&s->obj, &s->cap, s->n + 1, sizeof(CxObject)) || + grow((void **)&s->arena, &s->arena_cap, s->arena_n + n, sizeof(uint64_t))) + return CX_ERR_NOMEM; + if (l->n == l->cap) { + uint32_t c = l->cap ? l->cap * 2 : 64; + uint64_t *q = CX_REALLOC(l->ids, (size_t)c * sizeof(uint64_t)); + if (!q) return CX_ERR_NOMEM; + l->ids = q; + l->cap = c; + } + CxObject *o = &s->obj[s->n]; + memset(o, 0, sizeof(*o)); + o->id = s->n + 1; + o->cls = h->cls; + o->kind = h->kind; + o->subject = h->subject; + o->t = h->t; + o->generation = h->generation; + o->branch = h->branch; + o->protect = h->protect & CX_PROT_ALL; + o->tag = h->tag; + memcpy(o->links, h->links, sizeof o->links); + o->n = n; + o->off = s->arena_n; + if (n) memcpy(s->arena + s->arena_n, payload, (size_t)n * sizeof(uint64_t)); + s->arena_n += n; + cx_digest(o, s->arena + o->off, o->digest); + chain_step(s->chain, o->digest); + l->ids[l->n++] = o->id; + s->n++; + if (out_id) *out_id = o->id; + return CX_OK; +} + +/* Undo the newest in-memory append (journal write failed). */ +static void unappend_mem(CxStore *s, const uint8_t prev_chain[32]) { + CxObject *o = &s->obj[s->n - 1]; + s->by_subject[o->subject].n--; + s->arena_n = o->off; + s->n--; + memcpy(s->chain, prev_chain, 32); +} + +int cx_append_as(CxStore *s, uint64_t token, const CxHeader *h, const uint64_t *payload, + uint32_t n, uint64_t *out_id) { + if (!s) return CX_ERR_ARG; + if (s->writer != token) return CX_ERR_WRITER; + if (s->open_flags & CX_OPEN_READONLY) return CX_ERR_WRITER; + uint8_t prev[32]; + memcpy(prev, s->chain, 32); + uint64_t id = 0; + int rc = append_mem(s, h, payload, n, 0, &id); + if (rc != CX_OK) return rc; + if (s->jops) { + const CxObject *o = &s->obj[id - 1]; + size_t len = 0; + uint8_t *rec = encode_record(o, s->arena + o->off, &len); + if (!rec) { + unappend_mem(s, prev); + return CX_ERR_NOMEM; + } + /* The backend appends all of the record or none of it; memory never + * runs ahead of the journal. */ + int rc2 = s->jops->append(s->jctx, s->jh, rec, len, (s->open_flags & CX_OPEN_SYNC) != 0); + CX_FREE(rec); + if (rc2 != CX_OK) { + unappend_mem(s, prev); + return rc2; + } + } + if (out_id) *out_id = id; + return CX_OK; +} + +int cx_append(CxStore *s, const CxHeader *h, const uint64_t *payload, uint32_t n, uint64_t *out_id) { + return cx_append_as(s, 0, h, payload, n, out_id); +} + +int cx_claim_writer(CxStore *s, uint64_t token) { + if (!s || token == 0) return CX_ERR_ARG; + if (s->open_flags & CX_OPEN_READONLY) return CX_ERR_WRITER; + if (s->writer && s->writer != token) return CX_ERR_WRITER; + s->writer = token; + return CX_OK; +} + +void cx_release_writer(CxStore *s, uint64_t token) { + if (s && token && s->writer == token) s->writer = 0; +} + +/* ---- journal open / replay ----------------------------------------------- */ + +static int read_journal(const CxJournalOps *ops, void *ctx, void *h, uint8_t **out, size_t *len) { + size_t n = 0; + int rc = ops->size(ctx, h, &n); + if (rc != CX_OK) return rc; + uint8_t *b = CX_MALLOC(n ? n : 1); + if (!b) return CX_ERR_NOMEM; + if (n) { + rc = ops->read(ctx, h, 0, b, n); + if (rc != CX_OK) { CX_FREE(b); return rc; } + } + *out = b; + *len = n; + return CX_OK; +} + +static int replay(CxStore *s, const uint8_t *b, size_t len, size_t *good_end) { + size_t p = CX_J_HDR_WORDS * 8; + *good_end = p; + uint64_t *payload = NULL; + uint32_t payload_cap = 0; + int rc = CX_OK; + while (p < len) { + if (len - p < CX_R_FIXED * 8) { rc = CX_ERR_TORN; break; } + uint64_t w[CX_R_FIXED]; + for (uint32_t i = 0; i < CX_R_FIXED; i++) w[i] = le_get(b + p + 8 * i); + if (w[0] != CX_R_MAGIC || w[12] > UINT32_MAX) { rc = CX_ERR_FORMAT; break; } + uint32_t n = (uint32_t)w[12]; + size_t rec = ((size_t)CX_R_FIXED + n + CX_R_DIGEST) * 8; + if (len - p < rec) { rc = CX_ERR_TORN; break; } + if (n > payload_cap) { + uint64_t *q = CX_REALLOC(payload, (size_t)n * sizeof(uint64_t)); + if (!q) { rc = CX_ERR_NOMEM; break; } + payload = q; + payload_cap = n; + } + for (uint32_t i = 0; i < n; i++) payload[i] = le_get(b + p + 8 * (CX_R_FIXED + i)); + CxHeader h; + memset(&h, 0, sizeof h); + h.cls = (uint32_t)(w[2] >> 32); + h.kind = (uint32_t)w[2]; + h.subject = w[3]; + h.t = w[4]; + h.generation = w[5]; + h.branch = (uint32_t)(w[6] >> 32); + h.protect = (uint32_t)w[6]; + h.tag = w[7]; + for (uint32_t i = 0; i < CX_LINKS; i++) h.links[i] = w[8 + i]; + uint64_t id = 0; + rc = append_mem(s, &h, payload, n, w[1], &id); + if (rc != CX_OK) break; + if (memcmp(s->obj[id - 1].digest, b + p + 8 * (CX_R_FIXED + n), 32) != 0) { + rc = CX_ERR_DIGEST; + break; + } + p += rec; + *good_end = p; + } + CX_FREE(payload); + return rc; +} + +/* The single integrity seam: see the guarantee in rx_cortex.h. */ +int cx_open_with(CxStore *s, const CxJournalOps *ops, void *ctx, const char *name, + uint64_t n_subjects, uint32_t flags) { + if (!s || !ops || !name || !ops->open || !ops->size || !ops->read || !ops->append || + !ops->truncate || !ops->close) + return CX_ERR_ARG; + int ro = (flags & CX_OPEN_READONLY) != 0; + void *jh = NULL; + int rc = ops->open(ctx, name, ro, &jh); + if (rc != CX_OK) return rc; + uint8_t *b = NULL; + size_t len = 0; + rc = read_journal(ops, ctx, jh, &b, &len); + if (rc != CX_OK) { ops->close(ctx, jh); return rc; } + if (len == 0) { + if (ro || n_subjects == 0) { CX_FREE(b); ops->close(ctx, jh); return CX_ERR_FORMAT; } + uint8_t h[CX_J_HDR_WORDS * 8] = { 0 }; + le_put(h, CX_J_MAGIC); + le_put(h + 8, CX_J_VERSION); + le_put(h + 16, n_subjects); + le_put(h + 24, 0); /* reserved: canonical machine identity (M20 A1) */ + rc = ops->append(ctx, jh, h, sizeof h, 1); + if (rc != CX_OK) { CX_FREE(b); ops->close(ctx, jh); return rc; } + } else { + if (len < CX_J_HDR_WORDS * 8 || le_get(b) != CX_J_MAGIC || le_get(b + 8) != CX_J_VERSION) { + CX_FREE(b); ops->close(ctx, jh); return CX_ERR_FORMAT; + } + uint64_t file_subjects = le_get(b + 16); + if (n_subjects && n_subjects != file_subjects) { + CX_FREE(b); ops->close(ctx, jh); return CX_ERR_FORMAT; + } + n_subjects = file_subjects; + } + rc = cx_init(s, n_subjects); + if (rc != CX_OK) { CX_FREE(b); ops->close(ctx, jh); return rc; } + if (len) { + size_t good = 0; + rc = replay(s, b, len, &good); + if (rc == CX_ERR_TORN && !ro && (flags & CX_OPEN_REPAIR_TAIL)) { + /* Only an incomplete trailing record is dropped. A complete record + * whose digest differs is never repaired. */ + rc = ops->truncate(ctx, jh, good); + } + } + CX_FREE(b); + if (rc != CX_OK) { + ops->close(ctx, jh); + cx_free(s); + return rc; + } + s->jops = ops; + s->jctx = ctx; + s->jh = jh; + s->open_flags = flags; + return CX_OK; +} + +#ifndef CX_NO_POSIX +/* ---- the file backend ---------------------------------------------------- */ + +static int write_all(int fd, const uint8_t *b, size_t n) { + while (n) { + ssize_t w = write(fd, b, n); + if (w < 0) { + if (errno == EINTR) continue; + return -1; + } + b += w; + n -= (size_t)w; + } + return 0; +} + +static int jp_open(void *ctx, const char *name, int ro, void **h) { + (void)ctx; + int fd = open(name, ro ? O_RDONLY | O_CLOEXEC : O_RDWR | O_CREAT | O_CLOEXEC, 0644); + if (fd < 0) return CX_ERR_IO; + if (!ro && flock(fd, LOCK_EX | LOCK_NB) != 0) { + int e = errno; + close(fd); + return e == EWOULDBLOCK ? CX_ERR_WRITER : CX_ERR_IO; + } + *h = (void *)(intptr_t)fd; + return CX_OK; +} + +static int jp_size(void *ctx, void *h, size_t *len) { + (void)ctx; + struct stat st; + if (fstat((int)(intptr_t)h, &st) != 0) return CX_ERR_IO; + *len = (size_t)st.st_size; + return CX_OK; +} + +static int jp_read(void *ctx, void *h, size_t off, uint8_t *out, size_t n) { + (void)ctx; + int fd = (int)(intptr_t)h; + size_t got = 0; + while (got < n) { + ssize_t r = pread(fd, out + got, n - got, (off_t)(off + got)); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) return CX_ERR_IO; + got += (size_t)r; + } + return CX_OK; +} + +static int jp_append(void *ctx, void *h, const uint8_t *b, size_t n, int sync) { + (void)ctx; + int fd = (int)(intptr_t)h; + off_t end = lseek(fd, 0, SEEK_END); + if (end < 0) return CX_ERR_IO; + if (write_all(fd, b, n) != 0 || (sync && fdatasync(fd) != 0)) { + /* Never leave a partial record behind. */ + if (ftruncate(fd, end) != 0) { /* reopen will see a torn tail */ } + return CX_ERR_IO; + } + return CX_OK; +} + +static int jp_truncate(void *ctx, void *h, size_t len) { + (void)ctx; + int fd = (int)(intptr_t)h; + return ftruncate(fd, (off_t)len) == 0 && fdatasync(fd) == 0 ? CX_OK : CX_ERR_IO; +} + +static void jp_close(void *ctx, void *h) { + (void)ctx; + close((int)(intptr_t)h); /* closing drops the flock */ +} + +const CxJournalOps cx_journal_posix = { jp_open, jp_size, jp_read, jp_append, jp_truncate, jp_close }; + +int cx_open(CxStore *s, const char *path, uint64_t n_subjects, uint32_t flags) { + return cx_open_with(s, &cx_journal_posix, NULL, path, n_subjects, flags); +} +#endif /* !CX_NO_POSIX */ + +/* ---- read ---------------------------------------------------------------- */ + +const CxObject *cx_get(const CxStore *s, uint64_t id) { + return id >= 1 && id <= s->n ? &s->obj[id - 1] : NULL; +} + +const uint64_t *cx_payload(const CxStore *s, const CxObject *o) { return s->arena + o->off; } + +int cx_verify(const CxStore *s, uint64_t id) { + const CxObject *o = cx_get(s, id); + if (!o) return CX_ERR_ARG; + uint8_t d[32]; + cx_digest(o, cx_payload(s, o), d); + return memcmp(d, o->digest, 32) == 0 ? CX_OK : CX_ERR_DIGEST; +} + +int cx_verify_chain(const CxStore *s) { + uint8_t chain[32] = { 0 }; + for (uint64_t i = 0; i < s->n; i++) { + uint8_t d[32]; + cx_digest(&s->obj[i], cx_payload(s, &s->obj[i]), d); + if (memcmp(d, s->obj[i].digest, 32) != 0) return CX_ERR_DIGEST; + chain_step(chain, d); + } + return memcmp(chain, s->chain, 32) == 0 ? CX_OK : CX_ERR_DIGEST; +} + +int cx_promote(CxStore *s, uint64_t token, uint64_t candidate, uint64_t evidence, + uint64_t t, uint64_t *out_id) { + const CxObject *c = cx_get(s, candidate); + const CxObject *e = cx_get(s, evidence); + if (!c || !e || c->cls != CX_CLAIM || c->kind != CX_K_CANDIDATE || e->cls != CX_EVIDENCE) + return CX_ERR_ARG; + if (cx_verify(s, candidate) != CX_OK || cx_verify(s, evidence) != CX_OK) return CX_ERR_DIGEST; + CxHeader h; + memset(&h, 0, sizeof h); + h.cls = CX_EVIDENCE; + h.kind = CX_K_PROMOTION; + h.subject = c->subject; + h.t = t; + h.generation = c->generation; + h.branch = c->branch; + h.protect = CX_PROT_VERIFY_EVIDENCE; + h.links[0] = candidate; + h.links[1] = evidence; + uint64_t words[8]; + for (int i = 0; i < 4; i++) { + words[i] = le_get(c->digest + 8 * i); + words[4 + i] = le_get(e->digest + 8 * i); + } + return cx_append_as(s, token, &h, words, 8, out_id); +} + +static int matches(const CxObject *o, const CxFilter *f) { + if (!f) return 1; + if (f->cls && o->cls != f->cls) return 0; + if (f->kind && o->kind != f->kind) return 0; + if (!f->branch_any && o->branch != f->branch) return 0; + return 1; +} + +/* First index in the subject list with t >= t0. */ +static uint32_t lower_bound(const CxStore *s, const CxIdList *l, uint64_t t0) { + uint32_t lo = 0, hi = l->n; + while (lo < hi) { + uint32_t mid = lo + (hi - lo) / 2; + if (s->obj[l->ids[mid] - 1].t < t0) lo = mid + 1; + else hi = mid; + } + return lo; +} + +uint64_t cx_range(CxStore *s, uint64_t subject, uint64_t t0, uint64_t t1, + const CxFilter *f, CxVisit visit, void *user) { + if (subject >= s->n_subjects) return 0; + const CxIdList *l = &s->by_subject[subject]; + uint64_t visited = 0; + for (uint32_t i = lower_bound(s, l, t0); i < l->n; i++) { + const CxObject *o = &s->obj[l->ids[i] - 1]; + if (o->t > t1) break; + s->examined++; + if (!matches(o, f)) continue; + visited++; + if (visit && visit(user, o)) break; + } + return visited; +} + +uint64_t cx_latest(CxStore *s, uint64_t subject, uint64_t t_max, const CxFilter *f) { + if (subject >= s->n_subjects) return 0; + const CxIdList *l = &s->by_subject[subject]; + uint32_t i = lower_bound(s, l, t_max == UINT64_MAX ? UINT64_MAX : t_max + 1); + while (i > 0) { + const CxObject *o = &s->obj[l->ids[--i] - 1]; + s->examined++; + if (matches(o, f)) return o->id; + } + return 0; +} + +uint64_t cx_count_before(const CxStore *s, uint64_t subject, uint64_t t0) { + if (subject >= s->n_subjects) return 0; + return lower_bound(s, &s->by_subject[subject], t0); +} + +uint64_t cx_count_subject(const CxStore *s, uint64_t subject) { + return subject < s->n_subjects ? s->by_subject[subject].n : 0; +} + +/* ---- recall -------------------------------------------------------------- */ + +int cx_recall_id(const CxStore *s, uint64_t id, CxRecord *out) { + const CxObject *o = cx_get(s, id); + if (!o || !out) return CX_ERR_ARG; + out->hdr = *o; + out->payload = cx_payload(s, o); + out->verified = cx_verify(s, id) == CX_OK; + return out->verified ? CX_OK : CX_ERR_DIGEST; +} + +typedef struct { const CxStore *s; CxRecord *out; uint32_t n, max; } RecallCtx; + +static int recall_visit(void *user, const CxObject *o) { + RecallCtx *c = user; + cx_recall_id(c->s, o->id, &c->out[c->n++]); + return c->n >= c->max; +} + +uint32_t cx_recall(CxStore *s, uint64_t subject, uint64_t t0, uint64_t t1, + const CxFilter *f, CxRecord *out, uint32_t max) { + if (!s || !out || max == 0) return 0; + RecallCtx c = { s, out, 0, max }; + cx_range(s, subject, t0, t1, f, recall_visit, &c); + return c.n; +} + +uint32_t cx_provenance(const CxStore *s, uint64_t id, uint64_t *out, uint32_t max) { + if (!s || !out || !cx_get(s, id)) return 0; + uint32_t n = 0, head = 0; + /* Breadth first over `out` itself; links always point to older ids. */ + uint64_t cur = id; + for (;;) { + const CxObject *o = cx_get(s, cur); + for (uint32_t i = 0; o && i < CX_LINKS && n < max; i++) { + uint64_t l = o->links[i]; + if (l == 0 || l >= cur || l == id) continue; + int seen = 0; + for (uint32_t j = 0; j < n && !seen; j++) seen = out[j] == l; + if (!seen) out[n++] = l; + } + if (head >= n || n >= max) break; + cur = out[head++]; + } + return n; +} + +int cx_world_decode(const CxRecord *r, CxWorldRecord *out) { + if (!r || !out || r->hdr.kind < CX_K_WORK_ACCEPTED || r->hdr.kind > CX_K_EXEC_FAILED || + r->hdr.n != CX_WREC_WORDS) + return CX_ERR_ARG; + const uint64_t *p = r->payload; + memset(out, 0, sizeof(*out)); + out->cx_id = r->hdr.id; + out->kind = r->hdr.kind; + out->session = p[CX_WREC_SESSION]; + out->crumb = p[CX_WREC_CRUMB]; + out->crumb_kind = (uint32_t)p[CX_WREC_CRUMB_KIND]; + out->reaction = (uint32_t)p[CX_WREC_REACTION]; + out->faculty = (uint32_t)p[CX_WREC_FACULTY]; + out->episode = p[CX_WREC_EPISODE]; + out->reason = (int32_t)(int64_t)p[CX_WREC_REASON]; + out->obj = p[CX_WREC_OBJ]; + out->obj_gen = p[CX_WREC_OBJ_GEN]; + out->obj_version = p[CX_WREC_OBJ_VERSION]; + for (int i = 0; i < 8; i++) out->field[i] = p[CX_WREC_FIELD0 + i]; + for (int i = 0; i < 4; i++) le_put(out->crumb_digest + 8 * i, p[CX_WREC_DIGEST0 + i]); + out->n_inputs = (uint32_t)p[CX_WREC_N_INPUTS]; + out->n_outputs = (uint32_t)p[CX_WREC_N_OUTPUTS]; + out->cause = r->hdr.links[0]; + return CX_OK; +} + +void cx_tamper(CxStore *s, uint64_t id, uint32_t word, uint64_t value) { + const CxObject *o = cx_get(s, id); + if (o && word < o->n) s->arena[o->off + word] = value; +} diff --git a/native/kernel/third_party/omega/rx_cortex.h b/native/kernel/third_party/omega/rx_cortex.h new file mode 100644 index 00000000..6c358b6c --- /dev/null +++ b/native/kernel/third_party/omega/rx_cortex.h @@ -0,0 +1,376 @@ +/* + * rx_cortex.h -- Cortex, AIEN's durable typed memory. CANONICAL (M20). + * + * AUTHORITY (M20, 2026-09-30). This file is the one canonical Cortex + * contract. Every authoritative Cortex write goes through cx_append or + * cx_append_as on a CxStore defined here, and a store has at most one writer: + * cx_claim_writer inside a process, an exclusive lock on the journal across + * processes. Chosen because it is the C implementation in the runtime tree + * that owns World (rx_world.c), the one the runtime already calls + * (rx_projection.c), and the only one the no-Rust rule allows to grow. + * + * Non-authoritative implementations (not edited here, never a second writer): + * + * aien-sovereign-core crates/cortex-rs Linux LLM-stack memory service + * (HTTP :18080; callers aien-cli + * src/cortex.rs, spark-mail-rs + * src/cortex_sync.rs). + * aienos crates/aienos-cortex Rust epistemic store (callers + * aienos-aegis, aienos-kernel + * src/continuity.rs). + * + * Their records are not AIEN memory until they enter this store, and they + * enter only as CX_K_IMPORTED claims whose tag names the source (CX_SRC_*): + * never as facts and never by writing a journal directly. Removal path, per + * aien-architecture docs/plans/RUST_TO_C_MIGRATION.md §6 ("port or retire"): + * both are retired, not ported. (1) No new caller may be added to either. + * (2) Whatever is worth keeping is imported as CX_K_IMPORTED records through + * cx_append_as. (3) The crates are deleted. Until step 3 nothing may treat + * them as a source of truth. + * + * Cortex holds what the machine has seen, done, claimed and proven. It is + * append-only: an object, once recorded, never changes, and its digest says + * so. Nothing in Cortex is text. Every object is a fixed header plus a + * payload of 64-bit words. + * + * Two axes, never merged: + * + * content class what the object IS: one of the nine memory classes of + * doctrine AIEN.md §8.2 (entity, claim, observation, ...). + * treatment how one cognitive operation may use it (pinned, live, + * compressible, ...). Treatment is not stored here. It is + * decided per operation by the state projection + * (rx_projection.h). + * + * Protection bits are the one treatment fact Cortex does own: authority, + * commit receipts, verification evidence, generation identity and effect + * receipts may never be summarized, whatever an operation asks for. + * + * Cortex does not hand out its history. It answers typed queries: one + * subject, one time range, one class and kind. The indexes are per subject + * and time ordered, so a query costs the objects in its range, not the size + * of the store. `examined` counts every object a query touched. + * + * Tiers: one in-memory tier, optionally backed by an append-only journal + * file (cx_open) that is replayed and verified on reopen. Doctrine's L1/L2/L3 + * tiers (accelerator memory, host memory, NVMe) are not implemented here. + * Cortex is memory and evidence; runtime state-space material is J-Space + * (rx_jspace.h), not this. + */ +#ifndef RX_CORTEX_H +#define RX_CORTEX_H + +#include +#include + +/* Content axis: the nine memory classes of doctrine AIEN.md §8.2. */ +typedef enum { + CX_ENTITY = 1, CX_CLAIM, CX_OBSERVATION, CX_EXECUTION, CX_FAILURE, + CX_EVIDENCE, CX_PLAN, CX_REALIZATION, CX_RELATIONSHIP, + CX_CLASS_END +} CxClass; + +/* State that may never be summarized, derived away or dropped for budget. */ +enum { + CX_PROT_AUTHORITY = 1u << 0, + CX_PROT_COMMIT_RECEIPT = 1u << 1, + CX_PROT_VERIFY_EVIDENCE = 1u << 2, + CX_PROT_GENERATION_ID = 1u << 3, + CX_PROT_EFFECT_RECEIPT = 1u << 4, + CX_PROT_ALL = 0x1fu +}; + +/* ---- canonical record kinds --------------------------------------------- + * `kind` numbering below CX_K_BASE belongs to the writer (rx_projection's + * workloads use it). Kinds from CX_K_BASE up are the canonical contract and + * mean the same thing to every reader. Each canonical kind lives in exactly + * one class, given in the comment. + */ +#define CX_K_BASE 0x10000u +enum { + /* World execution (written only by rx_cortex_record.c, payload CX_WREC_*) */ + CX_K_WORK_ACCEPTED = CX_K_BASE + 1, /* OBSERVATION: outside input admitted into a World */ + CX_K_ENTITY_CREATED, /* ENTITY: a World object came to life */ + CX_K_ENTITY_RETIRED, /* ENTITY: a World object was retired */ + CX_K_EXEC_COMMIT, /* EXECUTION: work ran and committed a result */ + CX_K_EXEC_NOOP, /* EXECUTION: work ran and proposed no change */ + CX_K_EXEC_FAILED, /* FAILURE: failed, rejected, blocked, invalidated, + contained; tag = World crumb kind */ + /* Epistemic records (any claimed writer) */ + CX_K_CLAIM = CX_K_BASE + 0x10, /* CLAIM: asserted fact */ + CX_K_CANDIDATE, /* CLAIM: summary or memory candidate, not yet fact */ + CX_K_EVIDENCE_REF, /* EVIDENCE: reference to a receipt / digest */ + CX_K_PROMOTION, /* EVIDENCE: candidate promoted; links[0] = candidate, + links[1] = evidence (cx_promote) */ + CX_K_ADMISSION, /* EVIDENCE: admission decision; links name its inputs */ + CX_K_IMPORTED = CX_K_BASE + 0x20 /* CLAIM: record from a non-authoritative store; + tag = CX_SRC_* */ +}; + +/* Sources of CX_K_IMPORTED records (see AUTHORITY above). */ +enum { CX_SRC_CORTEX_RS = 1, CX_SRC_AIENOS_CORTEX = 2 }; + +#define CX_LINKS 4u + +typedef struct { + uint64_t id; /* 1-based and dense: object id == index + 1 */ + uint32_t cls; /* CxClass */ + uint32_t kind; /* fact type within the class; see CX_K_BASE */ + uint64_t subject; /* the entity the object is about */ + uint64_t t; /* logical time of the fact */ + uint64_t generation; /* generation the fact was recorded under */ + uint32_t branch; /* 0 = the main line; else a hypothetical branch */ + uint32_t protect; /* CX_PROT_* */ + uint64_t tag; /* one small header value (cause code, condition key, ...) */ + uint64_t links[CX_LINKS];/* ids of related objects, 0 = none (provenance) */ + uint32_t n; /* payload words */ + uint64_t off; /* payload offset in the arena */ + uint8_t digest[32]; /* SHA-256 of the canonical encoding */ +} CxObject; + +typedef struct { + uint64_t *ids; + uint32_t n, cap; +} CxIdList; + +typedef struct CxStore { + CxObject *obj; + uint64_t n, cap; + uint64_t *arena; + uint64_t arena_n, arena_cap; + CxIdList *by_subject; /* per subject, in append (= time) order */ + uint64_t n_subjects; + uint8_t chain[32]; /* running hash over every digest in append order */ + uint64_t examined; /* objects touched by queries, cumulative */ + /* Journal backing (cx_open_with). jops NULL: memory only. */ + const struct CxJournalOps *jops; + void *jctx; /* backend context, handed back to every op */ + void *jh; /* the open journal, owned by the backend */ + uint32_t open_flags; + /* The one writer, 0 = unclaimed. While claimed, only cx_append_as with + * the same token appends. */ + uint64_t writer; +} CxStore; + +/* What a writer supplies; id, offset and digest are Cortex's. */ +typedef struct { + uint32_t cls, kind; + uint64_t subject, t, generation; + uint32_t branch, protect; + uint64_t tag; + uint64_t links[CX_LINKS]; +} CxHeader; + +enum { + CX_OK = 0, CX_ERR_ARG = -1, CX_ERR_NOMEM = -2, CX_ERR_ORDER = -3, CX_ERR_DIGEST = -4, + CX_ERR_WRITER = -5, /* another writer holds this store or its journal */ + CX_ERR_IO = -6, /* journal read/write failed; memory state unchanged */ + CX_ERR_FORMAT = -7, /* not a Cortex journal, or another subject count */ + CX_ERR_TORN = -8 /* journal ends inside a record (see CX_OPEN_REPAIR_TAIL) */ +}; + +int cx_init(CxStore *s, uint64_t n_subjects); +void cx_free(CxStore *s); /* also closes and unlocks a journal */ + +/* Append one object. Per subject, time may not go backwards (CX_ERR_ORDER). + * CX_ERR_WRITER while a writer has claimed the store. */ +int cx_append(CxStore *s, const CxHeader *h, const uint64_t *payload, uint32_t n, uint64_t *out_id); + +/* ---- single writer ------------------------------------------------------ */ + +/* Claim the store for `token` (nonzero). CX_ERR_WRITER if another token + * holds it; claiming again with the same token is CX_OK. */ +int cx_claim_writer(CxStore *s, uint64_t token); +void cx_release_writer(CxStore *s, uint64_t token); +/* cx_append for the claimed writer (token 0 = unclaimed store). */ +int cx_append_as(CxStore *s, uint64_t token, const CxHeader *h, const uint64_t *payload, + uint32_t n, uint64_t *out_id); + +/* ---- journal ------------------------------------------------------------ + * File: 32-byte header (magic, version, n_subjects, reserved) then one + * record per object: 13 header words, n payload words, 4 digest words, all + * little-endian. Reopen replays every record through the append path and + * refuses the journal if any recomputed digest differs from the stored one. + * Subject numbers are whatever the writer used; for World records they are + * local object slots (rx_cortex_record.h), runtime indices, not machine or + * object identity. The reserved header word is kept for that identity. + */ +enum { + CX_OPEN_READONLY = 1u << 0, /* no lock, no writes; for inspection */ + CX_OPEN_SYNC = 1u << 1, /* fdatasync after every append */ + CX_OPEN_REPAIR_TAIL = 1u << 2 /* truncate one incomplete trailing record */ +}; + +/* ---- journal backend ------------------------------------------------------ + * The store reaches its journal only through this table. cx_journal_posix is + * the file backend (one file, flock for the writer lock); it is the default + * of cx_open and is compiled out under CX_NO_POSIX, where a freestanding host + * (AIENOS: sealed Store objects, P06 adapter) supplies its own table through + * cx_open_with. Memory comes from CX_MALLOC / CX_REALLOC / CX_FREE, which a + * config header named by CX_CONFIG_H may define; the default is libc. + * The record format, the digests, the chain and every check in cx_open are + * the same under every backend: a backend stores bytes, it never interprets + * them. */ +typedef struct CxJournalOps { + /* Open the journal `name`. ro: no lock, no writes, must exist. Writable: + * create when absent and take the one-writer lock, CX_ERR_WRITER when + * another writer holds it. *h receives the backend's handle. */ + int (*open)(void *ctx, const char *name, int ro, void **h); + /* Current length in bytes. */ + int (*size)(void *ctx, void *h, size_t *len); + /* Exactly n bytes at offset off, or an error. */ + int (*read)(void *ctx, void *h, size_t off, uint8_t *out, size_t n); + /* Append n bytes as ONE unit: on return either all of them are in the + * journal (durable when sync != 0) or none of them is, and the length is + * as before. A partial write is the backend's to undo. */ + int (*append)(void *ctx, void *h, const uint8_t *b, size_t n, int sync); + /* Cut the journal back to len bytes, durably (CX_OPEN_REPAIR_TAIL). A + * backend whose appends are atomic never holds a torn tail and may + * answer CX_ERR_IO. */ + int (*truncate)(void *ctx, void *h, size_t len); + /* Release the handle; a writer's lock drops here. */ + void (*close)(void *ctx, void *h); +} CxJournalOps; + +#ifndef CX_NO_POSIX +extern const CxJournalOps cx_journal_posix; +#endif + +/* cx_open through an explicit backend; the contract below is unchanged. */ +int cx_open_with(CxStore *s, const CxJournalOps *ops, void *ctx, const char *name, + uint64_t n_subjects, uint32_t flags); + +/* Open (creating if absent and writable) a journal-backed store. A writable + * open takes an exclusive lock; a second writable open of the same file, + * from this or any process, gets CX_ERR_WRITER. n_subjects must match a + * nonempty journal's. On error the store is left freed. + * + * cx_open is the single seam where integrity is established. At open, for + * every record: the magic word, the id equal to its position (1, 2, 3, ...), + * and the per-record digest recomputed from header plus payload and compared + * to the stored one (rx_cortex.c replay). The chain is rebuilt from those + * digests, not read from disk. Also checked: the subject count against the + * file header, an incomplete trailing record (CX_ERR_TORN, or truncated when + * CX_OPEN_REPAIR_TAIL is set), and the writer lock. + * After a CX_OK open, callers may assume the objects in memory equal the + * journal, and that cx_verify on an object read from this store cannot fail + * except through memory corruption or a later in-memory edit. + * NOT checked by cx_open: a journal cut exactly at a record boundary looks like a + * shorter valid journal (the file holds no record count or head marker). That + * cut is detected by rx_compose, which records the Cortex record count and head + * record digest in the J-Space checkpoint anchor and cross-checks it at open. + * KNOWN LIMIT: if both the Cortex journal and the J-Space checkpoint roll back + * together, nothing local detects it (an external anchor problem). */ +#ifndef CX_NO_POSIX +int cx_open(CxStore *s, const char *path, uint64_t n_subjects, uint32_t flags); +#endif +void cx_close(CxStore *s); /* = cx_free */ + +const CxObject *cx_get(const CxStore *s, uint64_t id); +const uint64_t *cx_payload(const CxStore *s, const CxObject *o); + +/* Recompute an object's digest and compare: CX_OK or CX_ERR_DIGEST. */ +int cx_verify(const CxStore *s, uint64_t id); + +/* AUDIT entry point, not needed after cx_open (which already verified every + * record). Re-hashes every in-memory object, compares each to its stored + * digest, replays the running hash and compares it to `chain`: CX_OK if all + * match. For audits and tests. */ +int cx_verify_chain(const CxStore *s); + +/* Canonical digest of a header plus payload. */ +void cx_digest(const CxObject *o, const uint64_t *payload, uint8_t out[32]); + +/* Record that a candidate (CX_CLAIM / CX_K_CANDIDATE) was promoted on the + * strength of an evidence object (class CX_EVIDENCE). Appends a protected + * CX_K_PROMOTION about the candidate's subject with links {candidate, + * evidence}. CX_ERR_ARG if either id is missing or of the wrong kind. */ +int cx_promote(CxStore *s, uint64_t token, uint64_t candidate, uint64_t evidence, + uint64_t t, uint64_t *out_id); + +/* ---- typed queries (every touched object is counted in s->examined) ---- */ + +/* Matches cls/kind (0 = any), and branch unless branch_any. */ +typedef struct { + uint32_t cls, kind; + uint32_t branch; + int branch_any; +} CxFilter; + +typedef int (*CxVisit)(void *user, const CxObject *o); + +/* Objects of `subject` with t in [t0, t1], oldest first. The visitor returns + * nonzero to stop. Returns the number visited. */ +uint64_t cx_range(CxStore *s, uint64_t subject, uint64_t t0, uint64_t t1, + const CxFilter *f, CxVisit visit, void *user); + +/* The newest matching object of `subject` with t <= t_max, or 0. */ +uint64_t cx_latest(CxStore *s, uint64_t subject, uint64_t t_max, const CxFilter *f); + +/* Count of `subject`'s objects with t < t0 (index arithmetic, no scan). */ +uint64_t cx_count_before(const CxStore *s, uint64_t subject, uint64_t t0); +uint64_t cx_count_subject(const CxStore *s, uint64_t subject); + +/* ---- recall: typed, provenanced records ---------------------------------- */ + +typedef struct { + CxObject hdr; /* copy of the header, links = provenance */ + const uint64_t *payload; /* valid while the store is unchanged */ + int verified; /* digest recomputed and matched */ +} CxRecord; + +/* Like cx_range, but fills up to `max` records (oldest first), each digest + * checked. Returns the number filled. */ +uint32_t cx_recall(CxStore *s, uint64_t subject, uint64_t t0, uint64_t t1, + const CxFilter *f, CxRecord *out, uint32_t max); + +/* One record by id (CX_OK, CX_ERR_ARG, or CX_ERR_DIGEST with *out still set). */ +int cx_recall_id(const CxStore *s, uint64_t id, CxRecord *out); + +/* Every object `id` derives from through links, nearest first, no repeats, + * at most `max`. Returns the number written. */ +uint32_t cx_provenance(const CxStore *s, uint64_t id, uint64_t *out, uint32_t max); + +/* ---- World execution record payload (CX_K_WORK_ACCEPTED .. EXEC_FAILED) -- + * Written by rx_cortex_record.c from one World causal crumb. Defined here so + * a reader needs no World header. + */ +enum { + CX_WREC_SESSION = 0, /* World session the writer was attached under */ + CX_WREC_CRUMB, /* crumb id in that session's causal log */ + CX_WREC_CRUMB_KIND, /* RxCrumbKind */ + CX_WREC_REACTION, /* reaction id, UINT32_MAX for outside / create */ + CX_WREC_FACULTY, + CX_WREC_EPISODE, /* crumb id of the outside input the episode started from */ + CX_WREC_REASON, /* crumb reason (sign-extended) */ + CX_WREC_OBJ, /* object slot, UINT64_MAX = none */ + CX_WREC_OBJ_GEN, + CX_WREC_OBJ_VERSION, + CX_WREC_FIELD0, /* 8 field values of the object after the crumb */ + CX_WREC_DIGEST0 = CX_WREC_FIELD0 + 8, /* crumb digest, 4 little-endian words */ + CX_WREC_N_INPUTS = CX_WREC_DIGEST0 + 4, + CX_WREC_N_OUTPUTS, + CX_WREC_T_START_NS, + CX_WREC_T_END_NS, + CX_WREC_WORDS +}; + +typedef struct { + uint64_t cx_id; + uint32_t kind; /* CX_K_* */ + uint64_t session, crumb, episode, obj, obj_gen, obj_version; + uint32_t crumb_kind, reaction, faculty; + int32_t reason; + uint64_t field[8]; + uint8_t crumb_digest[32]; + uint32_t n_inputs, n_outputs; + uint64_t cause; /* Cortex id of the record of the crumb that caused it, 0 = none */ +} CxWorldRecord; + +/* Decode a World execution record: CX_OK, or CX_ERR_ARG if `r` is not one. */ +int cx_world_decode(const CxRecord *r, CxWorldRecord *out); + +/* Test hook: overwrite one payload word without updating the digest. */ +void cx_tamper(CxStore *s, uint64_t id, uint32_t word, uint64_t value); + +#endif /* RX_CORTEX_H */ diff --git a/omega.lock b/omega.lock new file mode 100644 index 00000000..bc823c2f --- /dev/null +++ b/omega.lock @@ -0,0 +1,3 @@ +362c9ab50c8ecc3012dd2e3ac20329865ba80982 +sha256 999ca9c0b35831779b215d816f49ddc8e85761efde057382322c00ba949d1ff9 native/kernel/third_party/omega/rx_cortex.c src/runtime/rx_cortex.c +sha256 4ab6d9883609b5b529a040d9977e1de11e5dbb6d022ce9256d7adf5a6bec6ba9 native/kernel/third_party/omega/rx_cortex.h src/runtime/rx_cortex.h diff --git a/scripts/.crumb b/scripts/.crumb index a8796b00..4a1b8b8a 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T06:35:59Z", + "compiled_at": "2026-10-12T07:42:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:87981170f9983b962d7b2c8ea7f2f4811b354e13514dcb6365f0cc7a49cb1e9f", + "digest": "sha256:eecc6309e4e429e5236cbf29a3593351f5bd5b2cb2daf6cd36c73fc96c9b0a61", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 82, - "generated_at_commit": "101c710b24fad41fc9a8797222e366ed71e6b6f2", - "source_tree": "sha256:d5a697011627c2cead5f4b2c8be6a00698e85d73d7bf8698e575b41ad126783d" + "files": 83, + "generated_at_commit": "453f41e7fca07a97ee52db3a125d106dfaf17ff5", + "source_tree": "sha256:d703caef3f47b25c41635b5b5341056c640e58d745727f58177550250f352d68" }, "owner_lane": "", "provenance": { diff --git a/scripts/omega_lock_check.sh b/scripts/omega_lock_check.sh new file mode 100755 index 00000000..102f02c6 --- /dev/null +++ b/scripts/omega_lock_check.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# omega_lock_check.sh -- the vendored Omega sources (native/kernel/third_party/omega) +# are byte for byte the files of the omega commit named in omega.lock. +# +# omega.lock: line 1 is the full omega commit sha; every further line is +# sha256 +# Always: each vendored file's sha256 equals the recorded one (offline). +# When possible: the recorded sha256 equals the blob at that commit in omega +# (OMEGA_LOCK_REPO=, else a shallow fetch of the commit +# from GitHub; skipped with a NOTE when neither works, never a PASS for it). +# Exit 0 only when every check that ran passed. No Python. +set -u +cd "$(dirname "$0")/.." || exit 2 +lock=omega.lock +[ -r "$lock" ] || { echo "OMEGA_LOCK: FAIL $lock missing"; exit 1; } +sha=$(sed -n 1p "$lock") +case "$sha" in + [0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*) ;; + *) echo "OMEGA_LOCK: FAIL line 1 is not a commit sha"; exit 1 ;; +esac +[ ${#sha} -eq 40 ] || { echo "OMEGA_LOCK: FAIL line 1 is not a full sha"; exit 1; } +fail=0 +n=0 +while read -r tag hex path opath; do + [ "$tag" = sha256 ] || continue + n=$((n + 1)) + if [ ! -r "$path" ]; then echo "FAIL $path missing"; fail=1; continue; fi + have=$(sha256sum "$path" | cut -d' ' -f1) + if [ "$have" = "$hex" ]; then echo "PASS $path sha256 matches omega.lock"; else echo "FAIL $path sha256 $have, omega.lock says $hex"; fail=1; fi +done < "$lock" +[ "$n" -gt 0 ] || { echo "OMEGA_LOCK: FAIL no sha256 lines"; exit 1; } + +# upstream check +repo="${OMEGA_LOCK_REPO:-}" +tmp="" +if [ -z "$repo" ] && command -v git >/dev/null 2>&1; then + tmp=$(mktemp -d) + if git -C "$tmp" init -q 2>/dev/null && git -C "$tmp" fetch -q --depth=1 https://github.com/aien-dev/omega.git "$sha" 2>/dev/null; then + repo="$tmp" + up=FETCH_HEAD + fi +fi +[ -n "${up:-}" ] || up="$sha" +if [ -n "$repo" ] && git -C "$repo" cat-file -e "$up^{commit}" 2>/dev/null; then + while read -r tag hex path opath; do + [ "$tag" = sha256 ] || continue + blob=$(git -C "$repo" show "$up:$opath" 2>/dev/null | sha256sum | cut -d' ' -f1) + if [ "$blob" = "$hex" ]; then echo "PASS omega $opath at ${sha:0:12} matches omega.lock"; else echo "FAIL omega $opath at ${sha:0:12} is $blob, omega.lock says $hex"; fail=1; fi + done < "$lock" +else + echo "NOTE upstream check not run (no OMEGA_LOCK_REPO and no fetch of $sha); offline sha256 check only" +fi +[ -n "$tmp" ] && rm -rf "$tmp" +if [ "$fail" = 0 ]; then echo "OMEGA_LOCK: PASS commit=$sha files=$n"; exit 0; fi +echo "OMEGA_LOCK: FAIL commit=$sha" +exit 1