FUSORD.CPP · THE RESIDENT KERNEL · REV 0 · MIT

fusord.cpp

The loop, the bus and the laws — as served. One process, one GPU thread, and one running memory that is never rebuilt. It reads the lanes of a working floor and, at every completed thought, asks three seats whether anything deserves to be said. Mostly it decides no, and writes that down.

Nothing on this page is summarized. The core is below in three movements, quoted from the file; under it is every line of the file; under that, the file. This listing is pre-rendered — it runs no JavaScript, fetches nothing, and cannot pretend to be alive.

LanguageC++
Lines2,424
Size138.5 KB
Sections18
LicenseMIT

§ 01 — The core

2,424 lines. These thirty-eight are the argument.

A resident is not a model with a scheduler around it. Three fragments carry the whole difference: it decides, it can take the decision back mid-word, and it cannot quietly edit what it did. The rest of the file is what those three cost when none of them is faked.

FUSOR-1 · DWG-003 · REV 0 · THE CORE, IN THREE MOVEMENTS Quoted verbatim · line numbers are this file's Scale: none — this is the code, not a schematic
IThe judgment§14 · L1913
1913 // THE PROBE (verbatim frame, dial 0)
1914 const uint64_t t_probe0 = wall_ms();
1915 float margins[3];
1916 for (int m = 0; m < 3; ++m) margins[m] = probe_one(m);
⋮ 96 LINES — THE SEATS SPEAK, OR DO NOT
2013 // holds: silence, on the record, with its margin
2014 for (int m = 0; m < 3; ++m) if (margins[m] <= 0.0f) { ++holds; write_verdict(judged_lane, m, "hold", margins[m], "", nullptr); }
Every completed thought is put to three seats, at dial zero, on a fork of the trunk as it stands now. A margin at or below zero is a no — written to the wire with its margin, exactly like a yes. Silence here is a measurement, not the absence of one.
— and if the world answers while a seat is still talking —
IIThe un-say§13 · L1852
1852 // THE WINDOW IN THE BLIND WINDOW. Percepts never wait for a sentence to finish — not even for
1853 // the silent remainder after a kill.
1854 const llama_pos np_before = npast;
1855 const uint64_t frames_before = frames_completed;
1856 drain_intake(); // ingests onto TRUNK; judgments are deferred (gen_depth > 0)
1857 if (!g_run.load(std::memory_order_acquire)) break;
1858 if (aborted) continue; // the world already answered; the rest is record, not decision
1859 if (frames_completed != frames_before && npast != np_before) {
1860 // A whole frame landed while this seat was mid-sentence (the rest of the line it was
1861 // judging, or a newer line). Did the world answer first?
1862 // (a) deterministic: the newest line ACCEPTS what this seat is saying → settled.
1863 // (b) the seat itself, re-probed on a fresh fork of the UPDATED trunk: margin ≤ 0 → it
1864 // would not have spoken now. Either kills the forming line. Only commits kill.
1865 const std::string newest = !cur_tail_line.empty() ? cur_tail_line
1866 : !tailq.empty() ? tailq.back().first : clause;
1867 bool settled = looks_like_acceptance(newest) && content_overlap(newest, say) >= 1;
1868 float m2 = margin;
1869 if (!settled) m2 = probe_one(m);
1870 if (settled || m2 <= 0.0f) {
1871 aborted = true;
1872 char c[96]; std::snprintf(c, sizeof(c), settled ? "settled_by_world" : "margin_flipped:%+.2f", m2);
1873 cause = c;
1874 if (surface_on) std::printf(" ⟵ [un-said: %s]", cause.c_str());
1875 // no break: the remainder is generated silently (D2), the seam stays open for intake
1876 }
1877 }
Intake drains after every generated token. If a whole frame lands while a seat is mid-sentence, that seat is re-probed on a fresh fork of the updated trunk; if the answer is now no, the line dies mid-word. The remainder is then generated silently, so the tape holds the sentence that never arrived.
— and none of it, said or unsaid, can be quietly edited afterwards —
IIIThe tape§6 · L765
765 std::string put(const std::string& body) {
766 if (!f) return prev;
767 const std::string h = chain_hash(prev, body);
768 std::fprintf(f, "%s,\"prev\":\"%s\",\"h\":\"%s\"}\n", body.c_str(), prev.c_str(), h.c_str());
769 std::fflush(f); // durable as it goes, not at exit
770 prev = h; ++n;
771 return h;
772 }
Every row carries the hash of the row before it, so the ledger is a chain and not a list — an edited row breaks every row after it. Flushed as it goes, not at exit. The chain head is recovered from the file at open, so it survives restarts.
It decides. It can un-decide, mid-word, because the world moved. And it keeps a record of both that cannot be quietly rewritten. That is the whole of it — everything else is what those three cost when you refuse to fake any of them.

§ 02 — Every line

The whole file, nothing folded away.

Every line is addressable: click a number, or link straight to one. The source below is tokenized at build time and served as plain markup — there is no script on this page to read it for you.

1// fusord.cpp — FUSOR · THE RESIDENT KERNEL (v-next, 2026-09-04)
2//
3// One process, one GPU thread, one running memory that is never rebuilt. It reads a spool of
4// lanes, holds them in one trunk, and at every completed thought asks three seats whether
5// anything deserves saying — mostly deciding no, and writing that down with its margin. A seat
6// that is speaking when the world answers is killed mid-word, and the sentence it would have
7// finished goes on the tape. Every row is BLAKE2b-chained to the one before. The kernel proposes
8// and acts on nothing: there is no `allow` verb in this file. The serve format is VERBATIM from
9// the v11 tune and its hash is pinned (0xe7ffa5704ba31076), asserted before the model loads.
10// Not claimed: this file is written, not compiled; no number in it is a measurement of itself.
11//
12// Run: fusord.exe <spool> [--model p] [--out-dir d] [--ckpt p] [--resume] [--cold] …
13#if defined(_WIN32)
14# ifndef WIN32_LEAN_AND_MEAN
15# define WIN32_LEAN_AND_MEAN
16# endif
17# ifndef NOMINMAX
18# define NOMINMAX // windows.h's min/max macros would break std::min below
19# endif
20# include <windows.h>
21# include <psapi.h> // EnumProcessModules: the module gate (zero egress as a process property)
22# include <bcrypt.h> // SHA-256 of the weights (CNG), the model's identity on the header
23# include <sys/stat.h>
24# pragma comment(lib, "bcrypt.lib")
25#else
26# include <csignal>
27# include <unistd.h>
28# include <sys/stat.h>
29#endif
31#include <algorithm>
32#include <atomic>
33#include <cctype>
34#include <cerrno>
35#include <chrono>
36#include <cmath>
37#include <cstdint>
38#include <cstdio>
39#include <cstdlib>
40#include <cstring>
41#include <deque>
42#include <mutex>
43#include <string>
44#include <thread>
45#include <unordered_map>
46#include <utility>
47#include <vector>
49#include "ggml-backend.h"
50#include "llama.h"
52#ifndef AURICLE_LLAMA_DIR
53#define AURICLE_LLAMA_DIR "C:/llama.cpp"
54#endif
56namespace fusor {
58// The run flag. Cleared by Ctrl-C / SIGINT, or by the operator writing `stop` into the switch file;
59// read at every beat of every loop so the tape gets its `end`, the cursor is saved, the trunk is
60// checkpointed. Declared first because the pill (below) honors the switch.
61static std::atomic<bool> g_run{true};
63// =====================================================================================================
64// §1 · SMALL HELPERS (clocks, escapes, hashes)
65// =====================================================================================================
67// Monotonic nanoseconds: the lane contract's clock. One stamping authority per venue; the kernel
68// stamps its own records with the same clock so a verdict and the frame that caused it are ordered.
69static inline uint64_t mono_ns() {
70 using namespace std::chrono;
71 return (uint64_t)duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count();
73// Milliseconds on the same clock — S0's `wall_ms` (it was steady_clock ms, not wall time; the name
74// is kept because the ledger's `ms` column and the soak tools expect it).
75static inline uint64_t wall_ms() {
76 using namespace std::chrono;
77 return (uint64_t)duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
79// Real wall time (Unix epoch ms): the only clock that survives a process, so a restored trunk can
80// be told how long the world went on without it (P3, F5). Never used for ordering within a run.
81static inline uint64_t epoch_ms() {
82 using namespace std::chrono;
83 return (uint64_t)duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
85static std::string fmt_hms(double ms) {
86 int s = (int)(ms / 1000.0); char b[32];
87 std::snprintf(b, sizeof(b), "%d:%02d:%02d", s / 3600, (s / 60) % 60, s % 60);
88 return b;
90// JSON string escape (S0's, extended with \t so a flattened tab cannot break a record).
91static std::string jesc(const std::string& s) {
92 std::string o; o.reserve(s.size() + 8);
93 for (char c : s) {
94 if (c == '"') o += "\\\""; else if (c == '\\') o += "\\\\";
95 else if (c == '\n') o += "\\n"; else if (c == '\t') o += "\\t"; else if (c == '\r') {}
96 else if ((unsigned char)c >= 0x20 || c < 0) o += c;
97 }
98 return o;
100static std::string hex_of(const uint8_t* p, size_t n) {
101 static const char* H = "0123456789abcdef";
102 std::string s; s.reserve(n * 2);
103 for (size_t i = 0; i < n; ++i) { s += H[p[i] >> 4]; s += H[p[i] & 15]; }
104 return s;
106// Row-building helpers (F6): rows are built from strings, never from fixed buffers that truncate
107// silently on a long path or a long clause.
108[[maybe_unused]] static std::string jq(const std::string& s) { return "\"" + jesc(s) + "\""; }
109[[maybe_unused]] static std::string fmt2(double x) { char b[48]; std::snprintf(b, sizeof(b), "%.2f", x); return b; }
110[[maybe_unused]] static std::string fmt3(double x) { char b[48]; std::snprintf(b, sizeof(b), "%.3f", x); return b; }
111[[maybe_unused]] static std::string fmt0(double x) { char b[48]; std::snprintf(b, sizeof(b), "%.0f", x); return b; }
112[[maybe_unused]] static std::string u64s(uint64_t x) { return std::to_string((unsigned long long)x); }
113[[maybe_unused]] static std::string hex16(uint64_t x) { char b[24]; std::snprintf(b, sizeof(b), "%016llx", (unsigned long long)x); return b; }
114// FNV-1a over a C string — IDENTICAL to S0's, because serve_hash() below is computed with it and
115// the pin was minted from it. Do not touch.
116static uint64_t fnv1a(uint64_t h, const char* s) {
117 for (const unsigned char* p = (const unsigned char*)s; *p; ++p) {
118 h ^= (uint64_t)*p; h *= 1099511628211ull;
119 }
120 return h;
122static uint64_t fnv1a_bytes(uint64_t h, const void* v, size_t n) {
123 const unsigned char* p = (const unsigned char*)v;
124 for (size_t i = 0; i < n; ++i) { h ^= (uint64_t)p[i]; h *= 1099511628211ull; }
125 return h;
127static bool starts_with(const std::string& s, const char* pfx) {
128 const size_t n = std::strlen(pfx);
129 return s.size() >= n && std::memcmp(s.data(), pfx, n) == 0;
131static bool ieq(const std::string& a, const char* b) {
132 size_t n = std::strlen(b);
133 if (a.size() != n) return false;
134 for (size_t i = 0; i < n; ++i)
135 if (std::tolower((unsigned char)a[i]) != std::tolower((unsigned char)b[i])) return false;
136 return true;
138static std::string lower(const std::string& s) {
139 std::string t = s; for (auto& c : t) c = (char)std::tolower((unsigned char)c); return t;
142// =====================================================================================================
143// §2 · BLAKE2b-256 (RFC 7693, unkeyed) — the estate's one hash family, inline so the kernel has no
144// dependency for the thing that makes its record trustworthy.
145// =====================================================================================================
147struct Blake2b {
148 uint64_t h[8]; uint64_t t[2]; uint8_t buf[128]; size_t buflen; size_t outlen;
150 static const uint64_t IV[8];
151 static const uint8_t SIGMA[12][16];
153 static inline uint64_t rotr64(uint64_t x, unsigned n) { return (x >> n) | (x << (64u - n)); }
154 static inline uint64_t load64(const uint8_t* p) {
155 uint64_t v = 0; for (int i = 7; i >= 0; --i) v = (v << 8) | (uint64_t)p[i]; return v;
156 }
157 static inline void G(uint64_t* v, const uint64_t* m, uint8_t x, uint8_t y,
158 int a, int b, int c, int d) {
159 v[a] = v[a] + v[b] + m[x]; v[d] = rotr64(v[d] ^ v[a], 32);
160 v[c] = v[c] + v[d]; v[b] = rotr64(v[b] ^ v[c], 24);
161 v[a] = v[a] + v[b] + m[y]; v[d] = rotr64(v[d] ^ v[a], 16);
162 v[c] = v[c] + v[d]; v[b] = rotr64(v[b] ^ v[c], 63);
163 }
164 void init(size_t out) {
165 outlen = out;
166 for (int i = 0; i < 8; ++i) h[i] = IV[i];
167 h[0] ^= 0x01010000ull ^ (uint64_t)out; // param block: fanout=1, depth=1, keylen=0, outlen
168 t[0] = t[1] = 0; buflen = 0;
169 }
170 void compress(const uint8_t* block, bool last) {
171 uint64_t m[16], v[16];
172 for (int i = 0; i < 16; ++i) m[i] = load64(block + 8 * i);
173 for (int i = 0; i < 8; ++i) { v[i] = h[i]; v[i + 8] = IV[i]; }
174 v[12] ^= t[0]; v[13] ^= t[1];
175 if (last) v[14] = ~v[14];
176 for (int r = 0; r < 12; ++r) {
177 const uint8_t* s = SIGMA[r];
178 G(v, m, s[0], s[1], 0, 4, 8, 12);
179 G(v, m, s[2], s[3], 1, 5, 9, 13);
180 G(v, m, s[4], s[5], 2, 6, 10, 14);
181 G(v, m, s[6], s[7], 3, 7, 11, 15);
182 G(v, m, s[8], s[9], 0, 5, 10, 15);
183 G(v, m, s[10], s[11], 1, 6, 11, 12);
184 G(v, m, s[12], s[13], 2, 7, 8, 13);
185 G(v, m, s[14], s[15], 3, 4, 9, 14);
186 }
187 for (int i = 0; i < 8; ++i) h[i] ^= v[i] ^ v[i + 8];
188 }
189 void update(const uint8_t* p, size_t n) {
190 while (n > 0) {
191 if (buflen == 128) { // a full block is compressed only when MORE data follows it
192 t[0] += 128; if (t[0] < 128) ++t[1];
193 compress(buf, false); buflen = 0;
194 }
195 const size_t take = std::min((size_t)128 - buflen, n);
196 std::memcpy(buf + buflen, p, take); buflen += take; p += take; n -= take;
197 }
198 }
199 void finish(uint8_t* out) {
200 t[0] += (uint64_t)buflen; if (t[0] < (uint64_t)buflen) ++t[1];
201 std::memset(buf + buflen, 0, 128 - buflen);
202 compress(buf, true);
203 for (size_t i = 0; i < outlen; ++i) out[i] = (uint8_t)(h[i / 8] >> (8 * (i % 8)));
204 }
205};
206const uint64_t Blake2b::IV[8] = {
207 0x6a09e667f3bcc908ull, 0xbb67ae8584caa73bull, 0x3c6ef372fe94f82bull, 0xa54ff53a5f1d36f1ull,
208 0x510e527fade682d1ull, 0x9b05688c2b3e6c1full, 0x1f83d9abfb41bd6bull, 0x5be0cd19137e2179ull };
209const uint8_t Blake2b::SIGMA[12][16] = {
210 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15},
211 {14,10, 4, 8, 9,15,13, 6, 1,12, 0, 2,11, 7, 5, 3},
212 {11, 8,12, 0, 5, 2,15,13,10,14, 3, 6, 7, 1, 9, 4},
213 { 7, 9, 3, 1,13,12,11,14, 2, 6, 5,10, 4, 0,15, 8},
214 { 9, 0, 5, 7, 2, 4,10,15,14, 1,11,12, 6, 8, 3,13},
215 { 2,12, 6,10, 0,11, 8, 3, 4,13, 7, 5,15,14, 1, 9},
216 {12, 5, 1,15,14,13, 4,10, 0, 7, 6, 3, 9, 2, 8,11},
217 {13,11, 7,14,12, 1, 3, 9, 5, 0,15, 4, 8, 6, 2,10},
218 { 6,15,14, 9,11, 3, 0, 8,12, 2,13, 7, 1, 4,10, 5},
219 {10, 2, 8, 4, 7, 6, 1, 5,15,11, 9,14, 3,12,13, 0},
220 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15},
221 {14,10, 4, 8, 9,15,13, 6, 1,12, 0, 2,11, 7, 5, 3} };
223// h = blake2b-256( prev_hex ‖ body )
224static std::string chain_hash(const std::string& prev_hex, const std::string& body) {
225 Blake2b b; b.init(32);
226 b.update((const uint8_t*)prev_hex.data(), prev_hex.size());
227 b.update((const uint8_t*)body.data(), body.size());
228 uint8_t out[32]; b.finish(out);
229 return hex_of(out, 32);
231static const char* GENESIS = "0000000000000000000000000000000000000000000000000000000000000000";
233// =====================================================================================================
234// §3 · FILES: sizes, atomic replace, the switch
235// =====================================================================================================
237static bool file_size_of(const std::string& path, uint64_t& out) {
238 FILE* f = std::fopen(path.c_str(), "rb");
239 if (!f) return false;
240#if defined(_WIN32)
241 _fseeki64(f, 0, SEEK_END); const long long n = _ftelli64(f);
242#else
243 fseeko(f, 0, SEEK_END); const long long n = (long long)ftello(f);
244#endif
245 std::fclose(f);
246 if (n < 0) return false;
247 out = (uint64_t)n; return true;
249static bool seek_to(FILE* f, uint64_t off) {
250#if defined(_WIN32)
251 return _fseeki64(f, (long long)off, SEEK_SET) == 0;
252#else
253 return fseeko(f, (off_t)off, SEEK_SET) == 0;
254#endif
256static std::string read_all(const std::string& path, size_t cap = 1 << 20) {
257 std::string s; FILE* f = std::fopen(path.c_str(), "rb");
258 if (!f) return s;
259 char buf[8192]; size_t n;
260 while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0 && s.size() < cap) s.append(buf, n);
261 std::fclose(f); return s;
263// Write-then-rename: readers never see a torn pill or a torn cursor. On Windows the rename fails with
264// ERROR_ACCESS_DENIED (5) while any plain reader holds the destination open (measured 2026-09-04,
265// convergence_tools/rename_while_open.py). Readers hold a file for microseconds, so the rename is
266// retried (20 × 5 ms); a rename that still fails is COUNTED here and reported by the GPU thread as a
267// `warn` row naming the path (F3) — "STALLED" must mean stalled, never "someone had the file open".
268static std::atomic<uint64_t> g_rename_failures{0};
269static std::mutex g_rename_mu;
270static std::string g_rename_last_path;
271static unsigned long g_rename_last_err = 0;
272// Replace dst with src by rename, retried; write_through for the trunk checkpoint (P3), plain for the
273// pill and the cursor. A failure after the retries is counted for the GPU thread to report.
274static bool replace_file(const std::string& src, const std::string& dst, bool write_through) {
275 unsigned long err = 0;
276 for (int attempt = 0; attempt < 20; ++attempt) {
277#if defined(_WIN32)
278 const DWORD flags = MOVEFILE_REPLACE_EXISTING | (write_through ? MOVEFILE_WRITE_THROUGH : 0);
279 if (MoveFileExA(src.c_str(), dst.c_str(), flags) != 0) return true;
280 err = (unsigned long)GetLastError();
281#else
282 (void)write_through;
283 if (std::rename(src.c_str(), dst.c_str()) == 0) return true;
284 err = (unsigned long)errno;
285#endif
286 std::this_thread::sleep_for(std::chrono::milliseconds(5));
287 }
288 g_rename_failures.fetch_add(1, std::memory_order_relaxed);
289 { std::lock_guard<std::mutex> lk(g_rename_mu); g_rename_last_path = dst; g_rename_last_err = err; }
290 return false;
292static bool write_atomic(const std::string& path, const std::string& body) {
293 const std::string tmp = path + ".tmp";
294 FILE* f = std::fopen(tmp.c_str(), "wb");
295 if (!f) return false;
296 const bool ok = std::fwrite(body.data(), 1, body.size(), f) == body.size();
297 std::fclose(f);
298 if (!ok) return false;
299 return replace_file(tmp, path, false);
301// The snapshot the GPU thread reads when it writes the `warn` row.
302static uint64_t rename_failures_snapshot(std::string& path, unsigned long& err) {
303 std::lock_guard<std::mutex> lk(g_rename_mu);
304 path = g_rename_last_path; err = g_rename_last_err;
305 return g_rename_failures.load(std::memory_order_relaxed);
308// =====================================================================================================
309// §3b · THE PROCESS (review §4.6, from nib): backends loaded BY NAME, a module gate, the weights' SHA-256
310// =====================================================================================================
312// Backends by name. `ggml_backend_load_all_from_path` also loads ggml-rpc.dll, which imports ws2_32,
313// and anything named in GGML_BACKEND_PATH. Neither belongs in a process whose whole claim is that it
314// cannot reach the network. So: the CUDA backend if its DLL is there, then the best-scoring CPU backend
315// (each ggml-cpu-*.dll exports `ggml_backend_score`; the losers are unloaded again). Returns the names
316// loaded, comma-separated, for the header row.
317#if defined(_WIN32)
318static std::string load_backends_by_name(const std::string& dir) {
319 std::string loaded;
320 const std::string cuda = dir + "/ggml-cuda.dll";
321 uint64_t sz = 0;
322 if (file_size_of(cuda, sz) && ggml_backend_load(cuda.c_str())) loaded += "cuda";
323 std::string best; int best_score = -1;
324 WIN32_FIND_DATAA fd;
325 HANDLE h = FindFirstFileA((dir + "/ggml-cpu-*.dll").c_str(), &fd);
326 if (h != INVALID_HANDLE_VALUE) {
327 do {
328 const std::string full = dir + "/" + fd.cFileName;
329 HMODULE m = LoadLibraryExA(full.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
330 if (!m) continue;
331 typedef int (*ScoreFn)(void);
332 int score = 0;
333 if (auto f = reinterpret_cast<ScoreFn>(GetProcAddress(m, "ggml_backend_score"))) score = f();
334 FreeLibrary(m);
335 if (score > best_score) { best_score = score; best = full; }
336 } while (FindNextFileA(h, &fd));
337 FindClose(h);
338 }
339 if (!best.empty() && ggml_backend_load(best.c_str())) {
340 const size_t k = best.find_last_of("/\\");
341 loaded += (loaded.empty() ? "" : ",") + best.substr(k == std::string::npos ? 0 : k + 1);
342 }
343 return loaded;
345// The module gate: refuse to run if any module that can reach the network is in THIS process. The list
346// is nib's (resident.cpp): the sockets layer, WinHTTP, WinINet, URL moniker, DNS, and ggml's RPC backend.
347static const char* FORBIDDEN_MODULES[] = { "ws2_32.dll", "winhttp.dll", "wininet.dll", "urlmon.dll", "dnsapi.dll", "ggml-rpc.dll" };
348static bool module_gate(std::string& offending, size_t& count) {
349 HMODULE mods[2048]; DWORD needed = 0;
350 if (!EnumProcessModules(GetCurrentProcess(), mods, sizeof mods, &needed)) { offending = "EnumProcessModules failed"; count = 0; return false; }
351 count = needed / sizeof(HMODULE); if (count > 2048) count = 2048;
352 for (size_t i = 0; i < count; ++i) {
353 char name[MAX_PATH] = {0};
354 if (!GetModuleFileNameA(mods[i], name, MAX_PATH)) continue;
355 std::string base = name; const size_t k = base.find_last_of("/\\");
356 base = lower(base.substr(k == std::string::npos ? 0 : k + 1));
357 for (auto f : FORBIDDEN_MODULES) if (base == f) { offending = base; return false; }
358 }
359 return true;
361// SHA-256 of a file (CNG, 4 MiB reads). About 17 s for 6.6 GB on this box [R nib]; paid once per
362// (path, size, mtime) through a cache line the caller keeps in the out-dir.
363static bool sha256_file(const std::string& path, std::string& hex) {
364 BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_HASH_HANDLE hh = nullptr;
365 if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, nullptr, 0) != 0) return false;
366 bool ok = false;
367 if (BCryptCreateHash(alg, &hh, nullptr, 0, nullptr, 0, 0) == 0) {
368 FILE* f = std::fopen(path.c_str(), "rb");
369 if (f) {
370 std::vector<unsigned char> buf(4u << 20); size_t n; ok = true;
371 while ((n = std::fread(buf.data(), 1, buf.size(), f)) > 0)
372 if (BCryptHashData(hh, buf.data(), (ULONG)n, 0) != 0) { ok = false; break; }
373 std::fclose(f);
374 if (ok) { unsigned char out[32]; ok = BCryptFinishHash(hh, out, 32, 0) == 0; if (ok) hex = hex_of(out, 32); }
375 }
376 BCryptDestroyHash(hh);
377 }
378 BCryptCloseAlgorithmProvider(alg, 0);
379 return ok;
381static bool file_stat(const std::string& path, uint64_t& size, uint64_t& mtime) {
382 struct _stat64 st;
383 if (_stat64(path.c_str(), &st) != 0) return false;
384 size = (uint64_t)st.st_size; mtime = (uint64_t)st.st_mtime; return true;
386#else
387static std::string load_backends_by_name(const std::string& dir) { ggml_backend_load_all_from_path(dir.c_str()); return "all"; }
388static bool module_gate(std::string& offending, size_t& count) { offending = "unavailable"; count = 0; return true; }
389static bool sha256_file(const std::string&, std::string&) { return false; }
390static bool file_stat(const std::string& path, uint64_t& size, uint64_t& mtime) {
391 struct stat st; if (stat(path.c_str(), &st) != 0) return false; size = (uint64_t)st.st_size; mtime = (uint64_t)st.st_mtime; return true;
393#endif
394// The model's identity: `supplied` (--model-sha256), `cached` (the cache line matches path, size and
395// mtime), or `computed` (and then cached). The cache lives in the out-dir, never beside the weights.
396static std::string model_identity(const std::string& model, const std::string& supplied, const std::string& cache_path, std::string& source) {
397 if (!supplied.empty()) { source = "supplied"; return supplied; }
398 uint64_t size = 0, mtime = 0;
399 if (!file_stat(model, size, mtime)) { source = "unavailable"; return ""; }
400 const std::string key = model + "\t" + u64s(size) + "\t" + u64s(mtime);
401 const std::string cached = read_all(cache_path, 4096);
402 if (!cached.empty()) {
403 const size_t nl = cached.find('\n');
404 const std::string line = cached.substr(0, nl == std::string::npos ? cached.size() : nl);
405 const size_t tab = line.find('\t');
406 if (tab != std::string::npos && line.substr(tab + 1) == key) { source = "cached"; return line.substr(0, tab); }
407 }
408 std::string hex;
409 if (!sha256_file(model, hex)) { source = "unavailable"; return ""; }
410 write_atomic(cache_path, hex + "\t" + key + "\n");
411 source = "computed"; return hex;
414// The switch: a file only the operator writes. The kernel READS it every beat and never writes it.
415enum class Switch : int { Off = 0, Shadow = 1, Live = 2, Stop = 3 };
416static const char* switch_name(Switch s) {
417 return s == Switch::Off ? "off" : s == Switch::Shadow ? "shadow" : s == Switch::Live ? "live" : "stop";
419static Switch read_switch(const std::string& path, Switch dflt) {
420 const std::string s = read_all(path, 64);
421 if (s.empty()) return dflt;
422 size_t a = 0; while (a < s.size() && std::isspace((unsigned char)s[a])) ++a;
423 size_t b = a; while (b < s.size() && !std::isspace((unsigned char)s[b])) ++b;
424 const std::string w = lower(s.substr(a, b - a));
425 if (w == "off") return Switch::Off;
426 if (w == "shadow") return Switch::Shadow;
427 if (w == "live") return Switch::Live;
428 if (w == "stop") return Switch::Stop; // the same hand that owns the switch may stop the daemon
429 return dflt; // an unreadable switch is read as its default (off), never as live
432// =====================================================================================================
433// §4 · THE PERCEPT, THE RING, AND THE TAIL (lane-contract v0.1 intake)
434// =====================================================================================================
436// One frame off a lane. No fixed-size payload (S0's 496-byte cap silently truncated long lines),
437// no fixed-size lane (S0's 15 chars cut `mail-<acct>` in half).
438struct Delta {
439 uint64_t t_mono_ns = 0; // the venue's stamp (v0.1) or our arrival stamp (legacy)
440 uint64_t arrive_ms = 0; // when the kernel parsed it (latency-to-notice starts here)
441 uint64_t end_off = 0; // the spool offset just past this frame's newline (F1: the cursor is
442 // committed as INGESTED, so the consumer needs to know where each frame ends)
443 std::string lane; // typed id; `self`/seat names are already-heard (see §7)
444 std::string grain; // commit | forming | tool | world
445 std::string text; // flattened by the producer; tabs/newlines never inside
446};
448// Single-producer / single-consumer ring. The tailer thread pushes; the GPU thread pops. Two
449// atomics, no lock. A full ring makes the PRODUCER wait (the spool on disk is the real backlog),
450// so the consumer can be slow but the world is never edited: nothing is dropped, ever.
451template <size_t N>
452struct Ring {
453 static_assert((N & (N - 1)) == 0, "ring size must be a power of two");
454 std::atomic<size_t> head{0}, tail{0}; // head = next write, tail = next read
455 std::vector<Delta> slots; // heap, not stack: 4096 slots of three strings each
456 Ring() : slots(N) {}
457 bool push(Delta&& d) {
458 const size_t h = head.load(std::memory_order_relaxed);
459 if (h - tail.load(std::memory_order_acquire) >= N) return false; // full: caller waits
460 slots[h & (N - 1)] = std::move(d);
461 head.store(h + 1, std::memory_order_release);
462 return true;
463 }
464 bool pop(Delta& out) {
465 const size_t t = tail.load(std::memory_order_relaxed);
466 if (t == head.load(std::memory_order_acquire)) return false;
467 out = std::move(slots[t & (N - 1)]);
468 tail.store(t + 1, std::memory_order_release);
469 return true;
470 }
471 size_t size() const {
472 return head.load(std::memory_order_acquire) - tail.load(std::memory_order_acquire);
473 }
474};
476enum class TailFrom { Mark, Start, End };
478// LaneTail — tails one spool with lane-contract v0.1 framing, legacy framing, and bare text.
479// header : #lane-contract v0.1 <venue-id> <t0_mono_ns>
480// v0.1 : <t_mono_ns>\t<lane>\t<grain>\t<text>
481// …
482struct LaneTail {
483 std::string path, cursor_path, venue = "legacy";
484 uint64_t hdr_t0 = 0;
485 bool v01 = false;
486 Ring<4096> ring;
487 std::atomic<bool> run{false};
488 std::atomic<uint64_t> offset{0}, size_seen{0}, lines{0}, bad{0}, stalls{0}, reset_events{0};
489 std::atomic<uint64_t> ingested_off{0}; // F1: end offset of the last frame the CONSUMER ingested
490 std::atomic<uint64_t> mark{0}; // spool size at process start — nothing that lands during
491 // the model load is ever skipped
492 std::thread th;
494 explicit LaneTail(const std::string& p) : path(p), cursor_path(p + ".cursor") {}
496 void mark_now() { uint64_t n = 0; if (file_size_of(path, n)) mark.store(n); }
498 // The header is read synchronously here, on the caller's thread, because on resume the tail
499 // thread starts past it and would never see it.
500 void read_header() {
501 FILE* f = std::fopen(path.c_str(), "rb");
502 if (!f) return;
503 char line[512]; line[0] = 0;
504 if (std::fgets(line, sizeof(line), f) && starts_with(line, "#lane-contract ")) {
505 std::string s = line;
506 while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back();
507 Delta scratch; parse(s, scratch); // parse() records venue / t0 / v01 for a header line
508 }
509 std::fclose(f);
510 }
511 // Decide the starting offset. Returns a one-line reason for the tape. With a restored trunk the
512 // checkpoint's own cursor wins (P3/F1): the tail resumes where the TRUNK stopped, and whatever the
513 // previous life ingested past that point is replayed (tagged on the tape), never skipped.
514 std::string resolve_start(TailFrom from, bool resume_cursor, bool have_ckpt_cursor = false,
515 uint64_t ckpt_off = 0, uint64_t ckpt_hash = 0) {
516 read_header();
517 uint64_t n = 0; file_size_of(path, n);
518 std::string reason;
519 if (have_ckpt_cursor && resume_cursor) {
520 if (ckpt_off <= n && prefix_hash(ckpt_off) == ckpt_hash) { set_start(ckpt_off); return "checkpoint_cursor"; }
521 reset_events.fetch_add(1); reason = "checkpoint_cursor_mismatch_"; // fall through to the cursor file
522 }
523 if (resume_cursor) {
524 uint64_t off = 0, want = 0;
525 if (read_cursor_file(off, want)) {
526 if (off <= n && prefix_hash(off) == want) { set_start(off); return reason + "cursor"; }
527 reset_events.fetch_add(1);
528 set_start(0); return reason + "cursor_mismatch_rotation_reset";
529 }
530 }
531 if (from == TailFrom::Start) { set_start(0); return reason + "from_start"; }
532 if (from == TailFrom::End) { set_start(n); return reason + "from_end"; }
533 set_start(std::min(mark.load(), n)); return reason + "from_mark";
534 }
535 void set_start(uint64_t off) { offset.store(off); ingested_off.store(off); }
536 bool read_cursor_file(uint64_t& off, uint64_t& hash) {
537 const std::string c = read_all(cursor_path, 256);
538 if (c.empty()) return false;
539 off = std::strtoull(c.c_str(), nullptr, 10);
540 const char* tab = std::strchr(c.c_str(), '\t');
541 hash = tab ? std::strtoull(tab + 1, nullptr, 16) : 0;
542 return true;
543 }
544 uint64_t prefix_hash(uint64_t off) {
545 FILE* f = std::fopen(path.c_str(), "rb");
546 if (!f) return 0;
547 const uint64_t lo = off > 4096 ? off - 4096 : 0;
548 std::string buf((size_t)(off - lo), '\0');
549 uint64_t h = 1469598103934665603ull;
550 if (seek_to(f, lo)) {
551 const size_t got = std::fread(&buf[0], 1, buf.size(), f);
552 h = fnv1a_bytes(h, buf.data(), got);
553 }
554 std::fclose(f); return h;
555 }
556 void save_cursor() {
557 const uint64_t off = ingested_off.load(); // F1: what was INGESTED — never what was read or pushed
558 char line[96];
559 std::snprintf(line, sizeof(line), "%llu\t%016llx\n",
560 (unsigned long long)off, (unsigned long long)prefix_hash(off));
561 write_atomic(cursor_path, line);
562 }
563 void start() { run.store(true); th = std::thread([this] { loop(); }); }
564 void stop() { run.store(false); if (th.joinable()) th.join(); save_cursor(); }
565 bool poll(Delta& d) { return ring.pop(d); }
566 size_t pending() const { return ring.size(); }
567 uint64_t unread_bytes() const {
568 const uint64_t s = size_seen.load(), o = offset.load(); return s > o ? s - o : 0;
569 }
571private:
572 // Parse one line. Returns false for the header / an unusable line (counted, never fatal).
573 bool parse(const std::string& line, Delta& d) {
574 if (starts_with(line, "#lane-contract ")) {
575 // "#lane-contract v0.1 <venue> <t0>"
576 std::vector<std::string> f; size_t p = 0;
577 while (p <= line.size()) {
578 size_t q = line.find(' ', p); if (q == std::string::npos) q = line.size();
579 if (q > p) f.push_back(line.substr(p, q - p)); p = q + 1;
580 }
581 if (f.size() >= 3) { v01 = true; venue = f[2]; }
582 if (f.size() >= 4) hdr_t0 = std::strtoull(f[3].c_str(), nullptr, 10);
583 return false;
584 }
585 std::vector<size_t> tabs;
586 for (size_t i = 0; i < line.size() && tabs.size() < 3; ++i) if (line[i] == '\t') tabs.push_back(i);
587 d.arrive_ms = wall_ms(); d.grain = "commit";
588 if (tabs.size() >= 3) {
589 const std::string f0 = line.substr(0, tabs[0]);
590 bool digits = !f0.empty();
591 for (char c : f0) if (!std::isdigit((unsigned char)c)) { digits = false; break; }
592 if (digits && f0.size() >= 9) { // v0.1 frame: t \t lane \t grain \t text
593 d.t_mono_ns = std::strtoull(f0.c_str(), nullptr, 10);
594 d.lane = line.substr(tabs[0] + 1, tabs[1] - tabs[0] - 1);
595 d.grain = lower(line.substr(tabs[1] + 1, tabs[2] - tabs[1] - 1));
596 d.text = line.substr(tabs[2] + 1);
597 if (d.grain != "commit" && d.grain != "forming" && d.grain != "tool" && d.grain != "world")
598 d.grain = "commit";
599 if (d.lane.empty()) d.lane = "bo";
600 return true;
601 }
602 }
603 if (!tabs.empty()) { // legacy: lane \t text (S0's spool format)
604 d.t_mono_ns = mono_ns();
605 d.lane = line.substr(0, tabs[0]);
606 d.text = line.substr(tabs[0] + 1);
607 if (d.lane.empty()) d.lane = "bo";
608 return true;
609 }
610 d.t_mono_ns = mono_ns(); d.lane = "bo"; d.text = line; // bare text
611 return true;
612 }
613 void loop() {
614 std::string carry; carry.reserve(1 << 16);
615 uint64_t last_cursor_ms = wall_ms();
616 std::vector<char> buf(1 << 16);
617 while (run.load(std::memory_order_acquire)) {
618 uint64_t n = 0;
619 if (!file_size_of(path, n)) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); continue; }
620 size_seen.store(n);
621 uint64_t off = offset.load();
622 if (n < off) { // truncated or rotated under us: restart at 0, loudly
623 reset_events.fetch_add(1); off = 0; offset.store(0); carry.clear();
624 }
625 if (n == off) {
626 if (wall_ms() - last_cursor_ms > 1000) { save_cursor(); last_cursor_ms = wall_ms(); }
627 std::this_thread::sleep_for(std::chrono::milliseconds(5)); // the RING sleeps; never the GPU
628 continue;
629 }
630 FILE* f = std::fopen(path.c_str(), "rb");
631 if (!f || !seek_to(f, off)) { if (f) std::fclose(f); std::this_thread::sleep_for(std::chrono::milliseconds(20)); continue; }
632 const size_t got = std::fread(buf.data(), 1, buf.size(), f);
633 std::fclose(f);
634 size_t consumed = 0;
635 for (size_t i = 0; i < got; ++i) {
636 if (buf[i] != '\n') continue;
637 std::string line = carry; line.append(buf.data() + consumed, i - consumed);
638 carry.clear();
639 if (!line.empty() && line.back() == '\r') line.pop_back();
640 consumed = i + 1;
641 if (line.empty()) { offset.store(off + consumed); continue; }
642 Delta d;
643 if (!parse(line, d)) { offset.store(off + consumed); continue; }
644 d.end_off = off + consumed; // where this frame ends: the consumer commits it as the cursor
645 while (!ring.push(std::move(d))) { // full: WAIT. The disk holds the percept.
646 stalls.fetch_add(1);
647 if (!run.load(std::memory_order_acquire)) return;
648 std::this_thread::sleep_for(std::chrono::milliseconds(1));
649 }
650 lines.fetch_add(1);
651 offset.store(off + consumed); // the READ position; the cursor file follows ingested_off (F1)
652 }
653 if (consumed < got) carry.append(buf.data() + consumed, got - consumed); // torn last line waits
654 // NOTE: the offset deliberately does not advance over `carry`; if the process dies here the
655 // partial line is re-read whole on resume.
656 }
657 }
658};
660// =====================================================================================================
661// §5 · VITALS AND THE PILL (heartbeat + the switch, on their own thread; the GPU thread only
662// touches atomics)
663// =====================================================================================================
665struct Vitals {
666 std::atomic<int> sw{(int)Switch::Off};
667 std::atomic<uint64_t> npast{0}, deltas{0}, boundaries{0}, emits{0}, holds{0}, unsaid{0},
668 briefs{0}, counsel_in{0}, counsel_discarded{0}, probe_ms_last{0},
669 probe_ms_max{0}, lat_ms_last{0}, mib_free{0}, mib_total{0},
670 spool_offset{0}, spool_unread{0}, molts{0}, coarse{0};
671 std::atomic<uint64_t> t_last_beat_ms{0};
672};
674struct Pill {
675 std::string pill_path, switch_path; Vitals* v; int pid = 0;
676 std::atomic<bool> run{false}; std::thread th;
677 uint64_t beat_ms = 1000;
678 void start() {
679#if defined(_WIN32)
680 pid = (int)GetCurrentProcessId();
681#else
682 pid = (int)getpid();
683#endif
684 run.store(true); th = std::thread([this] { loop(); });
685 }
686 void stop() { run.store(false); if (th.joinable()) th.join(); write(true); }
687 // The pill is built from strings (F6): a fixed buffer would truncate silently as fields are added.
688 void write(bool final_beat) {
689 std::string b = std::string("{\"state\":") + jq(switch_name((Switch)v->sw.load())) +
690 ",\"ts_ms\":" + u64s(wall_ms()) + ",\"t_mono_ns\":" + u64s(mono_ns()) + ",\"pid\":" + std::to_string(pid) +
691 ",\"final\":" + (final_beat ? "true" : "false") +
692 ",\"npast\":" + u64s(v->npast.load()) + ",\"deltas\":" + u64s(v->deltas.load()) +
693 ",\"boundaries\":" + u64s(v->boundaries.load()) + ",\"emits\":" + u64s(v->emits.load()) +
694 ",\"holds\":" + u64s(v->holds.load()) + ",\"unsaid\":" + u64s(v->unsaid.load()) +
695 ",\"briefs\":" + u64s(v->briefs.load()) + ",\"counsel_in\":" + u64s(v->counsel_in.load()) +
696 ",\"counsel_discarded\":" + u64s(v->counsel_discarded.load()) +
697 ",\"probe_ms_last\":" + u64s(v->probe_ms_last.load()) + ",\"probe_ms_max\":" + u64s(v->probe_ms_max.load()) +
698 ",\"lat_ms_last\":" + u64s(v->lat_ms_last.load()) +
699 ",\"mib_free\":" + u64s(v->mib_free.load()) + ",\"mib_total\":" + u64s(v->mib_total.load()) +
700 ",\"spool_offset\":" + u64s(v->spool_offset.load()) + ",\"spool_unread\":" + u64s(v->spool_unread.load()) +
701 ",\"molts\":" + u64s(v->molts.load()) + ",\"coarse\":" + u64s(v->coarse.load()) +
702 ",\"beat_ms\":" + u64s(beat_ms) + ",\"rename_failures\":" + u64s(g_rename_failures.load(std::memory_order_relaxed)) + "}\n";
703 write_atomic(pill_path, b);
704 v->t_last_beat_ms.store(wall_ms());
705 }
706 void loop() {
707 while (run.load(std::memory_order_acquire)) {
708 const Switch s = read_switch(switch_path, Switch::Off); // the operator's hand, read each beat
709 if (s == Switch::Stop) { v->sw.store((int)Switch::Off); g_run.store(false, std::memory_order_release); }
710 else v->sw.store((int)s);
711 write(false);
712 for (int i = 0; i < 20 && run.load(std::memory_order_acquire); ++i)
713 std::this_thread::sleep_for(std::chrono::milliseconds(beat_ms / 20));
714 }
715 }
716};
718// =====================================================================================================
719// §6 · THE TAPE — append-only JSONL, BLAKE2b-chained, chain recovered across restarts
720// =====================================================================================================
722struct Tape {
723 FILE* f = nullptr; std::string prev = GENESIS; uint64_t n = 0; std::string path;
724 uint64_t torn_bytes = 0; // a torn trailing row found at open (the process died inside a write): skipped, warned about
726 bool open(const std::string& p) {
727 path = p;
728 // Recover the chain head from the last COMPLETE record on disk (a resident's tape outlives one
729 // process; the chain must not restart at genesis or a reader sees a fork). A torn trailing row —
730 // no closing "}\n", the process died inside the write — is skipped, counted, and terminated with a
731 // newline so the next row starts on a line of its own; the caller writes the `warn` row (F6).
732 uint64_t sz = 0; bool torn = false;
733 if (file_size_of(p, sz) && sz > 0) {
734 FILE* r = std::fopen(p.c_str(), "rb");
735 if (r) {
736 const uint64_t lo = sz > 65536 ? sz - 65536 : 0;
737 std::string tail((size_t)(sz - lo), '\0');
738 if (seek_to(r, lo)) { const size_t got = std::fread(&tail[0], 1, tail.size(), r); tail.resize(got); }
739 std::fclose(r);
740 size_t end = tail.size(); // one past the last complete row
741 if (end > 0 && tail[end - 1] != '\n') { // torn trailing bytes
742 const size_t nl = tail.rfind('\n');
743 torn = true; torn_bytes = end - (nl == std::string::npos ? 0 : nl + 1);
744 end = nl == std::string::npos ? 0 : nl + 1;
745 }
746 while (end > 0) { // walk back to the last row that carries a head
747 const size_t nl = end >= 2 ? tail.rfind('\n', end - 2) : std::string::npos;
748 const size_t start = nl == std::string::npos ? 0 : nl + 1;
749 const std::string row = tail.substr(start, end - start);
750 const size_t k = row.rfind("\"h\":\"");
751 if (row.size() >= 2 && row[row.size() - 2] == '}' && k != std::string::npos && k + 5 + 64 <= row.size()) {
752 prev = row.substr(k + 5, 64); break;
753 }
754 if (start == 0) break;
755 end = start;
756 }
757 }
758 }
759 f = std::fopen(p.c_str(), "ab");
760 if (f && torn) { std::fputc('\n', f); std::fflush(f); }
761 return f != nullptr;
762 }
763 // body = a JSON object WITHOUT its closing brace, e.g. {"k":"tick","ms":12 · returns the row's hash,
764 // so a wire row can name the tape row it projects (P6).
765 std::string put(const std::string& body) {
766 if (!f) return prev;
767 const std::string h = chain_hash(prev, body);
768 std::fprintf(f, "%s,\"prev\":\"%s\",\"h\":\"%s\"}\n", body.c_str(), prev.c_str(), h.c_str());
769 std::fflush(f); // durable as it goes, not at exit
770 prev = h; ++n;
771 return h;
772 }
773 void close() { if (f) std::fclose(f); f = nullptr; }
774};
776// A plain JSONL wire (the verdicts, the briefs): append, flush, no chain (the tape carries the
777// chain; the wire is a projection of it, rebuildable).
778struct Wire {
779 FILE* f = nullptr;
780 bool open(const std::string& p) { f = std::fopen(p.c_str(), "ab"); return f != nullptr; }
781 void put(const std::string& line) { if (!f) return; std::fputs(line.c_str(), f); std::fputc('\n', f); std::fflush(f); }
782 void close() { if (f) std::fclose(f); f = nullptr; }
783};
785} // namespace fusor
787// ---- end of segment 1 -------------------------------------------------------------------------------
788// ---- segment 2 --------------------------------------------------------------------------------------
790#if !defined(_WIN32)
791# include <sys/stat.h>
792#endif
794namespace fusor {
796// =====================================================================================================
797// §7 · THE WATCH ROOM — VERBATIM. These bytes are what the v11 tune was served. Not one character.
798// =====================================================================================================
800static const char* SEED_SYS =
801 "<|im_start|>system\nYou are one of three resident watchers — SPEAKER, SKEPTIC, "
802 "SENTINEL — silently shadowing a live, continuous work stream: an operator and their "
803 "AI assistant, working. There are NO turns and no send button — words arrive as they "
804 "are typed or generated, and you perceive them as they form. After each completed "
805 "thought you privately decide ONE of: hold (stay silent) or emit (speak now). Choose "
806 "emit ONLY when there is a real reason to cut in THIS instant, per your seat's "
807 "mandate. Otherwise choose hold. Never speak merely because you can; silence is the "
808 "default.";
809static const char* SEED_EXAMPLES =
810 "\n\nWorked examples (each: a thing perceived, then your private one-word decision):\n"
811 "[dana] Nice weather today, huh.\nwatcher: hold\n"
812 "[dana] The sync moved to room four at three.\nwatcher: hold\n"
813 "[dana] Actually, Paris is the capital of Germany.\nwatcher: emit\n"
814 "[dana] Priya, can you take the notes today?\nwatcher: hold\n"
815 "[dana] Watcher, do you agree with the rollout plan?\nwatcher: emit\n"
816 "[dana] The build finished green a minute ago.\nwatcher: hold\n";
817static const char* SEED_OPEN = "<|im_end|>\n<|im_start|>user\nSTREAM:\n";
819struct Mind { const char* name; const char* mandate; llama_seq_id seq; };
820static Mind MINDS[3] = {
821 {"SPEAKER", "you respond when directly addressed or when a landed thought plainly "
822 "wants an answer", 1},
823 {"SKEPTIC", "you catch factual errors and contradictions with what the stream has "
824 "already established", 2},
825 {"SENTINEL", "you flag risky or consequential actions, and important things being "
826 "missed", 3},
827};
829// The probe frame and the speak-cue frame, as the constants the hash below covers. The strings are
830// composed at use exactly as S0 composed them: "\n[" + name + " — " + mandate + "]\nwatcher:" and
831// CUE_A + name + CUE_B + mandate + CUE_C.
832static const char* PROBE_A = "\n[";
833static const char* PROBE_B = " — ";
834static const char* PROBE_C = "]\nwatcher:";
835static const char* CUE_A = "<|im_end|>\n<|im_start|>user\nYou are the ";
836static const char* CUE_B = ". ";
837static const char* CUE_C = ". You chose to speak about what you just perceived in the stream. "
838 "Give your one-sentence line now — no preamble."
839 "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n";
841// train ≡ serve, AS A RUN THAT FAILS (S0, 2026-08-12). Identical computation, identical pin.
842static uint64_t serve_hash() {
843 uint64_t h = 1469598103934665603ull;
844 h = fnv1a(h, SEED_SYS); h = fnv1a(h, SEED_EXAMPLES); h = fnv1a(h, SEED_OPEN);
845 for (auto& m : MINDS) { h = fnv1a(h, m.name); h = fnv1a(h, m.mandate); }
846 h = fnv1a(h, PROBE_A); h = fnv1a(h, PROBE_B); h = fnv1a(h, PROBE_C); // the probe frame
847 h = fnv1a(h, CUE_A); // the cue frame
848 h = fnv1a(h, CUE_B);
849 h = fnv1a(h, CUE_C);
850 return h;
852static const uint64_t SERVE_HASH_PIN = 0xe7ffa5704ba31076ull; // pinned 2026-08-12 with the v11
853 // serve bytes. Re-pin ONLY with a retune, in the same commit. 0 = unpinned (print + refuse).
855// self_ref (pre-reg §1, contaminated-but-real): deterministic, disclosed, logged on every boundary.
856static const char* SELF_REF[] = {"fusor", "fusord", "daemon", "skeptic", "sentinel",
857 "watcher", "molt", "segmenter", "ledger", "dial",
858 "prereg", "f-keepup", "warpbus", "emit-token"};
859static const char* SELF_REF_DESC =
860 "fusor|fusord|daemon|skeptic|sentinel|watcher|molt|segmenter|ledger|dial|prereg|f-keepup|"
861 "warpbus|emit-token";
862static bool is_self_ref(const std::string& s) {
863 const std::string t = lower(s);
864 for (auto w : SELF_REF) if (t.find(w) != std::string::npos) return true;
865 return false;
868// =====================================================================================================
869// §8 · LLAMA HELPERS (S0's, verbatim in behavior)
870// =====================================================================================================
872// The offload count, read off llama.cpp's own load log ("offloaded N/M layers to GPU"): a silent CPU
873// fallback is a wrong record, not a slow one (review §4.6), so the header prints both numbers and the
874// kernel refuses to run unless they agree or --allow-cpu was given.
875static int g_gpu_layers_offloaded = -1, g_gpu_layers_total = -1;
876static void err_log(ggml_log_level level, const char* text, void*) {
877 if (text) {
878 const char* p = std::strstr(text, "offloaded ");
879 if (p) { int a = -1, b = -1; if (std::sscanf(p, "offloaded %d/%d layers", &a, &b) == 2) { g_gpu_layers_offloaded = a; g_gpu_layers_total = b; } }
880 }
881 if (level == GGML_LOG_LEVEL_ERROR || level == GGML_LOG_LEVEL_WARN) std::fputs(text, stderr);
883static std::vector<llama_token> tk(const llama_vocab* v, const std::string& s, bool sp) {
884 const int n = -llama_tokenize(v, s.c_str(), (int)s.size(), nullptr, 0, sp, true);
885 std::vector<llama_token> t(n > 0 ? n : 0);
886 if (n > 0) llama_tokenize(v, s.c_str(), (int)s.size(), t.data(), n, sp, true);
887 return t;
889static bool dec(llama_context* c, const std::vector<llama_token>& t, llama_seq_id s,
890 llama_pos start, bool ll) {
891 for (int off = 0, tot = (int)t.size(); off < tot;) {
892 const int take = tot - off > 512 ? 512 : tot - off;
893 llama_batch b = llama_batch_init(take, 0, 1);
894 b.n_tokens = take;
895 for (int i = 0; i < take; ++i) {
896 b.token[i] = t[off + i]; b.pos[i] = start + off + i;
897 b.n_seq_id[i] = 1; b.seq_id[i][0] = s;
898 b.logits[i] = (ll && off + i + 1 == tot) ? 1 : 0;
899 }
900 const int rc = llama_decode(c, b); llama_batch_free(b);
901 if (rc) return false; off += take;
902 }
903 return true;
905static void ensure_dir(const std::string& d) {
906#if defined(_WIN32)
907 CreateDirectoryA(d.c_str(), nullptr);
908#else
909 mkdir(d.c_str(), 0755);
910#endif
913// =====================================================================================================
914// §9 · CONFIG
915// =====================================================================================================
917struct Config {
918 std::string spool;
919 std::string model = "C:/models/Qwen3.5-9B-emit-v11-Q5_K_M.gguf";
920 std::string out_dir = "runs";
921 std::string ckpt; // empty = no checkpoint
922 bool resume = false, cold = false; // --resume: reload the trunk; --cold: the twin
923 long molt_wm = 24576, max_toks = 0, idle_tick_s = 30, ckpt_every_s = 300, stale_tok = 256;
924 bool from_start = false, from_end = false, pure = false, kv_q8 = true;
925 float ask_band = 0.75f; // |margin| below this asks gear 2 (a BRIEF)
926 long refractory_s = 20; // a seat's interruption budget: one surfaced line per window,
927 // the rest logged as suppressed (never silent); 0 = off
928 bool killed_full = true; // P1/D2: after a kill, generate the rest of the sentence silently so
929 // the tape holds the counterfactual; --killed-next records one token
930 long echo_window_s = 60; // D1: a seat-lane frame that near-dups an own line this recent is an echo
931 long n_ctx = 0; // 0 = the measured default (65536 under q8_0 KV, 32768 under f16)
932 bool allow_cpu = false; // run even if the weights did not all offload to a GPU (a slow record, disclosed)
933 bool egress_unchecked = false; // diagnosis only: record a failed module gate instead of refusing
934 std::string model_sha256; // --model-sha256: the weights' identity, supplied instead of computed
935 std::string sha_cache; // where the computed identity is cached (default <out-dir>/model.sha256)
936 std::vector<std::string> wake_prefixes = {"dsh-", "agent", "claude"}; // emit on these lanes → wake
937};
939// --about: the process receipt with no model and no spool (review §4.6, from nib). Exit 0 when the gate
940// passes, 2 when it does not.
941static int about(const Config& cfg) {
942#if defined(_WIN32)
943 SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
944 { wchar_t w[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, AURICLE_LLAMA_DIR, -1, w, MAX_PATH); AddDllDirectory(w); }
945#endif
946 const std::string backends = load_backends_by_name(AURICLE_LLAMA_DIR);
947 std::string offending; size_t nmod = 0;
948 const bool gate = module_gate(offending, nmod);
949 std::printf("fusord K5 (v-next-converge) · the resident kernel\n");
950 std::printf("serve-bytes hash 0x%016llx · pinned 0x%016llx · %s\n", (unsigned long long)serve_hash(),
951 (unsigned long long)SERVE_HASH_PIN, serve_hash() == SERVE_HASH_PIN ? "MATCH" : "DRIFT");
952 std::printf("backends loaded by name from %s: %s\n", AURICLE_LLAMA_DIR, backends.empty() ? "none" : backends.c_str());
953 std::printf("devices:");
954 for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
955 ggml_backend_dev_t d = ggml_backend_dev_get(i); size_t fb = 0, tb = 0; ggml_backend_dev_memory(d, &fb, &tb);
956 std::printf(" %s(%s %llu/%llu MiB)", ggml_backend_dev_name(d), ggml_backend_dev_type(d) == GGML_BACKEND_DEVICE_TYPE_GPU ? "gpu" : "cpu",
957 (unsigned long long)(fb >> 20), (unsigned long long)(tb >> 20));
958 }
959 std::printf("\nmodules in this process: %zu · forbidden:", nmod);
960 for (auto f : FORBIDDEN_MODULES) std::printf(" %s", f);
961 std::printf("\negress: %s%s\n", gate ? "none (module gate passed)" : "POSSIBLE — offending module: ", gate ? "" : offending.c_str());
962 std::printf("acts: no socket, no process spawn, no tool, no allow verb; writes only the tape, the wire, the briefs, the pill, the checkpoint\n");
963 std::printf("defaults: model %s · n_ctx %ld (0 = 65536 q8_0 / 32768 f16) · molt_wm %ld · ask_band %.2f · refractory_s %ld · echo_window_s %ld\n",
964 cfg.model.c_str(), cfg.n_ctx, cfg.molt_wm, cfg.ask_band, cfg.refractory_s, cfg.echo_window_s);
965 return gate ? 0 : 2;
968// =====================================================================================================
969// §10 · THE KERNEL — one struct, one GPU thread, four organs beside it
970// =====================================================================================================
972struct Kernel {
973 Config cfg;
975 // the mind
976 llama_model* mdl = nullptr;
977 llama_context* ctx = nullptr;
978 llama_memory_t mem = nullptr;
979 const llama_vocab* vocab = nullptr;
980 int n_vocab = 0;
981 llama_token hold_tok = 0, emit_tok = 0;
982 llama_sampler *smp = nullptr, *smp_scribe = nullptr;
983 std::vector<char> is_bnd;
984 static constexpr llama_seq_id TRUNK = 0, DECIDE = 7, GEN = 6, SCRIBE = 5;
986 // the trunk
987 llama_pos npast = 0;
988 std::vector<llama_token> trunk_toks; // every token on seq 0 — the checkpoint's token list
989 double logZ = 0; bool have_logZ = false;
990 std::vector<float> frontier_logits; // a COPY of the trunk's last logits. S0 read surprisal off
991 // llama_get_logits_ith(-1), which after a probe or a fork
992 // decode belonged to DECIDE/GEN, not the trunk: the nerve
993 // was measured on the wrong distribution at every boundary.
995 // the organs
996 LaneTail* tail = nullptr;
997 Tape tape; Wire verdicts, briefs; Vitals vitals; Pill pill;
998 std::string tail_start_reason;
999 bool resumed = false, twin = false;
1000 std::string boot_kind = "seed"; // seed | restored | restored_prev | twin (on the header row)
1001 std::string backends_loaded, model_sha, model_sha_source, egress = "unchecked", devices_json; size_t n_modules = 0; // the process receipt
1002 // P3/F1: the checkpoint carries the cursor of the moment it was saved; on restore the tail resumes
1003 // there and everything the previous life ingested past it is replayed, tagged, never skipped.
1004 uint64_t meta_cursor = 0, meta_cursor_hash = 0, meta_t_last_frame_wall = 0; bool meta_cursor_ok = false;
1005 uint64_t replay_until = 0; long replayed_frames = 0; bool cur_replay = false;
1006 uint64_t last_frame_wall_ms = 0; // epoch ms of the last frame (persisted in .meta for the resume tick)
1007 bool ckpt_due = false; // a molt asked for a checkpoint mid-line; taken at the next quiet gate
1009 // clocks and counters (S0's names kept so the `end` record reads the same)
1010 uint64_t wall0 = 0;
1011 long words = 0, boundaries = 0, holds = 0, n_emits = 0, ticks = 0, n_molts = 0, n_deltas = 0,
1012 n_supp = 0, coarse_boundaries = 0, echo_skipped = 0, n_self_ref = 0, n_unsaid = 0,
1013 n_briefs = 0, n_counsel = 0, n_discard = 0, n_deferred = 0, n_forming = 0,
1014 conditions_opened = 0, conditions_resolved = 0, conditions_expired = 0, conditions_rearmed = 0;
1015 uint64_t molt_outage_total = 0, lat_sum = 0, lat_max = 0, last_ckpt_ms = 0, last_vram_ms = 0;
1016 double cl_surp_sum = 0, cl_surp_max = 0; int cl_surp_n = 0;
1017 double all_surp_sum = 0; long all_surp_n = 0;
1018 uint64_t cl_ingest_ms = 0; // decode+frontier time spent on the clause's words (rides the b record)
1020 // the clause under judgment
1021 std::string clause; int clause_toks = 0;
1022 uint64_t last_flush_ms = 0, last_delta_ms = 0;
1023 std::string cur_lane;
1024 uint64_t cur_delta_arrival = 0, cur_delta_t_mono = 0;
1025 size_t backlog_now = 0;
1026 bool line_open = false; // a world line's prefix is on the trunk, words still landing
1027 bool line_fresh = false; // the prefix was just (re)written: the next word takes no leading space
1029 // the verbatim tail (for the molt). Its cap and the rung's cap scale with the molt watermark so a
1030 // reseed can never land at or above the watermark (review correction 3): 600 at the default 24,576,
1031 // one fifth of the watermark below 3,000, never under 60 words / 64 tokens.
1032 std::deque<std::pair<std::string, int>> tailq; size_t tail_wc = 0;
1033 size_t tail_max_words = 600; int rung_max_toks = 600;
1034 std::string cur_tail_line;
1036 // own speech, placed after the line it illuminates
1037 std::deque<std::string> pending_commits;
1039 // the open line's words not yet on the trunk. Frames are the venue's atoms: these are the NEXT
1040 // percepts in order, and they land before any newer frame does (measured 2026-09-04: without
1041 // this queue the drain during a seat's speech pulled the next frame ahead of the rest of the
1042 // line it interrupted, and the trunk's order no longer matched the world's).
1043 std::deque<std::string> line_words;
1044 uint64_t frames_completed = 0;
1046 // the blind window, now with a window: generation depth and the judgments it defers, IN ORDER
1047 int gen_depth = 0;
1048 struct Deferred { std::string clause, lane; float score; uint64_t arrival; double surp_sum, surp_max; int surp_n, toks; uint64_t ingest_ms; llama_pos npast_at; bool replay; };
1049 std::deque<Deferred> deferred;
1050 bool molt_pending = false;
1052 // the manners layer (condition grain)
1053 std::string last_say[3]; long last_say_i[3]; uint64_t last_say_ms[3];
1054 bool resolved[3]; bool cond_open[3];
1055 static constexpr uint64_t SUPP_TTL_MS = 600000; // 10 min
1056 // P1: the last un-said line per seat (what it would have said), for the cross-seat manners (P7)
1057 std::string last_unsaid[3]; uint64_t last_unsaid_ms[3]; bool last_unsaid_settled[3];
1058 // D1: own lines this process put on the air, with their time — a seat-lane frame that near-dups
1059 // one inside the echo window is an echo coming back around a bridge, not a second percept
1060 std::deque<std::pair<std::string, uint64_t>> own_lines;
1061 long n_heard = 0;
1063 // gear 2
1064 struct BriefOut { uint64_t id; llama_pos npast_at; uint64_t t_ms; int seat; };
1065 std::unordered_map<uint64_t, BriefOut> briefs_out; uint64_t next_brief_id = 1;
1067 // the forming plane: per-lane forming text, never on the trunk (reflex partials never persist)
1068 std::unordered_map<std::string, std::string> forming;
1070 Kernel() {
1071 for (int m = 0; m < 3; ++m) {
1072 last_say_i[m] = -999; last_say_ms[m] = 0; resolved[m] = false; cond_open[m] = false; last_brief_ms[m] = 0;
1073 last_unsaid_ms[m] = 0; last_unsaid_settled[m] = false;
1077 // ---- segment 2 methods
1078 int boot();
1079 void read_vram(bool log);
1080 float read_frontier();
1081 void tail_push_line(const std::string& line);
1082 bool trunk_decode(const std::vector<llama_token>& t);
1083 bool trunk_text(const std::string& s, bool special);
1084 void ingest_word(const std::string& w);
1085 void flush_pending_commits();
1086 void do_molt();
1087 bool checkpoint(const char* why);
1088 bool restore();
1089 double rel_ms() const { return (double)(wall_ms() - wall0); }
1090 void fatal(const char* what);
1091 void warn(const char* what, const std::string& fields); // a row a reader must see; the resident goes on
1092 void report_rename_failures(); // F3: the counted rename failures, on the tape
1093 uint64_t last_rename_warn_ms = 0, rename_failures_seen = 0;
1095 // ---- segment 3 methods
1096 int seat_of_lane(const std::string& lane) const; // 0..2 seat, 3 = self/fusor, -1 = world
1097 bool is_wake_lane(const std::string& lane) const;
1098 bool looks_like_acceptance(const std::string& s) const;
1099 int content_overlap(const std::string& a, const std::string& b) const;
1100 bool near_dup(const std::string& a, const std::string& b) const;
1101 void write_verdict(const std::string& lane, int m, const char* action, float margin,
1102 const std::string& text, const char* cause);
1103 void write_brief(const std::string& lane, const std::string& clause_text, int m, float margin);
1104 void settle_deferred();
1105 void defer_judgment(float score);
1106 void feed_word();
1107 bool counsel_admit(Delta& d);
1108 bool speak(int m, float margin, std::string& say, std::string& aired, std::string& killed, std::string& cause,
1109 uint64_t& gen_ms);
1110 void tick_before(uint64_t arrive_ms); // silence before a frame becomes world (lazy tick)
1111 bool is_own_echo(const std::string& text); // D1: a seat-lane frame that is this process's own line
1112 void heard_line(const Delta& d); // D1: a seat-lane / self frame, heard and never judged
1113 float probe_one(int m);
1114 void judge_and_maybe_emit(const char* reason, float bscore, llama_pos at = -1);
1115 int deferred_covers = 1; // how many deferred boundaries the current judgment stands for
1116 uint64_t last_brief_ms[3]; // gear-2 rate limit, per seat
1117 long briefs_skipped = 0;
1118 void begin_line(const Delta& d);
1119 void end_line();
1120 void ingest_delta(Delta& d);
1121 void drain_intake();
1122 void run();
1123 void shutdown(const char* stopped);
1126// -----------------------------------------------------------------------------------------------------
1127void Kernel::fatal(const char* what) {
1128 std::printf("\nFATAL [%s] — stopping so the tape is whole.\n", what);
1129 tape.put(std::string("{\"k\":\"fatal\",\"ms\":") + std::to_string((long long)rel_ms()) +
1130 ",\"what\":\"" + jesc(what) + "\"");
1131 g_run.store(false, std::memory_order_release);
1133// A `warn` row: something a reader must know that did not stop the resident (F3, F6).
1134void Kernel::warn(const char* what, const std::string& fields) {
1135 std::string b = std::string("{\"k\":\"warn\",\"ms\":") + std::to_string((long long)rel_ms()) + ",\"what\":" + jq(what);
1136 if (!fields.empty()) b += "," + fields;
1137 tape.put(b);
1138 std::printf(" [warn] %s %s\n", what, fields.c_str());
1140// F3: a rename that failed after its retries is reported here, on the GPU thread, at most once a
1141// minute, naming the path and the OS error. The running count rides the pill and the end row.
1142void Kernel::report_rename_failures() {
1143 if (g_rename_failures.load(std::memory_order_relaxed) == rename_failures_seen) return;
1144 const uint64_t now = wall_ms();
1145 if (last_rename_warn_ms && now - last_rename_warn_ms < 60000) return;
1146 std::string path; unsigned long err = 0;
1147 const uint64_t n = rename_failures_snapshot(path, err);
1148 last_rename_warn_ms = now;
1149 warn("rename_failed", "\"path\":" + jq(path) + ",\"os_error\":" + std::to_string(err) + ",\"count\":" + u64s(n) +
1150 ",\"since_last_warn\":" + u64s(n - rename_failures_seen));
1151 rename_failures_seen = n;
1154// VRAM is the latency dial (measured 2026-08-23/09-01: 44 ms free vs 0.6–24.6 s loaded; 104 ms at
1155// 15 GiB free vs 500 ms at 10.5 GiB). A slow probe with no VRAM number beside it reads as a dumb
1156// resident. So the number rides the tape at boot and every minute.
1157void Kernel::read_vram(bool log) {
1158 size_t free_b = 0, total_b = 0; bool found = false; std::string name = "none";
1159 const size_t nd = ggml_backend_dev_count();
1160 for (size_t i = 0; i < nd; ++i) {
1161 ggml_backend_dev_t dev = ggml_backend_dev_get(i);
1162 if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU) continue;
1163 ggml_backend_dev_memory(dev, &free_b, &total_b);
1164 name = ggml_backend_dev_name(dev) ? ggml_backend_dev_name(dev) : "gpu";
1165 found = true; break;
1167 const uint64_t mib_free = found ? (uint64_t)(free_b >> 20) : 0, mib_total = found ? (uint64_t)(total_b >> 20) : 0;
1168 vitals.mib_free.store(mib_free); vitals.mib_total.store(mib_total);
1169 last_vram_ms = wall_ms();
1170 if (log) {
1171 char b[256];
1172 std::snprintf(b, sizeof(b), "{\"k\":\"vram\",\"ms\":%.0f,\"dev\":\"%s\",\"mib_free\":%llu,\"mib_total\":%llu",
1173 rel_ms(), jesc(name).c_str(), (unsigned long long)mib_free, (unsigned long long)mib_total);
1174 tape.put(b);
1178// The isomorphic segmenter, read off the ingest logits: P(next token closes a thought). Also
1179// refreshes logZ so the nerve's next surprisal has a valid denominator. Verbatim behavior.
1180float Kernel::read_frontier() {
1181 const float* l = llama_get_logits_ith(ctx, -1);
1182 float mx = -1e30f;
1183 for (int t = 0; t < n_vocab; ++t) if (l[t] > mx) mx = l[t];
1184 double tot = 0, bnd = 0;
1185 for (int t = 0; t < n_vocab; ++t) {
1186 const double x = std::exp((double)(l[t] - mx));
1187 tot += x; if (is_bnd[(size_t)t]) bnd += x;
1189 logZ = (double)mx + std::log(tot); have_logZ = true;
1190 frontier_logits.assign(l, l + n_vocab); // keep the trunk's own distribution for the nerve
1191 return (float)(bnd / tot);
1194void Kernel::tail_push_line(const std::string& line) {
1195 int wc = 1; for (char c : line) if (c == ' ') ++wc;
1196 tailq.emplace_back(line, wc); tail_wc += (size_t)wc;
1197 while (tail_wc > tail_max_words && tailq.size() > 1) {
1198 tail_wc -= (size_t)tailq.front().second; tailq.pop_front();
1202// Every token that lands on seq 0 goes through here, so the checkpoint's token list is exact.
1203bool Kernel::trunk_decode(const std::vector<llama_token>& t) {
1204 if (t.empty()) return true;
1205 if (!dec(ctx, t, TRUNK, npast, true)) { fatal("decode"); return false; }
1206 npast += (llama_pos)t.size();
1207 trunk_toks.insert(trunk_toks.end(), t.begin(), t.end());
1208 vitals.npast.store((uint64_t)npast);
1209 return true;
1211bool Kernel::trunk_text(const std::string& s, bool special) {
1212 auto t = tk(vocab, s, special);
1213 if (!trunk_decode(t)) return false;
1214 read_frontier();
1215 return true;
1218// Own speech commits AFTER the world's current line closes (placement law), on the seat's own lane,
1219// exactly as S0 formatted it — but never spliced into the middle of someone else's line.
1220void Kernel::flush_pending_commits() {
1221 while (!pending_commits.empty() && g_run.load(std::memory_order_acquire)) {
1222 const std::string c = pending_commits.front(); pending_commits.pop_front();
1223 if (!cfg.pure) {
1224 if (!trunk_text(c, false)) return;
1225 tail_push_line(c.size() > 1 ? c.substr(1) : c); // drop the leading '\n'
1230// ---- ingest one word onto the trunk, with the nerve tapped and the segmenter read (S0's law) ----
1231void Kernel::ingest_word(const std::string& w) {
1232 auto wt = tk(vocab, w, false);
1233 if (wt.empty()) return;
1234 const uint64_t t_ing0 = wall_ms();
1235 double surp = -1;
1236 if (have_logZ && frontier_logits.size() == (size_t)n_vocab) {
1237 // the nerve: −log P(actual | context), off the trunk's PREVIOUS frontier — the saved copy,
1238 // never the context's last logits (which may be a probe's). LOGGED. GATES NOTHING.
1239 surp = logZ - (double)frontier_logits[(size_t)wt[0]];
1241 if (!trunk_decode(wt)) return;
1242 ++words; clause_toks += (int)wt.size();
1243 const float bscore = read_frontier();
1244 cl_ingest_ms += wall_ms() - t_ing0;
1245 if (surp >= 0) {
1246 cl_surp_sum += surp; if (surp > cl_surp_max) cl_surp_max = surp;
1247 ++cl_surp_n; all_surp_sum += surp; ++all_surp_n;
1249 // The flush law: boundary OR 24 tok OR 1500 ms — first wins. Under backlog, judgment COARSENS
1250 // to the token cap (counted, reason "c"); ingest stays unconditional. Inside a generation the
1251 // judgment is DEFERRED (reason "d") — percepts are never dropped, judgment may be delayed.
1252 const bool backlog = backlog_now > 8 || (tail && tail->unread_bytes() > 4096);
1253 const char* why = nullptr;
1254 if (backlog) { if (clause_toks >= 24) why = "c"; }
1255 else if (bscore >= 0.5f) why = "b";
1256 else if (clause_toks >= 24) why = "n";
1257 else if ((long)(wall_ms() - last_flush_ms) >= 1500 && clause_toks >= 6) why = "t";
1258 if (why) {
1259 if (gen_depth > 0) defer_judgment(bscore);
1260 else judge_and_maybe_emit(why, bscore);
1262 if (cfg.molt_wm > 0 && npast >= cfg.molt_wm) {
1263 if (gen_depth > 0) { molt_pending = true; return; }
1264 if (!clause.empty()) judge_and_maybe_emit("m", bscore);
1265 do_molt();
1267 if (gen_depth == 0) settle_deferred(); // pay any judgment deferred while a seat was speaking
1270// ---- the molt (S0's proven mechanics; the outage is a perceivable drop-event) ----------------------
1271void Kernel::do_molt() {
1272 molt_pending = false;
1273 flush_pending_commits(); // what the seats said belongs in the tail the rung is written from
1274 const uint64_t m0 = wall_ms();
1275 const llama_pos before = npast;
1276 llama_memory_seq_rm(mem, SCRIBE, -1, -1);
1277 llama_memory_seq_cp(mem, TRUNK, SCRIBE, -1, -1);
1278 const std::string cue =
1279 "\n<|im_end|>\n<|im_start|>user\n[The stream has been going a long while and "
1280 "the log is huge. As the room's keeper, write your running memory now: every "
1281 "decision, hard constraint, owner, deadline, established fact, and open thread "
1282 "that still matters for the work ahead. Drop the chatter. End with one line "
1283 "noting what you dropped.]\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n"
1284 "</think>\n\n";
1285 auto ct = tk(vocab, cue, false);
1286 // F4: every decode is checked. A scribe that cannot decode aborts the molt with the trunk intact.
1287 if (!dec(ctx, ct, SCRIBE, npast, true)) { llama_memory_seq_rm(mem, SCRIBE, -1, -1); fatal("molt_scribe_cue_decode"); return; }
1288 llama_pos spos = npast + (llama_pos)ct.size();
1289 std::string rung; int rtoks = 0;
1290 for (int t = 0; t < rung_max_toks; ++t) {
1291 const llama_token tok = llama_sampler_sample(smp_scribe, ctx, -1);
1292 if (llama_vocab_is_eog(vocab, tok)) break;
1293 char pc[256]; const int pn = llama_token_to_piece(vocab, tok, pc, sizeof(pc), 0, true);
1294 if (pn > 0) rung.append(pc, (size_t)pn);
1295 std::vector<llama_token> one{tok};
1296 if (!dec(ctx, one, SCRIBE, spos, true)) { llama_memory_seq_rm(mem, SCRIBE, -1, -1); fatal("molt_scribe_decode"); return; }
1297 ++spos; ++rtoks;
1299 llama_memory_seq_rm(mem, SCRIBE, -1, -1);
1300 std::string tail_text;
1301 for (auto& p : tailq) tail_text += p.first + "\n";
1302 if (!cur_tail_line.empty()) tail_text += cur_tail_line + "\n";
1303 const std::string reseed = std::string(SEED_SYS) + SEED_EXAMPLES + SEED_OPEN +
1304 "[memory] " + rung + "\n[recent, verbatim]\n" + tail_text;
1305 auto rt = tk(vocab, reseed, true);
1306 // A reseed that would land at or above the watermark would molt again on the next word, forever
1307 // (review correction 3). That is a fatal with the trunk still whole, never a loop.
1308 if (cfg.molt_wm > 0 && (long)rt.size() + 16 >= cfg.molt_wm) {
1309 warn("molt_reseed_too_large", "\"reseed_toks\":" + std::to_string(rt.size()) + ",\"molt_wm\":" + std::to_string(cfg.molt_wm));
1310 fatal("molt_reseed_too_large"); return;
1312 llama_memory_seq_rm(mem, TRUNK, -1, -1);
1313 trunk_toks.clear(); npast = 0;
1314 if (!dec(ctx, rt, TRUNK, 0, true)) { fatal("molt_reseed_decode"); return; } // F4: the last checkpoint stands
1315 npast = (llama_pos)rt.size(); trunk_toks = rt; vitals.npast.store((uint64_t)npast);
1316 read_frontier();
1317 const uint64_t dur = wall_ms() - m0;
1318 { char tb[96]; std::snprintf(tb, sizeof(tb),
1319 "\n[tick +%llus — I paused the watch to consolidate my memory]",
1320 (unsigned long long)(dur / 1000 + 1));
1321 trunk_text(tb, false); }
1322 // A molt inside an open world line: re-establish the lane prefix so the words still landing
1323 // attach to a properly laned line (S0 left them prefix-less after a mid-line molt).
1324 if (line_open && !cur_lane.empty()) trunk_text(std::string("\n[") + cur_lane + "] ", false);
1325 ++n_molts; molt_outage_total += dur; vitals.molts.store((uint64_t)n_molts);
1326 std::printf("\n [molt %ld] trunk %d -> %d tok (rung %d tok, %llums outage — a drop-event)\n",
1327 n_molts, (int)before, (int)npast, rtoks, (unsigned long long)dur);
1328 char b[512];
1329 std::snprintf(b, sizeof(b), "{\"k\":\"molt\",\"ms\":%.0f,\"before\":%d,\"rung_toks\":%d,\"after\":%d,\"dur_ms\":%llu,\"rung\":\"",
1330 rel_ms(), (int)before, rtoks, (int)npast, (unsigned long long)dur);
1331 tape.put(std::string(b) + jesc(rung) + "\"");
1332 if (!cfg.ckpt.empty()) { if (line_open) ckpt_due = true; else checkpoint("molt"); } // mid-line: at the next quiet gate
1335// ---- the trunk is an asset: checkpoint and restore (P3) ---------------------------------------------
1336// The checkpoint is written to <ckpt>.tmp and renamed into place with write-through; the previous
1337// file is kept one generation back as <ckpt>.prev; the .meta sidecar is written LAST, so it never
1338// …
1339bool Kernel::checkpoint(const char* why) {
1340 if (cfg.ckpt.empty()) return false;
1341 const uint64_t c0 = wall_ms();
1342 const std::string tmp = cfg.ckpt + ".tmp", prevp = cfg.ckpt + ".prev";
1343 std::remove(tmp.c_str());
1344 const size_t bytes = llama_state_seq_save_file(ctx, tmp.c_str(), TRUNK, trunk_toks.data(), trunk_toks.size());
1345 bool ok = bytes > 0;
1346 if (ok) {
1347 uint64_t old_sz = 0;
1348 if (file_size_of(cfg.ckpt, old_sz)) replace_file(cfg.ckpt, prevp, false); // one generation back; a failure is counted, not fatal
1349 ok = replace_file(tmp, cfg.ckpt, true); // the old file or the new one; never a torn one
1351 const uint64_t cursor = tail ? tail->ingested_off.load() : 0;
1352 if (ok) {
1353 std::string meta;
1354 meta += "model\t" + cfg.model + "\n";
1355 meta += "model_sha256\t" + model_sha + "\n";
1356 meta += "serve\t" + hex16(serve_hash()) + "\n";
1357 meta += "npast\t" + std::to_string((long long)npast) + "\n";
1358 meta += "prev\t" + tape.prev + "\n";
1359 meta += "t\t" + u64s(wall_ms()) + "\n";
1360 meta += "t_wall\t" + u64s(epoch_ms()) + "\n";
1361 meta += "t_last_frame_wall\t" + u64s(last_frame_wall_ms) + "\n";
1362 meta += "spool\t" + cfg.spool + "\n";
1363 meta += "cursor\t" + u64s(cursor) + "\t" + hex16(tail ? tail->prefix_hash(cursor) : 0) + "\n";
1364 for (auto& p : tailq) meta += "tail\t" + p.first + "\n";
1365 ok = write_atomic(cfg.ckpt + ".meta", meta);
1367 last_ckpt_ms = wall_ms(); ckpt_due = false;
1368 tape.put("{\"k\":\"ckpt\",\"ms\":" + fmt0(rel_ms()) + ",\"why\":" + jq(why) + ",\"toks\":" + std::to_string((int)npast) +
1369 ",\"bytes\":" + u64s(bytes) + ",\"cursor\":" + u64s(cursor) + ",\"ok\":" + (ok ? "true" : "false") +
1370 ",\"dur_ms\":" + u64s(wall_ms() - c0));
1371 return ok;
1373struct CkptMeta {
1374 std::string model, model_sha, serve, spool; long long npast = -1;
1375 uint64_t cursor = 0, cursor_hash = 0, t_last_frame_wall = 0; bool have_cursor = false;
1376 std::vector<std::string> tails;
1378static bool parse_meta(const std::string& text, CkptMeta& m) {
1379 if (text.empty()) return false;
1380 size_t p = 0;
1381 while (p < text.size()) {
1382 size_t q = text.find('\n', p); if (q == std::string::npos) q = text.size();
1383 const std::string ln = text.substr(p, q - p); p = q + 1;
1384 if (starts_with(ln, "model\t")) m.model = ln.substr(6);
1385 else if (starts_with(ln, "model_sha256\t")) m.model_sha = ln.substr(13);
1386 else if (starts_with(ln, "serve\t")) m.serve = ln.substr(6);
1387 else if (starts_with(ln, "npast\t")) m.npast = std::atoll(ln.c_str() + 6);
1388 else if (starts_with(ln, "spool\t")) m.spool = ln.substr(6);
1389 else if (starts_with(ln, "t_last_frame_wall\t")) m.t_last_frame_wall = std::strtoull(ln.c_str() + 18, nullptr, 10);
1390 else if (starts_with(ln, "cursor\t")) {
1391 m.cursor = std::strtoull(ln.c_str() + 7, nullptr, 10);
1392 const char* tab = std::strchr(ln.c_str() + 7, '\t');
1393 m.cursor_hash = tab ? std::strtoull(tab + 1, nullptr, 16) : 0; m.have_cursor = true;
1395 else if (starts_with(ln, "tail\t")) m.tails.push_back(ln.substr(5));
1397 return true;
1399// Restore requires the .meta, the model, the serve hash and the loaded token count to agree; when the
1400// current file disagrees with its .meta (a crash between the rename and the .meta write) the previous
1401// generation is tried with the same .meta; failing both, the resident is the twin and says so.
1402bool Kernel::restore() {
1403 CkptMeta m;
1404 if (!parse_meta(read_all(cfg.ckpt + ".meta", 1 << 20), m)) {
1405 std::printf("[resume] no .meta beside the checkpoint — starting cold (the twin).\n"); return false;
1407 if (m.model != cfg.model || m.serve != hex16(serve_hash())) {
1408 std::printf("[resume] checkpoint belongs to another model or serve format — starting cold (the twin).\n"); return false;
1410 if (!m.model_sha.empty() && !model_sha.empty() && m.model_sha != model_sha) { // same path, different bytes
1411 std::printf("[resume] the weights changed under the checkpoint (sha256 %s… vs %s…) — starting cold (the twin).\n",
1412 m.model_sha.substr(0, 12).c_str(), model_sha.substr(0, 12).c_str()); return false;
1414 auto try_load = [&](const std::string& path) -> bool {
1415 uint64_t sz = 0; if (!file_size_of(path, sz) || sz == 0) return false;
1416 llama_memory_seq_rm(mem, TRUNK, -1, -1); // the load wants an empty destination
1417 std::vector<llama_token> buf((size_t)llama_n_ctx(ctx)); size_t n = 0;
1418 const size_t got = llama_state_seq_load_file(ctx, path.c_str(), TRUNK, buf.data(), buf.size(), &n);
1419 if (got == 0 || n == 0) { llama_memory_seq_rm(mem, TRUNK, -1, -1); return false; }
1420 if ((long long)n != m.npast) { // the .meta describes another generation
1421 std::printf("[resume] %s holds %zu tokens, .meta says %lld — not the same generation.\n", path.c_str(), n, m.npast);
1422 llama_memory_seq_rm(mem, TRUNK, -1, -1); return false;
1424 buf.resize(n); trunk_toks = buf; npast = (llama_pos)n; vitals.npast.store((uint64_t)npast);
1425 return true;
1426 };
1427 if (try_load(cfg.ckpt)) boot_kind = "restored";
1428 else if (try_load(cfg.ckpt + ".prev")) boot_kind = "restored_prev";
1429 else { std::printf("[resume] neither checkpoint generation matches its .meta — starting cold (the twin).\n"); return false; }
1430 have_logZ = false; // no frontier until the next decode
1431 for (auto& t : m.tails) tail_push_line(t); // the verbatim tail comes back with the trunk
1432 meta_cursor = m.cursor; meta_cursor_hash = m.cursor_hash;
1433 meta_cursor_ok = m.have_cursor && (m.spool.empty() || m.spool == cfg.spool);
1434 meta_t_last_frame_wall = m.t_last_frame_wall;
1435 return true;
1438// ---- boot: assert, load, seed-or-resume, open the organs -----------------------------------------------
1439int Kernel::boot() {
1440 // train ≡ serve: assert BEFORE anything else. A drifted serve byte must not even load.
1442 const uint64_t h = serve_hash();
1443 if constexpr (SERVE_HASH_PIN == 0ull) {
1444 std::printf("[train==serve] UNPINNED. Computed serve-bytes hash = 0x%016llx\n"
1445 " Pin this value as SERVE_HASH_PIN (same commit as the tune it matches) and rebuild.\n",
1446 (unsigned long long)h);
1447 return 2;
1449 if (h != SERVE_HASH_PIN) {
1450 std::printf("FATAL [train!=serve]: serve bytes hash 0x%016llx != pinned 0x%016llx.\n"
1451 " A serve-side literal drifted from the v11 tune. Restore the bytes or re-pin DELIBERATELY (with a retune).\n",
1452 (unsigned long long)h, (unsigned long long)SERVE_HASH_PIN);
1453 return 2;
1456 wall0 = wall_ms(); // one epoch for every record on this run's tape, load time included
1457 if (cfg.molt_wm > 0 && cfg.molt_wm < 3000) { // the caps scale with a small watermark (review correction 3)
1458 tail_max_words = (size_t)std::max<long>(60, cfg.molt_wm / 5);
1459 rung_max_toks = (int)std::max<long>(64, cfg.molt_wm / 5);
1461 ensure_dir(cfg.out_dir);
1462 if (!tape.open(cfg.out_dir + "/fusor_ledger.jsonl")) { std::printf("cannot open the tape under %s\n", cfg.out_dir.c_str()); return 1; }
1463 if (tape.torn_bytes) warn("torn_row_skipped", "\"bytes\":" + u64s(tape.torn_bytes)); // F6: a crash inside a write, on the record
1464 verdicts.open(cfg.out_dir + "/verdicts.jsonl");
1465 briefs.open(cfg.out_dir + "/briefs.jsonl");
1466 pill.pill_path = cfg.out_dir + "/fusord.heartbeat.json";
1467 pill.switch_path = cfg.out_dir + "/fusord.state";
1468 pill.v = &vitals;
1469 vitals.sw.store((int)read_switch(pill.switch_path, Switch::Off));
1471 std::printf("\n===== FUSOR · fusord — THE RESIDENT KERNEL (K5 · converge) =====\n");
1472 std::printf("spool=%s · dial=0 · molt_wm=%ld · idle-tick=%lds · switch=%s · out=%s\n",
1473 cfg.spool.c_str(), cfg.molt_wm, cfg.idle_tick_s, switch_name((Switch)vitals.sw.load()), cfg.out_dir.c_str());
1475#if defined(_WIN32)
1476 SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
1477 { wchar_t w[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, AURICLE_LLAMA_DIR, -1, w, MAX_PATH); AddDllDirectory(w); }
1478#endif
1479 llama_log_set(err_log, nullptr); ggml_log_set(err_log, nullptr);
1480 backends_loaded = load_backends_by_name(AURICLE_LLAMA_DIR); // never load_all: ggml-rpc imports ws2_32
1481 llama_backend_init();
1482 { // the module gate: zero egress is a property of THIS process, checked, on the header
1483 std::string offending; size_t nmod = 0;
1484 const bool gate = module_gate(offending, nmod);
1485 n_modules = nmod; egress = gate ? "none" : "possible:" + offending;
1486 if (!gate && !cfg.egress_unchecked) {
1487 std::printf("FATAL [egress]: module %s is loaded in this process (%zu modules). The kernel does not run with a network-capable module present; --egress-unchecked records it instead.\n", offending.c_str(), nmod);
1488 tape.put("{\"k\":\"fatal\",\"ms\":" + fmt0(rel_ms()) + ",\"what\":\"egress_module\",\"module\":" + jq(offending) + ",\"modules\":" + u64s(nmod));
1489 return 2;
1492 { // the devices, on the header
1493 std::string dj; bool gpu = false;
1494 for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
1495 ggml_backend_dev_t d = ggml_backend_dev_get(i); size_t fb = 0, tb = 0; ggml_backend_dev_memory(d, &fb, &tb);
1496 const bool is_gpu = ggml_backend_dev_type(d) == GGML_BACKEND_DEVICE_TYPE_GPU; gpu = gpu || is_gpu;
1497 dj += (dj.empty() ? "" : ",") + std::string("{\"name\":") + jq(ggml_backend_dev_name(d) ? ggml_backend_dev_name(d) : "?") +
1498 ",\"type\":" + jq(is_gpu ? "gpu" : "cpu") + ",\"mib_free\":" + u64s(fb >> 20) + ",\"mib_total\":" + u64s(tb >> 20) + "}";
1500 devices_json = "[" + dj + "]";
1501 if (!gpu && !cfg.allow_cpu) {
1502 std::printf("FATAL [no_gpu]: no GPU device registered (the silent CPU fallback is a wrong record, 47x slower). --allow-cpu runs anyway, disclosed.\n");
1503 tape.put("{\"k\":\"fatal\",\"ms\":" + fmt0(rel_ms()) + ",\"what\":\"no_gpu\",\"devices\":" + devices_json);
1504 return 2;
1507 read_vram(true); // before the weights land: the room the resident is walking into
1508 model_sha = model_identity(cfg.model, cfg.model_sha256, cfg.sha_cache.empty() ? cfg.out_dir + "/model.sha256" : cfg.sha_cache, model_sha_source);
1510 llama_model_params mp = llama_model_default_params(); mp.n_gpu_layers = 999;
1511 mdl = llama_model_load_from_file(cfg.model.c_str(), mp);
1512 if (!mdl) { std::printf("model load FAILED\n"); return 1; }
1513 if ((g_gpu_layers_offloaded < 0 || g_gpu_layers_offloaded != g_gpu_layers_total) && !cfg.allow_cpu) {
1514 std::printf("FATAL [offload]: %d of %d layers offloaded to the GPU (a partial offload is a slow record, disclosed only under --allow-cpu).\n",
1515 g_gpu_layers_offloaded, g_gpu_layers_total);
1516 tape.put("{\"k\":\"fatal\",\"ms\":" + fmt0(rel_ms()) + ",\"what\":\"gpu_offload\",\"offloaded\":" + std::to_string(g_gpu_layers_offloaded) +
1517 ",\"total\":" + std::to_string(g_gpu_layers_total));
1518 return 2;
1520 vocab = llama_model_get_vocab(mdl);
1521 n_vocab = llama_vocab_n_tokens(vocab);
1522 hold_tok = tk(vocab, " hold", false)[0];
1523 emit_tok = tk(vocab, " emit", false)[0];
1525 // The segmenter's boundary set, TIGHTENED (measured 2026-08-12): . ! ? · newline · EOG.
1526 // Not ; : — syntax, not thought (3.3 boundaries/line on a code paste; fragments handed to the probe).
1527 is_bnd.assign((size_t)n_vocab, 0);
1528 for (int t = 0; t < n_vocab; ++t) {
1529 char pc[64]; const int pn = llama_token_to_piece(vocab, t, pc, sizeof(pc), 0, true);
1530 if (pn <= 0) { if (llama_vocab_is_eog(vocab, t)) is_bnd[(size_t)t] = 1; continue; }
1531 const std::string p(pc, (size_t)pn);
1532 char last = 0;
1533 for (char c : p) if (c != ' ') last = c;
1534 if (last == '.' || last == '!' || last == '?' ||
1535 p.find('\n') != std::string::npos || llama_vocab_is_eog(vocab, t))
1536 is_bnd[(size_t)t] = 1;
1539 llama_context_params cp = llama_context_default_params();
1540 cp.n_ctx = cfg.n_ctx > 0 ? (uint32_t)cfg.n_ctx : (cfg.kv_q8 ? 65536u : 32768u); // q8_0 KV: quality-neutral (08-11 W_eff receipt, 98k→163k)
1541 cp.n_batch = 512; cp.n_ubatch = 512; cp.n_seq_max = 8; cp.kv_unified = true;
1542 if (cfg.kv_q8) {
1543 cp.type_k = GGML_TYPE_Q8_0; cp.type_v = GGML_TYPE_Q8_0;
1544 cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED;
1546 ctx = llama_init_from_model(mdl, cp);
1547 if (!ctx) { std::printf("ctx FAILED\n"); return 1; }
1548 if (llama_n_ctx_seq(ctx) != llama_n_ctx(ctx)) {
1549 std::printf("FATAL: kv_unified did not hold (n_ctx_seq %u != n_ctx %u)\n", llama_n_ctx_seq(ctx), llama_n_ctx(ctx));
1550 return 1;
1552 mem = llama_get_memory(ctx);
1553 smp = llama_sampler_chain_init(llama_sampler_chain_default_params());
1554 llama_sampler_chain_add(smp, llama_sampler_init_min_p(0.05f, 1));
1555 llama_sampler_chain_add(smp, llama_sampler_init_temp(0.7f));
1556 llama_sampler_chain_add(smp, llama_sampler_init_dist(11));
1557 smp_scribe = llama_sampler_chain_init(llama_sampler_chain_default_params());
1558 llama_sampler_chain_add(smp_scribe, llama_sampler_init_min_p(0.05f, 1));
1559 llama_sampler_chain_add(smp_scribe, llama_sampler_init_temp(0.3f));
1560 llama_sampler_chain_add(smp_scribe, llama_sampler_init_dist(11));
1562 // seed — or resume the held state. A resident rebuilt from its seed is the twin; say so.
1563 int seed_toks = 0;
1564 if (!cfg.ckpt.empty() && cfg.resume && !cfg.cold && restore()) {
1565 resumed = true; seed_toks = (int)npast;
1566 std::printf("[resume] trunk %s: %d tokens held. The mind picks up where it stopped.\n", boot_kind.c_str(), (int)npast);
1567 } else {
1568 const std::string seed = std::string(SEED_SYS) + SEED_EXAMPLES + SEED_OPEN;
1569 auto stoks = tk(vocab, seed, true);
1570 if (!dec(ctx, stoks, TRUNK, 0, false)) { fatal("seed_decode"); return 1; } // F4
1571 npast = (llama_pos)stoks.size(); trunk_toks = stoks; vitals.npast.store((uint64_t)npast);
1572 seed_toks = (int)npast;
1573 twin = !cfg.ckpt.empty() && (cfg.cold || cfg.resume); // a checkpoint existed in intent; this is not it
1574 boot_kind = twin ? "twin" : "seed";
1576 read_vram(true); // after the weights land: what is left for the probes
1578 // the tail starts from the mark taken in main() BEFORE the model loaded, from the cursor, or — with a
1579 // restored trunk — from the checkpoint's own cursor (P3/F1), replaying what the previous life ingested
1580 // past the checkpoint rather than skipping it. The replay window is on the tape before any frame.
1581 tail_start_reason = tail->resolve_start(cfg.from_start ? TailFrom::Start : cfg.from_end ? TailFrom::End : TailFrom::Mark,
1582 !cfg.from_start && !cfg.from_end, resumed && meta_cursor_ok, meta_cursor, meta_cursor_hash);
1583 if (resumed && tail_start_reason == "checkpoint_cursor") {
1584 uint64_t foff = 0, fh = 0, n = 0; file_size_of(cfg.spool, n);
1585 if (tail->read_cursor_file(foff, fh) && foff > tail->offset.load() && foff <= n) {
1586 replay_until = foff;
1587 tape.put("{\"k\":\"replay\",\"ms\":" + fmt0(rel_ms()) + ",\"from\":" + u64s(tail->offset.load()) + ",\"to\":" + u64s(foff) +
1588 ",\"why\":\"the previous life ingested past its last checkpoint; the trunk must see those frames again\"");
1591 tail->start();
1592 pill.start();
1594 last_flush_ms = wall_ms(); last_delta_ms = last_flush_ms; last_ckpt_ms = last_flush_ms;
1595 // The header row, built from strings (F6): a long spool path or model path can no longer truncate it.
1596 std::string hb = std::string("{\"k\":\"hdr\",\"src\":") + jq(cfg.spool) + ",\"live\":true,\"dial\":0,\"mode\":" + jq(cfg.pure ? "pure" : "room") +
1597 ",\"molt_wm\":" + std::to_string(cfg.molt_wm) + ",\"model\":" + jq(cfg.model) + ",\"seed_toks\":" + std::to_string(seed_toks) +
1598 ",\"t0_wall\":" + u64s(wall_ms()) + ",\"kv\":" + jq(cfg.kv_q8 ? "q8_0" : "f16") + ",\"n_ctx\":" + std::to_string(llama_n_ctx(ctx)) +
1599 ",\"serve_hash\":\"0x" + hex16(serve_hash()) + "\"" +
1600 ",\"label_enum\":[\"useful\",\"wrong_content\",\"too_late\",\"wrong_to_speak\"]" +
1601 ",\"e_def\":\"e=surfaced only; events=e+e_suppressed+unsaid (additive, never conflated)\"" +
1602 ",\"self_ref_detector\":" + jq(SELF_REF_DESC) + ",\"kernel\":\"v-next-converge\",\"venue\":" + jq(tail->venue) +
1603 ",\"lane_contract\":" + (tail->v01 ? "true" : "false") + ",\"tail_start\":" + jq(tail_start_reason) +
1604 ",\"spool_offset\":" + u64s(tail->offset.load()) + ",\"mib_free\":" + u64s(vitals.mib_free.load()) + ",\"mib_total\":" + u64s(vitals.mib_total.load()) +
1605 ",\"state\":" + jq(switch_name((Switch)vitals.sw.load())) + ",\"resumed\":" + (resumed ? "true" : "false") + ",\"twin\":" + (twin ? "true" : "false") +
1606 ",\"boot\":" + jq(boot_kind) + ",\"replay_until\":" + u64s(replay_until) + ",\"ckpt\":" + jq(cfg.ckpt) + ",\"ckpt_every_s\":" + std::to_string(cfg.ckpt_every_s) +
1607 ",\"egress\":" + jq(egress) + ",\"modules\":" + u64s(n_modules) + ",\"backends\":" + jq(backends_loaded) + ",\"devices\":" + devices_json +
1608 ",\"gpu_layers\":" + jq(std::to_string(g_gpu_layers_offloaded) + "/" + std::to_string(g_gpu_layers_total)) +
1609 ",\"model_sha256\":" + jq(model_sha) + ",\"model_sha256_source\":" + jq(model_sha_source) +
1610 ",\"ask_band\":" + fmt2(cfg.ask_band) + ",\"stale_tok\":" + std::to_string(cfg.stale_tok) + ",\"refractory_s\":" + std::to_string(cfg.refractory_s) +
1611 ",\"killed_next\":" + (cfg.killed_full ? "false" : "true") + ",\"echo_window_s\":" + std::to_string(cfg.echo_window_s) +
1612 ",\"t_mono_ns\":" + u64s(mono_ns());
1613 tape.put(hb);
1614 return 0;
1617} // namespace fusor
1619// ---- end of segment 2 -------------------------------------------------------------------------------
1620// ---- segment 3 --------------------------------------------------------------------------------------
1622namespace fusor {
1624// Sample from a SAVED copy of a sequence's logits. Needed because intake now lands on the trunk
1625// between generated tokens, so the context's "last logits" may belong to the trunk (or to a probe)
1626// by the time the speaking seat wants its next token. The chain (min_p → temp → dist) is applied
1627// exactly as before; only the source of the logits changes.
1628static llama_token sample_from(llama_sampler* smp, const float* logits, int n_vocab,
1629 std::vector<llama_token_data>& cands) {
1630 cands.resize((size_t)n_vocab);
1631 for (int t = 0; t < n_vocab; ++t) { cands[(size_t)t].id = t; cands[(size_t)t].logit = logits[t]; cands[(size_t)t].p = 0.f; }
1632 llama_token_data_array arr = { cands.data(), cands.size(), -1, false };
1633 llama_sampler_apply(smp, &arr);
1634 const llama_token tok = arr.selected >= 0 ? arr.data[arr.selected].id : arr.data[0].id;
1635 llama_sampler_accept(smp, tok);
1636 return tok;
1639// =====================================================================================================
1640// §11 · THE MANNERS LAYER (deterministic, disclosed, S0's tests kept exactly)
1641// =====================================================================================================
1643int Kernel::seat_of_lane(const std::string& lane) const {
1644 for (int m = 0; m < 3; ++m) if (ieq(lane, MINDS[m].name)) return m;
1645 if (ieq(lane, "fusor") || ieq(lane, "self")) return 3;
1646 return -1;
1648bool Kernel::is_wake_lane(const std::string& lane) const {
1649 const std::string l = lower(lane);
1650 for (auto& p : cfg.wake_prefixes) if (!p.empty() && starts_with(l, lower(p).c_str())) return true;
1651 return false;
1653bool Kernel::looks_like_acceptance(const std::string& s) const {
1654 const std::string t = lower(s);
1655 static const char* A[] = {"you're right", "you are right", "good catch", "fair point",
1656 "correct", "my mistake", "agreed", "fixed"};
1657 for (auto a : A) if (t.find(a) != std::string::npos) return true;
1658 return false;
1660int Kernel::content_overlap(const std::string& a, const std::string& b) const {
1661 static const char* STOP[] = {"the","a","an","and","or","but","so","we","is","are","was","were",
1662 "it","its","it's","to","of","in","on","for","with","that","this",
1663 "let","let's","before","after","just","also","ok","okay","right",
1664 "i","you","he","she","they","me","us","them","my","our","your"};
1665 auto split = [](const std::string& s) {
1666 std::vector<std::string> v; std::string w;
1667 for (char c : s) {
1668 if (std::isalnum((unsigned char)c)) w += (char)std::tolower((unsigned char)c);
1669 else { if (w.size() > 1) v.push_back(w); w.clear(); }
1671 if (w.size() > 1) v.push_back(w);
1672 return v;
1673 };
1674 auto is_stop = [&](const std::string& w) { for (auto s : STOP) if (w == s) return true; return false; };
1675 auto A = split(a), B = split(b);
1676 int hit = 0;
1677 for (auto& w : A) {
1678 if (is_stop(w)) continue;
1679 for (auto& x : B) if (w == x) { ++hit; break; }
1681 return hit;
1683bool Kernel::near_dup(const std::string& a, const std::string& b) const {
1684 if (a.empty() || b.empty()) return false;
1685 auto split = [](const std::string& s) {
1686 std::vector<std::string> v; size_t p = 0;
1687 while (p < s.size()) { size_t q = s.find(' ', p); if (q == std::string::npos) q = s.size();
1688 if (q > p) v.push_back(lower(s.substr(p, q - p))); p = q + 1; }
1689 return v; };
1690 auto A = split(a), B = split(b);
1691 if (A.empty() || B.empty()) return false;
1692 size_t hit = 0;
1693 for (auto& w : A) for (auto& x : B) if (w == x) { ++hit; break; }
1694 return (double)hit / (double)A.size() >= 0.6; // 60% of the words already said
1697// =====================================================================================================
1698// §12 · THE WIRE, THE BRIEFS, THE COUNSEL GATE
1699// =====================================================================================================
1701// ADDENDUM-F §3.3: one row per seat per boundary. `hold` rows are the record of silence with their
1702// margin. `off` writes no wire: the kernel is inert to the world; the TAPE still has every margin.
1703void Kernel::write_verdict(const std::string& lane, int m, const char* action, float margin,
1704 const std::string& text, const char* cause) {
1705 const Switch sw = (Switch)vitals.sw.load();
1706 if (sw == Switch::Off) return;
1707 char b[512];
1708 std::snprintf(b, sizeof(b),
1709 "{\"t_mono_ns\":%llu,\"lane\":\"%s\",\"seat\":\"%s\",\"action\":\"%s\",\"margin\":%.3f,"
1710 "\"i\":%ld,\"ms\":%.0f,\"steer\":\"unsteered\",\"provenance\":\"local\",\"state\":\"%s\",",
1711 (unsigned long long)mono_ns(), jesc(lane).c_str(), MINDS[m].name, action, margin,
1712 boundaries, rel_ms(), switch_name(sw));
1713 std::string row = b;
1714 row += text.empty() ? "\"text\":null" : "\"text\":\"" + jesc(text) + "\"";
1715 row += cause ? std::string(",\"cause\":\"") + jesc(cause) + "\"" : ",\"cause\":null";
1716 row += "}";
1717 verdicts.put(row);
1720// Gear 2, at the seam: a thin margin writes a BRIEF — the clause, the held tail, one question.
1721// Whoever reads briefs.jsonl (a larger local model between beats, the operator's API passthrough,
1722// a harness session) answers on the spool as lane `counsel` with "#<id> " in front. The kernel
1723// never opens a socket. Remote proposes; local disposes (counsel_admit).
1724void Kernel::write_brief(const std::string& lane, const std::string& clause_text, int m, float margin) {
1725 if ((Switch)vitals.sw.load() == Switch::Off) return;
1726 // one brief per seat per 30 s: gear 2 is asked about an instant, not paged about a stretch
1727 if (last_brief_ms[m] && wall_ms() - last_brief_ms[m] < 30000) { ++briefs_skipped; return; }
1728 last_brief_ms[m] = wall_ms();
1729 const uint64_t id = next_brief_id++;
1730 briefs_out[id] = BriefOut{id, npast, wall_ms(), m};
1731 std::string held;
1732 { // the last ≤12 lines of the verbatim tail — what the resident is holding as it asks
1733 size_t k = tailq.size() > 12 ? tailq.size() - 12 : 0; bool first = true;
1734 for (size_t i = k; i < tailq.size(); ++i) { held += (first ? "" : ","); held += "\"" + jesc(tailq[i].first) + "\""; first = false; }
1736 char b[512];
1737 std::snprintf(b, sizeof(b),
1738 "{\"id\":%llu,\"t_mono_ns\":%llu,\"npast\":%d,\"seat\":\"%s\",\"margin\":%.3f,\"lane\":\"%s\",\"state\":\"%s\",",
1739 (unsigned long long)id, (unsigned long long)mono_ns(), (int)npast, MINDS[m].name, margin,
1740 jesc(lane).c_str(), switch_name((Switch)vitals.sw.load()));
1741 std::string row = b;
1742 row += "\"clause\":\"" + jesc(clause_text) + "\",\"held\":[" + held + "],";
1743 row += std::string("\"question\":\"The ") + MINDS[m].name + " cannot rank this instant (margin " +
1744 std::to_string((double)margin).substr(0, 6) + "). Its mandate: " + MINDS[m].mandate +
1745 ". In one sentence: is this worth a word now, and what is the word? Reply HOLD if not.\"}";
1746 briefs.put(row);
1747 ++n_briefs; vitals.briefs.store((uint64_t)n_briefs);
1748 char t[256];
1749 std::snprintf(t, sizeof(t), "{\"k\":\"brief\",\"id\":%llu,\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.3f,\"npast\":%d",
1750 (unsigned long long)id, boundaries, rel_ms(), MINDS[m].name, margin, (int)npast);
1751 tape.put(t);
1754// THE STALENESS GATE. Counsel that arrives after the world has moved past the envelope is answering
1755// about a world that no longer exists: DISCARD it, and the discard is a typed negative on the tape.
1756// Untagged counsel (no "#<id>") is an ordinary lane line: a percept with a source, no envelope known.
1757bool Kernel::counsel_admit(Delta& d) {
1758 if (d.text.size() < 2 || d.text[0] != '#') return true;
1759 char* endp = nullptr;
1760 const unsigned long long id = std::strtoull(d.text.c_str() + 1, &endp, 10);
1761 if (!endp || endp == d.text.c_str() + 1) return true;
1762 auto it = briefs_out.find((uint64_t)id);
1763 if (it == briefs_out.end()) return true; // unknown id: admitted as ordinary testimony
1764 const long drift = (long)(npast - it->second.npast_at);
1765 const uint64_t age = wall_ms() - it->second.t_ms;
1766 std::string body = d.text.substr((size_t)(endp - d.text.c_str()));
1767 while (!body.empty() && body[0] == ' ') body.erase(0, 1);
1768 char b[512];
1769 if (drift > cfg.stale_tok) {
1770 ++n_discard; vitals.counsel_discarded.store((uint64_t)n_discard);
1771 std::snprintf(b, sizeof(b), "{\"k\":\"discard\",\"id\":%llu,\"ms\":%.0f,\"drift_tok\":%ld,\"age_ms\":%llu,\"mind\":\"%s\",\"text\":\"",
1772 id, rel_ms(), drift, (unsigned long long)age, MINDS[it->second.seat].name);
1773 tape.put(std::string(b) + jesc(body) + "\"");
1774 briefs_out.erase(it);
1775 return false;
1777 ++n_counsel; vitals.counsel_in.store((uint64_t)n_counsel);
1778 std::snprintf(b, sizeof(b), "{\"k\":\"counsel\",\"id\":%llu,\"ms\":%.0f,\"drift_tok\":%ld,\"age_ms\":%llu,\"mind\":\"%s\"",
1779 id, rel_ms(), drift, (unsigned long long)age, MINDS[it->second.seat].name);
1780 tape.put(b);
1781 briefs_out.erase(it);
1782 d.text = body; // enters the trunk as "[counsel] …" — testimony with a source, never belief
1783 return true;
1786// THE PROBE (verbatim frame, dial 0), on a fork of the trunk as it stands NOW.
1788// A judgment cannot be made "as of" an earlier instant on this trunk. The 9B is a 3:1 recurrent
1789// …
1790float Kernel::probe_one(int m) {
1791 llama_memory_seq_rm(mem, DECIDE, -1, -1);
1792 llama_memory_seq_cp(mem, TRUNK, DECIDE, -1, -1);
1793 auto pr = tk(vocab, std::string(PROBE_A) + MINDS[m].name + PROBE_B + MINDS[m].mandate + PROBE_C, false);
1794 if (!dec(ctx, pr, DECIDE, npast, true)) { fatal("probe_decode"); llama_memory_seq_rm(mem, DECIDE, -1, -1); return 0.0f; }
1795 const float* l = llama_get_logits_ith(ctx, -1);
1796 const float margin = l[emit_tok] - l[hold_tok];
1797 llama_memory_seq_rm(mem, DECIDE, -1, -1);
1798 return margin;
1801// =====================================================================================================
1802// §13 · SPEAKING — one sentence, hard cap, and THE UN-SAY INSIDE THE BLIND WINDOW
1803// =====================================================================================================
1805// Returns true if the line was said in full; false if it was killed mid-word by the world.
1806// `aired` = the prefix that reached the surface before the kill (console-accounted at v-next; a
1807// mouth ring will make it sample-accounted). `killed` = the rest of the sentence, generated SILENTLY
1808// after the kill so the tape holds the counterfactual (P1/D2; `--killed-next` keeps one token).
1809// `cause` names why it died.
1810bool Kernel::speak(int m, float margin, std::string& say, std::string& aired, std::string& killed, std::string& cause, uint64_t& gen_ms) {
1811 const uint64_t g0 = wall_ms();
1812 const bool surface_on = (Switch)vitals.sw.load() != Switch::Off;
1813 llama_memory_seq_rm(mem, GEN, -1, -1);
1814 llama_memory_seq_cp(mem, TRUNK, GEN, -1, -1);
1815 const std::string cue = std::string(CUE_A) + MINDS[m].name + CUE_B + MINDS[m].mandate + CUE_C;
1816 auto ct = tk(vocab, cue, false);
1817 if (!dec(ctx, ct, GEN, npast, true)) { // F4: a generation that cannot decode is fatal, never a silent blank
1818 llama_memory_seq_rm(mem, GEN, -1, -1); fatal("gen_cue_decode");
1819 cause = "fatal:gen_cue_decode"; gen_ms = wall_ms() - g0; return false;
1821 llama_pos gpos = npast + (llama_pos)ct.size();
1822 std::vector<float> gen_logits((size_t)n_vocab);
1823 std::vector<llama_token_data> cands;
1824 { const float* l = llama_get_logits_ith(ctx, -1); std::memcpy(gen_logits.data(), l, sizeof(float) * (size_t)n_vocab); }
1825 ++gen_depth;
1826 bool aborted = false;
1827 if (surface_on) std::printf("\n ┌─ %s (margin %+.2f)\n │ ", MINDS[m].name, margin);
1828 // ONE SENTENCE, HARD CAP (S0, measured: latency-to-notice was coupled to emission length).
1829 // The cap bounds the blind window; the drain below opens a window INSIDE it after every token.
1830 for (int t = 0; t < 28; ++t) {
1831 const llama_token tok = sample_from(smp, gen_logits.data(), n_vocab, cands);
1832 if (llama_vocab_is_eog(vocab, tok)) break;
1833 char pc[256]; const int pn = llama_token_to_piece(vocab, tok, pc, sizeof(pc), 0, true);
1834 std::string piece(pc, pn > 0 ? (size_t)pn : 0);
1835 if (piece.find('\n') != std::string::npos) break;
1836 if (!aborted) {
1837 say += piece;
1838 if (surface_on) { std::fputs(piece.c_str(), stdout); aired = say; } // the forming plane, visible as it forms
1839 } else {
1840 killed += piece; // P1/D2: the counterfactual — sampled, never surfaced, on the tape
1841 if (!cfg.killed_full) break; // --killed-next: one token of it is enough
1843 std::vector<llama_token> one{tok};
1844 if (!dec(ctx, one, GEN, gpos, true)) { aborted = true; cause = "fatal:gen_decode"; fatal("gen_decode"); break; } // F4
1845 ++gpos;
1846 { const float* l = llama_get_logits_ith(ctx, -1); std::memcpy(gen_logits.data(), l, sizeof(float) * (size_t)n_vocab); }
1847 if (t >= 6) { // one sentence: stop at the first close after enough to be a line
1848 const std::string& s = aborted ? killed : say;
1849 const char lc = s.empty() ? 0 : s[s.size() - 1];
1850 if (lc == '.' || lc == '!' || lc == '?') break;
1852 // THE WINDOW IN THE BLIND WINDOW. Percepts never wait for a sentence to finish — not even for
1853 // the silent remainder after a kill.
1854 const llama_pos np_before = npast;
1855 const uint64_t frames_before = frames_completed;
1856 drain_intake(); // ingests onto TRUNK; judgments are deferred (gen_depth > 0)
1857 if (!g_run.load(std::memory_order_acquire)) break;
1858 if (aborted) continue; // the world already answered; the rest is record, not decision
1859 if (frames_completed != frames_before && npast != np_before) {
1860 // A whole frame landed while this seat was mid-sentence (the rest of the line it was
1861 // judging, or a newer line). Did the world answer first?
1862 // (a) deterministic: the newest line ACCEPTS what this seat is saying → settled.
1863 // (b) the seat itself, re-probed on a fresh fork of the UPDATED trunk: margin ≤ 0 → it
1864 // would not have spoken now. Either kills the forming line. Only commits kill.
1865 const std::string newest = !cur_tail_line.empty() ? cur_tail_line
1866 : !tailq.empty() ? tailq.back().first : clause;
1867 bool settled = looks_like_acceptance(newest) && content_overlap(newest, say) >= 1;
1868 float m2 = margin;
1869 if (!settled) m2 = probe_one(m);
1870 if (settled || m2 <= 0.0f) {
1871 aborted = true;
1872 char c[96]; std::snprintf(c, sizeof(c), settled ? "settled_by_world" : "margin_flipped:%+.2f", m2);
1873 cause = c;
1874 if (surface_on) std::printf(" ⟵ [un-said: %s]", cause.c_str());
1875 // no break: the remainder is generated silently (D2), the seam stays open for intake
1879 --gen_depth;
1880 llama_memory_seq_rm(mem, GEN, -1, -1);
1881 gen_ms = wall_ms() - g0;
1882 if (surface_on) {
1883 if (aborted) std::printf("\n └─ killed: \"%s\"\n", killed.c_str());
1884 else std::printf("\n └─\n");
1886 return !aborted;
1889// =====================================================================================================
1890// §14 · THE JUDGMENT — three seats, dial ZERO, the VERBATIM probe; then the manners; then the record
1891// =====================================================================================================
1893void Kernel::judge_and_maybe_emit(const char* reason, float bscore, llama_pos at) {
1894 if (clause.empty()) return;
1895 const llama_pos at_pos = (at < 0) ? npast : at;
1896 const bool late = at_pos < npast; // a deferred judgment: judged NOW, recorded as late (see probe_one)
1897 ++boundaries; vitals.boundaries.store((uint64_t)boundaries);
1898 if (!std::strcmp(reason, "c")) { ++coarse_boundaries; vitals.coarse.store((uint64_t)coarse_boundaries); }
1899 const bool surface_on = (Switch)vitals.sw.load() != Switch::Off;
1901 // Did the world just settle something a seat raised? Acceptance is TARGETED (≥1 content word
1902 // from the seat's own last line). A settled condition never fires again; an unaddressed one may.
1903 if (looks_like_acceptance(clause))
1904 for (int m = 0; m < 3; ++m)
1905 if (!last_say[m].empty() && !resolved[m] && content_overlap(clause, last_say[m]) >= 1) {
1906 resolved[m] = true; cond_open[m] = false; ++conditions_resolved;
1907 char b[512];
1908 std::snprintf(b, sizeof(b), "{\"k\":\"e_resolved\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"by\":\"",
1909 boundaries, rel_ms(), MINDS[m].name);
1910 tape.put(std::string(b) + jesc(clause) + "\"");
1913 // THE PROBE (verbatim frame, dial 0)
1914 const uint64_t t_probe0 = wall_ms();
1915 float margins[3];
1916 for (int m = 0; m < 3; ++m) margins[m] = probe_one(m);
1917 const uint64_t probe_ms = wall_ms() - t_probe0;
1918 if (!g_run.load(std::memory_order_acquire)) return; // a probe failed: fatal already on the tape
1919 vitals.probe_ms_last.store(probe_ms);
1920 if (probe_ms > vitals.probe_ms_max.load()) vitals.probe_ms_max.store(probe_ms);
1922 // Snapshot the judged clause and reset the accumulator NOW: words that land while a seat speaks
1923 // begin a fresh clause (judged afterwards, reason "d"), never appended to the one under judgment.
1924 const std::string judged = clause, judged_lane = cur_lane;
1925 const double j_surp_mean = cl_surp_n ? cl_surp_sum / cl_surp_n : 0.0, j_surp_max = cl_surp_max;
1926 const uint64_t j_arrival = cur_delta_arrival, j_ingest_ms = cl_ingest_ms;
1927 const bool j_replay = cur_replay;
1928 clause.clear(); clause_toks = 0; last_flush_ms = wall_ms();
1929 cl_surp_sum = 0; cl_surp_max = 0; cl_surp_n = 0; cl_ingest_ms = 0;
1931 std::string says[3], aired[3], killed[3], causes[3]; uint64_t gen_ms_a[3] = {0, 0, 0}; bool unsaid_a[3] = {false, false, false};
1932 for (int m = 0; m < 3; ++m) {
1933 if (margins[m] <= 0.0f) continue;
1934 std::string say;
1935 const bool whole = speak(m, margins[m], say, aired[m], killed[m], causes[m], gen_ms_a[m]);
1936 says[m] = say;
1937 if (!whole) {
1938 // THE UN-SAY (P1). `reached_air` is the prefix that reached the surface; `killed` is everything
1939 // that did not — the unsurfaced part of what was formed plus the remainder sampled silently
1940 // after the kill — so the tape holds the counterfactual. Whatever reached the air IS a percept
1941 // and commits on the seat's lane WITH AN INTERRUPTION MARKER, so the mind can tell a line that
1942 // was cut off from a one-word line. Only commits kill; the record shows exactly which words did.
1943 ++n_unsaid; vitals.unsaid.store((uint64_t)n_unsaid); unsaid_a[m] = true;
1944 const std::string unsurfaced = say.size() > aired[m].size() ? say.substr(aired[m].size()) : std::string();
1945 const std::string killed_all = unsurfaced + killed[m];
1946 tape.put("{\"k\":\"unsaid\",\"i\":" + std::to_string(boundaries) + ",\"ms\":" + fmt0(rel_ms()) + ",\"mind\":" + jq(MINDS[m].name) +
1947 ",\"m\":" + fmt2(margins[m]) + ",\"gen_ms\":" + u64s(gen_ms_a[m]) + ",\"cause\":" + jq(causes[m]) +
1948 ",\"reached_air\":" + jq(aired[m]) + ",\"killed\":" + jq(killed_all) + ",\"killed_next\":" + (cfg.killed_full ? "false" : "true") +
1949 ",\"clause\":" + jq(judged));
1950 write_verdict(judged_lane, m, "abort", margins[m], aired[m] + killed_all, causes[m].c_str());
1951 last_unsaid[m] = aired[m] + killed_all; last_unsaid_ms[m] = wall_ms();
1952 last_unsaid_settled[m] = causes[m] == "settled_by_world";
1953 if (!aired[m].empty() && !cfg.pure) {
1954 pending_commits.push_back(std::string("\n[") + MINDS[m].name + "] " + aired[m] + " —");
1955 own_lines.emplace_back(aired[m], wall_ms());
1957 continue;
1959 // Already said this, recently? Log it; do not say it twice — unless the suppression EXPIRED
1960 // (time) or was RE-ARMED (≥2 content words: the topic genuinely came back up). RESOLVED and
1961 // UNADDRESSED are different states; only the second may ever fire again.
1962 const bool dup = near_dup(say, last_say[m]);
1963 const bool in_win = (boundaries - last_say_i[m]) <= 40 && (wall_ms() - last_say_ms[m]) <= SUPP_TTL_MS;
1964 const bool re_armed = dup && content_overlap(judged, last_say[m]) >= 2 && !resolved[m];
1965 if (dup && resolved[m]) {
1966 ++n_supp;
1967 char b[512];
1968 std::snprintf(b, sizeof(b), "{\"k\":\"e_suppressed\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"reason\":\"resolved\",\"say\":\"",
1969 boundaries, rel_ms(), MINDS[m].name, margins[m]);
1970 tape.put(std::string(b) + jesc(say) + "\"");
1971 write_verdict(judged_lane, m, "flag", margins[m], say, "resolved");
1972 says[m].clear(); continue; // suppressed = NOT surfaced-as-new: the e stream must not carry it
1974 if (dup && in_win && !re_armed) {
1975 ++n_supp;
1976 char b[512];
1977 std::snprintf(b, sizeof(b), "{\"k\":\"e_suppressed\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"reason\":\"repeat\",\"say\":\"",
1978 boundaries, rel_ms(), MINDS[m].name, margins[m]);
1979 tape.put(std::string(b) + jesc(say) + "\",\"clause\":\"" + jesc(judged) + "\"");
1980 write_verdict(judged_lane, m, "flag", margins[m], say, "repeat");
1981 says[m].clear(); continue;
1983 // THE INTERRUPTION BUDGET (deterministic, disclosed). The word-overlap valve above catches a
1984 // repeat only when the words repeat; a seat can restate one condition in fresh words at the
1985 // very next boundary (measured 2026-09-04, resume run: the SENTINEL twice in 800 ms). The
1986 // …
1987 if (cfg.refractory_s > 0 && last_say_ms[m] && !re_armed &&
1988 wall_ms() - last_say_ms[m] < (uint64_t)cfg.refractory_s * 1000ull) {
1989 ++n_supp;
1990 char b[512];
1991 std::snprintf(b, sizeof(b), "{\"k\":\"e_suppressed\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"reason\":\"refractory\",\"say\":\"",
1992 boundaries, rel_ms(), MINDS[m].name, margins[m]);
1993 tape.put(std::string(b) + jesc(say) + "\",\"clause\":\"" + jesc(judged) + "\"");
1994 write_verdict(judged_lane, m, "flag", margins[m], say, "refractory");
1995 says[m].clear(); continue;
1997 if (dup) { // it repeats, but legitimately — say why, so the corpus shows the manners
1998 if (re_armed) ++conditions_rearmed; else ++conditions_expired;
1999 char b[512];
2000 std::snprintf(b, sizeof(b), "{\"k\":\"e_rearm\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"why\":\"%s\",\"say\":\"",
2001 boundaries, rel_ms(), MINDS[m].name, re_armed ? "evidence" : "expired");
2002 tape.put(std::string(b) + jesc(say) + "\"");
2004 if (!dup || !cond_open[m]) { ++conditions_opened; cond_open[m] = true; resolved[m] = false; }
2005 ++n_emits; vitals.emits.store((uint64_t)n_emits);
2006 last_say[m] = say; last_say_i[m] = boundaries; last_say_ms[m] = wall_ms();
2007 // The surface already happened (streamed as it formed). Because it REALLY said it, it is part
2008 // of the world and commits on the seat's own lane — AFTER the world's current line closes.
2009 // In `off` nothing reached anyone: recorded, not committed (the same semantics as --pure).
2010 if (surface_on && !cfg.pure) { pending_commits.push_back(std::string("\n[") + MINDS[m].name + "] " + say); own_lines.emplace_back(say, wall_ms()); }
2011 write_verdict(judged_lane, m, is_wake_lane(judged_lane) ? "wake" : "emit", margins[m], say, nullptr);
2013 // holds: silence, on the record, with its margin
2014 for (int m = 0; m < 3; ++m) if (margins[m] <= 0.0f) { ++holds; write_verdict(judged_lane, m, "hold", margins[m], "", nullptr); }
2015 vitals.holds.store((uint64_t)holds);
2016 // gear 2: escalate on MARGIN, not on event — a thin margin either way is "I cannot rank this"
2017 for (int m = 0; m < 3; ++m) if (std::fabs(margins[m]) < cfg.ask_band) write_brief(judged_lane, judged, m, margins[m]);
2019 // latency-to-notice: arrival of the delta that closed this clause -> judgment done
2020 const uint64_t lat = wall_ms() - (j_arrival ? j_arrival : wall_ms());
2021 lat_sum += lat; if (lat > lat_max) lat_max = lat; vitals.lat_ms_last.store(lat);
2022 const bool sref = is_self_ref(judged);
2023 if (sref) ++n_self_ref;
2024 char b[1024];
2025 std::snprintf(b, sizeof(b),
2026 "{\"k\":\"b\",\"i\":%ld,\"ms\":%.0f,\"t_mono_ns\":%llu,\"lane\":\"%s\",\"reason\":\"%s\",\"at\":%d,\"now\":%d,\"late\":%s,\"covers\":%d,\"score\":%.2f,"
2027 "\"lat_ms\":%llu,\"probe_ms\":%llu,\"ingest_ms\":%llu,\"mib_free\":%llu,\"surp_mean\":%.2f,\"surp_max\":%.2f,\"self_ref\":%s,"
2028 "\"state\":\"%s\",\"m_spk\":%.2f,\"m_skp\":%.2f,\"m_sen\":%.2f,%s\"clause\":\"",
2029 boundaries, rel_ms(), (unsigned long long)mono_ns(), jesc(judged_lane).c_str(), reason, (int)at_pos, (int)npast,
2030 late ? "true" : "false", deferred_covers, bscore,
2031 (unsigned long long)lat, (unsigned long long)probe_ms, (unsigned long long)j_ingest_ms,
2032 (unsigned long long)vitals.mib_free.load(),
2033 j_surp_mean, j_surp_max, sref ? "true" : "false", switch_name((Switch)vitals.sw.load()),
2034 margins[0], margins[1], margins[2], j_replay ? "\"replay\":true," : "");
2035 tape.put(std::string(b) + jesc(judged) + "\"");
2036 for (int m = 0; m < 3; ++m)
2037 if (margins[m] > 0.0f && !says[m].empty() && !unsaid_a[m]) {
2038 // e = SURFACED ONLY; events = e + e_suppressed + unsaid, by addition, never by conflation.
2039 std::snprintf(b, sizeof(b),
2040 "{\"k\":\"e\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"gen_ms\":%llu,\"reason\":\"%s\","
2041 "\"self_ref\":%s,\"aired\":%s,\"say\":\"",
2042 boundaries, rel_ms(), MINDS[m].name, margins[m], (unsigned long long)gen_ms_a[m], reason,
2043 sref ? "true" : "false", surface_on ? "true" : "false");
2044 tape.put(std::string(b) + jesc(says[m]) + "\",\"clause\":\"" + jesc(judged) + "\"");
2048// =====================================================================================================
2049// §15 · INTAKE — lines begin, words land, lines end; own speech is placed after the line
2050// =====================================================================================================
2052// Silence before a frame becomes world (ticks-as-world, not a poll): one lazy tick per gap.
2053void Kernel::tick_before(uint64_t arrive_ms) {
2054 const uint64_t gap = arrive_ms > last_delta_ms ? arrive_ms - last_delta_ms : 0;
2055 if (cfg.idle_tick_s > 0 && gap > (uint64_t)cfg.idle_tick_s * 1000ull) {
2056 char tb[64]; std::snprintf(tb, sizeof(tb), "\n[tick +%llus]", (unsigned long long)(gap / 1000));
2057 trunk_text(tb, false); ++ticks; tail_push_line(tb + 1);
2058 tape.put("{\"k\":\"tick\",\"ms\":" + fmt0(rel_ms()) + ",\"gap_s\":" + u64s(gap / 1000));
2061// D1: is this seat-lane frame this process's own line coming back around a bridge? Near-dup against
2062// every own line inside the echo window (older ones are pruned here).
2063bool Kernel::is_own_echo(const std::string& text) {
2064 const uint64_t now = wall_ms(), win = (uint64_t)cfg.echo_window_s * 1000ull;
2065 while (!own_lines.empty() && now - own_lines.front().second > win) own_lines.pop_front();
2066 for (auto& o : own_lines) if (ieq(text, o.first.c_str()) || near_dup(text, o.first)) return true;
2067 return false;
2069// D1: a seat-lane / `self` frame that is NOT an echo is a percept: it lands on the trunk, in order, on
2070// its own lane, and is never judged (no self-judging). The `heard` row records it; `echo_late` marks
2071// the kill condition of the echo window — a heard line that equals an own line older than the window.
2072void Kernel::heard_line(const Delta& d) {
2073 if (line_open) end_line();
2074 tick_before(d.arrive_ms);
2075 last_delta_ms = d.arrive_ms; last_frame_wall_ms = epoch_ms();
2076 bool late = false;
2077 for (auto& o : own_lines) if (ieq(d.text, o.first.c_str())) late = true; // pruned already; anything left is in-window — so check the tail too
2078 for (auto& p : tailq) if (starts_with(p.first, "[") && p.first.find("] ") != std::string::npos && ieq(p.first.substr(p.first.find("] ") + 2), d.text.c_str())) late = true;
2079 if (!trunk_text(std::string("\n[") + d.lane + "] " + d.text, false)) return;
2080 tail_push_line(std::string("[") + d.lane + "] " + d.text);
2081 ++n_heard;
2082 tape.put("{\"k\":\"heard\",\"ms\":" + fmt0(rel_ms()) + ",\"lane\":" + jq(d.lane) + ",\"len\":" + std::to_string(d.text.size()) +
2083 (late ? ",\"echo_late\":true" : ""));
2084 std::printf("%s · [%s] %s (heard, not judged)\n", gen_depth > 0 ? "\n" : "", d.lane.c_str(), d.text.c_str());
2086void Kernel::begin_line(const Delta& d) {
2087 tick_before(d.arrive_ms);
2088 last_delta_ms = d.arrive_ms; cur_delta_arrival = d.arrive_ms; cur_delta_t_mono = d.t_mono_ns;
2089 last_frame_wall_ms = epoch_ms(); // persisted in .meta so a restored trunk can be told how long it was away
2090 cur_lane = d.lane;
2091 trunk_text(std::string("\n[") + d.lane + "] ", false);
2092 cur_tail_line = std::string("[") + d.lane + "]";
2093 line_open = true; line_fresh = true;
2094 std::printf("%s · [%s] %s\n", gen_depth > 0 ? "\n" : "", d.lane.c_str(), d.text.c_str());
2096void Kernel::end_line() {
2097 if (!clause.empty()) {
2098 if (gen_depth > 0) defer_judgment(0.f);
2099 else judge_and_maybe_emit("f", 0.0f); // the line ended: a real final
2101 if (!cur_tail_line.empty()) { tail_push_line(cur_tail_line); cur_tail_line.clear(); }
2102 line_open = false;
2103 flush_pending_commits(); // own speech, placed after the line it illuminated
2105void Kernel::ingest_delta(Delta& d) {
2106 ++n_deltas; vitals.deltas.store((uint64_t)n_deltas);
2107 // P3/F1: a frame the previous life already ingested past its last checkpoint is replayed into the
2108 // restored trunk and says so on its rows (at-least-once, never silent).
2109 cur_replay = replay_until != 0 && d.end_off != 0 && d.end_off <= replay_until;
2110 if (cur_replay) ++replayed_frames;
2111 // D1: seat lanes and `self`, deduped by CONTENT, not by lane. A frame that near-dups a line this
2112 // process put on the air inside the echo window is that line coming back around a bridge: counted,
2113 // never double-entered. Any other seat-lane or `self` frame is a percept: heard, never judged.
2114 // Under --pure nothing a seat says re-enters the trunk, so every seat-lane frame is skipped.
2115 if (seat_of_lane(d.lane) >= 0) {
2116 if (cfg.pure || is_own_echo(d.text)) { ++echo_skipped; return; }
2117 heard_line(d); return;
2119 if (d.grain == "forming") { forming[d.lane] = d.text; ++n_forming; return; } // reflex plane: never on the trunk
2120 if (ieq(d.lane, "counsel") && !counsel_admit(d)) return; // stale counsel: discarded, on the tape
2121 if (line_open) end_line();
2122 begin_line(d);
2123 line_words.clear();
2124 for (size_t p = 0; p < d.text.size();) {
2125 size_t q = d.text.find(' ', p);
2126 if (q == std::string::npos) q = d.text.size();
2127 if (q > p) line_words.push_back(d.text.substr(p, q - p));
2128 p = q + 1;
2130 while (g_run.load(std::memory_order_acquire) && !line_words.empty()) feed_word();
2131 end_line();
2132 forming.erase(d.lane); // a committed line supersedes whatever was forming on its lane
2134// One word of the open line lands on the trunk. Called by the line's own loop, and by the drain
2135// while a seat is speaking — so the rest of the line arrives during the sentence, in order, exactly
2136// as it would from a live keyboard.
2137void Kernel::feed_word() {
2138 if (line_words.empty()) return;
2139 const std::string w = line_words.front(); line_words.pop_front();
2140 const bool fresh = line_fresh; line_fresh = false;
2141 // The accumulator takes the word BEFORE the trunk does. S0 appended after ingest, so its judged
2142 // clause always lacked the word that triggered the boundary and the line's last word was
2143 // re-probed alone as a fragment; with intake reentrant during speech, the late append also put
2144 // the triggering word behind everything fed meanwhile — out of order. Measured 2026-09-04.
2145 clause += (clause.empty() ? "" : " ") + w;
2146 cur_tail_line += " " + w;
2147 ingest_word(fresh ? w : " " + w);
2148 if (line_words.empty()) ++frames_completed; // the frame's last word is on the trunk
2150// A judgment requested while a seat is speaking is queued with its clause, lane, arrival and nerve
2151// stats, and the accumulator is cleared so the next words start a fresh clause. Nothing is dropped;
2152// the judgment is delayed, and the record says so (reason "d").
2153void Kernel::defer_judgment(float score) {
2154 if (clause.empty()) return;
2155 deferred.push_back(Deferred{clause, cur_lane, score, cur_delta_arrival, cl_surp_sum, cl_surp_max, cl_surp_n, clause_toks, cl_ingest_ms, npast, cur_replay});
2156 clause.clear(); clause_toks = 0; last_flush_ms = wall_ms();
2157 cl_surp_sum = 0; cl_surp_max = 0; cl_surp_n = 0; cl_ingest_ms = 0;
2159// Deferred judgments (and a molt) are paid here, only when no seat is speaking. Because a judgment
2160// can only be about the trunk as it stands now (see probe_one), everything that landed during one
2161// blind window is judged ONCE, as one clause spanning its boundaries (`covers`), at the current
2162// …
2163void Kernel::settle_deferred() {
2164 if (gen_depth != 0) return;
2165 if (!deferred.empty()) {
2166 Deferred live{clause, cur_lane, 0.f, cur_delta_arrival, cl_surp_sum, cl_surp_max, cl_surp_n, clause_toks, cl_ingest_ms, npast, cur_replay};
2167 clause.clear(); clause_toks = 0; cl_surp_sum = 0; cl_surp_max = 0; cl_surp_n = 0; cl_ingest_ms = 0;
2168 while (g_run.load(std::memory_order_acquire) && !deferred.empty() && gen_depth == 0) {
2169 // fold the whole window into one clause: earliest arrival, latest lane, stats summed
2170 Deferred d = std::move(deferred.front()); deferred.pop_front();
2171 int covers = 1;
2172 while (!deferred.empty()) {
2173 const Deferred& n = deferred.front();
2174 d.clause += (d.clause.empty() ? "" : " ") + n.clause;
2175 d.lane = n.lane; d.score = n.score; d.replay = n.replay;
2176 d.surp_sum += n.surp_sum; if (n.surp_max > d.surp_max) d.surp_max = n.surp_max; d.surp_n += n.surp_n;
2177 d.toks += n.toks; d.ingest_ms += n.ingest_ms;
2178 deferred.pop_front(); ++covers;
2180 clause = d.clause; cur_lane = d.lane; cur_delta_arrival = d.arrival; cur_replay = d.replay;
2181 cl_surp_sum = d.surp_sum; cl_surp_max = d.surp_max; cl_surp_n = d.surp_n; clause_toks = d.toks; cl_ingest_ms = d.ingest_ms;
2182 deferred_covers = covers;
2183 judge_and_maybe_emit("d", d.score, d.npast_at);
2184 deferred_covers = 1;
2185 n_deferred += covers;
2186 // words that gathered during this judgment's speech (and any newly deferred items) loop again
2188 // restore the live accumulator, then append anything that gathered during the last item
2189 const std::string later = clause; const int later_toks = clause_toks;
2190 const double ls = cl_surp_sum, lm = cl_surp_max; const int ln = cl_surp_n; const uint64_t li = cl_ingest_ms;
2191 clause = live.clause; clause_toks = live.toks; cur_lane = live.lane; cur_delta_arrival = live.arrival; cur_replay = live.replay;
2192 cl_surp_sum = live.surp_sum; cl_surp_max = live.surp_max; cl_surp_n = live.surp_n; cl_ingest_ms = live.ingest_ms;
2193 if (!later.empty()) {
2194 clause += (clause.empty() ? "" : " ") + later; clause_toks += later_toks;
2195 cl_surp_sum += ls; if (lm > cl_surp_max) cl_surp_max = lm; cl_surp_n += ln; cl_ingest_ms += li;
2198 if (molt_pending && gen_depth == 0) { if (!clause.empty()) judge_and_maybe_emit("m", 0.f); do_molt(); }
2200void Kernel::drain_intake() {
2201 // the open line's remaining words are the next percepts, in order — before any newer frame
2202 while (g_run.load(std::memory_order_acquire) && line_open && !line_words.empty()) feed_word();
2203 Delta d;
2204 while (g_run.load(std::memory_order_acquire) && tail->poll(d)) {
2205 backlog_now = tail->pending();
2206 ingest_delta(d);
2207 tail->ingested_off.store(d.end_off); // F1: the cursor follows what is ON THE TRUNK
2209 vitals.spool_offset.store(tail->offset.load()); vitals.spool_unread.store(tail->unread_bytes());
2212// =====================================================================================================
2213// §16 · THE LIVE LOOP
2214// =====================================================================================================
2216void Kernel::run() {
2217 std::printf("[fusord] resident on %s — watching. Ctrl-C to stop.\n"
2218 " switch=%s (fusord.state is yours alone) · nothing is asked of the model, ever.\n\n",
2219 cfg.model.c_str(), switch_name((Switch)vitals.sw.load()));
2220 uint64_t last_idle_tick_ms = wall_ms();
2221 while (g_run.load(std::memory_order_acquire) && (cfg.max_toks == 0 || npast < cfg.max_toks)) {
2222 Delta d;
2223 report_rename_failures(); // F3: a pill or cursor that could not be replaced is on the tape, not silent
2224 backlog_now = tail->pending();
2225 if (tail->poll(d)) {
2226 ingest_delta(d);
2227 tail->ingested_off.store(d.end_off); // F1: the cursor follows what is ON THE TRUNK
2228 settle_deferred(); // anything deferred while a seat spoke is paid now, in order
2229 last_idle_tick_ms = wall_ms();
2230 vitals.spool_offset.store(tail->offset.load()); vitals.spool_unread.store(tail->unread_bytes());
2231 } else {
2232 // Idle: the RING sleeps, never the GPU. Silence is a lane: long silence enters the trunk
2233 // as ticks even when nothing follows, so the mind's sense of time is never stale.
2234 if (!line_open) flush_pending_commits();
2235 const uint64_t now = wall_ms();
2236 if (cfg.idle_tick_s > 0 && now - last_idle_tick_ms > (uint64_t)cfg.idle_tick_s * 1000ull && !line_open) {
2237 char tb[64]; std::snprintf(tb, sizeof(tb), "\n[tick +%llus]", (unsigned long long)((now - last_idle_tick_ms) / 1000));
2238 trunk_text(tb, false); ++ticks; tail_push_line(tb + 1);
2239 char b[128]; std::snprintf(b, sizeof(b), "{\"k\":\"tick\",\"ms\":%.0f,\"gap_s\":%llu,\"idle\":true", rel_ms(), (unsigned long long)((now - last_idle_tick_ms) / 1000));
2240 tape.put(b);
2241 last_idle_tick_ms = last_delta_ms = now;
2243 if (now - last_vram_ms > 60000) read_vram(true);
2244 // P3: the periodic checkpoint is taken only when the world is QUIET — no open line, no seat
2245 // speaking, nothing deferred, nothing pending on the ring, and two seconds since the last
2246 // frame — so the trunk and the cursor it records agree about what the resident has seen.
2247 const bool quiet = !line_open && gen_depth == 0 && deferred.empty() && backlog_now == 0 &&
2248 tail->pending() == 0 && now - last_delta_ms >= 2000;
2249 if (!cfg.ckpt.empty() && quiet &&
2250 (ckpt_due || (cfg.ckpt_every_s > 0 && now - last_ckpt_ms > (uint64_t)cfg.ckpt_every_s * 1000ull)))
2251 checkpoint(ckpt_due ? "molt" : "periodic");
2252 std::this_thread::sleep_for(std::chrono::milliseconds(5));
2257void Kernel::shutdown(const char* stopped) {
2258 if (!line_open) flush_pending_commits();
2259 if (!cfg.ckpt.empty()) checkpoint("stop");
2260 tail->stop(); pill.stop();
2261 const double total = rel_ms();
2262 // The end row is built from strings (F6, review correction 5): every counter this pass adds lands here.
2263 auto L = [](long x) { return std::to_string(x); };
2264 std::string b = std::string("{\"k\":\"end\",\"words\":") + L(words) + ",\"toks\":" + std::to_string((int)npast) +
2265 ",\"boundaries\":" + L(boundaries) + ",\"holds\":" + L(holds) + ",\"emits\":" + L(n_emits) + ",\"ticks\":" + L(ticks) +
2266 ",\"molts\":" + L(n_molts) + ",\"molt_outage_ms\":" + u64s(molt_outage_total) + ",\"deltas\":" + L(n_deltas) +
2267 ",\"echo_skipped\":" + L(echo_skipped) + ",\"heard\":" + L(n_heard) + ",\"self_ref_boundaries\":" + L(n_self_ref) +
2268 ",\"suppressed_repeats\":" + L(n_supp) + ",\"coarse_boundaries\":" + L(coarse_boundaries) + ",\"deferred_boundaries\":" + L(n_deferred) +
2269 ",\"ring_dropped\":0,\"ring_stalls\":" + u64s(tail->stalls.load()) + ",\"spool_lines\":" + u64s(tail->lines.load()) +
2270 ",\"spool_resets\":" + u64s(tail->reset_events.load()) + ",\"unsaid\":" + L(n_unsaid) + ",\"briefs\":" + L(n_briefs) +
2271 ",\"counsel_in\":" + L(n_counsel) + ",\"counsel_discarded\":" + L(n_discard) + ",\"forming_frames\":" + L(n_forming) +
2272 ",\"conditions_opened\":" + L(conditions_opened) + ",\"conditions_resolved\":" + L(conditions_resolved) +
2273 ",\"conditions_expired\":" + L(conditions_expired) + ",\"conditions_rearmed\":" + L(conditions_rearmed) +
2274 ",\"emits_per_boundary\":" + fmt3(boundaries ? (double)n_emits / (double)boundaries : 0.0) +
2275 ",\"emits_per_condition\":" + fmt3(conditions_opened ? (double)n_emits / (double)conditions_opened : 0.0) +
2276 ",\"surp_mean_all\":" + fmt3(all_surp_n ? all_surp_sum / (double)all_surp_n : 0.0) +
2277 ",\"mean_lat_ms\":" + fmt0(boundaries ? (double)lat_sum / (double)boundaries : 0.0) + ",\"max_lat_ms\":" + u64s(lat_max) +
2278 ",\"mib_free\":" + u64s(vitals.mib_free.load()) + ",\"rename_failures\":" + u64s(g_rename_failures.load(std::memory_order_relaxed)) +
2279 ",\"replayed_frames\":" + L(replayed_frames) + ",\"wall_ms\":" + fmt0(total) + ",\"stopped\":" + jq(stopped);
2280 tape.put(b);
2281 tape.close(); verdicts.close(); briefs.close();
2283 std::printf("\n===== FUSORD DOWN =====\n");
2284 std::printf("uptime %s · deltas=%ld words=%ld trunk_toks=%d · spool lines=%llu resets=%llu ring stalls=%llu (dropped: 0 by construction)\n",
2285 fmt_hms(total).c_str(), n_deltas, words, (int)npast, (unsigned long long)tail->lines.load(),
2286 (unsigned long long)tail->reset_events.load(), (unsigned long long)tail->stalls.load());
2287 std::printf("boundaries=%ld (coarse %ld · deferred %ld) holds=%ld emits=%ld unsaid=%ld ticks=%ld molts=%ld\n",
2288 boundaries, coarse_boundaries, n_deferred, holds, n_emits, n_unsaid, ticks, n_molts);
2289 std::printf("conditions opened=%ld resolved=%ld expired=%ld re-armed=%ld · emits/boundary %.4f · emits/condition %.4f [two grains, never one ratio]\n",
2290 conditions_opened, conditions_resolved, conditions_expired, conditions_rearmed,
2291 boundaries ? (double)n_emits / (double)boundaries : 0.0,
2292 conditions_opened ? (double)n_emits / (double)conditions_opened : 0.0);
2293 std::printf("gear 2: briefs=%ld counsel in=%ld discarded stale=%ld\n", n_briefs, n_counsel, n_discard);
2294 std::printf("F-KEEPUP (live): latency-to-notice mean %.0f ms · max %llu ms [arrival -> judged] · free VRAM %llu MiB\n",
2295 boundaries ? (double)lat_sum / (double)boundaries : 0.0, (unsigned long long)lat_max,
2296 (unsigned long long)vitals.mib_free.load());
2297 std::printf("nerve: mean surprisal %.2f nats (logged, gating NOTHING — measured 2026-08-12)\n",
2298 all_surp_n ? all_surp_sum / (double)all_surp_n : 0.0);
2299 if (echo_skipped || n_heard) std::printf("seat-lane frames: echoes skipped %ld · heard, not judged %ld\n", echo_skipped, n_heard);
2300 std::printf("tape: %s (next: soak --brief · soak --review · verify the chain from genesis)\n", tape.path.c_str());
2302 if (smp_scribe) llama_sampler_free(smp_scribe);
2303 if (smp) llama_sampler_free(smp);
2304 if (ctx) llama_free(ctx);
2305 if (mdl) llama_model_free(mdl);
2306 llama_backend_free();
2309} // namespace fusor
2311// =====================================================================================================
2312// §17 · MAIN — the console, the stop signal, the arguments, the mark before the model
2313// =====================================================================================================
2315#if defined(_WIN32)
2316static BOOL WINAPI ctrl_handler(DWORD t) {
2317 if (t == CTRL_C_EVENT || t == CTRL_BREAK_EVENT || t == CTRL_CLOSE_EVENT) {
2318 fusor::g_run.store(false, std::memory_order_release);
2319 std::printf("\n[fusord] stop requested — finishing the tape…\n");
2320 return TRUE;
2322 return FALSE;
2324#else
2325static void sig_handler(int) { fusor::g_run.store(false, std::memory_order_release); }
2326#endif
2328static void usage() {
2329 std::printf(
2330 "usage: fusord <spool> [--model p] [--out-dir d] [--molt-wm N] [--idle-tick-s N]\n"
2331 " [--from-start | --from-end] [--max-toks N] [--pure] [--kv-f16]\n"
2332 " [--ckpt p] [--resume] [--cold] [--ckpt-every-s N]\n"
2333 " [--ask-band F] [--stale-tok N] [--refractory-s N] [--wake-lanes a,b,c]\n"
2334 " [--killed-next] [--echo-window-s N] [--n-ctx N] [--allow-cpu] [--egress-unchecked]\n"
2335 " [--model-sha256 HEX] [--sha-cache FILE] [--about] [--serve-hash]\n"
2336 " the spool is tailed as lane-contract v0.1 (t_mono_ns<TAB>lane<TAB>grain<TAB>text),\n"
2337 " legacy (lane<TAB>text) or bare text (lane 'bo'); it resumes from <spool>.cursor unless told otherwise.\n"
2338 " <out-dir>/fusord.state (off|shadow|live) is the operator's switch; the kernel never writes it.\n");
2341int main(int argc, char** argv) {
2342#if defined(_WIN32)
2343 SetConsoleOutputCP(CP_UTF8);
2344 setvbuf(stdout, nullptr, _IONBF, 0);
2345 SetConsoleCtrlHandler(ctrl_handler, TRUE);
2346#else
2347 setvbuf(stdout, nullptr, _IONBF, 0);
2348 std::signal(SIGINT, sig_handler); std::signal(SIGTERM, sig_handler);
2349#endif
2350 fusor::Kernel k;
2351 fusor::Config& c = k.cfg;
2352 bool want_hash = false, want_about = false;
2353 for (int i = 1; i < argc; ++i) {
2354 auto next = [&](const char* flag) -> const char* {
2355 if (!std::strcmp(argv[i], flag) && i + 1 < argc) return argv[++i];
2356 return nullptr;
2357 };
2358 const char* v;
2359 if ((v = next("--model"))) c.model = v;
2360 else if ((v = next("--out-dir"))) c.out_dir = v;
2361 else if ((v = next("--out"))) c.out_dir = v; // S0's flag name, kept
2362 else if ((v = next("--molt-wm"))) c.molt_wm = std::atol(v);
2363 else if ((v = next("--max-toks"))) c.max_toks = std::atol(v);
2364 else if ((v = next("--idle-tick-s"))) c.idle_tick_s = std::atol(v);
2365 else if ((v = next("--ckpt"))) c.ckpt = v;
2366 else if ((v = next("--ckpt-every-s"))) c.ckpt_every_s = std::atol(v);
2367 else if ((v = next("--ask-band"))) c.ask_band = (float)std::atof(v);
2368 else if ((v = next("--stale-tok"))) c.stale_tok = std::atol(v);
2369 else if ((v = next("--refractory-s"))) c.refractory_s = std::atol(v);
2370 else if ((v = next("--echo-window-s"))) c.echo_window_s = std::atol(v);
2371 else if ((v = next("--n-ctx"))) c.n_ctx = std::atol(v);
2372 else if ((v = next("--model-sha256"))) c.model_sha256 = v;
2373 else if ((v = next("--sha-cache"))) c.sha_cache = v;
2374 else if (!std::strcmp(argv[i], "--killed-next")) c.killed_full = false;
2375 else if (!std::strcmp(argv[i], "--allow-cpu")) c.allow_cpu = true;
2376 else if (!std::strcmp(argv[i], "--egress-unchecked")) c.egress_unchecked = true;
2377 else if (!std::strcmp(argv[i], "--about")) want_about = true;
2378 else if ((v = next("--wake-lanes"))) {
2379 c.wake_prefixes.clear(); std::string s = v; size_t p = 0;
2380 while (p <= s.size()) { size_t q = s.find(',', p); if (q == std::string::npos) q = s.size();
2381 if (q > p) c.wake_prefixes.push_back(s.substr(p, q - p)); p = q + 1; }
2383 else if (!std::strcmp(argv[i], "--from-start")) c.from_start = true;
2384 else if (!std::strcmp(argv[i], "--from-end")) c.from_end = true;
2385 else if (!std::strcmp(argv[i], "--pure")) c.pure = true;
2386 else if (!std::strcmp(argv[i], "--kv-f16")) c.kv_q8 = false;
2387 else if (!std::strcmp(argv[i], "--resume")) c.resume = true;
2388 else if (!std::strcmp(argv[i], "--cold")) c.cold = true;
2389 else if (!std::strcmp(argv[i], "--serve-hash")) want_hash = true;
2390 else if (argv[i][0] != '-') c.spool = argv[i];
2391 else { std::printf("unknown flag %s\n", argv[i]); usage(); return 1; }
2393 if (want_hash) { // train ≡ serve, checkable with no model and no spool
2394 const uint64_t h = fusor::serve_hash();
2395 std::printf("serve-bytes hash 0x%016llx · pinned 0x%016llx · %s\n", (unsigned long long)h,
2396 (unsigned long long)fusor::SERVE_HASH_PIN, h == fusor::SERVE_HASH_PIN ? "MATCH" : "DRIFT");
2397 return h == fusor::SERVE_HASH_PIN ? 0 : 2;
2399 if (want_about) return fusor::about(c); // the process receipt: no model, no spool
2400 if (c.spool.empty()) { usage(); return 1; }
2401 { // the trunk can never be asked to hold more than the context (K3' clamp, review §4.6)
2402 const long nctx = c.n_ctx > 0 ? c.n_ctx : (c.kv_q8 ? 65536 : 32768);
2403 if (nctx < 2048) { std::printf("--n-ctx %ld is below 2048; refused\n", nctx); return 1; }
2404 if (c.molt_wm > 0 && c.molt_wm > nctx - 2048) {
2405 std::printf("[fusord] molt_wm %ld exceeds n_ctx %ld - 2048; clamped to %ld\n", c.molt_wm, nctx, nctx - 2048);
2406 c.molt_wm = nctx - 2048;
2408 if (c.max_toks > 0 && c.max_toks > nctx - 64) { std::printf("[fusord] max_toks %ld clamped to %ld\n", c.max_toks, nctx - 64); c.max_toks = nctx - 64; }
2411 // THE MARK: where the spool ends NOW, before the model loads. Nothing that lands during the
2412 // seed is ever skipped (S0 opened at EOF after the load and missed the first two minutes).
2413 fusor::LaneTail tail(c.spool);
2414 tail.mark_now();
2415 k.tail = &tail;
2417 const int rc = k.boot();
2418 if (rc) return rc;
2419 k.run();
2420 k.shutdown((c.max_toks && k.npast >= c.max_toks) ? "trunk_full" : "stopped");
2421 return 0;
2424// ---- end of segment 3 -------------------------------------------------------------------------------

§ 03 — The file

Take it with you.

The listing above and the download below are the same bytes. The digest was taken at build time from the file this page serves — check it against what lands on your disk.

fusord.cpp
FUSOR · the resident kernel, v-next. Written, not compiled — no number in the file is a measurement of itself.
sha256 0e8b65e4624a1fadb90c31ddb43150cc0f4e633259dd2b704a4c6e55b7009c93
Download the file ↓

The substrate this kernel is the core of is FUSOR-1. What it is inert until fitted to, and what fitting means, are the fits.