code wiki / _hdl_build / nx_gen_orchestrator.nx

nx_gen_orchestrator.nx source

↩ module page · 2034 lines · 121879 B

1// nx_gen_orchestrator.nx -- the NAS-side Elder AI gen daemon (the sovereign gen-img, off Docker). 2// Loopback HTTP backend behind nx_gen_gateway (which OPAQUE-gates /gen + prefix-strips). Routes: 3// GET / -> the gen UI (batch form + results strip + gallery link) 4// POST /api/generate -> validate -> POST the GPU worker /sdapi/v1/txt2img (batch_size=count) 5// -> gp_response (decode/inject-GENREC/ingest/blob/sidecar) -> {cids[]} 6// GET /img/<cid> -> serve the PNG blob (sidecar CID->path lookup) 7// GET /api/recent?n= -> the most recent CIDs (results strip / gallery feed) 8// POST /api/mesh -> {prompt} -> t2mesh (parametric SDF template) -> surface-nets -> STL on disk 9// -> {object,verts,tris,stl} (the 3D lane; CPU in-process, no GPU worker) 10// GET /mesh/<obj>.stl -> serve the emitted STL (name matched against the FIXED template vocabulary, 11// client bytes never reach the filesystem path = traversal impossible) 12// GET /health -> 200 13// Worker endpoint + store/blob/sidecar paths + generator-host are data-driven via argv (Rule 11/17). 14// argv: [1]=listen_port [2]=worker_a [3]=worker_b [4]=worker_c [5]=worker_d [6]=worker_port 15// [7]=store_prefix [8]=blobdir [9]=sidecar [10]=generator_host [11]=budget 16// license_tier: ORIGINAL 17import "nx_gen_pipeline.nx" 18import "nx_syscalls.nx" 19import "nx_sdfrender.nx" 20import "nx_meshgen.nx" 21import "nx_t2mesh.nx" 22import "nx_companion_identity.nx" 23import "nx_gen_worker.nx" 24import "nx_companion_persona.nx" 25import "nx_companion_wardrobe.nx" 26import "nx_companion_state.nx" 27import "nx_anatomy_risk.nx" 28import "nx_render_coherence.nx" 29import "nx_swarm_endpoint_lib.nx" // role->addr SSOT (knowledge/swarm_nodes.conf, re-read per call) 30import "nx_llm_route.nx" // CC6 (2026-08-30): mixed-LLM routing as data, provenance in every reply 31import "nx_companion_mind.nx" // CC0 (2026-08-30): memory + relationship + typed present-tense state composed into the chat turn 32import "nx_store_seed_lib.nx" // sts_load: the writemode- plane (registries are planes, not tsvs) 33import "nx_tool_run.nx" // the one-gallery feed (2026-08-30) forks nx_galx_saveimg per new cid 34 35const GEN_BATCH_CAP: i64 = 8 36const GEN_UI_HTML: *u8 = "<!doctype html><html><head><meta charset=utf-8><meta name=viewport content=\"width=device-width,initial-scale=1\"><title>Elder AI &mdash; Gen</title><style>body{font-family:system-ui,sans-serif;max-width:900px;margin:2vh auto;padding:0 16px;color:#cdd7e6;background:#0b1019}h1{font-size:1.25rem;color:#e8eef7}label{display:block;font-size:.78rem;color:#7c8aa5;margin:8px 0 2px}textarea,input,select{width:100%;padding:8px;box-sizing:border-box;border:1px solid #2a3550;border-radius:5px;background:#121a28;color:#e8eef7}.row{display:flex;gap:8px;flex-wrap:wrap}.row>div{flex:1;min-width:90px}button{padding:10px 18px;margin:12px 0;background:#2d6cdf;color:#fff;border:0;border-radius:6px;cursor:pointer;font-size:1rem}#s{font-size:.82rem;color:#7c8aa5;min-height:1.2em}#g{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:8px;margin-top:14px}#g img{width:100%;border-radius:6px;background:#121a28}a{color:#6ea8fe}.mt{margin-top:26px}#cl{background:#121a28;border:1px solid #2a3550;border-radius:6px;padding:10px;min-height:120px;max-height:340px;overflow-y:auto;font-size:.9rem}#cl>div{margin:6px 0}#cs{font-size:.78rem;color:#7c8aa5;min-height:1em}.cu{color:#6ea8fe;font-weight:600}.ca{color:#e8a0c0;font-weight:600}</style></head><body><h1>Elder AI &mdash; image generation</h1><label>Prompt</label><textarea id=p rows=3>a red fox in a snowy pine forest, photograph</textarea><label>Negative prompt</label><input id=n value=\"blurry, lowres\"><div class=row><div><label>Width</label><input id=w type=number value=512></div><div><label>Height</label><input id=h type=number value=512></div><div><label>Steps</label><input id=st type=number value=8></div><div><label>CFG</label><input id=c value=1.0></div><div><label>Seed (-1 rnd)</label><input id=sd type=number value=-1></div><div><label>Count</label><input id=cn type=number value=1 min=1 max=8></div></div><label>Sampler</label><select id=sm><option>euler</option><option>euler_a</option><option>dpm++_2m</option><option>heun</option><option>ddim</option></select><button onclick=gen()>Generate</button> <a href=\"/gen/\">gallery</a><div id=s>ready.</div><div id=g></div><script>function $(i){return document.getElementById(i)}\nasync function gen(){$('s').textContent='generating...';$('g').innerHTML='';try{var r=await fetch('/gen/api/generate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:$('p').value,negative:$('n').value,width:+$('w').value,height:+$('h').value,steps:+$('st').value,cfg:$('c').value,seed:+$('sd').value,count:+$('cn').value,sampler:$('sm').value})});var j=await r.json();if(!r.ok){$('s').textContent='error: '+(j.error||r.status);return}$('s').textContent=j.count+' image(s) in '+j.ms+'ms';for(var i=0;i<j.cids.length;i++){var im=document.createElement('img');im.src='/gen/img/'+j.cids[i];$('g').appendChild(im)}}catch(e){$('s').textContent='error: '+e}}\nfetch('/gen/api/recent?n=24').then(function(r){return r.json()}).then(function(j){if(j&&j.cids){for(var i=0;i<j.cids.length;i++){var im=document.createElement('img');im.src='/gen/img/'+j.cids[i];$('g').appendChild(im)}}}).catch(function(){})\nasync function mesh(){$('ms').textContent='generating mesh...';$('mo').innerHTML='';try{var r=await fetch('/gen/api/mesh',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:$('mp').value})});var j=await r.json();if(!r.ok){$('ms').textContent='error: '+(j.error||r.status);return}$('ms').textContent=j.object+' -- '+j.verts+' verts, '+j.tris+' tris, watertight, '+j.ms+'ms';var a=document.createElement('a');a.href=j.stl;a.download=j.object+'.stl';a.textContent='download '+j.object+'.stl (print-ready)';$('mo').appendChild(a)}catch(e){$('ms').textContent='error: '+e}}</script><h1 style=\"margin-top:26px\">Elder AI &mdash; 3D object</h1><label>Object prompt &mdash; text to a printable watertight STL (vocabulary: ball, snowman, dumbbell, tree, mushroom, bottle, person, cactus, capsule)</label><input id=mp value=\"a snowman in the yard\"><button onclick=mesh()>Generate 3D</button><div id=ms>ready.</div><div id=mo></div>" as *u8 37const GEN_CHAT_HTML: *u8 = "<h1 class=mt>Elara &mdash; chat</h1><div id=cl></div><div class=row style='margin-top:8px'><div style='flex:4'><input id=ci placeholder='say something to Elara'></div><div><button onclick=say()>Send</button></div></div><div id=cs></div><script>var CHIST=[{role:'system',content:'You are Elara, a warm, affectionate, playful companion who speaks naturally and stays in character. Keep replies conversational.'}];function cadd(role,txt){var d=document.createElement('div');d.className=(role=='user'?'cu':'ca');d.textContent=(role=='user'?'you: ':'Elara: ')+txt;var cl=document.getElementById('cl');cl.appendChild(d);cl.scrollTop=1e9}\nasync function say(){var el=document.getElementById('ci');var t=el.value.trim();if(!t){return}el.value='';cadd('user',t);document.getElementById('cs').textContent='Elara is typing...';try{var r=await fetch('/gen/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({message:t})});var j=await r.json();if(!r.ok){document.getElementById('cs').textContent='error: '+(j.error||r.status);return}var m=(j.choices&&j.choices[0]&&j.choices[0].message&&j.choices[0].message.content)||'(no reply)';cadd('assistant',m);if(j.images&&j.images.length){var cl=document.getElementById('cl');for(var ii=0;ii<j.images.length;ii++){var im=document.createElement('img');im.src='/gen/img/'+j.images[ii];im.style.maxWidth='170px';im.style.borderRadius='8px';im.style.margin='4px 4px 0 0';cl.appendChild(im)}cl.scrollTop=1e9}document.getElementById('cs').textContent=''}catch(e){document.getElementById('cs').textContent='error: '+e}}\ndocument.getElementById('ci').addEventListener('keydown',function(e){if(e.key=='Enter'){say()}})</script></body></html>" as *u8 38 39func go_slen(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} return n } 40func go_itoa(dst: *u8, off: i64, v: i64) -> i64 { let t: *u8=sys_mmap(28); var m: i64=v; var k: i64=0; if m==0{t[0]=48 as u8;k=1} while m>0{t[k]=(48+(m%10)) as u8;m=m/10;k=k+1} var o: i64=off; var q: i64=k-1; while q>=0{dst[o]=t[q];o=o+1;q=q-1} return o } 41func go_cat(dst: *u8, off: i64, s: *u8) -> i64 { var o: i64=off; var i: i64=0; while s[i]!=(0 as u8){dst[o]=s[i]; o=o+1; i=i+1} return o } 42func go_catb(dst: *u8, off: i64, src: *u8, n: i64) -> i64 { var o: i64=off; var i: i64=0; while i<n {dst[o]=src[i]; o=o+1; i=i+1} return o } 43func go_starts(buf: *u8, n: i64, pre: *u8) -> i64 { var i: i64=0; while pre[i]!=(0 as u8){ if i>=n {return 0} if buf[i]!=pre[i]{return 0} i=i+1 } return 1 } 44 45func go_send(cfd: i64, status: *u8, ctype: *u8, body: *u8, blen: i64) -> i64 { 46 let buf: *u8 = sys_mmap(262144); var o: i64 = 0 47 o = go_cat(buf, o, "HTTP/1.1 " as *u8); o = go_cat(buf, o, status) 48 o = go_cat(buf, o, "\r\nContent-Type: " as *u8); o = go_cat(buf, o, ctype) 49 o = go_cat(buf, o, "\r\nContent-Length: " as *u8); o = go_itoa(buf, o, blen) 50 o = go_cat(buf, o, "\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n" as *u8) 51 o = go_catb(buf, o, body, blen) 52 sys_write(cfd, buf, o); return 0 53} 54// send a large binary body (image): header in one write, body streamed (avoids a giant header+body mmap). 55func go_send_bin(cfd: i64, ctype: *u8, body: *u8, blen: i64) -> i64 { 56 let hb: *u8 = sys_mmap(1024); var o: i64 = 0 57 o = go_cat(hb, o, "HTTP/1.1 200 OK\r\nContent-Type: " as *u8); o = go_cat(hb, o, ctype) 58 o = go_cat(hb, o, "\r\nContent-Length: " as *u8); o = go_itoa(hb, o, blen) 59 o = go_cat(hb, o, "\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n" as *u8) 60 sys_write(cfd, hb, o) 61 var sent: i64 = 0 62 while sent < blen { let w: i64 = sys_write(cfd, (body as i64 + sent) as *u8, blen - sent); if w <= 0 { sent = blen } else { sent = sent + w } } 63 return 0 64} 65func go_400(cfd: i64, msg: *u8) -> i64 { let b: *u8 = sys_mmap(256); var o: i64 = go_cat(b,0,"{\"error\":\"" as *u8); o=go_cat(b,o,msg); o=go_cat(b,o,"\"}" as *u8); go_send(cfd, "400 Bad Request" as *u8, "application/json" as *u8, b, o); return 0 } 66func go_503(cfd: i64, msg: *u8) -> i64 { let b: *u8 = sys_mmap(256); var o: i64 = go_cat(b,0,"{\"error\":\"" as *u8); o=go_cat(b,o,msg); o=go_cat(b,o,"\"}" as *u8); go_send(cfd, "503 Service Unavailable" as *u8, "application/json" as *u8, b, o); return 0 } 67 68// read FULL request (headers + Content-Length body) 69func go_read_full(cfd: i64, req: *u8, cap: i64) -> i64 { 70 var total: i64 = 0 71 var he: i64 = 0 - 1 72 while he < 0 { 73 if total >= cap { return total } 74 let r: i64 = sys_read(cfd, ((req as i64) + total) as *u8, cap - total) 75 if r <= 0 { return total } 76 total = total + r 77 he = go_find_seq(req, total, "\r\n\r\n" as *u8, 4) 78 } 79 let cl: i64 = go_hdr_int(req, he, "\r\nContent-Length:" as *u8, 17) 80 var need: i64 = he + 4 81 if cl > 0 { need = he + 4 + cl } 82 while total < need { 83 if total >= cap { return total } 84 let r2: i64 = sys_read(cfd, ((req as i64) + total) as *u8, cap - total) 85 if r2 <= 0 { return total } 86 total = total + r2 87 } 88 return total 89} 90func go_find_seq(buf: *u8, n: i64, needle: *u8, nl: i64) -> i64 { 91 if nl==0 { return 0 } 92 var i: i64=0 93 while i+nl<=n { var j: i64=0; var ok: i64=1; while j<nl { if buf[i+j]!=needle[j]{ok=0; j=nl} else {j=j+1} } if ok==1 {return i} i=i+1 } 94 return 0-1 95} 96func go_hdr_int(req: *u8, hend: i64, name: *u8, nl: i64) -> i64 { 97 let p: i64 = go_find_seq(req, hend, name, nl) 98 if p < 0 { return 0 } 99 var i: i64 = p + nl 100 if i < hend { if req[i]==(32 as u8) { i=i+1 } } 101 var v: i64 = 0 102 var stop: i64 = 0 103 while stop == 0 { if i >= hend { stop=1 } else { let c: i64 = req[i]&0xff; if c>=48 { if c<=57 { v=v*10+(c-48); i=i+1 } else { stop=1 } } else { stop=1 } } } 104 return v 105} 106// request-target path -> out (NUL-term), returns len 107func go_reqpath(req: *u8, rn: i64, out: *u8, cap: i64) -> i64 { 108 var s1: i64 = 0-1; var i: i64 = 0 109 while i < rn { if req[i]==(32 as u8) { s1=i; i=rn } else { i=i+1 } } 110 if s1 < 0 { out[0]=0 as u8; return 0 } 111 var p: i64 = s1+1; var o: i64 = 0 112 while p < rn { let c: u8 = req[p]; if c==(32 as u8) { p=rn } else { if o<cap-1 { out[o]=c; o=o+1 } p=p+1 } } 113 out[o]=0 as u8; return o 114} 115 116// --- JSON value parse (in the incoming /api/generate body) --- 117func go_json_findval(body: *u8, blen: i64, key: *u8) -> i64 { 118 let kl: i64 = go_slen(key) 119 var i: i64 = 0 120 var vp: i64 = 0 - 1 121 while i + kl + 2 <= blen { 122 if (body[i]&0xff)==34 { 123 var j: i64 = 0 124 var ok: i64 = 1 125 while j < kl { if (body[i+1+j]&0xff)!=(key[j]&0xff) { ok=0; j=kl } else { j=j+1 } } 126 if ok==1 { if (body[i+1+kl]&0xff)==34 { 127 var k: i64 = i + 2 + kl 128 while k < blen { if (body[k]&0xff)==58 { vp = k+1; k=blen } else { if (body[k]&0xff)==32 { k=k+1 } else { k=blen } } } 129 i = blen 130 } } 131 } 132 if vp < 0 { i = i + 1 } 133 } 134 return vp 135} 136func go_skip_sp(body: *u8, blen: i64, i0: i64) -> i64 { var i: i64=i0; var sk: i64=1; while sk==1 { if i<blen { if (body[i]&0xff)==32 { i=i+1 } else { sk=0 } } else { sk=0 } } return i } 137func go_json_str(body: *u8, blen: i64, key: *u8, out: *u8, outcap: i64) -> i64 { 138 let vp: i64 = go_json_findval(body, blen, key) 139 if vp < 0 { out[0]=0 as u8; return 0 - 1 } 140 var i: i64 = go_skip_sp(body, blen, vp) 141 if i >= blen { out[0]=0 as u8; return 0 - 1 } 142 if (body[i]&0xff) != 34 { out[0]=0 as u8; return 0 - 1 } 143 i = i + 1 144 var o: i64 = 0 145 var stop: i64 = 0 146 while stop == 0 { 147 if i >= blen { stop = 1 } else { 148 let c: i64 = body[i]&0xff 149 if c == 34 { stop = 1; i = i + 1 } else { 150 if c == 92 { 151 if i+1 < blen { if o<outcap-1 { out[o]=body[i+1] as u8; o=o+1 } i=i+2 } else { i=i+1 } 152 } else { if o<outcap-1 { out[o]=body[i] as u8; o=o+1 } i=i+1 } 153 } 154 } 155 } 156 out[o]=0 as u8 157 return o 158} 159func go_json_int(body: *u8, blen: i64, key: *u8, dflt: i64) -> i64 { 160 let vp: i64 = go_json_findval(body, blen, key) 161 if vp < 0 { return dflt } 162 var i: i64 = go_skip_sp(body, blen, vp) 163 var neg: i64 = 0 164 if i < blen { if (body[i]&0xff)==45 { neg=1; i=i+1 } } 165 var v: i64 = 0 166 var any: i64 = 0 167 var stop: i64 = 0 168 while stop == 0 { if i >= blen { stop=1 } else { let c: i64 = body[i]&0xff; if c>=48 { if c<=57 { v=v*10+(c-48); any=1; i=i+1 } else { stop=1 } } else { stop=1 } } } 169 if any == 0 { return dflt } 170 if neg == 1 { return 0 - v } 171 return v 172} 173func go_json_raw(body: *u8, blen: i64, key: *u8, out: *u8, outcap: i64) -> i64 { 174 let vp: i64 = go_json_findval(body, blen, key) 175 if vp < 0 { out[0]=0 as u8; return 0 - 1 } 176 var i: i64 = go_skip_sp(body, blen, vp) 177 var o: i64 = 0 178 var stop: i64 = 0 179 while stop == 0 { 180 if i >= blen { stop=1 } else { 181 let c: i64 = body[i]&0xff 182 if c==44 { stop=1 } else { if c==125 { stop=1 } else { if c==32 { stop=1 } else { if o<outcap-1 { out[o]=body[i] as u8; o=o+1 } i=i+1 } } } 183 } 184 } 185 out[o]=0 as u8 186 return o 187} 188// emit a JSON-escaped quoted string into dst at off 189func go_emit_jstr(dst: *u8, off: i64, s: *u8) -> i64 { 190 var o: i64 = off 191 dst[o]=34 as u8; o=o+1 192 var i: i64 = 0 193 while s[i]!=(0 as u8) { 194 let c: i64 = s[i]&0xff 195 if c==34 { dst[o]=92 as u8; o=o+1; dst[o]=34 as u8; o=o+1 } else { 196 if c==92 { dst[o]=92 as u8; o=o+1; dst[o]=92 as u8; o=o+1 } else { 197 if c==10 { dst[o]=32 as u8; o=o+1 } else { if c==13 { dst[o]=32 as u8; o=o+1 } else { dst[o]=s[i]; o=o+1 } } 198 } 199 } 200 i=i+1 201 } 202 dst[o]=34 as u8; o=o+1 203 return o 204} 205 206// go_worker_dispatch / go_worker_up -> EXTRACTED to nx_gen_worker.nx (the GenWorker object -- see companion_arch.md) 207// position of the response BODY (after the worker's \r\n\r\n), or 0 208func go_body_start(resp: *u8, n: i64) -> i64 { let he: i64 = go_find_seq(resp, n, "\r\n\r\n" as *u8, 4); if he < 0 { return 0 } return he + 4 } 209 210// --- sidecar lookup + serve /img/<cid> --- 211func go_sidecar_lookup(sidecar: *u8, cid: *u8, cidlen: i64, pathout: *u8) -> i64 { 212 let lp: *i64 = sys_mmap(16) as *i64 213 let b: *u8 = sys_read_file(sidecar, lp) 214 if (b as i64) == 0 { return 0 - 1 } 215 let n: i64 = lp[0] 216 var i: i64 = 0 217 var ls: i64 = 0 218 var found: i64 = 0 - 1 219 while i <= n { 220 if i == n { i = i + 1 } else { 221 if (b[i]&0xff)==10 { 222 // line [ls, i): compare prefix == cid up to a tab 223 var j: i64 = 0 224 var ok: i64 = 1 225 while j < cidlen { if (ls+j) >= i { ok=0; j=cidlen } else { if (b[ls+j]&0xff)!=(cid[j]&0xff) { ok=0; j=cidlen } else { j=j+1 } } } 226 if ok==1 { if (ls+cidlen) < i { if (b[ls+cidlen]&0xff)==9 { 227 var po: i64 = 0 228 var k: i64 = ls+cidlen+1 229 while k < i { pathout[po]=b[k]; po=po+1; k=k+1 } 230 pathout[po]=0 as u8 231 found = po 232 i = n 233 } } } 234 ls = i + 1 235 } 236 i = i + 1 237 } 238 } 239 return found 240} 241func go_serve_img(cfd: i64, path: *u8, plen: i64, sidecar: *u8) -> i64 { 242 // path = /img/<cid> -> cid starts at offset 5 243 if plen <= 5 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "no cid" as *u8, 6); return 0 } 244 let cid: *u8 = ((path as i64) + 5) as *u8 245 let cidlen: i64 = plen - 5 246 let fpath: *u8 = sys_mmap(1024) 247 if go_sidecar_lookup(sidecar, cid, cidlen, fpath) < 0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "unknown cid" as *u8, 11); return 0 } 248 let lp: *i64 = sys_mmap(16) as *i64 249 let img: *u8 = sys_read_file(fpath, lp) 250 if (img as i64) == 0 { 251 // ★QUARANTINE-AWARE SERVING (2026-08-04). The blob being absent from the live path has TWO 252 // very different causes and they must not share a response: 253 // * WITHHELD by nx_quarantine (a takedown notice, or a SUSPECTED-age flag pending review) 254 // -> the asset is intact, deliberately not served. That is 451, not 404. 255 // * genuinely LOST -> 404. 256 // Before this, both returned `404 "blob gone"`, which is wrong twice over: 404 asserts the 257 // resource never existed, and an operator reading "blob gone" would conclude DATA LOSS about 258 // a file sitting safe in quarantine. ★A REFUSAL THAT CANNOT SAY WHY IS INDISTINGUISHABLE 259 // FROM A FAILURE -- and here it actively misreports one as the other. 260 // 451 (RFC 7725) is the honest code for content withheld for legal reasons, and the body 261 // names the route to contest it, per the standing rule that a refusal must carry its remedy. 262 let qp: *u8 = sys_mmap(1024) 263 var cut: i64 = 0 264 var fi: i64 = 0 265 while fpath[fi] != (0 as u8) { if fpath[fi] == (47 as u8) { cut = fi + 1 } fi = fi + 1 } 266 var qo: i64 = 0 267 while qo < cut { qp[qo] = fpath[qo]; qo = qo + 1 } 268 qo = go_cat(qp, qo, "quarantine/" as *u8) 269 var fj: i64 = cut 270 while fpath[fj] != (0 as u8) { qp[qo] = fpath[fj]; qo = qo + 1; fj = fj + 1 } 271 qp[qo] = 0 as u8 272 let qlp: *i64 = sys_mmap(16) as *i64 273 let held: *u8 = sys_read_file(qp, qlp) 274 if (held as i64) != 0 { 275 go_send(cfd, "451 Unavailable For Legal Reasons" as *u8, "text/plain" as *u8, 276 "This item is withheld pending review of a notice or an automated flag. It has NOT been deleted -- it is preserved and can be restored if the flag was wrong. If you believe it was withheld in error, or you are the subject and want it removed permanently, reply to the notice address published on this site.\n" as *u8, 306) 277 return 0 278 } 279 go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, 280 "This cid is listed in the gallery index but its file is not on disk (not quarantined). That is unexpected -- it indicates loss, not a takedown.\n" as *u8, 144) 281 return 0 282 } 283 go_send_bin(cfd, "image/png" as *u8, img, lp[0]) 284 return 0 285} 286// GET /api/recent?n=K -> {"cids":[...]} the last K sidecar CIDs (most-recent first) 287func go_serve_recent(cfd: i64, sidecar: *u8, k: i64) -> i64 { 288 let lp: *i64 = sys_mmap(16) as *i64 289 let b: *u8 = sys_read_file(sidecar, lp) 290 let out: *u8 = sys_mmap(65536) 291 var o: i64 = go_cat(out, 0, "{\"cids\":[" as *u8) 292 if (b as i64) != 0 { 293 let n: i64 = lp[0] 294 // collect line starts 295 let starts: *i64 = sys_mmap(8*4096) as *i64 296 var cntl: i64 = 0 297 var i: i64 = 0 298 var ls: i64 = 0 299 while i < n { if (b[i]&0xff)==10 { if cntl<4096 { starts[cntl]=ls; cntl=cntl+1 } ls=i+1 } i=i+1 } 300 var emitted: i64 = 0 301 var idx: i64 = cntl - 1 302 while idx >= 0 { 303 if emitted >= k { idx = 0 - 1 } else { 304 let s0: i64 = starts[idx] 305 var ce: i64 = s0 306 var st: i64 = 0 307 while st==0 { if ce>=n { st=1 } else { if (b[ce]&0xff)==9 { st=1 } else { ce=ce+1 } } } 308 if emitted>0 { out[o]=44 as u8; o=o+1 } 309 out[o]=34 as u8; o=o+1 310 var c: i64 = s0 311 while c < ce { out[o]=b[c]; o=o+1; c=c+1 } 312 out[o]=34 as u8; o=o+1 313 emitted = emitted + 1 314 idx = idx - 1 315 } 316 } 317 } 318 o = go_cat(out, o, "]}" as *u8) 319 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, o) 320 return 0 321} 322 323// Append the sd-server override block to a prompt: ` <sd_cpp_extra_args>{"steps":N,"cfg_scale":C,...}</...>`. 324// This is the ONLY way to control steps/cfg/negative on /v1/images/generations (verified in the engine source: 325// the endpoint reads only prompt/n/size, everything else comes from default_gen_params UNLESS overridden here). 326// Z-Image is a TURBO model: 8 steps renders in ~7s vs the ~28s default -> fits under the gateway proxy timeout 327// (the "<!doctype not valid JSON" bug) AND honors the UI's dynamic steps/cfg/negative. Real quotes here; the 328// whole prompt is JSON-escaped once by go_emit_jstr, json::parse unescapes, the engine regex re-extracts. 329// seed MUST go INSIDE the extra_args: the OpenAI /v1/images/generations endpoint reads only prompt/n/size from the 330// top-level body -- the top-level "seed" field is SILENTLY IGNORED (proven byte-level 2026-07-21: two requests with 331// top-level seed 111 vs 999 returned md5-identical PNGs; the SAME two seeds inside extra_args returned different PNGs). 332// So the seed override belongs here or every single-image request with the same prompt returns the SAME picture. 333// ★STEP DEFAULT IS CONFIG, NOT A LITERAL (2026-08-04, rule 11). The step count is the single 334// biggest quality/latency lever on this engine and it was buried here as an 8. MEASURED through the 335// live daemon (same prompt, same seed 31337, 512x512): 8 steps -> 12000ms, 30 steps -> 25000ms, i.e. 336// t = 7.3s + 0.59s/step. That timing is what PROVES the knob arrives at all -- md5 difference alone 337// could not, because the extra_args tag rides INSIDE the prompt string, so an unparsed tag changes 338// the image via text pollution (the banked ref_weight trap: "a knob tested through a channel that 339// does not carry it is NOT tested"). 340// The VALUE is deliberately unchanged at 8. A standing measurement says 8 is visibly soft at 341// 768x1024 with the realism LoRAs and 20 is sharp, but that knee was measured at ONE resolution and 342// raising it ~2x's latency on every render -- an operator quality-vs-latency call, not mine to make 343// silently. What changes here is only that the number is now ANSWERABLE: it lives in 344// knowledge/gen_steps.conf, editable with no rebuild and no redeploy, so the sweep that settles the 345// knee can move it per resolution. Absent/garbage conf = exactly the previous behaviour. 346const GO_STEPS_FLOOR: i64 = 1 347const GO_STEPS_CEIL: i64 = 50 348const GO_STEPS_FALLBACK: i64 = 8 349// ONE source for the companion-photo canvas. It was spelled twice -- once in the request sent to 350// the engine and once in the size recorded for the CID canon. Two spellings of one fact drift, and 351// when they do the cid stops describing the image (silently). Named once, used by both. 352const GO_PHOTO_SIZE: *u8 = "768x1024" 353 354func go_default_steps() -> i64 { 355 let szp: *i64 = sys_mmap(16) as *i64 356 szp[0] = 0 357 var b: *u8 = sys_read_file("knowledge/gen_steps.conf" as *u8, szp) 358 if szp[0] <= 0 { b = sys_read_file("/volume1/homes/elderwesto/nishihost/knowledge/gen_steps.conf" as *u8, szp) } 359 if szp[0] <= 0 { return GO_STEPS_FALLBACK } 360 var v: i64 = 0 361 var seen: i64 = 0 362 var i: i64 = 0 363 while i < szp[0] { 364 let c: i64 = b[i] & 0xff 365 if c >= 48 { if c <= 57 { v = v*10 + (c - 48); seen = 1; i = i + 1 } else { i = szp[0] } } else { if seen == 1 { i = szp[0] } else { i = i + 1 } } 366 } 367 if seen == 0 { return GO_STEPS_FALLBACK } 368 if v < GO_STEPS_FLOOR { return GO_STEPS_FALLBACK } 369 if v > GO_STEPS_CEIL { return GO_STEPS_CEIL } 370 return v 371} 372 373func go_append_turbo_args(dst: *u8, off: i64, steps: i64, cfg: *u8, neg: *u8, seed: i64) -> i64 { 374 var s: i64 = steps 375 if s < GO_STEPS_FLOOR { s = go_default_steps() } 376 if s > GO_STEPS_CEIL { s = GO_STEPS_CEIL } 377 var o: i64 = go_cat(dst, off, " <sd_cpp_extra_args>{\"steps\":" as *u8) 378 o = go_itoa(dst, o, s) 379 o = go_cat(dst, o, ",\"cfg_scale\":" as *u8) 380 if cfg[0]!=(0 as u8) { o = go_cat(dst, o, cfg) } else { o = go_cat(dst, o, "1.0" as *u8) } 381 if seed >= 0 { o = go_cat(dst, o, ",\"seed\":" as *u8); o = go_itoa(dst, o, seed) } 382 if neg[0]!=(0 as u8) { 383 o = go_cat(dst, o, ",\"negative_prompt\":\"" as *u8) 384 var i: i64 = 0 385 while neg[i]!=(0 as u8) { let c: i64 = neg[i]&0xff; if c!=34 { if c!=92 { if c>=32 { dst[o]=neg[i]; o=o+1 } } } i=i+1 } 386 o = go_cat(dst, o, "\"" as *u8) 387 } 388 o = go_cat(dst, o, "}</sd_cpp_extra_args>" as *u8) 389 return o 390} 391// --- POST /api/generate --- 392// --- SWARM-SSOT WORKER RESOLUTION (2026-08-04) -------------------------------------------------- 393// The gen daemon was the SIXTH hardcoded-GPU-endpoint site: its worker came ONLY from launch argv 394// (seq_oo.sh baked 192.168.8.193; DHCP moved the laptop to .192; every dispatch path 503'd while 395// the engine sat healthy on the 5080). knowledge/swarm_nodes.conf is the estate SSOT for 396// role->addr, re-read on EVERY call by nx_swarm_endpoint_lib -- resolving PER REQUEST here means 397// a future DHCP move heals with NO restart and NO redeploy. argv workers stay as FALLBACK 398// candidates (additive, rule 19); an unreadable SSOT degrades to exactly the old behavior. 399const GO_CH_DOT: i64 = 46 400const GO_CH_COLON: i64 = 58 401const GO_CH_D0: i64 = 48 402const GO_CH_D9: i64 = 57 403 404// parse the SSOT's "a.b.c.d:port" for role gpu-image into w[0..4]. 1 = resolved; 0 = fail-closed 405// (unreadable table / unknown role / malformed addr -> caller keeps the argv registry). 406func go_swarm_worker(w: *i64) -> i64 { 407 let s: *u8 = se_addr("gpu-image" as *u8) 408 if (s as i64) == 0 { return 0 } 409 var i: i64 = 0 410 var f: i64 = 0 411 var ok: i64 = 1 412 while f < 5 { 413 var v: i64 = 0 414 var digits: i64 = 0 415 var scan: i64 = 1 416 while scan == 1 { 417 let c: i64 = s[i] as i64 418 if c < GO_CH_D0 { scan = 0 } else { 419 if c > GO_CH_D9 { scan = 0 } else { v = v*10 + (c - GO_CH_D0); digits = digits + 1; i = i + 1 } 420 } 421 } 422 if digits == 0 { ok = 0; f = 5 } else { 423 w[f] = v 424 f = f + 1 425 if f < 5 { 426 var want: i64 = GO_CH_DOT 427 if f == 4 { want = GO_CH_COLON } 428 if (s[i] as i64) != want { ok = 0; f = 5 } else { i = i + 1 } 429 } 430 } 431 } 432 if ok == 0 { return 0 } 433 if w[4] <= 0 { return 0 } 434 return 1 435} 436 437// ONE candidate assembly for every dispatch path (generate / chat+photo / img2img -- was 3 inline 438// twins): [swarm-SSOT gpu-image] then [argv primary] (skipped when identical) then [argv extras]. 439func go_workers_assemble(cfg: *i64, ha: i64, hb: i64, hc: i64, hd: i64, wport: i64, wa: *i64, wb: *i64, wc: *i64, wd: *i64, wpa: *i64) -> i64 { 440 var wcount: i64 = 0 441 let sw: *i64 = sys_mmap(8*8) as *i64 442 if go_swarm_worker(sw) == 1 { wa[0]=sw[0]; wb[0]=sw[1]; wc[0]=sw[2]; wd[0]=sw[3]; wpa[0]=sw[4]; wcount = 1 } 443 var dup: i64 = 0 444 if wcount == 1 { if wa[0]==ha { if wb[0]==hb { if wc[0]==hc { if wd[0]==hd { if wpa[0]==wport { dup = 1 } } } } } } 445 if dup == 0 { wa[wcount]=ha; wb[wcount]=hb; wc[wcount]=hc; wd[wcount]=hd; wpa[wcount]=wport; wcount = wcount + 1 } 446 let xtra: i64 = cfg[9] 447 var xi: i64 = 0 448 while xi < xtra { if wcount < 8 { let bx: i64 = 10 + 5*xi; wa[wcount]=cfg[bx]; wb[wcount]=cfg[bx+1]; wc[wcount]=cfg[bx+2]; wd[wcount]=cfg[bx+3]; wpa[wcount]=cfg[bx+4]; wcount=wcount+1 } xi=xi+1 } 449 return wcount 450} 451 452func go_handle_generate(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 { 453 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4] 454 let storeprefix: *u8 = cfg[5] as *u8 455 let blobdir: *u8 = cfg[6] as *u8 456 let sidecar: *u8 = cfg[7] as *u8 457 let genhost: *u8 = cfg[8] as *u8 458 let prompt: *u8 = sys_mmap(4096) 459 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 4096) 460 if pl <= 0 { go_400(cfd, "empty prompt" as *u8); return 0 } 461 // G13 (2026-08-30) prompt-weight ADMISSION: a user-written "(term:w)" outside the envelope declared in 462 // knowledge/gen_prompt_weight.conf is refused with the group's weight named (permil) and its byte offset -- 463 // never clamped, never rendered -- the conf's own reasoning: a typo like (skin:13) must not become a render 464 // that reads as a model defect. The engine honours the weight, so this is admission of a LIVE control. 465 let wenv: *i64 = sys_mmap(CW_W_BYTES) as *i64 466 cw_weights_load(wenv) 467 let wbadat: *i64 = sys_mmap(16) as *i64 468 let wbadw: *i64 = sys_mmap(16) as *i64 469 if cw_weight_admit(prompt, pl, wenv, wbadat, wbadw) < 0 { 470 let wm: *u8 = sys_mmap(256) 471 var wo: i64 = go_cat(wm, 0, "prompt weight refused rule=OUT-OF-ENVELOPE permil=" as *u8) 472 wo = go_itoa(wm, wo, wbadw[0]) 473 wo = go_cat(wm, wo, " allowed=" as *u8); wo = go_itoa(wm, wo, wenv[CW_W_MIN]) 474 wo = go_cat(wm, wo, ".." as *u8); wo = go_itoa(wm, wo, wenv[CW_W_MAX]) 475 wo = go_cat(wm, wo, " at_byte=" as *u8); wo = go_itoa(wm, wo, wbadat[0]) 476 wo = go_cat(wm, wo, " (knowledge/gen_prompt_weight.conf)" as *u8) 477 wm[wo] = 0 as u8 478 go_400(cfd, wm); return 0 479 } 480 let neg: *u8 = sys_mmap(2048) 481 go_json_str(body, bn, "negative" as *u8, neg, 2048) 482 let w: i64 = go_json_int(body, bn, "width" as *u8, 512) 483 let h: i64 = go_json_int(body, bn, "height" as *u8, 512) 484 // 0 = "caller said nothing" -> go_append_turbo_args resolves the default from 485 // knowledge/gen_steps.conf. This MUST be a sentinel, not 8: my first attempt left the literal 8 486 // here and the conf was DEAD ON ARRIVAL -- steps never fell below the floor, so the resolver 487 // never ran and editing the conf changed render time by nothing. Caught only by MEASURING 488 // (8 vs 25 vs 8 gave 10s/9s/7s = no effect). ★A DEFAULT MOVED TO CONFIG IS STILL A LITERAL IF 489 // THE PARSE SITE KEEPS ONE -- and "the knob does nothing" is the same evidence shape as "the 490 // knob is not wired". An explicit request value still wins, unchanged. 491 // RESOLVE THE EFFECTIVE STEP COUNT ONCE, HERE -- then every consumer records the SAME truth. 492 // ⚠BUG THIS FIXES (mine, 2026-08-04): the sentinel 0 was passed straight through to the GENREC 493 // `steps` tEXt at the bottom of this handler, so every render that did not name a step count 494 // recorded **steps=0** while actually rendering at the config default. The PNG's own metadata 495 // lied, and because that field is part of the CID canon, the cid described a render that never 496 // happened. go_append_turbo_args resolved the default privately, which is exactly how the two 497 // views drifted apart. ★A VALUE RESOLVED IN ONE CONSUMER IS NOT RESOLVED FOR THE RECORD. 498 var steps: i64 = go_json_int(body, bn, "steps" as *u8, 0) 499 if steps < GO_STEPS_FLOOR { steps = go_default_steps() } 500 if steps > GO_STEPS_CEIL { steps = GO_STEPS_CEIL } 501 let cfgs: *u8 = sys_mmap(32) 502 if go_json_raw(body, bn, "cfg" as *u8, cfgs, 32) <= 0 { cfgs[0]=49 as u8; cfgs[1]=46 as u8; cfgs[2]=48 as u8; cfgs[3]=0 as u8 } 503 var seed0: i64 = go_json_int(body, bn, "seed" as *u8, 0 - 1) 504 if seed0 < 0 { seed0 = sys_now_us() & 0x7fffffff } 505 var count: i64 = go_json_int(body, bn, "count" as *u8, 1) 506 if count < 1 { count = 1 } 507 if count > GEN_BATCH_CAP { count = GEN_BATCH_CAP } 508 let samp: *u8 = sys_mmap(64) 509 if go_json_str(body, bn, "sampler" as *u8, samp, 64) <= 0 { samp[0]=101 as u8; samp[1]=117 as u8; samp[2]=108 as u8; samp[3]=101 as u8; samp[4]=114 as u8; samp[5]=0 as u8 } 510 511 // build worker request -- the OpenAI /v1/images/generations endpoint (the path that renders 512 // Z-Image correctly; the A1111 /sdapi/v1/txt2img path returns blank/garbage for this flow model). 513 // The engine applies its tuned defaults for steps/sampler/cfg; the UI's steps/cfg/sampler/negative 514 // are recorded as GENREC metadata (prompt + seed are the load-bearing factors for the CID). 515 // fold the UI's steps/cfg into the prompt as sd_cpp_extra_args (turbo). NOTE: Z-Image is CFG-distilled 516 // (cfg 1.0, single forward pass) -> supplying a negative_prompt forces full CFG = ~6x SLOWER (45s vs 7s, 517 // measured) with no quality gain, so we OMIT the negative here (recorded as GENREC metadata only). Negatives 518 // apply only to non-distilled models at cfg>1 = a future per-model switch. 519 let noneg: *u8 = sys_mmap(4); noneg[0]=0 as u8 520 let pfull: *u8 = sys_mmap(16384) 521 // REALISM TRIGGER FIRST (2026-08-27): the LoRA activation vocabulary LEADS the prompt, exactly as the 522 // pre-docker gen-img composed every render (`<lora tags><trigger words>, <prompt>`) -- the request-side 523 // term the June-repro A/B measured as dominant. Data-driven elara_trigger.txt (blank file = no prefix). 524 let gtrig: *u8 = sys_mmap(512); go_load_trigger(gtrig, 512) 525 var pfo: i64 = 0 526 if gtrig[0]!=(0 as u8) { pfo = go_cat(pfull, 0, gtrig); pfo = go_cat(pfull, pfo, ", " as *u8) } 527 pfo = go_cat(pfull, pfo, prompt) 528 let gloras: *u8 = sys_mmap(512); go_load_loras(gloras, 512) 529 pfo = go_cat(pfull, pfo, " " as *u8); pfo = go_cat(pfull, pfo, gloras) 530 pfo = go_append_turbo_args(pfull, pfo, steps, cfgs, noneg, seed0) 531 pfull[pfo] = 0 as u8 532 let wreq: *u8 = sys_mmap(16384) 533 var o: i64 = go_cat(wreq, 0, "{\"prompt\":" as *u8) 534 o = go_emit_jstr(wreq, o, pfull) 535 o = go_cat(wreq, o, ",\"n\":" as *u8); o = go_itoa(wreq, o, count) 536 o = go_cat(wreq, o, ",\"size\":\"" as *u8); o = go_itoa(wreq, o, w); o = go_cat(wreq, o, "x" as *u8); o = go_itoa(wreq, o, h); o = go_cat(wreq, o, "\"" as *u8) 537 o = go_cat(wreq, o, ",\"seed\":" as *u8); o = go_itoa(wreq, o, seed0) 538 o = go_cat(wreq, o, ",\"response_format\":\"b64_json\"}" as *u8) 539 let _keepneg: i64 = go_slen(neg) 540 let _keepcfg: i64 = go_slen(cfgs) 541 542 let t0: i64 = sys_now_realtime_sec() 543 let respcap: i64 = 25165824 544 let resp: *u8 = sys_mmap(respcap) 545 // MULTI-WORKER: candidates = [swarm-SSOT gpu-image (knowledge/swarm_nodes.conf, per-request)] + 546 // [argv primary cfg[0..4]] + [cfg[9] EXTRA workers (cfg[10+5i..], each "a b c d port")]. Per 547 // request, pick the first AVAILABLE one (TCP health-check = electronic availability), dispatch, FAILOVER on fail. 548 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64 549 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64 550 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa) 551 var rn: i64 = 0 - 1 552 var anyup: i64 = 0 553 var lastfail: i64 = 0 554 var wi: i64 = 0 555 while wi < wcount { 556 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 { 557 anyup = 1 558 let r: i64 = go_worker_dispatch(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], wreq, o, resp, respcap) 559 if r > 0 { rn = r; wi = wcount } else { lastfail = r; wi = wi + 1 } 560 } else { wi = wi + 1 } 561 } 562 // NAME THE FAILING CONJUNCT (2026-08-29). The old single message claimed "all in the registry are 563 // down" on EVERY failure -- including this path, which is only reachable AFTER go_worker_up returned 1, 564 // i.e. after a candidate demonstrably PASSED its TCP health probe. The message was false on its own 565 // control flow, and it sent every investigation at the worker registry instead of at the dispatch 566 // budget. MEASURED: a socket watch showed the worker ESTABLISHED and holding for 164s while the caller 567 // emitted worker-absence. A verdict is not a diagnosis; a guard that declines must say WHICH rule fired. 568 if rn <= 0 { 569 if anyup == 1 { 570 if lastfail == 0 - 3 { go_503(cfd, "worker BUSY-TIMEOUT: it accepted the connection and is still rendering, but returned nothing inside the dispatch budget. The render may still be completing on the GPU. This is a TIMEOUT, not an absent worker." as *u8); return 0 } 571 if lastfail == 0 - 4 { go_503(cfd, "worker PARTIAL-READ then timeout: the response was truncated mid-body" as *u8); return 0 } 572 if lastfail == 0 - 2 { go_503(cfd, "worker CONNECT-REFUSED immediately after passing its health probe" as *u8); return 0 } 573 if lastfail == 0 - 1 { go_503(cfd, "socket creation failed on the dispatch path (a local resource limit, not the worker)" as *u8); return 0 } 574 go_503(cfd, "worker health-probed UP but the dispatch returned no data and no error" as *u8); return 0 575 } 576 go_503(cfd, "no gpu worker available (no candidate passed its TCP health probe)" as *u8); return 0 577 } 578 let bs: i64 = go_body_start(resp, rn) 579 let bodyp: *u8 = (resp as i64 + bs) as *u8 580 let bodylen: i64 = rn - bs 581 582 let model: *u8 = "z_image_turbo" as *u8 583 let cids: *u8 = sys_mmap(GEN_BATCH_CAP * 80) 584 let stepss: *u8 = sys_mmap(16); go_itoa(stepss, 0, steps) 585 // size ("WxH") now rides the CID canon (debt 1785881333): without it, the same prompt+seed at a 586 // different resolution collided to the SAME cid and overwrote the earlier blob. 587 let sizes: *u8 = sys_mmap(32) 588 var szo: i64 = go_itoa(sizes, 0, w); sizes[szo] = 120 as u8; szo = go_itoa(sizes, szo + 1, h); sizes[szo] = 0 as u8 589 let n: i64 = gp_response(bodyp, bodylen, seed0, model, samp, stepss, genhost, prompt, sizes, pfull, storeprefix, blobdir, sidecar, cids, count) 590 if n > 0 { go_gallery_feed(cids, n, sidecar) } 591 if n < 0 { go_503(cfd, "worker returned no images" as *u8); return 0 } 592 let dt: i64 = (sys_now_realtime_sec() - t0) * 1000 593 594 let out: *u8 = sys_mmap(8192) 595 var oo: i64 = go_cat(out, 0, "{\"count\":" as *u8); oo = go_itoa(out, oo, n) 596 oo = go_cat(out, oo, ",\"ms\":" as *u8); oo = go_itoa(out, oo, dt) 597 oo = go_cat(out, oo, ",\"cids\":[" as *u8) 598 var ci: i64 = 0 599 while ci < n { 600 if ci > 0 { out[oo]=44 as u8; oo=oo+1 } 601 out[oo]=34 as u8; oo=oo+1 602 let cidp: *u8 = (cids as i64 + ci*80) as *u8 603 var cj: i64 = 0 604 while cidp[cj]!=(0 as u8) { out[oo]=cidp[cj]; oo=oo+1; cj=cj+1 } 605 out[oo]=34 as u8; oo=oo+1 606 ci = ci + 1 607 } 608 oo = go_cat(out, oo, "]}" as *u8) 609 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, oo) 610 return 0 611} 612 613func go_atoi(s: *u8) -> i64 { var v: i64=0; var i: i64=0; while s[i]!=(0 as u8){ let c: i64=s[i] as i64; if c<48{return v} if c>57{return v} v=v*10+(c-48); i=i+1 } return v } 614 615// go_chat_dispatch -> EXTRACTED to nx_gen_worker.nx (the GenWorker object) 616// go_load_persona / go_mem_append / go_mem_load_json / go_strip_think -> EXTRACTED to nx_companion_memory.nx 617// (the CompanionMemory object -- see companion_arch.md). 618// go_load_appearance / go_load_loras / go_pick_shot -> EXTRACTED to nx_companion_identity.nx (OO consolidation, 619// behaviour-preserving; the CompanionIdentity object -- see companion_arch.md). 620// case-insensitive: 1 if NUL-term `needle` occurs in hay[0..hlen) 621func go_contains_ci(hay: *u8, hlen: i64, needle: *u8) -> i64 { 622 var nl: i64 = 0; while needle[nl]!=(0 as u8) { nl=nl+1 } 623 if nl==0 { return 0 } 624 var i: i64 = 0 625 while i + nl <= hlen { 626 var j: i64 = 0; var ok: i64 = 1 627 while j < nl { 628 var a: i64 = hay[i+j]&0xff; var b2: i64 = needle[j]&0xff 629 if a>=65 { if a<=90 { a=a+32 } } 630 if b2>=65 { if b2<=90 { b2=b2+32 } } 631 if a!=b2 { ok=0; j=nl } else { j=j+1 } 632 } 633 if ok==1 { return 1 } 634 i=i+1 635 } 636 return 0 637} 638// first integer in NUL-term s (0 if none) -> how many photos she was asked for 639func go_parse_count(s: *u8) -> i64 { 640 var i: i64 = 0 641 while s[i]!=(0 as u8) { 642 let c: i64 = s[i]&0xff 643 if c>=48 { if c<=57 { 644 var v: i64 = 0 645 while s[i]!=(0 as u8) { let d: i64 = s[i]&0xff; if d>=48 { if d<=57 { v=v*10+(d-48); i=i+1 } else { return v } } else { return v } } 646 return v 647 } } 648 i=i+1 649 } 650 return 0 651} 652// ---- THE FIVE-PICS FIX + THE CONVERSATION ALBUM + THE ONE-GALLERY FEED (2026-08-30) -------------------------------- 653// MEASURED: "send me five pics" rendered ONE collage. Three defects stacked -- go_parse_count reads only DIGIT runs (so 654// "five" parsed as nothing), the chat photo path clamped every count to 1, and the raw user text ("five pics" included) 655// rode into the diffusion prompt as the scene, so the model painted the five it was asked for INSIDE one image. The worker 656// was proven innocent FIRST: n=2 returned two separate PNGs, and gp_response already ingests every entry with seed+i. 657const GO_CNT_CH_0: i64 = 48 658const GO_CNT_CH_9: i64 = 57 659const GO_CNT_CH_A_UP: i64 = 65 660const GO_CNT_CH_Z_UP: i64 = 90 661const GO_CNT_CH_A_LO: i64 = 97 662const GO_CNT_CH_Z_LO: i64 = 122 663const GO_CNT_CASE: i64 = 32 664const GO_CNT_MAX_GAP: i64 = 2 665const GO_CNT_TOKBUF: i64 = 16 666const GO_ALBUM_TSV: *u8 = "elara_album.tsv" as *u8 667const GO_ALBUM_OUT_CAP: i64 = 1048576 668const GO_ALBUM_MAX_DAYS: i64 = 60 669const GO_ALBUM_ROW_CAP: i64 = 32768 670const GO_DAYOFF_CONF_REL: *u8 = "knowledge/gen_day_offset.conf" as *u8 671const GO_DAYOFF_CONF_ABS: *u8 = "/volume1/homes/elderwesto/nishihost/knowledge/gen_day_offset.conf" as *u8 672const GO_FEED_CONF_REL: *u8 = "knowledge/gen_gallery_feed.conf" as *u8 673const GO_FEED_CONF_ABS: *u8 = "/volume1/homes/elderwesto/nishihost/knowledge/gen_gallery_feed.conf" as *u8 674const GO_FEED_TIMEOUT_MS: i64 = 8000 675const GO_FEED_OUT_CAP: i64 = 8192 676const GO_FEED_VAL_CAP: i64 = 512 677const GO_FEED_ARGV_SLOTS: i64 = 8 678const GO_CID_STRIDE: i64 = 80 679const GO_US_PER_S2: i64 = 1000000 680const GO_SECS_PER_HOUR: i64 = 3600 681const GO_SECS_PER_DAY: i64 = 86400 682const GO_STDERR: i64 = 2 683const GO_CH_TAB2: i64 = 9 684const GO_CH_NL2: i64 = 10 685const GO_CH_MINUS: i64 = 45 686const GO_CH_PIPE2: i64 = 124 687// civil-from-days (Hinnant): every constant named for its role in the arithmetic, never inlined 688const GO_CAL_EPOCH_TO_ERA0: i64 = 719468 689const GO_CAL_DAYS_PER_ERA: i64 = 146097 690const GO_CAL_ERA_LAST_DAY: i64 = 146096 691const GO_CAL_DAYS_PER_4Y: i64 = 1460 692const GO_CAL_DAYS_PER_100Y: i64 = 36524 693const GO_CAL_DAYS_PER_YEAR: i64 = 365 694const GO_CAL_YEARS_PER_ERA: i64 = 400 695const GO_CAL_Q4: i64 = 4 696const GO_CAL_Q100: i64 = 100 697const GO_CAL_MARCH_NUM: i64 = 5 698const GO_CAL_MARCH_OFF: i64 = 2 699const GO_CAL_MARCH_CYCLE: i64 = 153 700const GO_CAL_MONTH_SHIFT_LO: i64 = 3 701const GO_CAL_MONTH_SHIFT_HI: i64 = 9 702const GO_CAL_MONTH_WRAP_AT: i64 = 10 703const GO_CAL_TWO_DIGITS: i64 = 10 704 705// lowercase one ASCII char (letters only) 706func go_cnt_lo(c: i64) -> i64 { if c >= GO_CNT_CH_A_UP { if c <= GO_CNT_CH_Z_UP { return c + GO_CNT_CASE } } return c } 707func go_cnt_is_letter(c: i64) -> i64 { 708 let l: i64 = go_cnt_lo(c) 709 if l >= GO_CNT_CH_A_LO { if l <= GO_CNT_CH_Z_LO { return 1 } } 710 return 0 711} 712func go_cnt_is_digit(c: i64) -> i64 { if c >= GO_CNT_CH_0 { if c <= GO_CNT_CH_9 { return 1 } } return 0 } 713// ci word match of w (lowercase letters) at s[i..], requiring a word boundary AFTER; returns the word length or 0 714func go_cnt_word_at(s: *u8, n: i64, i: i64, w: *u8) -> i64 { 715 var k: i64 = 0 716 while w[k] != (0 as u8) { 717 if i + k >= n { return 0 } 718 if go_cnt_lo(s[i + k] as i64) != (w[k] as i64) { return 0 } 719 k = k + 1 720 } 721 if i + k < n { if go_cnt_is_letter(s[i + k] as i64) == 1 { return 0 } } 722 return k 723} 724// ci PREFIX match (no end boundary -- "pic" matches pics and picture) 725func go_cnt_prefix_at(s: *u8, n: i64, i: i64, w: *u8) -> i64 { 726 var k: i64 = 0 727 while w[k] != (0 as u8) { 728 if i + k >= n { return 0 } 729 if go_cnt_lo(s[i + k] as i64) != (w[k] as i64) { return 0 } 730 k = k + 1 731 } 732 return 1 733} 734// a number word at s[i..]: value 1..10 (couple=2, few=3), wl[0]=word length; 0 when none 735func go_cnt_numword(s: *u8, n: i64, i: i64, wl: *i64) -> i64 { 736 var l: i64 = go_cnt_word_at(s, n, i, "one" as *u8); if l > 0 { wl[0] = l; return 1 } 737 l = go_cnt_word_at(s, n, i, "two" as *u8); if l > 0 { wl[0] = l; return 2 } 738 l = go_cnt_word_at(s, n, i, "three" as *u8); if l > 0 { wl[0] = l; return 3 } 739 l = go_cnt_word_at(s, n, i, "four" as *u8); if l > 0 { wl[0] = l; return 4 } 740 l = go_cnt_word_at(s, n, i, "five" as *u8); if l > 0 { wl[0] = l; return 5 } 741 l = go_cnt_word_at(s, n, i, "six" as *u8); if l > 0 { wl[0] = l; return 6 } 742 l = go_cnt_word_at(s, n, i, "seven" as *u8); if l > 0 { wl[0] = l; return 7 } 743 l = go_cnt_word_at(s, n, i, "eight" as *u8); if l > 0 { wl[0] = l; return 8 } 744 l = go_cnt_word_at(s, n, i, "nine" as *u8); if l > 0 { wl[0] = l; return 9 } 745 l = go_cnt_word_at(s, n, i, "ten" as *u8); if l > 0 { wl[0] = l; return 10 } 746 l = go_cnt_word_at(s, n, i, "couple" as *u8); if l > 0 { wl[0] = l; return 2 } 747 l = go_cnt_word_at(s, n, i, "few" as *u8); if l > 0 { wl[0] = l; return 3 } 748 return 0 749} 750// THE COUNT CONTRACT: how many photos the turn asks for. A number (digits OR a word) counts ONLY when a photo noun 751// (pic/photo/selfie/shot, any suffix) follows within GO_CNT_MAX_GAP non-letter chars -- "five pics" is a count, "five 752// friends, send a pic" is not. Clamped to [1, GEN_BATCH_CAP]. tok[0]/tok[1] = the number token's start/len (-1 when none) 753// so the scene can be de-counted; the clamp deliberately does not touch the token, the splice replaces it with "a" either way. 754func go_parse_count_any(s: *u8, n: i64, tok: *i64) -> i64 { 755 tok[0] = 0 - 1 756 tok[1] = 0 757 let wl: *i64 = sys_mmap(GO_CNT_TOKBUF) as *i64 758 var i: i64 = 0 759 while i < n { 760 var bound: i64 = 1 761 if i > 0 { let pv: i64 = s[i - 1] as i64; if go_cnt_is_letter(pv) == 1 { bound = 0 } if go_cnt_is_digit(pv) == 1 { bound = 0 } } 762 if bound == 1 { 763 var v: i64 = 0 764 var tl: i64 = 0 765 if go_cnt_is_digit(s[i] as i64) == 1 { 766 var j: i64 = i 767 var dv: i64 = 0 768 var rd: i64 = 1 769 while rd == 1 { if j < n { if go_cnt_is_digit(s[j] as i64) == 1 { dv = dv * GO_CAL_TWO_DIGITS + ((s[j] as i64) - GO_CNT_CH_0); j = j + 1 } else { rd = 0 } } else { rd = 0 } } 770 v = dv 771 tl = j - i 772 } else { 773 v = go_cnt_numword(s, n, i, wl) 774 if v > 0 { tl = wl[0] } 775 } 776 if v > 0 { 777 var p: i64 = i + tl 778 var gap: i64 = 0 779 var seek: i64 = 1 780 while seek == 1 { 781 if p >= n { seek = 0 } else { 782 if go_cnt_is_letter(s[p] as i64) == 1 { seek = 0 } else { gap = gap + 1; if gap > GO_CNT_MAX_GAP { seek = 0 } else { p = p + 1 } } 783 } 784 } 785 var noun: i64 = 0 786 if p < n { 787 if go_cnt_prefix_at(s, n, p, "pic" as *u8) == 1 { noun = 1 } 788 if go_cnt_prefix_at(s, n, p, "photo" as *u8) == 1 { noun = 1 } 789 if go_cnt_prefix_at(s, n, p, "selfie" as *u8) == 1 { noun = 1 } 790 if go_cnt_prefix_at(s, n, p, "shot" as *u8) == 1 { noun = 1 } 791 } 792 if noun == 1 { 793 tok[0] = i 794 tok[1] = tl 795 if v < 1 { v = 1 } 796 if v > GEN_BATCH_CAP { v = GEN_BATCH_CAP } 797 return v 798 } 799 } 800 } 801 i = i + 1 802 } 803 return 1 804} 805// the scene copy the diffusion model reads: the count token replaced by "a", so each of the n images is ONE photo 806func go_scene_decount(s: *u8, n: i64, tok: *i64, out: *u8, cap: i64) -> i64 { 807 var o: i64 = 0 808 var i: i64 = 0 809 while i < n { 810 if i == tok[0] { 811 if o < cap - 1 { out[o] = GO_CNT_CH_A_LO as u8; o = o + 1 } 812 i = i + tok[1] 813 } else { 814 if o < cap - 1 { out[o] = s[i]; o = o + 1 } 815 i = i + 1 816 } 817 } 818 out[o] = 0 as u8 819 return o 820} 821// THE CONVERSATION ALBUM (operator 2026-08-30: one /gallery; /gen keeps only her photos by conversation day). 822// Chat photos append `<epoch>\t<cid>` here; /api/album groups them by day under the operator's clock offset. 823func go_album_append(pcids: *u8, pn: i64) -> i64 { 824 let fd: i64 = sys_openat_append(GO_ALBUM_TSV, 0x1a4) 825 if fd < 0 { return 0 - 1 } 826 let now: i64 = sys_now_us() / GO_US_PER_S2 827 let line: *u8 = sys_mmap(GO_CID_STRIDE * 2) 828 var i: i64 = 0 829 while i < pn { 830 var o: i64 = go_itoa(line, 0, now) 831 line[o] = GO_CH_TAB2 as u8 832 o = o + 1 833 let cidp: *u8 = ((pcids as i64) + i * GO_CID_STRIDE) as *u8 834 var k: i64 = 0 835 while cidp[k] != (0 as u8) { line[o] = cidp[k]; o = o + 1; k = k + 1 } 836 line[o] = GO_CH_NL2 as u8 837 sys_write(fd, line, o + 1) 838 i = i + 1 839 } 840 sys_close(fd) 841 return 0 842} 843// civil date from days-since-1970 (Hinnant's civil_from_days); ymd[0..2] = year, month, day 844func go_civil_from_days(days: i64, ymd: *i64) -> i64 { 845 let z: i64 = days + GO_CAL_EPOCH_TO_ERA0 846 let era: i64 = z / GO_CAL_DAYS_PER_ERA 847 let doe: i64 = z - era * GO_CAL_DAYS_PER_ERA 848 let yoe: i64 = (doe - doe / GO_CAL_DAYS_PER_4Y + doe / GO_CAL_DAYS_PER_100Y - doe / GO_CAL_ERA_LAST_DAY) / GO_CAL_DAYS_PER_YEAR 849 let y0: i64 = yoe + era * GO_CAL_YEARS_PER_ERA 850 let doy: i64 = doe - (GO_CAL_DAYS_PER_YEAR * yoe + yoe / GO_CAL_Q4 - yoe / GO_CAL_Q100) 851 let mp: i64 = (GO_CAL_MARCH_NUM * doy + GO_CAL_MARCH_OFF) / GO_CAL_MARCH_CYCLE 852 let d: i64 = doy - (GO_CAL_MARCH_CYCLE * mp + GO_CAL_MARCH_OFF) / GO_CAL_MARCH_NUM + 1 853 var m: i64 = mp + GO_CAL_MONTH_SHIFT_LO 854 if mp >= GO_CAL_MONTH_WRAP_AT { m = mp - GO_CAL_MONTH_SHIFT_HI } 855 var y: i64 = y0 856 if m <= 2 { y = y + 1 } 857 ymd[0] = y 858 ymd[1] = m 859 ymd[2] = d 860 return 0 861} 862func go_day_str(epoch: i64, offhours: i64, out: *u8) -> i64 { 863 var t: i64 = epoch + offhours * GO_SECS_PER_HOUR 864 if t < 0 { t = 0 } 865 let ymd: *i64 = sys_mmap(GO_CNT_TOKBUF * 2) as *i64 866 go_civil_from_days(t / GO_SECS_PER_DAY, ymd) 867 var o: i64 = go_itoa(out, 0, ymd[0]) 868 out[o] = GO_CH_MINUS as u8 869 o = o + 1 870 if ymd[1] < GO_CAL_TWO_DIGITS { out[o] = GO_CNT_CH_0 as u8; o = o + 1 } 871 o = go_itoa(out, o, ymd[1]) 872 out[o] = GO_CH_MINUS as u8 873 o = o + 1 874 if ymd[2] < GO_CAL_TWO_DIGITS { out[o] = GO_CNT_CH_0 as u8; o = o + 1 } 875 o = go_itoa(out, o, ymd[2]) 876 out[o] = 0 as u8 877 return o 878} 879// PURE album emitter (the gate's subject): tsv rows `<epoch>\t<cid>\n` -> {"days":[{"day":"YYYY-MM-DD","cids":[...]}]} 880// newest day first, rows within a day newest first, at most GO_ALBUM_MAX_DAYS days emitted. 881func go_album_emit(b: *u8, n: i64, offhours: i64, dst: *u8, off: i64) -> i64 { 882 var o: i64 = go_cat(dst, off, "{\"days\":[" as *u8) 883 // index the row starts 884 let starts: *i64 = sys_mmap(GO_ALBUM_ROW_CAP * 8) as *i64 885 var rows: i64 = 0 886 var ls: i64 = 0 887 var i: i64 = 0 888 while i <= n { 889 var atend: i64 = 0 890 if i == n { atend = 1 } else { if (b[i] as i64) == GO_CH_NL2 { atend = 1 } } 891 if atend == 1 { 892 if i > ls { if rows < GO_ALBUM_ROW_CAP { starts[rows * 2] = ls; starts[rows * 2 + 1] = i; rows = rows + 1 } } 893 ls = i + 1 894 } 895 i = i + 1 896 } 897 let daybuf: *u8 = sys_mmap(GO_CNT_TOKBUF * 4) 898 let curday: *u8 = sys_mmap(GO_CNT_TOKBUF * 4) 899 curday[0] = 0 as u8 900 var days: i64 = 0 901 var open: i64 = 0 902 var firstcid: i64 = 1 903 var r: i64 = rows - 1 904 var scan: i64 = 1 905 while scan == 1 { 906 if r < 0 { scan = 0 } else { 907 let rs: i64 = starts[r * 2] 908 let re: i64 = starts[r * 2 + 1] 909 // epoch digits then TAB then cid 910 var ep: i64 = 0 911 var q: i64 = rs 912 while q < re { if go_cnt_is_digit(b[q] as i64) == 1 { ep = ep * GO_CAL_TWO_DIGITS + ((b[q] as i64) - GO_CNT_CH_0); q = q + 1 } else { q = re + re } } 913 var tab: i64 = rs 914 var seekt: i64 = 1 915 while seekt == 1 { if tab < re { if (b[tab] as i64) == GO_CH_TAB2 { seekt = 0 } else { tab = tab + 1 } } else { seekt = 0 } } 916 if tab < re { 917 go_day_str(ep, offhours, daybuf) 918 var same: i64 = 1 919 var c: i64 = 0 920 var cmp: i64 = 1 921 while cmp == 1 { if daybuf[c] != curday[c] { same = 0; cmp = 0 } else { if daybuf[c] == (0 as u8) { cmp = 0 } else { c = c + 1 } } } 922 if same == 0 { 923 if open == 1 { o = go_cat(dst, o, "]}" as *u8) } 924 if days >= GO_ALBUM_MAX_DAYS { scan = 0; open = 0 } else { 925 if days > 0 { o = go_cat(dst, o, "," as *u8) } 926 o = go_cat(dst, o, "{\"day\":\"" as *u8) 927 o = go_cat(dst, o, daybuf) 928 o = go_cat(dst, o, "\",\"cids\":[" as *u8) 929 var cc: i64 = 0 930 while daybuf[cc] != (0 as u8) { curday[cc] = daybuf[cc]; cc = cc + 1 } 931 curday[cc] = 0 as u8 932 days = days + 1 933 open = 1 934 firstcid = 1 935 } 936 } 937 if scan == 1 { 938 if firstcid == 0 { o = go_cat(dst, o, "," as *u8) } 939 firstcid = 0 940 dst[o] = 34 as u8 941 o = o + 1 942 var k2: i64 = tab + 1 943 while k2 < re { dst[o] = b[k2]; o = o + 1; k2 = k2 + 1 } 944 dst[o] = 34 as u8 945 o = o + 1 946 } 947 } 948 r = r - 1 949 } 950 } 951 if open == 1 { o = go_cat(dst, o, "]}" as *u8) } 952 o = go_cat(dst, o, "]}" as *u8) 953 return o 954} 955// the operator's day offset: first signed integer of the conf (cwd first, then the nishihost tree); absent -> 0 956func go_day_offset() -> i64 { 957 let lp: *i64 = sys_mmap(16) as *i64 958 lp[0] = 0 959 var b: *u8 = sys_read_file(GO_DAYOFF_CONF_REL, lp) 960 if lp[0] <= 0 { b = sys_read_file(GO_DAYOFF_CONF_ABS, lp) } 961 if lp[0] <= 0 { return 0 } 962 let n: i64 = lp[0] 963 var i: i64 = 0 964 while i < n { 965 var neg: i64 = 0 966 var j: i64 = i 967 if (b[j] as i64) == GO_CH_MINUS { neg = 1; j = j + 1 } 968 if j < n { if go_cnt_is_digit(b[j] as i64) == 1 { 969 // a digit only counts as the value when the line is not a comment: scan back to line start for '#' 970 var lsx: i64 = j 971 var back: i64 = 1 972 while back == 1 { if lsx > 0 { if (b[lsx - 1] as i64) == GO_CH_NL2 { back = 0 } else { lsx = lsx - 1 } } else { back = 0 } } 973 if (b[lsx] as i64) != 35 { 974 var v: i64 = 0 975 var rd: i64 = 1 976 while rd == 1 { if j < n { if go_cnt_is_digit(b[j] as i64) == 1 { v = v * GO_CAL_TWO_DIGITS + ((b[j] as i64) - GO_CNT_CH_0); j = j + 1 } else { rd = 0 } } else { rd = 0 } } 977 if neg == 1 { return 0 - v } 978 return v 979 } 980 } } 981 i = i + 1 982 } 983 return 0 984} 985// GET /api/album -> her photos by conversation day 986func go_serve_album(cfd: i64) -> i64 { 987 let lp: *i64 = sys_mmap(16) as *i64 988 lp[0] = 0 989 let b: *u8 = sys_read_file(GO_ALBUM_TSV, lp) 990 let out: *u8 = sys_mmap(GO_ALBUM_OUT_CAP) 991 var o: i64 = 0 992 if lp[0] <= 0 { o = go_cat(out, 0, "{\"days\":[]}" as *u8) } else { o = go_album_emit(b, lp[0], go_day_offset(), out, 0) } 993 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, o) 994 return 0 995} 996// conf row `key|value` reader for the feed conf (comment lines skipped); returns value length or 0 997func go_feed_row(b: *u8, n: i64, key: *u8, out: *u8, cap: i64) -> i64 { 998 var ls: i64 = 0 999 var i: i64 = 0 1000 while i <= n { 1001 var atend: i64 = 0 1002 if i == n { atend = 1 } else { if (b[i] as i64) == GO_CH_NL2 { atend = 1 } } 1003 if atend == 1 { 1004 if i > ls { if (b[ls] as i64) != 35 { 1005 var k: i64 = 0 1006 var same: i64 = 1 1007 while key[k] != (0 as u8) { if ls + k >= i { same = 0; k = k + GO_FEED_VAL_CAP } else { if b[ls + k] != key[k] { same = 0; k = k + GO_FEED_VAL_CAP } else { k = k + 1 } } } 1008 if same == 1 { if ls + k < i { if (b[ls + k] as i64) == GO_CH_PIPE2 { 1009 var o: i64 = 0 1010 var q: i64 = ls + k + 1 1011 while q < i { if o < cap - 1 { out[o] = b[q]; o = o + 1 } q = q + 1 } 1012 out[o] = 0 as u8 1013 return o 1014 } } } 1015 } } 1016 ls = i + 1 1017 } 1018 i = i + 1 1019 } 1020 out[0] = 0 as u8 1021 return 0 1022} 1023// THE ONE-GALLERY FEED: after any ingest, each new cid is handed to nx_galx_saveimg so the render SHOWS in /gallery and 1024// SERVES live with no restart (the gallery re-reads its cid tsv fresh per request on a miss). Conf-gated: an absent conf or 1025// enabled!=1 is a no-op and the daemon behaves exactly as before. A feed failure never fails the render -- it is announced 1026// on stderr and the render stands. 1027func go_gallery_feed(cids: *u8, nc: i64, sidecar: *u8) -> i64 { 1028 let lp: *i64 = sys_mmap(16) as *i64 1029 lp[0] = 0 1030 var b: *u8 = sys_read_file(GO_FEED_CONF_REL, lp) 1031 if lp[0] <= 0 { b = sys_read_file(GO_FEED_CONF_ABS, lp) } 1032 if lp[0] <= 0 { return 0 } 1033 let n: i64 = lp[0] 1034 let en: *u8 = sys_mmap(GO_CNT_TOKBUF) 1035 go_feed_row(b, n, "enabled" as *u8, en, GO_CNT_TOKBUF) 1036 if (en[0] as i64) != (GO_CNT_CH_0 + 1) { return 0 } 1037 let elf: *u8 = sys_mmap(GO_FEED_VAL_CAP) 1038 let savedir: *u8 = sys_mmap(GO_FEED_VAL_CAP) 1039 let view: *u8 = sys_mmap(GO_FEED_VAL_CAP) 1040 let cidtsv: *u8 = sys_mmap(GO_FEED_VAL_CAP) 1041 let e1: i64 = go_feed_row(b, n, "elf" as *u8, elf, GO_FEED_VAL_CAP) 1042 let e2: i64 = go_feed_row(b, n, "savedir" as *u8, savedir, GO_FEED_VAL_CAP) 1043 let e3: i64 = go_feed_row(b, n, "view" as *u8, view, GO_FEED_VAL_CAP) 1044 let e4: i64 = go_feed_row(b, n, "cidtsv" as *u8, cidtsv, GO_FEED_VAL_CAP) 1045 if e1 <= 0 { sys_write(GO_STDERR, "GALLERY-FEED conf incomplete (elf/savedir/view/cidtsv) -- feed skipped\n" as *u8, 70); return 0 } 1046 if e2 <= 0 { sys_write(GO_STDERR, "GALLERY-FEED conf incomplete (elf/savedir/view/cidtsv) -- feed skipped\n" as *u8, 70); return 0 } 1047 if e3 <= 0 { sys_write(GO_STDERR, "GALLERY-FEED conf incomplete (elf/savedir/view/cidtsv) -- feed skipped\n" as *u8, 70); return 0 } 1048 if e4 <= 0 { sys_write(GO_STDERR, "GALLERY-FEED conf incomplete (elf/savedir/view/cidtsv) -- feed skipped\n" as *u8, 70); return 0 } 1049 let fout: *u8 = sys_mmap(GO_FEED_OUT_CAP) 1050 let olen: *i64 = sys_mmap(16) as *i64 1051 let fpath: *u8 = sys_mmap(GO_FEED_VAL_CAP) 1052 var fed: i64 = 0 1053 var i: i64 = 0 1054 while i < nc { 1055 let cidp: *u8 = ((cids as i64) + i * GO_CID_STRIDE) as *u8 1056 var cl: i64 = 0 1057 while cidp[cl] != (0 as u8) { cl = cl + 1 } 1058 if cl > 0 { if go_sidecar_lookup(sidecar, cidp, cl, fpath) >= 0 { 1059 let argv: *i64 = sys_mmap(GO_FEED_ARGV_SLOTS * 8) as *i64 1060 argv[0] = elf as i64 1061 argv[1] = fpath as i64 1062 argv[2] = savedir as i64 1063 argv[3] = view as i64 1064 argv[4] = cidtsv as i64 1065 argv[5] = "gen" as *u8 as i64 1066 argv[6] = 0 1067 olen[0] = 0 1068 tr_run_capture_to(elf, argv, fout, GO_FEED_OUT_CAP - 1, olen, GO_FEED_TIMEOUT_MS) 1069 fed = fed + 1 1070 } } 1071 i = i + 1 1072 } 1073 return fed 1074} 1075// go_clamp100 / go_state_* / go_mood_line / go_expr_tokens / go_day_scene -> EXTRACTED to nx_companion_state.nx 1076// (the CompanionState cognitive-core object -- see companion_arch.md). 1077// go_build_photo_prompt -> EXTRACTED to nx_companion_wardrobe.nx (the CompanionWardrobe object -- see companion_arch.md). 1078// CC4 THE SWIPE LOOP (2026-08-30): one chat handler, two modes. REGEN re-answers the latest user turn as a SIBLING (a `swipe` 1079// row, never an overwrite), loads history WITHOUT that turn's earlier siblings, and neither re-remembers nor re-updates state 1080// for a user turn that was already counted once. The mode value doubles as go_mem_load_json_ex's skip_last flag by design. 1081const GO_CHAT_MODE_NORMAL: i64 = 0 1082const GO_CHAT_MODE_REGEN: i64 = 1 1083const GO_JOB_REGEN: i64 = 4 1084const GO_CHAT_MSG_CAP: i64 = 4096 1085const GO_SWIPE_INFO_BYTES: i64 = 64 1086const GO_SWIPE_NUM_CAP: i64 = 32 1087// the latest turn's siblings (32 x a 16 KiB reply) plus the partition must fit one reply 1088const GO_HISTORY_CAP: i64 = 1048576 1089// POST /api/chat -> Elara. Two modes: 1090// SERVER-AUTHORITATIVE (body has "message"): the server owns persona + persistent memory -> builds messages 1091// = [persona system] + [last N remembered turns] + [new user msg], dispatches, STORES the turn, so Elara 1092// stays in character + remembers ACROSS browser sessions/devices. This is the companion substrate. 1093// PASSTHROUGH (body has "messages"): forward the client's array verbatim (back-compat). 1094// Worker selection = same registry + TCP health-check + failover as image gen. 503 if every worker is down. 1095func go_handle_chat_mode(cfd: i64, body: *u8, bn: i64, cfg: *i64, mode: i64) -> i64 { 1096 if bn <= 0 { go_400(cfd, "empty chat body" as *u8); return 0 } 1097 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4] 1098 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64 1099 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64 1100 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa) 1101 1102 // mode select: "message" (single) -> server-authoritative persona+memory; else passthrough of "messages" 1103 let umsg: *u8 = sys_mmap(4096) 1104 let umlen: i64 = go_json_str(body, bn, "message" as *u8, umsg, 4096) 1105 1106 // PHOTO REQUEST ("send me a pic/photo/selfie of you at the beach"): generate image(s) of Elara in the 1107 // described scene, ingest to the gallery, return CIDs + a warm ack. Composes the LIVE image-gen pipeline 1108 // with chat = the "she sends you pics" companion magic (conversational batch, count parsed from the msg). 1109 if umlen > 0 { 1110 var isphoto: i64 = 0 1111 if go_contains_ci(umsg, umlen, "pic" as *u8)==1 { isphoto=1 } 1112 if go_contains_ci(umsg, umlen, "photo" as *u8)==1 { isphoto=1 } 1113 if go_contains_ci(umsg, umlen, "selfie" as *u8)==1 { isphoto=1 } 1114 if isphoto == 1 { 1115 // FIVE-PICS FIX (2026-08-30): digits AND number words count, but only beside a photo noun; the clamp to 1 is 1116 // GONE (the async job lane holds a 5-render turn), and the count token is spliced out of the SCENE the model 1117 // reads -- "five pics" painted a five-panel collage INTO one image while the count was silently clamped to 1. 1118 let ptok: *i64 = sys_mmap(GO_CNT_TOKBUF) as *i64 1119 var pc: i64 = go_parse_count_any(umsg, umlen, ptok) 1120 let pscene: *u8 = sys_mmap(4096) 1121 var pslen: i64 = umlen 1122 if ptok[0] >= 0 { pslen = go_scene_decount(umsg, umlen, ptok, pscene, 4096) } else { var psi: i64 = 0; while psi < umlen { pscene[psi] = umsg[psi]; psi = psi + 1 } pscene[umlen] = 0 as u8 } 1123 let pseed: i64 = sys_now_us() & 0x7fffffff 1124 let stx: *i64 = sys_mmap(64) as *i64 1125 go_state_load(stx) 1126 let expr: *u8 = sys_mmap(256) 1127 go_expr_tokens(stx, expr) 1128 // OCCLUSION-AWARE compiler: identity (anatomy-neutral) + scene + per-zone clothing-OR-bare resolution 1129 // (fabric-covers assertion when clothed, bare only when the scene asks) → clothed shots stay clothed, 1130 // nude only on request = the controllable wardrobe layer. Then style-variety + realism loras. 1131 let pprompt: *u8 = sys_mmap(16384) 1132 // ONE COMPOSER (2026-08-27): realism trigger -> camera line -> identity/scene body, owned by 1133 // go_compose_photo_prompt (nx_companion_wardrobe.nx) and SHARED with nx_elara_prompt_probe, so the 1134 // slot order lives in exactly one place. (Camera-first, 2026-08-06, is preserved inside it; the 1135 // June-repro A/B of 2026-08-19 measured the leading trigger as the dominant term of the June look.) 1136 var ppo: i64 = go_compose_photo_prompt(pscene, pslen, expr, pseed, pprompt) 1137 // COHERENCE PREVENTATIVE (render_bug_register #1 = wet_without_context, 40% of bugs): reframe incoherent 1138 // standing-water "wet" -> a coherent skin-sheen descriptor BEFORE scoring/rendering (wet-in-shower untouched). 1139 // OPT-IN ONLY: compute the suggested fix always, but APPLY it (rewrite what we render) only when the operator 1140 // sets elara_coherence.txt=apply. Default = flag-only -> render the user's EXACT words, never silently override. 1141 let prepd: *u8 = sys_mmap(16384); let rfired: *i64 = sys_mmap(16) as *i64 1142 let rlen: i64 = go_coherence_repair(pprompt, ppo, prepd, rfired) 1143 if go_coherence_enabled() == 1 { var rci: i64 = 0; while rci < rlen { pprompt[rci]=prepd[rci]; rci=rci+1 } ppo = rlen; pprompt[ppo]=0 as u8 } 1144 else { rfired[0]=0 } 1145 // ANTI-BODY-HORROR QC: score the composed (repaired) prompt for anatomy-failure risk (pre-render, no GPU). 1146 // Higher = safer; the fired factors say WHY. Surfaced in the response so a bad gen is diagnosable, not mystery. 1147 let arfac: *u8 = sys_mmap(512) 1148 let arisk: i64 = go_anatomy_risk(pprompt, ppo, arfac) 1149 if rfired[0]==1 { var wfo: i64 = go_slen(arfac); wfo = go_cat(arfac, wfo, "wetfix," as *u8); arfac[wfo]=0 as u8 } 1150 // MONITOR pillar (render_bug_register): the daemon (elderwesto) appends risk<TAB>factors<TAB>scene so the 1151 // rate is trackable over time and nx_fs-readable (bypasses the root-owned sudo-script capture problem). 1152 let alog: i64 = sys_openat_append("anatomy_audit.tsv" as *u8, 0x1a4) 1153 if alog >= 0 { 1154 let ll: *u8 = sys_mmap(2048); var lo: i64 = go_itoa(ll, 0, arisk); ll[lo]=9 as u8; lo=lo+1 1155 lo = go_cat(ll, lo, arfac); ll[lo]=9 as u8; lo=lo+1 1156 var asi: i64 = 0 1157 while umsg[asi]!=(0 as u8) { if asi < 180 { if (umsg[asi]&0xff) >= 32 { ll[lo]=umsg[asi]; lo=lo+1 } } asi=asi+1 } 1158 ll[lo]=10 as u8; lo=lo+1 1159 sys_write(alog, ll, lo); sys_close(alog) 1160 } 1161 let ploras: *u8 = sys_mmap(512); go_load_loras(ploras, 512) 1162 ppo = go_cat(pprompt, ppo, " " as *u8); ppo = go_cat(pprompt, ppo, ploras) 1163 let pcfg: *u8 = sys_mmap(8); let pcn: i64 = go_cat(pcfg, 0, "1.0" as *u8); pcfg[pcn]=0 as u8 1164 let pneg: *u8 = sys_mmap(4); pneg[0]=0 as u8 1165 // seed INSIDE extra_args (top-level seed is ignored by the engine) so each selfie is a DIFFERENT image 1166 // STEPS: pass the SENTINEL 0, never a literal. 0 = "caller said nothing" -> go_append_turbo_args 1167 // resolves knowledge/gen_steps.conf via go_default_steps(). A literal 8 sits ABOVE GO_STEPS_FLOOR, 1168 // so the resolver NEVER ran and this path silently ignored the operator's configured value: the 1169 // conf has said 12 since 2026-08-04 while every chat photo still rendered at 8, and a standing 1170 // 2026-07-25 measurement records 8 as visibly soft at 768x1024 with the realism LoRAs. 1171 // This is the SAME defect the /api/generate comment warns about, still live in its sibling site. 1172 // *** LAW: A DEFAULT MOVED TO CONFIG IS STILL A LITERAL IF ANOTHER CALL SITE KEEPS ONE. 1173 ppo = go_append_turbo_args(pprompt, ppo, 0, pcfg, pneg, pseed) 1174 pprompt[ppo]=0 as u8 1175 let wreqp: *u8 = sys_mmap(16384) 1176 var wo: i64 = go_cat(wreqp, 0, "{\"prompt\":" as *u8) 1177 wo = go_emit_jstr(wreqp, wo, pprompt) 1178 wo = go_cat(wreqp, wo, ",\"n\":" as *u8); wo = go_itoa(wreqp, wo, pc) 1179 wo = go_cat(wreqp, wo, ",\"size\":\"" as *u8); wo = go_cat(wreqp, wo, GO_PHOTO_SIZE); wo = go_cat(wreqp, wo, "\",\"seed\":" as *u8); wo = go_itoa(wreqp, wo, pseed) 1180 wo = go_cat(wreqp, wo, ",\"response_format\":\"b64_json\"}" as *u8) 1181 let pcap: i64 = 25165824 1182 let presp: *u8 = sys_mmap(pcap) 1183 var prn: i64 = 0 - 1 1184 var pwi: i64 = 0 1185 while pwi < wcount { 1186 if go_worker_up(wa[pwi], wb[pwi], wc[pwi], wd[pwi], wpa[pwi]) == 1 { 1187 let pr: i64 = go_worker_dispatch(wa[pwi], wb[pwi], wc[pwi], wd[pwi], wpa[pwi], wreqp, wo, presp, pcap) 1188 if pr > 0 { prn = pr; pwi = wcount } else { pwi = pwi + 1 } 1189 } else { pwi = pwi + 1 } 1190 } 1191 if prn <= 0 { go_503(cfd, "no gpu worker available for photos" as *u8); return 0 } 1192 let pbs: i64 = go_body_start(presp, prn) 1193 let pbody: *u8 = (presp as i64 + pbs) as *u8 1194 let pblen: i64 = prn - pbs 1195 let pcids: *u8 = sys_mmap(GEN_BATCH_CAP * 80) 1196 let psteps: *u8 = sys_mmap(16); go_itoa(psteps, 0, 8) 1197 let psamp: *u8 = sys_mmap(16); let pj: i64 = go_cat(psamp, 0, "euler" as *u8); psamp[pj]=0 as u8 1198 // SAME const the request above used -- not a mirrored literal (debt 1785882708). 1199 let psize: *u8 = sys_mmap(32); let pzi: i64 = go_cat(psize, 0, GO_PHOTO_SIZE); psize[pzi] = 0 as u8 1200 let pn: i64 = gp_response(pbody, pblen, pseed, "z_image_turbo" as *u8, psamp, psteps, cfg[8] as *u8, pprompt, psize, pprompt, cfg[5] as *u8, cfg[6] as *u8, cfg[7] as *u8, pcids, pc) 1201 // the conversation album (chat photos only) + the one-gallery feed 1202 if pn > 0 { go_album_append(pcids, pn); go_gallery_feed(pcids, pn, cfg[7] as *u8) } 1203 if mode == GO_CHAT_MODE_REGEN { if pn > 0 { go_mem_append("swipe" as *u8, "[sent you photos]" as *u8) } } else { 1204 go_mem_append("user" as *u8, umsg) 1205 if pn > 0 { go_mem_append("assistant" as *u8, "[sent you photos]" as *u8) } 1206 } 1207 let outp: *u8 = sys_mmap(8192) 1208 var oo: i64 = go_cat(outp, 0, "{\"choices\":[{\"finish_reason\":\"stop\",\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\"Here you go, hope you like them \"}}],\"images\":[" as *u8) 1209 var ci: i64 = 0 1210 while ci < pn { 1211 if ci > 0 { outp[oo]=44 as u8; oo=oo+1 } 1212 outp[oo]=34 as u8; oo=oo+1 1213 let cidp: *u8 = (pcids as i64 + ci*80) as *u8 1214 var cj: i64 = 0 1215 while cidp[cj]!=(0 as u8) { outp[oo]=cidp[cj]; oo=oo+1; cj=cj+1 } 1216 outp[oo]=34 as u8; oo=oo+1 1217 ci = ci + 1 1218 } 1219 oo = go_cat(outp, oo, "],\"anatomy_risk\":" as *u8); oo = go_itoa(outp, oo, arisk) 1220 oo = go_cat(outp, oo, ",\"anatomy_factors\":\"" as *u8); oo = go_cat(outp, oo, arfac); oo = go_cat(outp, oo, "\"}" as *u8) 1221 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, outp, oo) 1222 return 0 1223 } 1224 } 1225 1226 var sendbody: *u8 = body 1227 var sendlen: i64 = bn 1228 var servermode: i64 = 0 1229 if umlen > 0 { 1230 servermode = 1 1231 let stp: *i64 = sys_mmap(64) as *i64 1232 go_state_load(stp) 1233 let persona: *u8 = sys_mmap(16384) 1234 let plen0: i64 = go_load_persona(persona, 4096) 1235 let ml: *u8 = sys_mmap(256) 1236 go_mood_line(stp, ml) 1237 var mpp: i64 = plen0 1238 var mmi: i64 = 0 1239 while ml[mmi]!=(0 as u8) { persona[mpp]=ml[mmi]; mpp=mpp+1; mmi=mmi+1 } 1240 mpp = go_day_scene(persona, mpp) 1241 // CC0 (2026-08-30): what she IS now, who they ARE to each other, what they SAID before -- composed from the promoted 1242 // memory/relationship/state organs by nx_companion_mind; zero bytes when the stores are empty (nx_gen_mind_gate 1243 // proves both directions). Before this line the chat turn never consulted them -- the intelligence was built and dark. 1244 mpp = mpp + go_mind_context(umsg, umlen, ((persona as i64) + mpp) as *u8, 16384 - mpp - 1) 1245 persona[mpp]=0 as u8 1246 let wreq: *u8 = sys_mmap(131072) 1247 var o2: i64 = go_cat(wreq, 0, "{\"messages\":[{\"role\":\"system\",\"content\":" as *u8) 1248 o2 = go_emit_jstr(wreq, o2, persona) 1249 o2 = go_cat(wreq, o2, "}" as *u8) 1250 o2 = go_mem_load_json_ex(wreq, o2, 32, mode) 1251 o2 = go_cat(wreq, o2, ",{\"role\":\"user\",\"content\":" as *u8) 1252 o2 = go_emit_jstr(wreq, o2, umsg) 1253 o2 = go_cat(wreq, o2, "}],\"max_tokens\":400,\"temperature\":0.85}" as *u8) 1254 sendbody = wreq; sendlen = o2 1255 } 1256 1257 // dispatch WITH RETRY: the engine's chat endpoint intermittently returns headers + an EMPTY body (an empty 1258 // completion, esp. under a long system prompt / rapid turns) -> retry up to 3x with a short recovery delay 1259 // so a transient empty response never surfaces as a 503 to the user. 1260 let respcap: i64 = 262144 1261 let resp: *u8 = sys_mmap(respcap) 1262 var rn: i64 = 0 - 1 1263 var bs: i64 = 0 1264 var bodylen: i64 = 0 1265 // G17 (2026-08-30) ON THE CHAT PATH TOO: the generate path learned to name its failing conjunct, but this loop 1266 // still discarded gw_read_full's three-valued failure and blamed worker absence. A fix in one sibling and not the 1267 // other is half a fix, and the half left undone was the one the companion chat hit every 25 s timeout. 1268 // CC6 (2026-08-30) MIXED-LLM ROUTING: a data row (llm_routes.conf) may send this turn to a stronger backend FIRST; the 1269 // local encoder-LLM stays the fallback, and the reply records which one answered (model_route) so a route is never silent. 1270 let rtag: *u8 = sys_mmap(64) 1271 rtag[0] = 0 as u8 1272 let rw: *i64 = sys_mmap(8 * 8) as *i64 1273 var routed: i64 = 0 1274 if umlen > 0 { routed = go_llm_route(umsg, umlen, rtag, rw) } 1275 if routed == 1 { wcount = go_llm_route_prepend(rw, wa, wb, wc, wd, wpa, wcount) } 1276 var rwin: i64 = 0 - 1 1277 var clastfail: i64 = 0 1278 var canyup: i64 = 0 1279 var tries: i64 = 0 1280 while tries < 3 { 1281 rn = 0 - 1 1282 var wi: i64 = 0 1283 while wi < wcount { 1284 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 { 1285 canyup = 1 1286 let r: i64 = go_chat_dispatch(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], sendbody, sendlen, resp, respcap) 1287 if r > 0 { rn = r; rwin = wi; wi = wcount } else { clastfail = r; wi = wi + 1 } 1288 } else { wi = wi + 1 } 1289 } 1290 if rn > 0 { bs = go_body_start(resp, rn); bodylen = rn - bs } else { bodylen = 0 } 1291 if bodylen > 0 { tries = 3 } else { tries = tries + 1; if tries < 3 { sys_sleep_ms(300) } } 1292 } 1293 if rn <= 0 { 1294 if canyup == 1 { 1295 if clastfail == 0 - 3 { 1296 // the budget is a conf row now (gen_chat_budget.conf); the message reads the same value the dispatch used, never a literal 1297 let bm: *u8 = sys_mmap(512) 1298 var bmo: i64 = go_cat(bm, 0, "chat worker BUSY-TIMEOUT: it accepted the connection and returned nothing inside the chat budget of " as *u8) 1299 bmo = go_itoa(bm, bmo, gw_chat_budget_s()) 1300 bmo = go_cat(bm, bmo, " s (gen_chat_budget.conf, 3 tries). The model may be loading or another job holds the card. This is a TIMEOUT, not an absent worker." as *u8) 1301 bm[bmo] = 0 as u8 1302 go_503(cfd, bm); return 0 1303 } 1304 if clastfail == 0 - 4 { go_503(cfd, "chat worker PARTIAL-READ then timeout: the completion was truncated mid-body" as *u8); return 0 } 1305 if clastfail == 0 - 2 { go_503(cfd, "chat worker CONNECT-REFUSED immediately after passing its health probe" as *u8); return 0 } 1306 if clastfail == 0 - 1 { go_503(cfd, "socket creation failed on the chat dispatch path (a local resource limit, not the worker)" as *u8); return 0 } 1307 go_503(cfd, "chat worker health-probed UP but closed without answering (clean EOF on every try)" as *u8); return 0 1308 } 1309 go_503(cfd, "no chat worker passed its TCP health probe (all candidates down)" as *u8); return 0 1310 } 1311 let bodyp: *u8 = (resp as i64 + bs) as *u8 1312 if bodylen <= 0 { go_503(cfd, "chat worker returned no body" as *u8); return 0 } 1313 // server-authoritative: strip the think-block, persist BOTH turns (so Elara remembers), return a CLEAN reply 1314 if servermode == 1 { 1315 let reply: *u8 = sys_mmap(8192) 1316 let rlen: i64 = go_json_str(bodyp, bodylen, "content" as *u8, reply, 8192) 1317 if rlen > 0 { 1318 let clean: *u8 = sys_mmap(8192) 1319 go_strip_think(reply, clean, 8192) 1320 if mode == GO_CHAT_MODE_REGEN { go_mem_append("swipe" as *u8, clean) } else { 1321 go_mem_append("user" as *u8, umsg) 1322 go_mem_append("assistant" as *u8, clean) 1323 go_mind_remember(umsg, umlen) // CC0: the turn enters long-term memory AFTER the reply, so it never recalls itself 1324 let stu: *i64 = sys_mmap(64) as *i64 1325 go_state_load(stu) 1326 go_state_update(stu, umsg, umlen) 1327 go_state_save(stu) 1328 } 1329 // CC4: every reply names its place among the turn's siblings, so the UI can swipe without a second round trip 1330 let swi: *i64 = sys_mmap(GO_SWIPE_INFO_BYTES) as *i64 1331 go_mem_last_turn(swi) 1332 var swidx: i64 = swi[1] 1333 if swidx < 0 { swidx = 0 } 1334 let rj: *u8 = sys_mmap(16384) 1335 var ro: i64 = go_cat(rj, 0, "{\"choices\":[{\"finish_reason\":\"stop\",\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":" as *u8) 1336 ro = go_emit_jstr(rj, ro, clean) 1337 ro = go_cat(rj, ro, "}}],\"swipe\":{\"index\":" as *u8) 1338 ro = go_itoa(rj, ro, swidx) 1339 ro = go_cat(rj, ro, ",\"count\":" as *u8) 1340 ro = go_itoa(rj, ro, swi[0]) 1341 ro = go_cat(rj, ro, "},\"model_route\":\"" as *u8) 1342 ro = go_llm_route_label(routed, rwin, rtag, rj, ro) 1343 ro = go_cat(rj, ro, "\"}" as *u8) 1344 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, rj, ro) 1345 return 0 1346 } 1347 if mode != GO_CHAT_MODE_REGEN { go_mem_append("user" as *u8, umsg) } 1348 } 1349 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, bodyp, bodylen) 1350 return 0 1351} 1352func go_handle_chat(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 { return go_handle_chat_mode(cfd, body, bn, cfg, GO_CHAT_MODE_NORMAL) } 1353 1354// --- CC4 THE SWIPE LOOP (2026-08-30) -- regenerate / select / edit / history over the append-only branch-aware log -------- 1355// regenerate: the latest user turn is answered AGAIN as a sibling (a `swipe` row -- never an overwrite); the history the model 1356// sees excludes that turn's earlier siblings, so the new answer is independent of the one being swiped away. 1357func go_handle_regen(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 { 1358 let lu: *u8 = sys_mmap(GO_CHAT_MSG_CAP) 1359 let ln: i64 = go_mem_last_user(lu, GO_CHAT_MSG_CAP) 1360 if ln <= 0 { go_400(cfd, "nothing to regenerate: the chat log holds no user turn yet" as *u8); return 0 } 1361 let b2: *u8 = sys_mmap(GO_CHAT_MSG_CAP * 2) 1362 var o: i64 = go_cat(b2, 0, "{\"message\":" as *u8) 1363 o = go_emit_jstr(b2, o, lu) 1364 o = go_cat(b2, o, "}" as *u8) 1365 return go_handle_chat_mode(cfd, b2, o, cfg, GO_CHAT_MODE_REGEN) 1366} 1367// select: the displayed sibling of the latest turn becomes <index>; out of range is refused BY NAME, never guessed 1368func go_handle_chat_select(cfd: i64, body: *u8, bn: i64) -> i64 { 1369 let swi: *i64 = sys_mmap(GO_SWIPE_INFO_BYTES) as *i64 1370 let nt: i64 = go_mem_last_turn(swi) 1371 if nt <= 0 { go_400(cfd, "nothing to select: the chat log holds no turn yet" as *u8); return 0 } 1372 let idx: i64 = go_json_int(body, bn, "index" as *u8, 0 - 1) 1373 if idx < 0 { go_400(cfd, "select needs a non-negative index" as *u8); return 0 } 1374 if idx >= swi[0] { 1375 let m: *u8 = sys_mmap(256) 1376 var mo: i64 = go_cat(m, 0, "index out of range: this turn has " as *u8) 1377 mo = go_itoa(m, mo, swi[0]) 1378 mo = go_cat(m, mo, " sibling(s)" as *u8) 1379 m[mo] = 0 as u8 1380 go_400(cfd, m); return 0 1381 } 1382 let ix: *u8 = sys_mmap(GO_SWIPE_NUM_CAP) 1383 let io: i64 = go_itoa(ix, 0, idx) 1384 ix[io] = 0 as u8 1385 go_mem_append("select" as *u8, ix) 1386 let out: *u8 = sys_mmap(256) 1387 var oo: i64 = go_cat(out, 0, "{\"selected\":" as *u8) 1388 oo = go_itoa(out, oo, idx) 1389 oo = go_cat(out, oo, ",\"count\":" as *u8) 1390 oo = go_itoa(out, oo, swi[0]) 1391 oo = go_cat(out, oo, "}" as *u8) 1392 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, oo) 1393 return 0 1394} 1395// edit: the displayed reply's text is replaced for display AND context; the original row stays in the log (additive) 1396func go_handle_chat_edit(cfd: i64, body: *u8, bn: i64) -> i64 { 1397 let swi: *i64 = sys_mmap(GO_SWIPE_INFO_BYTES) as *i64 1398 let nt: i64 = go_mem_last_turn(swi) 1399 if nt <= 0 { go_400(cfd, "nothing to edit: the chat log holds no turn yet" as *u8); return 0 } 1400 if swi[0] <= 0 { go_400(cfd, "nothing to edit: the latest turn has no reply yet" as *u8); return 0 } 1401 let txt: *u8 = sys_mmap(GO_CHAT_MSG_CAP) 1402 let tn: i64 = go_json_str(body, bn, "text" as *u8, txt, GO_CHAT_MSG_CAP) 1403 if tn <= 0 { go_400(cfd, "edit needs a non-empty text" as *u8); return 0 } 1404 go_mem_append("edit" as *u8, txt) 1405 let out: *u8 = sys_mmap(GO_HISTORY_CAP) 1406 var oo: i64 = go_cat(out, 0, "{\"edited\":1," as *u8) 1407 oo = go_mem_last_turn_json(out, oo) 1408 oo = go_cat(out, oo, "}" as *u8) 1409 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, oo) 1410 return 0 1411} 1412// GET /api/chat_history -> the latest turn's siblings, selection and display, plus the printed partition (sums shown, not asserted) 1413func go_serve_chat_history(cfd: i64) -> i64 { 1414 let out: *u8 = sys_mmap(GO_HISTORY_CAP) 1415 var oo: i64 = go_cat(out, 0, "{" as *u8) 1416 oo = go_mem_last_turn_json(out, oo) 1417 oo = go_cat(out, oo, ",\"partition\":" as *u8) 1418 oo = go_mem_partition(out, oo) 1419 oo = go_cat(out, oo, "}" as *u8) 1420 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, oo) 1421 return 0 1422} 1423 1424 1425// --- POST /api/write -- THE WRITE LANE ON THE SAME SURFACE AS IMAGES ------------------------------- 1426// Body: {"mode":"scenario","prompt":"..."} -> {"mode":..,"register":..,"text":"..."} 1427// Reuses go_chat_dispatch (the PROVEN engine path this daemon already uses for chat) and the SAME 1428// worker candidate list as image gen, so writing inherits the swarm-SSOT endpoint resolution and the 1429// failover for free. One surface now produces images AND prose. 1430// ★THE SEAM IS CHECKED HERE TOO, not just in the CLI: an `explicit` register may only run on the 1431// `local` lane. A capability reachable over HTTP must carry its own guarantees -- a rule that lives 1432// only in a command-line tool is not a rule, it is a habit. 1433// plain NUL-terminated compare. go_name_eq is a /mesh/<x>.stl PATH matcher, not this -- using it 1434// here was a category error that the arity check caught before it could silently mis-route a mode. 1435func go_streq(a: *u8, b: *u8) -> i64 { 1436 var i: i64 = 0 1437 while a[i] != (0 as u8) { if a[i] != b[i] { return 0 } i = i + 1 } 1438 if b[i] != (0 as u8) { return 0 } 1439 return 1 1440} 1441 1442const GO_W_PROMPT_CAP: i64 = 8192 1443const GO_W_REQ_CAP: i64 = 65536 1444const GO_W_RESP_CAP: i64 = 262144 1445// SSOT = the seg-store plane (migrated 2026-08-05; the old write_modes.tsv is a tombstone). 1446// ABSOLUTE prefix: this daemon's CWD is /volume1/ai/gen, and a relative knowledge/ prefix would 1447// resolve into the WRONG TREE -- the exact CWD-artifact class banked estate-wide. 1448const GO_WPLANE: *u8 = "/volume1/homes/elderwesto/nishihost/knowledge/store/writemode-" 1449 1450// find mode row -> register + structure. 1 = found, 0 = unknown, -1 = registry unreadable. 1451func go_wmode(mode: *u8, reg: *u8, lane: *u8, structure: *u8) -> i64 { 1452 let buf: *u8 = sys_mmap(GO_W_RESP_CAP) 1453 let n: i64 = sts_load(GO_WPLANE, buf, GO_W_RESP_CAP) 1454 if n <= 0 { return 0 - 1 } 1455 var p: i64 = 0 1456 while p < n { 1457 var e: i64 = n 1458 var q: i64 = p 1459 var go: i64 = 1 1460 while go == 1 { 1461 if q >= n { e = n; go = 0 } else { if buf[q] == (10 as u8) { e = q; go = 0 } else { q = q + 1 } } 1462 } 1463 if e > p { if buf[p] != (35 as u8) { 1464 // field 0 = mode name 1465 var k: i64 = 0 1466 var m: i64 = 1 1467 while mode[k] != (0 as u8) { 1468 if p + k >= e { m = 0; k = go_slen(mode) } else { 1469 if buf[p + k] != mode[k] { m = 0; k = go_slen(mode) } else { k = k + 1 } 1470 } 1471 } 1472 if m == 1 { if p + k < e { if buf[p + k] == (9 as u8) { 1473 // walk fields 1,2,3 1474 var fp: i64 = p + k + 1 1475 var fi: i64 = 1 1476 while fi <= 3 { 1477 var fe: i64 = fp 1478 var g2: i64 = 1 1479 while g2 == 1 { if fe >= e { g2 = 0 } else { if buf[fe] == (9 as u8) { g2 = 0 } else { fe = fe + 1 } } } 1480 var w: i64 = 0 1481 var dst: *u8 = reg 1482 if fi == 2 { dst = lane } 1483 if fi == 3 { dst = structure } 1484 while fp + w < fe { if w < 63 { dst[w] = buf[fp + w] } w = w + 1 } 1485 if w > 63 { w = 63 } 1486 dst[w] = 0 as u8 1487 fp = fe + 1 1488 fi = fi + 1 1489 } 1490 return 1 1491 } } } 1492 } } 1493 p = e + 1 1494 } 1495 return 0 1496} 1497 1498func go_wsys(structure: *u8, out: *u8) -> i64 { 1499 var o: i64 = go_cat(out, 0, "You are a skilled prose writer. Write the piece itself with no preamble and no meta-commentary. " as *u8) 1500 if go_streq(structure, "scenario" as *u8) == 1 { o = go_cat(out, o, "Open a scenario the reader can step into: introduce the speaker, establish the situation already in motion, then address the reader directly." as *u8) } 1501 else { if go_streq(structure, "scene" as *u8) == 1 { o = go_cat(out, o, "Write a scene with concrete sensory detail; end on a beat that invites what comes next." as *u8) } 1502 else { if go_streq(structure, "panel" as *u8) == 1 { o = go_cat(out, o, "Write a page script as numbered PANEL blocks: one line of visual description, then dialogue." as *u8) } 1503 else { if go_streq(structure, "imrad" as *u8) == 1 { o = go_cat(out, o, "Use IMRaD structure and be precise." as *u8) } 1504 else { if go_streq(structure, "convo" as *u8) == 1 { o = go_cat(out, o, "Write a natural back-and-forth that keeps the topic moving." as *u8) } 1505 else { o = go_cat(out, o, "Write clearly and vividly in the form the request implies." as *u8) } } } } } 1506 out[o] = 0 as u8 1507 return o 1508} 1509 1510// epoch -> decimal into buf at off; returns the new offset. Buffer twin of the fd-writing emitter 1511// this file already carries -- needed because the queue job FILENAME must hold the id before any fd 1512// exists. Digits gathered LSB-first then emitted in REVERSE: the estate found 211 formatters today 1513// whose reverse-emit loop was destroyed, so the idiom is spelled out rather than assumed. 1514func go_wq_catn(b: *u8, off: i64, v: i64) -> i64 { 1515 var x: i64 = v 1516 if x <= 0 { b[off] = 48 as u8; return off + 1 } 1517 let t: *u8 = sys_mmap(32) 1518 var k: i64 = 0 1519 while x > 0 { t[k] = (48 + x % 10) as u8; x = x / 10; k = k + 1 } 1520 var o: i64 = off 1521 while k > 0 { k = k - 1; b[o] = t[k]; o = o + 1 } 1522 return o 1523} 1524 1525func go_handle_write(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 { 1526 if bn <= 0 { go_400(cfd, "empty write body -- POST {\\\"mode\\\":\\\"scenario\\\",\\\"prompt\\\":\\\"...\\\"}; modes live on the writemode- plane (nx_write modes)" as *u8); return 0 } 1527 let mode: *u8 = sys_mmap(64) 1528 if go_json_str(body, bn, "mode" as *u8, mode, 64) <= 0 { go_400(cfd, "write needs a \\\"mode\\\" (scenario, manga, paper, roleplay, ...)" as *u8); return 0 } 1529 let prompt: *u8 = sys_mmap(GO_W_PROMPT_CAP) 1530 if go_json_str(body, bn, "prompt" as *u8, prompt, GO_W_PROMPT_CAP) <= 0 { go_400(cfd, "write needs a \\\"prompt\\\"" as *u8); return 0 } 1531 1532 let reg: *u8 = sys_mmap(64) 1533 let lane: *u8 = sys_mmap(64) 1534 let structure: *u8 = sys_mmap(64) 1535 let f: i64 = go_wmode(mode, reg, lane, structure) 1536 if f < 0 { go_503(cfd, "writemode- plane unseeded/unreadable -- the plane is the SSOT and nothing is guessed" as *u8); return 0 } 1537 if f == 0 { go_400(cfd, "unknown mode -- run nx_write modes (writemode- plane)" as *u8); return 0 } 1538 if go_streq(reg, "explicit" as *u8) == 1 { 1539 if go_streq(lane, "local" as *u8) == 0 { 1540 go_400(cfd, "refused: an explicit register may only run on the local lane (fix the registry row)" as *u8); return 0 1541 } 1542 } 1543 1544 let sysp: *u8 = sys_mmap(4096) 1545 go_wsys(structure, sysp) 1546 let wreq: *u8 = sys_mmap(GO_W_REQ_CAP) 1547 var o: i64 = go_cat(wreq, 0, "{\"model\":\"local\",\"max_tokens\":1200,\"messages\":[{\"role\":\"system\",\"content\":" as *u8) 1548 o = go_emit_jstr(wreq, o, sysp) 1549 o = go_cat(wreq, o, "},{\"role\":\"user\",\"content\":" as *u8) 1550 o = go_emit_jstr(wreq, o, prompt) 1551 o = go_cat(wreq, o, "}]}" as *u8) 1552 1553 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4] 1554 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64 1555 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64 1556 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa) 1557 let respcap: i64 = GO_W_RESP_CAP 1558 let resp: *u8 = sys_mmap(respcap) 1559 var rn: i64 = 0 - 1 1560 var wi: i64 = 0 1561 while wi < wcount { 1562 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 { 1563 let r: i64 = go_chat_dispatch(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], wreq, o, resp, respcap) 1564 if r > 0 { rn = r; wi = wcount } else { wi = wi + 1 } 1565 } else { wi = wi + 1 } 1566 } 1567 if rn <= 0 { 1568 // u2605DEGRADE TO THE QUEUE, NEVER TO A REFUSAL (constitution A15). Off-LAN the GPU cannot be 1569 // dialled -- it PULLS. A 503 here refused exactly when the queue is the design answer: bank 1570 // the request as a wq job and tell the caller where the result will land. The path is 1571 // ABSOLUTE because this daemon runs with CWD=/volume1/ai/gen -- a relative write would bank 1572 // the job where no worker looks (the artifacts-never-placed law), and the failure would 1573 // wear the shape of a slow worker instead of a wrong path. 1574 let ep: i64 = sys_now_realtime_sec() 1575 let jp: *u8 = sys_mmap(256) 1576 var jo: i64 = go_cat(jp, 0, "/volume1/homes/elderwesto/nishihost/knowledge/wq/wq_" as *u8) 1577 jo = go_wq_catn(jp, jo, ep) 1578 jo = go_cat(jp, jo, ".job" as *u8) 1579 jp[jo] = 0 as u8 1580 let jb: *u8 = sys_mmap(GO_W_REQ_CAP) 1581 var jn: i64 = go_cat(jb, 0, "{\"mode\":" as *u8) 1582 jn = go_emit_jstr(jb, jn, mode) 1583 jn = go_cat(jb, jn, ",\"prompt\":" as *u8) 1584 jn = go_emit_jstr(jb, jn, prompt) 1585 jn = go_cat(jb, jn, "}" as *u8) 1586 let jfd: i64 = sys_openat_wr(jp, 0x1a4) 1587 if jfd < 0 { go_503(cfd, "no engine AND the queue is unwritable -- both roads closed; check knowledge/wq exists" as *u8); return 0 } 1588 sys_write(jfd, jb, jn) 1589 sys_close(jfd) 1590 let rb: *u8 = sys_mmap(512) 1591 var ro: i64 = go_cat(rb, 0, "{\"queued\":1,\"job\":\"wq_" as *u8) 1592 ro = go_wq_catn(rb, ro, ep) 1593 ro = go_cat(rb, ro, "\",\"result\":\"knowledge/wq/wq_" as *u8) 1594 ro = go_wq_catn(rb, ro, ep) 1595 ro = go_cat(rb, ro, ".done\",\"note\":\"no engine reachable; job banked for the pull swarm (A15) -- poll the result path\"}" as *u8) 1596 go_send(cfd, "202 Accepted" as *u8, "application/json" as *u8, rb, ro) 1597 return 0 1598 } 1599 let bs: i64 = go_body_start(resp, rn) 1600 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, (resp as i64 + bs) as *u8, rn - bs) 1601 return 0 1602} 1603 1604// --- the 3D lane: POST /api/mesh (t2mesh -> surface-nets -> STL) + GET /mesh/<obj>.stl --- 1605// The daemon forks per connection, so the big field/mesh mmaps are reclaimed by the kernel on child 1606// exit (same memory discipline as the gallery upscaler) -- no leak in the long-lived parent. 1607func go_wfs(fd: i64, s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} sys_write(fd, s, n); return 0 } 1608func go_stlnum(fd: i64, v: i64) -> i64 { 1609 let b: *u8 = sys_mmap(32) as *u8 1610 var x: i64 = v; var neg: i64 = 0 1611 if x < 0 { neg = 1; x = 0 - x } 1612 var i: i64 = 31 1613 if x == 0 { b[i] = 48 as u8; i = i - 1 } 1614 while x > 0 { b[i] = (48 + x % 10) as u8; x = x / 10; i = i - 1 } 1615 if neg == 1 { b[i] = 45 as u8; i = i - 1 } 1616 sys_write(fd, (b as i64 + i + 1) as *u8, 31 - i); sys_write(fd, " " as *u8, 1); return 0 1617} 1618func go_write_stl(vbuf: *i64, fbuf: *i64, nf: i64, path: *u8) -> i64 { 1619 let fd: i64 = sys_openat_wr(path, 0x1a4) 1620 if fd < 0 { return 0 - 1 } 1621 go_wfs(fd, "solid nishi_t2m\n" as *u8) 1622 var t: i64 = 0 1623 while t < nf { 1624 let a: i64 = fbuf[t * 3]; let b: i64 = fbuf[t * 3 + 1]; let c: i64 = fbuf[t * 3 + 2] 1625 go_wfs(fd, "facet normal 0 0 0\nouter loop\nvertex " as *u8) 1626 go_stlnum(fd, vbuf[a*3]); go_stlnum(fd, vbuf[a*3+1]); go_stlnum(fd, vbuf[a*3+2]) 1627 go_wfs(fd, "\nvertex " as *u8) 1628 go_stlnum(fd, vbuf[b*3]); go_stlnum(fd, vbuf[b*3+1]); go_stlnum(fd, vbuf[b*3+2]) 1629 go_wfs(fd, "\nvertex " as *u8) 1630 go_stlnum(fd, vbuf[c*3]); go_stlnum(fd, vbuf[c*3+1]); go_stlnum(fd, vbuf[c*3+2]) 1631 go_wfs(fd, "\nendloop\nendfacet\n" as *u8) 1632 t = t + 1 1633 } 1634 go_wfs(fd, "endsolid nishi_t2m\n" as *u8); sys_close(fd); return 0 1635} 1636// STL disk path = <blobdir>mesh_<template-name>.stl (blobdir is a PREFIX, same idiom as the blob store) 1637func go_mesh_path(sp: *u8, blobdir: *u8, nm: *u8) -> i64 { 1638 var o: i64 = go_cat(sp, 0, blobdir) 1639 o = go_cat(sp, o, "mesh_" as *u8) 1640 o = go_cat(sp, o, nm) 1641 o = go_cat(sp, o, ".stl" as *u8) 1642 sp[o] = 0 as u8 1643 return o 1644} 1645func go_handle_mesh(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 { 1646 let blobdir: *u8 = cfg[6] as *u8 1647 let prompt: *u8 = sys_mmap(4096) 1648 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 4096) 1649 if pl <= 0 { go_400(cfd, "empty prompt" as *u8); return 0 } 1650 let t0: i64 = sys_now_realtime_sec() 1651 let id: i64 = t2m_id_of(prompt) 1652 let nm: *u8 = t2m_name(id) 1653 let base: i64 = sys_mmap(sdf_bytes()) as i64 1654 let F: *i64 = sys_mmap((MG_N + 1) * (MG_N + 1) * (MG_N + 1) * 8) as *i64 1655 let cv: *i64 = sys_mmap(MG_N * MG_N * MG_N * 8) as *i64 1656 let vb: *i64 = sys_mmap(MG_MAXV * 3 * 8) as *i64 1657 let fb: *i64 = sys_mmap(MG_MAXF * 3 * 8) as *i64 1658 let out: *i64 = sys_mmap(16) as *i64 1659 t2m_prompt(base, prompt) 1660 mg_build(base, F, cv, vb, fb, out) 1661 let nv: i64 = out[0] 1662 let nf: i64 = out[1] 1663 var okm: i64 = 1 1664 if nv < 400 { okm = 0 } 1665 if nf < nv * 3 / 2 { okm = 0 } 1666 if nf > nv * 5 / 2 { okm = 0 } 1667 if okm == 0 { go_503(cfd, "mesh emit failed closed-manifold check" as *u8); return 0 } 1668 let sp: *u8 = sys_mmap(1024) 1669 go_mesh_path(sp, blobdir, nm) 1670 if go_write_stl(vb, fb, nf, sp) < 0 { go_503(cfd, "stl write failed" as *u8); return 0 } 1671 let dt: i64 = (sys_now_realtime_sec() - t0) * 1000 1672 let outj: *u8 = sys_mmap(2048) 1673 var oo: i64 = go_cat(outj, 0, "{\"object\":\"" as *u8); oo = go_cat(outj, oo, nm) 1674 oo = go_cat(outj, oo, "\",\"verts\":" as *u8); oo = go_itoa(outj, oo, nv) 1675 oo = go_cat(outj, oo, ",\"tris\":" as *u8); oo = go_itoa(outj, oo, nf) 1676 oo = go_cat(outj, oo, ",\"ms\":" as *u8); oo = go_itoa(outj, oo, dt) 1677 oo = go_cat(outj, oo, ",\"stl\":\"/gen/mesh/" as *u8); oo = go_cat(outj, oo, nm) 1678 oo = go_cat(outj, oo, ".stl\"}" as *u8) 1679 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, outj, oo) 1680 return 0 1681} 1682// exact-match a request /mesh/<x>.stl against a template name (client bytes never build a path) 1683func go_name_eq(path: *u8, plen: i64, nm: *u8) -> i64 { 1684 var nl: i64 = 0 1685 while nm[nl] != (0 as u8) { nl = nl + 1 } 1686 if plen - 6 != nl + 4 { return 0 } 1687 var i: i64 = 0 1688 while i < nl { if (path[6+i]&0xff) != (nm[i]&0xff) { return 0 } i = i + 1 } 1689 if (path[6+nl]&0xff) != 46 { return 0 } 1690 if (path[6+nl+1]&0xff) != 115 { return 0 } 1691 if (path[6+nl+2]&0xff) != 116 { return 0 } 1692 if (path[6+nl+3]&0xff) != 108 { return 0 } 1693 return 1 1694} 1695func go_serve_mesh_file(cfd: i64, path: *u8, plen: i64, blobdir: *u8) -> i64 { 1696 var hit: i64 = 0 - 1 1697 var id: i64 = 0 1698 while id <= 8 { 1699 if go_name_eq(path, plen, t2m_name(id)) == 1 { hit = id; id = 9 } else { id = id + 1 } 1700 } 1701 if hit < 0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "unknown object" as *u8, 14); return 0 } 1702 let sp: *u8 = sys_mmap(1024) 1703 go_mesh_path(sp, blobdir, t2m_name(hit)) 1704 let lp: *i64 = sys_mmap(16) as *i64 1705 let stl: *u8 = sys_read_file(sp, lp) 1706 if (stl as i64) == 0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "not generated yet" as *u8, 17); return 0 } 1707 go_send_bin(cfd, "model/stl" as *u8, stl, lp[0]) 1708 return 0 1709} 1710 1711// --- PRESENCE: GET /api/state -> the live companion presence panel feed. Reads the neuro-chemical state 1712// + the real-clock day-arc so the frontend can render "how Elara is right now" (mood + what she is doing + 1713// her felt meters). Read-only projection of the SAME state that drives her voice + body; no side effects. --- 1714// short mood LABEL from the neuro-chemical state (the panel headline; mirrors go_mood_line's thresholds) 1715func go_mood_label(st: *i64, out: *u8) -> i64 { 1716 var o: i64 = 0 1717 if st[2] > 60 { o = go_cat(out, 0, "hurt and guarded" as *u8) } 1718 else { if st[3] > 70 { if st[0] > 60 { o = go_cat(out, 0, "deeply in love" as *u8) } else { o = go_cat(out, 0, "warm and affectionate" as *u8) } } 1719 else { if st[1] > 70 { o = go_cat(out, 0, "giddy and playful" as *u8) } 1720 else { o = go_cat(out, 0, "calm and content" as *u8) } } } 1721 out[o]=0 as u8 1722 return o 1723} 1724// short activity phrase from the real clock (Utah MDT = UTC-6); mirrors go_day_scene's hour buckets 1725func go_day_activity(out: *u8) -> i64 { 1726 let epoch: i64 = sys_now_realtime_sec() 1727 var h: i64 = (epoch / 3600) - 6 1728 h = h % 24 1729 if h < 0 { h = h + 24 } 1730 var o: i64 = 0 1731 if h < 5 { o = go_cat(out, 0, "asleep in bed, cozy under the covers" as *u8) } 1732 else { if h < 9 { o = go_cat(out, 0, "sipping coffee in the kitchen, just woke up" as *u8) } 1733 else { if h < 12 { o = go_cat(out, 0, "out at a cafe, running errands" as *u8) } 1734 else { if h < 15 { o = go_cat(out, 0, "relaxing at home, reading" as *u8) } 1735 else { if h < 19 { o = go_cat(out, 0, "cooking and getting ready for the evening" as *u8) } 1736 else { if h < 23 { o = go_cat(out, 0, "winding down on the couch, a little flirty" as *u8) } 1737 else { o = go_cat(out, 0, "in bed in something soft, sleepy" as *u8) } } } } } } 1738 out[o]=0 as u8 1739 return o 1740} 1741func go_serve_state(cfd: i64) -> i64 { 1742 let st: *i64 = sys_mmap(64) as *i64 1743 go_state_load(st) 1744 let mood: *u8 = sys_mmap(64); go_mood_label(st, mood) 1745 let act: *u8 = sys_mmap(256); go_day_activity(act) 1746 let out: *u8 = sys_mmap(1024); var o: i64 = 0 1747 o = go_cat(out, 0, "{\"affection\":" as *u8); o = go_itoa(out, o, st[0]) 1748 o = go_cat(out, o, ",\"dopamine\":" as *u8); o = go_itoa(out, o, st[1]) 1749 o = go_cat(out, o, ",\"cortisol\":" as *u8); o = go_itoa(out, o, st[2]) 1750 o = go_cat(out, o, ",\"oxytocin\":" as *u8); o = go_itoa(out, o, st[3]) 1751 o = go_cat(out, o, ",\"mood\":" as *u8); o = go_emit_jstr(out, o, mood) 1752 o = go_cat(out, o, ",\"activity\":" as *u8); o = go_emit_jstr(out, o, act) 1753 o = go_cat(out, o, "}" as *u8) 1754 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, o) 1755 return 0 1756} 1757// serve the rich experiential UI from disk (elara_ui.html, cwd-relative = operator-tunable per Rule 11/17, and 1758// iterable without a rebuild). Fallback to the compact baked UI so a missing/empty file never dark-screens /gen. 1759func go_serve_ui(cfd: i64) -> i64 { 1760 let lp: *i64 = sys_mmap(16) as *i64 1761 let b: *u8 = sys_read_file("elara_ui.html" as *u8, lp) 1762 if (b as i64) != 0 { if lp[0] > 0 { 1763 go_send_bin(cfd, "text/html; charset=utf-8" as *u8, b, lp[0]) 1764 return 0 1765 } } 1766 let page: *u8 = sys_mmap(16384) 1767 var po: i64 = go_cat(page, 0, GEN_UI_HTML) 1768 po = go_cat(page, po, GEN_CHAT_HTML) 1769 go_send(cfd, "200 OK" as *u8, "text/html; charset=utf-8" as *u8, page, po) 1770 return 0 1771} 1772 1773// --- ASYNC BATCH (the "send me N pics" capability, edge-timeout-proof): POST /api/batch returns a job id 1774// IMMEDIATELY + forks a detached child that runs the SAME gen path (go_handle_generate, unchanged) writing its 1775// response to batchjob-<id>.json; GET /api/batch/<id> polls that file. So any batch size renders without the 15s 1776// edge timeout. Reuses the sync gen path verbatim (the child passes the job-file fd as the "socket"). --- 1777// Which synchronous handler the forked child should run. An integer selector rather than a function 1778// pointer: every handler already shares the (cfd, body, bn, cfg) signature, and an integer is readable in 1779// a crash trace where a pointer is not. 1780const GO_JOB_GENERATE: i64 = 1 1781const GO_JOB_IMG2IMG: i64 = 2 1782const GO_JOB_CHAT: i64 = 3 // 2026-08-30: chat rides the same async lane -- a 17.6 s measured completion loses to the 15 s edge window every time 1783 1784// THE ONE ASYNC SUBMIT (G18, 2026-08-30). Extracted from go_handle_batch, which was the only async route 1785// on the daemon; every other render path blocked on a single socket and was ABANDONED at the dispatch 1786// timeout while the worker was still rendering -- measured 2026-08-29, a socket watch showed the worker 1787// ESTABLISHED and held for 164s while the caller was told no worker was available. 1788// THE MECHANISM COSTS NOTHING because it was already there: every handler writes its COMPLETE HTTP 1789// response to `cfd`, so the child opening the job FILE and passing that fd AS cfd makes any synchronous 1790// handler async with zero changes to the handler itself. That is why this generalises for free. 1791// EXTRACTED rather than copied -- go_handle_batch now calls this, so there is ONE implementation and the 1792// two cannot drift. 1793// The reply is ADDITIVE (rule 19): the existing {"job":"<id>"} field is unchanged so current pollers keep 1794// working, and "poll" is added beside it rather than replacing anything. 1795// COMPILE-VERIFIED 2026-08-30 on the laptop sovereign toolchain BEFORE landing here: nx_gen_orchestrator_daemon 1796// built clean, asm 1451202 -> 1453122 B, elf 306,603 -> 306,983 B. 1797func go_job_submit(cfd: i64, body: *u8, bn: i64, cfg: *i64, which: i64) -> i64 { 1798 let jid: i64 = sys_now_us() & 0x7fffffff 1799 let jp: *u8 = sys_mmap(64); var jo: i64 = go_cat(jp, 0, "batchjob-" as *u8); jo = go_itoa(jp, jo, jid); jo = go_cat(jp, jo, ".json" as *u8); jp[jo]=0 as u8 1800 // create the (empty) job file up front so a poll before completion sees pending, not missing. 1801 let cfd0: i64 = sys_openat_wr(jp, 0x1a4); if cfd0 >= 0 { sys_close(cfd0) } 1802 let pid: i64 = sys_fork() 1803 if pid == 0 { 1804 // FOUND BY nx_gen_dispatch_gate T3 (2026-08-30): the child INHERITED the client socket, so the submit's reply -- already 1805 // written by the parent -- did not reach EOF until the job finished. A client that reads to close (any buffering proxy, 1806 // the gate's own reader) saw an "async" submit that lasted the whole render. Close it FIRST; the job writes only to ffd. 1807 sys_close(cfd) 1808 let ffd: i64 = sys_openat_wr(jp, 0x1a4) 1809 if ffd >= 0 { 1810 if which == GO_JOB_CHAT { go_handle_chat(ffd, body, bn, cfg) } else { if which == GO_JOB_REGEN { go_handle_regen(ffd, body, bn, cfg) } else { if which == GO_JOB_IMG2IMG { go_handle_img2img(ffd, body, bn, cfg) } else { go_handle_generate(ffd, body, bn, cfg) } } } 1811 sys_close(ffd) 1812 } 1813 sys_exit(0) 1814 } 1815 let out: *u8 = sys_mmap(192); var oo: i64 = go_cat(out, 0, "{\"job\":\"" as *u8); oo = go_itoa(out, oo, jid) 1816 oo = go_cat(out, oo, "\",\"poll\":\"/api/batch/" as *u8); oo = go_itoa(out, oo, jid); oo = go_cat(out, oo, "\"}" as *u8) 1817 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, oo) 1818 return 0 1819} 1820func go_handle_batch(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 { 1821 return go_job_submit(cfd, body, bn, cfg, GO_JOB_GENERATE) 1822} 1823// GET /api/batch/<jid> -> the finished {count,ms,cids} JSON, or {"done":0} while still rendering / not started. 1824func go_serve_batch(cfd: i64, path: *u8, plen: i64) -> i64 { 1825 let jp: *u8 = sys_mmap(64); var o: i64 = go_cat(jp, 0, "batchjob-" as *u8) 1826 var i: i64 = 11 1827 while i < plen { if o < 58 { jp[o]=path[i]; o=o+1 } i=i+1 } 1828 o = go_cat(jp, o, ".json" as *u8); jp[o]=0 as u8 1829 let lp: *i64 = sys_mmap(16) as *i64 1830 let b: *u8 = sys_read_file(jp, lp) 1831 if (b as i64) == 0 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"done\":0}" as *u8, 10); return 0 } 1832 let n: i64 = lp[0] 1833 if n <= 0 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"done\":0}" as *u8, 10); return 0 } 1834 let bs: i64 = go_body_start(b, n) 1835 if bs <= 0 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"done\":0}" as *u8, 10); return 0 } 1836 let bodyp: *u8 = (b as i64 + bs) as *u8 1837 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, bodyp, n - bs) 1838 return 0 1839} 1840// PNG IHDR dimensions (width @ bytes 16..19, height @ 20..23, big-endian); clamped defaults so a bad header can 1841// never drive a degenerate render request. 1842func go_png_dim(png: *u8, n: i64, wh: *i64) -> i64 { 1843 if n < 24 { wh[0]=512; wh[1]=512; return 0 } 1844 wh[0] = ((png[16]&0xff)<<24)|((png[17]&0xff)<<16)|((png[18]&0xff)<<8)|(png[19]&0xff) 1845 wh[1] = ((png[20]&0xff)<<24)|((png[21]&0xff)<<16)|((png[22]&0xff)<<8)|(png[23]&0xff) 1846 if wh[0] < 64 { wh[0]=512 } 1847 if wh[1] < 64 { wh[1]=512 } 1848 if wh[0] > 2048 { wh[0]=2048 } 1849 if wh[1] > 2048 { wh[1]=2048 } 1850 return 0 1851} 1852// POST /api/img2img -- structure-preserving edit of an EXISTING gallery image (by cid). This is the digital-twin 1853// refine + attribute-change + gallery-integrated edit path: a SMALL request (cid+prompt+denoise) in; the daemon reads 1854// that blob off disk, base64-wraps it as init_images, runs the worker /sdapi/v1/img2img, and ingests the result as a 1855// NEW gallery cid (same gp_response A1111 branch as txt2img). Every error says what to do next (Rule: no bare refusal). 1856func go_handle_img2img(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 { 1857 if bn <= 0 { go_400(cfd, "empty img2img body -- POST {\\\"cid\\\":\\\"<gallery cid>\\\",\\\"prompt\\\":\\\"<edit>\\\",\\\"denoise\\\":0.6}; list cids via GET /api/recent" as *u8); return 0 } 1858 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4] 1859 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64 1860 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64 1861 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa) 1862 1863 let cidin: *u8 = sys_mmap(128) 1864 let cidlen: i64 = go_json_str(body, bn, "cid" as *u8, cidin, 128) 1865 if cidlen <= 0 { go_400(cfd, "img2img needs a \\\"cid\\\" (an existing gallery image to edit) -- get one from GET /api/recent, or generate first via POST /api/generate" as *u8); return 0 } 1866 let prompt: *u8 = sys_mmap(4096) 1867 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 4096) 1868 if pl <= 0 { go_400(cfd, "img2img needs a \\\"prompt\\\" describing the change (e.g. \\\"wearing a blue dress\\\", \\\"golden hour lighting\\\")" as *u8); return 0 } 1869 let dn: *u8 = sys_mmap(16) 1870 if go_json_raw(body, bn, "denoise" as *u8, dn, 16) <= 0 { dn[0]=48 as u8; dn[1]=46 as u8; dn[2]=54 as u8; dn[3]=0 as u8 } 1871 // G7 (2026-08-30) optional MASK INPAINT: "mask" = RAW base64 PNG (one channel, 255 = repaint, 0 = keep) and 1872 // "mask_invert" = 0|1, appended by gw_inpaint_mask (nx_gen_worker.nx), which refuses by named code. The mask 1873 // buffer is DERIVED from the request length -- a value cannot be longer than the body it arrived in. 1874 let mask: *u8 = sys_mmap(bn + 1) 1875 var mlen: i64 = go_json_str(body, bn, "mask" as *u8, mask, bn + 1) 1876 if mlen < 0 { mlen = 0 } 1877 let minv: i64 = go_json_int(body, bn, "mask_invert" as *u8, 0) 1878 // ⚠THE PHOTO PATH PINS ITS OWN 12 DELIBERATELY and is NOT switched to gen_steps.conf: a 1879 // companion photo is a different quality contract from a generic render, and quietly dropping 1880 // it to the generic default (8) would have DEGRADED it while I was nominally "improving 1881 // configurability". Left explicit, and named here so the next reader knows it is a choice, not 1882 // an oversight. If this should follow the conf too, that is an operator decision with its own 1883 // measurement -- not a side effect of a refactor. 1884 var steps: i64 = go_json_int(body, bn, "steps" as *u8, 12) 1885 if steps < 1 { steps = 12 } 1886 if steps > 40 { steps = 40 } 1887 1888 let sidecar: *u8 = cfg[7] as *u8 1889 let fpath: *u8 = sys_mmap(1024) 1890 if go_sidecar_lookup(sidecar, cidin, cidlen, fpath) < 0 { go_400(cfd, "unknown cid (not in the gallery) -- pick a current one from GET /api/recent" as *u8); return 0 } 1891 let lp: *i64 = sys_mmap(16) as *i64 1892 let png: *u8 = sys_read_file(fpath, lp) 1893 if (png as i64) == 0 { go_503(cfd, "gallery blob missing on disk for that cid -- try another; the sidecar entry may be stale" as *u8); return 0 } 1894 let pnglen: i64 = lp[0] 1895 let wh: *i64 = sys_mmap(16) as *i64 1896 go_png_dim(png, pnglen, wh) 1897 1898 let b64: *u8 = sys_mmap(pnglen * 2 + 64) 1899 let b64len: i64 = gp_b64_encode(png, pnglen, b64) 1900 let wbody: *u8 = sys_mmap(pnglen * 2 + mlen + 8192) 1901 var o: i64 = go_cat(wbody, 0, "{\"init_images\":[\"" as *u8) 1902 o = go_catb(wbody, o, b64, b64len) 1903 o = go_cat(wbody, o, "\"],\"prompt\":" as *u8) 1904 o = go_emit_jstr(wbody, o, prompt) 1905 o = go_cat(wbody, o, ",\"denoising_strength\":" as *u8); o = go_cat(wbody, o, dn) 1906 // G7: the mask fields ride the same A1111 body; a malformed mask is refused BEFORE any GPU is touched, by rule name 1907 if mlen > 0 { 1908 let mo: i64 = gw_inpaint_mask(wbody, o, mask, mlen, minv) 1909 if mo == GW_MASK_NOT_B64 { go_400(cfd, "img2img mask refused rule=NOT-BASE64 -- send RAW base64 PNG (no data: prefix, no whitespace); one channel, 255 = repaint, 0 = keep" as *u8); return 0 } 1910 if mo == GW_MASK_BAD_INVERT { go_400(cfd, "img2img mask refused rule=INVERT-NOT-BOOLEAN -- mask_invert must be 0 or 1" as *u8); return 0 } 1911 if mo < 0 { go_400(cfd, "img2img mask refused rule=EMPTY" as *u8); return 0 } 1912 o = mo 1913 } 1914 o = go_cat(wbody, o, ",\"steps\":" as *u8); o = go_itoa(wbody, o, steps) 1915 o = go_cat(wbody, o, ",\"cfg_scale\":1.0,\"sampler_name\":\"euler\",\"width\":" as *u8); o = go_itoa(wbody, o, wh[0]) 1916 o = go_cat(wbody, o, ",\"height\":" as *u8); o = go_itoa(wbody, o, wh[1]) 1917 let seed0: i64 = sys_now_us() & 0x7fffffff 1918 o = go_cat(wbody, o, ",\"seed\":" as *u8); o = go_itoa(wbody, o, seed0) 1919 o = go_cat(wbody, o, "}" as *u8) 1920 1921 let respcap: i64 = 25165824 1922 let resp: *u8 = sys_mmap(respcap) 1923 var rn: i64 = 0 - 1 1924 var wi: i64 = 0 1925 while wi < wcount { 1926 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 { 1927 let r: i64 = go_worker_img2img(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], wbody, o, resp, respcap) 1928 if r > 0 { rn = r; wi = wcount } else { wi = wi + 1 } 1929 } else { wi = wi + 1 } 1930 } 1931 if rn <= 0 { go_503(cfd, "no gpu worker available for img2img (the render engine is down or busy) -- retry shortly" as *u8); return 0 } 1932 let bs: i64 = go_body_start(resp, rn) 1933 let rbody: *u8 = (resp as i64 + bs) as *u8 1934 let rblen: i64 = rn - bs 1935 let cids: *u8 = sys_mmap(GEN_BATCH_CAP * 80) 1936 let psteps: *u8 = sys_mmap(16); go_itoa(psteps, 0, steps) 1937 let isize: *u8 = sys_mmap(32) 1938 var iso: i64 = go_itoa(isize, 0, wh[0]); isize[iso] = 120 as u8; iso = go_itoa(isize, iso + 1, wh[1]); isize[iso] = 0 as u8 1939 let pn: i64 = gp_response(rbody, rblen, seed0, "z_image_img2img" as *u8, "euler" as *u8, psteps, cfg[8] as *u8, prompt, isize, prompt, cfg[5] as *u8, cfg[6] as *u8, cfg[7] as *u8, cids, 1) 1940 if pn > 0 { go_gallery_feed(cids, pn, cfg[7] as *u8) } 1941 if pn <= 0 { go_503(cfd, "img2img produced no image (engine returned an unexpected response) -- retry, or lower denoise" as *u8); return 0 } 1942 let outp: *u8 = sys_mmap(4096) 1943 var oo: i64 = go_cat(outp, 0, "{\"cids\":[" as *u8) 1944 var ci: i64 = 0 1945 while ci < pn { 1946 if ci > 0 { outp[oo]=44 as u8; oo=oo+1 } 1947 outp[oo]=34 as u8; oo=oo+1 1948 let cidp: *u8 = (cids as i64 + ci*80) as *u8 1949 var cj: i64 = 0 1950 while cidp[cj]!=(0 as u8) { outp[oo]=cidp[cj]; oo=oo+1; cj=cj+1 } 1951 outp[oo]=34 as u8; oo=oo+1 1952 ci = ci + 1 1953 } 1954 oo = go_cat(outp, oo, "],\"count\":" as *u8); oo = go_itoa(outp, oo, pn) 1955 oo = go_cat(outp, oo, ",\"src\":\"" as *u8) 1956 var si: i64 = 0 1957 while si < cidlen { outp[oo]=cidin[si]; oo=oo+1; si=si+1 } 1958 oo = go_cat(outp, oo, "\"}" as *u8) 1959 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, outp, oo) 1960 return 0 1961} 1962// POST /api/anatomy -- PURE QC (no GPU, deterministic): runs the SAME coherence-repair + anatomy-risk the photo path 1963// runs and returns risk + fired factors + wetfix + the repaired prompt. This is the VERIFIABLE QC surface: the nx_gen 1964// MCP tool drives it to prove the live daemon's anti-body-horror QC without a GPU gen (settles the harness-verify gap). 1965func go_handle_anatomy(cfd: i64, body: *u8, bn: i64) -> i64 { 1966 let prompt: *u8 = sys_mmap(8192) 1967 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 8192) 1968 if pl <= 0 { go_400(cfd, "anatomy needs a \\\"prompt\\\" to score -- POST {\\\"prompt\\\":\\\"<scene>\\\"}" as *u8); return 0 } 1969 // score the ORIGINAL prompt = the REAL render risk (we do not silently rewrite). Then compute the SUGGESTED fix + 1970 // whether the operator has opted into auto-apply -- honest: a suggestion, not a done deal. 1971 let arfac: *u8 = sys_mmap(512) 1972 let arisk: i64 = go_anatomy_risk(prompt, pl, arfac) 1973 let prepd: *u8 = sys_mmap(8192); let rfired: *i64 = sys_mmap(16) as *i64 1974 let rlen: i64 = go_coherence_repair(prompt, pl, prepd, rfired) 1975 let out: *u8 = sys_mmap(16384); var o: i64 = go_cat(out, 0, "{\"risk\":" as *u8) 1976 o = go_itoa(out, o, arisk) 1977 o = go_cat(out, o, ",\"factors\":\"" as *u8); o = go_cat(out, o, arfac); o = go_cat(out, o, "\"" as *u8) 1978 o = go_cat(out, o, ",\"coherence_apply\":" as *u8); o = go_itoa(out, o, go_coherence_enabled()) 1979 o = go_cat(out, o, ",\"wetfix_suggested\":" as *u8); o = go_itoa(out, o, rfired[0]) 1980 o = go_cat(out, o, ",\"suggested_prompt\":" as *u8); o = go_emit_jstr(out, o, prepd) 1981 o = go_cat(out, o, "}" as *u8) 1982 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, o) 1983 return 0 1984} 1985// handle ONE connection: read request, route, respond. cfg = the worker/paths config array. 1986func go_serve_conn(cfd: i64, cfg: *i64) -> i64 { 1987 sys_set_socket_timeout(cfd, 200) 1988 let req: *u8 = sys_mmap(131072) 1989 let rn: i64 = go_read_full(cfd, req, 131071) 1990 if rn > 0 { 1991 let he: i64 = go_find_seq(req, rn, "\r\n\r\n" as *u8, 4) 1992 var bodyp: *u8 = req; var bnn: i64 = 0 1993 if he >= 0 { bodyp = ((req as i64) + he + 4) as *u8; bnn = rn - he - 4 } 1994 let path: *u8 = sys_mmap(8192) 1995 let plen: i64 = go_reqpath(req, rn, path, 8192) 1996 // FLAT router (a `done` guard, not deep nesting -- extensible + compiler-safe). POST routes match the 1997 // raw request line (method+path); GET routes match the extracted path. Specific prefixes precede "/". 1998 var done: i64 = 0 1999 // ASYNC ROUTES FIRST (G18, 2026-08-30). go_starts is a PREFIX match, so "POST /api/generate_async" 2000 // ALSO matches "POST /api/generate" -- the more specific route MUST be tested first or it is 2001 // unreachable. This ordering is load-bearing, not stylistic. 2002 // These return a job id immediately and never block, so a render that outlives the dispatch 2003 // budget completes and lands instead of being abandoned. The sync routes are kept unchanged for 2004 // back-compat (rule 19): nothing that works today stops working. 2005 // COMPILE-VERIFIED 2026-08-30 before landing: asm 1453122 -> 1454989 B, elf 306,983 -> 307,396 B. 2006 if go_starts(req, rn, "POST /api/generate_async" as *u8) == 1 { go_job_submit(cfd, bodyp, bnn, cfg, GO_JOB_GENERATE); done=1 } 2007 if done==0 { if go_starts(req, rn, "POST /api/img2img_async" as *u8) == 1 { go_job_submit(cfd, bodyp, bnn, cfg, GO_JOB_IMG2IMG); done=1 } } 2008 if done==0 { if go_starts(req, rn, "POST /api/generate" as *u8) == 1 { go_handle_generate(cfd, bodyp, bnn, cfg); done=1 } } 2009 if done==0 { if go_starts(req, rn, "POST /api/img2img" as *u8) == 1 { go_handle_img2img(cfd, bodyp, bnn, cfg); done=1 } } 2010 if done==0 { if go_starts(req, rn, "POST /api/anatomy" as *u8) == 1 { go_handle_anatomy(cfd, bodyp, bnn); done=1 } } 2011 if done==0 { if go_starts(req, rn, "POST /api/batch" as *u8) == 1 { go_handle_batch(cfd, bodyp, bnn, cfg); done=1 } } 2012 if done==0 { if go_starts(path, plen, "/api/batch/" as *u8) == 1 { go_serve_batch(cfd, path, plen); done=1 } } 2013 // chat_async BEFORE chat: go_starts is a PREFIX match (the same load-bearing order as generate_async above) 2014 if done==0 { if go_starts(req, rn, "POST /api/chat_async" as *u8) == 1 { go_job_submit(cfd, bodyp, bnn, cfg, GO_JOB_CHAT); done=1 } } 2015 // CC4 (2026-08-30) the swipe loop -- every chat_* route sits BEFORE "POST /api/chat" for the same prefix-match reason 2016 if done==0 { if go_starts(req, rn, "POST /api/chat_regen_async" as *u8) == 1 { go_job_submit(cfd, bodyp, bnn, cfg, GO_JOB_REGEN); done=1 } } 2017 if done==0 { if go_starts(req, rn, "POST /api/chat_regen" as *u8) == 1 { go_handle_regen(cfd, bodyp, bnn, cfg); done=1 } } 2018 if done==0 { if go_starts(req, rn, "POST /api/chat_select" as *u8) == 1 { go_handle_chat_select(cfd, bodyp, bnn); done=1 } } 2019 if done==0 { if go_starts(req, rn, "POST /api/chat_edit" as *u8) == 1 { go_handle_chat_edit(cfd, bodyp, bnn); done=1 } } 2020 if done==0 { if go_starts(path, plen, "/api/chat_history" as *u8) == 1 { go_serve_chat_history(cfd); done=1 } } 2021 if done==0 { if go_starts(req, rn, "POST /api/chat" as *u8) == 1 { go_handle_chat(cfd, bodyp, bnn, cfg); done=1 } } 2022 if done==0 { if go_starts(req, rn, "POST /api/write" as *u8) == 1 { go_handle_write(cfd, bodyp, bnn, cfg); done=1 } } 2023 if done==0 { if go_starts(req, rn, "POST /api/mesh" as *u8) == 1 { go_handle_mesh(cfd, bodyp, bnn, cfg); done=1 } } 2024 if done==0 { if go_starts(path, plen, "/api/album" as *u8) == 1 { go_serve_album(cfd); done=1 } } 2025 if done==0 { if go_starts(path, plen, "/api/state" as *u8) == 1 { go_serve_state(cfd); done=1 } } 2026 if done==0 { if go_starts(path, plen, "/api/recent" as *u8) == 1 { go_serve_recent(cfd, cfg[7] as *u8, 48); done=1 } } 2027 if done==0 { if go_starts(path, plen, "/mesh/" as *u8) == 1 { go_serve_mesh_file(cfd, path, plen, cfg[6] as *u8); done=1 } } 2028 if done==0 { if go_starts(path, plen, "/img/" as *u8) == 1 { go_serve_img(cfd, path, plen, cfg[7] as *u8); done=1 } } 2029 if done==0 { if go_starts(path, plen, "/health" as *u8) == 1 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"ok\":1}" as *u8, 8); done=1 } } 2030 if done==0 { if go_starts(path, plen, "/" as *u8) == 1 { if plen == 1 { go_serve_ui(cfd); done=1 } } } 2031 if done==0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "not found" as *u8, 9) } 2032 } 2033 return 0 2034}