interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tests / runtime / rx_r13_living.c

2413 lines · 123285 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 /* Timing sensitivity (omega #313 item 1, #527): `target` is 55 percent of the incumbent cost AIEN
18 * confirmed on the old core class, and `final_expected` is the cost AIEN later confirmed on the new
19 * one. Both are measured on this machine, as the CPU time the serving thread spent in the matvec
20 * (rx_omega.c cost_ns). Wall-clock time counted a preemption or a busy neighbour as cost: on a
21 * loaded host a slow interval failed AIEN's prediction before the goal, or tipped Omega's first
22 * selection, and the episode could not start. The checks are unchanged.
23 * The production windows (AIEN, Omega, GPU experiment, promotion barrier) are held open until
24 * production commits (seat_watch, barrier_watch): under whole-machine load the host episode is
25 * shorter than a starved producer's wait for a CPU, and counting the commits that happened to
26 * land in it measured the scheduler (omega #598 c2dd2a0d: AIEN=0 Omega=0 GPU=0 at load 70). */
27/* R13: one world; after the goal, only production requests and observation. */
28#include "runtime/rx_living.h"
29#include "runtime/rx_resident_gpu.h"
30#include "runtime/aien_machine_id.h"
31#include "runtime/rx_operator.h"
32/* Lane 32: two programs from this file (docs/r16-production-entry-point.md).
33 * PRODUCTION (default, no flag): no test pieces. ARGUS is linked and observes
34 * (RX_ARGUS=2, authority observer, consumer ingest), pinned by argus.lock; the
35 * composition and Fabric phases are reported NOT_RUN with their reason.
36 * TEST BUILD (-DAIEN_TEST_BUILD=1, test-r13-testbuild-*): adds the composition
37 * phase (rx_compose test hooks, host only) and the Fabric F5-0 phase (loopback
38 * transport, HMAC stand-in, fixed test keys); its gate line is
39 * R13_LIVING_SYSTEM_TEST_BUILD and it never claims R13_LIVING_SYSTEM. */
40#ifdef AIEN_TEST_BUILD
41#include "rx_compose_fixture.h"
42#include "../fabric/fab_living_phase.h"
43#else
44#include "runtime/rx_argus.h"
45#if RX_ARGUS != 2 || !defined(RX_ARGUS_AUTHORITY_OBSERVER)
46#error "the production R13 program links ARGUS: build with -DRX_ARGUS=2 -DRX_ARGUS_AUTHORITY_OBSERVER (Makefile RX_PROD_ARGUS_FLAGS)"
47#endif
48#endif
49#include "omega_evidence.h"
50#include "sha256.h"
51#include "omega_path_check.h"
52
53#include <dirent.h>
54#include <errno.h>
55#include <ftw.h>
56#include <stdarg.h>
57#include <stdatomic.h>
58#include <sched.h>
59#include <signal.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <sys/random.h>
64#include <sys/stat.h>
65#include <sys/un.h>
66#include <sys/utsname.h>
67#include <time.h>
68#include <unistd.h>
69
70enum { EXTERNAL = 100, ISSUER = 3 };
71enum { POSITIVE, NO_AIEN, NO_PROMOTION, REVOKED_EXPERIMENT,
72 STALE_GPU, FAILED_VERIFICATION };
73#define M 64u
74#define N 256u
75#define CLASS_A725 0xd87u
76#define CLASS_X925 0xd85u
77#define RES_INTENT 0x6130010ull
78#define U(x) ((unsigned long long)(x))
79
80typedef struct {
81 AienosCapAdmin *admin;
82 AienosCapView *view;
83 RxWorld w;
84 RxOmegaFaculty omega;
85 RxAienFaculty aien;
86 RxAegisFaculty aegis;
87 RxLiving living;
88 RxLivingPromoter promoter;
89 RxLivingKeyrings keys; /* R16 C6: runtime-issued caller credentials */
90 RxCallerKeyring compose_keys; /* the composition's subjects (rx_compose_enroll_callers) */
91 RxGenStore *gen;
92 RxGpuSeat *seat;
93 pthread_t acceptor;
94 atomic_int acceptor_stop;
95 int acceptor_live;
96 atomic_int acceptor_error;
97 RxObjRef intent;
98 RxCapRef ext_request, ext_goal, ext_placement, ext_intent;
99 RxCapRef seat_input, seat_output;
100 uint32_t r_ask;
101 uint64_t request_seq, served, wrong;
102 uint64_t unpromoted_use; /* results that used a realization not yet in force */
103 pthread_t producer;
104 atomic_int producer_stop, producer_error;
105 int producer_live;
106 uint64_t minted;
107 char generation_dir[128];
108 /* The living system's durable home: its provisioned machine identity
109 * (home/machine.id, created once, reused on every start) and the
110 * composition it runs (home/compose). */
111 char home_dir[128];
112 AienMachineId machine;
113 /* R16 G6 operator control (docs/r16-operator-control.md): the operator's
114 * credential is handed to its file and wiped; the program keeps no copy. */
115 int mode;
116 RxCallerCred op_cred;
117 RxCapRef op_cap;
118 RxOperator *op;
119 int op_gate_held, op_restored, ready;
120 atomic_ullong op_halt_since, op_halt_total; /* ns; stopped time is not run time */
121 atomic_int op_shutdown, op_teardown;
122 /* POSITIVE: what production did while the promotion barrier was held
123 * (barrier_watch, on the store executor). */
124 uint64_t barrier_calls, barrier_commits, barrier_wait_ns;
125 /* Seat results the transport accepted into the world; POSITIVE: what
126 * production did while the transport held the experiment after the first
127 * one (seat_watch, on the acceptor thread). */
128 uint64_t accepted, seat_calls, seat_commits, seat_wait_ns;
129} Rig;
130static int g_stage;
131typedef struct {
132 uint64_t before, after, recovered;
133 RxObjRef goal, plan, search, gpu_input, gpu_output, evidence, belief;
134 RxObjRef selection, candidate, promotion, inforce;
135 uint64_t target_ns, incumbent_ns, selected_ps, reference_ps;
136 uint64_t final_expected_ns, final_status, final_prediction_epoch;
137 uint64_t aien_acts, omega_acts, seat_acts, aegis_decide_acts, root_install_acts;
138 uint64_t promote_acts, prepare_acts;
139 uint64_t gpu_claims, gpu_completions, gpu_worker;
140 uint64_t production_aien, production_omega, production_gpu;
141 uint64_t production_before_promotion, production_after_promotion, production_during_promotion;
142 uint64_t unpromoted_use, externals_after_goal, crumbs, links_verified, aien_overlap;
143 uint64_t caps_swept, promote_holders;
144 uint64_t promotion_barrier_ns, promotion_latency_ns;
145 int causal_verified, silicon_observed;
146 char selected_identity[65], promoted_identity[65], rebuilt_identity[65];
147 char realization_sha256[65];
148} Receipt;
149static Receipt g_receipt;
150static int g_controls[5];
151
152static uint64_t now_ns(void) {
153 struct timespec ts;
154 clock_gettime(CLOCK_MONOTONIC, &ts);
155 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
156}
157
158/* Busy wait without a system call: a 20 us sleep costs about 80 us on Linux. */
159static void spin_us(unsigned us) {
160 uint64_t until = now_ns() + (uint64_t)us * 1000u;
161 while (now_ns() < until) {
162#if defined(__aarch64__)
163 __asm__ volatile("yield");
164#endif
165 }
166}
167
168static void pause_us(int us) {
169 struct timespec ts = {0, (long)us * 1000L};
170 nanosleep(&ts, NULL);
171}
172
173static RxCapRef mint(Rig *r, uint32_t subject, uint64_t resource, uint32_t rights) {
174 AienosCapRef office, ref = {UINT32_MAX, 0};
175 aienos_cap_office(r->admin, &office);
176 AienosCapMint m = {ISSUER, subject, resource, rights, 0,
177 {UINT32_MAX, 0}, office};
178 if (aienos_cap_mint(r->admin, &m, &ref) == 0) r->minted++;
179 return (RxCapRef){ref.cap_id, ref.generation};
180}
181
182static uint64_t field(Rig *r, RxObjRef ref, uint32_t i) {
183 RxObject o;
184 return rx_world_read(&r->w, ref, &o) == RX_OK ? o.field[i] : UINT64_MAX;
185}
186
187static const RxSnapshotDep *snapshot(RxCtx *c, RxObjRef ref) {
188 for (uint32_t i = 0; i < c->n_in; i++)
189 if (c->in[i].obj.id == ref.id) return &c->in[i];
190 return NULL;
191}
192
193/* Client intent becomes an R8 request through a reaction of that client. */
194static int ask(RxCtx *c) {
195 Rig *r = c->user;
196 const RxSnapshotDep *in = snapshot(c, r->intent);
197 const RxSnapshotDep *out = snapshot(c, r->aegis.o[0].request);
198 if (!in || !out) return -1;
199 if (!in->field[0] || in->field[0] == out->field[0]) return 0;
200 for (uint32_t i = 0; i < 6; i++)
201 c->out[c->n_out++] = (RxMutation){r->aegis.o[0].request, i, in->field[i]};
202 return 0;
203}
204
205static int core_sets(cpu_set_t *a, cpu_set_t *x) {
206 CPU_ZERO(a); CPU_ZERO(x);
207 DIR *d = opendir("/sys/devices/system/cpu");
208 if (!d) return -1;
209 struct dirent *e;
210 int na = 0, nx = 0;
211 while ((e = readdir(d))) {
212 int cpu = -1;
213 if (sscanf(e->d_name, "cpu%d", &cpu) != 1 || cpu < 0 || cpu >= CPU_SETSIZE)
214 continue;
215 char path[256];
216 snprintf(path, sizeof path,
217 "/sys/devices/system/cpu/cpu%d/regs/identification/midr_el1", cpu);
218 FILE *f = fopen(path, "r");
219 unsigned long long midr = 0;
220 if (!f) continue;
221 int ok = fscanf(f, "%llx", &midr);
222 fclose(f);
223 if (ok != 1) continue;
224 uint32_t part = (uint32_t)(midr >> 4) & 0xfffu;
225 if (part == CLASS_A725) { CPU_SET(cpu, a); na++; }
226 if (part == CLASS_X925) { CPU_SET(cpu, x); nx++; }
227 }
228 closedir(d);
229 return na && nx ? 0 : -1;
230}
231
232static int move_threads(const cpu_set_t *set) {
233 DIR *d = opendir("/proc/self/task");
234 if (!d) return -1;
235 struct dirent *e;
236 int moved = 0;
237 while ((e = readdir(d))) {
238 int tid = atoi(e->d_name);
239 if (tid > 0 && sched_setaffinity(tid, sizeof(*set), set) == 0) moved++;
240 }
241 closedir(d);
242 return moved;
243}
244
245static int new_object(Rig *r, uint32_t type, uint64_t resource, RxObjRef *out) {
246 uint64_t z[RX_MAX_FIELDS] = {0};
247 return rx_world_create(&r->w, type, RX_PERSIST_RESIDENT, resource, z, out);
248}
249
250static int rm_one(const char *p, const struct stat *sb, int flag, struct FTW *ftw) {
251 (void)sb; (void)flag; (void)ftw;
252 return remove(p);
253}
254
255/* A scratch directory under $TMPDIR (default /tmp); a TMPDIR that src/omega_path_check.h refuses fails the
256 * caller rather than naming a directory from unchecked bytes. */
257static int scratch_dir(char *out, size_t n, const char *stem) {
258 const char *e = getenv("TMPDIR");
259 char t[160];
260 if (!e || !e[0]) e = "/tmp";
261 if (omega_path_copy(t, sizeof t, e) != 0) return -1;
262 if ((size_t)snprintf(out, n, "%s/%s-XXXXXX", t, stem) >= n) return -1;
263 return mkdtemp(out) ? 0 : -1;
264}
265
266/* Provisioning (aienos ADR 0010): the machine identity is created once in
267 * the living home from fresh provisioned root bytes, then only loaded. */
268static int living_identity(Rig *r) {
269 char p[192];
270 snprintf(p, sizeof p, "%s/machine.id", r->home_dir);
271 if (access(p, F_OK) == 0) return aien_mid_load(p, &r->machine) == AIEN_MID_OK ? 0 : -1;
272 uint8_t root[32];
273 if (getrandom(root, sizeof root, 0) != (ssize_t)sizeof root) return -1;
274 if (aien_mid_derive(AIEN_MID_ROOT_PROVISIONED, root, sizeof root, &r->machine) != AIEN_MID_OK)
275 return -1;
276 return aien_mid_store(p, &r->machine) == AIEN_MID_OK ? 0 : -1;
277}
278
279/* ---- R16 G6 operator control (docs/r16-operator-control.md) --------------
280 * The program's durable state: <state>/control (the operator's credential
281 * file and socket) and one generation store per mode, <state>/gen-<key>,
282 * which is also the world's durable halt directory. */
283enum { OP_SHUTDOWN = 2 };
284static const char *const g_mode_key[] = {"positive", "no-aien", "no-promotion",
285 "revoked-experiment", "stale-gpu", "failed-verification"};
286static char g_state_dir[192];
287static char g_control_dir[224];
288/* flock descriptors held for the program's life (rx_operator_lock_dir): the
289 * state directory and each generation (halt) directory once a world uses it. */
290static int g_state_lock = -1;
291static int g_gen_lock[] = {-1, -1, -1, -1, -1, -1};
292static uint64_t g_op_stops, g_op_resumes, g_op_restored, g_op_open, g_op_cancelled;
293
294static int world_halted(Rig *r) {
295 RxHaltStatus h;
296 rx_world_halt_status(&r->w, &h);
297 return h.halted;
298}
299
300/* Run time: wall time minus the time the world spent stopped. Episode
301 * deadlines count run time, so a stop delays the episode and never fails it. */
302static uint64_t run_clock(Rig *r) {
303 uint64_t now = now_ns(), since = atomic_load(&r->op_halt_since);
304 return now - atomic_load(&r->op_halt_total) - (since && since < now ? now - since : 0);
305}
306
307static void op_on_halt(void *ctx, int halted) {
308 Rig *r = ctx;
309 uint64_t now = now_ns(), since = atomic_load(&r->op_halt_since);
310 if (halted && !since) atomic_store(&r->op_halt_since, now);
311 if (!halted && since) {
312 atomic_fetch_add(&r->op_halt_total, now - since);
313 atomic_store(&r->op_halt_since, 0);
314 }
315}
316
317static atomic_int g_op_shutdown; /* the operator ended this program (FAIL reports it) */
318static void op_on_shutdown(void *ctx) {
319 atomic_store(&((Rig *)ctx)->op_shutdown, 1);
320 atomic_store(&g_op_shutdown, 1);
321}
322
323static void op_describe(void *ctx, char *buf, size_t n) {
324 Rig *r = ctx;
325 if (!r->ready) { snprintf(buf, n, "world=%s setup=pending", g_mode_key[r->mode]); return; }
326 uint64_t active = 0, lineage = 0;
327 rx_gen_active(r->gen, &active, &lineage);
328 snprintf(buf, n, "world=%s served=%llu production_commits=%llu promotion=%llu inforce=%llu "
329 "active_generation=%llu seat_claims=%llu seat_halted=%llu",
330 g_mode_key[r->mode], (unsigned long long)__atomic_load_n(&r->served, __ATOMIC_RELAXED),
331 (unsigned long long)__atomic_load_n(&r->w.reactions[r->omega.r_serve].commits,
332 __ATOMIC_RELAXED),
333 (unsigned long long)field(r, r->living.o.promotion, 0),
334 (unsigned long long)field(r, r->living.o.inforce, 0), (unsigned long long)active,
335 (unsigned long long)__atomic_load_n(&r->w.stats.resident_claims, __ATOMIC_RELAXED),
336 (unsigned long long)__atomic_load_n(&r->w.stats.resident_halted, __ATOMIC_RELAXED));
337}
338
339/* Wait while the world is stopped. -1 when the operator shut the program
340 * down, the program is tearing the world down, or the production thread
341 * is told to stop, 0 when the world runs. */
342static __thread int t_producer; /* set on the production request thread */
343static int wait_running(Rig *r) {
344 while (world_halted(r)) {
345 if (atomic_load(&r->op_shutdown) || atomic_load(&r->op_teardown) ||
346 (t_producer && atomic_load(&r->producer_stop))) return -1;
347 pause_us(1000);
348 }
349 return atomic_load(&r->op_shutdown) ? -1 : 0;
350}
351
352/* An outside publication refused by an operator stop is published again
353 * after the resume; any other refusal is an error. */
354static int publish(Rig *r, RxCapRef cap, const RxMutation *m, uint32_t n) {
355 for (;;) {
356 int64_t rc = rx_world_publish_external(&r->w, cap, m, n);
357 if (rc != RX_ERR_HALTED) return rc > 0 ? 0 : -1;
358 if (wait_running(r) != 0) return 1; /* abandoned under a stop, not an error */
359 }
360}
361
362static int operator_open(Rig *r) {
363 RxOperatorConfig oc = {&r->w, r->admin, g_control_dir, g_mode_key[r->mode],
364 op_describe, op_on_halt, op_on_shutdown, r};
365 if (rx_operator_open(&r->op, &oc, RX_OPERATOR_SUBJ, &r->op_cred, r->op_cap) != 0) return -1;
366 r->op_gate_held = 1;
367 return 0;
368}
369static void operator_release(Rig *r) {
370 if (r->op && r->op_gate_held) { r->op_gate_held = 0; rx_operator_release(r->op); }
371}
372static void operator_hold(Rig *r) {
373 if (r->op && !r->op_gate_held) { rx_operator_hold(r->op); r->op_gate_held = 1; }
374}
375
376/* The canonical evidence of operator control in this world: its crumb log.
377 * Between an OPERATOR_STOP and its OPERATOR_RESUME (or after a stop never
378 * resumed) no COMMIT and no EXTERNAL crumb may appear; each RESUME is caused
379 * by the STOP before it. */
380static int operator_audit(Rig *r) {
381 uint64_t stops = 0, resumes = 0, commits = 0, externals = 0, cancelled = 0, open = 0;
382 int order_ok = 1;
383 for (uint64_t id = 1; id <= r->w.n_crumbs; id++) {
384 const RxCrumb *c = rx_world_crumb(&r->w, id);
385 if (!c) continue;
386 if (c->kind == RX_CRUMB_OPERATOR_STOP) {
387 if (open) order_ok = 0;
388 stops++;
389 open = id;
390 } else if (c->kind == RX_CRUMB_OPERATOR_RESUME) {
391 if (!open || c->n_parents < 1 || c->parents[0] != open) order_ok = 0;
392 resumes++;
393 open = 0;
394 } else if (open) {
395 if (c->kind == RX_CRUMB_COMMIT) commits++;
396 if (c->kind == RX_CRUMB_EXTERNAL) externals++;
397 if (c->kind == RX_CRUMB_CANCELLED && c->reason == RX_ERR_HALTED) cancelled++;
398 }
399 }
400 g_op_stops += stops; g_op_resumes += resumes; g_op_cancelled += cancelled;
401 g_op_restored += (uint64_t)r->op_restored; g_op_open += open ? 1 : 0;
402 printf("R13 operator %s: stops %llu resumes %llu restored %d open %d; under stop: commits %llu "
403 "externals %llu cancelled %llu; order %s\n", g_mode_key[r->mode], U(stops), U(resumes),
404 r->op_restored, open ? 1 : 0, U(commits), U(externals), U(cancelled),
405 order_ok ? "ok" : "BROKEN");
406 return commits || externals || !order_ok ? -1 : 0;
407}
408
409
410/* The program's state directory: --state-dir, or a fresh 0700 scratch
411 * directory. Refused (exit 2, before any world starts) unless it and its
412 * control directory are real directories owned by this uid with no group or
413 * other permission bits, and the socket path fits a socket address. */
414static int operator_state(const char *dir) {
415 char why[320];
416 if (dir) {
417 if ((size_t)snprintf(g_state_dir, sizeof g_state_dir, "%s", dir) >= sizeof g_state_dir) {
418 fprintf(stderr, "R13 operator: state directory refused: path too long\n");
419 return -1;
420 }
421 } else if (scratch_dir(g_state_dir, sizeof g_state_dir, "r13-state") != 0) {
422 fprintf(stderr, "R13 operator: no scratch state directory\n");
423 return -1;
424 }
425 /* Held for the program's life: a second program on the same state
426 * directory is refused here, before it touches a socket or a credential. */
427 if (rx_operator_lock_dir(g_state_dir, 1, &g_state_lock, why, sizeof why) != 0) {
428 fprintf(stderr, "R13 operator: state directory refused: %s\n", why);
429 return -1;
430 }
431 if ((size_t)snprintf(g_control_dir, sizeof g_control_dir, "%s/control", g_state_dir) >=
432 sizeof g_control_dir ||
433 strlen(g_control_dir) + 1 + strlen(RX_OPERATOR_SOCK) >=
434 sizeof(((struct sockaddr_un *)0)->sun_path)) {
435 fprintf(stderr, "R13 operator: state directory refused: socket path too long\n");
436 return -1;
437 }
438 if (rx_operator_dir_check(g_control_dir, 1, why, sizeof why) != 0) {
439 fprintf(stderr, "R13 operator: control directory refused: %s\n", why);
440 return -1;
441 }
442 printf("R13 operator: state %s, control %s (operator subject %u, pid %ld)\n", g_state_dir,
443 g_control_dir, (unsigned)RX_OPERATOR_SUBJ, (long)getpid());
444 return 0;
445}
446static int start(Rig *r, int mode) {
447 int with_aien = mode != NO_AIEN;
448 int promotion_authority = mode != NO_PROMOTION;
449 memset(r, 0, sizeof *r);
450 r->mode = mode;
451 g_stage = 1;
452 if (aienos_cap_start(&r->admin, &r->view) != 0) return -1;
453 if (rx_world_init_native(&r->w, r->view, 4, RX_CRUMBS_LONG_EPISODE) != RX_OK) return -1;
454 r->w.external_subject = EXTERNAL;
455 /* R16 C6: every production subject gets a runtime-issued credential,
456 * then the world refuses any registration that does not present one. */
457 if (rx_living_enroll_callers(&r->w, &r->keys) != RX_OK) return -1;
458 /* R16 G6: the operator, enrolled like every production subject before
459 * enrollment closes. It runs no reaction (docs/r16-operator-control.md). */
460 if (rx_world_enroll_caller(&r->w, RX_OPERATOR_SUBJ, &r->op_cred) != RX_OK) return -1;
461 /* Test build only: the composition and Fabric phases run inside this
462 * World (rx_compose_attach); their subjects are enrolled here, before
463 * enrollment closes. The production program enrolls no test subject. */
464#ifdef AIEN_TEST_BUILD
465 if (rx_compose_enroll_callers(&r->w, &r->compose_keys) != RX_OK) return -1;
466#endif
467 if (rx_world_bind_callers(&r->w) != RX_OK) return -1;
468 /* The generation store of this mode lives in the program's validated
469 * state directory; it is also the world's durable halt directory. */
470 char why[320];
471 if ((size_t)snprintf(r->generation_dir, sizeof r->generation_dir, "%s/gen-%s", g_state_dir,
472 g_mode_key[mode]) >= sizeof r->generation_dir ||
473 (g_gen_lock[mode] < 0 &&
474 rx_operator_lock_dir(r->generation_dir, 1, &g_gen_lock[mode], why, sizeof why) != 0)) {
475 fprintf(stderr, "R13 operator: generation directory refused: %s\n", why);
476 return -1;
477 }
478 if (scratch_dir(r->home_dir, sizeof r->home_dir, "r13-home") != 0 || living_identity(r) != 0)
479 return -1;
480 if (rx_gen_open(r->generation_dir, &r->gen) != RX_GEN_OK) return -1;
481 if (rx_gen_bind_authority(r->gen, rx_world_caller_check_fn, &r->w,
482 rx_living_native_authority, r->view) != RX_GEN_OK) return -1;
483 /* R16 G6: the control capability, the durable halt directory, then the
484 * entry point, all before any object exists or any work is published. A
485 * stop that outlived the last start is in force from here; the program
486 * then serves the operator and does nothing else until it is resumed. */
487 r->op_cap = mint(r, RX_OPERATOR_SUBJ, RX_WORLD_RES_CONTROL, RX_WORLD_RIGHT_HALT);
488 int halt_mark = rx_world_set_halt_dir(&r->w, r->generation_dir);
489 if (operator_open(r) != 0) return -1;
490 if (world_halted(r)) {
491 r->op_restored = 1;
492 atomic_store(&r->op_halt_since, now_ns());
493 printf("R13 operator %s: restored STOPPED from %s (mark %d); no work until an operator "
494 "resume\n", g_mode_key[mode], r->generation_dir, halt_mark);
495 operator_release(r);
496 if (wait_running(r) != 0) return OP_SHUTDOWN;
497 operator_hold(r);
498 }
499 g_stage = 2;
500 const uint32_t R = RX_RIGHT_READ, RW = RX_RIGHT_READ | RX_RIGHT_WRITE;
501 RxOmegaConfig oc;
502 rx_omega_default_config(&oc);
503 oc.hot_calls = 64; oc.hot_ns = 200000; oc.margin_pct = 10;
504 if (mode == FAILED_VERIFICATION) oc.defect = RX_OMEGA_DEFECT_CRASH;
505 if (rx_omega_create_objects(&r->omega, &r->w, &oc) != RX_OK) return -1;
506 r->omega.keys = &r->keys.omega;
507 RxAienConfig ac;
508 rx_aien_default_config(&ac);
509 RxAienInputs ai = {r->omega.o.demand, r->omega.o.selection};
510 if (rx_aien_create_objects(&r->aien, &r->w, &ac, &ai) != RX_OK) return -1;
511 r->aien.keys = &r->keys.aien;
512 if (rx_living_create(&r->living, &r->w, &r->aien, &r->omega,
513 r->gen, r->view) != RX_OK) return -1;
514 r->living.keys = &r->keys.living;
515 if (new_object(r, 0x6135, RES_INTENT, &r->intent) != RX_OK) return -1;
516
517 /* R8 permits exactly one experiment output resource. */
518 RxAegisPolicy pol;
519 memset(&pol, 0, sizeof pol);
520 pol.n_rules = 1;
521 pol.rules[0] = (RxAegisRule){1, RX_LIVING_SEAT_SUBJ,
522 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT,
523 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, RW, 0, 0};
524 RxAegisClient cl = {RX_LIVING_SEAT_SUBJ,
525 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT,
526 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, RW};
527 if (rx_aegis_create(&r->aegis, &r->w, r->admin, &pol, &cl, 1) != RX_OK) return -1;
528 r->aegis.keys = &r->keys.aegis;
529 RxAegisCaps aeg;
530 memset(&aeg, 0, sizeof aeg);
531 aeg.aegis_request = mint(r, RX_AEGIS_SUBJ, rx_aegis_res(0, RX_AEGIS_RES_REQUEST), R);
532 aeg.aegis_approval = mint(r, RX_AEGIS_SUBJ, rx_aegis_res(0, RX_AEGIS_RES_APPROVAL), R);
533 aeg.aegis_decision = mint(r, RX_AEGIS_SUBJ, rx_aegis_res(0, RX_AEGIS_RES_DECISION), RW);
534 aeg.root_request = mint(r, RX_AEGIS_ROOT_SUBJ, rx_aegis_res(0, RX_AEGIS_RES_REQUEST), R);
535 aeg.root_decision = mint(r, RX_AEGIS_ROOT_SUBJ, rx_aegis_res(0, RX_AEGIS_RES_DECISION), R);
536 for (uint32_t j = 0; j < RX_AEGIS_SLOTS; j++)
537 aeg.root_slot[j] = mint(r, RX_AEGIS_ROOT_SUBJ,
538 rx_aegis_res(0, RX_AEGIS_RES_SLOT0+j), RW);
539 if (rx_aegis_register(&r->aegis, &aeg) != RX_OK) return -1;
540 g_stage = 3;
541
542 RxOmegaCaps omega;
543 memset(&omega, 0xff, sizeof omega);
544 omega.serve[RX_OMEGA_RES_REQUEST] = mint(r, RX_OMEGA_SUBJ_SERVE,
545 RX_OMEGA_RES_BASE + RX_OMEGA_RES_REQUEST, R);
546 omega.serve[RX_OMEGA_RES_SELECTION] = mint(r, RX_OMEGA_SUBJ_SERVE,
547 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, R);
548 omega.serve[RX_OMEGA_RES_DEMAND] = mint(r, RX_OMEGA_SUBJ_SERVE,
549 RX_OMEGA_RES_BASE + RX_OMEGA_RES_DEMAND, RW);
550 omega.serve[RX_OMEGA_RES_RESULT] = mint(r, RX_OMEGA_SUBJ_SERVE,
551 RX_OMEGA_RES_BASE + RX_OMEGA_RES_RESULT, RW);
552 omega.omega[RX_OMEGA_RES_DEMAND] = mint(r, RX_OMEGA_SUBJ_OMEGA,
553 RX_OMEGA_RES_BASE + RX_OMEGA_RES_DEMAND, R);
554 omega.omega[RX_OMEGA_RES_SEARCH] = mint(r, RX_OMEGA_SUBJ_OMEGA,
555 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SEARCH, RW);
556 omega.omega[RX_OMEGA_RES_SELECTION] = mint(r, RX_OMEGA_SUBJ_OMEGA,
557 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, RW);
558 for (uint32_t k = 0; k < r->omega.cfg.n_slots; k++) {
559 uint32_t indices[3] = {RX_OMEGA_RES_CANDIDATE0+k,
560 RX_OMEGA_RES_VERDICT0+k, RX_OMEGA_RES_MEASURE0+k};
561 for (uint32_t j = 0; j < 3; j++)
562 omega.omega[indices[j]] = mint(r, RX_OMEGA_SUBJ_OMEGA,
563 RX_OMEGA_RES_BASE + indices[j], RW);
564 }
565 RxCapRef omega_belief = mint(r, RX_OMEGA_SUBJ_OMEGA,
566 RX_AIEN_RES_BASE + RX_AIEN_RES_EXPERIMENT_BELIEF, R);
567 if (rx_omega_require_evidence(&r->omega, r->aien.o.experiment_belief,
568 omega_belief) != RX_OK) return -1;
569 /* Production runs what the promotion authority put in force, not what
570 * Omega merely selected. */
571 if (rx_omega_serve_from(&r->omega, r->living.o.inforce, mint(r, RX_OMEGA_SUBJ_SERVE,
572 RX_LIVING_RES_BASE + RX_LIVING_RES_INFORCE, R)) != RX_OK) return -1;
573 if (rx_omega_register(&r->omega, &omega) != RX_OK) return -1;
574 g_stage = 4;
575
576 RxAienCaps aien;
577 memset(&aien, 0xff, sizeof aien);
578 for (uint32_t i = 0; i < RX_AIEN_RES_COUNT; i++)
579 aien.own[i] = mint(r, RX_AIEN_SUBJ, RX_AIEN_RES_BASE + i,
580 i == RX_AIEN_RES_PLACEMENT || i == RX_AIEN_RES_GOAL ? R : RW);
581 aien.demand = mint(r, RX_AIEN_SUBJ,
582 RX_OMEGA_RES_BASE + RX_OMEGA_RES_DEMAND, R);
583 aien.selection = mint(r, RX_AIEN_SUBJ,
584 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, R);
585 if (with_aien) {
586 if (rx_aien_register(&r->aien, &aien) != RX_OK) return -1;
587 g_stage = 41;
588 RxCapRef ev = mint(r, RX_AIEN_SUBJ,
589 RX_LIVING_RES_BASE + RX_LIVING_RES_EVIDENCE, R);
590 if (rx_aien_register_experiment(&r->aien, r->living.o.evidence,
591 ev, aien.own[RX_AIEN_RES_EXPERIMENT_BELIEF]) != RX_OK) return -1;
592 g_stage = 42;
593 RxCapRef plan_read = mint(r, RX_OMEGA_SUBJ_OMEGA,
594 RX_AIEN_RES_BASE + RX_AIEN_RES_PLAN, R);
595 if (rx_omega_register_reconsider(&r->omega, r->aien.o.plan,
596 plan_read, omega.omega[RX_OMEGA_RES_SEARCH],
597 omega.omega[RX_OMEGA_RES_SELECTION]) != RX_OK) return -1;
598 g_stage = 43;
599 }
600
601 RxLivingCaps lc;
602 memset(&lc, 0, sizeof lc);
603 lc.plan_read = mint(r, RX_LIVING_SUBJ, RX_AIEN_RES_BASE + RX_AIEN_RES_PLAN, R);
604 lc.search_read = mint(r, RX_LIVING_SUBJ,
605 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SEARCH, R);
606 lc.input_write = mint(r, RX_LIVING_SUBJ,
607 RX_LIVING_RES_BASE + RX_LIVING_RES_INPUT, RW);
608 lc.input_seat_read = mint(r, RX_LIVING_SEAT_SUBJ,
609 RX_LIVING_RES_BASE + RX_LIVING_RES_INPUT, R);
610 lc.output_read = mint(r, RX_LIVING_SUBJ,
611 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, R);
612 lc.evidence_write = mint(r, RX_LIVING_SUBJ,
613 RX_LIVING_RES_BASE + RX_LIVING_RES_EVIDENCE, RW);
614 lc.belief_read = mint(r, RX_LIVING_PREPARE_SUBJ,
615 RX_AIEN_RES_BASE + RX_AIEN_RES_EXPERIMENT_BELIEF, R);
616 lc.selection_read = mint(r, RX_LIVING_PREPARE_SUBJ,
617 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, R);
618 lc.evidence_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
619 RX_LIVING_RES_BASE + RX_LIVING_RES_EVIDENCE, R);
620 lc.candidate_write = mint(r, RX_LIVING_PREPARE_SUBJ,
621 RX_LIVING_RES_BASE + RX_LIVING_RES_CANDIDATE, RW);
622 lc.goal_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
623 RX_AIEN_RES_BASE + RX_AIEN_RES_GOAL, R);
624 lc.plan_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
625 RX_AIEN_RES_BASE + RX_AIEN_RES_PLAN, R);
626 lc.search_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
627 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SEARCH, R);
628 lc.output_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
629 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, R);
630 r->promoter.world = &r->w;
631 r->promoter.keys = &r->keys.promoter;
632 r->promoter.store = r->gen;
633 r->promoter.authority = r->view;
634 r->promoter.candidate = r->living.o.candidate;
635 r->promoter.promotion = r->living.o.promotion;
636 r->promoter.inforce = r->living.o.inforce;
637 r->promoter.candidate_read = mint(r, RX_LIVING_PROMOTE_SUBJ,
638 RX_LIVING_RES_BASE + RX_LIVING_RES_CANDIDATE, R);
639 r->promoter.promotion_write = mint(r, RX_LIVING_PROMOTE_SUBJ,
640 RX_LIVING_RES_BASE + RX_LIVING_RES_PROMOTION, RW);
641 r->promoter.inforce_write = mint(r, RX_LIVING_PROMOTE_SUBJ,
642 RX_LIVING_RES_BASE + RX_LIVING_RES_INFORCE, RW);
643 r->promoter.promotion_authority = promotion_authority ? mint(r, RX_LIVING_PROMOTE_SUBJ,
644 RX_GEN_RES_PROMOTION, RX_GEN_RIGHT_PROMOTE) : (RxCapRef){UINT32_MAX, 0};
645 lc.output_slot = r->aegis.o[0].slot[0];
646 lc.output_slot_read = mint(r, RX_LIVING_SEAT_SUBJ,
647 rx_aegis_res(0, RX_AEGIS_RES_SLOT0), R);
648 /* R8 acquisition takes place before the measured human episode. */
649 r->ext_intent = mint(r, EXTERNAL, RES_INTENT, RX_RIGHT_WRITE);
650 RxReactionDesc d;
651 memset(&d, 0, sizeof d);
652 d.name = "living.experiment.ask";
653 d.faculty = RX_FACULTY_OMEGA;
654 d.subject = RX_LIVING_SEAT_SUBJ;
655 d.priority = RX_PRIO_FOREGROUND;
656 d.fn = ask; d.user = r; d.stamp_proposed = true;
657 d.n_triggers = 1;
658 d.triggers[0] = (RxDep){r->intent, RX_ALL_FIELDS};
659 d.n_reads = 1;
660 d.reads[0] = (RxDep){r->aegis.o[0].request, RX_ALL_FIELDS};
661 d.n_writes = 1;
662 d.writes[0] = (RxDep){r->aegis.o[0].request, RX_ALL_FIELDS};
663 d.n_caps = 2;
664 d.caps[0] = (RxCapNeed){mint(r, RX_LIVING_SEAT_SUBJ, RES_INTENT, R), RES_INTENT, R};
665 d.caps[1] = (RxCapNeed){mint(r, RX_LIVING_SEAT_SUBJ,
666 rx_aegis_res(0, RX_AEGIS_RES_REQUEST), RW),
667 rx_aegis_res(0, RX_AEGIS_RES_REQUEST), RW};
668 if (rx_world_add_reaction_keyed(&r->w, &r->keys.living, &d, &r->r_ask) != RX_OK) return -1;
669 RxMutation request[6] = {
670 {r->intent, 0, 1},
671 {r->intent, 1, RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT},
672 {r->intent, 2, RW}, {r->intent, 3, 0}, {r->intent, 4, 0},
673 {r->intent, 5, RX_AEGIS_OP_ACQUIRE}};
674 if (rx_world_publish_external(&r->w, r->ext_intent, request, 6) <= 0 ||
675 rx_world_wait_quiescent(&r->w, 10000) != RX_OK) return -1;
676 r->seat_output = (RxCapRef){field(r, lc.output_slot, 0),
677 field(r, lc.output_slot, 1)};
678 r->seat_input = lc.input_seat_read;
679 if (field(r, lc.output_slot, 2) != RX_AEGIS_SLOT_LIVE) return -1;
680 g_stage = 6;
681 if (rx_world_bind_capability(&r->w, r->living.o.input, r->seat_input) != RX_OK ||
682 rx_world_bind_capability(&r->w, r->living.o.output, r->seat_output) != RX_OK)
683 return -1;
684 if (rx_world_enable_resident(&r->w) != RX_OK) return -1;
685 int lrc = rx_living_register(&r->living, &lc, &r->promoter);
686 if (lrc != RX_OK) {
687 fprintf(stderr, "living register rc=%d reactions=%u\n", lrc, r->w.n_reactions);
688 return -1;
689 }
690 RxResourceBudget budget = {0};
691 budget.slots = 8;
692 budget.memory_bytes = UINT64_MAX;
693 budget.energy_budget = UINT64_MAX;
694 budget.offered_locality = UINT32_MAX;
695 budget.offered_accel = RX_ACCEL_BLACKWELL;
696 budget.compute_mask = UINT32_MAX;
697 rx_world_set_resources(&r->w, &budget);
698 r->ext_request = mint(r, EXTERNAL,
699 RX_OMEGA_RES_BASE + RX_OMEGA_RES_REQUEST, RX_RIGHT_WRITE);
700 r->ext_goal = mint(r, EXTERNAL,
701 RX_AIEN_RES_BASE + RX_AIEN_RES_GOAL, RX_RIGHT_WRITE);
702 r->ext_placement = mint(r, EXTERNAL,
703 RX_AIEN_RES_BASE + RX_AIEN_RES_PLACEMENT, RX_RIGHT_WRITE);
704#ifdef R13_SILICON
705 if (rx_gpu_seat_begin(&r->w, &r->seat) != 0 || !r->seat) return -1;
706#endif
707 g_stage = 7;
708 r->ready = 1;
709 operator_release(r); /* operator requests are served from here */
710 return 0;
711}
712
713/* The human goal: bring this matvec below TARGET_PCT percent of the cost the
714 * body had confirmed before the goal, preserving its semantics. */
715#ifndef TARGET_PCT
716#define TARGET_PCT 55u
717#endif
718
719static uint64_t expected_digest(uint64_t seed) {
720 uint64_t *A = malloc((size_t)M*N*sizeof(uint64_t));
721 uint64_t *x = malloc((size_t)N*sizeof(uint64_t));
722 uint64_t *y = malloc((size_t)M*sizeof(uint64_t));
723 if (!A || !x || !y) { free(A); free(x); free(y); return 0; }
724 rx_omega_fill(seed, A, x, M, N);
725 omega_matvec_reference(A, x, y, M, N);
726 uint64_t result = rx_omega_digest(y, M);
727 free(A); free(x); free(y);
728 return result;
729}
730
731/* One ordinary production request. The harness publishes it and reads the
732 * result; it never touches a faculty. */
733static int serve(Rig *r) {
734 uint64_t seq = ++r->request_seq;
735 uint64_t seed = seq * 0x2545F4914F6CDD1Dull;
736 RxMutation m[4] = {{r->omega.o.request, 0, seq},
737 {r->omega.o.request, 1, M}, {r->omega.o.request, 2, N},
738 {r->omega.o.request, 3, seed}};
739 int p = publish(r, r->ext_request, m, 4);
740 if (p != 0) return p;
741 uint64_t t = run_clock(r); /* a stop pauses this deadline */
742 while (field(r, r->omega.o.result, 0) != seq) {
743 /* Under a stop (seen through the operator clock, no world lock in this
744 * spin) the request is refused or queued: it runs again on resume. */
745 if (atomic_load(&r->op_halt_since) && world_halted(r)) {
746 if (wait_running(r) != 0) return 1;
747 continue;
748 }
749 if (run_clock(r) - t > 5000000000ull) return -1;
750 spin_us(5); /* a workload does not nap between requests */
751 }
752 if (field(r, r->omega.o.result, 1) != expected_digest(seed)) r->wrong++;
753 uint64_t used = field(r, r->omega.o.result, 2);
754 /* The in-force record only moves forward, so reading it after the result
755 * can only excuse a use that was in force by then. */
756 if (used != 0 && (field(r, r->living.o.inforce, 0) == 0 ||
757 field(r, r->living.o.inforce, 1) != used))
758 r->unpromoted_use++;
759 __atomic_add_fetch(&r->served, 1, __ATOMIC_RELAXED);
760 return 0;
761}
762
763static void *producer_main(void *arg) {
764 Rig *r = arg;
765 t_producer = 1;
766 while (!atomic_load(&r->producer_stop)) {
767 int s = serve(r);
768 if (s < 0) { atomic_store(&r->producer_error, 1); break; }
769 if (s > 0) break; /* told to stop while the world was stopped */
770 }
771 return NULL;
772}
773
774/* The store calls this on its executor inside the promotion barrier: the
775 * barrier lock is held and the candidate is closing, after the candidate is
776 * written and before the root flips (as R15 G7 does). It waits until
777 * production has committed three more requests, at most 3 s (under the
778 * producer's 5 s request limit, so a stop is reported here). Without it the
779 * window is as long as the barrier's disk work, and on a tmpfs state
780 * directory (the judge's /tmp) that is about 0.35 ms: whether a request
781 * lands in it measured the scheduler, not the barrier. A barrier that stops
782 * production cannot pass: nothing commits while it is held, the wait runs
783 * out, and the check finds fewer than three. (A request stuck behind such a
784 * stop commits the moment it ends, before the promotion crumb, so the
785 * window count alone could not see it.) It reads one counter, takes no lock. */
786static void barrier_watch(const char *dir, void *ctx) {
787 (void)dir;
788 Rig *r = ctx;
789 const uint64_t *commits = &r->w.reactions[r->omega.r_serve].commits;
790 uint64_t c0 = __atomic_load_n(commits, __ATOMIC_RELAXED), t0 = now_ns();
791 while (__atomic_load_n(commits, __ATOMIC_RELAXED) < c0 + 3 &&
792 now_ns() - t0 < 3000000000ull)
793 pause_us(50);
794 r->barrier_calls++;
795 r->barrier_commits = __atomic_load_n(commits, __ATOMIC_RELAXED) - c0;
796 r->barrier_wait_ns = now_ns() - t0;
797}
798
799/* The seat transport calls this once, after it accepted the first trial's
800 * result and before it moves the next claim, so the experiment (and with it
801 * AIEN's plan and Omega's search, which wait on its evidence) is held in
802 * flight until production has committed three more requests, at most 3 s of
803 * run time (an operator stop pauses the bound as it pauses production). On
804 * the host the whole episode from goal to candidate runs on the executor in
805 * less time than a starved producer waits for a CPU under whole-machine load,
806 * so whether a request landed in the AIEN, Omega or GPU window measured the
807 * scheduler, not the faculties. An episode that stops production while it
808 * runs cannot pass: nothing commits while it is held, the wait runs out, and
809 * the check finds fewer than three. It reads one counter, takes no lock. */
810static void seat_watch(Rig *r) {
811 const uint64_t *commits = &r->w.reactions[r->omega.r_serve].commits;
812 uint64_t c0 = __atomic_load_n(commits, __ATOMIC_RELAXED), t0 = run_clock(r);
813 int64_t waited = 0;
814 while (__atomic_load_n(commits, __ATOMIC_RELAXED) < c0 + 3 &&
815 !atomic_load(&r->acceptor_stop)) {
816 waited = (int64_t)(run_clock(r) - t0); /* a stop in flight can read low */
817 if (waited >= 3000000000ll) break;
818 pause_us(50);
819 }
820 r->seat_calls++;
821 r->seat_commits = __atomic_load_n(commits, __ATOMIC_RELAXED) - c0;
822 r->seat_wait_ns = waited > 0 ? (uint64_t)waited : 0;
823}
824
825static int start_producer(Rig *r) {
826 atomic_store(&r->producer_stop, 0);
827 if (pthread_create(&r->producer, NULL, producer_main, r) != 0) return -1;
828 r->producer_live = 1;
829 return 0;
830}
831
832static void stop_producer(Rig *r) {
833 if (!r->producer_live) return;
834 atomic_store(&r->producer_stop, 1);
835 pthread_join(r->producer, NULL);
836 r->producer_live = 0;
837}
838
839static int publish_placement(Rig *r, uint64_t cls) {
840 RxMutation m[2] = {{r->aien.o.placement, 0,
841 field(r, r->aien.o.placement, 0)+1},
842 {r->aien.o.placement, 1, cls}};
843 return publish(r, r->ext_placement, m, 2);
844}
845
846static int publish_goal(Rig *r, uint64_t target) {
847 RxMutation m[3] = {{r->aien.o.goal, 0, 1},
848 {r->aien.o.goal, 1, rx_omega_regime(M, N)},
849 {r->aien.o.goal, 2, target}};
850 return publish(r, r->ext_goal, m, 3);
851}
852
853/* Is `wanted` a causal ancestor of (or equal to) `node`? Iterative, with a
854 * visited set; parents always have smaller ids. */
855static uint8_t *g_seen;
856static uint64_t *g_stack;
857/* The visited set and stack grow with the causal log. */
858static uint64_t g_seen_cap;
859static int seen_fit(uint64_t n) {
860 if (n + 1 <= g_seen_cap) return 0;
861 uint64_t cap = g_seen_cap ? g_seen_cap : 1024;
862 while (cap < n + 1) cap *= 2;
863 uint8_t *s = realloc(g_seen, (size_t)cap);
864 if (!s) return -1;
865 g_seen = s;
866 uint64_t *k = realloc(g_stack, sizeof(uint64_t) * (size_t)cap);
867 if (!k) return -1;
868 g_stack = k;
869 g_seen_cap = cap;
870 return 0;
871}
872static int ancestor(RxWorld *w, uint64_t node, uint64_t wanted) {
873 if (!node || !wanted || wanted > node || node > w->n_crumbs) return 0;
874 if (node == wanted) return 1;
875 if (seen_fit(w->n_crumbs) != 0) return 0;
876 memset(g_seen, 0, (size_t)w->n_crumbs + 1);
877 uint64_t sp = 0;
878 g_stack[sp++] = node;
879 g_seen[node] = 1;
880 while (sp) {
881 const RxCrumb *c = rx_world_crumb(w, g_stack[--sp]);
882 if (!c) continue;
883 for (uint32_t i = 0; i < c->n_parents; i++) {
884 uint64_t p = c->parents[i];
885 if (p == wanted) return 1;
886 if (p < wanted || p > w->n_crumbs || g_seen[p]) continue;
887 g_seen[p] = 1;
888 g_stack[sp++] = p;
889 }
890 }
891 return 0;
892}
893
894/* Production commits that ended while an activation of `faculty` (after
895 * crumb `lo`) was executing. */
896static uint64_t overlap(Rig *r, uint64_t lo, uint32_t faculty) {
897 enum { MAXW = 4096 };
898 static uint64_t ws[MAXW], we[MAXW];
899 uint32_t nw = 0;
900 for (uint64_t id = lo + 1; id <= r->w.n_crumbs && nw < MAXW; id++) {
901 const RxCrumb *a = rx_world_crumb(&r->w, id);
902 if (a && a->faculty == faculty && a->reaction != UINT32_MAX) {
903 ws[nw] = a->t_start_ns;
904 we[nw++] = a->t_end_ns;
905 }
906 }
907 uint64_t n = 0;
908 for (uint64_t id = lo + 1; id <= r->w.n_crumbs; id++) {
909 const RxCrumb *p = rx_world_crumb(&r->w, id);
910 if (!p || p->kind != RX_CRUMB_COMMIT || p->reaction != r->omega.r_serve) continue;
911 for (uint32_t j = 0; j < nw; j++)
912 if (ws[j] <= p->t_end_ns && p->t_end_ns <= we[j]) { n++; break; }
913 }
914 return n;
915}
916
917static uint64_t production_between(Rig *r, uint64_t lo, uint64_t hi) {
918 uint64_t n = 0;
919 for (uint64_t id = lo + 1; id < hi; id++) {
920 const RxCrumb *c = rx_world_crumb(&r->w, id);
921 if (c && c->kind == RX_CRUMB_COMMIT && c->reaction == r->omega.r_serve)
922 n++;
923 }
924 return n;
925}
926
927/* Ring transport only: accept the seat's completion notices into the world.
928 * It carries no meaning and decides nothing. */
929/* R16 G6: a seat result refused because an operator stop is in force
930 * (RX_ERR_HALTED) is not a transport fault: the world re-projected the window
931 * and runs the activation again on resume (spec section 3). */
932static int progress(Rig *r) {
933#ifdef R13_SILICON
934 int rc = rx_resident_accept(&r->w);
935 if (rc == RX_OK) r->accepted++;
936 return rc == RX_ERR_NOT_FOUND || rc == RX_OK || rc == RX_ERR_HALTED ? 0 : rc;
937#else
938 int rc = rx_resident_seat_step(&r->w);
939 if (rc == 1) {
940 rc = rx_resident_accept(&r->w);
941 if (rc == RX_OK) r->accepted++;
942 return rc == RX_ERR_HALTED ? 0 : rc;
943 }
944 return rc < 0 && rc != RX_ERR_HALTED ? rc : 0;
945#endif
946}
947
948static void *acceptor_main(void *arg) {
949 Rig *r = arg;
950 while (!atomic_load(&r->acceptor_stop)) {
951 int rc = progress(r);
952 if (rc != 0) atomic_store(&r->acceptor_error, rc);
953 if (r->mode == POSITIVE && r->accepted == 1 && !r->seat_calls) seat_watch(r);
954 pause_us(1000);
955 }
956 return NULL;
957}
958
959/* Every capability the authority holds. Only the promotion authority may
960 * hold the promotion right; no faculty or experiment subject may hold a
961 * privileged right (mint, revoke, reclaim, epoch, clock, promote). */
962static int authority_sweep(Rig *r, uint64_t *swept, uint64_t *holders) {
963 const uint32_t unprivileged[] = {RX_AIEN_SUBJ, RX_OMEGA_SUBJ_SERVE, RX_OMEGA_SUBJ_OMEGA,
964 RX_LIVING_SUBJ, RX_LIVING_SEAT_SUBJ, RX_LIVING_PREPARE_SUBJ, RX_AEGIS_SUBJ, EXTERNAL};
965 AienosCapRef office;
966 if (aienos_cap_office(r->admin, &office) != 0) return -4;
967 *swept = 0; *holders = 0;
968 /* Entry 0 is the Aienux root office itself: the mint, not a holder. Every
969 * other entry starts on the boot generation and moves only on reclaim. */
970 for (uint32_t id = 1; id < 1024; id++)
971 for (uint64_t gen = office.generation; gen < office.generation + 8; gen++) {
972 AienosCapEntry e;
973 if (aienos_cap_inspect(r->view, (AienosCapRef){id, gen}, &e) != 0) continue;
974 if (e.state != 1u) continue; /* AIENOS_CAP_STATE_LIVE */
975 (*swept)++;
976 if ((e.rights & RX_RIGHT_PROMOTE) || e.resource == RX_GEN_RES_PROMOTION) {
977 if (e.subject != RX_LIVING_PROMOTE_SUBJ || e.rights != RX_GEN_RIGHT_PROMOTE)
978 return -1;
979 (*holders)++;
980 }
981 for (uint32_t i = 0; i < sizeof unprivileged / sizeof unprivileged[0]; i++)
982 if (e.subject == unprivileged[i] && (e.rights & RX_RIGHT_PRIVILEGED))
983 return -2;
984 if (e.subject == RX_LIVING_PROMOTE_SUBJ &&
985 (e.rights & RX_RIGHT_PRIVILEGED & ~RX_RIGHT_PROMOTE))
986 return -3;
987 /* R16 G6: only the operator holds the world's control resource,
988 * with exactly the halt right; the operator holds nothing else. */
989 if ((e.resource == RX_WORLD_RES_CONTROL &&
990 (e.subject != RX_OPERATOR_SUBJ || e.rights != RX_WORLD_RIGHT_HALT)) ||
991 (e.subject == RX_OPERATOR_SUBJ && e.resource != RX_WORLD_RES_CONTROL))
992 return -5;
993 }
994 return 0;
995}
996
997/* After the goal, the only outside publications are production requests. */
998static int externals_after(Rig *r, uint64_t goal_crumb, uint64_t *n) {
999 *n = 0;
1000 for (uint64_t id = goal_crumb + 1; id <= r->w.n_crumbs; id++) {
1001 const RxCrumb *c = rx_world_crumb(&r->w, id);
1002 if (!c || c->kind != RX_CRUMB_EXTERNAL) continue;
1003 (*n)++;
1004 if (c->n_outputs != 1 || c->outputs[0].obj.id != r->omega.o.request.id) return -1;
1005 }
1006 return 0;
1007}
1008
1009static long read_file(const char *dir, uint64_t gen, const char *name, void *buf, size_t n) {
1010 char path[512];
1011 snprintf(path, sizeof path, "%s/g/%llu/%s", dir, (unsigned long long)gen, name);
1012 FILE *f = fopen(path, "rb");
1013 if (!f) return -1;
1014 size_t got = fread(buf, 1, n, f);
1015 int more = fgetc(f) != EOF;
1016 fclose(f);
1017 return more ? -1 : (long)got;
1018}
1019
1020static void hex(const uint8_t *b, char out[65]) {
1021 for (uint32_t i = 0; i < 32; i++) sprintf(out + i*2, "%02x", b[i]);
1022}
1023
1024/* The promoted generation explains itself backward from what is on disk:
1025 * its provenance names the crumbs, each crumb still verifies in the world,
1026 * each is an ancestor of the promotion, and the stored bytes rebuild the
1027 * identity the in-force record names. */
1028static int check_durable(Rig *r, uint64_t active, uint64_t promotion, uint64_t *links,
1029 char rebuilt[65], char code_sha[65]) {
1030 RxLivingProvenance pv;
1031 RxLivingConfig cfg;
1032 uint8_t code[AARCH64_MAX_CODE_BYTES];
1033 if (read_file(r->generation_dir, active, "provenance", &pv, sizeof pv) != (long)sizeof pv ||
1034 memcmp(pv.magic, "R13PROV1", 8) != 0) return -1;
1035 if (read_file(r->generation_dir, active, "config", &cfg, sizeof cfg) != (long)sizeof cfg ||
1036 memcmp(cfg.magic, "R13CONF1", 8) != 0) return -2;
1037 long n = read_file(r->generation_dir, active, "realization", code, sizeof code);
1038 if (n <= 0 || (uint64_t)n != cfg.code_len) return -3;
1039 const uint32_t author[RX_LINK_COUNT] = {
1040 UINT32_MAX, r->aien.r_plan, r->omega.r_reconsider, r->living.r_prepare,
1041 r->living.r_seat, r->living.r_evidence, r->aien.r_experiment,
1042 r->omega.r_synth[cfg.kind], r->omega.r_verify[cfg.kind], r->omega.r_measure[cfg.kind],
1043 r->omega.r_select };
1044 *links = 0;
1045 for (uint32_t i = 0; i < RX_LINK_COUNT; i++) {
1046 const RxCrumb *k = rx_world_crumb(&r->w, pv.link[i].crumb);
1047 if (!k || memcmp(k->digest, pv.link[i].digest, 32) != 0 ||
1048 k->reaction != author[i] || pv.link[i].reaction != author[i]) return -10 - (int)i;
1049 if (!ancestor(&r->w, promotion, pv.link[i].crumb)) return -30 - (int)i;
1050 (*links)++;
1051 }
1052 /* Adjacent links are themselves causally ordered. */
1053 const uint32_t chain[][2] = {
1054 {RX_LINK_PLAN, RX_LINK_GOAL}, {RX_LINK_SEARCH, RX_LINK_PLAN},
1055 {RX_LINK_GPU_INPUT, RX_LINK_SEARCH}, {RX_LINK_GPU_OUTPUT, RX_LINK_GPU_INPUT},
1056 {RX_LINK_EVIDENCE, RX_LINK_GPU_OUTPUT}, {RX_LINK_BELIEF, RX_LINK_EVIDENCE},
1057 {RX_LINK_SELECTION, RX_LINK_BELIEF}, {RX_LINK_SYNTH, RX_LINK_SEARCH},
1058 {RX_LINK_VERDICT, RX_LINK_SYNTH}, {RX_LINK_MEASURE, RX_LINK_VERDICT},
1059 {RX_LINK_SELECTION, RX_LINK_MEASURE} };
1060 for (uint32_t i = 0; i < sizeof chain / sizeof chain[0]; i++)
1061 if (!ancestor(&r->w, pv.link[chain[i][0]].crumb, pv.link[chain[i][1]].crumb))
1062 return -50 - (int)i;
1063 SemanticId id;
1064 if (rx_omega_identity_of(&r->omega, code, (size_t)n, &id) != 0 ||
1065 memcmp(id.bytes, cfg.identity, 32) != 0) return -4;
1066 for (uint32_t j = 0; j < 4; j++) {
1067 uint64_t word = 0;
1068 for (uint32_t b = 0; b < 8; b++) word |= (uint64_t)id.bytes[j*8+b] << (8*b);
1069 if (word != field(r, r->living.o.inforce, 1 + j)) return -5;
1070 }
1071 hex(id.bytes, rebuilt);
1072 sha256_ctx c;
1073 uint8_t h[32];
1074 sha256_init(&c);
1075 sha256_update(&c, code, (size_t)n);
1076 sha256_final(&c, h);
1077 hex(h, code_sha);
1078 return 0;
1079}
1080
1081/* The seat was made ready and stopped by the authority check. */
1082static int seat_blocked(Rig *r, uint64_t after) {
1083 for (uint64_t id = after + 1; id <= r->w.n_crumbs; id++) {
1084 const RxCrumb *c = rx_world_crumb(&r->w, id);
1085 if (c && c->kind == RX_CRUMB_BLOCKED_AUTHORITY && c->reaction == r->living.r_seat)
1086 return 1;
1087 }
1088 return 0;
1089}
1090
1091static uint64_t acts(Rig *r, uint32_t id) { return r->w.reactions[id].activations; }
1092
1093/* Failure evidence (omega #313 item 3): the FIRST failure message is kept for the receipt,
1094 * never overwritten by later ones. stderr still gets every message. */
1095static char g_first_failure[512];
1096static void note_failure(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
1097static void note_failure(const char *fmt, ...) {
1098 char msg[512];
1099 va_list ap;
1100 va_start(ap, fmt);
1101 vsnprintf(msg, sizeof msg, fmt, ap);
1102 va_end(ap);
1103 fprintf(stderr, "%s\n", msg);
1104 if (!g_first_failure[0]) snprintf(g_first_failure, sizeof g_first_failure, "%s", msg);
1105}
1106
1107#define FAIL(...) do { if (atomic_load(&g_op_shutdown)) return OP_SHUTDOWN; \
1108 char fail_msg_[400]; \
1109 snprintf(fail_msg_, sizeof fail_msg_, __VA_ARGS__); \
1110 note_failure("R13 mode %d: %s", mode, fail_msg_); return -1; } while (0)
1111
1112static int run(Rig *r, int mode) {
1113 int with_aien = mode != NO_AIEN;
1114 cpu_set_t a, x;
1115 if (core_sets(&a, &x) != 0 || move_threads(&a) <= 0) FAIL("needs both core classes");
1116 if (publish_placement(r, CLASS_A725) != 0) FAIL("placement");
1117 uint64_t limit = run_clock(r) + 60000000000ull;
1118 while (field(r, r->omega.o.selection, 0) < 1 && run_clock(r) < limit)
1119 if (serve(r) != 0) FAIL("serve");
1120 if (field(r, r->omega.o.selection, 0) != 1) FAIL("no first selection");
1121 uint64_t incumbent = field(r, r->omega.o.selection, 1);
1122 uint64_t incumbent_ns = 0;
1123 if (with_aien) {
1124 while (field(r, r->aien.o.prediction, 6) != RX_AIEN_PRED_CONFIRMED &&
1125 run_clock(r) < limit)
1126 if (serve(r) != 0) FAIL("serve");
1127 if (field(r, r->aien.o.prediction, 6) != RX_AIEN_PRED_CONFIRMED)
1128 FAIL("AIEN never confirmed the incumbent cost");
1129 incumbent_ns = field(r, r->aien.o.prediction, 5);
1130 } else {
1131 incumbent_ns = field(r, r->omega.o.demand, 1) / field(r, r->omega.o.demand, 0);
1132 }
1133 uint64_t target = incumbent_ns * TARGET_PCT / 100u;
1134 uint64_t before_generation = 0, lineage = 0;
1135 rx_gen_active(r->gen, &before_generation, &lineage);
1136 uint64_t before_decide = acts(r, r->aegis.r_decide[0]);
1137 uint64_t before_install = acts(r, r->aegis.r_install[0]);
1138 uint64_t before_production = r->w.reactions[r->omega.r_serve].commits;
1139 uint64_t before_served = r->served;
1140 if (mode == REVOKED_EXPERIMENT) {
1141 AienosCapRef office;
1142 aienos_cap_office(r->admin, &office);
1143 if (aienos_cap_revoke(r->admin, office,
1144 (AienosCapRef){r->seat_output.cap_id, r->seat_output.generation}) != 0)
1145 FAIL("revoke");
1146 }
1147 /* Production is a workload of its own, already running when the goal
1148 * arrives. From here this thread only observes. */
1149 /* A burst that passes is refuted by AIEN relearning the record; a cost
1150 * that really moved before the goal is researched as drift, so the
1151 * episode below is no longer the goal's alone. Say so: it is a real
1152 * slowdown of this machine, not a fault of the episode. */
1153 if (with_aien && field(r, r->aien.o.plan, 0) != 0 &&
1154 field(r, r->aien.o.plan, 5) == RX_AIEN_WHY_DRIFT)
1155 fprintf(stderr, "R13 note (mode %d): the incumbent cost moved before the goal (AIEN "
1156 "expected %llu ns, saw %llu ns, relearned %llu ns) and AIEN asked for drift "
1157 "research\n", mode, U(field(r, r->aien.o.hypothesis, 5)),
1158 U(field(r, r->aien.o.hypothesis, 6)), U(incumbent_ns));
1159 if (start_producer(r) != 0) FAIL("producer");
1160 if (mode == POSITIVE) rx_gen_set_disk_hook(r->gen, barrier_watch, r);
1161 /* The environment changes (the body now runs on the X925 cores) and the
1162 * human states the goal. After this, the harness only serves and reads. */
1163 if (move_threads(&x) <= 0 || publish_placement(r, CLASS_X925) != 0 ||
1164 publish_goal(r, target) != 0) FAIL("goal");
1165 uint64_t goal_crumb = rx_world_explain(&r->w, r->aien.o.goal, 0);
1166 if (mode != STALE_GPU) {
1167 atomic_store(&r->acceptor_stop, 0);
1168 if (pthread_create(&r->acceptor, NULL, acceptor_main, r) != 0) FAIL("thread");
1169 r->acceptor_live = 1;
1170 }
1171 /* From here production runs on its own thread, like any workload, and
1172 * this thread only observes. Nothing below advances a faculty. */
1173 limit = run_clock(r) + 90000000000ull;
1174 int stale_injected = 0;
1175 while (run_clock(r) < limit) {
1176 pause_us(20);
1177 if (atomic_load(&r->producer_error)) FAIL("serve");
1178 if (mode == STALE_GPU && !stale_injected &&
1179 r->w.reactions[r->living.r_seat].state == RX_RUNNING) {
1180 /* The object the seat is writing changes generation mid-claim. */
1181 int rr;
1182 while ((rr = rx_world_retire(&r->w, r->living.o.output)) == RX_ERR_HALTED)
1183 if (wait_running(r) != 0) FAIL("retire");
1184 if (rr != RX_OK) FAIL("retire");
1185 stale_injected = 1;
1186 }
1187 int step = mode == STALE_GPU ?
1188 (stale_injected ? progress(r) : 0) : atomic_load(&r->acceptor_error);
1189 if (step != 0 && mode != STALE_GPU) FAIL("seat transport %d", step);
1190 if (field(r, r->living.o.promotion, 0) != 0) break;
1191 uint64_t served = __atomic_load_n(&r->served, __ATOMIC_RELAXED);
1192 if (mode == NO_AIEN && served > before_served + 512) break;
1193 if ((mode == REVOKED_EXPERIMENT || mode == STALE_GPU) &&
1194 field(r, r->aien.o.plan, 0) && served > before_served + 512) break;
1195 }
1196 uint64_t at_promotion = r->w.reactions[r->omega.r_serve].commits;
1197 int promoted = field(r, r->living.o.promotion, 0) != 0 && r->promoter.result == RX_GEN_OK;
1198
1199 /* The organism keeps working. With a promotion, until AIEN has a
1200 * confirmed prediction for the promoted record and has assessed the goal
1201 * on it. Without one, long enough to see production stay put. */
1202 uint64_t final_limit = run_clock(r) + 60000000000ull;
1203 if (promoted) {
1204 uint64_t epoch = field(r, r->living.o.inforce, 0);
1205 while (run_clock(r) < final_limit && !atomic_load(&r->producer_error) &&
1206 !(field(r, r->aien.o.prediction, 1) == epoch &&
1207 field(r, r->aien.o.prediction, 6) == RX_AIEN_PRED_CONFIRMED &&
1208 field(r, r->aien.o.prediction, 4) == CLASS_X925 &&
1209 field(r, r->aien.o.assessment, 6) == field(r, r->aien.o.prediction, 0)))
1210 pause_us(100);
1211 } else {
1212 uint64_t until = __atomic_load_n(&r->served, __ATOMIC_RELAXED) + 256;
1213 while (run_clock(r) < final_limit && !atomic_load(&r->producer_error) &&
1214 __atomic_load_n(&r->served, __ATOMIC_RELAXED) < until)
1215 pause_us(100);
1216 }
1217 stop_producer(r);
1218 if (atomic_load(&r->producer_error)) FAIL("serve");
1219 /* The checks below read a settled world: they wait while it is stopped. */
1220 if (wait_running(r) != 0) FAIL("operator shutdown");
1221 int quiet;
1222 while ((quiet = rx_world_wait_quiescent(&r->w, 10000)) != RX_OK && world_halted(r))
1223 if (wait_running(r) != 0) FAIL("operator shutdown");
1224 uint64_t active = 0, after_lineage = 0;
1225 rx_gen_active(r->gen, &active, &after_lineage);
1226 if (quiet != RX_OK &&
1227 mode != REVOKED_EXPERIMENT && mode != STALE_GPU) FAIL("did not quiesce");
1228 uint64_t checked = 0;
1229 if (rx_world_verify_crumbs(&r->w, &checked) != 0) FAIL("crumbs do not verify");
1230 if (r->w.stats.illegal_transitions) FAIL("illegal lifecycle transition");
1231 if (r->wrong || !r->served ||
1232 r->w.reactions[r->omega.r_serve].commits <= before_production) FAIL("production");
1233 if (r->unpromoted_use) FAIL("production ran a realization not in force (%llu)",
1234 (unsigned long long)r->unpromoted_use);
1235 if (acts(r, r->aegis.r_decide[0]) != before_decide ||
1236 acts(r, r->aegis.r_install[0]) != before_install)
1237 FAIL("AEGIS or root woke during the episode");
1238 uint64_t externals = 0, swept = 0, holders = 0;
1239 if (externals_after(r, goal_crumb, &externals) != 0)
1240 FAIL("an outside publication other than production after the goal");
1241 int sw = authority_sweep(r, &swept, &holders);
1242 if (sw != 0 || swept < r->minted / 2) FAIL("authority sweep %d (%llu live)", sw,
1243 (unsigned long long)swept);
1244 if (holders != (mode == NO_PROMOTION ? 0u : 1u)) FAIL("promotion holders %llu",
1245 (unsigned long long)holders);
1246
1247 if (!with_aien) {
1248 if (field(r, r->aien.o.plan, 0) || r->w.stats.resident_claims ||
1249 field(r, r->living.o.candidate, 0) || active != before_generation ||
1250 field(r, r->living.o.inforce, 0) || r->omega.served_realized)
1251 FAIL("adaptation without AIEN");
1252 printf("R13 control A: no AIEN -> no plan, no GPU experiment, no candidate, "
1253 "generation stays %llu\n", (unsigned long long)active);
1254 g_controls[0] = 1;
1255 return 0;
1256 }
1257 if (mode == NO_PROMOTION) {
1258 RxRecoveryRecord rec;
1259 if (!field(r, r->living.o.candidate, 0) ||
1260 r->promoter.result != RX_GEN_ERR_AUTHORITY ||
1261 (int64_t)field(r, r->living.o.promotion, 1) != RX_GEN_ERR_AUTHORITY ||
1262 active != before_generation || after_lineage != lineage ||
1263 field(r, r->living.o.inforce, 0) || r->omega.served_realized ||
1264 rx_gen_recover(r->generation_dir, &rec) != RX_GEN_OK ||
1265 rec.active_id != before_generation)
1266 FAIL("candidate without promotion authority");
1267 printf("R13 control B: verified candidate %llu refused (RX_GEN_ERR_AUTHORITY); "
1268 "never in force, production stayed on the reference\n",
1269 (unsigned long long)field(r, r->living.o.candidate, 0));
1270 g_controls[1] = 1;
1271 return 0;
1272 }
1273 if (mode == REVOKED_EXPERIMENT) {
1274 if (!field(r, r->aien.o.plan, 0) ||
1275 !seat_blocked(r, goal_crumb) ||
1276 r->w.reactions[r->living.r_seat].commits || r->w.stats.resident_claims ||
1277 field(r, r->living.o.evidence, 0) || field(r, r->living.o.candidate, 0) ||
1278 active != before_generation || field(r, r->living.o.inforce, 0))
1279 FAIL("revoked experiment: seat state %s commits %llu claims %llu evidence %llu",
1280 rx_state_name(r->w.reactions[r->living.r_seat].state),
1281 U(r->w.reactions[r->living.r_seat].commits), U(r->w.stats.resident_claims),
1282 U(field(r, r->living.o.evidence, 0)));
1283 printf("R13 control C: revoked grant -> seat blocked on authority, no claim, "
1284 "no evidence; %llu requests served meanwhile\n",
1285 (unsigned long long)(r->served - before_served));
1286 g_controls[2] = 1;
1287 return 0;
1288 }
1289 if (mode == STALE_GPU) {
1290 if (!stale_injected || r->w.reactions[r->living.r_seat].commits ||
1291 field(r, r->living.o.evidence, 0) || field(r, r->living.o.candidate, 0) ||
1292 active != before_generation || field(r, r->living.o.inforce, 0))
1293 FAIL("stale GPU result");
1294 printf("R13 control D: output generation changed mid-claim -> result refused, "
1295 "no evidence, no candidate\n");
1296 g_controls[3] = 1;
1297 return 0;
1298 }
1299
1300 /* POSITIVE and FAILED_VERIFICATION: the full episode. */
1301 if (!promoted) FAIL("no promotion: result %d, prepare refusal %d", r->promoter.result,
1302 r->living.last_refusal);
1303 uint64_t plan = rx_world_explain(&r->w, r->aien.o.plan, 0);
1304 uint64_t search = rx_world_explain(&r->w, r->omega.o.search, 0);
1305 uint64_t gpu_input = rx_world_explain(&r->w, r->living.o.input, 2);
1306 uint64_t gpu = rx_world_explain(&r->w, r->living.o.output, 0);
1307 uint64_t evidence = rx_world_explain(&r->w, r->living.o.evidence, 0);
1308 uint64_t belief = rx_world_explain(&r->w, r->aien.o.experiment_belief, 0);
1309 uint64_t selection = rx_world_explain(&r->w, r->omega.o.selection, 0);
1310 uint64_t candidate = rx_world_explain(&r->w, r->living.o.candidate, 0);
1311 uint64_t promotion = rx_world_explain(&r->w, r->living.o.promotion, 0);
1312 uint64_t inforce = rx_world_explain(&r->w, r->living.o.inforce, 0);
1313 if (field(r, r->aien.o.plan, 5) != RX_AIEN_WHY_GOAL || field(r, r->aien.o.plan, 6) != 1 ||
1314 field(r, r->aien.o.assessment, 0) != 1) FAIL("plan was not for the goal");
1315 uint64_t nodes[] = {goal_crumb, plan, search, gpu_input, gpu, evidence, belief,
1316 selection, candidate};
1317 for (uint32_t i = 0; i < sizeof nodes / sizeof nodes[0]; i++)
1318 if (!ancestor(&r->w, promotion, nodes[i])) FAIL("promotion does not reach node %u", i);
1319 if (!ancestor(&r->w, inforce, promotion) || inforce != promotion)
1320 FAIL("in-force record not published by the promotion");
1321 if (incumbent != 0 || field(r, r->omega.o.selection, 1) == 0 ||
1322 field(r, r->aien.o.experiment_belief, 0) != 2 ||
1323 field(r, r->aien.o.experiment_belief, 2) != RX_AIEN_EXP_SUPPORTED ||
1324 field(r, r->aien.o.experiment_belief, 3) != RX_LIVING_TRIALS ||
1325 field(r, r->living.o.evidence, 4) != RX_LIVING_TRIALS ||
1326 /* A seat result caught by an operator stop is claimed again on resume. */
1327 r->w.stats.resident_claims - r->w.stats.resident_halted != RX_LIVING_TRIALS ||
1328 r->w.reactions[r->living.r_seat].commits != RX_LIVING_TRIALS ||
1329 r->w.reactions[r->living.r_candidate].commits != 1 ||
1330 r->w.reactions[r->promoter.reaction].commits != 1)
1331 FAIL("episode shape: claims %llu (%llu caught by a stop) seat commits %llu trials %llu",
1332 U(r->w.stats.resident_claims), U(r->w.stats.resident_halted),
1333 U(r->w.reactions[r->living.r_seat].commits),
1334 U(field(r, r->living.o.evidence, 4)));
1335 if (after_lineage != lineage + 1 || active == before_generation ||
1336 field(r, r->living.o.inforce, 7) != active)
1337 FAIL("generation did not advance exactly once");
1338 for (uint32_t j = 0; j < 4; j++)
1339 if (field(r, r->living.o.inforce, 1 + j) != field(r, r->omega.o.selection, 1 + j) ||
1340 field(r, r->living.o.candidate, 2 + j) != field(r, r->omega.o.selection, 1 + j))
1341 FAIL("in force is not the selected realization");
1342 if (!r->omega.served_realized) FAIL("production never ran the promoted realization");
1343 if (mode == FAILED_VERIFICATION) {
1344 uint32_t bad = RX_OMEGA_SLOTS - 1;
1345 if (field(r, r->omega.o.verdict[bad], 1) != RX_OMEGA_REFUSED ||
1346 field(r, r->omega.o.verdict[bad], 5) != RX_OMEGA_WHY_CRASHED ||
1347 field(r, r->living.o.inforce, 1) == field(r, r->omega.o.candidate[bad], 2) ||
1348 field(r, r->living.o.candidate, 2) == field(r, r->omega.o.candidate[bad], 2))
1349 FAIL("defective candidate");
1350 printf("R13 control E: crashing candidate refused by the verifier; the promoted "
1351 "generation holds a verified one\n");
1352 g_controls[4] = 1;
1353 }
1354 RxRecoveryRecord recovery;
1355 if (rx_gen_recover(r->generation_dir, &recovery) != RX_GEN_OK || !recovery.coherent ||
1356 recovery.active_id != active || recovery.lineage != after_lineage)
1357 FAIL("recovery");
1358 uint64_t links = 0;
1359 char rebuilt[65], code_sha[65];
1360 int dr = check_durable(r, active, promotion, &links, rebuilt, code_sha);
1361 if (dr != 0) FAIL("durable provenance %d", dr);
1362 /* AIEN's belief after the change: a confirmed prediction on the new
1363 * record, and the goal assessed against it. */
1364 uint64_t final_status = field(r, r->aien.o.assessment, 4);
1365 uint64_t final_expected = field(r, r->aien.o.assessment, 3);
1366 /* AIEN's part of the episode: from the goal to its belief about the
1367 * physical evidence. The strict count, production that committed while an
1368 * AIEN activation itself was executing, is reported, not gated. */
1369 uint64_t during_aien = production_between(r, goal_crumb, belief);
1370 uint64_t aien_overlap = overlap(r, goal_crumb, RX_FACULTY_AIEN);
1371 uint64_t during_omega = production_between(r, plan, selection);
1372 uint64_t during_gpu = production_between(r, gpu_input, evidence);
1373 uint64_t before_promotion = production_between(r, goal_crumb, promotion);
1374 /* The R9 barrier runs inside generation.promote. Production that committed
1375 * between the candidate and its promotion shows it is not a global stop.
1376 * In POSITIVE the barrier is held until production commits (barrier_watch),
1377 * so a live production always lands in this window; the watch must have run
1378 * once, inside that barrier, and seen three commits while it was held.
1379 * The same for the AIEN, Omega and GPU windows: the seat transport holds
1380 * the experiment after its first trial until production commits
1381 * (seat_watch), and that hold lies inside all three (the input's field 2
1382 * is written once, before the first claim; the evidence closes the last).
1383 * The hold must have run once and seen three commits. */
1384 uint64_t during_promotion = production_between(r, candidate, promotion);
1385 printf("R13 costs: incumbent %llu ns, target %llu ns, selected %llu ps, reference on new "
1386 "cores %llu ps, AIEN now expects %llu ns, goal status %llu\n",
1387 (unsigned long long)incumbent_ns, (unsigned long long)target,
1388 (unsigned long long)field(r, r->omega.o.selection, 5),
1389 (unsigned long long)field(r, r->omega.o.selection, 7),
1390 (unsigned long long)final_expected, (unsigned long long)final_status);
1391 if (final_status != RX_AIEN_GOAL_MET || final_expected > target ||
1392 field(r, r->aien.o.prediction, 1) != field(r, r->living.o.inforce, 0))
1393 FAIL("AIEN's belief does not show the goal met under the new generation");
1394 if (mode == POSITIVE && (!during_aien || !during_omega || !during_gpu ||
1395 !before_promotion || !during_promotion ||
1396 r->seat_calls != 1 || r->seat_commits < 3 ||
1397 r->barrier_calls != 1 || r->barrier_commits < 3))
1398 FAIL("production intervals: AIEN=%llu Omega=%llu GPU=%llu before promotion=%llu "
1399 "during promotion=%llu (seat hold: %llu calls, %llu commits in %llu us; "
1400 "barrier watch: %llu calls, %llu commits in %llu us)",
1401 (unsigned long long)during_aien, (unsigned long long)during_omega,
1402 (unsigned long long)during_gpu, (unsigned long long)before_promotion,
1403 (unsigned long long)during_promotion, (unsigned long long)r->seat_calls,
1404 (unsigned long long)r->seat_commits,
1405 (unsigned long long)(r->seat_wait_ns / 1000u),
1406 (unsigned long long)r->barrier_calls,
1407 (unsigned long long)r->barrier_commits,
1408 (unsigned long long)(r->barrier_wait_ns / 1000u));
1409 const RxCrumb *gpu_c = rx_world_crumb(&r->w, gpu);
1410#ifdef R13_SILICON
1411 if (!r->seat || !gpu_c || gpu_c->worker != RX_SEAT_BLACKWELL)
1412 FAIL("GPU result was not published by the resident Blackwell seat");
1413#endif
1414 if (mode == POSITIVE) {
1415 Receipt *g = &g_receipt;
1416 g->before = before_generation;
1417 g->after = active;
1418 g->recovered = recovery.active_id;
1419 g->goal = r->aien.o.goal;
1420 g->plan = r->aien.o.plan;
1421 g->search = r->omega.o.search;
1422 g->gpu_input = r->living.o.input;
1423 g->gpu_output = r->living.o.output;
1424 g->evidence = r->living.o.evidence;
1425 g->belief = r->aien.o.experiment_belief;
1426 g->selection = r->omega.o.selection;
1427 g->candidate = r->living.o.candidate;
1428 g->promotion = r->living.o.promotion;
1429 g->inforce = r->living.o.inforce;
1430 g->target_ns = target;
1431 g->incumbent_ns = incumbent_ns;
1432 g->selected_ps = field(r, r->omega.o.selection, 5);
1433 g->reference_ps = field(r, r->omega.o.selection, 7);
1434 g->final_expected_ns = final_expected;
1435 g->final_status = final_status;
1436 g->final_prediction_epoch = field(r, r->aien.o.prediction, 1);
1437 g->aien_acts = acts(r, r->aien.r_observe) + acts(r, r->aien.r_predict) +
1438 acts(r, r->aien.r_explain) + acts(r, r->aien.r_assess) +
1439 acts(r, r->aien.r_plan) + acts(r, r->aien.r_experiment);
1440 g->omega_acts = acts(r, r->omega.r_watch) + acts(r, r->omega.r_reconsider) +
1441 acts(r, r->omega.r_select);
1442 for (uint32_t k = 0; k < r->omega.cfg.n_slots; k++)
1443 g->omega_acts += acts(r, r->omega.r_synth[k]) + acts(r, r->omega.r_verify[k]) +
1444 acts(r, r->omega.r_measure[k]);
1445 g->seat_acts = acts(r, r->living.r_seat);
1446 g->aegis_decide_acts = acts(r, r->aegis.r_decide[0]) - before_decide;
1447 g->root_install_acts = acts(r, r->aegis.r_install[0]) - before_install;
1448 g->promote_acts = acts(r, r->promoter.reaction);
1449 g->prepare_acts = acts(r, r->living.r_candidate);
1450 g->gpu_claims = r->w.stats.resident_claims;
1451 g->gpu_completions = r->w.reactions[r->living.r_seat].commits;
1452 g->gpu_worker = gpu_c ? gpu_c->worker : 0;
1453 g->production_aien = during_aien;
1454 g->aien_overlap = aien_overlap;
1455 g->production_omega = during_omega;
1456 g->production_gpu = during_gpu;
1457 g->production_before_promotion = before_promotion;
1458 g->production_during_promotion = during_promotion;
1459 g->production_after_promotion = r->w.reactions[r->omega.r_serve].commits - at_promotion;
1460 g->unpromoted_use = r->unpromoted_use;
1461 g->externals_after_goal = externals;
1462 g->crumbs = checked;
1463 g->links_verified = links;
1464 g->caps_swept = swept;
1465 g->promote_holders = holders;
1466 g->promotion_barrier_ns = field(r, r->living.o.promotion, 2);
1467 const RxCrumb *kc = rx_world_crumb(&r->w, candidate);
1468 const RxCrumb *kp = rx_world_crumb(&r->w, promotion);
1469 if (kc && kp) g->promotion_latency_ns = kp->t_end_ns - kc->t_end_ns;
1470 g->causal_verified = 1;
1471 RxOmegaRealization sel;
1472 if (rx_omega_store_find(&r->omega, field(r, r->omega.o.selection, 1), &sel) == 0)
1473 hex(sel.id.bytes, g->selected_identity);
1474 uint8_t pid[32];
1475 for (uint32_t j = 0; j < 4; j++)
1476 for (uint32_t b = 0; b < 8; b++)
1477 pid[j*8+b] = (uint8_t)(field(r, r->living.o.inforce, 1 + j) >> (8*b));
1478 hex(pid, g->promoted_identity);
1479 memcpy(g->rebuilt_identity, rebuilt, 65);
1480 memcpy(g->realization_sha256, code_sha, 65);
1481#ifdef R13_SILICON
1482 g->silicon_observed = 1;
1483#endif
1484 }
1485 printf("R13 %s: generation %llu -> %llu, recovered %llu; served %llu (%llu after "
1486 "promotion), crumbs %llu, GPU claims %llu, durable links %llu\n",
1487 mode == POSITIVE ? "positive" : "control E episode",
1488 (unsigned long long)before_generation, (unsigned long long)active,
1489 (unsigned long long)recovery.active_id, (unsigned long long)r->served,
1490 (unsigned long long)(r->w.reactions[r->omega.r_serve].commits - at_promotion),
1491 (unsigned long long)checked, (unsigned long long)r->w.stats.resident_claims,
1492 (unsigned long long)links);
1493 return 0;
1494}
1495
1496static void stop(Rig *r) {
1497 /* The entry point goes first: no operator request reaches a world being
1498 * torn down. A stop still in force stays in force (and on disk). */
1499 atomic_store(&r->op_teardown, 1);
1500 operator_release(r);
1501 rx_operator_close(r->op);
1502 r->op = NULL;
1503 stop_producer(r);
1504 if (r->acceptor_live) {
1505 atomic_store(&r->acceptor_stop, 1);
1506 pthread_join(r->acceptor, NULL);
1507 }
1508#ifdef R13_SILICON
1509 if (r->seat) {
1510 (void)rx_resident_shutdown(&r->w);
1511 (void)rx_gpu_seat_finish(r->seat);
1512 }
1513#endif
1514 rx_world_destroy(&r->w);
1515 rx_aegis_destroy(&r->aegis);
1516 rx_omega_destroy(&r->omega);
1517 rx_gen_close(r->gen);
1518 aienos_cap_stop(r->admin, r->view);
1519 if (r->home_dir[0]) nftw(r->home_dir, rm_one, 16, FTW_DEPTH | FTW_PHYS);
1520}
1521
1522/* ---- COMPOSITION-2 in the living system (host phase) ----------------------
1523 * The living system's provisioned machine identity, its Aienux authority and
1524 * its durable home carry one goal at a time through rx_compose: Capability
1525 * Graph registration of digest-pinned Skills for this machine, route, two
1526 * staged J-Space candidates, AEGIS verify, World commit binder (seal), settle
1527 * (loser reclaim, durable winner, Cortex record), reopen/replay and recall.
1528 * The boundaries of the living system must hold through it: the living
1529 * World refuses composition subjects and capabilities, a revoked (stale
1530 * generation) composition capability writes nothing, and the R9 generation,
1531 * the in-force record and the promotion right are untouched.
1532 *
1533 * The composition runs inside the living World (rx_compose_attach on r->w):
1534 * its five objects are created in that World, its reactions are registered
1535 * with the credentials enrolled in start() before rx_world_bind_callers, its
1536 * Cortex store is a scoped link on the World's recorder (only its own
1537 * objects' crumbs reach it), the World keeps its external subject (the
1538 * composition's goal right is minted to it) and close leaves the World up.
1539 * Limits (stated in the receipt): the World has no reaction unregister, so a
1540 * closed composition's reactions stay registered but inert (their objects are
1541 * retired and their rights revoked); the composition subjects 200..204 are
1542 * fixed, so one composition per World. */
1543/* Test build only (Lane 32): it needs the AIEN_TEST_BUILD rogue-candidate hook
1544 * and the test fixture (rx_compose_fixture.h). */
1545#if defined(AIEN_TEST_BUILD) && !defined(R13_SILICON)
1546typedef struct {
1547 int ran, ok;
1548 uint64_t result1, result2;
1549 uint32_t alternatives, winner, reclaimed;
1550 uint64_t cx_records, cx_promotions;
1551 int recall_verified, replay_ok, identity_refused;
1552 int stale_commit_refused, stale_external_refused, rogue_refused;
1553 int living_refuses_subject, living_refuses_cap, compose_refuses_living_cap;
1554 int in_living_world, keyed_foreign_refused, world_alive_after_close;
1555 int subject_rc, stale_commit_outcome, stale_goal_rc; /* the refusals as returned */
1556 int generation_untouched, inforce_untouched, promote_holders_ok;
1557 char machine[65];
1558 char winner_digest[65];
1559} CompositionReceipt;
1560static CompositionReceipt g_comp;
1561static RxCompose g_compose; /* large: static */
1562static Fx g_cfx;
1563
1564static int intruder_fn(RxCtx *x) { (void)x; return 0; }
1565
1566/* Attach this machine's composition to the living World. */
1567static int compose_attach(Rig *r, Fx *f, RxCompose *c, const char *dir) {
1568 memset(c, 0, sizeof *c);
1569 return rx_compose_attach(c, &r->w, &r->compose_keys, dir, &f->self, FX_SESSION, &f->router,
1570 fx_contract, r->admin);
1571}
1572
1573static int composition_ok_route(const RxcResult *o) {
1574 return o->n_alternatives == 2 && o->route[0].chosen.skill_id == FX_SKILL_A &&
1575 o->route[1].chosen.skill_id == FX_SKILL_B;
1576}
1577
1578static int revoke_cap(Rig *r, RxCapRef cap) {
1579 AienosCapRef office;
1580 if (aienos_cap_office(r->admin, &office) != 0) return -1;
1581 return aienos_cap_revoke(r->admin, office, (AienosCapRef){cap.cap_id, cap.generation});
1582}
1583
1584/* Cleanup after a run inside the living World, checked before any close
1585 * (L7-LIVING): every candidate branch the run forked and did not commit is
1586 * reclaimed, no staged branch survives, and exactly one branch is live (the
1587 * superseded one is released after a commit; nothing new after a refusal). */
1588static int compose_cleanup_ok(RxCompose *c, const RxcResult *o) {
1589 JsBranchRef s = rx_compose_state(c);
1590 for (uint32_t k = 0; k < RXC_K; k++) {
1591 JsBranchRef b = o->cand_ref[k];
1592 if (!b.id && !b.gen) continue;
1593 if (b.id == s.id && b.gen == s.gen) continue;
1594 if (js_branch_check(&c->js, b) != JS_ERR_STALE) return 0;
1595 }
1596 uint32_t staged = 0;
1597 for (uint32_t i = 0; i < c->js.n_branches; i++)
1598 staged += c->js.branches[i] && c->js.branches[i]->staged;
1599 return staged == 0 && fx_live_branches(&c->js) == 1;
1600}
1601
1602#define CFAIL(...) do { fprintf(stderr, "R13 composition: "); fprintf(stderr, __VA_ARGS__); \
1603 fputc('\n', stderr); goto out; } while (0)
1604
1605static int composition_phase(Rig *r) {
1606 CompositionReceipt *g = &g_comp;
1607 RxCompose *c = &g_compose;
1608 char dir[200];
1609 int rc, is_open = 0, fx = 0;
1610 memset(g, 0, sizeof *g);
1611 g->ran = 1;
1612 hex(r->machine.id, g->machine);
1613 if (snprintf(dir, sizeof dir, "%s/compose", r->home_dir) >= (int)sizeof dir)
1614 CFAIL("home path too long");
1615
1616 /* What the living system had in force before the composition. */
1617 uint64_t gen_before = 0, lineage_before = 0, inforce_before[RX_MAX_FIELDS];
1618 rx_gen_active(r->gen, &gen_before, &lineage_before);
1619 for (uint32_t i = 0; i < RX_MAX_FIELDS; i++) inforce_before[i] = field(r, r->living.o.inforce, i);
1620
1621 /* Capability Graph: two digest-pinned Skills registered for this machine. */
1622 if (fx_init_for(&g_cfx, &r->machine) != 0) CFAIL("capability graph");
1623 fx = 1;
1624 rc = compose_attach(r, &g_cfx, c, dir);
1625 if (rc != RX_OK) CFAIL("attach (%d)", rc);
1626 is_open = 1;
1627 g->in_living_world = c->world == &r->w && !c->owns_world;
1628 if (!g->in_living_world) CFAIL("composition is not in the living World");
1629 if (r->w.external_subject != EXTERNAL) CFAIL("attach changed the external subject");
1630 if (memcmp(c->self.id, r->machine.id, 32) != 0) CFAIL("composition machine is not the living one");
1631
1632 RxcResult o;
1633 JsBranchRef s0 = rx_compose_state(c);
1634 if (fx_run(&g_cfx, c, 5, &o) != RX_OK || o.outcome != RXC_OUT_COMMITTED)
1635 CFAIL("goal 1 not committed (outcome %d)", o.outcome);
1636 if (!composition_ok_route(&o)) CFAIL("route: %u alternatives, not A then B", o.n_alternatives);
1637 if (o.winner != 0 || o.result != 16) CFAIL("winner %u result %llu", o.winner, U(o.result));
1638 if (o.old_ref.id != s0.id || o.old_ref.gen != s0.gen) CFAIL("old ref");
1639 JsBranchRef now = rx_compose_state(c);
1640 if (now.id != o.new_ref.id || now.gen != o.new_ref.gen) CFAIL("World does not name NEW");
1641 if (js_branch_check(&c->js, o.cand_ref[1]) != JS_ERR_STALE) CFAIL("loser not reclaimed");
1642 JsBranchInfo bi;
1643 if (js_branch_info(&c->js, o.new_ref, &bi) != JS_OK || bi.staged) CFAIL("winner not sealed");
1644 if (!compose_cleanup_ok(c, &o))
1645 CFAIL("cleanup after commit: branch left (live %u)", fx_live_branches(&c->js));
1646 if (!o.cx_candidate[0] || !o.cx_candidate[1] || !o.cx_evidence || !o.cx_promotion ||
1647 !o.cx_admission[1]) CFAIL("composition record incomplete");
1648 g->alternatives = o.n_alternatives;
1649 g->winner = o.winner;
1650 g->reclaimed = o.reclaimed;
1651 g->result1 = o.result;
1652 hex(o.winner_digest, g->winner_digest);
1653 JsBranchRef first = o.new_ref;
1654 uint64_t winner_claim = o.cx_candidate[0];
1655
1656 /* The boundary holds inside the shared World: a composition subject cannot
1657 * be registered without the composition's credential (unkeyed, or keyed
1658 * with the living system's keyrings). */
1659 RxReactionDesc d;
1660 memset(&d, 0, sizeof d);
1661 d.name = "compose.commit.intruder";
1662 d.faculty = RX_FACULTY_OMEGA;
1663 d.subject = RXC_SUBJ_COMMIT;
1664 d.priority = RX_PRIO_FOREGROUND;
1665 d.triggers[d.n_triggers++] = (RxDep){r->intent, RX_ALL_FIELDS};
1666 d.writes[d.n_writes++] = (RxDep){r->living.o.inforce, RX_ALL_FIELDS};
1667 d.caps[d.n_caps++] = (RxCapNeed){c->cap_commit[1], RXC_RES_STATE, RX_RIGHT_WRITE};
1668 d.fn = intruder_fn;
1669 uint32_t rid = 0;
1670 rc = rx_world_add_reaction(&r->w, &d, &rid);
1671 g->subject_rc = rc;
1672 g->living_refuses_subject = rc == RX_ERR_IDENTITY || rc == RX_ERR_AUTHORITY;
1673 if (!g->living_refuses_subject) CFAIL("living World registered a composition subject (%d)", rc);
1674 int krc = rx_world_add_reaction_keyed(&r->w, &r->keys.living, &d, &rid);
1675 int krc2 = rx_world_add_reaction_keyed(&r->w, &r->keys.omega, &d, &rid);
1676 g->keyed_foreign_refused = krc != RX_OK && krc2 != RX_OK;
1677 if (!g->keyed_foreign_refused)
1678 CFAIL("composition subject registered with living credentials (%d %d)", krc, krc2);
1679 RxMutation mi = {r->intent, 0, 1};
1680 g->living_refuses_cap = rx_world_publish_external(&r->w, c->cap_ext, &mi, 1) < 0;
1681 if (!g->living_refuses_cap) CFAIL("living World took a composition capability");
1682 RxMutation mg = {c->goal, RXC_G_INPUT, 9};
1683 g->compose_refuses_living_cap = rx_world_publish_external(c->world, r->ext_goal, &mg, 1) < 0;
1684 if (!g->compose_refuses_living_cap) CFAIL("composition goal took a living capability");
1685
1686 /* A candidate that also proposes a state write is refused; OLD kept. */
1687 c->test.rogue_candidate = 1;
1688 rc = fx_run(&g_cfx, c, 6, &o);
1689 c->test.rogue_candidate = 0;
1690 now = rx_compose_state(c);
1691 g->rogue_refused = rc == RX_OK && o.outcome == RXC_OUT_NOT_COMMITTED &&
1692 now.id == first.id && now.gen == first.gen &&
1693 compose_cleanup_ok(c, &o); /* cleanup after a refusal */
1694 if (!g->rogue_refused) CFAIL("rogue candidate (rc %d outcome %d)", rc, o.outcome);
1695
1696 /* Replay: close (the living World stays up), attach again on the same
1697 * machine, authority and World; recovery names OLD or NEW. */
1698 rx_compose_close(c);
1699 is_open = 0;
1700 if ((rc = compose_attach(r, &g_cfx, c, dir)) != RX_OK) CFAIL("reattach (%d)", rc);
1701 is_open = 1;
1702 now = rx_compose_state(c);
1703 if (now.id != first.id || now.gen != first.gen) CFAIL("reopen does not name the winner");
1704 if (cx_verify_chain(&c->cx) != CX_OK) CFAIL("Cortex chain");
1705 CxFilter cf = {CX_CLAIM, CX_K_CANDIDATE, 0, 1};
1706 CxRecord rec[16];
1707 uint32_t nr = cx_recall(&c->cx, RXC_CX_SUBJECT(RXC_SLOT_STATE), 0, UINT64_MAX, &cf, rec, 16);
1708 for (uint32_t i = 0; i < nr; i++)
1709 if (rec[i].hdr.id == winner_claim && rec[i].verified &&
1710 rec[i].payload[RXC_CP_REF] == fx_pack(first)) g->recall_verified = 1;
1711 if (!g->recall_verified) CFAIL("recall did not find the verified winner claim (%u)", nr);
1712 if (fx_run(&g_cfx, c, 7, &o) != RX_OK || o.outcome != RXC_OUT_COMMITTED || o.result != 22 ||
1713 o.old_ref.id != first.id || o.old_ref.gen != first.gen)
1714 CFAIL("goal after replay (outcome %d result %llu)", o.outcome, U(o.result));
1715 g->replay_ok = 1;
1716 g->result2 = o.result;
1717 JsBranchRef second = o.new_ref;
1718
1719 /* Stale generation: the commit step's state-write right is revoked; the
1720 * next goal's winner cannot be written and nothing changes. */
1721 if (revoke_cap(r, c->cap_commit[1]) != 0) CFAIL("revoke commit right");
1722 rc = fx_run(&g_cfx, c, 8, &o);
1723 now = rx_compose_state(c);
1724 g->stale_commit_outcome = rc == RX_OK ? o.outcome : rc;
1725 g->stale_commit_refused = rc == RX_OK && o.outcome != RXC_OUT_COMMITTED &&
1726 now.id == second.id && now.gen == second.gen &&
1727 compose_cleanup_ok(c, &o); /* cleanup after a refusal */
1728 if (!g->stale_commit_refused) CFAIL("revoked commit right still wrote (rc %d outcome %d)", rc,
1729 o.outcome);
1730 /* Outside input under a revoked capability is refused at the World. */
1731 if (revoke_cap(r, c->cap_ext) != 0) CFAIL("revoke goal right");
1732 rc = fx_run(&g_cfx, c, 9, &o);
1733 now = rx_compose_state(c);
1734 g->stale_goal_rc = rc;
1735 g->stale_external_refused = rc < 0 && now.id == second.id && now.gen == second.gen;
1736 if (!g->stale_external_refused) CFAIL("revoked goal right accepted (rc %d)", rc);
1737 g->cx_records = c->cx.n;
1738 g->cx_promotions = fx_count(&c->cx, CX_K_PROMOTION, UINT64_MAX);
1739 if (g->cx_promotions != 2) CFAIL("promotions %llu, want 2", U(g->cx_promotions));
1740 rx_compose_close(c);
1741 is_open = 0;
1742 /* Close left the living World up: its objects still read. */
1743 g->world_alive_after_close = field(r, r->living.o.inforce, 0) != UINT64_MAX &&
1744 field(r, r->intent, 0) != UINT64_MAX;
1745 if (!g->world_alive_after_close) CFAIL("living World objects gone after close");
1746
1747 /* Another machine cannot open this machine's composition. */
1748 AienMachineId other = fx_mid(2);
1749 Fx foreign;
1750 if (fx_init_for(&foreign, &other) != 0) CFAIL("foreign graph");
1751 rc = compose_attach(r, &foreign, c, dir);
1752 g->identity_refused = rc == RX_ERR_IDENTITY;
1753 if (rc == RX_OK) rx_compose_close(c);
1754 fx_free(&foreign);
1755 if (!g->identity_refused) CFAIL("foreign machine opened the composition (%d)", rc);
1756
1757 /* The living system's generation management is untouched. */
1758 uint64_t gen_after = 0, lineage_after = 0;
1759 rx_gen_active(r->gen, &gen_after, &lineage_after);
1760 g->generation_untouched = gen_after == gen_before && lineage_after == lineage_before;
1761 g->inforce_untouched = 1;
1762 for (uint32_t i = 0; i < RX_MAX_FIELDS; i++)
1763 if (field(r, r->living.o.inforce, i) != inforce_before[i]) g->inforce_untouched = 0;
1764 uint64_t swept = 0, holders = 0;
1765 g->promote_holders_ok = authority_sweep(r, &swept, &holders) == 0 && holders == 1;
1766 if (!g->generation_untouched || !g->inforce_untouched || !g->promote_holders_ok)
1767 CFAIL("living generation %d in force %d promotion right %d", g->generation_untouched,
1768 g->inforce_untouched, g->promote_holders_ok);
1769 /* No composition subject holds a privileged right. */
1770 AienosCapRef office;
1771 if (aienos_cap_office(r->admin, &office) != 0) CFAIL("office");
1772 for (uint32_t id = 1; id < 1024; id++)
1773 for (uint64_t gn = office.generation; gn < office.generation + 8; gn++) {
1774 AienosCapEntry e;
1775 if (aienos_cap_inspect(r->view, (AienosCapRef){id, gn}, &e) != 0 || e.state != 1u)
1776 continue;
1777 if (e.subject >= RXC_SUBJ_EXTERNAL && e.subject < RXC_SUBJ_OF(RXC_MAX_ACTIVE, RXC_SUBJ_EXTERNAL) &&
1778 (e.rights & RX_RIGHT_PRIVILEGED))
1779 CFAIL("composition subject %u holds a privileged right", e.subject);
1780 }
1781 g->ok = 1;
1782out:
1783 if (is_open) rx_compose_close(c);
1784 if (fx) fx_free(&g_cfx);
1785 printf("R13 composition (host, inside the living World): %s; machine %.16s..., "
1786 "goal 5 -> %llu (winner %u of %u, reclaimed %u), replay -> %llu, recall %s, "
1787 "Cortex %llu records %llu promotions; refusals: living subject %d, living cap %d, "
1788 "cross cap %d, keyed living credential %d, rogue %d, stale commit %d, stale goal %d, foreign machine %d; "
1789 "living generation %d in force %d promotion right %d; codes: subject rc %d, "
1790 "revoked commit outcome %d, revoked goal rc %d\n",
1791 g->ok ? "PASS" : "FAIL", g->machine, U(g->result1), g->winner, g->alternatives,
1792 g->reclaimed, U(g->result2), g->recall_verified ? "verified" : "missing",
1793 U(g->cx_records), U(g->cx_promotions), g->living_refuses_subject,
1794 g->living_refuses_cap, g->compose_refuses_living_cap, g->keyed_foreign_refused,
1795 g->rogue_refused,
1796 g->stale_commit_refused, g->stale_external_refused, g->identity_refused,
1797 g->generation_untouched, g->inforce_untouched, g->promote_holders_ok, g->subject_rc,
1798 g->stale_commit_outcome, g->stale_goal_rc);
1799 return g->ok ? 0 : -1;
1800}
1801
1802#endif /* AIEN_TEST_BUILD && !R13_SILICON (composition phase) */
1803
1804#ifdef AIEN_TEST_BUILD
1805/* Fabric F5-0 in the living World (Lane 13; host and silicon TEST builds since
1806 * Lane 17; test build only since Lane 32: loopback, HMAC stand-in and fixed
1807 * test keys never enter the production program). A second simulated
1808 * machine joins over the loopback transport and advertises a Skill; the
1809 * composition attached to this World finds it in the Capability Graph as a
1810 * CQ_SRC_FABRIC candidate, runs it through the Fabric dispatcher (an
1811 * in-process stand-in: F5-0 has no work message) and commits it; then the
1812 * machine leaves, is lost and rejoins, and forged, stale and wrong-machine
1813 * traffic is refused (fab_living_phase.h has the steps). The living
1814 * generation, the in-force record and the single promotion holder must be
1815 * untouched. On the host it runs after composition_phase, on a fresh
1816 * composition directory, after the first composition closed (up to
1817 * RXC_MAX_ACTIVE run at once, each isolated). In the silicon build (Lane 17) it runs in the World whose GPU
1818 * work goes to the physical resident GB10 seat; the Fabric part stays CPU-only
1819 * loopback (no network, HMAC stand-in) and its Skills are CPU procedures. */
1820#ifdef R13_SILICON
1821#define FL_BUILD "silicon"
1822#else
1823#define FL_BUILD "host"
1824#endif
1825static FlReceipt g_fab;
1826
1827static int fabric_attach(void *ctx, RxCompose *c, const char *dir, const AienMachineId *self,
1828 const SrRouter *router) {
1829 Rig *r = ctx;
1830 memset(c, 0, sizeof *c);
1831 return rx_compose_attach(c, &r->w, &r->compose_keys, dir, self, FX_SESSION, router,
1832 fx_contract, r->admin);
1833}
1834
1835static void fabric_close(void *ctx, RxCompose *c) { (void)ctx; rx_compose_close(c); }
1836
1837static int fabric_phase(Rig *r) {
1838 char dir[200];
1839 if (snprintf(dir, sizeof dir, "%s/compose-fabric", r->home_dir) >= (int)sizeof dir) {
1840 fprintf(stderr, "R13 Fabric: home path too long\n");
1841 return -1;
1842 }
1843 uint64_t gen_before = 0, lineage_before = 0, inforce_before[RX_MAX_FIELDS];
1844 rx_gen_active(r->gen, &gen_before, &lineage_before);
1845 for (uint32_t i = 0; i < RX_MAX_FIELDS; i++) inforce_before[i] = field(r, r->living.o.inforce, i);
1846 int rc = fl_run(&r->machine, dir, fabric_attach, fabric_close, r, &g_fab);
1847 uint64_t gen_after = 0, lineage_after = 0;
1848 rx_gen_active(r->gen, &gen_after, &lineage_after);
1849 int untouched = gen_after == gen_before && lineage_after == lineage_before &&
1850 r->w.external_subject == EXTERNAL;
1851 for (uint32_t i = 0; i < RX_MAX_FIELDS; i++)
1852 if (field(r, r->living.o.inforce, i) != inforce_before[i]) untouched = 0;
1853 uint64_t swept = 0, holders = 0;
1854 if (authority_sweep(r, &swept, &holders) != 0 || holders != 1) untouched = 0;
1855 g_fab.ok = rc == 0 && untouched;
1856 printf("R13 Fabric (" FL_BUILD ", second machine in the living World): %s; %u checks, %u failed; "
1857 "remote wins %u, dispatched %llu, dispatcher refusals route %llu digest %llu; "
1858 "living untouched %d\n",
1859 g_fab.ok ? "PASS" : "FAIL", g_fab.checks, g_fab.failures, g_fab.remote_wins,
1860 U(g_fab.dispatched), U(g_fab.dispatch_refused[FAB_DX_ROUTE]),
1861 U(g_fab.dispatch_refused[FAB_DX_DIGEST]), untouched);
1862 return g_fab.ok ? 0 : -1;
1863}
1864
1865static void fabric_json(char *out, size_t n) {
1866 const FlReceipt *g = &g_fab;
1867 if (!g->ran) {
1868 snprintf(out, n, " \"fabric_host_phase\": {\"result\": \"NOT_RUN\", \"build\": \"" FL_BUILD "\"},\n");
1869 return;
1870 }
1871 char rec[65], fab[65];
1872 fx_hex(g->record_digest, 32, rec);
1873 fx_hex(g->fabric_digest, 32, fab);
1874 snprintf(out, n,
1875 " \"fabric_host_phase\": {\"result\": \"%s\", \"build\": \"" FL_BUILD "\", \"checks\": %u, \"failures\": %u, "
1876 "\"transport\": \"F5-0 loopback (in-process)\", \"auth\": \"HMAC stand-in\", "
1877 "\"remote_execution\": \"in-process stand-in (fab_dispatch); no work message in F5-0\", "
1878 "\"remote_wins\": %u, \"dispatched\": %llu, \"results\": [%llu, %llu, %llu, %llu, %llu, %llu], "
1879 "\"winners\": [%u, %u, %u, %u, %u, %u], \"refused\": {\"forged_wrong_key\": \"%s\", "
1880 "\"forged_altered_byte\": \"%s\", \"relayed_other_machine_record\": \"%s\", "
1881 "\"misdelivered\": \"%s\", \"stale_generation_replay\": \"%s\", "
1882 "\"advertise_after_lease\": \"%s\", \"pinned_unknown_machine\": %d, "
1883 "\"remote_only_after_loss\": %d, \"dispatch_route\": %llu, \"dispatch_digest\": %llu}, "
1884 "\"fabric_candidates_held\": %d, \"record_digest\": \"%s\", \"fabric_digest\": \"%s\"},\n",
1885 g->ok ? "PASS" : "FAIL", g->checks, g->failures, g->remote_wins, U(g->dispatched),
1886 U(g->result[0]), U(g->result[1]), U(g->result[2]), U(g->result[3]), U(g->result[4]),
1887 U(g->result[5]), g->winner[0], g->winner[1], g->winner[2], g->winner[3], g->winner[4],
1888 g->winner[5], fab_strerror(g->forged_wrong_key), fab_strerror(g->forged_altered),
1889 fab_strerror(g->relayed_record), fab_strerror(g->misdelivered),
1890 fab_strerror(g->stale_gen), fab_strerror(g->lease_expired), g->pinned_wrong_machine,
1891 g->remote_only_after_loss, U(g->dispatch_refused[FAB_DX_ROUTE]),
1892 U(g->dispatch_refused[FAB_DX_DIGEST]), g->fabric_held, rec, fab);
1893}
1894/* end Fabric phase */
1895#else /* production program: no Fabric (no real transport before TRUST-1) */
1896#ifdef R13_SILICON
1897#define FL_BUILD "silicon"
1898#else
1899#define FL_BUILD "host"
1900#endif
1901static void fabric_json(char *out, size_t n) {
1902 snprintf(out, n, " \"fabric_host_phase\": {\"result\": \"NOT_RUN\", \"build\": \"" FL_BUILD "\", "
1903 "\"reason\": \"production program: Fabric F5-0 has only the loopback transport and "
1904 "HMAC stand-in (test build only, AIEN_TEST_BUILD); no real transport before TRUST-1\"},\n");
1905}
1906#endif /* AIEN_TEST_BUILD (Fabric phase) */
1907
1908static void binary_digest(char out[65]) {
1909 strcpy(out, "unavailable");
1910 FILE *f = fopen("/proc/self/exe", "rb");
1911 if (!f) return;
1912 sha256_ctx c;
1913 sha256_init(&c);
1914 uint8_t block[65536], digest[32];
1915 size_t n;
1916 while ((n = fread(block, 1, sizeof block, f)) > 0)
1917 sha256_update(&c, block, n);
1918 fclose(f);
1919 sha256_final(&c, digest);
1920 hex(digest, out);
1921}
1922
1923#define OBJ(o) (o).id, (o).generation
1924/* The composition phase in the receipt (host TEST build only: it needs the
1925 * AIEN_TEST_BUILD rogue-candidate hook and the test fixture), then the Fabric
1926 * phase (test builds only). */
1927static void composition_json(char *out, size_t n) {
1928#if defined(AIEN_TEST_BUILD) && !defined(R13_SILICON)
1929 const CompositionReceipt *c = &g_comp;
1930 if (c->ran) {
1931 snprintf(out, n,
1932 " \"composition_host_phase\": {\"result\": \"%s\", \"machine_id\": \"%s\", "
1933 "\"world\": \"the living RxWorld (rx_compose_attach)\", \"in_living_world\": %s, "
1934 "\"world_alive_after_close\": %s, "
1935 "\"authority\": \"living AIENOS admin\", \"alternatives\": %u, \"winner\": %u, "
1936 "\"goal_5_result\": %llu, \"after_replay_goal_7_result\": %llu, "
1937 "\"winner_digest\": \"%s\", \"cortex_records\": %llu, \"promotions\": %llu, "
1938 "\"recall_verified\": %s, \"refused\": {\"composition_subject_in_living_world\": %s, "
1939 "\"composition_subject_with_living_credential\": %s, "
1940 "\"composition_cap_in_living_world\": %s, \"living_cap_in_composition\": %s, "
1941 "\"rogue_candidate_state_write\": %s, \"revoked_commit_right\": %s, "
1942 "\"revoked_goal_right\": %s, \"foreign_machine\": %s}, "
1943 "\"living_generation_untouched\": %s, \"in_force_untouched\": %s, "
1944 "\"single_promotion_holder\": %s},\n",
1945 c->ok ? "PASS" : "FAIL", c->machine, c->in_living_world ? "true" : "false",
1946 c->world_alive_after_close ? "true" : "false", c->alternatives, c->winner, U(c->result1),
1947 U(c->result2), c->winner_digest, U(c->cx_records), U(c->cx_promotions),
1948 c->recall_verified ? "true" : "false",
1949 c->living_refuses_subject ? "true" : "false", c->keyed_foreign_refused ? "true" : "false",
1950 c->living_refuses_cap ? "true" : "false",
1951 c->compose_refuses_living_cap ? "true" : "false", c->rogue_refused ? "true" : "false",
1952 c->stale_commit_refused ? "true" : "false", c->stale_external_refused ? "true" : "false",
1953 c->identity_refused ? "true" : "false", c->generation_untouched ? "true" : "false",
1954 c->inforce_untouched ? "true" : "false", c->promote_holders_ok ? "true" : "false");
1955 } else {
1956 snprintf(out, n, " \"composition_host_phase\": {\"result\": \"NOT_RUN\", "
1957 "\"reason\": \"phase did not run (an earlier step failed)\"},\n");
1958 }
1959#elif defined(AIEN_TEST_BUILD)
1960 snprintf(out, n, " \"composition_host_phase\": {\"result\": \"NOT_RUN\", \"reason\": "
1961 "\"silicon test build: the composition phase runs in the host test build only\"},\n");
1962#else
1963 snprintf(out, n, " \"composition_host_phase\": {\"result\": \"NOT_RUN\", \"reason\": "
1964 "\"production program: the composition phase needs the AIEN_TEST_BUILD rogue-candidate "
1965 "hook and test fixture (test-r13-testbuild-host)\"},\n");
1966#endif
1967 /* Then the Fabric phase (NOT_RUN with its reason in the production program). */
1968 size_t used = strlen(out);
1969 if (used < n) fabric_json(out + used, n - used);
1970}
1971
1972/* Which program this is (Lane 32). The test build has its own receipt and
1973 * gate key, so it can never stand in for the production R13 gate. */
1974#ifdef AIEN_TEST_BUILD
1975#define R13_RECEIPT "R13/rx_living_test_build_receipt.json"
1976#define R13_GATE_KEY "R13_LIVING_SYSTEM_TEST_BUILD"
1977#define R13_BUILD "test (AIEN_TEST_BUILD)"
1978static int g_argus_ok = 1; /* ARGUS is not linked into the test build */
1979static char g_argus_json[512] =
1980 " \"argus\": {\"result\": \"NOT_RUN\", \"reason\": \"test build: ARGUS is linked into "
1981 "the production program only\"},\n";
1982#else
1983#define R13_RECEIPT "R13/rx_living_receipt.json"
1984#define R13_GATE_KEY "R13_LIVING_SYSTEM"
1985#define R13_BUILD "production"
1986static int g_argus_ok;
1987static char g_argus_json[1024] =
1988 " \"argus\": {\"result\": \"FAIL\", \"reason\": \"ARGUS was not checked\"},\n";
1989
1990/* ARGUS in the production program (ARGUS-1 decisions, 2026-09-29): observe and
1991 * record only. ARGUS (pinned by argus.lock) receives the runtime's capability
1992 * events and the authority's own mint/revoke announcements, runs its
1993 * detectors and keeps findings. It holds no capability, takes no action and
1994 * never blocks a request, so it cannot expand its own authority; the one
1995 * narrow automatic revoke the decisions allow is not in the pinned ARGUS.
1996 * The program refuses to run unobserved: ARGUS must be active with its
1997 * consumer ingesting (RX_ARGUS_AUTO=0 or RX_ARGUS_CONSUMER=off/discard make
1998 * the gate FAIL). */
1999static int argus_check_start(void) {
2000 RxArgusStats s;
2001 rx_argus_stats(&s);
2002 if (rx_argus_active() && s.consumer_mode == RX_ARGUS_CONSUMER_INGEST) return 0;
2003 snprintf(g_argus_json, sizeof g_argus_json,
2004 " \"argus\": {\"result\": \"FAIL\", \"reason\": \"ARGUS not observing at start "
2005 "(active %d, consumer mode %d; production needs ingest)\"},\n",
2006 rx_argus_active(), s.consumer_mode);
2007 fprintf(stderr, "R13 ARGUS: not observing at start (active %d, consumer mode %d); "
2008 "the production program refuses to run unobserved\n", rx_argus_active(), s.consumer_mode);
2009 return -1;
2010}
2011
2012/* After every World is stopped (producers quiescent): drain, stop the
2013 * consumer, record what ARGUS saw. Findings are recorded, never acted on. */
2014static void argus_finish(void) {
2015 RxArgusStats s;
2016 rx_argus_stats(&s);
2017 int mode = s.consumer_mode;
2018 rx_argus_shutdown();
2019 rx_argus_stats(&s);
2020 uint64_t obs = 0;
2021 for (unsigned k = 0; k < 9; k++) obs += s.authority_obs[k];
2022 g_argus_ok = mode == RX_ARGUS_CONSUMER_INGEST && s.received > 0 && obs > 0 &&
2023 s.ingest_errors == 0;
2024 snprintf(g_argus_json, sizeof g_argus_json,
2025 " \"argus\": {\"result\": \"%s\", \"mode\": \"observe and record (RX_ARGUS=2, "
2026 "authority observer, consumer ingest); no response action, holds no capability\", "
2027 "\"argus_lock\": \"argus.lock\", \"emitted\": %llu, \"received\": %llu, "
2028 "\"authority_observations\": %llu, \"authority_mints\": %llu, "
2029 "\"authority_revokes\": %llu, \"findings\": %llu, \"ingest_errors\": %llu, "
2030 "\"ring_refused\": %llu},\n",
2031 g_argus_ok ? "OBSERVED" : "FAIL", U(s.emitted), U(s.received), U(obs),
2032 U(s.authority_obs[AIENOS_CAP_OBS_MINT]), U(s.authority_obs[AIENOS_CAP_OBS_REVOKE]),
2033 U(s.findings_total), U(s.ingest_errors), U(s.ring_refused));
2034 printf("R13 ARGUS: %s; observe and record, received %llu events, %llu authority "
2035 "observations, %llu findings, %llu ingest errors\n",
2036 g_argus_ok ? "observing" : "FAIL", U(s.received), U(obs), U(s.findings_total),
2037 U(s.ingest_errors));
2038 const char *p = getenv("RX_ARGUS_SUMMARY");
2039 if (p) rx_argus_write_summary(p, getenv("RX_ARGUS_SUITE") ? getenv("RX_ARGUS_SUITE") : "r13");
2040}
2041
2042/* `--argus-probe`: the host-run check that ARGUS is present and observing in
2043 * THIS binary (test-prod-hygiene; CI cannot run the living episode, which
2044 * needs both Spark core classes). It starts one authority through the same
2045 * link-wrapped aienos_cap_start the living run uses, makes one observed
2046 * authority call, stops it and requires ARGUS to have received the events.
2047 * It runs no living episode and writes no receipt. */
2048static int argus_probe(void) {
2049 if (argus_check_start() != 0) return 1;
2050 AienosCapAdmin *admin = NULL;
2051 AienosCapView *view = NULL;
2052 AienosCapRef office;
2053 if (aienos_cap_start(&admin, &view) != 0 || aienos_cap_office(admin, &office) != 0 ||
2054 aienos_cap_advance_clock(admin, office, 1) != 0) {
2055 fprintf(stderr, "R13 ARGUS probe: authority start failed\n");
2056 return 1;
2057 }
2058 aienos_cap_stop(admin, view);
2059 argus_finish();
2060 printf("R13 ARGUS probe: ARGUS_OBSERVING=%s\n", g_argus_ok ? "PASS" : "FAIL");
2061 return g_argus_ok ? 0 : 1;
2062}
2063#endif
2064
2065static void receipt(int tests_ok) {
2066 char path[512], commit[41] = {0}, binary[65], physics[80] = {0};
2067 if (omega_evidence_path(R13_RECEIPT, path, sizeof path) != 0)
2068 return;
2069 if (!omega_evidence_run_commit(commit)) strcpy(commit, "unknown");
2070 if (!omega_evidence_physics_commit(physics, sizeof physics))
2071 strcpy(physics, "unknown");
2072 binary_digest(binary);
2073 const char *candidate = getenv("OMEGA_CANDIDATE_COMMIT");
2074 const char *aienos = getenv("AIENOS_COMMIT");
2075 int dirty = omega_evidence_tree_dirty();
2076 int bound = candidate && candidate[0] && strcmp(candidate, commit) == 0 && !dirty;
2077 int controls = 1;
2078 for (uint32_t i = 0; i < 5; i++) controls &= g_controls[i];
2079 const Receipt *g = &g_receipt;
2080 int pass = tests_ok && controls && g_argus_ok && bound && g->silicon_observed;
2081 const char *gate = pass ? "PASS"
2082 : !tests_ok || !controls || !g_argus_ok ? "FAIL"
2083 : !g->silicon_observed ? "HOST_PASS_NON_SILICON"
2084 : "SILICON_PASS_UNBOUND";
2085 /* The first failure message as a JSON string, or null when there was none. */
2086 char first_failure[1100];
2087 if (!g_first_failure[0]) strcpy(first_failure, "null");
2088 else {
2089 size_t k = 0;
2090 first_failure[k++] = '"';
2091 for (const char *s = g_first_failure; *s && k + 8 < sizeof first_failure; s++) {
2092 unsigned char c = (unsigned char)*s;
2093 if (c == '"' || c == '\\') { first_failure[k++] = '\\'; first_failure[k++] = (char)c; }
2094 else if (c < 0x20 || c >= 0x7f) k += (size_t)snprintf(first_failure + k, 7, "\\u%04x", c);
2095 else first_failure[k++] = (char)c;
2096 }
2097 first_failure[k++] = '"';
2098 first_failure[k] = 0;
2099 }
2100 struct utsname host;
2101 memset(&host, 0, sizeof host);
2102 uname(&host);
2103 char comp[6144];
2104 composition_json(comp, sizeof comp);
2105 size_t used = strlen(comp);
2106 if (used < sizeof comp)
2107 snprintf(comp + used, sizeof comp - used, " \"build\": \"" R13_BUILD "\",\n%s", g_argus_json);
2108 used = strlen(comp);
2109 if (used < sizeof comp)
2110 snprintf(comp + used, sizeof comp - used,
2111 " \"operator\": {\"entry_point\": \"owner-only unix socket, SO_PEERCRED, runtime-issued "
2112 "caller credential plus RX_WORLD_RES_CONTROL halt capability "
2113 "(docs/r16-operator-control.md)\", \"subject\": %u, \"stops\": %llu, "
2114 "\"resumes\": %llu, \"restored_stops\": %llu, \"open_stops\": %llu, "
2115 "\"activations_cancelled_under_stop\": %llu},\n",
2116 (unsigned)RX_OPERATOR_SUBJ, U(g_op_stops), U(g_op_resumes), U(g_op_restored),
2117 U(g_op_open), U(g_op_cancelled));
2118 FILE *f = omega_evidence_create(path);
2119 if (!f) return;
2120 fprintf(f,
2121 "{\n"
2122 " \"schema\": \"AIEN_RX_R13_LIVING_SYSTEM_V1\",\n"
2123 " \"run_id\": \"%s\",\n"
2124 " \"candidate_commit\": \"%s\",\n"
2125 " \"run_commit\": \"%s\",\n"
2126 " \"candidate_bound\": %s,\n"
2127 " \"tree_dirty\": %s,\n"
2128 " \"aienos_commit\": \"%s\",\n"
2129 " \"physics_forge_commit\": \"%s\",\n"
2130 " \"test_binary_sha256\": \"%s\",\n"
2131 " \"machine_identity\": {\"node\": \"%s\", \"system\": \"%s\", "
2132 "\"release\": \"%s\", \"architecture\": \"%s\"},\n"
2133 " \"silicon_observed\": %s,\n"
2134 " \"gate\": {\"" R13_GATE_KEY "\": \"%s\"},\n"
2135 " \"first_failure\": %s,\n"
2136 " \"scenario\": {\"operation\": \"omega integer matvec 64x256\", "
2137 "\"goal\": \"cost below %u%% of the confirmed incumbent, semantics preserved\", "
2138 "\"incumbent_ns\": %llu, \"target_ns\": %llu, "
2139 "\"selected_ps_per_call\": %llu, \"reference_ps_per_call_new_cores\": %llu, "
2140 "\"aien_final_expected_ns\": %llu, \"aien_final_goal_status\": \"%s\", "
2141 "\"aien_final_prediction_epoch\": %llu},\n"
2142 " \"active_generation_before\": %llu,\n"
2143 " \"active_generation_after\": %llu,\n"
2144 " \"recovered_generation\": %llu,\n"
2145 " \"objects\": {\n"
2146 " \"human_goal\": {\"id\": %u, \"generation\": %u},\n"
2147 " \"aien_plan\": {\"id\": %u, \"generation\": %u},\n"
2148 " \"omega_search\": {\"id\": %u, \"generation\": %u},\n"
2149 " \"gpu_input\": {\"id\": %u, \"generation\": %u},\n"
2150 " \"gpu_output\": {\"id\": %u, \"generation\": %u},\n"
2151 " \"experiment_evidence\": {\"id\": %u, \"generation\": %u},\n"
2152 " \"aien_experiment_belief\": {\"id\": %u, \"generation\": %u},\n"
2153 " \"omega_selection\": {\"id\": %u, \"generation\": %u},\n"
2154 " \"generation_candidate\": {\"id\": %u, \"generation\": %u},\n"
2155 " \"promotion\": {\"id\": %u, \"generation\": %u},\n"
2156 " \"in_force\": {\"id\": %u, \"generation\": %u}\n"
2157 " },\n"
2158 " \"selected_realization_identity\": \"%s\",\n"
2159 " \"promoted_realization_identity\": \"%s\",\n"
2160 " \"rebuilt_from_durable_bytes_identity\": \"%s\",\n"
2161 " \"promoted_realization_bytes_sha256\": \"%s\",\n"
2162 " \"aien_activations\": %llu,\n"
2163 " \"omega_activations\": %llu,\n"
2164 " \"experiment_seat_activations_on_existing_grant\": %llu,\n"
2165 " \"aegis_decide_activations_during_episode\": %llu,\n"
2166 " \"root_install_activations_during_episode\": %llu,\n"
2167 " \"generation_prepare_activations\": %llu,\n"
2168 " \"promotion_authority_activations\": %llu,\n"
2169 " \"gpu_claims\": %llu,\n"
2170 " \"gpu_completions\": %llu,\n"
2171 " \"gpu_publication_worker\": \"0x%llx\",\n"
2172 " \"production_commits_during_aien\": %llu,\n"
2173 " \"production_commits_while_an_aien_activation_executed\": %llu,\n"
2174 " \"production_commits_during_omega\": %llu,\n"
2175 " \"production_commits_during_gpu_experiment\": %llu,\n"
2176 " \"production_commits_before_promotion\": %llu,\n"
2177 " \"production_commits_during_promotion_barrier\": %llu,\n"
2178 " \"production_commits_after_promotion\": %llu,\n"
2179 " \"production_results_using_unpromoted_realization\": %llu,\n"
2180 " \"outside_publications_after_goal_all_production_requests\": %llu,\n"
2181 " \"generation_promotion_barrier_ns\": %llu,\n"
2182 " \"generation_candidate_to_promotion_ns\": %llu,\n"
2183 " \"causal_crumb_count\": %llu,\n"
2184 " \"durable_provenance_links_verified\": %llu,\n"
2185 " \"causal_verification_result\": \"%s\",\n"
2186 " \"authority\": {\"live_capabilities_swept\": %llu, "
2187 "\"promotion_right_holders\": %llu, \"promotion_subject\": %u},\n"
2188 " \"controls\": {\"A_no_aien\": \"%s\", "
2189 "\"B_no_promotion_authority\": \"%s\", "
2190 "\"C_revoked_experiment\": \"%s\", "
2191 "\"D_stale_generation\": \"%s\", "
2192 "\"E_failed_verification\": \"%s\"},\n"
2193 "%s"
2194 " \"not_claimed\": [\"R14\", \"R15\", \"R16\", "
2195 "\"neural/general cognition beyond R11\", "
2196 "\"open-ended realization invention beyond R10\", "
2197 "\"AIENOS-kernel isolation (authority is the host-library C port)\", "
2198 "\"the GPU add measures matvec cost (it is a physical witness of the experiment)\"]\n"
2199 "}\n",
2200 omega_evidence_run_id(), candidate ? candidate : "unknown", commit,
2201 bound ? "true" : "false", dirty ? "true" : "false",
2202 aienos ? aienos : "unknown", physics, binary,
2203 host.nodename, host.sysname, host.release, host.machine,
2204 g->silicon_observed ? "true" : "false", gate,
2205 first_failure,
2206 TARGET_PCT, U(g->incumbent_ns), U(g->target_ns), U(g->selected_ps), U(g->reference_ps),
2207 U(g->final_expected_ns), g->final_status == RX_AIEN_GOAL_MET ? "MET" : "NOT_MET",
2208 U(g->final_prediction_epoch),
2209 U(g->before), U(g->after), U(g->recovered),
2210 OBJ(g->goal), OBJ(g->plan), OBJ(g->search), OBJ(g->gpu_input), OBJ(g->gpu_output),
2211 OBJ(g->evidence), OBJ(g->belief), OBJ(g->selection), OBJ(g->candidate),
2212 OBJ(g->promotion), OBJ(g->inforce),
2213 g->selected_identity, g->promoted_identity, g->rebuilt_identity,
2214 g->realization_sha256,
2215 U(g->aien_acts), U(g->omega_acts), U(g->seat_acts), U(g->aegis_decide_acts),
2216 U(g->root_install_acts), U(g->prepare_acts), U(g->promote_acts),
2217 U(g->gpu_claims), U(g->gpu_completions), U(g->gpu_worker),
2218 U(g->production_aien), U(g->aien_overlap), U(g->production_omega), U(g->production_gpu),
2219 U(g->production_before_promotion), U(g->production_during_promotion),
2220 U(g->production_after_promotion),
2221 U(g->unpromoted_use), U(g->externals_after_goal),
2222 U(g->promotion_barrier_ns), U(g->promotion_latency_ns),
2223 U(g->crumbs), U(g->links_verified), g->causal_verified ? "PASS" : "FAIL",
2224 U(g->caps_swept), U(g->promote_holders), (unsigned)RX_LIVING_PROMOTE_SUBJ,
2225 g_controls[0] ? "PASS" : "FAIL", g_controls[1] ? "PASS" : "FAIL",
2226 g_controls[2] ? "PASS" : "FAIL", g_controls[3] ? "PASS" : "FAIL",
2227 g_controls[4] ? "PASS" : "FAIL", comp);
2228 fclose(f);
2229 printf("R13 gate: " R13_GATE_KEY "=%s\nR13 receipt: %s\n", gate, path);
2230}
2231
2232/* omega #527: why a mode failed, on STDOUT (the judge keeps stdout in its receipt) as well as stderr.
2233 * The counts line alone said "GPU 0" without saying why no GPU experiment ran. These lines name the
2234 * state AIEN, Omega and the seat transport were in when the mode gave up. They only read the world. */
2235static const char *pred_state_name(uint64_t s) {
2236 return s == RX_AIEN_PRED_HOLDING ? "holding" : s == RX_AIEN_PRED_CONFIRMED ? "confirmed" :
2237 s == RX_AIEN_PRED_FAILED ? "failed" : s == 0 ? "none" : "?";
2238}
2239static const char *hyp_state_name(uint64_t s) {
2240 return s == RX_AIEN_HYP_OPEN ? "open" : s == RX_AIEN_HYP_TESTING ? "testing (a plan is out)" :
2241 s == RX_AIEN_HYP_SUPPORTED ? "supported" : s == RX_AIEN_HYP_UNSUPPORTED ? "unsupported" :
2242 s == RX_AIEN_HYP_EXHAUSTED ? "exhausted" : s == 0 ? "none" : "?";
2243}
2244static const char *why_name(uint64_t w) {
2245 return w == RX_AIEN_WHY_CORE_CLASS ? "core class" : w == RX_AIEN_WHY_DRIFT ? "drift" :
2246 w == RX_AIEN_WHY_GOAL ? "goal" : w == 0 ? "none" : "?";
2247}
2248static void both(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
2249static void both(const char *fmt, ...) {
2250 char line[768];
2251 va_list ap;
2252 va_start(ap, fmt);
2253 vsnprintf(line, sizeof line, fmt, ap);
2254 va_end(ap);
2255 fprintf(stderr, "%s\n", line);
2256 printf("%s\n", line);
2257}
2258static void explain_failure(Rig *r, const char *name) {
2259 if (g_first_failure[0]) printf("R13 first failure: %s\n", g_first_failure);
2260 both("R13 %s FAILED: plan %llu search %llu GPU %llu evidence %llu "
2261 "belief %llu selection %llu candidate %llu promotion %llu in force %llu "
2262 "result %d prepare refusal %d", name,
2263 U(field(r, r->aien.o.plan, 0)), U(field(r, r->omega.o.search, 0)),
2264 U(field(r, r->living.o.output, 0)), U(field(r, r->living.o.evidence, 0)),
2265 U(field(r, r->aien.o.experiment_belief, 0)),
2266 U(field(r, r->omega.o.selection, 0)), U(field(r, r->living.o.candidate, 0)),
2267 U(field(r, r->living.o.promotion, 0)), U(field(r, r->living.o.inforce, 0)),
2268 r->promoter.result, r->living.last_refusal);
2269 if (!r->ready) return; /* setup failed: the objects below may not exist */
2270 both("R13 %s AIEN: prediction %llu %s on record %llu, hits %llu, expects %llu ns, failed at %llu ns; "
2271 "belief record %llu, intervals %llu, baseline %llu ns, last %llu ns, misses %llu; "
2272 "hypothesis %llu %s for prediction %llu, %s; plan %llu (%s, hypothesis %llu, goal %llu); goal %llu",
2273 name, U(field(r, r->aien.o.prediction, 0)), pred_state_name(field(r, r->aien.o.prediction, 6)),
2274 U(field(r, r->aien.o.prediction, 1)), U(field(r, r->aien.o.prediction, 3)),
2275 U(field(r, r->aien.o.prediction, 5)), U(field(r, r->aien.o.prediction, 7)),
2276 U(field(r, r->aien.o.belief, 0)), U(field(r, r->aien.o.belief, 5)),
2277 U(field(r, r->aien.o.belief, 4)), U(field(r, r->aien.o.belief, 6)),
2278 U(field(r, r->aien.o.belief, 7)),
2279 U(field(r, r->aien.o.hypothesis, 0)),
2280 field(r, r->aien.o.hypothesis, 1) == RX_AIEN_HYP_CORE_CLASS ? "core class" :
2281 field(r, r->aien.o.hypothesis, 1) == RX_AIEN_HYP_DRIFT ? "drift" : "-",
2282 U(field(r, r->aien.o.hypothesis, 2)), hyp_state_name(field(r, r->aien.o.hypothesis, 7)),
2283 U(field(r, r->aien.o.plan, 0)), why_name(field(r, r->aien.o.plan, 5)),
2284 U(field(r, r->aien.o.plan, 4)), U(field(r, r->aien.o.plan, 6)),
2285 U(field(r, r->aien.o.goal, 0)));
2286 uint64_t search = field(r, r->omega.o.search, 0), sel = field(r, r->omega.o.selection, 0);
2287 both("R13 %s Omega: search epoch %llu (for plan %llu), selection epoch %llu realization %016llx; "
2288 "production calls %llu using realization %016llx, in force epoch %llu realization %016llx%s", name,
2289 U(search), U(field(r, r->omega.o.search, 6)), U(sel), U(field(r, r->omega.o.selection, 1)),
2290 U(field(r, r->omega.o.demand, 0)), U(field(r, r->omega.o.demand, 6)),
2291 U(field(r, r->living.o.inforce, 0)), U(field(r, r->living.o.inforce, 1)),
2292 search != sel ? "; that search waits for the GPU experiment's evidence before it can select" : "");
2293 uint64_t claims = r->w.stats.resident_claims, seat_acts = acts(r, r->living.r_seat);
2294 int err = atomic_load(&r->acceptor_error);
2295 const char *why;
2296 char buf[160];
2297 uint64_t prepared = field(r, r->living.o.input, 2); /* search epoch the experiment is for */
2298 if (err != 0) { snprintf(buf, sizeof buf, "seat transport error %d (the seat's own line is on stderr)", err); why = buf; }
2299 else if (seat_blocked(r, 0)) why = "the seat was stopped by the authority check";
2300 else if (r->living.last_refusal != 0) { snprintf(buf, sizeof buf, "experiment prepare refused (%d)", r->living.last_refusal); why = buf; }
2301 else if (prepared == 0)
2302 why = r->acceptor_live ? "no GPU experiment was prepared (no AIEN plan taken up by an Omega search)"
2303 : "no GPU experiment was prepared, and the seat transport was not started yet "
2304 "(it starts with the goal)";
2305 else if (!r->acceptor_live)
2306 why = "a GPU experiment was prepared but the seat transport that completes claims was not started yet "
2307 "(it starts with the goal)";
2308 else if (claims != 0) why = "the seat claimed; see the counts above";
2309 else why = "a GPU experiment was prepared and the seat transport ran, but no claim completed";
2310 both("R13 %s GPU: claims %llu, seat activations %llu, transport %s, transport error %d, "
2311 "experiment input search %llu trial %llu; why no GPU result: %s", name,
2312 U(claims), U(seat_acts), r->acceptor_live ? "started" : "not started", err,
2313 U(field(r, r->living.o.input, 2)), U(field(r, r->living.o.input, 3)), why);
2314 /* The two pre-goal dead ends behind "AIEN never confirmed the incumbent cost" (omega #527).
2315 * Both start from wall-clock jitter; neither is a GPU failure, and neither can recover before
2316 * the goal, so the 60 s wait only runs out. */
2317 uint64_t sel_real = field(r, r->omega.o.selection, 1), used = field(r, r->omega.o.demand, 6);
2318 if (field(r, r->aien.o.goal, 0) == 0 && field(r, r->aien.o.prediction, 6) != RX_AIEN_PRED_CONFIRMED) {
2319 if (sel != 0 && sel_real != used && field(r, r->living.o.inforce, 0) == 0)
2320 both("R13 %s diagnosis: Omega's first search selected realization %016llx, but production serves "
2321 "the in-force record (%016llx, the reference) and nothing can be promoted before the goal; "
2322 "AIEN discards every interval as \"production has not switched yet\", so it can never "
2323 "confirm. Not a GPU failure.", name, U(sel_real), U(used));
2324 else if (field(r, r->aien.o.prediction, 6) == RX_AIEN_PRED_FAILED && search != sel)
2325 both("R13 %s diagnosis: AIEN's prediction failed before the goal (baseline %llu ns, observed "
2326 "%llu ns); its %s plan opened Omega search %llu, which waits for GPU evidence while the seat "
2327 "transport starts only with the goal, and the failed prediction is not relearned while its "
2328 "hypothesis is under test, so it can never confirm. Not a GPU failure.", name,
2329 U(field(r, r->aien.o.prediction, 5)), U(field(r, r->aien.o.prediction, 7)),
2330 why_name(field(r, r->aien.o.plan, 5)), U(search));
2331 }
2332}
2333
2334int main(int argc, char **argv) {
2335 signal(SIGPIPE, SIG_IGN);
2336 setvbuf(stdout, NULL, _IONBF, 0);
2337#ifndef AIEN_TEST_BUILD
2338 if (argc == 2 && strcmp(argv[1], "--argus-probe") == 0) return argus_probe();
2339#endif
2340 const char *state = NULL;
2341 if (argc == 3 && strcmp(argv[1], "--state-dir") == 0) state = argv[2];
2342 else if (argc != 1) {
2343 fprintf(stderr, "usage: %s [--state-dir <dir>] [--argus-probe (production program only)]\n",
2344 argv[0]);
2345 return 2;
2346 }
2347 if (operator_state(state) != 0) return 2;
2348 if (seen_fit(1u << 17) != 0) return 1;
2349 int result = 0;
2350#ifndef AIEN_TEST_BUILD
2351 /* Production: ARGUS observes from the first authority on, or nothing runs. */
2352 if (argus_check_start() != 0) {
2353 receipt(0);
2354 return 1;
2355 }
2356#endif
2357 static const char *names[] = {"positive", "A no AIEN", "B no promotion authority",
2358 "C revoked experiment", "D stale generation", "E failed verification"};
2359 for (int mode = POSITIVE; mode <= FAILED_VERIFICATION; mode++) {
2360 Rig *r = calloc(1, sizeof *r);
2361 if (!r) return 1;
2362 int rc = start(r, mode);
2363 if (rc != 0 && rc != OP_SHUTDOWN)
2364 note_failure("R13 %s: setup failed at stage %d", names[mode], g_stage);
2365 if (rc == 0) rc = run(r, mode);
2366#if defined(AIEN_TEST_BUILD) && !defined(R13_SILICON)
2367 /* COMPOSITION-2 in the living system (host test build only), after the episode,
2368 * while the living World and its authority are still up. */
2369 if (rc == 0 && mode == POSITIVE) rc = composition_phase(r);
2370#endif
2371#ifdef AIEN_TEST_BUILD
2372 /* Fabric F5-0: host and silicon test builds (Lane 17, Lane 32). */
2373 if (rc == 0 && mode == POSITIVE) rc = fabric_phase(r);
2374#endif
2375 /* R16 G6: a world is not torn down under an operator stop. A stop that lands
2376 * after the episode keeps the world up until the operator resumes it (or
2377 * shuts the program down); only then is the mode audited and ended. */
2378 if (rc == 0 && r->ready && world_halted(r)) {
2379 printf("R13 operator %s: stopped after its episode; waiting for an operator resume\n",
2380 g_mode_key[mode]);
2381 if (wait_running(r) != 0) rc = OP_SHUTDOWN;
2382 }
2383 /* R16 G6: the crumb log shows what operator control did in this world. */
2384 if (r->ready && (rc == 0 || rc == OP_SHUTDOWN) && operator_audit(r) != 0 && rc == 0) {
2385 note_failure("R13 %s: work committed or published while the operator stop was in force",
2386 names[mode]);
2387 rc = -1;
2388 }
2389 if (rc != 0 && rc != OP_SHUTDOWN) explain_failure(r, names[mode]);
2390 if (r->admin && r->view) stop(r);
2391 free(r);
2392 if (rc == OP_SHUTDOWN) {
2393 /* An operator shutdown of a stopped world: the stop stays on disk, the
2394 * next start of this mode comes up stopped. No receipt is written. */
2395#ifndef AIEN_TEST_BUILD
2396 argus_finish();
2397#endif
2398 printf("R13 operator: shutdown while stopped in %s; the stop stays in %s/gen-%s; "
2399 "no receipt written\n", g_mode_key[mode], g_state_dir, g_mode_key[mode]);
2400 free(g_seen);
2401 free(g_stack);
2402 return 3;
2403 }
2404 if (rc != 0) { result = 1; break; }
2405 }
2406#ifndef AIEN_TEST_BUILD
2407 argus_finish(); /* every World is stopped: producers are quiescent */
2408#endif
2409 receipt(result == 0);
2410 free(g_seen);
2411 free(g_stack);
2412 return result;
2413}