code wiki / (root) / nx_sbr_admission_candidate.nx

nx_sbr_admission_candidate.nx source

↩ module page · 1832 lines · 120839 B

1// nx_sov_build_run.nx -- FULLY SOVEREIGN, REUSABLE build runner (operator: "no sh and no c build, 2// from the hardware layer up"). Generalizes nx_retire_gcc_orchestrator from hardcoded targets to ANY 3// module passed as argv[1]. The build path is bits-up sovereign end to end: 4// nx_cc_sovereign.elf <module>.nx -> _build/<module>.s (the team's SELF-HOSTED compiler) 5// nxasm_x86_main.elf <module>.s -> _build/<module>.sov.elf (the team's x86-64 assembler+linker) 6// _build/<module>.sov.elf (run it; exit = its exit) 7// ⚠OUTPUT PATH IS _build/, RELATIVE TO CWD -- NOT /tmp/. These three lines said /tmp/ until 2026-07-30, 8// left stale by the flock change that moved artifacts to a per-target _build/<name>.lock+.s+.sov.elf so 9// concurrent sweeps stop overwriting each other mid-build. A doc that disagrees with the code is a defect, 10// not a nit: it is why callers hunt for the artifact, and it hid a REAL brick hazard -- nx_hostctl 11// cmd_buildrun (nx_hostctl.nx) ONCE read only /tmp/<name>.sov.elf, which made this runner and that 12// supervisor a MATCHED PAIR that had to ship together or every /api/build failed. 13// CLOSED -- VERIFIED 2026-08-17 BY READING THE LIVE SOURCE, not by assuming: cmd_buildrun now probes the 14// ABSOLUTE .../nishihost/buildroot/_build/<name>.sov.elf FIRST (the parent is not in the child's CWD, so 15// it must name it absolutely), falls back to /tmp/ for pre-flock builders, and its failure line NAMES 16// BOTH paths. The pairing constraint no longer holds and this runner ships alone. 17// The old line also cited :3089 while the code now sits near :3571 -- a stale line number is the tell. 18// * A STALE HAZARD NOTE IS ITSELF A HAZARD: it makes the next reader either avoid a safe change or 19// hunt a defect that was already fixed. This estate has the receipt -- a standing RED-gate list that 20// nobody re-measured cost NINE sessions the SAME nine investigations, and 5 of the 9 were already 21// green. Re-measure a warning before repeating it. 22// NO gcc, NO bash, NO .sh anywhere. Orchestration is NishiLang sys_fork/dup3/execve/wait4. 23// Recompile-retry guards the known-good compiler's empty-.s nondeterminism. Usage: 24// nx_sov_build_run.elf <module-basename-in-runtime/_hdl_build> 25 26 27// license_tier: ORIGINAL Reuses the _run spine from nx_retire_gcc_orchestrator. 28import "nx_syscalls.nx" 29import "nx_itoa_lib.nx" // shared MSB-first emitter (zero-alloc) 30import "nx_sha256.nx" // CONTENT identity for the tree-canon admission (2026-08-06) 31import "nx_import.nx" // the SAME closure resolver nx_cc uses -> content-addressed build cache (B2, 2026-08-17) 32import "nx_builddeploy_lib.nx" // THE ruler for "may this build write a consumer-visible binary" (2026-08-26) 33import "nx_build_canon_input_lib.nx" // Refuse absent or malformed admission evidence before compilation. 34 35// TOOLCHAIN NAMES -- the binaries that BUILD everything else, so they may never be installed as a 36// side effect of a build (see the refusal at the install site; seq1464). 37// ⚠BOTH COMPILER NAMES: the module is `nx_compile_x86` but it ships as `nx_cc_sovereign.elf`, so a 38// guard that knew only one name would leave the other door open -- which is exactly the door the 39// regressed compiler came through. `nx_sov_build_run` is listed because a runner that can overwrite 40// ITSELF mid-build is the same hazard pointed inward. 41// st_mtime seconds, -1 when absent. Offset 88 is the channel proven by _freshness_gate T5 and used 42// unchanged by nx_staging_guard / nx_tree_diff / nx_gate_verdict_lib -- same offset, never a fourth copy 43// of the number. Used by the canon admission to tell STALENESS from a FORK. 44const SBR_STATBUF: i64 = 256 45const SBR_STAT_MTIME_OFF: i64 = 88 46func sbr_mtime(path: *u8) -> i64 { 47 let sb: *u8 = sys_mmap(SBR_STATBUF) 48 if sys_fstatat(path, sb) != 0 { sys_munmap(sb, SBR_STATBUF); return 0 - 1 } 49 let p: *i64 = ((sb as i64) + SBR_STAT_MTIME_OFF) as *i64 50 let v: i64 = p[0] 51 sys_munmap(sb, SBR_STATBUF) 52 return v 53} 54 55func sbr_name_is(a: *u8, b: *u8) -> i64 { 56 var i: i64 = 0 57 while a[i] != (0 as u8) { if a[i] != b[i] { return 0 } i = i + 1 } 58 if b[i] != (0 as u8) { return 0 } 59 return 1 60} 61func sbr_is_toolchain(name: *u8) -> i64 { 62 if sbr_name_is(name, "nx_compile_x86" as *u8) == 1 { return 1 } 63 if sbr_name_is(name, "nx_cc_sovereign" as *u8) == 1 { return 1 } 64 if sbr_name_is(name, "nxasm_x86_main" as *u8) == 1 { return 1 } 65 if sbr_name_is(name, "nxasm_x86" as *u8) == 1 { return 1 } 66 if sbr_name_is(name, "nx_sov_build_run" as *u8) == 1 { return 1 } 67 return 0 68} 69 70// ⚠⚠A DAEMON'S SERVING-ROOT TWIN IS NOT A CACHE, IT IS THE DEPLOYED ARTIFACT (2026-08-07). 71// refresh-IF-PRESENT is right for an ordinary organ: the next fork picks up the fresh bytes and 72// LM-026 staleness is retired. For a DAEMON it is a DEPLOY -- the sovereign supervisor health-probes, 73// finds the process unresponsive, and respawns FROM DISK, so the refreshed file becomes the running 74// binary with no promote, no canary, no health gate, no .prev and no rollback. 75// This is the SAME argument the toolchain guard above already makes, applied to the class that has the 76// same property: the artifact is re-executed by something other than the caller. 77// ★★★★★★ A FLAG WHOSE NAME PROMISES NO SIDE EFFECT, ON A TREE WHERE A SUPERVISOR RESPAWNS FROM 78// DISK, IS A DEPLOY WITH EXTRA STEPS. 79// MEASURED INCIDENT: `nx_sov_build_run nx_tools_api_serve --build-only` refreshed the serving-root 80// twin; the supervisor respawned onto it; netstat then showed ZERO listeners on :18096 with four live 81// instances. The agent surface was down for every seat. The caller had explicitly chosen NOT to deploy 82// and believed --build-only meant it. 83// Daemons have exactly ONE lawful update route: an organ_kind.conf row plus health-checked 84// /api/deploy, which validates, banks .prev and auto-rolls-back. This makes that route the only one 85// BY CONSTRUCTION rather than by convention -- the same upgrade the toolchain got after seq1464. 86// 87// RETURNS 1 declared daemon · 0 not a daemon · -1 UNPROVEN (conf unreadable). 88// The catastrophic few are ALSO hardcoded, so a missing or edited conf cannot silently re-open the 89// hole on the two surfaces every other seat depends on. ★ DATA-DRIVE THE LIST, HARDCODE THE BLAST. 90func sbr_is_daemon(name: *u8) -> i64 { 91 if sbr_name_is(name, "nx_tools_api_serve" as *u8) == 1 { return 1 } 92 if sbr_name_is(name, "nx_mgmt_api" as *u8) == 1 { return 1 } 93 let szp: *i64 = sys_mmap(16) as *i64 94 // ⚠THIS PATH MUST TOLERATE THE CWD ANCHOR -- FIXED 2026-08-15, AND IT HAD DISABLED THE GUARD. 95 // main() chdir's into buildroot/ whenever the runner is started from the serving root (which is how 96 // nx_job_run, the supervisor and every operator invoke it). This BARE path therefore resolved to 97 // buildroot/knowledge/status/organ_kind.conf, WHICH DOES NOT EXIST -- the conf lives at the nishihost 98 // root (37,596 B, verified both ways). sys_read_file returned 0, this returned -1 = UNPROVEN, and the 99 // caller's UNPROVEN branch WRITES THE BINARY ANYWAY and prints its warning AFTERWARDS. 100 // NET EFFECT, and it is not theoretical: the daemon guard has been silently OFF since the anchor 101 // landed, so every daemon built through this lane went straight to the SERVING ROOT with no canary, 102 // no health gate and no .prev -- the supervisor respawns from disk, so that write IS a deploy. 103 // MEASURED TODAY: a `--build-only` invocation deployed nx_docportal_admin_daemon. 104 // This same file ALREADY learned the lesson for tree-canon ("the manifest is ../knowledge/... because 105 // main() anchors CWD to buildroot") and applied it there. It was missed here. 106 // ★★★★★★A GUARD THAT CANNOT READ ITS OWN RULEBOOK DOES NOT FAIL LOUD, IT FAILS ABSENT -- AND AN 107 // ABSENT GUARD IS INDISTINGUISHABLE FROM A GUARD THAT APPROVED. The build-admission check twenty 108 // lines below gets the same question right (rc=5 CANNOT-MEASURE -> REFUSE); this one waved through. 109 // Anchored path FIRST, bare path second, so the answer is correct from EITHER cwd rather than 110 // trading one broken vantage for the other. 111 var buf: *u8 = sys_read_file("../knowledge/status/organ_kind.conf" as *u8, szp) 112 if (buf as i64) == 0 { buf = sys_read_file("knowledge/status/organ_kind.conf" as *u8, szp) } 113 if (buf as i64) == 0 { return 0 - 1 } 114 let n: i64 = szp[0] 115 if n <= 0 { return 0 - 1 } 116 var nl: i64 = 0 117 while name[nl] != (0 as u8) { nl = nl + 1 } 118 let pat: *u8 = "daemon" as *u8 119 var i: i64 = 0 120 while i < n { 121 // ⚠⚠THE EOL SCAN USED A SENTINEL THAT CLOBBERED ITS OWN CURSOR -- FIXED 2026-08-15, AND IT HAD 122 // MADE THIS ENTIRE LOOKUP DEAD. The old form was: 123 // while e < n { if buf[e] == 10 { e = n + 1 } else { e = e + 1 } } 124 // if e > n { e = e - 1 } 125 // On finding a newline it wrote n+1 INTO e to break, destroying the position it had just found; 126 // e-1 then yields n, never the newline index. So every "line" spanned the whole rest of the 127 // buffer, `i = e + 1` pushed i past n, and the outer loop ran EXACTLY ONCE -- on a first line 128 // that begins with '#' and is skipped as a comment. sbr_is_daemon therefore returned 0 for every 129 // name whenever the file was readable: not a wrong answer, a lookup that never ran. 130 // ★★★★★★THE TELL WAS ALREADY IN THE SOURCE: the two hardcoded `nx_tools_api_serve` / 131 // `nx_mgmt_api` early-returns above are a workaround for a table lookup that never matched. WHEN 132 // A DATA-DRIVEN CHECK HAS HARDCODED EXCEPTIONS, SUSPECT THE LOOKUP, NOT THE DATA. 133 // This is the estate's named recurring defect ("a loop-exit sentinel written into the search 134 // cursor erases the answer -- use a flag"); separate cursor, explicit flag, cursor preserved. 135 var e: i64 = i 136 var eol: i64 = 0 137 while eol == 0 { 138 if e >= n { eol = 1 } else { 139 if buf[e] == (10 as u8) { eol = 1 } else { e = e + 1 } 140 } 141 } 142 if buf[i] != (35 as u8) { 143 if i + nl < e { 144 var k: i64 = 0 145 var ok: i64 = 1 146 while k < nl { if buf[i+k] != name[k] { ok = 0; k = nl } else { k = k + 1 } } 147 if ok == 1 { 148 if buf[i+nl] == (32 as u8) { 149 var j: i64 = i + nl 150 var found: i64 = 0 151 while j + 6 <= e { 152 var m: i64 = 0 153 var eq: i64 = 1 154 while m < 6 { if buf[j+m] != pat[m] { eq = 0; m = 6 } else { m = m + 1 } } 155 if eq == 1 { found = 1; j = e } 156 j = j + 1 157 } 158 if found == 1 { return 1 } 159 } 160 } 161 } 162 } 163 i = e + 1 164 } 165 return 0 166} 167const SBR_MAGIC_4096: i64 = 4096 // read-chunk size (folded from the buildroot branch's rule-11 sweep, 2026-07-29 merge) 168 169// ---- CONTENT IDENTITY FOR THE TREE-CANON ADMISSION (2026-08-06) ---- 170// The admission below used to compare BYTE SIZES, and its own comment said so honestly: 171// "SIZE IS A SCREEN, NOT PROOF OF IDENTITY -- equal-size rewrites pass here; 172// nx_treecanon_gate stays the tree-level instrument." 173// THAT DELEGATION WAS NOT AN IMPLEMENTATION. nx_treecanon_gate compared sizes too, so NOTHING in 174// the build lane ever checked content, and each half looked reasonable only because it assumed the 175// other half was doing the work. A MUTATION-CLASS DEFECT PRESERVES SIZE BY CONSTRUCTION, and one 176// had already escaped into this very buildroot: _hdl_build/nx_media_extract.nx held `if hit != 0` 177// where the authoring tree held `if hit == 0` -- one byte, 4389 bytes on BOTH sides. 178// Canon rows now compare sha256 whenever the authoring tree publishes a digest manifest, and fall 179// back to the byte-size screen when it does not. STRICTLY STRONGER, NEVER WEAKER. 180const SBR_SHA_HEX: i64 = 64 181const SBR_QMARK: i64 = 63 // '?' fills the digest slot when a file is unreadable / row absent 182// sys_read_file reserves filesize+16, but 4 GiB when lseek(END) reports 0 -- freeing an empty file 183// as "0+16" would leak 4 GiB of address space per call and walk into RLIMIT_AS. 184const SBR_EMPTY_RESERVE: i64 = 4294967296 185func sbr_sha_hex(path: *u8, out: *u8) -> i64 { 186 let ln: *i64 = sys_mmap(16) as *i64 187 ln[0] = 0 188 let buf: *u8 = sys_read_file(path, ln) 189 if (buf as i64) == 0 { sys_munmap(ln as *u8, 16); return 0 - 1 } 190 let n: i64 = ln[0] 191 let d: *u8 = sys_mmap(48) 192 sha256_digest(buf, n, d) 193 if n > 0 { sys_munmap(buf, n + 16) } else { sys_munmap(buf, SBR_EMPTY_RESERVE + 16) } 194 sys_munmap(ln as *u8, 16) 195 var i: i64 = 0 196 while i < 32 { 197 let v: i64 = d[i] as i64 198 let hi: i64 = (v >> 4) & 15 199 let lo: i64 = v & 15 200 if hi < 10 { out[i*2] = (48+hi) as u8 } else { out[i*2] = (87+hi) as u8 } 201 if lo < 10 { out[i*2+1] = (48+lo) as u8 } else { out[i*2+1] = (87+lo) as u8 } 202 i = i + 1 203 } 204 sys_munmap(d, 48) 205 out[SBR_SHA_HEX] = 0 as u8 206 return 0 207} 208 209const SBR_OK: i64 = 0 210const SBR_USAGE: i64 = 2 211const SBR_COMPILE_FAIL: i64 = 3 212const SBR_ASM_FAIL: i64 = 4 213const SBR_ADMIT_REFUSED: i64 = 6 // build admission said no; distinct from a compile/assemble failure 214 // (3 and 4 raw would COLLIDE with COMPILE_FAIL/ASM_FAIL -- a retry-later 215 // signal must never decode as a broken build) 216const SBR_CANON_REFUSED: i64 = 7 // canon evidence unavailable, invalid, or divergent 217const SBR_CANON_PATH_BYTES: i64 = 512 218const SBR_RUNTIME_PREFIX_BYTES: i64 = 8 219const SBR_MIN_ASM_BYTES: i64 = 128 // empty/failed .s is ~0-byte header; the smallest real program (_min42) is 540B 220const SBR_MAX_RETRIES: i64 = 12 221// ---- BUILD DEADLINE (2026-08-16) --------------------------------------------------------------- 222// A build that HANGS is not a build that FAILED, and the two demand OPPOSITE responses -- the same 223// law the exit codes above already encode ("a retry-later signal must never decode as a broken 224// build"). MEASURED that day: nx_cc SPUN FOREVER on a specific source (a br_comp_border variant in 225// nx_browser_bisect.nx). With no deadline anywhere in this runner the child burned a core 226// indefinitely; two such spinners took the host from load_centi=542 to 1394, at which point 227// nx_ctxtop REFUSED to run ("host already saturated"). Only a human noticing stopped it. 228// nx_gate_build_sweep already carries "timeout per-build deadline in ms, default 180000" -- this is 229// that same shape, applied to the runner every organ is built through. 230const SBR_TIMEOUT_RC: i64 = 0 - 9 // sbr_run sentinel: NEGATIVE, so it cannot collide with a real 231 // exit code (0..255) nor with the 128+signal convention above 232const SBR_BUILD_TIMEOUT: i64 = 8 // process exit code; next free after CANON_REFUSED=7 233const SBR_SIGKILL: i64 = 9 234const SBR_POLL_MS: i64 = 100 // wait4(WNOHANG) poll interval; fork+WNOHANG liveness is already 235 // host-proven by nx_initlive_probe -- composed, not re-verified 236const SBR_NO_DEADLINE: i64 = 0 // explicit: RUNNING the built program must never be time-boxed 237// DERIVED FROM MEASUREMENT, NOT TASTE: the largest closure this runner compiles in practice is 238// nx_browser's 29-import set (9,243,150 B of .s), which completed in under 5 minutes on this host, 239// timed repeatedly on 2026-08-16. 900000 ms is 3x that worst observed case, so a legitimate build 240// cannot trip it while an infinite loop is still bounded. Raise it here if a bigger closure appears 241// -- and if you do, say what you measured. 242const SBR_BUILD_DEADLINE_MS: i64 = 900000 243 244func sbr_puts(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 } 245// MIGRATED to the shared emitter (debt 1785563586). The old body mmapped a scratch buffer 246// per call and never freed it. At PAGE granularity that is 4096B leaked PER CALL -- the 247// defect that took 28.5GB of a 36GB host in nx_ts_lumadiff (2MB input, ~3.66M calls). 248// nxi_* is MSB-first, allocates NOTHING, and emits identical bytes including the sign. 249func sbr_putn(v: i64) -> i64 { nxi_out(v); return 0 } 250 251// append NUL-terminated s into dst at off; return new offset (no NUL written) 252func sbr_cat(dst: *u8, off: i64, s: *u8) -> i64 { var i: i64 = 0; while s[i] != (0 as u8) { dst[off+i] = s[i]; i = i + 1 } return off + i } 253 254// bounded byte-range equality on (base,offset,len) pairs -- conf/manifest lines are not NUL-terminated 255func sbr_ceq_at(a: *u8, ao: i64, al: i64, b: *u8, bo: i64, bl: i64) -> i64 { 256 if al != bl { return 0 } 257 var i: i64 = 0 258 while i < al { if a[ao+i] != b[bo+i] { return 0 } i = i + 1 } 259 return 1 260} 261 262func sbr_exitcode(status: i64) -> i64 { return (status >> 8) & 0xff } 263 264// Decimal argv value -> integer, or -1 on ANYTHING malformed (empty, sign, units, stray char). 265// REFUSES rather than defaulting: a deadline that silently became 0 would restore the exact 266// unbounded-hang this flag exists to prevent, and it would do it while looking configured. 267func sbr_atoi(s: *u8) -> i64 { 268 var v: i64 = 0 269 var i: i64 = 0 270 while s[i] != (0 as u8) { 271 let c: i64 = s[i] as i64 272 if c < 48 { return 0 - 1 } 273 if c > 57 { return 0 - 1 } 274 v = v * 10 + (c - 48) 275 i = i + 1 276 } 277 if i == 0 { return 0 - 1 } 278 return v 279} 280 281// fork + optional stdout/stderr redirect + execve; parent waits; returns child's WEXITSTATUS, 282// OR 128+signal if the child died to a signal (shell convention). Without the signal check a 283// SEGFAULTED tool decodes as rc=0 = silent fake success (caught live 2026-06-09: nxasm segfaulted 284// on the 2.4MB compiler .s, the runner reported the assemble step OK, and the missing ELF 285// surfaced later as a confusing execve-127). Composes [[feedback-evidence-driven-live-grading]]. 286// redir_err>=0 -> child stderr (e.g. /dev/null to mute nx_cc's symbol-table dump). 287// deadline_ms > 0 time-boxes the child: poll wait4(WNOHANG), and on expiry SIGKILL it, REAP it (never 288// leave a zombie behind a timeout) and return SBR_TIMEOUT_RC. deadline_ms = SBR_NO_DEADLINE waits 289// forever, which is correct for RUNNING the built program -- a daemon or a long job must not be shot. 290func sbr_run(path: *u8, argv: *i64, envp: *i64, redir_out: i64, redir_err: i64, deadline_ms: i64) -> i64 { 291 let pid: i64 = sys_fork() 292 if pid == 0 { 293 if redir_out >= 0 { sys_dup3(redir_out, 1, 0) } 294 if redir_err >= 0 { sys_dup3(redir_err, 2, 0) } 295 sys_execve(path, argv, envp) 296 sys_exit(127) 297 } 298 let st: *i64 = sys_mmap(16) as *i64 299 if deadline_ms <= 0 { 300 sys_wait4(pid, st, 0) 301 } else { 302 // Deadline measured against the CLOCK, not against a count of sleeps: accumulating the poll 303 // interval drifts by however long each wait4 itself took, and a drifting deadline is a 304 // threshold nobody can state. 305 let t0: i64 = sys_now_ms() 306 var settled: i64 = 0 307 while settled == 0 { 308 let r: i64 = sys_wait4(pid, st, WNOHANG) 309 if r == pid { settled = 1 } 310 if settled == 0 { 311 if (sys_now_ms() - t0) >= deadline_ms { 312 nx_kill(pid, SBR_SIGKILL) 313 sys_wait4(pid, st, 0) 314 sbr_puts("[nx_sov_build_run] COMPILE-TIMEOUT after " as *u8) 315 sbr_putn(deadline_ms) 316 sbr_puts("ms -- child pid " as *u8) 317 sbr_putn(pid) 318 sbr_puts(" (" as *u8) 319 sbr_puts(path) 320 sbr_puts(") was KILLED and reaped. THIS IS NOT A COMPILE FAILURE: the tool never\n" as *u8) 321 sbr_puts(" answered, so nothing was judged about your source. A hang and a rejection demand opposite\n" as *u8) 322 sbr_puts(" responses -- do NOT go looking for a syntax error until you have reproduced this bounded.\n" as *u8) 323 return SBR_TIMEOUT_RC 324 } 325 sys_sleep_ms(SBR_POLL_MS) 326 } 327 } 328 } 329 let sig: i64 = st[0] & 0x7f 330 if sig != 0 { return 128 + sig } 331 return sbr_exitcode(st[0]) 332} 333 334// byte-size of a file (open, read in chunks, count) -- the determinism check for the empty-.s guard. 335func sbr_filesize(path: *u8) -> i64 { 336 let fd: i64 = sys_openat_rd(path) 337 if fd < 0 { return 0 } 338 let buf: *u8 = sys_mmap(SBR_MAGIC_4096) 339 var total: i64 = 0 340 var n: i64 = sys_read(fd, buf, SBR_MAGIC_4096) 341 while n > 0 { total = total + n; n = sys_read(fd, buf, SBR_MAGIC_4096) } 342 sys_close(fd) 343 return total 344} 345 346// ---- CONTENT-ADDRESSED BUILD CACHE (B2, 2026-08-17) -------------------------------------------------- 347// The compiler is FAST (measured 80ms/gate) but re-emits the whole unchanged import closure every build. 348// This caches the FINAL .sov.elf keyed on a hash that covers EVERY compile input -- the fully-expanded 349// source closure (via nx_cc's OWN resolver expand_imports, composition not a second ruler), the compiler 350// AND assembler binaries, and the -g flag. A hit is byte-identical BY CONSTRUCTION: identical key => every 351// input identical => the deterministic toolchain emits identical bytes. FAIL-OPEN everywhere -- a miss, 352// an expand overflow, or any error just compiles normally, so the cache can only speed up, never break. 353// Toolchain targets are never cached (their own binary is in every key; a self-cache is meaningless). 354// COMPLETED 2026-08-23 (rung B2 of /compare/toolchain, watch symbol bld_cache_cas): the first cut stored 355// an entry by plain copy and served any entry that OPENED. That left three gaps the rung's own risk row 356// names: (1) a hit was never byte-verified, so a truncated or mid-write entry would be served as a HIT; 357// (2) the store was not atomic, so a concurrent reader could see a half-written elf; (3) a MISS was 358// SILENT, so "the cache missed" and "the cache is not there" were the same absence of output. 359// Now: every entry carries a SIDECAR (<key>.sov.elf.sha: sha256= bytes= key=) written AFTER the elf, 360// both via tmp+renameat; a hit is served ONLY after the cached bytes re-hash to the sidecar, and the 361// copy into _build/ is re-hashed too; every outcome prints ONE line, BUILD-CACHE HIT | MISS reason=<r> 362// | STORE, so a gate can assert on STATE (the .s the compiler writes is ABSENT on a hit) and a reader 363// can see which path ran. Kill switches: `cache_enabled=0` in ../knowledge/buildcache.conf (one parser 364// with cache_max_bytes) and the --no-cache lane flag. bld_cache_cas is the lookup+verify+serve entry; 365// bld_cache_cas_store the populate. Still fail-open on every error: the worst outcome is a compile. 366const SBR_CACHE_EXPAND_CAP: i64 = 33554432 // 32 MiB: biggest measured closure .s is ~9.2 MB (nx_browser); 367 // expand_imports FAILS LOUD on overflow and we fail-open, so a 368 // larger closure simply skips the cache -- safe, never wrong. 369 370// whole-file copy for cache <-> artifact. returns 0 ok, -1 fail (caller treats -1 as "no cache", fail-open). 371// COPY WHAT A COPY MEANS -- MODE IS PART OF THE FILE (2026-08-18). This copier opened its destination 372// 0644 for every byte it wrote, so a BUILD-CACHE HIT reproduced the artifact byte-perfect and INERT: 373// nx_sov_build_run removes the stale _build/<t>.sov.elf before every build, so the hit path always 374// CREATED the file fresh at 0644, and `nx_sov_build_run <t>` then ran it -> exit 127. Measured live 375// the day after B2 shipped (nx_vcodec_layout_gate: BUILD-CACHE HIT ... run-exit=127). B2's own proof 376// was byte identity -- structurally blind to mode, exactly the nx_filecopy defect banked 2026-08-14. 377// The fix is the same one nx_filecopy took: stat the SOURCE and apply ITS mode (st_mode is a u32 at 378// stat offset 24, the channel nx_offc_install proves), announcing UNKNOWN when it cannot stat rather 379// than silently leaving 0644. Every consumer inherits it: a nxasm-emitted 0755 artifact stored into 380// the cache is 0755 there, and a hit that copies it back is 0755 again -- no per-call-site chmod, one 381// mechanism. 382const SBR_STAT_MODE_OFF: i64 = 24 383const SBR_MODE_PERM_MASK: i64 = 511 // 0777: permission bits only; type bits never travel 384func sbr_src_mode(path: *u8) -> i64 { 385 let sb: *u8 = sys_mmap(SBR_STATBUF) 386 if sys_fstatat(path, sb) != 0 { sys_munmap(sb, SBR_STATBUF); return 0 - 1 } 387 let m: i64 = (sb[SBR_STAT_MODE_OFF] as i64) + ((sb[SBR_STAT_MODE_OFF + 1] as i64) << 8) 388 sys_munmap(sb, SBR_STATBUF) 389 return m & SBR_MODE_PERM_MASK 390} 391// STAT-BASED SIZE. Returns -1 when the path is ABSENT and >=0 when it is present, so "gone" and "empty" 392// are two answers rather than one. sbr_filesize() below reads the whole file and returns 0 for BOTH -- an 393// absent-and-empty conflation that is harmless where it is used for a .s byte count and NOT harmless on the 394// one axis that matters here: the artifact a cache HIT claims to have delivered. st_size is the 64-bit field 395// at offset 48 of x86-64 struct stat; st_mode at offset 24 is the same buffer sbr_src_mode already proves, 396// so this opens no new syscall channel. Assembled top byte down, so no intermediate multiplier overflows. 397const SBR_STAT_SIZE_OFF: i64 = 48 398const SBR_STAT_SIZE_W: i64 = 8 399func sbr_stat_size(path: *u8) -> i64 { 400 let sb: *u8 = sys_mmap(SBR_STATBUF) 401 if sys_fstatat(path, sb) != 0 { sys_munmap(sb, SBR_STATBUF); return 0 - 1 } 402 var v: i64 = 0 403 var i: i64 = SBR_STAT_SIZE_W - 1 404 while i >= 0 { 405 v = v * 256 + (sb[SBR_STAT_SIZE_OFF + i] as i64) 406 i = i - 1 407 } 408 sys_munmap(sb, SBR_STATBUF) 409 return v 410} 411func sbr_copyfile(srcp: *u8, dstp: *u8) -> i64 { 412 let ln: *i64 = sys_mmap(16) as *i64 413 ln[0] = 0 414 let buf: *u8 = sys_read_file(srcp, ln) 415 if (buf as i64) == 0 { sys_munmap(ln as *u8, 16); return 0 - 1 } 416 let n: i64 = ln[0] 417 let smode: i64 = sbr_src_mode(srcp) 418 let fd: i64 = sys_openat_wr(dstp, 0x1a4) 419 if fd < 0 { if n > 0 { sys_munmap(buf, n + 16) } sys_munmap(ln as *u8, 16); return 0 - 1 } 420 var off: i64 = 0 421 while off < n { 422 let w: i64 = sys_write(fd, ((buf as i64) + off) as *u8, n - off) 423 if w <= 0 { sys_close(fd); if n > 0 { sys_munmap(buf, n + 16) } sys_munmap(ln as *u8, 16); return 0 - 1 } 424 off = off + w 425 } 426 sys_close(fd) 427 if n > 0 { sys_munmap(buf, n + 16) } 428 sys_munmap(ln as *u8, 16) 429 // apply the source's permission bits AFTER the write (openat's mode is masked by umask and only 430 // applies to a CREATED file; an existing destination keeps its old bits -- fchmodat sets both cases). 431 if smode >= 0 { nx_chmod(dstp, smode) } 432 if smode < 0 { sbr_puts("[nx_sov_build_run] copy: source mode UNKNOWN (stat failed) -- destination left at the create default\n" as *u8) } 433 return 0 434} 435 436// 32-byte digest -> 64 lowercase hex chars at out (no NUL written). ONE encoder: sbr_cache_key and the 437// sidecar verify used to carry their own copy of this loop. 438func bld_cache_cas_hex(d: *u8, out: *u8) -> i64 { 439 var i: i64 = 0 440 while i < 32 { 441 let v: i64 = d[i] as i64 442 let hi: i64 = (v >> 4) & 15 443 let lo: i64 = v & 15 444 if hi < 10 { out[i*2] = (48+hi) as u8 } else { out[i*2] = (87+hi) as u8 } 445 if lo < 10 { out[i*2+1] = (48+lo) as u8 } else { out[i*2+1] = (87+lo) as u8 } 446 i = i + 1 447 } 448 return 0 449} 450 451// Compute the cache key hex (64 chars into out, null-terminated). Returns 0 on success, -1 fail-open. 452// key = sha256( hex(sha256(expanded closure src incl crash guard)) ++ compilerSha ++ asmSha ++ 'g'|'n' ). 453// THE INCUMBENT'S FLAVOUR, READ FROM ITS BYTES (2026-09-05, operator: "first byte fix"). A debug build carries the 454// DWARF section-name string .debug_line (nxasm writes it under -g; nx_contentdiff partitions exactly these runs as 455// lost_sectname); a release build carries no such run. Returns 1 = debug, 0 = release, -1 = unreadable / absent. 456// The needle is ASSEMBLED from two halves at runtime so THIS organ's own binary never holds it contiguously -- a 457// self-rebuild would otherwise read its own literal as evidence and default every runner build to debug (the 458// detector-counts-itself class, nx_gatelaw_gate 2026-09-03). sys_read_file sizes from the file: no cap, no short read. 459func sbr_incumbent_flavour(path: *u8) -> i64 { 460 let ln: *i64 = sys_mmap(16) as *i64 461 ln[0] = 0 462 let buf: *u8 = sys_read_file(path, ln) 463 if (buf as i64) == 0 { sys_munmap(ln as *u8, 16); return 0 - 1 } 464 let n: i64 = ln[0] 465 let needle: *u8 = sys_mmap(32); var no: i64 = 0 466 no = sbr_cat(needle, no, ".debug_" as *u8); no = sbr_cat(needle, no, "line" as *u8); needle[no] = 0 as u8 467 var found: i64 = 0 468 var i: i64 = 0 469 while found == 0 { 470 if i + no > n { found = 0 - 1 } else { 471 var j: i64 = 0 472 var ok: i64 = 1 473 while j < no { 474 if buf[i + j] != needle[j] { ok = 0; j = no } else { j = j + 1 } 475 } 476 if ok == 1 { found = 1 } 477 i = i + 1 478 } 479 } 480 sys_munmap(needle, 32) 481 sys_munmap(buf, n + 16) 482 sys_munmap(ln as *u8, 16) 483 if found == 1 { return 1 } 484 return 0 485} 486 487func sbr_cache_key(src: *u8, compiler: *u8, asm_tool: *u8, want_debug: i64, out: *u8) -> i64 { 488 let ebuf: *u8 = sys_mmap(SBR_CACHE_EXPAND_CAP) 489 let ectx: *ExpandCtx = expand_ctx_new(ebuf, SBR_CACHE_EXPAND_CAP) 490 let erc: i64 = expand_imports(ectx, src) 491 if erc < 0 { sys_munmap(ebuf, SBR_CACHE_EXPAND_CAP); return 0 - 1 } 492 expand_imports(ectx, "runtime/nx_crash.nx" as *u8) // match nx_cc's default guard append (dedup-safe) 493 let opp: *i64 = ectx.out_pos 494 let elen: i64 = *opp 495 let d0: *u8 = sys_mmap(48) 496 sha256_digest(ebuf, elen, d0) 497 let km: *u8 = sys_mmap(256) 498 var kp: i64 = 0 499 bld_cache_cas_hex(d0, km) 500 kp = SBR_SHA_HEX 501 if sbr_sha_hex(compiler, ((km as i64) + kp) as *u8) != 0 { sys_munmap(ebuf, SBR_CACHE_EXPAND_CAP); return 0 - 1 } 502 kp = kp + SBR_SHA_HEX 503 if sbr_sha_hex(asm_tool, ((km as i64) + kp) as *u8) != 0 { sys_munmap(ebuf, SBR_CACHE_EXPAND_CAP); return 0 - 1 } 504 kp = kp + SBR_SHA_HEX 505 if want_debug == 1 { km[kp] = 103 as u8 } else { km[kp] = 110 as u8 } // 'g' | 'n' 506 kp = kp + 1 507 let dk: *u8 = sys_mmap(48) 508 sha256_digest(km, kp, dk) 509 bld_cache_cas_hex(dk, out) 510 out[SBR_SHA_HEX] = 0 as u8 511 sys_munmap(ebuf, SBR_CACHE_EXPAND_CAP) 512 return 0 513} 514 515// ---- bld_cache_cas: the content-addressed LOOKUP + VERIFY + SERVE entry (rung B2 done-rule) ---------- 516// Sidecar grammar (line-anchored, one field per line, order fixed): sha256=<64 hex> NL bytes=<dec> NL key=<64 hex> NL 517// The sidecar is written AFTER the elf (both tmp+renameat), so "sidecar present" implies "elf complete". 518// Path widths DERIVED: cachepath is at most SBR_CACHE_PATHW (the prune census bound); the sidecar adds 519// ".sha" (4) and a tmp adds ".tmp-" (5) plus the target name, which argv bounds only by PATH_MAX -- so a 520// 4x slot is used and ANY overflow is announced and skipped (fail-open), never truncated. 521const SBR_CACHE_SIDE_SUFFIX: *u8 = ".sha" 522const SBR_CACHE_TMP_INFIX: *u8 = ".tmp-" 523const SBR_CACHE_TMPW: i64 = 512 // 4 x SBR_CACHE_PATHW, see derivation above 524const SBR_CACHE_SIDE_MAX: i64 = 256 // sha256= (7+64) + bytes= (6+20 max i64 digits) + key= (4+64) + 3 NL = 168 < 256 525const SBR_CACHE_ELF_SUFFIX_LEN: i64 = 8 // ".sov.elf" -- the key is the SBR_SHA_HEX hex chars before it 526 527// first line of buf[0..n) that starts with `key`: copy the rest of that line (sans NL) into out[0..cap), 528// NUL-terminate, return its length; -1 when absent or longer than cap-1 (an over-long field is 529// malformed, not truncated-and-trusted). 530func bld_cache_cas_field(buf: *u8, n: i64, key: *u8, out: *u8, cap: i64) -> i64 { 531 var klen: i64 = 0 532 while key[klen] != (0 as u8) { klen = klen + 1 } 533 var i: i64 = 0 534 while i < n { 535 var at_start: i64 = 0 536 if i == 0 { at_start = 1 } 537 if i > 0 { if buf[i-1] == (10 as u8) { at_start = 1 } } 538 if at_start == 1 { 539 var k: i64 = 0 540 var hit: i64 = 1 541 while k < klen { 542 if i + k >= n { hit = 0; k = klen } 543 if hit == 1 { if buf[i+k] != key[k] { hit = 0; k = klen } } 544 if k < klen { k = k + 1 } 545 } 546 if hit == 1 { 547 var j: i64 = i + klen 548 var o: i64 = 0 549 var scanning: i64 = 1 550 while scanning == 1 { 551 if j >= n { scanning = 0 } 552 if scanning == 1 { if buf[j] == (10 as u8) { scanning = 0 } } 553 if scanning == 1 { 554 if o >= cap - 1 { return 0 - 1 } 555 out[o] = buf[j]; o = o + 1; j = j + 1 556 } 557 } 558 out[o] = 0 as u8 559 return o 560 } 561 } 562 i = i + 1 563 } 564 return 0 - 1 565} 566 567// Verify the entry at cachepath against its sidecar. 1 = verified (hex of the artifact's sha256 is left in 568// shaout, its size in *bytesout) | 0 = sha or size MISMATCH | -1 no entry | -2 sidecar absent | -3 sidecar 569// malformed. Reads the WHOLE artifact and re-hashes it every time: a hit that is not re-hashed is a hit 570// that trusts the disk, and the only reason to have a sidecar is not to. 571func bld_cache_cas_verify(cachepath: *u8, shaout: *u8, bytesout: *i64) -> i64 { 572 let ce: i64 = sys_openat_rd(cachepath) 573 if ce < 0 { return 0 - 1 } 574 sys_close(ce) 575 let side: *u8 = sys_mmap(SBR_CACHE_TMPW) 576 var so: i64 = sbr_cat(side, 0, cachepath) 577 so = sbr_cat(side, so, SBR_CACHE_SIDE_SUFFIX); side[so] = 0 as u8 578 let sl: *i64 = sys_mmap(16) as *i64 579 sl[0] = 0 580 let sbuf: *u8 = sys_read_file(side, sl) 581 if (sbuf as i64) == 0 { sys_munmap(side, SBR_CACHE_TMPW); sys_munmap(sl as *u8, 16); return 0 - 2 } 582 let sn: i64 = sl[0] 583 let want_sha: *u8 = sys_mmap(SBR_CACHE_SIDE_MAX) 584 let want_bytes_s: *u8 = sys_mmap(SBR_CACHE_SIDE_MAX) 585 let f1: i64 = bld_cache_cas_field(sbuf, sn, "sha256=" as *u8, want_sha, SBR_CACHE_SIDE_MAX) 586 let f2: i64 = bld_cache_cas_field(sbuf, sn, "bytes=" as *u8, want_bytes_s, SBR_CACHE_SIDE_MAX) 587 if sn > 0 { sys_munmap(sbuf, sn + 16) } else { sys_munmap(sbuf, SBR_EMPTY_RESERVE + 16) } 588 sys_munmap(sl as *u8, 16) 589 sys_munmap(side, SBR_CACHE_TMPW) 590 if f1 != SBR_SHA_HEX { return 0 - 3 } 591 if f2 <= 0 { return 0 - 3 } 592 let want_bytes: i64 = sbr_atoi(want_bytes_s) 593 if want_bytes < 0 { return 0 - 3 } 594 if sbr_sha_hex(cachepath, shaout) != 0 { return 0 - 1 } 595 // BY STAT, NOT BY WHOLE-FILE READ: sbr_filesize returns 0 for an ABSENT file, so an entry that vanished 596 // between the open above and here would be reported as a size MISMATCH (which EVICTS) instead of as the 597 // absence it is. -1 is routed to no-entry, the honest answer. 598 let have_bytes: i64 = sbr_stat_size(cachepath) 599 bytesout[0] = have_bytes 600 if have_bytes < 0 { return 0 - 1 } 601 if have_bytes != want_bytes { return 0 } 602 var i: i64 = 0 603 while i < SBR_SHA_HEX { if shaout[i] != want_sha[i] { return 0 } i = i + 1 } 604 return 1 605} 606 607func bld_cache_cas_say(name: *u8, what: *u8, key: *u8) -> i64 { 608 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name); sbr_puts(": BUILD-CACHE " as *u8); sbr_puts(what) 609 if key != (0 as *u8) { sbr_puts(" key=" as *u8); sbr_puts(key) } 610 return 0 611} 612func bld_cache_cas_nl() -> i64 { let b: *u8 = sys_mmap(2); b[0] = 10 as u8; sys_write(1, b, 1); sys_munmap(b, 2); return 0 } 613 614// THE ENTRY. Returns 1 on a verified HIT (elfpath now holds the byte-identical artifact, mode preserved), 615// 0 on any MISS -- and prints exactly one BUILD-CACHE line either way, naming the reason on a miss. 616// sha-mismatch EVICTS the entry and its sidecar (a corrupt entry must not be offered twice); every other 617// miss leaves the store alone so a concurrent populate in flight is never destroyed. 618func bld_cache_cas(cachekey: *u8, cachepath: *u8, elfpath: *u8, name: *u8) -> i64 { 619 let sha: *u8 = sys_mmap(SBR_SHA_HEX + 2) 620 let bp: *i64 = sys_mmap(16) as *i64 621 bp[0] = 0 622 let v: i64 = bld_cache_cas_verify(cachepath, sha, bp) 623 if v == 0 - 1 { bld_cache_cas_say(name, "MISS reason=no-entry" as *u8, cachekey); bld_cache_cas_nl(); return 0 } 624 if v == 0 - 2 { bld_cache_cas_say(name, "MISS reason=sidecar-absent" as *u8, cachekey); bld_cache_cas_nl(); return 0 } 625 if v == 0 - 3 { bld_cache_cas_say(name, "MISS reason=sidecar-malformed" as *u8, cachekey); bld_cache_cas_nl(); return 0 } 626 if v == 0 { 627 let side: *u8 = sys_mmap(SBR_CACHE_TMPW) 628 var so: i64 = sbr_cat(side, 0, cachepath) 629 so = sbr_cat(side, so, SBR_CACHE_SIDE_SUFFIX); side[so] = 0 as u8 630 sys_unlinkat(cachepath) 631 sys_unlinkat(side) 632 bld_cache_cas_say(name, "MISS reason=sha-mismatch (entry EVICTED: cached bytes do not re-hash to their sidecar)" as *u8, cachekey) 633 bld_cache_cas_nl() 634 return 0 635 } 636 if sbr_copyfile(cachepath, elfpath) != 0 { bld_cache_cas_say(name, "MISS reason=copy-failed" as *u8, cachekey); bld_cache_cas_nl(); return 0 } 637 // the COPY is re-hashed too: a short write into _build/ would otherwise be a verified hit of the wrong bytes 638 let sha2: *u8 = sys_mmap(SBR_SHA_HEX + 2) 639 if sbr_sha_hex(elfpath, sha2) != 0 { bld_cache_cas_say(name, "MISS reason=copy-failed" as *u8, cachekey); bld_cache_cas_nl(); return 0 } 640 var i: i64 = 0 641 while i < SBR_SHA_HEX { 642 if sha[i] != sha2[i] { sys_unlinkat(elfpath); bld_cache_cas_say(name, "MISS reason=copy-failed (copy does not re-hash)" as *u8, cachekey); bld_cache_cas_nl(); return 0 } 643 i = i + 1 644 } 645 // ---- THE ARTIFACT ASSERTION (2026-09-04, LANE-D root fix) ------------------------------------ 646 // A CACHE THAT VERIFIES A SIDECAR WITHOUT STAT-ING THE FILE THE SIDECAR DESCRIBES IS ASSERTING A 647 // PROPERTY OF AN ARTIFACT IT NEVER LOOKED AT. Everything above this line judges the CACHE ENTRY and 648 // the COPY OPERATION. Nothing judged the DELIVERED FILE -- so "byte-identical artifact reused" was an 649 // invariant EMERGING from three helpers agreeing, never an asserted fact, and the builder had no 650 // vocabulary in which to report its failure. MEASURED 2026-09-04 on a copy of this builder with the 651 // copy-back chain removed: it printed BUILD-CACHE HIT ... byte-identical artifact reused, exited 0, 652 // and left NO FILE; every downstream consumer then failed against an artifact announced as reused. 653 // This stat is the only check whose SUBJECT is the delivered artifact rather than the operation that 654 // was supposed to produce it, which is exactly why it survives the removal of that operation. 655 // FAIL DIRECTION IS A MISS, NEVER AN ERROR: returning 0 sends the build down the compile path, so the 656 // worst outcome of this check is one compile -- the same fail-open contract the rest of this cache keeps. 657 let delivered: i64 = sbr_stat_size(elfpath) 658 if delivered != bp[0] { 659 sys_unlinkat(elfpath) 660 bld_cache_cas_say(name, "MISS reason=artifact-not-materialised (a HIT was verified but the artifact is not on disk: stat says " as *u8, 0 as *u8) 661 if delivered < 0 { sbr_puts("ABSENT" as *u8) } 662 if delivered >= 0 { sbr_putn(delivered); sbr_puts(" bytes" as *u8) } 663 sbr_puts(", the verified entry is " as *u8); sbr_putn(bp[0]) 664 sbr_puts(" bytes. NOT claiming reuse; compiling instead)" as *u8) 665 bld_cache_cas_nl() 666 return 0 667 } 668 bld_cache_cas_say(name, "HIT" as *u8, cachekey) 669 sbr_puts(" bytes=" as *u8); sbr_putn(bp[0]); sbr_puts(" sha256=" as *u8); sbr_puts(sha) 670 sbr_puts(" -- verified against its sidecar, byte-identical artifact reused, compiler NOT run" as *u8) 671 bld_cache_cas_nl() 672 return 1 673} 674 675// POPULATE after a real build: elf via tmp+renameat, THEN sidecar via tmp+renameat (ordering is the 676// contract bld_cache_cas_verify relies on). Announces STORE / STORE-FAILED reason=. Fail-open. 677func bld_cache_cas_store(elfpath: *u8, cachepath: *u8, name: *u8) -> i64 { 678 var plen: i64 = 0 679 while cachepath[plen] != (0 as u8) { plen = plen + 1 } 680 var nlen: i64 = 0 681 while name[nlen] != (0 as u8) { nlen = nlen + 1 } 682 if plen + 4 + 5 + nlen + 1 >= SBR_CACHE_TMPW { 683 bld_cache_cas_say(name, "STORE-FAILED reason=path-too-long (not truncated; entry skipped)" as *u8, 0 as *u8); bld_cache_cas_nl() 684 return 0 - 1 685 } 686 let tmp: *u8 = sys_mmap(SBR_CACHE_TMPW) 687 var t: i64 = sbr_cat(tmp, 0, cachepath) 688 t = sbr_cat(tmp, t, SBR_CACHE_TMP_INFIX); t = sbr_cat(tmp, t, name); tmp[t] = 0 as u8 689 if sbr_copyfile(elfpath, tmp) != 0 { sys_unlinkat(tmp); bld_cache_cas_say(name, "STORE-FAILED reason=copy" as *u8, 0 as *u8); bld_cache_cas_nl(); return 0 - 1 } 690 let sha: *u8 = sys_mmap(SBR_SHA_HEX + 2) 691 if sbr_sha_hex(tmp, sha) != 0 { sys_unlinkat(tmp); bld_cache_cas_say(name, "STORE-FAILED reason=hash" as *u8, 0 as *u8); bld_cache_cas_nl(); return 0 - 1 } 692 // SAME LAW, STORE SIDE: the sidecar is a claim ABOUT the staged entry, so size it by stat and refuse 693 // to write a sidecar describing a file that is not there (sbr_filesize would have recorded bytes=0 and 694 // produced an entry that self-evicts as sha-mismatch forever after). 695 let nbytes: i64 = sbr_stat_size(tmp) 696 if nbytes < 0 { 697 sys_unlinkat(tmp) 698 bld_cache_cas_say(name, "STORE-FAILED reason=staged-entry-absent (refusing to write a sidecar describing a file that is not there)" as *u8, 0 as *u8) 699 bld_cache_cas_nl() 700 return 0 - 1 701 } 702 if sys_renameat(tmp, cachepath) != 0 { sys_unlinkat(tmp); bld_cache_cas_say(name, "STORE-FAILED reason=rename" as *u8, 0 as *u8); bld_cache_cas_nl(); return 0 - 1 } 703 // sidecar: build the text, write to tmp, rename over <cachepath>.sha 704 let side: *u8 = sys_mmap(SBR_CACHE_TMPW) 705 var so: i64 = sbr_cat(side, 0, cachepath) 706 so = sbr_cat(side, so, SBR_CACHE_SIDE_SUFFIX); side[so] = 0 as u8 707 let stmp: *u8 = sys_mmap(SBR_CACHE_TMPW) 708 var st: i64 = sbr_cat(stmp, 0, side) 709 st = sbr_cat(stmp, st, SBR_CACHE_TMP_INFIX); st = sbr_cat(stmp, st, name); stmp[st] = 0 as u8 710 let txt: *u8 = sys_mmap(SBR_CACHE_SIDE_MAX) 711 var x: i64 = sbr_cat(txt, 0, "sha256=" as *u8); x = sbr_cat(txt, x, sha); txt[x] = 10 as u8; x = x + 1 712 x = sbr_cat(txt, x, "bytes=" as *u8) 713 x = nxi_buf(txt, x, nbytes) // digits only, returns the offset after them (nx_itoa_lib contract) 714 txt[x] = 10 as u8; x = x + 1 715 // key= is the basename of cachepath between "_build/cache/" and ".sov.elf" -- written so a sidecar 716 // found out of place still says which key it belongs to; the reader does not depend on it. 717 x = sbr_cat(txt, x, "key=" as *u8) 718 var kb: i64 = plen - SBR_CACHE_ELF_SUFFIX_LEN - SBR_SHA_HEX 719 if kb < 0 { kb = 0 } 720 var ki: i64 = 0 721 while ki < SBR_SHA_HEX { if kb + ki < plen { txt[x] = cachepath[kb + ki]; x = x + 1 } ki = ki + 1 } 722 txt[x] = 10 as u8; x = x + 1 723 let sfd: i64 = sys_openat_wr(stmp, 0x1a4) 724 if sfd < 0 { bld_cache_cas_say(name, "STORE-FAILED reason=sidecar-open" as *u8, 0 as *u8); bld_cache_cas_nl(); return 0 - 1 } 725 var woff: i64 = 0 726 while woff < x { 727 let w: i64 = sys_write(sfd, ((txt as i64) + woff) as *u8, x - woff) 728 if w <= 0 { sys_close(sfd); sys_unlinkat(stmp); bld_cache_cas_say(name, "STORE-FAILED reason=sidecar-write" as *u8, 0 as *u8); bld_cache_cas_nl(); return 0 - 1 } 729 woff = woff + w 730 } 731 sys_close(sfd) 732 if sys_renameat(stmp, side) != 0 { sys_unlinkat(stmp); bld_cache_cas_say(name, "STORE-FAILED reason=sidecar-rename" as *u8, 0 as *u8); bld_cache_cas_nl(); return 0 - 1 } 733 bld_cache_cas_say(name, "STORE" as *u8, 0 as *u8) 734 sbr_puts(" bytes=" as *u8); sbr_putn(nbytes); sbr_puts(" sha256=" as *u8); sbr_puts(sha) 735 bld_cache_cas_nl() 736 return 0 737} 738 739// ---- BUILD-CACHE BYTE BUDGET (2026-08-18) -- the cap owed since B2 shipped --------------------- 740// One elf per distinct (closure, toolchain, flags) forever is an unbounded append-only store, and a 741// compiler promote orphans an entire key generation at once (measured the day B1 DCE shipped: all 742// 121 entries dead in one promote). The estate's remedy for an unbounded store is a LOUD budget -- 743// and for a CACHE, eviction is additionally safe by construction: every entry is regenerable from 744// source, so a wrong eviction costs one compile, never data. 745// THE BUDGET IS DATA (rules 11+17): ../knowledge/buildcache.conf key cache_max_bytes overrides the 746// default without a rebuild. THE DEFAULT IS DERIVED, NOT TASTE: 13,202 buildable sources x ~45 KB 747// mean post-DCE elf (558 MB over 12,336 built, measured in the B1 full-population sweep) is ~600 MB 748// for one full compiler generation; the budget must hold one generation plus churn or the daily 749// drift census would thrash its own hits. 1 GiB covers that with headroom on the volume. 750// EVICTION IS OLDEST-mtime-FIRST. Documented imprecision: a HIT does not refresh mtime, so mtime is 751// store order, not use order -- a hot entry can be evicted and costs one re-compile on its next 752// miss. Chosen because touching on hit would put a write on the fast path this cache exists to keep 753// read-only. 754const SBR_CACHE_BUDGET_DEFAULT: i64 = 1073741824 755const SBR_CACHE_DIRBUF: i64 = 65536 756// enumeration pool bound. NOT a silent cap: overflow ANNOUNCES and skips the prune entirely (the 757// cache keeps working; only its janitor abstains), because pruning from a partial listing would 758// evict by an incomplete ordering. 32768 slots is 2.5x the whole estate's source count. 759const SBR_CACHE_PRUNE_SLOTS: i64 = 32768 760// Path slot width, DERIVED not hand-counted (the first cut of this constant was 80 and silently 761// truncated every real entry -- "_build/cache/" is 13 bytes, the key is a 64-hex sha256, ".sov.elf" 762// is 8, plus the NUL = 86 -- so the census dropped the very entries it was sizing and the budget 763// never tripped; caught by strace showing an open of "....s"). 128 = the derivation rounded up to 764// a power of two; anything that still does not fit is SKIPPED AND ANNOUNCED, never truncated. 765const SBR_CACHE_PATHW: i64 = 128 766 767// Read one `<key>=<decimal>` row from ../knowledge/buildcache.conf; absent/unreadable/non-numeric -> dflt. 768// ONE parser for every cache conf row (cache_max_bytes, cache_enabled): the second row to need it is the 769// signal it was a shared primitive, not a second copy of the loop. 770func sbr_cache_conf_int(key: *u8, dflt: i64) -> i64 { 771 let lenp: *i64 = sys_mmap(16) as *i64 772 let cf: *u8 = sys_read_file("../knowledge/buildcache.conf" as *u8, lenp) 773 if (cf as i64) == 0 { return dflt } 774 let n: i64 = lenp[0] 775 var klen: i64 = 0 776 while key[klen] != (0 as u8) { klen = klen + 1 } 777 var i: i64 = 0 778 while i < n { 779 var at_start: i64 = 0 780 if i == 0 { at_start = 1 } 781 if i > 0 { if cf[i-1] == (10 as u8) { at_start = 1 } } 782 if at_start == 1 { 783 var k: i64 = 0 784 var hit: i64 = 1 785 while k < klen { 786 if i + k >= n { hit = 0; k = klen } 787 if hit == 1 { if cf[i+k] != key[k] { hit = 0; k = klen } } 788 if k < klen { k = k + 1 } 789 } 790 if hit == 1 { 791 var v: i64 = 0 792 var got: i64 = 0 793 var j: i64 = i + klen 794 var scanning: i64 = 1 795 while scanning == 1 { 796 if j >= n { scanning = 0 } 797 if scanning == 1 { 798 let c: i64 = cf[j] as i64 799 var isdig: i64 = 0 800 if c >= 48 { if c <= 57 { isdig = 1 } } 801 if isdig == 1 { v = v * 10 + (c - 48); got = 1; j = j + 1 } 802 if isdig == 0 { scanning = 0 } 803 } 804 } 805 if got == 1 { return v } 806 } 807 } 808 i = i + 1 809 } 810 return dflt 811} 812// cache_max_bytes: nonpositive is not a budget -> default (the conf cannot switch the janitor off by 0). 813func sbr_cache_budget() -> i64 { 814 let v: i64 = sbr_cache_conf_int("cache_max_bytes=" as *u8, SBR_CACHE_BUDGET_DEFAULT) 815 if v <= 0 { return SBR_CACHE_BUDGET_DEFAULT } 816 return v 817} 818// cache_enabled: 0 disables lookup AND store without a rebuild; any other value (or no row) = enabled. 819func sbr_cache_enabled() -> i64 { 820 let v: i64 = sbr_cache_conf_int("cache_enabled=" as *u8, 1) 821 if v == 0 { return 0 } 822 return 1 823} 824 825// Enforce the byte budget on _build/cache. Called ONLY after a successful store, so its cost rides 826// the slow path (a real compile just happened; one directory walk is noise beside it) and never the 827// hit path. Fail-open at every step: a janitor that cannot run must never break a build. 828func sbr_cache_prune() -> i64 { 829 let budget: i64 = sbr_cache_budget() 830 let dfd: i64 = __syscall(257, 0-100, "_build/cache" as *u8 as i64, 0x10000, 0, 0, 0) 831 if dfd < 0 { return 0 } 832 let mt: *i64 = sys_mmap(SBR_CACHE_PRUNE_SLOTS * 8) as *i64 833 let sz: *i64 = sys_mmap(SBR_CACHE_PRUNE_SLOTS * 8) as *i64 834 let no: *i64 = sys_mmap(SBR_CACHE_PRUNE_SLOTS * 8) as *i64 835 let arena: *u8 = sys_mmap(SBR_CACHE_PRUNE_SLOTS * SBR_CACHE_PATHW) 836 var ap: i64 = 0 837 var ne: i64 = 0 838 var overflow: i64 = 0 839 var total: i64 = 0 840 let dbuf: *u8 = sys_mmap(SBR_CACHE_DIRBUF) 841 var more: i64 = 1 842 while more == 1 { 843 let nb: i64 = sys_getdents64(dfd, dbuf, SBR_CACHE_DIRBUF) 844 if nb <= 0 { more = 0 } else { 845 var p: i64 = 0 846 while p < nb { 847 let reclen: i64 = (dbuf[p+16] as i64) + ((dbuf[p+17] as i64) * 256) 848 if reclen <= 0 { p = nb } else { 849 let nmp: *u8 = ((dbuf as i64) + p + 19) as *u8 850 var isdot: i64 = 0 851 if nmp[0] == (46 as u8) { if nmp[1] == (0 as u8) { isdot = 1 } } 852 if nmp[0] == (46 as u8) { if nmp[1] == (46 as u8) { if nmp[2] == (0 as u8) { isdot = 1 } } } 853 if isdot == 0 { 854 if ne >= SBR_CACHE_PRUNE_SLOTS { overflow = 1 } 855 if overflow == 0 { 856 let path: *u8 = ((arena as i64) + ap) as *u8 857 var q: i64 = 0 858 q = sbr_cat(path, q, "_build/cache/" as *u8) 859 var c: i64 = 0 860 var toolong: i64 = 0 861 while nmp[c] != (0 as u8) { 862 if q < SBR_CACHE_PATHW - 1 { path[q] = nmp[c]; q = q + 1 } 863 if q >= SBR_CACHE_PATHW - 1 { toolong = 1 } 864 c = c + 1 865 } 866 path[q] = 0 as u8 867 if toolong == 1 { 868 sbr_puts("[nx_sov_build_run] BUILD-CACHE-PRUNE SKIP-ENTRY: name exceeds the path slot (SBR_CACHE_PATHW) -- counted out of the census rather than stat'd through a truncated path 869" as *u8) 870 } 871 var fsz: i64 = 0 - 1 872 var fmt: i64 = 0 - 1 873 if toolong == 0 { fsz = sbr_filesize(path) } 874 if toolong == 0 { fmt = sbr_mtime(path) } 875 if fsz >= 0 { if fmt >= 0 { 876 mt[ne] = fmt 877 sz[ne] = fsz 878 no[ne] = ap 879 total = total + fsz 880 ne = ne + 1 881 ap = ap + SBR_CACHE_PATHW 882 } } 883 } 884 } 885 p = p + reclen 886 } 887 } 888 } 889 } 890 sys_close(dfd) 891 if overflow == 1 { 892 sbr_puts("[nx_sov_build_run] BUILD-CACHE-PRUNE SKIPPED: more entries than the enumeration pool (SBR_CACHE_PRUNE_SLOTS) -- pruning from a partial listing would evict by an incomplete ordering. Raise the pool or prune by hand.\n" as *u8) 893 return 0 894 } 895 if total <= budget { return 0 } 896 var evicted: i64 = 0 897 var freed: i64 = 0 898 var draining: i64 = 1 899 while draining == 1 { 900 if total <= budget { draining = 0 } 901 if draining == 1 { 902 var oldest: i64 = 0 - 1 903 var oldmt: i64 = 0 904 var i2: i64 = 0 905 while i2 < ne { 906 if sz[i2] >= 0 { 907 if oldest < 0 { oldest = i2; oldmt = mt[i2] } 908 if mt[i2] < oldmt { oldest = i2; oldmt = mt[i2] } 909 } 910 i2 = i2 + 1 911 } 912 if oldest < 0 { draining = 0 } 913 if oldest >= 0 { 914 let vp: *u8 = ((arena as i64) + no[oldest]) as *u8 915 if sys_unlinkat(vp) == 0 { 916 total = total - sz[oldest] 917 freed = freed + sz[oldest] 918 evicted = evicted + 1 919 } 920 sz[oldest] = 0 - 1 921 } 922 } 923 } 924 if evicted > 0 { 925 sbr_puts("[nx_sov_build_run] BUILD-CACHE-PRUNE evicted=" as *u8); sbr_putn(evicted) 926 sbr_puts(" freed=" as *u8); sbr_putn(freed) 927 sbr_puts("B budget=" as *u8); sbr_putn(budget) 928 sbr_puts("B kept=" as *u8); sbr_putn(ne - evicted) 929 sbr_puts(" (oldest-mtime-first; every entry regenerable by one compile)\n" as *u8) 930 } 931 return evicted 932} 933 934func main(argc: i64, argv: *i64) -> i64 { 935 if argc < 2 { sbr_puts("usage: nx_sov_build_run <module-basename> [--build-only] [--install] [--debug] [args-forwarded-to-program...] (--debug passes -g to nx_cc so the ELF carries .debug_line and nx_addr2line can name the faulting source line; lane flags may be combined)\n" as *u8); sys_exit(SBR_USAGE); return SBR_USAGE } 936 let name: *u8 = argv[1] as *u8 937 938 // ---- ANCHOR THE CWD 2026-08-07 ------------------------------------------------------------- 939 // EVERY path in this runner is relative to the build tree root: the source probes, the toolchain 940 // (_build/nx_cc_sovereign.elf), the admission binary, ../knowledge/tree_canon.conf, and -- decisively 941 // -- nx_cc's OWN import resolution for `import "nx_syscalls.nx"`. That is correct only when CWD is 942 // already the tree, which holds when a human runs it from buildroot/ and fails for every other 943 // caller: nx_job_run, the supervisor and any operator all start in the SERVING ROOT, where the same 944 // tree sits one level down under buildroot/. 945 // The first attempt at this added buildroot/ prefixes to the source probe. It moved the failure 946 // exactly one step -- SOURCE-NOT-FOUND became "BUILD ADMISSION DID NOT RUN (rc=127)", "TREE-CANON 947 // NOT CHECKED: ../knowledge/tree_canon.conf absent", then COMPILE-FAIL with an EMPTY .s and EMPTY 948 // stderr, because the compiler could not resolve the imports either. Prefixing one path fixed one 949 // path, and there were five. 950 // WHEN EVERY PATH IN A PROGRAM IS RELATIVE TO ONE DIRECTORY, THE FIX IS TO BE IN THAT DIRECTORY, 951 // NOT TO PREFIX EVERY PATH -- and the prefix version is worse than nothing, because it converts a 952 // loud SOURCE-NOT-FOUND into two silent PROCEEDING-UNGUARDED warnings and a misleading compile 953 // error. IT DISARMED TWO GUARDS TO REACH A FAILURE. 954 // Detect, do not assume: only chdir when runtime/ is genuinely absent here AND present under 955 // buildroot/, so a correct invocation from the tree root is completely unaffected. 956 // PROBE A LOAD-BEARING FILE, NOT A DIRECTORY NAME. The first version of this probe asked whether 957 // runtime/_hdl_build EXISTED and was satisfied by a NINE-FILE scratch directory sitting in the 958 // serving root beside the real 6,992-file tree in buildroot/. So the anchor never fired, and worse: 959 // left alone, this runner resolves runtime/_hdl_build/<name>.nx against that scratch dir and would 960 // compile a DIFFERENT tree from the one /api/build builds -- a forked copy reported as success, 961 // which is precisely what the tree-canon admission exists to prevent and which canon cannot see, 962 // because canon compares the laptop against buildroot and has never heard of this third directory. 963 // A DIRECTORY WITH THE RIGHT NAME IS NOT THE TREE; PROBE SOMETHING THE TREE CANNOT LACK. 964 // runtime/nx_syscalls.nx is imported by essentially every organ, so its presence identifies the 965 // real tree and its absence rules out any partial look-alike. 966 // ★ROOT FIX 2026-08-07 -- WHERE `_offc/` POINTS DEPENDS ON WHETHER WE ANCHORED. 967 // Everything below resolves `_offc/<name>.elf` relative to the CWD. When the anchor fires we are 968 // INSIDE buildroot/, so that path is buildroot/_offc/ -- a 106-file SHADOW of the serving root's 969 // 340-file _offc/, which is the one gates and organs actually fork. Two consequences, both 970 // MEASURED 2026-08-07: 971 // (1) --install printed "INSTALLED -> _offc/<name>.elf" and the consumer's copy was untouched. 972 // THE SUCCESS WORD WAS TRUE ABOUT THE COPY AND WRONG ABOUT THE DESTINATION. 973 // (2) Worse, LM-026's refresh-IF-PRESENT decides `do_install` by testing whether that same 974 // shadow path exists -- so for every organ whose twin lives in the SERVING _offc/, the 975 // probe missed, do_install stayed 0, and the rebuild silently did not reach the consumer. 976 // The staleness LM-026 was written to retire has been surviving its own fix. 977 // This prefix makes both the probe and the install name the directory consumers read. It is also 978 // why the toolchain incident this file records could happen at all: buildroot/_offc is REACHABLE, 979 // not inert, so writing there is not a harmless no-op -- it plants a shadow. 980 var offc_pfx: *u8 = "_offc/" as *u8 981 // ★ROOT FIX 2026-08-07 (second deploy location). THE ESTATE HAS TWO CONSUMER DIRECTORIES, and 982 // refresh-IF-PRESENT only ever knew about one. MEASURED: 1,652 .elf are served from the SERVING 983 // ROOT and only 110 from _offc/ -- and 1,551 organs have a ROOT twin with a source but NO _offc 984 // twin, so for 94% of everything deployed the LM-026 probe missed, do_install stayed 0, and a 985 // successful rebuild never reached the consumer. That is the estate's "1,557 deployed / 6 986 // CURRENT" adoption gap, and this line is its mechanism. 987 // A REFRESH THAT KNOWS ONE OF THE TWO PLACES ITS CONSUMERS READ IS BLIND TO MOST OF THEM. 988 var root_pfx: *u8 = "" as *u8 989 let probe_here: i64 = sys_openat_rd("runtime/nx_syscalls.nx" as *u8) 990 if probe_here < 0 { 991 let probe_br: i64 = sys_openat_rd("buildroot/runtime/nx_syscalls.nx" as *u8) 992 if probe_br >= 0 { 993 sys_close(probe_br) 994 sys_chdir("buildroot" as *u8) 995 offc_pfx = "../_offc/" as *u8 // we are now inside buildroot/; the consumers' _offc is one level up 996 root_pfx = "../" as *u8 // ...and the serving root, where 1,551 organs actually live 997 sbr_puts("[nx_sov_build_run] CWD anchored to buildroot/ (started in the serving root)\ 998" as *u8) 999 } 1000 } 1001 if probe_here >= 0 { sys_close(probe_here) } 1002 1003 // FLAGS (argv[2]): --build-only (--b*) = skip the run; --install (--i*) = FORCE-install /tmp/<name>.sov.elf 1004 // to _offc/<name>.elf even with NO existing twin (makes a reusable TOOL permanent on first build) + skip run. 1005 // Default = refresh-IF-PRESENT (LM-026) + run. Opt-in so throwaway gates/probes never clutter _offc. 1006 // Everything AFTER the optional flag is FORWARDED to the built program (fwd_start below). 1007 var force_install: i64 = 0 1008 var skip_run: i64 = 0 1009 // --build-only MUST MEAN BUILD ONLY (2026-08-26). Tracked SEPARATELY from skip_run because --install 1010 // also skips the run yet is an explicit, deliberate request TO install -- so skip_run cannot carry 1011 // this meaning. nx_builddeploy_lib owns the resulting decision. 1012 var build_only: i64 = 0 1013 var want_debug: i64 = 0 1014 var want_release: i64 = 0 1015 var fwd_start: i64 = 2 1016 // LANE FLAGS ARE A LOOP, NOT A SLOT (2026-08-15). This read argv[2] ONLY, so a SECOND lane flag was 1017 // silently FORWARDED TO THE BUILT PROGRAM instead of consumed: `--build-only --debug` would have 1018 // compiled WITHOUT debug and passed "--debug" to the target as a program argument. One slot is not a 1019 // parser, and the defect is invisible because both halves succeed at something. 1020 // A lane flag is recognised by its '--' prefix; the first non-flag argument ends the lane's section 1021 // and everything from there is forwarded. With no flags fwd_start stays 2, so the default path is 1022 // byte-identical to the single-slot version it replaces. 1023 // --timeout-ms <n> overrides the build deadline. It keys on 't' because --debug already owns 'd', 1024 // and it is the ONLY lane flag that CONSUMES A VALUE -- hence `extra`, since advancing by one 1025 // would forward the number to the built program as an argument (the exact single-slot defect the 1026 // comment above records). 1027 var deadline_ms: i64 = SBR_BUILD_DEADLINE_MS 1028 var no_cache: i64 = 0 1029 var fi: i64 = 2 1030 var scanning: i64 = 1 1031 while scanning == 1 { 1032 if fi >= argc { scanning = 0 } else { 1033 let fl: *u8 = argv[fi] as *u8 1034 if fl[0] != (45 as u8) { scanning = 0 } else { 1035 if fl[1] != (45 as u8) { scanning = 0 } else { 1036 var extra: i64 = 0 1037 if fl[2] == (98 as u8) { skip_run = 1; build_only = 1 } // --build-only 1038 if fl[2] == (105 as u8) { force_install = 1; skip_run = 1 } // --install 1039 if fl[2] == (100 as u8) { want_debug = 1 } // --debug -> -g to nx_cc 1040 if fl[2] == (110 as u8) { no_cache = 1 } // --no-cache: skip the B2 lookup AND store 1041 if fl[2] == (114 as u8) { want_release = 1 } // --release -> a release build even when the incumbent is debug (announced below) 1042 if fl[2] == (116 as u8) { // --timeout-ms <n> 1043 if (fi + 1) >= argc { 1044 sbr_puts("[nx_sov_build_run] REFUSED: --timeout-ms needs a value in milliseconds.\n" as *u8) 1045 sys_exit(SBR_USAGE); return SBR_USAGE 1046 } 1047 let dv: i64 = sbr_atoi(argv[fi + 1] as *u8) 1048 if dv < 0 { 1049 sbr_puts("[nx_sov_build_run] REFUSED: --timeout-ms value must be a plain decimal count of milliseconds.\n" as *u8) 1050 sys_exit(SBR_USAGE); return SBR_USAGE 1051 } 1052 deadline_ms = dv 1053 extra = 1 1054 } 1055 fi = fi + 1 + extra 1056 fwd_start = fi 1057 } 1058 } 1059 } 1060 } 1061 // THE FLAVOUR FOLLOWS THE INCUMBENT (2026-09-05, operator: "first byte fix"). A build's debug/release flavour used to be 1062 // a per-call flag nobody declares per target, so a rebuild that omitted --debug silently produced the OTHER flavour of 1063 // the live binary and /api/promote then read the swap as CAPLOSS 422 permil (nx_wgsl: 823 lost runs, every one a source 1064 // path, a symbol name or a DWARF section name, lost_other=0). A seat then either rebuilt or passed allow_capability_loss 1065 // and disarmed the one guard that catches a real regression. Now, with neither --debug nor --release given, the flavour 1066 // is READ FROM THE INCUMBENT'S BYTES (root_pfx + name + .elf, the serving-root twin this runner holds or refreshes): 1067 // the DWARF line-table section name present = debug. No incumbent = release, the historical default. Every path 1068 // ANNOUNCES flavour= and src= so a reader can tell a derived flavour from a declared one; --release is the explicit 1069 // switch. The announce strings deliberately never spell the section name contiguously (sbr_incumbent_flavour's note). 1070 var flavour_src: *u8 = "argv --debug" as *u8 1071 if want_release == 1 { want_debug = 0; flavour_src = "argv --release" as *u8 } 1072 if want_release == 0 { 1073 if want_debug == 0 { 1074 let incp: *u8 = sys_mmap(256); var io: i64 = 0 1075 io = sbr_cat(incp, io, root_pfx); io = sbr_cat(incp, io, name); io = sbr_cat(incp, io, ".elf" as *u8); incp[io] = 0 as u8 1076 let ifl: i64 = sbr_incumbent_flavour(incp) 1077 if ifl == 1 { want_debug = 1; flavour_src = "incumbent (the serving-root twin carries a DWARF line table)" as *u8 } 1078 if ifl == 0 { flavour_src = "incumbent (the serving-root twin carries no DWARF line table)" as *u8 } 1079 if ifl < 0 { flavour_src = "default (no incumbent to read)" as *u8 } 1080 sys_munmap(incp, 256) 1081 } 1082 } 1083 sbr_puts("[nx_sov_build_run] FLAVOUR " as *u8) 1084 if want_debug == 1 { sbr_puts("debug" as *u8) } else { sbr_puts("release" as *u8) } 1085 sbr_puts(" src=" as *u8); sbr_puts(flavour_src); sbr_puts("\n" as *u8) 1086 // ANNOUNCE THE FEATURE, NOT ONLY ITS FAILURE (the 2026-08-07 law): if this line is absent when 1087 // --debug was passed, the FLAG PARSE missed it -- which is otherwise indistinguishable from the 1088 // compiler ignoring -g, and those have opposite remedies. 1089 if want_debug == 1 { sbr_puts("[nx_sov_build_run] DEBUG BUILD: -g -> nx_cc emits .file/.loc -> nxasm builds .debug_line -> nx_addr2line resolves a fault address to file:line.\n" as *u8) } 1090 // ANNOUNCE A NON-DEFAULT BOUND (same law as --debug above). Deliberately SILENT on the default so 1091 // the ordinary build's output stays byte-identical for anything that parses it -- a safety line 1092 // that regresses every caller's log is not safety. An UNBOUNDED deadline always announces. 1093 if deadline_ms != SBR_BUILD_DEADLINE_MS { 1094 sbr_puts("[nx_sov_build_run] build deadline OVERRIDDEN to " as *u8); sbr_putn(deadline_ms) 1095 if deadline_ms <= 0 { sbr_puts("ms = UNBOUNDED: a hanging tool will burn a core until a human notices.\n" as *u8) } 1096 if deadline_ms > 0 { sbr_puts("ms per compile/assemble step.\n" as *u8) } 1097 } 1098 1099 let src: *u8 = sys_mmap(512); var o: i64 = 0 1100 o = sbr_cat(src, o, "runtime/_hdl_build/" as *u8); o = sbr_cat(src, o, name); o = sbr_cat(src, o, ".nx" as *u8); src[o] = 0 as u8 1101 // fall back to runtime/<name>.nx if the module isn't under _hdl_build (additive; the older slice stack lives in runtime/) 1102 let chk: i64 = sys_openat_rd(src) 1103 if chk < 0 { 1104 o = 0 1105 o = sbr_cat(src, o, "runtime/" as *u8); o = sbr_cat(src, o, name); o = sbr_cat(src, o, ".nx" as *u8); src[o] = 0 as u8 1106 } 1107 if chk >= 0 { sys_close(chk) } 1108 // 2nd fallback: nxasm/<name>.nx -- so the TOOLCHAIN itself (assembler/linker) is built 1109 // through THIS runner's retry guard, never direct 1-shot (2026-06-09 lesson: a direct 1110 // unguarded nxasm rebuild handed back a nondeterministic miscompile that exited pre-pass0). 1111 let chk2: i64 = sys_openat_rd(src) 1112 if chk2 < 0 { 1113 o = 0 1114 o = sbr_cat(src, o, "nxasm/" as *u8); o = sbr_cat(src, o, name); o = sbr_cat(src, o, ".nx" as *u8); src[o] = 0 as u8 1115 } 1116 if chk2 >= 0 { sys_close(chk2) } 1117 // 3rd fallback: runtime/wiki/<name>.nx -- the internal wiki engine (nx_wiki_main) and 1118 // its render organs live here, NOT in runtime/ or _hdl_build/. Mirrors the fallbacks 1119 // above exactly (reopen src; if still missing, rewrite to the next candidate path). 1120 // Added 2026-06-15 (a wiki organ otherwise mis-compiled on a bogus nxasm/<name>.nx path 1121 // and surfaced as a misleading "COMPILE-FAIL (empty .s)"). 1122 let chk3: i64 = sys_openat_rd(src) 1123 if chk3 < 0 { 1124 o = 0 1125 o = sbr_cat(src, o, "runtime/wiki/" as *u8); o = sbr_cat(src, o, name); o = sbr_cat(src, o, ".nx" as *u8); src[o] = 0 as u8 1126 } 1127 if chk3 >= 0 { sys_close(chk3) } 1128 // (The buildroot/ path-prefix fallbacks that briefly lived here were REMOVED: the CWD is anchored 1129 // once at the top of main instead, which fixes the source probe, the toolchain, the admission 1130 // binary, tree_canon.conf and nx_cc's import resolution together rather than one of the five.) 1131 // FINAL existence verdict: if NONE of the candidate paths resolved to a real file, fail 1132 // LOUD with SOURCE-NOT-FOUND rather than running the compiler on a non-existent path 1133 // (which produces an empty .s and the misleading "COMPILE-FAIL" above). Fail-fast at the 1134 // boundary (Cardinal 12 + Cardinal 20: a build that can't find its source must say so). 1135 let chkf: i64 = sys_openat_rd(src) 1136 if chkf < 0 { 1137 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name) 1138 sbr_puts(": SOURCE-NOT-FOUND (probed runtime/_hdl_build/, runtime/, nxasm/, runtime/wiki/ -- relative to CWD, which is anchored to the build tree at startup)\n" as *u8) 1139 sys_exit(SBR_USAGE); return SBR_USAGE 1140 } 1141 sys_close(chkf) 1142 // BUILD OUTPUT LIVES IN THE REPO, NOT /tmp (operator 2026-07-27). WSL's /tmp is wiped 1143 // between sessions, which silently deleted built ELFs mid-run and made scripts that 1144 // referenced them fail in confusing ways (a documented recurring trap). `_build/` is 1145 // repo-local and durable; mkdir is idempotent (EEXIST is fine, hence the ignored rc). 1146 sys_mkdir("_build\x00" as *u8, 493) 1147 // PER-TARGET BUILD LOCK (seq1260, 2026-07-29): two concurrent builds of the SAME target used to 1148 // interleave on _build/<name>.{s,sov.elf} -- one overwrote the other's artifact MID-SWEEP and a 1149 // BD control curve read garbage (the /api/build shared-capture class at the local tier). Blocking 1150 // flock on _build/<name>.lock serializes per target, held through compile->assemble->install and 1151 // RELEASED before the run phase (a long-running target must never wedge future rebuilds; an 1152 // already-running process keeps its inode across the atomic rename, so rebuild-under-run is safe). 1153 // Cross-target builds never contend; process exit releases (crash-safe); the lock file is NEVER 1154 // unlinked (the documented lock-file law). 1155 let lockpath: *u8 = sys_mmap(256); o = 0 1156 o = sbr_cat(lockpath, o, "_build/" as *u8); o = sbr_cat(lockpath, o, name); o = sbr_cat(lockpath, o, ".lock" as *u8); lockpath[o] = 0 as u8 1157 let lockfd: i64 = sys_openat_wr(lockpath, 0x1a4) 1158 if lockfd >= 0 { sys_flock(lockfd, SYS_LOCK_EX) } 1159 let spath: *u8 = sys_mmap(256); o = 0 1160 o = sbr_cat(spath, o, "_build/" as *u8); o = sbr_cat(spath, o, name); o = sbr_cat(spath, o, ".s" as *u8); spath[o] = 0 as u8 1161 let elfpath: *u8 = sys_mmap(256); o = 0 1162 o = sbr_cat(elfpath, o, "_build/" as *u8); o = sbr_cat(elfpath, o, name); o = sbr_cat(elfpath, o, ".sov.elf" as *u8); elfpath[o] = 0 as u8 1163 // FAIL-LOUD (seq132, 2026-07-19): remove any STALE _build/<name>.sov.elf from a prior build BEFORE 1164 // compiling, so a failed build can never leave the previous working binary behind to be staged as a 1165 // false "BUILT" (the masking trap that cost a 3-reship cascade). 1166 // 1167 // ROOT FIX seq363 (2026-07-30): this used to TRUNCATE the stale artifact to 0 bytes via O_TRUNC and 1168 // leave it there. That achieved the anti-staleness goal but replaced one fail-open with a weaker one: 1169 // after a COMPILE-FAIL a 0-byte file REMAINED on disk, so `does the elf exist?` -- the check every 1170 // naive caller actually writes -- still answered YES for a build that produced nothing. Measured 1171 // 2026-07-30: a deliberately-broken target left _build/<t>.sov.elf at 0 bytes, and separately a PIPE 1172 // swallows this runner's exit code, so neither the artifact nor `$?` was trustworthy. 1173 // 1174 // UNLINK instead. The invariant becomes the one callers already assume: THE ARTIFACT EXISTS IF AND 1175 // ONLY IF THE BUILD SUCCEEDED. Downstream ELF-magic/size guards (nx_hostctl cmd_buildrun, /api/promote, 1176 // md_tc_elf_size) all still hold -- this makes them belt-and-suspenders rather than load-bearing. 1177 // Success path is unchanged: the atomic rename below creates the file fresh. 1178 // MOVED 2026-09-05 (measured on nx_goalmap_gate the day it was built): this unlink used to run HERE, BEFORE 1179 // build admission, tree-canon admission and the build-cache check -- so an admission REFUSAL (which is not 1180 // a build failure) destroyed the prior fossil, and every drift and staleness instrument that compares 1181 // against _build/<t>.sov.elf then measured against an absence (CLAUDE.md 2026-08-28 and 2026-09-04; debt 1182 // 1787078015 recurrence). The unlink now sits immediately before the compile loop, after every refusal has 1183 // had its say and only on a cache MISS, so THE ARTIFACT EXISTS IFF THE LAST ATTEMPT THAT REACHED THE 1184 // COMPILER SUCCEEDED -- the invariant callers already assume, now also true across refusals. 1185 1186 // SOVEREIGN compiler (self-hosted), NOT nx_cc_known_good (= the C 1187 // bootstrap, FORBIDDEN on the build path per operator law -- C is 1188 // for benchmarking only). Fixed 2026-06-09 during C2-deploy. 1189 let compiler: *u8 = "_offc/nx_cc_sovereign.elf" as *u8 1190 // the CURRENT (post-cl-shift-fix, 2026-06-09) sovereign assembler. The older _offc/nxasm_x86.elf 1191 // (2026-05-30) systemically mis-encodes registers->r15 and segfaults even ret-42 -- do NOT use it. 1192 let asm_tool: *u8 = "_offc/nxasm_x86_main.elf" as *u8 1193 1194 let envp: *i64 = sys_mmap(8*4) as *i64 1195 envp[0] = "PATH=/usr/bin:/bin" as *u8 as i64; envp[1] = 0 1196 1197 let devnull: i64 = sys_openat_wr("/dev/null" as *u8, 0x1a4) // mute nx_cc's symbol-table dump 1198 1199 // ---- BUILD ADMISSION (2026-08-01): consult nx_build_admit BEFORE forking the compiler. 1200 // MEASURED THE NIGHT THIS LANDED: load average 132.58, 334MB available of 36GB, four concurrent 1201 // compiles -- builds were being OOM-killed mid-flight for every seat sharing this host, and two of 1202 // mine died that way. nx_build_admit has existed since 2026-07-30 and NOTHING called it: its own 1203 // header names ma_do_build as the filed rung, and THIS runner -- the path agents actually invoke -- 1204 // was never wired either. A COMPILE IS A HEAVY LAUNCH. 1205 // Refuse LOUDLY rather than pile on and be killed. That is the memfloor law already on the board: 1206 // REFUSE, NEVER SILENTLY SHRINK. A build that never starts is recoverable; a wedged host is not. 1207 // 0 GRANT | 3 DENY-MEM (below the memory floor) | 4 QUEUE (D-state I/O storm, run-queue saturation, or the storm ceiling -- NOT plain 1-minute load: the conf sets max_centiload unreachable) 1208 // 5 CANNOT-MEASURE (unreadable /proc -> fail-CLOSED by construction, never wave through) 1209 // FAIL-OPEN ON ABSENCE ONLY: a missing admitter makes execve return 127 and we proceed, so a tree 1210 // without it still builds -- but any verdict it DOES return is obeyed. Absence is not permission. 1211 let sbr_admit: *u8 = "_build/nx_build_admit.sov.elf" as *u8 1212 // THRESHOLDS ARE EXPLICIT, AND ONLY THE CAUSAL ONE IS ARMED (2026-08-01). 1213 // MEMORY FLOOR 512MB IS ARMED: it is the DIRECTLY MEASURED cause -- builds were OOM-killed 1214 // tonight at 334MB available, which is below this floor, so this check would have refused 1215 // exactly the builds that died instead of letting them pile on and be killed. 1216 // LOAD CEILING IS DELIBERATELY DISABLED (1000000 centiload = load 10000, unreachable) because 1217 // it is UNCALIBRATED for this host: the admitter default is 400 (load 4.00) while this Synology 1218 // IDLES at 17.62/24.80/36.19 and only wedged at 132.58. Arming it at the default would refuse 1219 // every build for every seat -- including this runner own rebuild, a self-bricking guard. 1220 // Picking a number that merely produces the outcome I want would be FITTING, NOT MODELLING. 1221 // TO ARM IT: sample /proc/loadavg over a representative window, set the ceiling above the normal 1222 // distribution and below the wedge point, and record the measurement that justifies the number. 1223 let sbr_aargv: *i64 = sys_mmap(8*6) as *i64 1224 sbr_aargv[0] = sbr_admit as i64 1225 sbr_aargv[1] = "check" as *u8 as i64 1226 // NO THRESHOLDS PASSED (2026-08-18). The comment that stood here said "if this number ever moves, 1227 // move BOTH" -- the very sentence that proves two copies were one too many (and mgmt's max was 1228 // 100000 while this one was 1000000: they had already drifted). nx_build_admit now reads THE ONE 1229 // envelope from knowledge/build_admit.conf (../knowledge/ from this buildroot-anchored CWD) and 1230 // prints envelope_src=conf; every caller that passes nothing gets the same bar as /api/build. 1231 sbr_aargv[2] = 0 1232 var sbr_arc: i64 = sbr_run(sbr_admit, sbr_aargv, envp, 0 - 1, 0 - 1, deadline_ms) 1233 // DURABLE FALLBACK (2026-09-03). The admitter above is the _build FOSSIL, and A REFUSED BUILD DELETES 1234 // THAT FOSSIL -- so one refusal silently DISARMS THIS GUARD for the next build, precisely when the box 1235 // is busiest and the guard matters most. MEASURED THIS DAY, on a genuinely storming host: 1236 // BUILD ADMISSION DID NOT RUN (rc=127 ...). PROCEEDING UNGUARDED 1237 // solely because an earlier refusal had eaten the artifact. The fail-open-on-absence rule documented 1238 // above is deliberate and STAYS -- a tree that has never built the admitter must still bootstrap. 1239 // But ABSENCE-BY-DELETION IS NOT ABSENCE-BY-BOOTSTRAP, and the PROMOTED binary is the durable copy that 1240 // survives a refusal. CWD is buildroot, so the serving root is one level up. 1241 // STRICTLY ADDITIVE BY CONSTRUCTION: it runs only when the first attempt found NOTHING to run, so it can 1242 // only ever ADD a guard where there was none. A present fossil behaves exactly as before, and a tree 1243 // missing both copies now refuses before compilation. 1244 let sbr_rc_notfound: i64 = 127 1245 if sbr_arc == sbr_rc_notfound { 1246 let sbr_admit2: *u8 = "../nx_build_admit.elf" as *u8 1247 sbr_aargv[0] = sbr_admit2 as i64 1248 sbr_arc = sbr_run(sbr_admit2, sbr_aargv, envp, 0 - 1, 0 - 1, deadline_ms) 1249 if sbr_arc != sbr_rc_notfound { 1250 sbr_puts("[nx_sov_build_run] admission fossil absent (a refused build deletes it); GUARDED by the PROMOTED ../nx_build_admit.elf instead.\n" as *u8) 1251 } 1252 } 1253 // EXIT IS SBR_ADMIT_REFUSED(6) FOR ALL THREE DENIALS (restored in the 2026-08-03 fork merge -- 1254 // the NAS branch had regressed to returning the admitter's raw 3/4/5, which COLLIDE with 1255 // COMPILE_FAIL(3)/ASM_FAIL(4): a wait-and-retry signal decoding as a broken build). The REASON 1256 // stays in the message; the code says only "admission refused, not a build failure". 1257 if sbr_arc == 3 { 1258 sbr_puts("[nx_sov_build_run] REFUSED-BUILD-ADMIT rc=3 DENY-MEM -- available memory is BELOW THE FLOOR. Compiling now risks wedging the HOST, not just this build. Wait for headroom and retry.\n" as *u8) 1259 sys_exit(SBR_ADMIT_REFUSED); return SBR_ADMIT_REFUSED 1260 } 1261 if sbr_arc == 4 { 1262 sbr_puts("[nx_sov_build_run] REFUSED-BUILD-ADMIT rc=4 QUEUE -- the BUILD-ADMIT report ABOVE names which conjunct fired (D-state I/O storm, run-queue saturation, or the storm ceiling). THIS RUNNER DELIBERATELY DOES NOT RESTATE THE CAUSE: a hand-copied paraphrase of another organ's verdict drifts from it silently and sends every reader at the wrong cause -- and this line used to name the 1-minute load ceiling, which the shared conf sets UNREACHABLE, so it named the one conjunct that CANNOT fire. Nothing is queued by THIS runner: re-issue once the box clears (admission re-measures per call); pace re-issues, never spin.\n" as *u8) 1263 sys_exit(SBR_ADMIT_REFUSED); return SBR_ADMIT_REFUSED 1264 } 1265 if sbr_arc == 5 { 1266 sbr_puts("[nx_sov_build_run] REFUSED-BUILD-ADMIT rc=5 CANNOT-MEASURE -- /proc unreadable, so admission FAILS CLOSED by construction. A guard that cannot measure must refuse, never wave through.\n" as *u8) 1267 sys_exit(SBR_ADMIT_REFUSED); return SBR_ADMIT_REFUSED 1268 } 1269 if bci_resource_allowed(sbr_arc) != 1 { 1270 sbr_puts("[nx_sov_build_run] REFUSED-BUILD-ADMIT detector_rc=" as *u8); sbr_putn(sbr_arc) 1271 sbr_puts(" -- no explicit GRANT. Restore the admitter or resolve its failure; bootstrap must provision admission before compiling. No compiler launched.\n" as *u8) 1272 sys_exit(SBR_ADMIT_REFUSED); return SBR_ADMIT_REFUSED 1273 } 1274 1275 // ---- TREE-CANON ADMISSION (2026-08-03, debt 1785622769): a build must never compile a copy 1276 // that diverges from canon. ../knowledge/tree_canon.conf (cwd is buildroot; the conf lives at 1277 // the nishihost root) lists tree-root-relative paths that MUST be byte-identical across every 1278 // tree that can build them. Row grammar: '#' comment, blank ignored, '!path' = FREEZE EVERY 1279 // BUILD while divergent (shared infrastructure -- a fork there miscompiles everything 1280 // downstream), 'path' = refuse only the build OF THAT FILE (a lane's own divergence must not 1281 // block unrelated targets). The other tree's sizes come from the last pushed authoring 1282 // manifest (../knowledge/status/treecanon_laptop.mf, produced by nx_treediff on that tree). 1283 // SIZE IS A SCREEN, NOT PROOF OF IDENTITY (nx_treediff's own declared bound) -- equal-size 1284 // rewrites pass here; nx_treecanon_gate stays the tree-level instrument. 1285 // ⚠the manifest is AS FRESH AS ITS LAST PUSH: a stale one can false-pass a scoped row. The 1286 // authoring loop owns pushing it after edits; this check is the floor, not the ceiling. 1287 // Admission requires a valid nonempty rulebook and SHA256 manifest. Bootstrap provisions these 1288 // inputs before using the runner. A size screen remains diagnostic history, not content proof. 1289 let cn_conf_l: *i64 = sys_mmap(16) as *i64 1290 let cn_conf: *u8 = sys_read_file("../knowledge/tree_canon.conf" as *u8, cn_conf_l) 1291 let cn_mf_l: *i64 = sys_mmap(16) as *i64 1292 let cn_mf: *u8 = sys_read_file("../knowledge/status/treecanon_laptop.mf" as *u8, cn_mf_l) 1293 // The DIGEST manifest (nx_treehash on the authoring tree). When present it WINS: it decides 1294 // identity by content, which is the only thing a size screen cannot do. 1295 let cn_hmf_l: *i64 = sys_mmap(16) as *i64 1296 let cn_hmf: *u8 = sys_read_file("../knowledge/status/treecanon_laptop_hash.mf" as *u8, cn_hmf_l) 1297 let cn_rules: i64 = bci_conf_rows(cn_conf, cn_conf_l[0], SBR_CANON_PATH_BYTES - SBR_RUNTIME_PREFIX_BYTES - 1) 1298 if cn_rules <= 0 { 1299 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON INPUT: rulebook missing, empty, malformed or path out of bounds. Provision ../knowledge/tree_canon.conf; no compiler launched.\n" as *u8) 1300 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1301 } 1302 if (cn_hmf as i64) == 0 { 1303 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON INPUT: SHA256 manifest missing. Size-only evidence cannot admit a build; provision ../knowledge/status/treecanon_laptop_hash.mf.\n" as *u8) 1304 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1305 } 1306 if cn_hmf_l[0] <= 0 { 1307 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON INPUT: SHA256 manifest empty; no compiler launched.\n" as *u8) 1308 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1309 } 1310 sbr_puts("[nx_sov_build_run] TREE-CANON RULEBOOK VALID rules=" as *u8); sbr_putn(cn_rules); sbr_puts(" SHA256-evidence=loaded; relevant rows checked below\n" as *u8) 1311 var cn_have: i64 = 0 1312 if (cn_mf as i64) != 0 { cn_have = 1 } 1313 if (cn_hmf as i64) != 0 { cn_have = 1 } 1314 if (cn_conf as i64) != 0 { if cn_have == 1 { 1315 // the canon rows are relative to the runtime root; src is "runtime/<rel>" for every probe 1316 // path except the nxasm/ fallback (toolchain sources are not canon-governed rows today) 1317 var cn_isrt: i64 = 1 1318 let cn_rt: *u8 = "runtime/" as *u8 1319 var cn_i: i64 = 0 1320 while cn_i < 8 { if src[cn_i] != cn_rt[cn_i] { cn_isrt = 0 } cn_i = cn_i + 1 } 1321 var cn_srclen: i64 = 0 1322 while src[cn_srclen] != (0 as u8) { cn_srclen = cn_srclen + 1 } 1323 let cn_path: *u8 = sys_mmap(SBR_CANON_PATH_BYTES) 1324 let cn_cl: i64 = cn_conf_l[0] 1325 let cn_ml: i64 = cn_mf_l[0] 1326 var cn_p: i64 = 0 1327 while cn_p < cn_cl { 1328 var cn_e: i64 = cn_p 1329 var cn_go: i64 = 1 1330 while cn_go == 1 { 1331 if cn_e >= cn_cl { cn_go = 0 } 1332 if cn_go == 1 { if cn_conf[cn_e] == (10 as u8) { cn_go = 0 } } 1333 if cn_go == 1 { cn_e = cn_e + 1 } 1334 } 1335 var cn_len: i64 = cn_e - cn_p 1336 if cn_len > 0 { if cn_conf[cn_p + cn_len - 1] == (13 as u8) { cn_len = cn_len - 1 } } // CRLF-tolerant 1337 var cn_frozen: i64 = 0 1338 var cn_ps: i64 = cn_p 1339 if cn_len > 0 { if cn_conf[cn_ps] == (33 as u8) { cn_frozen = 1; cn_ps = cn_ps + 1; cn_len = cn_len - 1 } } 1340 var cn_live: i64 = 0 1341 if cn_len > 0 { if cn_conf[cn_ps] != (35 as u8) { cn_live = 1 } } 1342 if cn_live == 1 { 1343 // relevant = frozen row, OR the row IS the file this build compiles 1344 var cn_rel: i64 = cn_frozen 1345 if cn_isrt == 1 { if sbr_ceq_at(src, 8, cn_srclen - 8, cn_conf, cn_ps, cn_len) == 1 { cn_rel = 1 } } 1346 if cn_rel == 1 { 1347 var cq: i64 = 0 1348 cq = sbr_cat(cn_path, cq, "runtime/" as *u8) 1349 var ck: i64 = 0 1350 while ck < cn_len { cn_path[cq] = cn_conf[cn_ps + ck]; cq = cq + 1; ck = ck + 1 } 1351 cn_path[cq] = 0 as u8 1352 let cn_nas: i64 = sbr_filesize(cn_path) 1353 var cn_found: i64 = 0 1354 var cn_lap: i64 = 0 - 1 1355 var cn_div: i64 = 0 1356 var cn_hmode: i64 = 0 1357 var cn_hash_ok: i64 = 0 1358 var cn_matches: i64 = 0 1359 if (cn_hmf as i64) != 0 { cn_hmode = 1 } 1360 let cn_lhex: *u8 = sys_mmap(128) 1361 let cn_mhex: *u8 = sys_mmap(128) 1362 // ---- CONTENT MODE: digest rows are "<64hex> <bytes> <relpath>" ---- 1363 if cn_hmode == 1 { 1364 var hq: i64 = 0 1365 while hq < SBR_SHA_HEX { cn_mhex[hq] = SBR_QMARK as u8; hq = hq + 1 } 1366 cn_mhex[SBR_SHA_HEX] = 0 as u8 1367 let cn_hash_rc: i64 = sbr_sha_hex(cn_path, cn_lhex) 1368 if cn_hash_rc == 0 { cn_hash_ok = 1 } 1369 if cn_hash_rc != 0 { 1370 var hz: i64 = 0 1371 while hz < SBR_SHA_HEX { cn_lhex[hz] = SBR_QMARK as u8; hz = hz + 1 } 1372 cn_lhex[SBR_SHA_HEX] = 0 as u8 1373 } 1374 var hp: i64 = 0 1375 let cn_hl: i64 = cn_hmf_l[0] 1376 while hp < cn_hl { 1377 var he: i64 = hp 1378 var hg: i64 = 1 1379 while hg == 1 { 1380 if he >= cn_hl { hg = 0 } 1381 if hg == 1 { if cn_hmf[he] == (10 as u8) { hg = 0 } } 1382 if hg == 1 { he = he + 1 } 1383 } 1384 var hl2: i64 = he - hp 1385 if hl2 > 0 { if cn_hmf[hp + hl2 - 1] == (13 as u8) { hl2 = hl2 - 1 } } 1386 if hl2 > SBR_SHA_HEX + 2 { 1387 // the SECOND space ends the size field; the relpath follows it 1388 var s2: i64 = 0 - 1 1389 var hi2: i64 = SBR_SHA_HEX + 1 1390 while hi2 < hl2 { if s2 < 0 { if cn_hmf[hp + hi2] == (32 as u8) { s2 = hi2 } } hi2 = hi2 + 1 } 1391 if s2 > 0 { 1392 if sbr_ceq_at(cn_hmf, hp + s2 + 1, hl2 - s2 - 1, cn_conf, cn_ps, cn_len) == 1 { 1393 if bci_hash_row(cn_hmf, hp, hl2) != 1 { 1394 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON EVIDENCE: malformed SHA256 row for " as *u8); sbr_puts(cn_path); sbr_puts("\n" as *u8) 1395 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1396 } 1397 cn_found = 1 1398 cn_matches = cn_matches + 1 1399 var hk: i64 = 0 1400 while hk < SBR_SHA_HEX { cn_mhex[hk] = cn_hmf[hp + hk]; hk = hk + 1 } 1401 } 1402 } 1403 } 1404 hp = he + 1 1405 } 1406 if cn_found == 1 { 1407 var hd: i64 = 0 1408 while hd < SBR_SHA_HEX { if cn_lhex[hd] != cn_mhex[hd] { cn_div = 1 } hd = hd + 1 } 1409 } 1410 } 1411 // ---- SIZE MODE (unchanged): only when no digest manifest was published ---- 1412 if cn_hmode == 0 { 1413 var mp: i64 = 0 1414 while mp < cn_ml { 1415 var me: i64 = mp 1416 var mg: i64 = 1 1417 while mg == 1 { 1418 if me >= cn_ml { mg = 0 } 1419 if mg == 1 { if cn_mf[me] == (10 as u8) { mg = 0 } } 1420 if mg == 1 { me = me + 1 } 1421 } 1422 var ml2: i64 = me - mp 1423 if ml2 > 0 { if cn_mf[mp + ml2 - 1] == (13 as u8) { ml2 = ml2 - 1 } } 1424 // split at the first space 1425 var ms: i64 = 0 - 1 1426 var mi: i64 = 0 1427 while mi < ml2 { if ms < 0 { if cn_mf[mp + mi] == (32 as u8) { ms = mi } } mi = mi + 1 } 1428 if ms > 0 { 1429 if sbr_ceq_at(cn_mf, mp + ms + 1, ml2 - ms - 1, cn_conf, cn_ps, cn_len) == 1 { 1430 cn_found = 1 1431 var mv: i64 = 0 1432 var md: i64 = 0 1433 while md < ms { mv = mv * 10 + ((cn_mf[mp + md] as i64) - 48); md = md + 1 } 1434 cn_lap = mv 1435 } 1436 } 1437 mp = me + 1 1438 } 1439 if cn_found == 1 { if cn_lap != cn_nas { cn_div = 1 } } 1440 } 1441 // Timestamps cannot repair missing, duplicate or unreadable evidence. 1442 if cn_matches != 1 { 1443 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON EVIDENCE: expected one SHA256 row for " as *u8); sbr_puts(cn_path) 1444 sbr_puts(" matches=" as *u8); sbr_putn(cn_matches); sbr_puts("\n" as *u8) 1445 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1446 } 1447 if cn_nas <= 0 { 1448 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON EVIDENCE: source absent or empty: " as *u8); sbr_puts(cn_path); sbr_puts("\n" as *u8) 1449 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1450 } 1451 if cn_hash_ok != 1 { 1452 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON EVIDENCE: source digest unreadable: " as *u8); sbr_puts(cn_path); sbr_puts("\n" as *u8) 1453 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1454 } 1455 // a canon row ABSENT from the authoring manifest is divergent in EITHER mode 1456 if cn_found == 0 { cn_div = 1 } 1457 if cn_nas == 0 { cn_div = 1 } 1458 // ---- STALENESS IS NOT A FORK (2026-08-07) ------------------------------------------ 1459 // This guard REFUSED on any content difference whatever, and the manifest it compares 1460 // against is a snapshot of ONE laptop refreshed by a SessionStart hook. So one seat 1461 // saving a widely-imported file made EVERY build of EVERY dependent target fail for 1462 // EVERY seat until somebody re-ran the manifest push. Measured live: another seat was 1463 // editing runtime/nx_syscalls.nx -- which essentially every organ imports -- and it 1464 // changed three times in ~20 minutes; each time converge+push+build succeeded 1465 // IMMEDIATELY, proving the refusal was staleness and not a defect in the code. 1466 // ★A GUARD THAT IS RIGHT ABOUT CONTENT IDENTITY CAN STILL BE WRONG ABOUT AVAILABILITY: 1467 // IT TURNED ONE SEAT'S SAVE INTO AN ESTATE-WIDE BUILD OUTAGE. 1468 // 1469 // THE HARM IT ACTUALLY EXISTS TO PREVENT is compiling a copy that is BEHIND the 1470 // authoring tree -- that is how the unfreed-mmap fix got applied twice. Being AHEAD is 1471 // not that harm: it is just the newest work, and building does not write source. 1472 // The NAS cannot do symbol containment here (the manifest carries only sha+bytes+path, 1473 // never the laptop's content), but it CAN answer the question that decides the case: 1474 // was this file modified AFTER the snapshot was taken? 1475 // nas mtime > manifest mtime -> the snapshot is simply STALE about this file, 1476 // this tree holds the newer bytes -> PROCEED, LOUDLY. 1477 // nas mtime <= manifest mtime -> the snapshot SAW this content and still disagrees 1478 // -> a real fork, the laptop is ahead -> REFUSE. 1479 // No new constant, no new data, and it fails CLOSED whenever either stat is unreadable. 1480 if cn_div == 1 { 1481 // ⚠cn_conf is the CONF FILE'S CONTENT BUFFER, not a path -- the row is a 1482 // (buffer, offset, length) triple. Passing it to a stat() stats garbage, which 1483 // returns -1 and silently skipped this whole check: the first version of this 1484 // fix REFUSED exactly as before and looked like the branch was simply wrong. 1485 // cn_path is the resolved tree-relative path the refusal message already prints. 1486 // ⚠And the manifest is ../knowledge/... because main() anchors CWD to buildroot. 1487 // A PATH THAT IS RIGHT FOR THE MESSAGE IS NOT AUTOMATICALLY RIGHT FOR A SYSCALL. 1488 let cn_fmt: i64 = sbr_mtime(cn_path) 1489 let cn_mmt: i64 = sbr_mtime("../knowledge/status/treecanon_laptop_hash.mf" as *u8) 1490 if cn_fmt > 0 { 1491 if cn_mmt > 0 { 1492 if cn_fmt > cn_mmt { 1493 sbr_puts("[nx_sov_build_run] TREE-CANON STALE-NOT-FORKED: canon path " as *u8) 1494 sbr_puts(cn_path) 1495 sbr_puts(" differs from the authoring manifest, but THIS TREE'S COPY IS NEWER THAN THE SNAPSHOT (file mtime " as *u8) 1496 sbr_putn(cn_fmt) 1497 sbr_puts(" > manifest mtime " as *u8) 1498 sbr_putn(cn_mmt) 1499 sbr_puts("), so the manifest is behind, not the tree. PROCEEDING on the newer bytes -- re-run the treecanon push to re-sync the authoring tree.\ 1500" as *u8) 1501 cn_div = 0 1502 } 1503 } 1504 } 1505 } 1506 if cn_div == 1 { 1507 sbr_puts("[nx_sov_build_run] REFUSED-TREE-CANON rc=7: canon path " as *u8) 1508 sbr_puts(cn_path) 1509 if cn_hmode == 1 { 1510 sbr_puts(" DIVERGES across trees by CONTENT (sha256) -- this tree=" as *u8) 1511 sbr_puts(cn_lhex) 1512 sbr_puts(" authoring manifest=" as *u8) 1513 sbr_puts(cn_mhex) 1514 sbr_puts(" ('?' repeated = file unreadable, or the row is absent from the manifest). " as *u8) 1515 } 1516 if cn_hmode == 0 { 1517 sbr_puts(" DIVERGES across trees by SIZE (this tree=" as *u8); sbr_putn(cn_nas) 1518 sbr_puts("B, authoring manifest=" as *u8); sbr_putn(cn_lap) 1519 sbr_puts("B; -1 = absent). NOTE: this is the SIZE SCREEN, so equal-size rewrites would have PASSED -- push a nx_treehash digest manifest to close that class. " as *u8) 1520 } 1521 sbr_puts("Building now would compile a FORKED copy -- the exact class that applied the unfreed-mmap fix twice. Remedy: body-diff and converge the file in BOTH trees (merge per file, never wholesale), regenerate + push knowledge/status/treecanon_laptop_hash.mf (and treecanon_laptop.mf), then rebuild.\n" as *u8) 1522 sys_exit(SBR_CANON_REFUSED); return SBR_CANON_REFUSED 1523 } 1524 } 1525 } 1526 cn_p = cn_e + 1 1527 } 1528 } } 1529 1530 // ---- compile+ASSEMBLE with recompile-retry until the .s ASSEMBLES CLEANLY (compiler nondeterminism guard). 1531 // ROOT FIX 2026-06-25: the old guard stopped at the first NON-EMPTY .s -- but nx_cc's nondeterminism also 1532 // TRUNCATES (a non-empty .s missing the trailing `main` -> nxasm rc=102 "UNDEFINED label: main", caught x3 1533 // assembling nx_raci_sov / nx_pattern_library). So success now REQUIRES rc_a==0 from nxasm, not merely 1534 // non-empty bytes -> truncation-nondeterminism becomes reliability. The assemble lands in tmpelf (atomic 1535 // rename after the loop). If a real DETERMINISTIC miscompile, the retries exhaust + we LOUD-fail saying so. ---- 1536 // ---- CONTENT-ADDRESSED BUILD CACHE: try a hit BEFORE compiling (B2, 2026-08-17). FAIL-OPEN: any 1537 // problem here leaves cache_hit=0 and the build proceeds EXACTLY as before this block existed. ---- 1538 var cache_hit: i64 = 0 1539 var cache_have_key: i64 = 0 1540 let cachekey: *u8 = sys_mmap(SBR_SHA_HEX + 2) 1541 let cachepath: *u8 = sys_mmap(SBR_CACHE_TMPW) 1542 // EVERY path prints one BUILD-CACHE line (HIT | MISS reason=...), so a silent build can never be 1543 // mistaken for a cached one, and a gate can assert on the reason rather than on the absence of a word. 1544 var cache_route: i64 = 0 // 0 = consult the store | 1 = toolchain target | 2 = --no-cache | 3 = conf disabled 1545 if sbr_is_toolchain(name) == 1 { cache_route = 1 } 1546 if cache_route == 0 { if no_cache == 1 { cache_route = 2 } } 1547 if cache_route == 0 { if sbr_cache_enabled() == 0 { cache_route = 3 } } 1548 if cache_route == 1 { bld_cache_cas_say(name, "MISS reason=toolchain-target (a toolchain binary is in every key; it is never cached)" as *u8, 0 as *u8); bld_cache_cas_nl() } 1549 if cache_route == 2 { bld_cache_cas_say(name, "MISS reason=disabled-by-flag (--no-cache)" as *u8, 0 as *u8); bld_cache_cas_nl() } 1550 if cache_route == 3 { bld_cache_cas_say(name, "MISS reason=disabled-by-conf (../knowledge/buildcache.conf cache_enabled=0)" as *u8, 0 as *u8); bld_cache_cas_nl() } 1551 if cache_route == 0 { 1552 if sbr_cache_key(src, compiler, asm_tool, want_debug, cachekey) != 0 { 1553 bld_cache_cas_say(name, "MISS reason=key-unavailable (closure could not be expanded for hashing; building normally)" as *u8, 0 as *u8); bld_cache_cas_nl() 1554 } 1555 if sbr_cache_key(src, compiler, asm_tool, want_debug, cachekey) == 0 { 1556 cache_have_key = 1 1557 sys_mkdir("_build/cache" as *u8, 0x1ed) // 0755; idempotent; already-exists is fine 1558 var cq: i64 = 0 1559 cq = sbr_cat(cachepath, cq, "_build/cache/" as *u8) 1560 cq = sbr_cat(cachepath, cq, cachekey) 1561 cq = sbr_cat(cachepath, cq, ".sov.elf" as *u8); cachepath[cq] = 0 as u8 1562 cache_hit = bld_cache_cas(cachekey, cachepath, elfpath, name) 1563 } 1564 } 1565 // FAIL-LOUD unlink of the stale fossil (seq132 / seq363), MOVED HERE 2026-09-05: every refusal above has 1566 // already exited and a cache HIT has just materialised the artifact, so only a MISS that is about to 1567 // compile may remove the prior binary. A refused build now leaves the last good fossil in place. 1568 if cache_hit == 0 { sys_unlinkat(elfpath) } 1569 let tmpelf: *u8 = sys_mmap(256); o = 0 1570 o = sbr_cat(tmpelf, o, "_build/_sbr_asm_out." as *u8); o = sbr_cat(tmpelf, o, name); tmpelf[o] = 0 as u8 1571 var asmbytes: i64 = 0 1572 var rc_a: i64 = 0 - 1 1573 var built: i64 = 0 1574 var tries: i64 = 0 1575 if cache_hit == 1 { built = 1; tries = SBR_MAX_RETRIES } // BUILD-CACHE HIT: artifact already in elfpath, skip compile+assemble 1576 while tries < SBR_MAX_RETRIES { 1577 let sfd: i64 = sys_openat_wr(spath, 0x1a4) 1578 // FLAG POSITION IS LOAD-BEARING, NOT STYLISTIC. nx_cc's argv walk EXITS at the first non-flag 1579 // argument (nx_compile_x86.nx: `path_addr = arg as i64; i = argc`), so ANY flag placed AFTER the 1580 // source path is never seen. -g therefore goes BEFORE src. Had it gone after, the build would 1581 // have succeeded, printed the DEBUG BUILD banner, and produced a binary with no .debug_line -- 1582 // i.e. nx_addr2line would still say "built without -g" and the flag would read as broken rather 1583 // than misplaced. Widened to 6 slots so a future third flag cannot silently overrun the 4 this 1584 // needs (compiler, -g, src, NULL); mmap rounds to a page either way, so the cost is zero and the 1585 // declared size states the intent. 1586 let cc: *i64 = sys_mmap(8*6) as *i64 1587 var ci: i64 = 0 1588 cc[ci] = compiler as i64; ci = ci + 1 1589 if want_debug == 1 { cc[ci] = "-g" as *u8 as i64; ci = ci + 1 } 1590 cc[ci] = src as i64; ci = ci + 1 1591 cc[ci] = 0 1592 let rc_c: i64 = sbr_run(compiler, cc, envp, sfd, devnull, deadline_ms) 1593 sys_close(sfd) 1594 // A HANG IS NOT RETRIED. The retry loop above exists for nx_cc's nondeterministic .s 1595 // truncation -- a real, transient class. A timeout is the opposite: deterministic, and each 1596 // retry would burn another full deadline before failing the same way. 1597 if rc_c == SBR_TIMEOUT_RC { 1598 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name) 1599 sbr_puts(": COMPILE-TIMEOUT -- NOT retried, and NOT a compile failure. nx_cc never answered, so\n" as *u8) 1600 sbr_puts(" nothing was judged about this source. Do not hunt a syntax error: minimise the input that\n" as *u8) 1601 sbr_puts(" hangs the compiler and file it against the compiler lane.\n" as *u8) 1602 sys_exit(SBR_BUILD_TIMEOUT); return SBR_BUILD_TIMEOUT 1603 } 1604 asmbytes = sbr_filesize(spath) 1605 if rc_c == 0 { if asmbytes > SBR_MIN_ASM_BYTES { 1606 let aa2: *i64 = sys_mmap(8*4) as *i64 1607 aa2[0] = asm_tool as i64; aa2[1] = spath as i64; aa2[2] = tmpelf as i64; aa2[3] = 0 1608 rc_a = sbr_run(asm_tool, aa2, envp, 0 - 1, 0 - 1, deadline_ms) 1609 if rc_a == SBR_TIMEOUT_RC { 1610 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name) 1611 sbr_puts(": ASSEMBLE-TIMEOUT -- NOT retried. nxasm never answered on this .s.\n" as *u8) 1612 sys_exit(SBR_BUILD_TIMEOUT); return SBR_BUILD_TIMEOUT 1613 } 1614 if rc_a == 0 { built = 1; tries = SBR_MAX_RETRIES } 1615 } } 1616 if tries != SBR_MAX_RETRIES { tries = tries + 1 } 1617 } 1618 if built == 0 { 1619 if asmbytes <= SBR_MIN_ASM_BYTES { 1620 // ROOT-CAUSE SURFACE (2026-07-06): the retry loop mutes nx_cc's stderr, so a plain source error 1621 // (undefined function / parse / arg-count) hid behind this opaque "empty .s" (cost a ~15-build blind 1622 // hunt). Re-run the compiler ONCE with stderr VISIBLE so the REAL diagnostic always prints. Same 1623 // one-look answer as _offc/nx_ccdiag.elf, now automatic on every failure. 1624 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name); sbr_puts(": COMPILE-FAIL (empty .s) -- nx_cc says:\n---- nx_cc stderr ----\n" as *u8) 1625 let dcc: *i64 = sys_mmap(8*4) as *i64 1626 dcc[0] = compiler as i64; dcc[1] = src as i64; dcc[2] = 0 1627 sbr_run(compiler, dcc, envp, devnull, 0 - 1, deadline_ms) // stdout->devnull, stderr VISIBLE = the real cause 1628 sbr_puts("----------------------\n(usually an undefined fn / missing import / parse error -- NOT a codegen crash; fix the source above)\n" as *u8) 1629 sys_exit(SBR_COMPILE_FAIL); return SBR_COMPILE_FAIL 1630 } 1631 if rc_a > 128 { 1632 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name); sbr_puts(": NXASM-CRASHED sig=" as *u8); sbr_putn(rc_a - 128); sbr_puts(" (assembler died on this .s -> capacity/robustness bug)\n" as *u8) 1633 sys_exit(SBR_ASM_FAIL); return SBR_ASM_FAIL 1634 } 1635 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name); sbr_puts(": NXASM-FAIL rc=" as *u8); sbr_putn(rc_a) 1636 sbr_puts(" after recompile-retries -- DETERMINISTIC (not the nondeterministic-truncation class). rc=102 = nxasm 'UNDEFINED label: main' = USUALLY a no-main LIBRARY built standalone -> run its _gate/importer (the one with main), NOT the lib. Else a real deterministic compiler/source miscompile.\n" as *u8) 1637 sys_exit(SBR_ASM_FAIL); return SBR_ASM_FAIL 1638 } 1639 1640 // CORRECTED 2026-06-25: the old comment here claimed the rc=6/102 "ctx-x-output-path" class was 1641 // "non-reproducible / nxasm outpath codegen CLEAN". That was WRONG -- the real rc=102 is nxasm's pass-2 1642 // "UNDEFINED label: main" (axc_label_resolve), i.e. nx_cc emitted a TRUNCATED .s missing `main`. It is the 1643 // COMPILER truncation-nondeterminism, not the output path. The retry loop above now requires a clean assemble, 1644 // so a truncated .s no longer escapes. tmpelf holds the good ELF -> atomic rename install (temp+rename kept 1645 // for atomicity = never overwrite a running binary mid-write). 1646 // On a BUILD-CACHE HIT elfpath already holds the byte-identical artifact, so skip the rename and the 1647 // store; on a MISS, install the fresh ELF and populate the content-addressed cache (fail-open). 1648 if cache_hit == 0 { 1649 sys_renameat(tmpelf, elfpath) 1650 if cache_have_key == 1 { bld_cache_cas_store(elfpath, cachepath, name); sbr_cache_prune() } 1651 } 1652 1653 // ---- LM-026 ROOT FIX: refresh the INSTALLED artifact if one exists ----------------------------- 1654 // Historical trap (cost a full session on the MMU rung): this runner builds to /tmp/<name>.sov.elf, 1655 // but gates/organs fork _offc/<name>.elf -- so a rebuild left _offc STALE and source edits silently 1656 // never took effect. Now, on a SUCCESSFUL build, if _offc/<name>.elf ALREADY EXISTS (i.e. <name> is 1657 // an installed artifact that something forks), atomically refresh it from the fresh build. This is 1658 // refresh-IF-PRESENT only: throwaway gate/probe builds (run straight from /tmp, no _offc twin) never 1659 // get a spurious _offc entry. Atomic (write .sbrtmp + renameat) = no torn binary, retires LM-026 at 1660 // the source. The reactive nx_offc_install guardrail stays as the belt-and-suspenders detector. 1661 let offcpath: *u8 = sys_mmap(256); o = 0 1662 o = sbr_cat(offcpath, o, offc_pfx); o = sbr_cat(offcpath, o, name); o = sbr_cat(offcpath, o, ".elf" as *u8); offcpath[o] = 0 as u8 1663 // The SECOND consumer location: <serving-root>/<name>.elf. Probed independently of _offc, 1664 // because most organs have exactly one of the two and the old code only ever looked at _offc. 1665 let rootpath: *u8 = sys_mmap(256); var ro: i64 = 0 1666 ro = sbr_cat(rootpath, ro, root_pfx); ro = sbr_cat(rootpath, ro, name); ro = sbr_cat(rootpath, ro, ".elf" as *u8); rootpath[ro] = 0 as u8 1667 let oex: i64 = sys_openat_rd(offcpath) 1668 let rex: i64 = sys_openat_rd(rootpath) 1669 var has_offc: i64 = 0 1670 var has_root: i64 = 0 1671 if oex >= 0 { sys_close(oex); has_offc = 1 } 1672 if rex >= 0 { sys_close(rex); has_root = 1 } 1673 // ---- THE DECISION IS DELEGATED, NOT MADE HERE (2026-08-26) ---- 1674 // nx_builddeploy_lib owns "may this build write a consumer-visible binary?", so the QUEUED lane and 1675 // the SEAT lane cannot disagree, and a fixture can hold every combination of its inputs. The probes 1676 // stay here (does a twin exist, is this a toolchain, is this a declared daemon); the JUDGEMENT moved. 1677 // 1678 // WHAT CHANGED: --build-only now installs NOTHING. WHY, measured 2026-08-26 from the queue's OWN 1679 // artifact knowledge/store/planrun-build-nx_gate_roster_run-: 1680 // [nx_sov_build_run] nx_gate_roster_run: DEPLOYED to serving root (twin refresh, live for the 1681 // next fork) -> ../nx_gate_roster_run.elf 1682 // /api/build's load-refusal path forks nx_job_run nx_buildq add; nx_buildq seeds the plan step 1683 // "nx_sov_build_run <target> --build-only"; nx_orchestrate fires it from the SERVING ROOT -- where 1684 // this runner's CWD anchor DOES fire, so root_pfx becomes "../" and the twin refresh lands on the 1685 // LIVE binary. The caller had been told only that its build was deferred and to promote deliberately 1686 // afterwards. Every promote-lane guard -- nx_contentdiff, nx_behaveprobe, the capability-loss check, 1687 // the .prev bank -- was bypassed by construction, with no seat anywhere in the loop. 1688 // A FLAG WHOSE MEANING DEPENDS ON THE CALLER'S CWD CANNOT BE REASONED ABOUT FROM ITS NAME. 1689 let bd_tc: i64 = sbr_is_toolchain(name) 1690 let bd_dk: i64 = sbr_is_daemon(name) 1691 // What the twin probes ALONE would have wanted, kept only so the refusals below can say "there was 1692 // something here and I declined to write it" instead of going silent. 1693 var bd_would: i64 = 0 1694 if has_offc == 1 { bd_would = 1 } 1695 if has_root == 1 { bd_would = 1 } 1696 if force_install == 1 { bd_would = 1 } 1697 let bd_loc: i64 = bd_locations(has_offc, has_root, force_install, build_only, bd_tc, bd_dk) 1698 let bd_reason: i64 = bd_why(has_offc, has_root, force_install, build_only, bd_tc, bd_dk) 1699 let bd_held: i64 = bd_root_held(has_root, force_install, build_only, bd_tc, bd_dk) 1700 has_offc = bd_writes_offc(bd_loc) 1701 has_root = bd_writes_root(bd_loc) 1702 var do_install: i64 = 0 1703 if bd_loc != BD_LOC_NONE { do_install = 1 } 1704 // A RECEIPT MUST NAME THE CONSEQUENCE, AND AN UNWRITTEN LIVE BINARY IS A RESULT, NOT AN ABSENCE. 1705 // Silence here is exactly what let the queued-build class run unnoticed for weeks: the only way to 1706 // learn what a build had done to the serving root was to hash it afterwards and compare. 1707 if bd_held == 1 { 1708 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name) 1709 sbr_puts(": SERVING-ROOT TWIN HELD -- a live binary exists at " as *u8); sbr_puts(rootpath) 1710 sbr_puts(" and was deliberately NOT written.\n" as *u8) 1711 if bd_reason == BD_WHY_BUILD_ONLY { 1712 sbr_puts(" REASON: --build-only. This build installed NOTHING, anywhere. AWAITING PROMOTE.\n" as *u8) 1713 sbr_puts(" Ship it deliberately with nx_organ_ship <target>, which runs the content ruler, the\n" as *u8) 1714 sbr_puts(" behaviour probe and the gate BEFORE it promotes. Do not re-run this builder without\n" as *u8) 1715 sbr_puts(" the flag to apply it -- that is a deploy with none of those guards.\n" as *u8) 1716 } 1717 if bd_dk == 1 { 1718 sbr_puts(" REASON: this target is a DECLARED DAEMON. The supervisor respawns from disk, so that\n" as *u8) 1719 sbr_puts(" write IS a deploy -- no canary, no health gate, no .prev. Deploy it deliberately via\n" as *u8) 1720 sbr_puts(" POST /api/deploy (validated, .prev-banked, async health probe + auto-rollback).\n" as *u8) 1721 } 1722 sbr_puts(" Staged artifact: " as *u8); sbr_puts(elfpath); sbr_puts("\n" as *u8) 1723 } 1724 // ⚠⚠TOOLCHAIN IS NEVER AUTO-INSTALLED (rule 26, added 2026-07-30 after seq1464; RESTORED in the 1725 // 2026-08-03 fork merge -- the NAS branch had dropped this entire guard, so any successful build 1726 // of a toolchain binary silently replaced the deployed one, canary-less, even under --build-only). 1727 // MEASURED INCIDENT: buildroot/_offc/nx_cc_sovereign.elf was found LIVE at 520103 bytes -- the 1728 // output of a rebuild made while buildroot was stale -- instead of the 543126 that had been 1729 // deliberately promoted. The hub was therefore compiling EVERY organ with a compiler whose 1730 // optimiser was 11712 source-bytes short, and its .s came out 16430B larger from identical 1731 // sources. Nobody chose that; a build installed it. 1732 // 1733 // THE INVARIANT: refresh-IF-PRESENT is right for ordinary organs (it retires LM-026 staleness) and 1734 // CATASTROPHIC for the toolchain, because the toolchain is what BUILT the thing being installed -- 1735 // a bad build then replaces the compiler that produced it and every subsequent build inherits the 1736 // damage, with no promote, no canary and no .prev. That is a self-modifying build path. 1737 // The toolchain has exactly ONE lawful update route: /api/promote_toolchain, which ELF-validates, 1738 // banks .prev, chmod +x, CANARY-COMPILES AND RUNS, and auto-rolls-back. This guard makes that route 1739 // the only one BY CONSTRUCTION rather than by convention. 1740 // ★Applies to --install too: an explicit flag must not be able to brick the toolchain either. 1741 if bd_tc == 1 { 1742 if bd_would == 1 { 1743 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name) 1744 sbr_puts(": REFUSED to auto-install a TOOLCHAIN binary into _offc (rule 26 / seq1464).\n" as *u8) 1745 sbr_puts(" The build artifact is staged and usable; promote it deliberately via\n" as *u8) 1746 sbr_puts(" POST /api/promote_toolchain (ELF-validated, .prev-banked, canary-run, auto-rollback).\n" as *u8) 1747 } 1748 do_install = 0 1749 } 1750 if do_install == 1 { 1751 let il: *i64 = sys_mmap(16) as *i64 1752 let ib: *u8 = sys_read_file(elfpath, il) 1753 if (ib as i64) != 0 { 1754 // Refresh EVERY consumer location that actually holds a twin -- an organ forked from the 1755 // serving root got nothing when only _offc was refreshed. Both writes are atomic 1756 // (.sbrtmp + renameat), so neither can leave a torn binary. 1757 if has_offc == 1 { 1758 let otmp: *u8 = sys_mmap(256); var oo: i64 = 0 1759 oo = sbr_cat(otmp, oo, offc_pfx); oo = sbr_cat(otmp, oo, name); oo = sbr_cat(otmp, oo, ".elf.sbrtmp" as *u8); otmp[oo] = 0 as u8 1760 let ofd: i64 = sys_openat_wr(otmp, 493) // 0755 = executable (refresh AND force-install-new) 1761 if ofd >= 0 { sys_write(ofd, ib, il[0]); sys_close(ofd); sys_renameat(otmp, offcpath) } 1762 } 1763 if has_root == 1 { 1764 // has_root SURVIVED bd_locations, so this target is provably NOT a declared daemon, not 1765 // the toolchain, and the caller's intent permits an install. The daemon refusal moved up 1766 // to the held-twin reasons, where it prints even when nothing is installed at all -- 1767 // down here it could only ever speak on a path that had already decided to write. 1768 let rtmp: *u8 = sys_mmap(256); var rr: i64 = 0 1769 rr = sbr_cat(rtmp, rr, root_pfx); rr = sbr_cat(rtmp, rr, name); rr = sbr_cat(rtmp, rr, ".elf.sbrtmp" as *u8); rtmp[rr] = 0 as u8 1770 let rfd: i64 = sys_openat_wr(rtmp, 493) 1771 if rfd >= 0 { sys_write(rfd, ib, il[0]); sys_close(rfd); sys_renameat(rtmp, rootpath) } 1772 // Say DEPLOYED, not REFRESHED. The old word is why a caller who had decided not to 1773 // deploy read this line and believed nothing had shipped. 1774 // ★ A RECEIPT MUST NAME THE CONSEQUENCE, NOT THE MECHANISM. 1775 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name) 1776 sbr_puts(": DEPLOYED to serving root (twin refresh, live for the next fork) -> " as *u8) 1777 sbr_puts(rootpath); sbr_puts("\n" as *u8) 1778 if bd_dk < 0 { 1779 sbr_puts(" ⚠ daemon-check UNPROVEN: knowledge/status/organ_kind.conf unreadable, so\n" as *u8) 1780 sbr_puts(" this target's kind was never established. Verify it is not a daemon.\n" as *u8) 1781 } 1782 } 1783 // Print the path that was ACTUALLY written, not a hardcoded one. The old message said 1784 // "_offc/<name>.elf" unconditionally while writing buildroot/_offc/<name>.elf, so the 1785 // receipt could not be used to check the claim. VERIFY BY ARTIFACT, AND LET THE RECEIPT 1786 // NAME THE ARTIFACT IT WROTE. 1787 if force_install == 1 { sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name); sbr_puts(": INSTALLED -> " as *u8); sbr_puts(offcpath); sbr_puts(" (--install)\n" as *u8) } 1788 } 1789 } 1790 1791 // release the per-target build lock HERE -- artifacts are final (atomic renames done); the run 1792 // phase below must not hold it (a daemon target would wedge every future rebuild of itself). 1793 if lockfd >= 0 { sys_flock(lockfd, SYS_LOCK_UN); sys_close(lockfd) } 1794 1795 // ---- build-only mode: argv[2] starting "--b" (--build-only) SKIPS the run, so a sovereign 1796 // bring-up/supervisor can build a dependency without triggering its side effects (e.g. a worker 1797 // would otherwise start a live download). The build path above is byte-for-byte unchanged; 1798 // this only short-circuits before the run. Default (no 2nd arg) behaves exactly as before. ---- 1799 // --build-only OR --install both SKIP the run (skip_run was set from argv[2] at the top). 1800 if skip_run == 1 { 1801 // ARTIFACT PATH IS PART OF THE OUTPUT CONTRACT (2026-07-30). --build-only used to print only 1802 // "asm=NNNNB", so the caller was told the build SUCCEEDED but not WHERE the ELF landed -- and the 1803 // header comments still said /tmp/<name>.sov.elf while the code has written _build/<name>.sov.elf 1804 // since the flock change. Every caller therefore had to go hunting (measured: 3 shell round-trips 1805 // to locate one artifact). A tool that produces a file MUST say where it put it; the run path 1806 // below already prints elf=<path>, so build-only was the odd one out. Same line shape as the run 1807 // branch so existing log scrapers see a superset, never a changed field (rule 19). 1808 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name); sbr_puts(": asm=" as *u8); sbr_putn(asmbytes) 1809 sbr_puts("B SOVEREIGN build (nx_cc->nxasm_x86, no gcc, no run) elf=" as *u8); sbr_puts(elfpath) 1810 sbr_puts("\n" as *u8) 1811 sys_exit(SBR_OK); return SBR_OK 1812 } 1813 1814 // ---- run the sovereign ELF WITH FORWARDED ARGS; report; exit with its code ---- 1815 // ARG-FORWARDING (2026-07-14 debt-eat): argv[fwd_start..argc) pass through to the built program, so a 1816 // daemon/tool builds AND launches with its runtime args in one command (e.g. a cap-secret path). Before 1817 // this, extra args were silently DROPPED -- caught live when the self-gated git server ran AUTH OFF. 1818 let rr: *i64 = sys_mmap(8 * 20) as *i64 1819 rr[0] = elfpath as i64 1820 var ra: i64 = 1 1821 var ai: i64 = fwd_start 1822 while ai < argc { if ra < 19 { rr[ra] = argv[ai]; ra = ra + 1 } ai = ai + 1 } 1823 rr[ra] = 0 1824 // NO DEADLINE HERE, deliberately: this runs the BUILT PROGRAM, which may be a daemon or a long 1825 // job. Time-boxing a build tool is safety; time-boxing the user's program is a wrong answer. 1826 let rc_r: i64 = sbr_run(elfpath, rr, envp, 0 - 1, 0 - 1, SBR_NO_DEADLINE) 1827 sbr_puts("[nx_sov_build_run] " as *u8); sbr_puts(name); sbr_puts(": asm=" as *u8); sbr_putn(asmbytes) 1828 sbr_puts("B SOVEREIGN(nx_cc->nxasm_x86, no gcc) elf=" as *u8); sbr_puts(elfpath) 1829 sbr_puts(" run-exit=" as *u8); sbr_putn(rc_r); sbr_puts("\n" as *u8) 1830 sys_exit(rc_r) 1831 return rc_r 1832}