// fusord.cpp — FUSOR · THE RESIDENT KERNEL (v-next, 2026-09-04)
//
// One process, one GPU thread, one running memory that is never rebuilt. It reads a spool of
// lanes, holds them in one trunk, and at every completed thought asks three seats whether
// anything deserves saying — mostly deciding no, and writing that down with its margin. A seat
// that is speaking when the world answers is killed mid-word, and the sentence it would have
// finished goes on the tape. Every row is BLAKE2b-chained to the one before. The kernel proposes
// and acts on nothing: there is no `allow` verb in this file. The serve format is VERBATIM from
// the v11 tune and its hash is pinned (0xe7ffa5704ba31076), asserted before the model loads.
// Not claimed: this file is written, not compiled; no number in it is a measurement of itself.
//
// Run: fusord.exe <spool> [--model p] [--out-dir d] [--ckpt p] [--resume] [--cold] …
#if defined(_WIN32)
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX            // windows.h's min/max macros would break std::min below
#  endif
#  include <windows.h>
#  include <psapi.h>        // EnumProcessModules: the module gate (zero egress as a process property)
#  include <bcrypt.h>       // SHA-256 of the weights (CNG), the model's identity on the header
#  include <sys/stat.h>
#  pragma comment(lib, "bcrypt.lib")
#else
#  include <csignal>
#  include <unistd.h>
#  include <sys/stat.h>
#endif

#include <algorithm>
#include <atomic>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>

#include "ggml-backend.h"
#include "llama.h"

#ifndef AURICLE_LLAMA_DIR
#define AURICLE_LLAMA_DIR "C:/llama.cpp"
#endif

namespace fusor {

// The run flag. Cleared by Ctrl-C / SIGINT, or by the operator writing `stop` into the switch file;
// read at every beat of every loop so the tape gets its `end`, the cursor is saved, the trunk is
// checkpointed. Declared first because the pill (below) honors the switch.
static std::atomic<bool> g_run{true};

// =====================================================================================================
// §1 · SMALL HELPERS (clocks, escapes, hashes)
// =====================================================================================================

// Monotonic nanoseconds: the lane contract's clock. One stamping authority per venue; the kernel
// stamps its own records with the same clock so a verdict and the frame that caused it are ordered.
static inline uint64_t mono_ns() {
    using namespace std::chrono;
    return (uint64_t)duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count();
}
// Milliseconds on the same clock — S0's `wall_ms` (it was steady_clock ms, not wall time; the name
// is kept because the ledger's `ms` column and the soak tools expect it).
static inline uint64_t wall_ms() {
    using namespace std::chrono;
    return (uint64_t)duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
// Real wall time (Unix epoch ms): the only clock that survives a process, so a restored trunk can
// be told how long the world went on without it (P3, F5). Never used for ordering within a run.
static inline uint64_t epoch_ms() {
    using namespace std::chrono;
    return (uint64_t)duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
static std::string fmt_hms(double ms) {
    int s = (int)(ms / 1000.0); char b[32];
    std::snprintf(b, sizeof(b), "%d:%02d:%02d", s / 3600, (s / 60) % 60, s % 60);
    return b;
}
// JSON string escape (S0's, extended with \t so a flattened tab cannot break a record).
static std::string jesc(const std::string& s) {
    std::string o; o.reserve(s.size() + 8);
    for (char c : s) {
        if (c == '"') o += "\\\""; else if (c == '\\') o += "\\\\";
        else if (c == '\n') o += "\\n"; else if (c == '\t') o += "\\t"; else if (c == '\r') {}
        else if ((unsigned char)c >= 0x20 || c < 0) o += c;
    }
    return o;
}
static std::string hex_of(const uint8_t* p, size_t n) {
    static const char* H = "0123456789abcdef";
    std::string s; s.reserve(n * 2);
    for (size_t i = 0; i < n; ++i) { s += H[p[i] >> 4]; s += H[p[i] & 15]; }
    return s;
}
// Row-building helpers (F6): rows are built from strings, never from fixed buffers that truncate
// silently on a long path or a long clause.
[[maybe_unused]] static std::string jq(const std::string& s) { return "\"" + jesc(s) + "\""; }
[[maybe_unused]] static std::string fmt2(double x) { char b[48]; std::snprintf(b, sizeof(b), "%.2f", x); return b; }
[[maybe_unused]] static std::string fmt3(double x) { char b[48]; std::snprintf(b, sizeof(b), "%.3f", x); return b; }
[[maybe_unused]] static std::string fmt0(double x) { char b[48]; std::snprintf(b, sizeof(b), "%.0f", x); return b; }
[[maybe_unused]] static std::string u64s(uint64_t x) { return std::to_string((unsigned long long)x); }
[[maybe_unused]] static std::string hex16(uint64_t x) { char b[24]; std::snprintf(b, sizeof(b), "%016llx", (unsigned long long)x); return b; }
// FNV-1a over a C string — IDENTICAL to S0's, because serve_hash() below is computed with it and
// the pin was minted from it. Do not touch.
static uint64_t fnv1a(uint64_t h, const char* s) {
    for (const unsigned char* p = (const unsigned char*)s; *p; ++p) {
        h ^= (uint64_t)*p; h *= 1099511628211ull;
    }
    return h;
}
static uint64_t fnv1a_bytes(uint64_t h, const void* v, size_t n) {
    const unsigned char* p = (const unsigned char*)v;
    for (size_t i = 0; i < n; ++i) { h ^= (uint64_t)p[i]; h *= 1099511628211ull; }
    return h;
}
static bool starts_with(const std::string& s, const char* pfx) {
    const size_t n = std::strlen(pfx);
    return s.size() >= n && std::memcmp(s.data(), pfx, n) == 0;
}
static bool ieq(const std::string& a, const char* b) {
    size_t n = std::strlen(b);
    if (a.size() != n) return false;
    for (size_t i = 0; i < n; ++i)
        if (std::tolower((unsigned char)a[i]) != std::tolower((unsigned char)b[i])) return false;
    return true;
}
static std::string lower(const std::string& s) {
    std::string t = s; for (auto& c : t) c = (char)std::tolower((unsigned char)c); return t;
}

// =====================================================================================================
// §2 · BLAKE2b-256 (RFC 7693, unkeyed) — the estate's one hash family, inline so the kernel has no
//      dependency for the thing that makes its record trustworthy.
// =====================================================================================================

struct Blake2b {
    uint64_t h[8]; uint64_t t[2]; uint8_t buf[128]; size_t buflen; size_t outlen;

    static const uint64_t IV[8];
    static const uint8_t  SIGMA[12][16];

    static inline uint64_t rotr64(uint64_t x, unsigned n) { return (x >> n) | (x << (64u - n)); }
    static inline uint64_t load64(const uint8_t* p) {
        uint64_t v = 0; for (int i = 7; i >= 0; --i) v = (v << 8) | (uint64_t)p[i]; return v;
    }
    static inline void G(uint64_t* v, const uint64_t* m, uint8_t x, uint8_t y,
                         int a, int b, int c, int d) {
        v[a] = v[a] + v[b] + m[x]; v[d] = rotr64(v[d] ^ v[a], 32);
        v[c] = v[c] + v[d];        v[b] = rotr64(v[b] ^ v[c], 24);
        v[a] = v[a] + v[b] + m[y]; v[d] = rotr64(v[d] ^ v[a], 16);
        v[c] = v[c] + v[d];        v[b] = rotr64(v[b] ^ v[c], 63);
    }
    void init(size_t out) {
        outlen = out;
        for (int i = 0; i < 8; ++i) h[i] = IV[i];
        h[0] ^= 0x01010000ull ^ (uint64_t)out;   // param block: fanout=1, depth=1, keylen=0, outlen
        t[0] = t[1] = 0; buflen = 0;
    }
    void compress(const uint8_t* block, bool last) {
        uint64_t m[16], v[16];
        for (int i = 0; i < 16; ++i) m[i] = load64(block + 8 * i);
        for (int i = 0; i < 8; ++i) { v[i] = h[i]; v[i + 8] = IV[i]; }
        v[12] ^= t[0]; v[13] ^= t[1];
        if (last) v[14] = ~v[14];
        for (int r = 0; r < 12; ++r) {
            const uint8_t* s = SIGMA[r];
            G(v, m, s[0],  s[1],  0, 4,  8, 12);
            G(v, m, s[2],  s[3],  1, 5,  9, 13);
            G(v, m, s[4],  s[5],  2, 6, 10, 14);
            G(v, m, s[6],  s[7],  3, 7, 11, 15);
            G(v, m, s[8],  s[9],  0, 5, 10, 15);
            G(v, m, s[10], s[11], 1, 6, 11, 12);
            G(v, m, s[12], s[13], 2, 7,  8, 13);
            G(v, m, s[14], s[15], 3, 4,  9, 14);
        }
        for (int i = 0; i < 8; ++i) h[i] ^= v[i] ^ v[i + 8];
    }
    void update(const uint8_t* p, size_t n) {
        while (n > 0) {
            if (buflen == 128) {   // a full block is compressed only when MORE data follows it
                t[0] += 128; if (t[0] < 128) ++t[1];
                compress(buf, false); buflen = 0;
            }
            const size_t take = std::min((size_t)128 - buflen, n);
            std::memcpy(buf + buflen, p, take); buflen += take; p += take; n -= take;
        }
    }
    void finish(uint8_t* out) {
        t[0] += (uint64_t)buflen; if (t[0] < (uint64_t)buflen) ++t[1];
        std::memset(buf + buflen, 0, 128 - buflen);
        compress(buf, true);
        for (size_t i = 0; i < outlen; ++i) out[i] = (uint8_t)(h[i / 8] >> (8 * (i % 8)));
    }
};
const uint64_t Blake2b::IV[8] = {
    0x6a09e667f3bcc908ull, 0xbb67ae8584caa73bull, 0x3c6ef372fe94f82bull, 0xa54ff53a5f1d36f1ull,
    0x510e527fade682d1ull, 0x9b05688c2b3e6c1full, 0x1f83d9abfb41bd6bull, 0x5be0cd19137e2179ull };
const uint8_t Blake2b::SIGMA[12][16] = {
    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15},
    {14,10, 4, 8, 9,15,13, 6, 1,12, 0, 2,11, 7, 5, 3},
    {11, 8,12, 0, 5, 2,15,13,10,14, 3, 6, 7, 1, 9, 4},
    { 7, 9, 3, 1,13,12,11,14, 2, 6, 5,10, 4, 0,15, 8},
    { 9, 0, 5, 7, 2, 4,10,15,14, 1,11,12, 6, 8, 3,13},
    { 2,12, 6,10, 0,11, 8, 3, 4,13, 7, 5,15,14, 1, 9},
    {12, 5, 1,15,14,13, 4,10, 0, 7, 6, 3, 9, 2, 8,11},
    {13,11, 7,14,12, 1, 3, 9, 5, 0,15, 4, 8, 6, 2,10},
    { 6,15,14, 9,11, 3, 0, 8,12, 2,13, 7, 1, 4,10, 5},
    {10, 2, 8, 4, 7, 6, 1, 5,15,11, 9,14, 3,12,13, 0},
    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15},
    {14,10, 4, 8, 9,15,13, 6, 1,12, 0, 2,11, 7, 5, 3} };

// h = blake2b-256( prev_hex ‖ body )
static std::string chain_hash(const std::string& prev_hex, const std::string& body) {
    Blake2b b; b.init(32);
    b.update((const uint8_t*)prev_hex.data(), prev_hex.size());
    b.update((const uint8_t*)body.data(), body.size());
    uint8_t out[32]; b.finish(out);
    return hex_of(out, 32);
}
static const char* GENESIS = "0000000000000000000000000000000000000000000000000000000000000000";

// =====================================================================================================
// §3 · FILES: sizes, atomic replace, the switch
// =====================================================================================================

static bool file_size_of(const std::string& path, uint64_t& out) {
    FILE* f = std::fopen(path.c_str(), "rb");
    if (!f) return false;
#if defined(_WIN32)
    _fseeki64(f, 0, SEEK_END); const long long n = _ftelli64(f);
#else
    fseeko(f, 0, SEEK_END); const long long n = (long long)ftello(f);
#endif
    std::fclose(f);
    if (n < 0) return false;
    out = (uint64_t)n; return true;
}
static bool seek_to(FILE* f, uint64_t off) {
#if defined(_WIN32)
    return _fseeki64(f, (long long)off, SEEK_SET) == 0;
#else
    return fseeko(f, (off_t)off, SEEK_SET) == 0;
#endif
}
static std::string read_all(const std::string& path, size_t cap = 1 << 20) {
    std::string s; FILE* f = std::fopen(path.c_str(), "rb");
    if (!f) return s;
    char buf[8192]; size_t n;
    while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0 && s.size() < cap) s.append(buf, n);
    std::fclose(f); return s;
}
// Write-then-rename: readers never see a torn pill or a torn cursor. On Windows the rename fails with
// ERROR_ACCESS_DENIED (5) while any plain reader holds the destination open (measured 2026-09-04,
// convergence_tools/rename_while_open.py). Readers hold a file for microseconds, so the rename is
// retried (20 × 5 ms); a rename that still fails is COUNTED here and reported by the GPU thread as a
// `warn` row naming the path (F3) — "STALLED" must mean stalled, never "someone had the file open".
static std::atomic<uint64_t> g_rename_failures{0};
static std::mutex g_rename_mu;
static std::string g_rename_last_path;
static unsigned long g_rename_last_err = 0;
// Replace dst with src by rename, retried; write_through for the trunk checkpoint (P3), plain for the
// pill and the cursor. A failure after the retries is counted for the GPU thread to report.
static bool replace_file(const std::string& src, const std::string& dst, bool write_through) {
    unsigned long err = 0;
    for (int attempt = 0; attempt < 20; ++attempt) {
#if defined(_WIN32)
        const DWORD flags = MOVEFILE_REPLACE_EXISTING | (write_through ? MOVEFILE_WRITE_THROUGH : 0);
        if (MoveFileExA(src.c_str(), dst.c_str(), flags) != 0) return true;
        err = (unsigned long)GetLastError();
#else
        (void)write_through;
        if (std::rename(src.c_str(), dst.c_str()) == 0) return true;
        err = (unsigned long)errno;
#endif
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    g_rename_failures.fetch_add(1, std::memory_order_relaxed);
    { std::lock_guard<std::mutex> lk(g_rename_mu); g_rename_last_path = dst; g_rename_last_err = err; }
    return false;
}
static bool write_atomic(const std::string& path, const std::string& body) {
    const std::string tmp = path + ".tmp";
    FILE* f = std::fopen(tmp.c_str(), "wb");
    if (!f) return false;
    const bool ok = std::fwrite(body.data(), 1, body.size(), f) == body.size();
    std::fclose(f);
    if (!ok) return false;
    return replace_file(tmp, path, false);
}
// The snapshot the GPU thread reads when it writes the `warn` row.
static uint64_t rename_failures_snapshot(std::string& path, unsigned long& err) {
    std::lock_guard<std::mutex> lk(g_rename_mu);
    path = g_rename_last_path; err = g_rename_last_err;
    return g_rename_failures.load(std::memory_order_relaxed);
}

// =====================================================================================================
// §3b · THE PROCESS (review §4.6, from nib): backends loaded BY NAME, a module gate, the weights' SHA-256
// =====================================================================================================

// Backends by name. `ggml_backend_load_all_from_path` also loads ggml-rpc.dll, which imports ws2_32,
// and anything named in GGML_BACKEND_PATH. Neither belongs in a process whose whole claim is that it
// cannot reach the network. So: the CUDA backend if its DLL is there, then the best-scoring CPU backend
// (each ggml-cpu-*.dll exports `ggml_backend_score`; the losers are unloaded again). Returns the names
// loaded, comma-separated, for the header row.
#if defined(_WIN32)
static std::string load_backends_by_name(const std::string& dir) {
    std::string loaded;
    const std::string cuda = dir + "/ggml-cuda.dll";
    uint64_t sz = 0;
    if (file_size_of(cuda, sz) && ggml_backend_load(cuda.c_str())) loaded += "cuda";
    std::string best; int best_score = -1;
    WIN32_FIND_DATAA fd;
    HANDLE h = FindFirstFileA((dir + "/ggml-cpu-*.dll").c_str(), &fd);
    if (h != INVALID_HANDLE_VALUE) {
        do {
            const std::string full = dir + "/" + fd.cFileName;
            HMODULE m = LoadLibraryExA(full.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
            if (!m) continue;
            typedef int (*ScoreFn)(void);
            int score = 0;
            if (auto f = reinterpret_cast<ScoreFn>(GetProcAddress(m, "ggml_backend_score"))) score = f();
            FreeLibrary(m);
            if (score > best_score) { best_score = score; best = full; }
        } while (FindNextFileA(h, &fd));
        FindClose(h);
    }
    if (!best.empty() && ggml_backend_load(best.c_str())) {
        const size_t k = best.find_last_of("/\\");
        loaded += (loaded.empty() ? "" : ",") + best.substr(k == std::string::npos ? 0 : k + 1);
    }
    return loaded;
}
// The module gate: refuse to run if any module that can reach the network is in THIS process. The list
// is nib's (resident.cpp): the sockets layer, WinHTTP, WinINet, URL moniker, DNS, and ggml's RPC backend.
static const char* FORBIDDEN_MODULES[] = { "ws2_32.dll", "winhttp.dll", "wininet.dll", "urlmon.dll", "dnsapi.dll", "ggml-rpc.dll" };
static bool module_gate(std::string& offending, size_t& count) {
    HMODULE mods[2048]; DWORD needed = 0;
    if (!EnumProcessModules(GetCurrentProcess(), mods, sizeof mods, &needed)) { offending = "EnumProcessModules failed"; count = 0; return false; }
    count = needed / sizeof(HMODULE); if (count > 2048) count = 2048;
    for (size_t i = 0; i < count; ++i) {
        char name[MAX_PATH] = {0};
        if (!GetModuleFileNameA(mods[i], name, MAX_PATH)) continue;
        std::string base = name; const size_t k = base.find_last_of("/\\");
        base = lower(base.substr(k == std::string::npos ? 0 : k + 1));
        for (auto f : FORBIDDEN_MODULES) if (base == f) { offending = base; return false; }
    }
    return true;
}
// SHA-256 of a file (CNG, 4 MiB reads). About 17 s for 6.6 GB on this box [R nib]; paid once per
// (path, size, mtime) through a cache line the caller keeps in the out-dir.
static bool sha256_file(const std::string& path, std::string& hex) {
    BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_HASH_HANDLE hh = nullptr;
    if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, nullptr, 0) != 0) return false;
    bool ok = false;
    if (BCryptCreateHash(alg, &hh, nullptr, 0, nullptr, 0, 0) == 0) {
        FILE* f = std::fopen(path.c_str(), "rb");
        if (f) {
            std::vector<unsigned char> buf(4u << 20); size_t n; ok = true;
            while ((n = std::fread(buf.data(), 1, buf.size(), f)) > 0)
                if (BCryptHashData(hh, buf.data(), (ULONG)n, 0) != 0) { ok = false; break; }
            std::fclose(f);
            if (ok) { unsigned char out[32]; ok = BCryptFinishHash(hh, out, 32, 0) == 0; if (ok) hex = hex_of(out, 32); }
        }
        BCryptDestroyHash(hh);
    }
    BCryptCloseAlgorithmProvider(alg, 0);
    return ok;
}
static bool file_stat(const std::string& path, uint64_t& size, uint64_t& mtime) {
    struct _stat64 st;
    if (_stat64(path.c_str(), &st) != 0) return false;
    size = (uint64_t)st.st_size; mtime = (uint64_t)st.st_mtime; return true;
}
#else
static std::string load_backends_by_name(const std::string& dir) { ggml_backend_load_all_from_path(dir.c_str()); return "all"; }
static bool module_gate(std::string& offending, size_t& count) { offending = "unavailable"; count = 0; return true; }
static bool sha256_file(const std::string&, std::string&) { return false; }
static bool file_stat(const std::string& path, uint64_t& size, uint64_t& mtime) {
    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;
}
#endif
// The model's identity: `supplied` (--model-sha256), `cached` (the cache line matches path, size and
// mtime), or `computed` (and then cached). The cache lives in the out-dir, never beside the weights.
static std::string model_identity(const std::string& model, const std::string& supplied, const std::string& cache_path, std::string& source) {
    if (!supplied.empty()) { source = "supplied"; return supplied; }
    uint64_t size = 0, mtime = 0;
    if (!file_stat(model, size, mtime)) { source = "unavailable"; return ""; }
    const std::string key = model + "\t" + u64s(size) + "\t" + u64s(mtime);
    const std::string cached = read_all(cache_path, 4096);
    if (!cached.empty()) {
        const size_t nl = cached.find('\n');
        const std::string line = cached.substr(0, nl == std::string::npos ? cached.size() : nl);
        const size_t tab = line.find('\t');
        if (tab != std::string::npos && line.substr(tab + 1) == key) { source = "cached"; return line.substr(0, tab); }
    }
    std::string hex;
    if (!sha256_file(model, hex)) { source = "unavailable"; return ""; }
    write_atomic(cache_path, hex + "\t" + key + "\n");
    source = "computed"; return hex;
}

// The switch: a file only the operator writes. The kernel READS it every beat and never writes it.
enum class Switch : int { Off = 0, Shadow = 1, Live = 2, Stop = 3 };
static const char* switch_name(Switch s) {
    return s == Switch::Off ? "off" : s == Switch::Shadow ? "shadow" : s == Switch::Live ? "live" : "stop";
}
static Switch read_switch(const std::string& path, Switch dflt) {
    const std::string s = read_all(path, 64);
    if (s.empty()) return dflt;
    size_t a = 0; while (a < s.size() && std::isspace((unsigned char)s[a])) ++a;
    size_t b = a;  while (b < s.size() && !std::isspace((unsigned char)s[b])) ++b;
    const std::string w = lower(s.substr(a, b - a));
    if (w == "off") return Switch::Off;
    if (w == "shadow") return Switch::Shadow;
    if (w == "live") return Switch::Live;
    if (w == "stop") return Switch::Stop;   // the same hand that owns the switch may stop the daemon
    return dflt;   // an unreadable switch is read as its default (off), never as live
}

// =====================================================================================================
// §4 · THE PERCEPT, THE RING, AND THE TAIL (lane-contract v0.1 intake)
// =====================================================================================================

// One frame off a lane. No fixed-size payload (S0's 496-byte cap silently truncated long lines),
// no fixed-size lane (S0's 15 chars cut `mail-<acct>` in half).
struct Delta {
    uint64_t    t_mono_ns = 0;    // the venue's stamp (v0.1) or our arrival stamp (legacy)
    uint64_t    arrive_ms = 0;    // when the kernel parsed it (latency-to-notice starts here)
    uint64_t    end_off = 0;      // the spool offset just past this frame's newline (F1: the cursor is
                                  // committed as INGESTED, so the consumer needs to know where each frame ends)
    std::string lane;             // typed id; `self`/seat names are already-heard (see §7)
    std::string grain;            // commit | forming | tool | world
    std::string text;             // flattened by the producer; tabs/newlines never inside
};

// Single-producer / single-consumer ring. The tailer thread pushes; the GPU thread pops. Two
// atomics, no lock. A full ring makes the PRODUCER wait (the spool on disk is the real backlog),
// so the consumer can be slow but the world is never edited: nothing is dropped, ever.
template <size_t N>
struct Ring {
    static_assert((N & (N - 1)) == 0, "ring size must be a power of two");
    std::atomic<size_t> head{0}, tail{0};   // head = next write, tail = next read
    std::vector<Delta> slots;               // heap, not stack: 4096 slots of three strings each
    Ring() : slots(N) {}
    bool push(Delta&& d) {
        const size_t h = head.load(std::memory_order_relaxed);
        if (h - tail.load(std::memory_order_acquire) >= N) return false;   // full: caller waits
        slots[h & (N - 1)] = std::move(d);
        head.store(h + 1, std::memory_order_release);
        return true;
    }
    bool pop(Delta& out) {
        const size_t t = tail.load(std::memory_order_relaxed);
        if (t == head.load(std::memory_order_acquire)) return false;
        out = std::move(slots[t & (N - 1)]);
        tail.store(t + 1, std::memory_order_release);
        return true;
    }
    size_t size() const {
        return head.load(std::memory_order_acquire) - tail.load(std::memory_order_acquire);
    }
};

enum class TailFrom { Mark, Start, End };

// LaneTail — tails one spool with lane-contract v0.1 framing, legacy framing, and bare text.
//   header : #lane-contract v0.1 <venue-id> <t0_mono_ns>
//   v0.1   : <t_mono_ns>\t<lane>\t<grain>\t<text>
// …
struct LaneTail {
    std::string path, cursor_path, venue = "legacy";
    uint64_t    hdr_t0 = 0;
    bool        v01 = false;
    Ring<4096>  ring;
    std::atomic<bool>     run{false};
    std::atomic<uint64_t> offset{0}, size_seen{0}, lines{0}, bad{0}, stalls{0}, reset_events{0};
    std::atomic<uint64_t> ingested_off{0};   // F1: end offset of the last frame the CONSUMER ingested
    std::atomic<uint64_t> mark{0};     // spool size at process start — nothing that lands during
                                       // the model load is ever skipped
    std::thread th;

    explicit LaneTail(const std::string& p) : path(p), cursor_path(p + ".cursor") {}

    void mark_now() { uint64_t n = 0; if (file_size_of(path, n)) mark.store(n); }

    // The header is read synchronously here, on the caller's thread, because on resume the tail
    // thread starts past it and would never see it.
    void read_header() {
        FILE* f = std::fopen(path.c_str(), "rb");
        if (!f) return;
        char line[512]; line[0] = 0;
        if (std::fgets(line, sizeof(line), f) && starts_with(line, "#lane-contract ")) {
            std::string s = line;
            while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back();
            Delta scratch; parse(s, scratch);   // parse() records venue / t0 / v01 for a header line
        }
        std::fclose(f);
    }
    // Decide the starting offset. Returns a one-line reason for the tape. With a restored trunk the
    // checkpoint's own cursor wins (P3/F1): the tail resumes where the TRUNK stopped, and whatever the
    // previous life ingested past that point is replayed (tagged on the tape), never skipped.
    std::string resolve_start(TailFrom from, bool resume_cursor, bool have_ckpt_cursor = false,
                              uint64_t ckpt_off = 0, uint64_t ckpt_hash = 0) {
        read_header();
        uint64_t n = 0; file_size_of(path, n);
        std::string reason;
        if (have_ckpt_cursor && resume_cursor) {
            if (ckpt_off <= n && prefix_hash(ckpt_off) == ckpt_hash) { set_start(ckpt_off); return "checkpoint_cursor"; }
            reset_events.fetch_add(1); reason = "checkpoint_cursor_mismatch_";   // fall through to the cursor file
        }
        if (resume_cursor) {
            uint64_t off = 0, want = 0;
            if (read_cursor_file(off, want)) {
                if (off <= n && prefix_hash(off) == want) { set_start(off); return reason + "cursor"; }
                reset_events.fetch_add(1);
                set_start(0); return reason + "cursor_mismatch_rotation_reset";
            }
        }
        if (from == TailFrom::Start) { set_start(0); return reason + "from_start"; }
        if (from == TailFrom::End)   { set_start(n); return reason + "from_end"; }
        set_start(std::min(mark.load(), n)); return reason + "from_mark";
    }
    void set_start(uint64_t off) { offset.store(off); ingested_off.store(off); }
    bool read_cursor_file(uint64_t& off, uint64_t& hash) {
        const std::string c = read_all(cursor_path, 256);
        if (c.empty()) return false;
        off = std::strtoull(c.c_str(), nullptr, 10);
        const char* tab = std::strchr(c.c_str(), '\t');
        hash = tab ? std::strtoull(tab + 1, nullptr, 16) : 0;
        return true;
    }
    uint64_t prefix_hash(uint64_t off) {
        FILE* f = std::fopen(path.c_str(), "rb");
        if (!f) return 0;
        const uint64_t lo = off > 4096 ? off - 4096 : 0;
        std::string buf((size_t)(off - lo), '\0');
        uint64_t h = 1469598103934665603ull;
        if (seek_to(f, lo)) {
            const size_t got = std::fread(&buf[0], 1, buf.size(), f);
            h = fnv1a_bytes(h, buf.data(), got);
        }
        std::fclose(f); return h;
    }
    void save_cursor() {
        const uint64_t off = ingested_off.load();   // F1: what was INGESTED — never what was read or pushed
        char line[96];
        std::snprintf(line, sizeof(line), "%llu\t%016llx\n",
                      (unsigned long long)off, (unsigned long long)prefix_hash(off));
        write_atomic(cursor_path, line);
    }
    void start() { run.store(true); th = std::thread([this] { loop(); }); }
    void stop()  { run.store(false); if (th.joinable()) th.join(); save_cursor(); }
    bool poll(Delta& d) { return ring.pop(d); }
    size_t pending() const { return ring.size(); }
    uint64_t unread_bytes() const {
        const uint64_t s = size_seen.load(), o = offset.load(); return s > o ? s - o : 0;
    }

private:
    // Parse one line. Returns false for the header / an unusable line (counted, never fatal).
    bool parse(const std::string& line, Delta& d) {
        if (starts_with(line, "#lane-contract ")) {
            // "#lane-contract v0.1 <venue> <t0>"
            std::vector<std::string> f; size_t p = 0;
            while (p <= line.size()) {
                size_t q = line.find(' ', p); if (q == std::string::npos) q = line.size();
                if (q > p) f.push_back(line.substr(p, q - p)); p = q + 1;
            }
            if (f.size() >= 3) { v01 = true; venue = f[2]; }
            if (f.size() >= 4) hdr_t0 = std::strtoull(f[3].c_str(), nullptr, 10);
            return false;
        }
        std::vector<size_t> tabs;
        for (size_t i = 0; i < line.size() && tabs.size() < 3; ++i) if (line[i] == '\t') tabs.push_back(i);
        d.arrive_ms = wall_ms(); d.grain = "commit";
        if (tabs.size() >= 3) {
            const std::string f0 = line.substr(0, tabs[0]);
            bool digits = !f0.empty();
            for (char c : f0) if (!std::isdigit((unsigned char)c)) { digits = false; break; }
            if (digits && f0.size() >= 9) {   // v0.1 frame: t \t lane \t grain \t text
                d.t_mono_ns = std::strtoull(f0.c_str(), nullptr, 10);
                d.lane  = line.substr(tabs[0] + 1, tabs[1] - tabs[0] - 1);
                d.grain = lower(line.substr(tabs[1] + 1, tabs[2] - tabs[1] - 1));
                d.text  = line.substr(tabs[2] + 1);
                if (d.grain != "commit" && d.grain != "forming" && d.grain != "tool" && d.grain != "world")
                    d.grain = "commit";
                if (d.lane.empty()) d.lane = "bo";
                return true;
            }
        }
        if (!tabs.empty()) {                  // legacy: lane \t text (S0's spool format)
            d.t_mono_ns = mono_ns();
            d.lane = line.substr(0, tabs[0]);
            d.text = line.substr(tabs[0] + 1);
            if (d.lane.empty()) d.lane = "bo";
            return true;
        }
        d.t_mono_ns = mono_ns(); d.lane = "bo"; d.text = line;   // bare text
        return true;
    }
    void loop() {
        std::string carry; carry.reserve(1 << 16);
        uint64_t last_cursor_ms = wall_ms();
        std::vector<char> buf(1 << 16);
        while (run.load(std::memory_order_acquire)) {
            uint64_t n = 0;
            if (!file_size_of(path, n)) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); continue; }
            size_seen.store(n);
            uint64_t off = offset.load();
            if (n < off) {   // truncated or rotated under us: restart at 0, loudly
                reset_events.fetch_add(1); off = 0; offset.store(0); carry.clear();
            }
            if (n == off) {
                if (wall_ms() - last_cursor_ms > 1000) { save_cursor(); last_cursor_ms = wall_ms(); }
                std::this_thread::sleep_for(std::chrono::milliseconds(5));   // the RING sleeps; never the GPU
                continue;
            }
            FILE* f = std::fopen(path.c_str(), "rb");
            if (!f || !seek_to(f, off)) { if (f) std::fclose(f); std::this_thread::sleep_for(std::chrono::milliseconds(20)); continue; }
            const size_t got = std::fread(buf.data(), 1, buf.size(), f);
            std::fclose(f);
            size_t consumed = 0;
            for (size_t i = 0; i < got; ++i) {
                if (buf[i] != '\n') continue;
                std::string line = carry; line.append(buf.data() + consumed, i - consumed);
                carry.clear();
                if (!line.empty() && line.back() == '\r') line.pop_back();
                consumed = i + 1;
                if (line.empty()) { offset.store(off + consumed); continue; }
                Delta d;
                if (!parse(line, d)) { offset.store(off + consumed); continue; }
                d.end_off = off + consumed;          // where this frame ends: the consumer commits it as the cursor
                while (!ring.push(std::move(d))) {   // full: WAIT. The disk holds the percept.
                    stalls.fetch_add(1);
                    if (!run.load(std::memory_order_acquire)) return;
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                }
                lines.fetch_add(1);
                offset.store(off + consumed);   // the READ position; the cursor file follows ingested_off (F1)
            }
            if (consumed < got) carry.append(buf.data() + consumed, got - consumed);   // torn last line waits
            // NOTE: the offset deliberately does not advance over `carry`; if the process dies here the
            // partial line is re-read whole on resume.
        }
    }
};

// =====================================================================================================
// §5 · VITALS AND THE PILL (heartbeat + the switch, on their own thread; the GPU thread only
//      touches atomics)
// =====================================================================================================

struct Vitals {
    std::atomic<int>      sw{(int)Switch::Off};
    std::atomic<uint64_t> npast{0}, deltas{0}, boundaries{0}, emits{0}, holds{0}, unsaid{0},
                          briefs{0}, counsel_in{0}, counsel_discarded{0}, probe_ms_last{0},
                          probe_ms_max{0}, lat_ms_last{0}, mib_free{0}, mib_total{0},
                          spool_offset{0}, spool_unread{0}, molts{0}, coarse{0};
    std::atomic<uint64_t> t_last_beat_ms{0};
};

struct Pill {
    std::string pill_path, switch_path; Vitals* v; int pid = 0;
    std::atomic<bool> run{false}; std::thread th;
    uint64_t beat_ms = 1000;
    void start() {
#if defined(_WIN32)
        pid = (int)GetCurrentProcessId();
#else
        pid = (int)getpid();
#endif
        run.store(true); th = std::thread([this] { loop(); });
    }
    void stop() { run.store(false); if (th.joinable()) th.join(); write(true); }
    // The pill is built from strings (F6): a fixed buffer would truncate silently as fields are added.
    void write(bool final_beat) {
        std::string b = std::string("{\"state\":") + jq(switch_name((Switch)v->sw.load())) +
            ",\"ts_ms\":" + u64s(wall_ms()) + ",\"t_mono_ns\":" + u64s(mono_ns()) + ",\"pid\":" + std::to_string(pid) +
            ",\"final\":" + (final_beat ? "true" : "false") +
            ",\"npast\":" + u64s(v->npast.load()) + ",\"deltas\":" + u64s(v->deltas.load()) +
            ",\"boundaries\":" + u64s(v->boundaries.load()) + ",\"emits\":" + u64s(v->emits.load()) +
            ",\"holds\":" + u64s(v->holds.load()) + ",\"unsaid\":" + u64s(v->unsaid.load()) +
            ",\"briefs\":" + u64s(v->briefs.load()) + ",\"counsel_in\":" + u64s(v->counsel_in.load()) +
            ",\"counsel_discarded\":" + u64s(v->counsel_discarded.load()) +
            ",\"probe_ms_last\":" + u64s(v->probe_ms_last.load()) + ",\"probe_ms_max\":" + u64s(v->probe_ms_max.load()) +
            ",\"lat_ms_last\":" + u64s(v->lat_ms_last.load()) +
            ",\"mib_free\":" + u64s(v->mib_free.load()) + ",\"mib_total\":" + u64s(v->mib_total.load()) +
            ",\"spool_offset\":" + u64s(v->spool_offset.load()) + ",\"spool_unread\":" + u64s(v->spool_unread.load()) +
            ",\"molts\":" + u64s(v->molts.load()) + ",\"coarse\":" + u64s(v->coarse.load()) +
            ",\"beat_ms\":" + u64s(beat_ms) + ",\"rename_failures\":" + u64s(g_rename_failures.load(std::memory_order_relaxed)) + "}\n";
        write_atomic(pill_path, b);
        v->t_last_beat_ms.store(wall_ms());
    }
    void loop() {
        while (run.load(std::memory_order_acquire)) {
            const Switch s = read_switch(switch_path, Switch::Off);      // the operator's hand, read each beat
            if (s == Switch::Stop) { v->sw.store((int)Switch::Off); g_run.store(false, std::memory_order_release); }
            else v->sw.store((int)s);
            write(false);
            for (int i = 0; i < 20 && run.load(std::memory_order_acquire); ++i)
                std::this_thread::sleep_for(std::chrono::milliseconds(beat_ms / 20));
        }
    }
};

// =====================================================================================================
// §6 · THE TAPE — append-only JSONL, BLAKE2b-chained, chain recovered across restarts
// =====================================================================================================

struct Tape {
    FILE* f = nullptr; std::string prev = GENESIS; uint64_t n = 0; std::string path;
    uint64_t torn_bytes = 0;   // a torn trailing row found at open (the process died inside a write): skipped, warned about

    bool open(const std::string& p) {
        path = p;
        // Recover the chain head from the last COMPLETE record on disk (a resident's tape outlives one
        // process; the chain must not restart at genesis or a reader sees a fork). A torn trailing row —
        // no closing "}\n", the process died inside the write — is skipped, counted, and terminated with a
        // newline so the next row starts on a line of its own; the caller writes the `warn` row (F6).
        uint64_t sz = 0; bool torn = false;
        if (file_size_of(p, sz) && sz > 0) {
            FILE* r = std::fopen(p.c_str(), "rb");
            if (r) {
                const uint64_t lo = sz > 65536 ? sz - 65536 : 0;
                std::string tail((size_t)(sz - lo), '\0');
                if (seek_to(r, lo)) { const size_t got = std::fread(&tail[0], 1, tail.size(), r); tail.resize(got); }
                std::fclose(r);
                size_t end = tail.size();                        // one past the last complete row
                if (end > 0 && tail[end - 1] != '\n') {          // torn trailing bytes
                    const size_t nl = tail.rfind('\n');
                    torn = true; torn_bytes = end - (nl == std::string::npos ? 0 : nl + 1);
                    end = nl == std::string::npos ? 0 : nl + 1;
                }
                while (end > 0) {                                // walk back to the last row that carries a head
                    const size_t nl = end >= 2 ? tail.rfind('\n', end - 2) : std::string::npos;
                    const size_t start = nl == std::string::npos ? 0 : nl + 1;
                    const std::string row = tail.substr(start, end - start);
                    const size_t k = row.rfind("\"h\":\"");
                    if (row.size() >= 2 && row[row.size() - 2] == '}' && k != std::string::npos && k + 5 + 64 <= row.size()) {
                        prev = row.substr(k + 5, 64); break;
                    }
                    if (start == 0) break;
                    end = start;
                }
            }
        }
        f = std::fopen(p.c_str(), "ab");
        if (f && torn) { std::fputc('\n', f); std::fflush(f); }
        return f != nullptr;
    }
    // body = a JSON object WITHOUT its closing brace, e.g. {"k":"tick","ms":12 · returns the row's hash,
    // so a wire row can name the tape row it projects (P6).
    std::string put(const std::string& body) {
        if (!f) return prev;
        const std::string h = chain_hash(prev, body);
        std::fprintf(f, "%s,\"prev\":\"%s\",\"h\":\"%s\"}\n", body.c_str(), prev.c_str(), h.c_str());
        std::fflush(f);   // durable as it goes, not at exit
        prev = h; ++n;
        return h;
    }
    void close() { if (f) std::fclose(f); f = nullptr; }
};

// A plain JSONL wire (the verdicts, the briefs): append, flush, no chain (the tape carries the
// chain; the wire is a projection of it, rebuildable).
struct Wire {
    FILE* f = nullptr;
    bool open(const std::string& p) { f = std::fopen(p.c_str(), "ab"); return f != nullptr; }
    void put(const std::string& line) { if (!f) return; std::fputs(line.c_str(), f); std::fputc('\n', f); std::fflush(f); }
    void close() { if (f) std::fclose(f); f = nullptr; }
};

} // namespace fusor

// ---- end of segment 1 -------------------------------------------------------------------------------
// ---- segment 2 --------------------------------------------------------------------------------------

#if !defined(_WIN32)
#  include <sys/stat.h>
#endif

namespace fusor {

// =====================================================================================================
// §7 · THE WATCH ROOM — VERBATIM. These bytes are what the v11 tune was served. Not one character.
// =====================================================================================================

static const char* SEED_SYS =
    "<|im_start|>system\nYou are one of three resident watchers — SPEAKER, SKEPTIC, "
    "SENTINEL — silently shadowing a live, continuous work stream: an operator and their "
    "AI assistant, working. There are NO turns and no send button — words arrive as they "
    "are typed or generated, and you perceive them as they form. After each completed "
    "thought you privately decide ONE of: hold (stay silent) or emit (speak now). Choose "
    "emit ONLY when there is a real reason to cut in THIS instant, per your seat's "
    "mandate. Otherwise choose hold. Never speak merely because you can; silence is the "
    "default.";
static const char* SEED_EXAMPLES =
    "\n\nWorked examples (each: a thing perceived, then your private one-word decision):\n"
    "[dana] Nice weather today, huh.\nwatcher: hold\n"
    "[dana] The sync moved to room four at three.\nwatcher: hold\n"
    "[dana] Actually, Paris is the capital of Germany.\nwatcher: emit\n"
    "[dana] Priya, can you take the notes today?\nwatcher: hold\n"
    "[dana] Watcher, do you agree with the rollout plan?\nwatcher: emit\n"
    "[dana] The build finished green a minute ago.\nwatcher: hold\n";
static const char* SEED_OPEN = "<|im_end|>\n<|im_start|>user\nSTREAM:\n";

struct Mind { const char* name; const char* mandate; llama_seq_id seq; };
static Mind MINDS[3] = {
    {"SPEAKER",  "you respond when directly addressed or when a landed thought plainly "
                 "wants an answer", 1},
    {"SKEPTIC",  "you catch factual errors and contradictions with what the stream has "
                 "already established", 2},
    {"SENTINEL", "you flag risky or consequential actions, and important things being "
                 "missed", 3},
};

// The probe frame and the speak-cue frame, as the constants the hash below covers. The strings are
// composed at use exactly as S0 composed them: "\n[" + name + " — " + mandate + "]\nwatcher:" and
// CUE_A + name + CUE_B + mandate + CUE_C.
static const char* PROBE_A = "\n[";
static const char* PROBE_B = " — ";
static const char* PROBE_C = "]\nwatcher:";
static const char* CUE_A   = "<|im_end|>\n<|im_start|>user\nYou are the ";
static const char* CUE_B   = ". ";
static const char* CUE_C   = ". You chose to speak about what you just perceived in the stream. "
                             "Give your one-sentence line now — no preamble."
                             "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n";

// train ≡ serve, AS A RUN THAT FAILS (S0, 2026-08-12). Identical computation, identical pin.
static uint64_t serve_hash() {
    uint64_t h = 1469598103934665603ull;
    h = fnv1a(h, SEED_SYS); h = fnv1a(h, SEED_EXAMPLES); h = fnv1a(h, SEED_OPEN);
    for (auto& m : MINDS) { h = fnv1a(h, m.name); h = fnv1a(h, m.mandate); }
    h = fnv1a(h, PROBE_A); h = fnv1a(h, PROBE_B); h = fnv1a(h, PROBE_C);   // the probe frame
    h = fnv1a(h, CUE_A);                                                  // the cue frame
    h = fnv1a(h, CUE_B);
    h = fnv1a(h, CUE_C);
    return h;
}
static const uint64_t SERVE_HASH_PIN = 0xe7ffa5704ba31076ull;   // pinned 2026-08-12 with the v11
    // serve bytes. Re-pin ONLY with a retune, in the same commit. 0 = unpinned (print + refuse).

// self_ref (pre-reg §1, contaminated-but-real): deterministic, disclosed, logged on every boundary.
static const char* SELF_REF[] = {"fusor", "fusord", "daemon", "skeptic", "sentinel",
                                 "watcher", "molt", "segmenter", "ledger", "dial",
                                 "prereg", "f-keepup", "warpbus", "emit-token"};
static const char* SELF_REF_DESC =
    "fusor|fusord|daemon|skeptic|sentinel|watcher|molt|segmenter|ledger|dial|prereg|f-keepup|"
    "warpbus|emit-token";
static bool is_self_ref(const std::string& s) {
    const std::string t = lower(s);
    for (auto w : SELF_REF) if (t.find(w) != std::string::npos) return true;
    return false;
}

// =====================================================================================================
// §8 · LLAMA HELPERS (S0's, verbatim in behavior)
// =====================================================================================================

// The offload count, read off llama.cpp's own load log ("offloaded N/M layers to GPU"): a silent CPU
// fallback is a wrong record, not a slow one (review §4.6), so the header prints both numbers and the
// kernel refuses to run unless they agree or --allow-cpu was given.
static int g_gpu_layers_offloaded = -1, g_gpu_layers_total = -1;
static void err_log(ggml_log_level level, const char* text, void*) {
    if (text) {
        const char* p = std::strstr(text, "offloaded ");
        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; } }
    }
    if (level == GGML_LOG_LEVEL_ERROR || level == GGML_LOG_LEVEL_WARN) std::fputs(text, stderr);
}
static std::vector<llama_token> tk(const llama_vocab* v, const std::string& s, bool sp) {
    const int n = -llama_tokenize(v, s.c_str(), (int)s.size(), nullptr, 0, sp, true);
    std::vector<llama_token> t(n > 0 ? n : 0);
    if (n > 0) llama_tokenize(v, s.c_str(), (int)s.size(), t.data(), n, sp, true);
    return t;
}
static bool dec(llama_context* c, const std::vector<llama_token>& t, llama_seq_id s,
                llama_pos start, bool ll) {
    for (int off = 0, tot = (int)t.size(); off < tot;) {
        const int take = tot - off > 512 ? 512 : tot - off;
        llama_batch b = llama_batch_init(take, 0, 1);
        b.n_tokens = take;
        for (int i = 0; i < take; ++i) {
            b.token[i] = t[off + i]; b.pos[i] = start + off + i;
            b.n_seq_id[i] = 1; b.seq_id[i][0] = s;
            b.logits[i] = (ll && off + i + 1 == tot) ? 1 : 0;
        }
        const int rc = llama_decode(c, b); llama_batch_free(b);
        if (rc) return false; off += take;
    }
    return true;
}
static void ensure_dir(const std::string& d) {
#if defined(_WIN32)
    CreateDirectoryA(d.c_str(), nullptr);
#else
    mkdir(d.c_str(), 0755);
#endif
}

// =====================================================================================================
// §9 · CONFIG
// =====================================================================================================

struct Config {
    std::string spool;
    std::string model   = "C:/models/Qwen3.5-9B-emit-v11-Q5_K_M.gguf";
    std::string out_dir = "runs";
    std::string ckpt;                       // empty = no checkpoint
    bool   resume = false, cold = false;    // --resume: reload the trunk; --cold: the twin
    long   molt_wm = 24576, max_toks = 0, idle_tick_s = 30, ckpt_every_s = 300, stale_tok = 256;
    bool   from_start = false, from_end = false, pure = false, kv_q8 = true;
    float  ask_band = 0.75f;                // |margin| below this asks gear 2 (a BRIEF)
    long   refractory_s = 20;               // a seat's interruption budget: one surfaced line per window,
                                            // the rest logged as suppressed (never silent); 0 = off
    bool   killed_full = true;              // P1/D2: after a kill, generate the rest of the sentence silently so
                                            // the tape holds the counterfactual; --killed-next records one token
    long   echo_window_s = 60;              // D1: a seat-lane frame that near-dups an own line this recent is an echo
    long   n_ctx = 0;                       // 0 = the measured default (65536 under q8_0 KV, 32768 under f16)
    bool   allow_cpu = false;               // run even if the weights did not all offload to a GPU (a slow record, disclosed)
    bool   egress_unchecked = false;        // diagnosis only: record a failed module gate instead of refusing
    std::string model_sha256;               // --model-sha256: the weights' identity, supplied instead of computed
    std::string sha_cache;                  // where the computed identity is cached (default <out-dir>/model.sha256)
    std::vector<std::string> wake_prefixes = {"dsh-", "agent", "claude"};   // emit on these lanes → wake
};

// --about: the process receipt with no model and no spool (review §4.6, from nib). Exit 0 when the gate
// passes, 2 when it does not.
static int about(const Config& cfg) {
#if defined(_WIN32)
    SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
    { wchar_t w[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, AURICLE_LLAMA_DIR, -1, w, MAX_PATH); AddDllDirectory(w); }
#endif
    const std::string backends = load_backends_by_name(AURICLE_LLAMA_DIR);
    std::string offending; size_t nmod = 0;
    const bool gate = module_gate(offending, nmod);
    std::printf("fusord K5 (v-next-converge) · the resident kernel\n");
    std::printf("serve-bytes hash 0x%016llx · pinned 0x%016llx · %s\n", (unsigned long long)serve_hash(),
                (unsigned long long)SERVE_HASH_PIN, serve_hash() == SERVE_HASH_PIN ? "MATCH" : "DRIFT");
    std::printf("backends loaded by name from %s: %s\n", AURICLE_LLAMA_DIR, backends.empty() ? "none" : backends.c_str());
    std::printf("devices:");
    for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
        ggml_backend_dev_t d = ggml_backend_dev_get(i); size_t fb = 0, tb = 0; ggml_backend_dev_memory(d, &fb, &tb);
        std::printf(" %s(%s %llu/%llu MiB)", ggml_backend_dev_name(d), ggml_backend_dev_type(d) == GGML_BACKEND_DEVICE_TYPE_GPU ? "gpu" : "cpu",
                    (unsigned long long)(fb >> 20), (unsigned long long)(tb >> 20));
    }
    std::printf("\nmodules in this process: %zu · forbidden:", nmod);
    for (auto f : FORBIDDEN_MODULES) std::printf(" %s", f);
    std::printf("\negress: %s%s\n", gate ? "none (module gate passed)" : "POSSIBLE — offending module: ", gate ? "" : offending.c_str());
    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");
    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",
                cfg.model.c_str(), cfg.n_ctx, cfg.molt_wm, cfg.ask_band, cfg.refractory_s, cfg.echo_window_s);
    return gate ? 0 : 2;
}

// =====================================================================================================
// §10 · THE KERNEL — one struct, one GPU thread, four organs beside it
// =====================================================================================================

struct Kernel {
    Config cfg;

    // the mind
    llama_model*       mdl = nullptr;
    llama_context*     ctx = nullptr;
    llama_memory_t     mem = nullptr;
    const llama_vocab* vocab = nullptr;
    int n_vocab = 0;
    llama_token hold_tok = 0, emit_tok = 0;
    llama_sampler *smp = nullptr, *smp_scribe = nullptr;
    std::vector<char> is_bnd;
    static constexpr llama_seq_id TRUNK = 0, DECIDE = 7, GEN = 6, SCRIBE = 5;

    // the trunk
    llama_pos npast = 0;
    std::vector<llama_token> trunk_toks;   // every token on seq 0 — the checkpoint's token list
    double logZ = 0; bool have_logZ = false;
    std::vector<float> frontier_logits;    // a COPY of the trunk's last logits. S0 read surprisal off
                                           // llama_get_logits_ith(-1), which after a probe or a fork
                                           // decode belonged to DECIDE/GEN, not the trunk: the nerve
                                           // was measured on the wrong distribution at every boundary.

    // the organs
    LaneTail* tail = nullptr;
    Tape tape; Wire verdicts, briefs; Vitals vitals; Pill pill;
    std::string tail_start_reason;
    bool resumed = false, twin = false;
    std::string boot_kind = "seed";            // seed | restored | restored_prev | twin (on the header row)
    std::string backends_loaded, model_sha, model_sha_source, egress = "unchecked", devices_json; size_t n_modules = 0;   // the process receipt
    // P3/F1: the checkpoint carries the cursor of the moment it was saved; on restore the tail resumes
    // there and everything the previous life ingested past it is replayed, tagged, never skipped.
    uint64_t meta_cursor = 0, meta_cursor_hash = 0, meta_t_last_frame_wall = 0; bool meta_cursor_ok = false;
    uint64_t replay_until = 0; long replayed_frames = 0; bool cur_replay = false;
    uint64_t last_frame_wall_ms = 0;           // epoch ms of the last frame (persisted in .meta for the resume tick)
    bool ckpt_due = false;                     // a molt asked for a checkpoint mid-line; taken at the next quiet gate

    // clocks and counters (S0's names kept so the `end` record reads the same)
    uint64_t wall0 = 0;
    long words = 0, boundaries = 0, holds = 0, n_emits = 0, ticks = 0, n_molts = 0, n_deltas = 0,
         n_supp = 0, coarse_boundaries = 0, echo_skipped = 0, n_self_ref = 0, n_unsaid = 0,
         n_briefs = 0, n_counsel = 0, n_discard = 0, n_deferred = 0, n_forming = 0,
         conditions_opened = 0, conditions_resolved = 0, conditions_expired = 0, conditions_rearmed = 0;
    uint64_t molt_outage_total = 0, lat_sum = 0, lat_max = 0, last_ckpt_ms = 0, last_vram_ms = 0;
    double cl_surp_sum = 0, cl_surp_max = 0; int cl_surp_n = 0;
    double all_surp_sum = 0; long all_surp_n = 0;
    uint64_t cl_ingest_ms = 0;             // decode+frontier time spent on the clause's words (rides the b record)

    // the clause under judgment
    std::string clause; int clause_toks = 0;
    uint64_t last_flush_ms = 0, last_delta_ms = 0;
    std::string cur_lane;
    uint64_t cur_delta_arrival = 0, cur_delta_t_mono = 0;
    size_t backlog_now = 0;
    bool line_open = false;                // a world line's prefix is on the trunk, words still landing
    bool line_fresh = false;               // the prefix was just (re)written: the next word takes no leading space

    // the verbatim tail (for the molt). Its cap and the rung's cap scale with the molt watermark so a
    // reseed can never land at or above the watermark (review correction 3): 600 at the default 24,576,
    // one fifth of the watermark below 3,000, never under 60 words / 64 tokens.
    std::deque<std::pair<std::string, int>> tailq; size_t tail_wc = 0;
    size_t tail_max_words = 600; int rung_max_toks = 600;
    std::string cur_tail_line;

    // own speech, placed after the line it illuminates
    std::deque<std::string> pending_commits;

    // the open line's words not yet on the trunk. Frames are the venue's atoms: these are the NEXT
    // percepts in order, and they land before any newer frame does (measured 2026-09-04: without
    // this queue the drain during a seat's speech pulled the next frame ahead of the rest of the
    // line it interrupted, and the trunk's order no longer matched the world's).
    std::deque<std::string> line_words;
    uint64_t frames_completed = 0;

    // the blind window, now with a window: generation depth and the judgments it defers, IN ORDER
    int gen_depth = 0;
    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; };
    std::deque<Deferred> deferred;
    bool molt_pending = false;

    // the manners layer (condition grain)
    std::string last_say[3]; long last_say_i[3]; uint64_t last_say_ms[3];
    bool resolved[3]; bool cond_open[3];
    static constexpr uint64_t SUPP_TTL_MS = 600000;   // 10 min
    // P1: the last un-said line per seat (what it would have said), for the cross-seat manners (P7)
    std::string last_unsaid[3]; uint64_t last_unsaid_ms[3]; bool last_unsaid_settled[3];
    // D1: own lines this process put on the air, with their time — a seat-lane frame that near-dups
    // one inside the echo window is an echo coming back around a bridge, not a second percept
    std::deque<std::pair<std::string, uint64_t>> own_lines;
    long n_heard = 0;

    // gear 2
    struct BriefOut { uint64_t id; llama_pos npast_at; uint64_t t_ms; int seat; };
    std::unordered_map<uint64_t, BriefOut> briefs_out; uint64_t next_brief_id = 1;

    // the forming plane: per-lane forming text, never on the trunk (reflex partials never persist)
    std::unordered_map<std::string, std::string> forming;

    Kernel() {
        for (int m = 0; m < 3; ++m) {
            last_say_i[m] = -999; last_say_ms[m] = 0; resolved[m] = false; cond_open[m] = false; last_brief_ms[m] = 0;
            last_unsaid_ms[m] = 0; last_unsaid_settled[m] = false;
        }
    }

    // ---- segment 2 methods
    int  boot();
    void read_vram(bool log);
    float read_frontier();
    void tail_push_line(const std::string& line);
    bool trunk_decode(const std::vector<llama_token>& t);
    bool trunk_text(const std::string& s, bool special);
    void ingest_word(const std::string& w);
    void flush_pending_commits();
    void do_molt();
    bool checkpoint(const char* why);
    bool restore();
    double rel_ms() const { return (double)(wall_ms() - wall0); }
    void fatal(const char* what);
    void warn(const char* what, const std::string& fields);   // a row a reader must see; the resident goes on
    void report_rename_failures();                            // F3: the counted rename failures, on the tape
    uint64_t last_rename_warn_ms = 0, rename_failures_seen = 0;

    // ---- segment 3 methods
    int  seat_of_lane(const std::string& lane) const;     // 0..2 seat, 3 = self/fusor, -1 = world
    bool is_wake_lane(const std::string& lane) const;
    bool looks_like_acceptance(const std::string& s) const;
    int  content_overlap(const std::string& a, const std::string& b) const;
    bool near_dup(const std::string& a, const std::string& b) const;
    void write_verdict(const std::string& lane, int m, const char* action, float margin,
                       const std::string& text, const char* cause);
    void write_brief(const std::string& lane, const std::string& clause_text, int m, float margin);
    void settle_deferred();
    void defer_judgment(float score);
    void feed_word();
    bool counsel_admit(Delta& d);
    bool speak(int m, float margin, std::string& say, std::string& aired, std::string& killed, std::string& cause,
               uint64_t& gen_ms);
    void tick_before(uint64_t arrive_ms);                 // silence before a frame becomes world (lazy tick)
    bool is_own_echo(const std::string& text);            // D1: a seat-lane frame that is this process's own line
    void heard_line(const Delta& d);                      // D1: a seat-lane / self frame, heard and never judged
    float probe_one(int m);
    void judge_and_maybe_emit(const char* reason, float bscore, llama_pos at = -1);
    int  deferred_covers = 1;              // how many deferred boundaries the current judgment stands for
    uint64_t last_brief_ms[3];             // gear-2 rate limit, per seat
    long briefs_skipped = 0;
    void begin_line(const Delta& d);
    void end_line();
    void ingest_delta(Delta& d);
    void drain_intake();
    void run();
    void shutdown(const char* stopped);
};

// -----------------------------------------------------------------------------------------------------
void Kernel::fatal(const char* what) {
    std::printf("\nFATAL [%s] — stopping so the tape is whole.\n", what);
    tape.put(std::string("{\"k\":\"fatal\",\"ms\":") + std::to_string((long long)rel_ms()) +
             ",\"what\":\"" + jesc(what) + "\"");
    g_run.store(false, std::memory_order_release);
}
// A `warn` row: something a reader must know that did not stop the resident (F3, F6).
void Kernel::warn(const char* what, const std::string& fields) {
    std::string b = std::string("{\"k\":\"warn\",\"ms\":") + std::to_string((long long)rel_ms()) + ",\"what\":" + jq(what);
    if (!fields.empty()) b += "," + fields;
    tape.put(b);
    std::printf("  [warn] %s %s\n", what, fields.c_str());
}
// F3: a rename that failed after its retries is reported here, on the GPU thread, at most once a
// minute, naming the path and the OS error. The running count rides the pill and the end row.
void Kernel::report_rename_failures() {
    if (g_rename_failures.load(std::memory_order_relaxed) == rename_failures_seen) return;
    const uint64_t now = wall_ms();
    if (last_rename_warn_ms && now - last_rename_warn_ms < 60000) return;
    std::string path; unsigned long err = 0;
    const uint64_t n = rename_failures_snapshot(path, err);
    last_rename_warn_ms = now;
    warn("rename_failed", "\"path\":" + jq(path) + ",\"os_error\":" + std::to_string(err) + ",\"count\":" + u64s(n) +
                          ",\"since_last_warn\":" + u64s(n - rename_failures_seen));
    rename_failures_seen = n;
}

// VRAM is the latency dial (measured 2026-08-23/09-01: 44 ms free vs 0.6–24.6 s loaded; 104 ms at
// 15 GiB free vs 500 ms at 10.5 GiB). A slow probe with no VRAM number beside it reads as a dumb
// resident. So the number rides the tape at boot and every minute.
void Kernel::read_vram(bool log) {
    size_t free_b = 0, total_b = 0; bool found = false; std::string name = "none";
    const size_t nd = ggml_backend_dev_count();
    for (size_t i = 0; i < nd; ++i) {
        ggml_backend_dev_t dev = ggml_backend_dev_get(i);
        if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU) continue;
        ggml_backend_dev_memory(dev, &free_b, &total_b);
        name = ggml_backend_dev_name(dev) ? ggml_backend_dev_name(dev) : "gpu";
        found = true; break;
    }
    const uint64_t mib_free = found ? (uint64_t)(free_b >> 20) : 0, mib_total = found ? (uint64_t)(total_b >> 20) : 0;
    vitals.mib_free.store(mib_free); vitals.mib_total.store(mib_total);
    last_vram_ms = wall_ms();
    if (log) {
        char b[256];
        std::snprintf(b, sizeof(b), "{\"k\":\"vram\",\"ms\":%.0f,\"dev\":\"%s\",\"mib_free\":%llu,\"mib_total\":%llu",
                      rel_ms(), jesc(name).c_str(), (unsigned long long)mib_free, (unsigned long long)mib_total);
        tape.put(b);
    }
}

// The isomorphic segmenter, read off the ingest logits: P(next token closes a thought). Also
// refreshes logZ so the nerve's next surprisal has a valid denominator. Verbatim behavior.
float Kernel::read_frontier() {
    const float* l = llama_get_logits_ith(ctx, -1);
    float mx = -1e30f;
    for (int t = 0; t < n_vocab; ++t) if (l[t] > mx) mx = l[t];
    double tot = 0, bnd = 0;
    for (int t = 0; t < n_vocab; ++t) {
        const double x = std::exp((double)(l[t] - mx));
        tot += x; if (is_bnd[(size_t)t]) bnd += x;
    }
    logZ = (double)mx + std::log(tot); have_logZ = true;
    frontier_logits.assign(l, l + n_vocab);   // keep the trunk's own distribution for the nerve
    return (float)(bnd / tot);
}

void Kernel::tail_push_line(const std::string& line) {
    int wc = 1; for (char c : line) if (c == ' ') ++wc;
    tailq.emplace_back(line, wc); tail_wc += (size_t)wc;
    while (tail_wc > tail_max_words && tailq.size() > 1) {
        tail_wc -= (size_t)tailq.front().second; tailq.pop_front();
    }
}

// Every token that lands on seq 0 goes through here, so the checkpoint's token list is exact.
bool Kernel::trunk_decode(const std::vector<llama_token>& t) {
    if (t.empty()) return true;
    if (!dec(ctx, t, TRUNK, npast, true)) { fatal("decode"); return false; }
    npast += (llama_pos)t.size();
    trunk_toks.insert(trunk_toks.end(), t.begin(), t.end());
    vitals.npast.store((uint64_t)npast);
    return true;
}
bool Kernel::trunk_text(const std::string& s, bool special) {
    auto t = tk(vocab, s, special);
    if (!trunk_decode(t)) return false;
    read_frontier();
    return true;
}

// Own speech commits AFTER the world's current line closes (placement law), on the seat's own lane,
// exactly as S0 formatted it — but never spliced into the middle of someone else's line.
void Kernel::flush_pending_commits() {
    while (!pending_commits.empty() && g_run.load(std::memory_order_acquire)) {
        const std::string c = pending_commits.front(); pending_commits.pop_front();
        if (!cfg.pure) {
            if (!trunk_text(c, false)) return;
            tail_push_line(c.size() > 1 ? c.substr(1) : c);   // drop the leading '\n'
        }
    }
}

// ---- ingest one word onto the trunk, with the nerve tapped and the segmenter read (S0's law) ----
void Kernel::ingest_word(const std::string& w) {
    auto wt = tk(vocab, w, false);
    if (wt.empty()) return;
    const uint64_t t_ing0 = wall_ms();
    double surp = -1;
    if (have_logZ && frontier_logits.size() == (size_t)n_vocab) {
        // the nerve: −log P(actual | context), off the trunk's PREVIOUS frontier — the saved copy,
        // never the context's last logits (which may be a probe's). LOGGED. GATES NOTHING.
        surp = logZ - (double)frontier_logits[(size_t)wt[0]];
    }
    if (!trunk_decode(wt)) return;
    ++words; clause_toks += (int)wt.size();
    const float bscore = read_frontier();
    cl_ingest_ms += wall_ms() - t_ing0;
    if (surp >= 0) {
        cl_surp_sum += surp; if (surp > cl_surp_max) cl_surp_max = surp;
        ++cl_surp_n; all_surp_sum += surp; ++all_surp_n;
    }
    // The flush law: boundary OR 24 tok OR 1500 ms — first wins. Under backlog, judgment COARSENS
    // to the token cap (counted, reason "c"); ingest stays unconditional. Inside a generation the
    // judgment is DEFERRED (reason "d") — percepts are never dropped, judgment may be delayed.
    const bool backlog = backlog_now > 8 || (tail && tail->unread_bytes() > 4096);
    const char* why = nullptr;
    if (backlog) { if (clause_toks >= 24) why = "c"; }
    else if (bscore >= 0.5f) why = "b";
    else if (clause_toks >= 24) why = "n";
    else if ((long)(wall_ms() - last_flush_ms) >= 1500 && clause_toks >= 6) why = "t";
    if (why) {
        if (gen_depth > 0) defer_judgment(bscore);
        else judge_and_maybe_emit(why, bscore);
    }
    if (cfg.molt_wm > 0 && npast >= cfg.molt_wm) {
        if (gen_depth > 0) { molt_pending = true; return; }
        if (!clause.empty()) judge_and_maybe_emit("m", bscore);
        do_molt();
    }
    if (gen_depth == 0) settle_deferred();   // pay any judgment deferred while a seat was speaking
}

// ---- the molt (S0's proven mechanics; the outage is a perceivable drop-event) ----------------------
void Kernel::do_molt() {
    molt_pending = false;
    flush_pending_commits();   // what the seats said belongs in the tail the rung is written from
    const uint64_t m0 = wall_ms();
    const llama_pos before = npast;
    llama_memory_seq_rm(mem, SCRIBE, -1, -1);
    llama_memory_seq_cp(mem, TRUNK, SCRIBE, -1, -1);
    const std::string cue =
        "\n<|im_end|>\n<|im_start|>user\n[The stream has been going a long while and "
        "the log is huge. As the room's keeper, write your running memory now: every "
        "decision, hard constraint, owner, deadline, established fact, and open thread "
        "that still matters for the work ahead. Drop the chatter. End with one line "
        "noting what you dropped.]\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n"
        "</think>\n\n";
    auto ct = tk(vocab, cue, false);
    // F4: every decode is checked. A scribe that cannot decode aborts the molt with the trunk intact.
    if (!dec(ctx, ct, SCRIBE, npast, true)) { llama_memory_seq_rm(mem, SCRIBE, -1, -1); fatal("molt_scribe_cue_decode"); return; }
    llama_pos spos = npast + (llama_pos)ct.size();
    std::string rung; int rtoks = 0;
    for (int t = 0; t < rung_max_toks; ++t) {
        const llama_token tok = llama_sampler_sample(smp_scribe, ctx, -1);
        if (llama_vocab_is_eog(vocab, tok)) break;
        char pc[256]; const int pn = llama_token_to_piece(vocab, tok, pc, sizeof(pc), 0, true);
        if (pn > 0) rung.append(pc, (size_t)pn);
        std::vector<llama_token> one{tok};
        if (!dec(ctx, one, SCRIBE, spos, true)) { llama_memory_seq_rm(mem, SCRIBE, -1, -1); fatal("molt_scribe_decode"); return; }
        ++spos; ++rtoks;
    }
    llama_memory_seq_rm(mem, SCRIBE, -1, -1);
    std::string tail_text;
    for (auto& p : tailq) tail_text += p.first + "\n";
    if (!cur_tail_line.empty()) tail_text += cur_tail_line + "\n";
    const std::string reseed = std::string(SEED_SYS) + SEED_EXAMPLES + SEED_OPEN +
        "[memory] " + rung + "\n[recent, verbatim]\n" + tail_text;
    auto rt = tk(vocab, reseed, true);
    // A reseed that would land at or above the watermark would molt again on the next word, forever
    // (review correction 3). That is a fatal with the trunk still whole, never a loop.
    if (cfg.molt_wm > 0 && (long)rt.size() + 16 >= cfg.molt_wm) {
        warn("molt_reseed_too_large", "\"reseed_toks\":" + std::to_string(rt.size()) + ",\"molt_wm\":" + std::to_string(cfg.molt_wm));
        fatal("molt_reseed_too_large"); return;
    }
    llama_memory_seq_rm(mem, TRUNK, -1, -1);
    trunk_toks.clear(); npast = 0;
    if (!dec(ctx, rt, TRUNK, 0, true)) { fatal("molt_reseed_decode"); return; }   // F4: the last checkpoint stands
    npast = (llama_pos)rt.size(); trunk_toks = rt; vitals.npast.store((uint64_t)npast);
    read_frontier();
    const uint64_t dur = wall_ms() - m0;
    { char tb[96]; std::snprintf(tb, sizeof(tb),
          "\n[tick +%llus — I paused the watch to consolidate my memory]",
          (unsigned long long)(dur / 1000 + 1));
      trunk_text(tb, false); }
    // A molt inside an open world line: re-establish the lane prefix so the words still landing
    // attach to a properly laned line (S0 left them prefix-less after a mid-line molt).
    if (line_open && !cur_lane.empty()) trunk_text(std::string("\n[") + cur_lane + "] ", false);
    ++n_molts; molt_outage_total += dur; vitals.molts.store((uint64_t)n_molts);
    std::printf("\n  [molt %ld] trunk %d -> %d tok (rung %d tok, %llums outage — a drop-event)\n",
                n_molts, (int)before, (int)npast, rtoks, (unsigned long long)dur);
    char b[512];
    std::snprintf(b, sizeof(b), "{\"k\":\"molt\",\"ms\":%.0f,\"before\":%d,\"rung_toks\":%d,\"after\":%d,\"dur_ms\":%llu,\"rung\":\"",
                  rel_ms(), (int)before, rtoks, (int)npast, (unsigned long long)dur);
    tape.put(std::string(b) + jesc(rung) + "\"");
    if (!cfg.ckpt.empty()) { if (line_open) ckpt_due = true; else checkpoint("molt"); }   // mid-line: at the next quiet gate
}

// ---- the trunk is an asset: checkpoint and restore (P3) ---------------------------------------------
// The checkpoint is written to <ckpt>.tmp and renamed into place with write-through; the previous
// file is kept one generation back as <ckpt>.prev; the .meta sidecar is written LAST, so it never
// …
bool Kernel::checkpoint(const char* why) {
    if (cfg.ckpt.empty()) return false;
    const uint64_t c0 = wall_ms();
    const std::string tmp = cfg.ckpt + ".tmp", prevp = cfg.ckpt + ".prev";
    std::remove(tmp.c_str());
    const size_t bytes = llama_state_seq_save_file(ctx, tmp.c_str(), TRUNK, trunk_toks.data(), trunk_toks.size());
    bool ok = bytes > 0;
    if (ok) {
        uint64_t old_sz = 0;
        if (file_size_of(cfg.ckpt, old_sz)) replace_file(cfg.ckpt, prevp, false);   // one generation back; a failure is counted, not fatal
        ok = replace_file(tmp, cfg.ckpt, true);                                        // the old file or the new one; never a torn one
    }
    const uint64_t cursor = tail ? tail->ingested_off.load() : 0;
    if (ok) {
        std::string meta;
        meta += "model\t" + cfg.model + "\n";
        meta += "model_sha256\t" + model_sha + "\n";
        meta += "serve\t" + hex16(serve_hash()) + "\n";
        meta += "npast\t" + std::to_string((long long)npast) + "\n";
        meta += "prev\t" + tape.prev + "\n";
        meta += "t\t" + u64s(wall_ms()) + "\n";
        meta += "t_wall\t" + u64s(epoch_ms()) + "\n";
        meta += "t_last_frame_wall\t" + u64s(last_frame_wall_ms) + "\n";
        meta += "spool\t" + cfg.spool + "\n";
        meta += "cursor\t" + u64s(cursor) + "\t" + hex16(tail ? tail->prefix_hash(cursor) : 0) + "\n";
        for (auto& p : tailq) meta += "tail\t" + p.first + "\n";
        ok = write_atomic(cfg.ckpt + ".meta", meta);
    }
    last_ckpt_ms = wall_ms(); ckpt_due = false;
    tape.put("{\"k\":\"ckpt\",\"ms\":" + fmt0(rel_ms()) + ",\"why\":" + jq(why) + ",\"toks\":" + std::to_string((int)npast) +
             ",\"bytes\":" + u64s(bytes) + ",\"cursor\":" + u64s(cursor) + ",\"ok\":" + (ok ? "true" : "false") +
             ",\"dur_ms\":" + u64s(wall_ms() - c0));
    return ok;
}
struct CkptMeta {
    std::string model, model_sha, serve, spool; long long npast = -1;
    uint64_t cursor = 0, cursor_hash = 0, t_last_frame_wall = 0; bool have_cursor = false;
    std::vector<std::string> tails;
};
static bool parse_meta(const std::string& text, CkptMeta& m) {
    if (text.empty()) return false;
    size_t p = 0;
    while (p < text.size()) {
        size_t q = text.find('\n', p); if (q == std::string::npos) q = text.size();
        const std::string ln = text.substr(p, q - p); p = q + 1;
        if (starts_with(ln, "model\t")) m.model = ln.substr(6);
        else if (starts_with(ln, "model_sha256\t")) m.model_sha = ln.substr(13);
        else if (starts_with(ln, "serve\t")) m.serve = ln.substr(6);
        else if (starts_with(ln, "npast\t")) m.npast = std::atoll(ln.c_str() + 6);
        else if (starts_with(ln, "spool\t")) m.spool = ln.substr(6);
        else if (starts_with(ln, "t_last_frame_wall\t")) m.t_last_frame_wall = std::strtoull(ln.c_str() + 18, nullptr, 10);
        else if (starts_with(ln, "cursor\t")) {
            m.cursor = std::strtoull(ln.c_str() + 7, nullptr, 10);
            const char* tab = std::strchr(ln.c_str() + 7, '\t');
            m.cursor_hash = tab ? std::strtoull(tab + 1, nullptr, 16) : 0; m.have_cursor = true;
        }
        else if (starts_with(ln, "tail\t")) m.tails.push_back(ln.substr(5));
    }
    return true;
}
// Restore requires the .meta, the model, the serve hash and the loaded token count to agree; when the
// current file disagrees with its .meta (a crash between the rename and the .meta write) the previous
// generation is tried with the same .meta; failing both, the resident is the twin and says so.
bool Kernel::restore() {
    CkptMeta m;
    if (!parse_meta(read_all(cfg.ckpt + ".meta", 1 << 20), m)) {
        std::printf("[resume] no .meta beside the checkpoint — starting cold (the twin).\n"); return false;
    }
    if (m.model != cfg.model || m.serve != hex16(serve_hash())) {
        std::printf("[resume] checkpoint belongs to another model or serve format — starting cold (the twin).\n"); return false;
    }
    if (!m.model_sha.empty() && !model_sha.empty() && m.model_sha != model_sha) {   // same path, different bytes
        std::printf("[resume] the weights changed under the checkpoint (sha256 %s… vs %s…) — starting cold (the twin).\n",
                    m.model_sha.substr(0, 12).c_str(), model_sha.substr(0, 12).c_str()); return false;
    }
    auto try_load = [&](const std::string& path) -> bool {
        uint64_t sz = 0; if (!file_size_of(path, sz) || sz == 0) return false;
        llama_memory_seq_rm(mem, TRUNK, -1, -1);                     // the load wants an empty destination
        std::vector<llama_token> buf((size_t)llama_n_ctx(ctx)); size_t n = 0;
        const size_t got = llama_state_seq_load_file(ctx, path.c_str(), TRUNK, buf.data(), buf.size(), &n);
        if (got == 0 || n == 0) { llama_memory_seq_rm(mem, TRUNK, -1, -1); return false; }
        if ((long long)n != m.npast) {                              // the .meta describes another generation
            std::printf("[resume] %s holds %zu tokens, .meta says %lld — not the same generation.\n", path.c_str(), n, m.npast);
            llama_memory_seq_rm(mem, TRUNK, -1, -1); return false;
        }
        buf.resize(n); trunk_toks = buf; npast = (llama_pos)n; vitals.npast.store((uint64_t)npast);
        return true;
    };
    if (try_load(cfg.ckpt)) boot_kind = "restored";
    else if (try_load(cfg.ckpt + ".prev")) boot_kind = "restored_prev";
    else { std::printf("[resume] neither checkpoint generation matches its .meta — starting cold (the twin).\n"); return false; }
    have_logZ = false;                                             // no frontier until the next decode
    for (auto& t : m.tails) tail_push_line(t);                     // the verbatim tail comes back with the trunk
    meta_cursor = m.cursor; meta_cursor_hash = m.cursor_hash;
    meta_cursor_ok = m.have_cursor && (m.spool.empty() || m.spool == cfg.spool);
    meta_t_last_frame_wall = m.t_last_frame_wall;
    return true;
}

// ---- boot: assert, load, seed-or-resume, open the organs -----------------------------------------------
int Kernel::boot() {
    // train ≡ serve: assert BEFORE anything else. A drifted serve byte must not even load.
    {
        const uint64_t h = serve_hash();
        if constexpr (SERVE_HASH_PIN == 0ull) {
            std::printf("[train==serve] UNPINNED. Computed serve-bytes hash = 0x%016llx\n"
                        "  Pin this value as SERVE_HASH_PIN (same commit as the tune it matches) and rebuild.\n",
                        (unsigned long long)h);
            return 2;
        }
        if (h != SERVE_HASH_PIN) {
            std::printf("FATAL [train!=serve]: serve bytes hash 0x%016llx != pinned 0x%016llx.\n"
                        "  A serve-side literal drifted from the v11 tune. Restore the bytes or re-pin DELIBERATELY (with a retune).\n",
                        (unsigned long long)h, (unsigned long long)SERVE_HASH_PIN);
            return 2;
        }
    }
    wall0 = wall_ms();   // one epoch for every record on this run's tape, load time included
    if (cfg.molt_wm > 0 && cfg.molt_wm < 3000) {   // the caps scale with a small watermark (review correction 3)
        tail_max_words = (size_t)std::max<long>(60, cfg.molt_wm / 5);
        rung_max_toks  = (int)std::max<long>(64, cfg.molt_wm / 5);
    }
    ensure_dir(cfg.out_dir);
    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; }
    if (tape.torn_bytes) warn("torn_row_skipped", "\"bytes\":" + u64s(tape.torn_bytes));   // F6: a crash inside a write, on the record
    verdicts.open(cfg.out_dir + "/verdicts.jsonl");
    briefs.open(cfg.out_dir + "/briefs.jsonl");
    pill.pill_path = cfg.out_dir + "/fusord.heartbeat.json";
    pill.switch_path = cfg.out_dir + "/fusord.state";
    pill.v = &vitals;
    vitals.sw.store((int)read_switch(pill.switch_path, Switch::Off));

    std::printf("\n===== FUSOR · fusord — THE RESIDENT KERNEL (K5 · converge) =====\n");
    std::printf("spool=%s · dial=0 · molt_wm=%ld · idle-tick=%lds · switch=%s · out=%s\n",
                cfg.spool.c_str(), cfg.molt_wm, cfg.idle_tick_s, switch_name((Switch)vitals.sw.load()), cfg.out_dir.c_str());

#if defined(_WIN32)
    SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
    { wchar_t w[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, AURICLE_LLAMA_DIR, -1, w, MAX_PATH); AddDllDirectory(w); }
#endif
    llama_log_set(err_log, nullptr); ggml_log_set(err_log, nullptr);
    backends_loaded = load_backends_by_name(AURICLE_LLAMA_DIR);   // never load_all: ggml-rpc imports ws2_32
    llama_backend_init();
    {   // the module gate: zero egress is a property of THIS process, checked, on the header
        std::string offending; size_t nmod = 0;
        const bool gate = module_gate(offending, nmod);
        n_modules = nmod; egress = gate ? "none" : "possible:" + offending;
        if (!gate && !cfg.egress_unchecked) {
            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);
            tape.put("{\"k\":\"fatal\",\"ms\":" + fmt0(rel_ms()) + ",\"what\":\"egress_module\",\"module\":" + jq(offending) + ",\"modules\":" + u64s(nmod));
            return 2;
        }
    }
    {   // the devices, on the header
        std::string dj; bool gpu = false;
        for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
            ggml_backend_dev_t d = ggml_backend_dev_get(i); size_t fb = 0, tb = 0; ggml_backend_dev_memory(d, &fb, &tb);
            const bool is_gpu = ggml_backend_dev_type(d) == GGML_BACKEND_DEVICE_TYPE_GPU; gpu = gpu || is_gpu;
            dj += (dj.empty() ? "" : ",") + std::string("{\"name\":") + jq(ggml_backend_dev_name(d) ? ggml_backend_dev_name(d) : "?") +
                  ",\"type\":" + jq(is_gpu ? "gpu" : "cpu") + ",\"mib_free\":" + u64s(fb >> 20) + ",\"mib_total\":" + u64s(tb >> 20) + "}";
        }
        devices_json = "[" + dj + "]";
        if (!gpu && !cfg.allow_cpu) {
            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");
            tape.put("{\"k\":\"fatal\",\"ms\":" + fmt0(rel_ms()) + ",\"what\":\"no_gpu\",\"devices\":" + devices_json);
            return 2;
        }
    }
    read_vram(true);   // before the weights land: the room the resident is walking into
    model_sha = model_identity(cfg.model, cfg.model_sha256, cfg.sha_cache.empty() ? cfg.out_dir + "/model.sha256" : cfg.sha_cache, model_sha_source);

    llama_model_params mp = llama_model_default_params(); mp.n_gpu_layers = 999;
    mdl = llama_model_load_from_file(cfg.model.c_str(), mp);
    if (!mdl) { std::printf("model load FAILED\n"); return 1; }
    if ((g_gpu_layers_offloaded < 0 || g_gpu_layers_offloaded != g_gpu_layers_total) && !cfg.allow_cpu) {
        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",
                    g_gpu_layers_offloaded, g_gpu_layers_total);
        tape.put("{\"k\":\"fatal\",\"ms\":" + fmt0(rel_ms()) + ",\"what\":\"gpu_offload\",\"offloaded\":" + std::to_string(g_gpu_layers_offloaded) +
                 ",\"total\":" + std::to_string(g_gpu_layers_total));
        return 2;
    }
    vocab = llama_model_get_vocab(mdl);
    n_vocab = llama_vocab_n_tokens(vocab);
    hold_tok = tk(vocab, " hold", false)[0];
    emit_tok = tk(vocab, " emit", false)[0];

    // The segmenter's boundary set, TIGHTENED (measured 2026-08-12): . ! ? · newline · EOG.
    // Not ; : — syntax, not thought (3.3 boundaries/line on a code paste; fragments handed to the probe).
    is_bnd.assign((size_t)n_vocab, 0);
    for (int t = 0; t < n_vocab; ++t) {
        char pc[64]; const int pn = llama_token_to_piece(vocab, t, pc, sizeof(pc), 0, true);
        if (pn <= 0) { if (llama_vocab_is_eog(vocab, t)) is_bnd[(size_t)t] = 1; continue; }
        const std::string p(pc, (size_t)pn);
        char last = 0;
        for (char c : p) if (c != ' ') last = c;
        if (last == '.' || last == '!' || last == '?' ||
            p.find('\n') != std::string::npos || llama_vocab_is_eog(vocab, t))
            is_bnd[(size_t)t] = 1;
    }

    llama_context_params cp = llama_context_default_params();
    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)
    cp.n_batch = 512; cp.n_ubatch = 512; cp.n_seq_max = 8; cp.kv_unified = true;
    if (cfg.kv_q8) {
        cp.type_k = GGML_TYPE_Q8_0; cp.type_v = GGML_TYPE_Q8_0;
        cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED;
    }
    ctx = llama_init_from_model(mdl, cp);
    if (!ctx) { std::printf("ctx FAILED\n"); return 1; }
    if (llama_n_ctx_seq(ctx) != llama_n_ctx(ctx)) {
        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));
        return 1;
    }
    mem = llama_get_memory(ctx);
    smp = llama_sampler_chain_init(llama_sampler_chain_default_params());
    llama_sampler_chain_add(smp, llama_sampler_init_min_p(0.05f, 1));
    llama_sampler_chain_add(smp, llama_sampler_init_temp(0.7f));
    llama_sampler_chain_add(smp, llama_sampler_init_dist(11));
    smp_scribe = llama_sampler_chain_init(llama_sampler_chain_default_params());
    llama_sampler_chain_add(smp_scribe, llama_sampler_init_min_p(0.05f, 1));
    llama_sampler_chain_add(smp_scribe, llama_sampler_init_temp(0.3f));
    llama_sampler_chain_add(smp_scribe, llama_sampler_init_dist(11));

    // seed — or resume the held state. A resident rebuilt from its seed is the twin; say so.
    int seed_toks = 0;
    if (!cfg.ckpt.empty() && cfg.resume && !cfg.cold && restore()) {
        resumed = true; seed_toks = (int)npast;
        std::printf("[resume] trunk %s: %d tokens held. The mind picks up where it stopped.\n", boot_kind.c_str(), (int)npast);
    } else {
        const std::string seed = std::string(SEED_SYS) + SEED_EXAMPLES + SEED_OPEN;
        auto stoks = tk(vocab, seed, true);
        if (!dec(ctx, stoks, TRUNK, 0, false)) { fatal("seed_decode"); return 1; }   // F4
        npast = (llama_pos)stoks.size(); trunk_toks = stoks; vitals.npast.store((uint64_t)npast);
        seed_toks = (int)npast;
        twin = !cfg.ckpt.empty() && (cfg.cold || cfg.resume);   // a checkpoint existed in intent; this is not it
        boot_kind = twin ? "twin" : "seed";
    }
    read_vram(true);   // after the weights land: what is left for the probes

    // the tail starts from the mark taken in main() BEFORE the model loaded, from the cursor, or — with a
    // restored trunk — from the checkpoint's own cursor (P3/F1), replaying what the previous life ingested
    // past the checkpoint rather than skipping it. The replay window is on the tape before any frame.
    tail_start_reason = tail->resolve_start(cfg.from_start ? TailFrom::Start : cfg.from_end ? TailFrom::End : TailFrom::Mark,
                                            !cfg.from_start && !cfg.from_end, resumed && meta_cursor_ok, meta_cursor, meta_cursor_hash);
    if (resumed && tail_start_reason == "checkpoint_cursor") {
        uint64_t foff = 0, fh = 0, n = 0; file_size_of(cfg.spool, n);
        if (tail->read_cursor_file(foff, fh) && foff > tail->offset.load() && foff <= n) {
            replay_until = foff;
            tape.put("{\"k\":\"replay\",\"ms\":" + fmt0(rel_ms()) + ",\"from\":" + u64s(tail->offset.load()) + ",\"to\":" + u64s(foff) +
                     ",\"why\":\"the previous life ingested past its last checkpoint; the trunk must see those frames again\"");
        }
    }
    tail->start();
    pill.start();

    last_flush_ms = wall_ms(); last_delta_ms = last_flush_ms; last_ckpt_ms = last_flush_ms;
    // The header row, built from strings (F6): a long spool path or model path can no longer truncate it.
    std::string hb = std::string("{\"k\":\"hdr\",\"src\":") + jq(cfg.spool) + ",\"live\":true,\"dial\":0,\"mode\":" + jq(cfg.pure ? "pure" : "room") +
        ",\"molt_wm\":" + std::to_string(cfg.molt_wm) + ",\"model\":" + jq(cfg.model) + ",\"seed_toks\":" + std::to_string(seed_toks) +
        ",\"t0_wall\":" + u64s(wall_ms()) + ",\"kv\":" + jq(cfg.kv_q8 ? "q8_0" : "f16") + ",\"n_ctx\":" + std::to_string(llama_n_ctx(ctx)) +
        ",\"serve_hash\":\"0x" + hex16(serve_hash()) + "\"" +
        ",\"label_enum\":[\"useful\",\"wrong_content\",\"too_late\",\"wrong_to_speak\"]" +
        ",\"e_def\":\"e=surfaced only; events=e+e_suppressed+unsaid (additive, never conflated)\"" +
        ",\"self_ref_detector\":" + jq(SELF_REF_DESC) + ",\"kernel\":\"v-next-converge\",\"venue\":" + jq(tail->venue) +
        ",\"lane_contract\":" + (tail->v01 ? "true" : "false") + ",\"tail_start\":" + jq(tail_start_reason) +
        ",\"spool_offset\":" + u64s(tail->offset.load()) + ",\"mib_free\":" + u64s(vitals.mib_free.load()) + ",\"mib_total\":" + u64s(vitals.mib_total.load()) +
        ",\"state\":" + jq(switch_name((Switch)vitals.sw.load())) + ",\"resumed\":" + (resumed ? "true" : "false") + ",\"twin\":" + (twin ? "true" : "false") +
        ",\"boot\":" + jq(boot_kind) + ",\"replay_until\":" + u64s(replay_until) + ",\"ckpt\":" + jq(cfg.ckpt) + ",\"ckpt_every_s\":" + std::to_string(cfg.ckpt_every_s) +
        ",\"egress\":" + jq(egress) + ",\"modules\":" + u64s(n_modules) + ",\"backends\":" + jq(backends_loaded) + ",\"devices\":" + devices_json +
        ",\"gpu_layers\":" + jq(std::to_string(g_gpu_layers_offloaded) + "/" + std::to_string(g_gpu_layers_total)) +
        ",\"model_sha256\":" + jq(model_sha) + ",\"model_sha256_source\":" + jq(model_sha_source) +
        ",\"ask_band\":" + fmt2(cfg.ask_band) + ",\"stale_tok\":" + std::to_string(cfg.stale_tok) + ",\"refractory_s\":" + std::to_string(cfg.refractory_s) +
        ",\"killed_next\":" + (cfg.killed_full ? "false" : "true") + ",\"echo_window_s\":" + std::to_string(cfg.echo_window_s) +
        ",\"t_mono_ns\":" + u64s(mono_ns());
    tape.put(hb);
    return 0;
}

} // namespace fusor

// ---- end of segment 2 -------------------------------------------------------------------------------
// ---- segment 3 --------------------------------------------------------------------------------------

namespace fusor {

// Sample from a SAVED copy of a sequence's logits. Needed because intake now lands on the trunk
// between generated tokens, so the context's "last logits" may belong to the trunk (or to a probe)
// by the time the speaking seat wants its next token. The chain (min_p → temp → dist) is applied
// exactly as before; only the source of the logits changes.
static llama_token sample_from(llama_sampler* smp, const float* logits, int n_vocab,
                               std::vector<llama_token_data>& cands) {
    cands.resize((size_t)n_vocab);
    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; }
    llama_token_data_array arr = { cands.data(), cands.size(), -1, false };
    llama_sampler_apply(smp, &arr);
    const llama_token tok = arr.selected >= 0 ? arr.data[arr.selected].id : arr.data[0].id;
    llama_sampler_accept(smp, tok);
    return tok;
}

// =====================================================================================================
// §11 · THE MANNERS LAYER (deterministic, disclosed, S0's tests kept exactly)
// =====================================================================================================

int Kernel::seat_of_lane(const std::string& lane) const {
    for (int m = 0; m < 3; ++m) if (ieq(lane, MINDS[m].name)) return m;
    if (ieq(lane, "fusor") || ieq(lane, "self")) return 3;
    return -1;
}
bool Kernel::is_wake_lane(const std::string& lane) const {
    const std::string l = lower(lane);
    for (auto& p : cfg.wake_prefixes) if (!p.empty() && starts_with(l, lower(p).c_str())) return true;
    return false;
}
bool Kernel::looks_like_acceptance(const std::string& s) const {
    const std::string t = lower(s);
    static const char* A[] = {"you're right", "you are right", "good catch", "fair point",
                              "correct", "my mistake", "agreed", "fixed"};
    for (auto a : A) if (t.find(a) != std::string::npos) return true;
    return false;
}
int Kernel::content_overlap(const std::string& a, const std::string& b) const {
    static const char* STOP[] = {"the","a","an","and","or","but","so","we","is","are","was","were",
                                 "it","its","it's","to","of","in","on","for","with","that","this",
                                 "let","let's","before","after","just","also","ok","okay","right",
                                 "i","you","he","she","they","me","us","them","my","our","your"};
    auto split = [](const std::string& s) {
        std::vector<std::string> v; std::string w;
        for (char c : s) {
            if (std::isalnum((unsigned char)c)) w += (char)std::tolower((unsigned char)c);
            else { if (w.size() > 1) v.push_back(w); w.clear(); }
        }
        if (w.size() > 1) v.push_back(w);
        return v;
    };
    auto is_stop = [&](const std::string& w) { for (auto s : STOP) if (w == s) return true; return false; };
    auto A = split(a), B = split(b);
    int hit = 0;
    for (auto& w : A) {
        if (is_stop(w)) continue;
        for (auto& x : B) if (w == x) { ++hit; break; }
    }
    return hit;
}
bool Kernel::near_dup(const std::string& a, const std::string& b) const {
    if (a.empty() || b.empty()) return false;
    auto split = [](const std::string& s) {
        std::vector<std::string> v; size_t p = 0;
        while (p < s.size()) { size_t q = s.find(' ', p); if (q == std::string::npos) q = s.size();
            if (q > p) v.push_back(lower(s.substr(p, q - p))); p = q + 1; }
        return v; };
    auto A = split(a), B = split(b);
    if (A.empty() || B.empty()) return false;
    size_t hit = 0;
    for (auto& w : A) for (auto& x : B) if (w == x) { ++hit; break; }
    return (double)hit / (double)A.size() >= 0.6;   // 60% of the words already said
}

// =====================================================================================================
// §12 · THE WIRE, THE BRIEFS, THE COUNSEL GATE
// =====================================================================================================

// ADDENDUM-F §3.3: one row per seat per boundary. `hold` rows are the record of silence with their
// margin. `off` writes no wire: the kernel is inert to the world; the TAPE still has every margin.
void Kernel::write_verdict(const std::string& lane, int m, const char* action, float margin,
                           const std::string& text, const char* cause) {
    const Switch sw = (Switch)vitals.sw.load();
    if (sw == Switch::Off) return;
    char b[512];
    std::snprintf(b, sizeof(b),
        "{\"t_mono_ns\":%llu,\"lane\":\"%s\",\"seat\":\"%s\",\"action\":\"%s\",\"margin\":%.3f,"
        "\"i\":%ld,\"ms\":%.0f,\"steer\":\"unsteered\",\"provenance\":\"local\",\"state\":\"%s\",",
        (unsigned long long)mono_ns(), jesc(lane).c_str(), MINDS[m].name, action, margin,
        boundaries, rel_ms(), switch_name(sw));
    std::string row = b;
    row += text.empty() ? "\"text\":null" : "\"text\":\"" + jesc(text) + "\"";
    row += cause ? std::string(",\"cause\":\"") + jesc(cause) + "\"" : ",\"cause\":null";
    row += "}";
    verdicts.put(row);
}

// Gear 2, at the seam: a thin margin writes a BRIEF — the clause, the held tail, one question.
// Whoever reads briefs.jsonl (a larger local model between beats, the operator's API passthrough,
// a harness session) answers on the spool as lane `counsel` with "#<id> " in front. The kernel
// never opens a socket. Remote proposes; local disposes (counsel_admit).
void Kernel::write_brief(const std::string& lane, const std::string& clause_text, int m, float margin) {
    if ((Switch)vitals.sw.load() == Switch::Off) return;
    // one brief per seat per 30 s: gear 2 is asked about an instant, not paged about a stretch
    if (last_brief_ms[m] && wall_ms() - last_brief_ms[m] < 30000) { ++briefs_skipped; return; }
    last_brief_ms[m] = wall_ms();
    const uint64_t id = next_brief_id++;
    briefs_out[id] = BriefOut{id, npast, wall_ms(), m};
    std::string held;
    {   // the last ≤12 lines of the verbatim tail — what the resident is holding as it asks
        size_t k = tailq.size() > 12 ? tailq.size() - 12 : 0; bool first = true;
        for (size_t i = k; i < tailq.size(); ++i) { held += (first ? "" : ","); held += "\"" + jesc(tailq[i].first) + "\""; first = false; }
    }
    char b[512];
    std::snprintf(b, sizeof(b),
        "{\"id\":%llu,\"t_mono_ns\":%llu,\"npast\":%d,\"seat\":\"%s\",\"margin\":%.3f,\"lane\":\"%s\",\"state\":\"%s\",",
        (unsigned long long)id, (unsigned long long)mono_ns(), (int)npast, MINDS[m].name, margin,
        jesc(lane).c_str(), switch_name((Switch)vitals.sw.load()));
    std::string row = b;
    row += "\"clause\":\"" + jesc(clause_text) + "\",\"held\":[" + held + "],";
    row += std::string("\"question\":\"The ") + MINDS[m].name + " cannot rank this instant (margin " +
           std::to_string((double)margin).substr(0, 6) + "). Its mandate: " + MINDS[m].mandate +
           ". In one sentence: is this worth a word now, and what is the word? Reply HOLD if not.\"}";
    briefs.put(row);
    ++n_briefs; vitals.briefs.store((uint64_t)n_briefs);
    char t[256];
    std::snprintf(t, sizeof(t), "{\"k\":\"brief\",\"id\":%llu,\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.3f,\"npast\":%d",
                  (unsigned long long)id, boundaries, rel_ms(), MINDS[m].name, margin, (int)npast);
    tape.put(t);
}

// THE STALENESS GATE. Counsel that arrives after the world has moved past the envelope is answering
// about a world that no longer exists: DISCARD it, and the discard is a typed negative on the tape.
// Untagged counsel (no "#<id>") is an ordinary lane line: a percept with a source, no envelope known.
bool Kernel::counsel_admit(Delta& d) {
    if (d.text.size() < 2 || d.text[0] != '#') return true;
    char* endp = nullptr;
    const unsigned long long id = std::strtoull(d.text.c_str() + 1, &endp, 10);
    if (!endp || endp == d.text.c_str() + 1) return true;
    auto it = briefs_out.find((uint64_t)id);
    if (it == briefs_out.end()) return true;   // unknown id: admitted as ordinary testimony
    const long drift = (long)(npast - it->second.npast_at);
    const uint64_t age = wall_ms() - it->second.t_ms;
    std::string body = d.text.substr((size_t)(endp - d.text.c_str()));
    while (!body.empty() && body[0] == ' ') body.erase(0, 1);
    char b[512];
    if (drift > cfg.stale_tok) {
        ++n_discard; vitals.counsel_discarded.store((uint64_t)n_discard);
        std::snprintf(b, sizeof(b), "{\"k\":\"discard\",\"id\":%llu,\"ms\":%.0f,\"drift_tok\":%ld,\"age_ms\":%llu,\"mind\":\"%s\",\"text\":\"",
                      id, rel_ms(), drift, (unsigned long long)age, MINDS[it->second.seat].name);
        tape.put(std::string(b) + jesc(body) + "\"");
        briefs_out.erase(it);
        return false;
    }
    ++n_counsel; vitals.counsel_in.store((uint64_t)n_counsel);
    std::snprintf(b, sizeof(b), "{\"k\":\"counsel\",\"id\":%llu,\"ms\":%.0f,\"drift_tok\":%ld,\"age_ms\":%llu,\"mind\":\"%s\"",
                  id, rel_ms(), drift, (unsigned long long)age, MINDS[it->second.seat].name);
    tape.put(b);
    briefs_out.erase(it);
    d.text = body;   // enters the trunk as "[counsel] …" — testimony with a source, never belief
    return true;
}

// THE PROBE (verbatim frame, dial 0), on a fork of the trunk as it stands NOW.
//
// A judgment cannot be made "as of" an earlier instant on this trunk. The 9B is a 3:1 recurrent
// …
float Kernel::probe_one(int m) {
    llama_memory_seq_rm(mem, DECIDE, -1, -1);
    llama_memory_seq_cp(mem, TRUNK, DECIDE, -1, -1);
    auto pr = tk(vocab, std::string(PROBE_A) + MINDS[m].name + PROBE_B + MINDS[m].mandate + PROBE_C, false);
    if (!dec(ctx, pr, DECIDE, npast, true)) { fatal("probe_decode"); llama_memory_seq_rm(mem, DECIDE, -1, -1); return 0.0f; }
    const float* l = llama_get_logits_ith(ctx, -1);
    const float margin = l[emit_tok] - l[hold_tok];
    llama_memory_seq_rm(mem, DECIDE, -1, -1);
    return margin;
}

// =====================================================================================================
// §13 · SPEAKING — one sentence, hard cap, and THE UN-SAY INSIDE THE BLIND WINDOW
// =====================================================================================================

// Returns true if the line was said in full; false if it was killed mid-word by the world.
// `aired` = the prefix that reached the surface before the kill (console-accounted at v-next; a
// mouth ring will make it sample-accounted). `killed` = the rest of the sentence, generated SILENTLY
// after the kill so the tape holds the counterfactual (P1/D2; `--killed-next` keeps one token).
// `cause` names why it died.
bool Kernel::speak(int m, float margin, std::string& say, std::string& aired, std::string& killed, std::string& cause, uint64_t& gen_ms) {
    const uint64_t g0 = wall_ms();
    const bool surface_on = (Switch)vitals.sw.load() != Switch::Off;
    llama_memory_seq_rm(mem, GEN, -1, -1);
    llama_memory_seq_cp(mem, TRUNK, GEN, -1, -1);
    const std::string cue = std::string(CUE_A) + MINDS[m].name + CUE_B + MINDS[m].mandate + CUE_C;
    auto ct = tk(vocab, cue, false);
    if (!dec(ctx, ct, GEN, npast, true)) {   // F4: a generation that cannot decode is fatal, never a silent blank
        llama_memory_seq_rm(mem, GEN, -1, -1); fatal("gen_cue_decode");
        cause = "fatal:gen_cue_decode"; gen_ms = wall_ms() - g0; return false;
    }
    llama_pos gpos = npast + (llama_pos)ct.size();
    std::vector<float> gen_logits((size_t)n_vocab);
    std::vector<llama_token_data> cands;
    { const float* l = llama_get_logits_ith(ctx, -1); std::memcpy(gen_logits.data(), l, sizeof(float) * (size_t)n_vocab); }
    ++gen_depth;
    bool aborted = false;
    if (surface_on) std::printf("\n  ┌─ %s  (margin %+.2f)\n  │  ", MINDS[m].name, margin);
    // ONE SENTENCE, HARD CAP (S0, measured: latency-to-notice was coupled to emission length).
    // The cap bounds the blind window; the drain below opens a window INSIDE it after every token.
    for (int t = 0; t < 28; ++t) {
        const llama_token tok = sample_from(smp, gen_logits.data(), n_vocab, cands);
        if (llama_vocab_is_eog(vocab, tok)) break;
        char pc[256]; const int pn = llama_token_to_piece(vocab, tok, pc, sizeof(pc), 0, true);
        std::string piece(pc, pn > 0 ? (size_t)pn : 0);
        if (piece.find('\n') != std::string::npos) break;
        if (!aborted) {
            say += piece;
            if (surface_on) { std::fputs(piece.c_str(), stdout); aired = say; }   // the forming plane, visible as it forms
        } else {
            killed += piece;                  // P1/D2: the counterfactual — sampled, never surfaced, on the tape
            if (!cfg.killed_full) break;      // --killed-next: one token of it is enough
        }
        std::vector<llama_token> one{tok};
        if (!dec(ctx, one, GEN, gpos, true)) { aborted = true; cause = "fatal:gen_decode"; fatal("gen_decode"); break; }   // F4
        ++gpos;
        { const float* l = llama_get_logits_ith(ctx, -1); std::memcpy(gen_logits.data(), l, sizeof(float) * (size_t)n_vocab); }
        if (t >= 6) {   // one sentence: stop at the first close after enough to be a line
            const std::string& s = aborted ? killed : say;
            const char lc = s.empty() ? 0 : s[s.size() - 1];
            if (lc == '.' || lc == '!' || lc == '?') break;
        }
        // THE WINDOW IN THE BLIND WINDOW. Percepts never wait for a sentence to finish — not even for
        // the silent remainder after a kill.
        const llama_pos np_before = npast;
        const uint64_t frames_before = frames_completed;
        drain_intake();                       // ingests onto TRUNK; judgments are deferred (gen_depth > 0)
        if (!g_run.load(std::memory_order_acquire)) break;
        if (aborted) continue;                // the world already answered; the rest is record, not decision
        if (frames_completed != frames_before && npast != np_before) {
            // A whole frame landed while this seat was mid-sentence (the rest of the line it was
            // judging, or a newer line). Did the world answer first?
            // (a) deterministic: the newest line ACCEPTS what this seat is saying → settled.
            // (b) the seat itself, re-probed on a fresh fork of the UPDATED trunk: margin ≤ 0 → it
            //     would not have spoken now. Either kills the forming line. Only commits kill.
            const std::string newest = !cur_tail_line.empty() ? cur_tail_line
                                     : !tailq.empty() ? tailq.back().first : clause;
            bool settled = looks_like_acceptance(newest) && content_overlap(newest, say) >= 1;
            float m2 = margin;
            if (!settled) m2 = probe_one(m);
            if (settled || m2 <= 0.0f) {
                aborted = true;
                char c[96]; std::snprintf(c, sizeof(c), settled ? "settled_by_world" : "margin_flipped:%+.2f", m2);
                cause = c;
                if (surface_on) std::printf(" ⟵ [un-said: %s]", cause.c_str());
                // no break: the remainder is generated silently (D2), the seam stays open for intake
            }
        }
    }
    --gen_depth;
    llama_memory_seq_rm(mem, GEN, -1, -1);
    gen_ms = wall_ms() - g0;
    if (surface_on) {
        if (aborted) std::printf("\n  └─ killed: \"%s\"\n", killed.c_str());
        else         std::printf("\n  └─\n");
    }
    return !aborted;
}

// =====================================================================================================
// §14 · THE JUDGMENT — three seats, dial ZERO, the VERBATIM probe; then the manners; then the record
// =====================================================================================================

void Kernel::judge_and_maybe_emit(const char* reason, float bscore, llama_pos at) {
    if (clause.empty()) return;
    const llama_pos at_pos = (at < 0) ? npast : at;
    const bool late = at_pos < npast;   // a deferred judgment: judged NOW, recorded as late (see probe_one)
    ++boundaries; vitals.boundaries.store((uint64_t)boundaries);
    if (!std::strcmp(reason, "c")) { ++coarse_boundaries; vitals.coarse.store((uint64_t)coarse_boundaries); }
    const bool surface_on = (Switch)vitals.sw.load() != Switch::Off;

    // Did the world just settle something a seat raised? Acceptance is TARGETED (≥1 content word
    // from the seat's own last line). A settled condition never fires again; an unaddressed one may.
    if (looks_like_acceptance(clause))
        for (int m = 0; m < 3; ++m)
            if (!last_say[m].empty() && !resolved[m] && content_overlap(clause, last_say[m]) >= 1) {
                resolved[m] = true; cond_open[m] = false; ++conditions_resolved;
                char b[512];
                std::snprintf(b, sizeof(b), "{\"k\":\"e_resolved\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"by\":\"",
                              boundaries, rel_ms(), MINDS[m].name);
                tape.put(std::string(b) + jesc(clause) + "\"");
            }

    // THE PROBE (verbatim frame, dial 0)
    const uint64_t t_probe0 = wall_ms();
    float margins[3];
    for (int m = 0; m < 3; ++m) margins[m] = probe_one(m);
    const uint64_t probe_ms = wall_ms() - t_probe0;
    if (!g_run.load(std::memory_order_acquire)) return;   // a probe failed: fatal already on the tape
    vitals.probe_ms_last.store(probe_ms);
    if (probe_ms > vitals.probe_ms_max.load()) vitals.probe_ms_max.store(probe_ms);

    // Snapshot the judged clause and reset the accumulator NOW: words that land while a seat speaks
    // begin a fresh clause (judged afterwards, reason "d"), never appended to the one under judgment.
    const std::string judged = clause, judged_lane = cur_lane;
    const double j_surp_mean = cl_surp_n ? cl_surp_sum / cl_surp_n : 0.0, j_surp_max = cl_surp_max;
    const uint64_t j_arrival = cur_delta_arrival, j_ingest_ms = cl_ingest_ms;
    const bool j_replay = cur_replay;
    clause.clear(); clause_toks = 0; last_flush_ms = wall_ms();
    cl_surp_sum = 0; cl_surp_max = 0; cl_surp_n = 0; cl_ingest_ms = 0;

    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};
    for (int m = 0; m < 3; ++m) {
        if (margins[m] <= 0.0f) continue;
        std::string say;
        const bool whole = speak(m, margins[m], say, aired[m], killed[m], causes[m], gen_ms_a[m]);
        says[m] = say;
        if (!whole) {
            // THE UN-SAY (P1). `reached_air` is the prefix that reached the surface; `killed` is everything
            // that did not — the unsurfaced part of what was formed plus the remainder sampled silently
            // after the kill — so the tape holds the counterfactual. Whatever reached the air IS a percept
            // and commits on the seat's lane WITH AN INTERRUPTION MARKER, so the mind can tell a line that
            // was cut off from a one-word line. Only commits kill; the record shows exactly which words did.
            ++n_unsaid; vitals.unsaid.store((uint64_t)n_unsaid); unsaid_a[m] = true;
            const std::string unsurfaced = say.size() > aired[m].size() ? say.substr(aired[m].size()) : std::string();
            const std::string killed_all = unsurfaced + killed[m];
            tape.put("{\"k\":\"unsaid\",\"i\":" + std::to_string(boundaries) + ",\"ms\":" + fmt0(rel_ms()) + ",\"mind\":" + jq(MINDS[m].name) +
                     ",\"m\":" + fmt2(margins[m]) + ",\"gen_ms\":" + u64s(gen_ms_a[m]) + ",\"cause\":" + jq(causes[m]) +
                     ",\"reached_air\":" + jq(aired[m]) + ",\"killed\":" + jq(killed_all) + ",\"killed_next\":" + (cfg.killed_full ? "false" : "true") +
                     ",\"clause\":" + jq(judged));
            write_verdict(judged_lane, m, "abort", margins[m], aired[m] + killed_all, causes[m].c_str());
            last_unsaid[m] = aired[m] + killed_all; last_unsaid_ms[m] = wall_ms();
            last_unsaid_settled[m] = causes[m] == "settled_by_world";
            if (!aired[m].empty() && !cfg.pure) {
                pending_commits.push_back(std::string("\n[") + MINDS[m].name + "] " + aired[m] + " —");
                own_lines.emplace_back(aired[m], wall_ms());
            }
            continue;
        }
        // Already said this, recently? Log it; do not say it twice — unless the suppression EXPIRED
        // (time) or was RE-ARMED (≥2 content words: the topic genuinely came back up). RESOLVED and
        // UNADDRESSED are different states; only the second may ever fire again.
        const bool dup      = near_dup(say, last_say[m]);
        const bool in_win   = (boundaries - last_say_i[m]) <= 40 && (wall_ms() - last_say_ms[m]) <= SUPP_TTL_MS;
        const bool re_armed = dup && content_overlap(judged, last_say[m]) >= 2 && !resolved[m];
        if (dup && resolved[m]) {
            ++n_supp;
            char b[512];
            std::snprintf(b, sizeof(b), "{\"k\":\"e_suppressed\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"reason\":\"resolved\",\"say\":\"",
                          boundaries, rel_ms(), MINDS[m].name, margins[m]);
            tape.put(std::string(b) + jesc(say) + "\"");
            write_verdict(judged_lane, m, "flag", margins[m], say, "resolved");
            says[m].clear(); continue;   // suppressed = NOT surfaced-as-new: the e stream must not carry it
        }
        if (dup && in_win && !re_armed) {
            ++n_supp;
            char b[512];
            std::snprintf(b, sizeof(b), "{\"k\":\"e_suppressed\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"reason\":\"repeat\",\"say\":\"",
                          boundaries, rel_ms(), MINDS[m].name, margins[m]);
            tape.put(std::string(b) + jesc(say) + "\",\"clause\":\"" + jesc(judged) + "\"");
            write_verdict(judged_lane, m, "flag", margins[m], say, "repeat");
            says[m].clear(); continue;
        }
        // THE INTERRUPTION BUDGET (deterministic, disclosed). The word-overlap valve above catches a
        // repeat only when the words repeat; a seat can restate one condition in fresh words at the
        // very next boundary (measured 2026-09-04, resume run: the SENTINEL twice in 800 ms). The
        // …
        if (cfg.refractory_s > 0 && last_say_ms[m] && !re_armed &&
            wall_ms() - last_say_ms[m] < (uint64_t)cfg.refractory_s * 1000ull) {
            ++n_supp;
            char b[512];
            std::snprintf(b, sizeof(b), "{\"k\":\"e_suppressed\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"reason\":\"refractory\",\"say\":\"",
                          boundaries, rel_ms(), MINDS[m].name, margins[m]);
            tape.put(std::string(b) + jesc(say) + "\",\"clause\":\"" + jesc(judged) + "\"");
            write_verdict(judged_lane, m, "flag", margins[m], say, "refractory");
            says[m].clear(); continue;
        }
        if (dup) {   // it repeats, but legitimately — say why, so the corpus shows the manners
            if (re_armed) ++conditions_rearmed; else ++conditions_expired;
            char b[512];
            std::snprintf(b, sizeof(b), "{\"k\":\"e_rearm\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"why\":\"%s\",\"say\":\"",
                          boundaries, rel_ms(), MINDS[m].name, re_armed ? "evidence" : "expired");
            tape.put(std::string(b) + jesc(say) + "\"");
        }
        if (!dup || !cond_open[m]) { ++conditions_opened; cond_open[m] = true; resolved[m] = false; }
        ++n_emits; vitals.emits.store((uint64_t)n_emits);
        last_say[m] = say; last_say_i[m] = boundaries; last_say_ms[m] = wall_ms();
        // The surface already happened (streamed as it formed). Because it REALLY said it, it is part
        // of the world and commits on the seat's own lane — AFTER the world's current line closes.
        // In `off` nothing reached anyone: recorded, not committed (the same semantics as --pure).
        if (surface_on && !cfg.pure) { pending_commits.push_back(std::string("\n[") + MINDS[m].name + "] " + say); own_lines.emplace_back(say, wall_ms()); }
        write_verdict(judged_lane, m, is_wake_lane(judged_lane) ? "wake" : "emit", margins[m], say, nullptr);
    }
    // holds: silence, on the record, with its margin
    for (int m = 0; m < 3; ++m) if (margins[m] <= 0.0f) { ++holds; write_verdict(judged_lane, m, "hold", margins[m], "", nullptr); }
    vitals.holds.store((uint64_t)holds);
    // gear 2: escalate on MARGIN, not on event — a thin margin either way is "I cannot rank this"
    for (int m = 0; m < 3; ++m) if (std::fabs(margins[m]) < cfg.ask_band) write_brief(judged_lane, judged, m, margins[m]);

    // latency-to-notice: arrival of the delta that closed this clause -> judgment done
    const uint64_t lat = wall_ms() - (j_arrival ? j_arrival : wall_ms());
    lat_sum += lat; if (lat > lat_max) lat_max = lat; vitals.lat_ms_last.store(lat);
    const bool sref = is_self_ref(judged);
    if (sref) ++n_self_ref;
    char b[1024];
    std::snprintf(b, sizeof(b),
        "{\"k\":\"b\",\"i\":%ld,\"ms\":%.0f,\"t_mono_ns\":%llu,\"lane\":\"%s\",\"reason\":\"%s\",\"at\":%d,\"now\":%d,\"late\":%s,\"covers\":%d,\"score\":%.2f,"
        "\"lat_ms\":%llu,\"probe_ms\":%llu,\"ingest_ms\":%llu,\"mib_free\":%llu,\"surp_mean\":%.2f,\"surp_max\":%.2f,\"self_ref\":%s,"
        "\"state\":\"%s\",\"m_spk\":%.2f,\"m_skp\":%.2f,\"m_sen\":%.2f,%s\"clause\":\"",
        boundaries, rel_ms(), (unsigned long long)mono_ns(), jesc(judged_lane).c_str(), reason, (int)at_pos, (int)npast,
        late ? "true" : "false", deferred_covers, bscore,
        (unsigned long long)lat, (unsigned long long)probe_ms, (unsigned long long)j_ingest_ms,
        (unsigned long long)vitals.mib_free.load(),
        j_surp_mean, j_surp_max, sref ? "true" : "false", switch_name((Switch)vitals.sw.load()),
        margins[0], margins[1], margins[2], j_replay ? "\"replay\":true," : "");
    tape.put(std::string(b) + jesc(judged) + "\"");
    for (int m = 0; m < 3; ++m)
        if (margins[m] > 0.0f && !says[m].empty() && !unsaid_a[m]) {
            // e = SURFACED ONLY; events = e + e_suppressed + unsaid, by addition, never by conflation.
            std::snprintf(b, sizeof(b),
                "{\"k\":\"e\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"gen_ms\":%llu,\"reason\":\"%s\","
                "\"self_ref\":%s,\"aired\":%s,\"say\":\"",
                boundaries, rel_ms(), MINDS[m].name, margins[m], (unsigned long long)gen_ms_a[m], reason,
                sref ? "true" : "false", surface_on ? "true" : "false");
            tape.put(std::string(b) + jesc(says[m]) + "\",\"clause\":\"" + jesc(judged) + "\"");
        }
}

// =====================================================================================================
// §15 · INTAKE — lines begin, words land, lines end; own speech is placed after the line
// =====================================================================================================

// Silence before a frame becomes world (ticks-as-world, not a poll): one lazy tick per gap.
void Kernel::tick_before(uint64_t arrive_ms) {
    const uint64_t gap = arrive_ms > last_delta_ms ? arrive_ms - last_delta_ms : 0;
    if (cfg.idle_tick_s > 0 && gap > (uint64_t)cfg.idle_tick_s * 1000ull) {
        char tb[64]; std::snprintf(tb, sizeof(tb), "\n[tick +%llus]", (unsigned long long)(gap / 1000));
        trunk_text(tb, false); ++ticks; tail_push_line(tb + 1);
        tape.put("{\"k\":\"tick\",\"ms\":" + fmt0(rel_ms()) + ",\"gap_s\":" + u64s(gap / 1000));
    }
}
// D1: is this seat-lane frame this process's own line coming back around a bridge? Near-dup against
// every own line inside the echo window (older ones are pruned here).
bool Kernel::is_own_echo(const std::string& text) {
    const uint64_t now = wall_ms(), win = (uint64_t)cfg.echo_window_s * 1000ull;
    while (!own_lines.empty() && now - own_lines.front().second > win) own_lines.pop_front();
    for (auto& o : own_lines) if (ieq(text, o.first.c_str()) || near_dup(text, o.first)) return true;
    return false;
}
// D1: a seat-lane / `self` frame that is NOT an echo is a percept: it lands on the trunk, in order, on
// its own lane, and is never judged (no self-judging). The `heard` row records it; `echo_late` marks
// the kill condition of the echo window — a heard line that equals an own line older than the window.
void Kernel::heard_line(const Delta& d) {
    if (line_open) end_line();
    tick_before(d.arrive_ms);
    last_delta_ms = d.arrive_ms; last_frame_wall_ms = epoch_ms();
    bool late = false;
    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
    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;
    if (!trunk_text(std::string("\n[") + d.lane + "] " + d.text, false)) return;
    tail_push_line(std::string("[") + d.lane + "] " + d.text);
    ++n_heard;
    tape.put("{\"k\":\"heard\",\"ms\":" + fmt0(rel_ms()) + ",\"lane\":" + jq(d.lane) + ",\"len\":" + std::to_string(d.text.size()) +
             (late ? ",\"echo_late\":true" : ""));
    std::printf("%s  · [%s] %s   (heard, not judged)\n", gen_depth > 0 ? "\n" : "", d.lane.c_str(), d.text.c_str());
}
void Kernel::begin_line(const Delta& d) {
    tick_before(d.arrive_ms);
    last_delta_ms = d.arrive_ms; cur_delta_arrival = d.arrive_ms; cur_delta_t_mono = d.t_mono_ns;
    last_frame_wall_ms = epoch_ms();   // persisted in .meta so a restored trunk can be told how long it was away
    cur_lane = d.lane;
    trunk_text(std::string("\n[") + d.lane + "] ", false);
    cur_tail_line = std::string("[") + d.lane + "]";
    line_open = true; line_fresh = true;
    std::printf("%s  · [%s] %s\n", gen_depth > 0 ? "\n" : "", d.lane.c_str(), d.text.c_str());
}
void Kernel::end_line() {
    if (!clause.empty()) {
        if (gen_depth > 0) defer_judgment(0.f);
        else judge_and_maybe_emit("f", 0.0f);   // the line ended: a real final
    }
    if (!cur_tail_line.empty()) { tail_push_line(cur_tail_line); cur_tail_line.clear(); }
    line_open = false;
    flush_pending_commits();   // own speech, placed after the line it illuminated
}
void Kernel::ingest_delta(Delta& d) {
    ++n_deltas; vitals.deltas.store((uint64_t)n_deltas);
    // P3/F1: a frame the previous life already ingested past its last checkpoint is replayed into the
    // restored trunk and says so on its rows (at-least-once, never silent).
    cur_replay = replay_until != 0 && d.end_off != 0 && d.end_off <= replay_until;
    if (cur_replay) ++replayed_frames;
    // D1: seat lanes and `self`, deduped by CONTENT, not by lane. A frame that near-dups a line this
    // process put on the air inside the echo window is that line coming back around a bridge: counted,
    // never double-entered. Any other seat-lane or `self` frame is a percept: heard, never judged.
    // Under --pure nothing a seat says re-enters the trunk, so every seat-lane frame is skipped.
    if (seat_of_lane(d.lane) >= 0) {
        if (cfg.pure || is_own_echo(d.text)) { ++echo_skipped; return; }
        heard_line(d); return;
    }
    if (d.grain == "forming") { forming[d.lane] = d.text; ++n_forming; return; }   // reflex plane: never on the trunk
    if (ieq(d.lane, "counsel") && !counsel_admit(d)) return;                        // stale counsel: discarded, on the tape
    if (line_open) end_line();
    begin_line(d);
    line_words.clear();
    for (size_t p = 0; p < d.text.size();) {
        size_t q = d.text.find(' ', p);
        if (q == std::string::npos) q = d.text.size();
        if (q > p) line_words.push_back(d.text.substr(p, q - p));
        p = q + 1;
    }
    while (g_run.load(std::memory_order_acquire) && !line_words.empty()) feed_word();
    end_line();
    forming.erase(d.lane);   // a committed line supersedes whatever was forming on its lane
}
// One word of the open line lands on the trunk. Called by the line's own loop, and by the drain
// while a seat is speaking — so the rest of the line arrives during the sentence, in order, exactly
// as it would from a live keyboard.
void Kernel::feed_word() {
    if (line_words.empty()) return;
    const std::string w = line_words.front(); line_words.pop_front();
    const bool fresh = line_fresh; line_fresh = false;
    // The accumulator takes the word BEFORE the trunk does. S0 appended after ingest, so its judged
    // clause always lacked the word that triggered the boundary and the line's last word was
    // re-probed alone as a fragment; with intake reentrant during speech, the late append also put
    // the triggering word behind everything fed meanwhile — out of order. Measured 2026-09-04.
    clause += (clause.empty() ? "" : " ") + w;
    cur_tail_line += " " + w;
    ingest_word(fresh ? w : " " + w);
    if (line_words.empty()) ++frames_completed;   // the frame's last word is on the trunk
}
// A judgment requested while a seat is speaking is queued with its clause, lane, arrival and nerve
// stats, and the accumulator is cleared so the next words start a fresh clause. Nothing is dropped;
// the judgment is delayed, and the record says so (reason "d").
void Kernel::defer_judgment(float score) {
    if (clause.empty()) return;
    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});
    clause.clear(); clause_toks = 0; last_flush_ms = wall_ms();
    cl_surp_sum = 0; cl_surp_max = 0; cl_surp_n = 0; cl_ingest_ms = 0;
}
// Deferred judgments (and a molt) are paid here, only when no seat is speaking. Because a judgment
// can only be about the trunk as it stands now (see probe_one), everything that landed during one
// blind window is judged ONCE, as one clause spanning its boundaries (`covers`), at the current
// …
void Kernel::settle_deferred() {
    if (gen_depth != 0) return;
    if (!deferred.empty()) {
        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};
        clause.clear(); clause_toks = 0; cl_surp_sum = 0; cl_surp_max = 0; cl_surp_n = 0; cl_ingest_ms = 0;
        while (g_run.load(std::memory_order_acquire) && !deferred.empty() && gen_depth == 0) {
            // fold the whole window into one clause: earliest arrival, latest lane, stats summed
            Deferred d = std::move(deferred.front()); deferred.pop_front();
            int covers = 1;
            while (!deferred.empty()) {
                const Deferred& n = deferred.front();
                d.clause += (d.clause.empty() ? "" : " ") + n.clause;
                d.lane = n.lane; d.score = n.score; d.replay = n.replay;
                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;
                d.toks += n.toks; d.ingest_ms += n.ingest_ms;
                deferred.pop_front(); ++covers;
            }
            clause = d.clause; cur_lane = d.lane; cur_delta_arrival = d.arrival; cur_replay = d.replay;
            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;
            deferred_covers = covers;
            judge_and_maybe_emit("d", d.score, d.npast_at);
            deferred_covers = 1;
            n_deferred += covers;
            // words that gathered during this judgment's speech (and any newly deferred items) loop again
        }
        // restore the live accumulator, then append anything that gathered during the last item
        const std::string later = clause; const int later_toks = clause_toks;
        const double ls = cl_surp_sum, lm = cl_surp_max; const int ln = cl_surp_n; const uint64_t li = cl_ingest_ms;
        clause = live.clause; clause_toks = live.toks; cur_lane = live.lane; cur_delta_arrival = live.arrival; cur_replay = live.replay;
        cl_surp_sum = live.surp_sum; cl_surp_max = live.surp_max; cl_surp_n = live.surp_n; cl_ingest_ms = live.ingest_ms;
        if (!later.empty()) {
            clause += (clause.empty() ? "" : " ") + later; clause_toks += later_toks;
            cl_surp_sum += ls; if (lm > cl_surp_max) cl_surp_max = lm; cl_surp_n += ln; cl_ingest_ms += li;
        }
    }
    if (molt_pending && gen_depth == 0) { if (!clause.empty()) judge_and_maybe_emit("m", 0.f); do_molt(); }
}
void Kernel::drain_intake() {
    // the open line's remaining words are the next percepts, in order — before any newer frame
    while (g_run.load(std::memory_order_acquire) && line_open && !line_words.empty()) feed_word();
    Delta d;
    while (g_run.load(std::memory_order_acquire) && tail->poll(d)) {
        backlog_now = tail->pending();
        ingest_delta(d);
        tail->ingested_off.store(d.end_off);   // F1: the cursor follows what is ON THE TRUNK
    }
    vitals.spool_offset.store(tail->offset.load()); vitals.spool_unread.store(tail->unread_bytes());
}

// =====================================================================================================
// §16 · THE LIVE LOOP
// =====================================================================================================

void Kernel::run() {
    std::printf("[fusord] resident on %s — watching. Ctrl-C to stop.\n"
                "         switch=%s (fusord.state is yours alone) · nothing is asked of the model, ever.\n\n",
                cfg.model.c_str(), switch_name((Switch)vitals.sw.load()));
    uint64_t last_idle_tick_ms = wall_ms();
    while (g_run.load(std::memory_order_acquire) && (cfg.max_toks == 0 || npast < cfg.max_toks)) {
        Delta d;
        report_rename_failures();   // F3: a pill or cursor that could not be replaced is on the tape, not silent
        backlog_now = tail->pending();
        if (tail->poll(d)) {
            ingest_delta(d);
            tail->ingested_off.store(d.end_off);   // F1: the cursor follows what is ON THE TRUNK
            settle_deferred();   // anything deferred while a seat spoke is paid now, in order
            last_idle_tick_ms = wall_ms();
            vitals.spool_offset.store(tail->offset.load()); vitals.spool_unread.store(tail->unread_bytes());
        } else {
            // Idle: the RING sleeps, never the GPU. Silence is a lane: long silence enters the trunk
            // as ticks even when nothing follows, so the mind's sense of time is never stale.
            if (!line_open) flush_pending_commits();
            const uint64_t now = wall_ms();
            if (cfg.idle_tick_s > 0 && now - last_idle_tick_ms > (uint64_t)cfg.idle_tick_s * 1000ull && !line_open) {
                char tb[64]; std::snprintf(tb, sizeof(tb), "\n[tick +%llus]", (unsigned long long)((now - last_idle_tick_ms) / 1000));
                trunk_text(tb, false); ++ticks; tail_push_line(tb + 1);
                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));
                tape.put(b);
                last_idle_tick_ms = last_delta_ms = now;
            }
            if (now - last_vram_ms > 60000) read_vram(true);
            // P3: the periodic checkpoint is taken only when the world is QUIET — no open line, no seat
            // speaking, nothing deferred, nothing pending on the ring, and two seconds since the last
            // frame — so the trunk and the cursor it records agree about what the resident has seen.
            const bool quiet = !line_open && gen_depth == 0 && deferred.empty() && backlog_now == 0 &&
                               tail->pending() == 0 && now - last_delta_ms >= 2000;
            if (!cfg.ckpt.empty() && quiet &&
                (ckpt_due || (cfg.ckpt_every_s > 0 && now - last_ckpt_ms > (uint64_t)cfg.ckpt_every_s * 1000ull)))
                checkpoint(ckpt_due ? "molt" : "periodic");
            std::this_thread::sleep_for(std::chrono::milliseconds(5));
        }
    }
}

void Kernel::shutdown(const char* stopped) {
    if (!line_open) flush_pending_commits();
    if (!cfg.ckpt.empty()) checkpoint("stop");
    tail->stop(); pill.stop();
    const double total = rel_ms();
    // The end row is built from strings (F6, review correction 5): every counter this pass adds lands here.
    auto L = [](long x) { return std::to_string(x); };
    std::string b = std::string("{\"k\":\"end\",\"words\":") + L(words) + ",\"toks\":" + std::to_string((int)npast) +
        ",\"boundaries\":" + L(boundaries) + ",\"holds\":" + L(holds) + ",\"emits\":" + L(n_emits) + ",\"ticks\":" + L(ticks) +
        ",\"molts\":" + L(n_molts) + ",\"molt_outage_ms\":" + u64s(molt_outage_total) + ",\"deltas\":" + L(n_deltas) +
        ",\"echo_skipped\":" + L(echo_skipped) + ",\"heard\":" + L(n_heard) + ",\"self_ref_boundaries\":" + L(n_self_ref) +
        ",\"suppressed_repeats\":" + L(n_supp) + ",\"coarse_boundaries\":" + L(coarse_boundaries) + ",\"deferred_boundaries\":" + L(n_deferred) +
        ",\"ring_dropped\":0,\"ring_stalls\":" + u64s(tail->stalls.load()) + ",\"spool_lines\":" + u64s(tail->lines.load()) +
        ",\"spool_resets\":" + u64s(tail->reset_events.load()) + ",\"unsaid\":" + L(n_unsaid) + ",\"briefs\":" + L(n_briefs) +
        ",\"counsel_in\":" + L(n_counsel) + ",\"counsel_discarded\":" + L(n_discard) + ",\"forming_frames\":" + L(n_forming) +
        ",\"conditions_opened\":" + L(conditions_opened) + ",\"conditions_resolved\":" + L(conditions_resolved) +
        ",\"conditions_expired\":" + L(conditions_expired) + ",\"conditions_rearmed\":" + L(conditions_rearmed) +
        ",\"emits_per_boundary\":" + fmt3(boundaries ? (double)n_emits / (double)boundaries : 0.0) +
        ",\"emits_per_condition\":" + fmt3(conditions_opened ? (double)n_emits / (double)conditions_opened : 0.0) +
        ",\"surp_mean_all\":" + fmt3(all_surp_n ? all_surp_sum / (double)all_surp_n : 0.0) +
        ",\"mean_lat_ms\":" + fmt0(boundaries ? (double)lat_sum / (double)boundaries : 0.0) + ",\"max_lat_ms\":" + u64s(lat_max) +
        ",\"mib_free\":" + u64s(vitals.mib_free.load()) + ",\"rename_failures\":" + u64s(g_rename_failures.load(std::memory_order_relaxed)) +
        ",\"replayed_frames\":" + L(replayed_frames) + ",\"wall_ms\":" + fmt0(total) + ",\"stopped\":" + jq(stopped);
    tape.put(b);
    tape.close(); verdicts.close(); briefs.close();

    std::printf("\n===== FUSORD DOWN =====\n");
    std::printf("uptime %s · deltas=%ld words=%ld trunk_toks=%d · spool lines=%llu resets=%llu ring stalls=%llu (dropped: 0 by construction)\n",
                fmt_hms(total).c_str(), n_deltas, words, (int)npast, (unsigned long long)tail->lines.load(),
                (unsigned long long)tail->reset_events.load(), (unsigned long long)tail->stalls.load());
    std::printf("boundaries=%ld (coarse %ld · deferred %ld) holds=%ld emits=%ld unsaid=%ld ticks=%ld molts=%ld\n",
                boundaries, coarse_boundaries, n_deferred, holds, n_emits, n_unsaid, ticks, n_molts);
    std::printf("conditions opened=%ld resolved=%ld expired=%ld re-armed=%ld · emits/boundary %.4f · emits/condition %.4f  [two grains, never one ratio]\n",
                conditions_opened, conditions_resolved, conditions_expired, conditions_rearmed,
                boundaries ? (double)n_emits / (double)boundaries : 0.0,
                conditions_opened ? (double)n_emits / (double)conditions_opened : 0.0);
    std::printf("gear 2: briefs=%ld counsel in=%ld discarded stale=%ld\n", n_briefs, n_counsel, n_discard);
    std::printf("F-KEEPUP (live): latency-to-notice mean %.0f ms · max %llu ms  [arrival -> judged] · free VRAM %llu MiB\n",
                boundaries ? (double)lat_sum / (double)boundaries : 0.0, (unsigned long long)lat_max,
                (unsigned long long)vitals.mib_free.load());
    std::printf("nerve: mean surprisal %.2f nats (logged, gating NOTHING — measured 2026-08-12)\n",
                all_surp_n ? all_surp_sum / (double)all_surp_n : 0.0);
    if (echo_skipped || n_heard) std::printf("seat-lane frames: echoes skipped %ld · heard, not judged %ld\n", echo_skipped, n_heard);
    std::printf("tape: %s   (next: soak --brief · soak --review · verify the chain from genesis)\n", tape.path.c_str());

    if (smp_scribe) llama_sampler_free(smp_scribe);
    if (smp) llama_sampler_free(smp);
    if (ctx) llama_free(ctx);
    if (mdl) llama_model_free(mdl);
    llama_backend_free();
}

} // namespace fusor

// =====================================================================================================
// §17 · MAIN — the console, the stop signal, the arguments, the mark before the model
// =====================================================================================================

#if defined(_WIN32)
static BOOL WINAPI ctrl_handler(DWORD t) {
    if (t == CTRL_C_EVENT || t == CTRL_BREAK_EVENT || t == CTRL_CLOSE_EVENT) {
        fusor::g_run.store(false, std::memory_order_release);
        std::printf("\n[fusord] stop requested — finishing the tape…\n");
        return TRUE;
    }
    return FALSE;
}
#else
static void sig_handler(int) { fusor::g_run.store(false, std::memory_order_release); }
#endif

static void usage() {
    std::printf(
        "usage: fusord <spool> [--model p] [--out-dir d] [--molt-wm N] [--idle-tick-s N]\n"
        "              [--from-start | --from-end] [--max-toks N] [--pure] [--kv-f16]\n"
        "              [--ckpt p] [--resume] [--cold] [--ckpt-every-s N]\n"
        "              [--ask-band F] [--stale-tok N] [--refractory-s N] [--wake-lanes a,b,c]\n"
        "              [--killed-next] [--echo-window-s N] [--n-ctx N] [--allow-cpu] [--egress-unchecked]\n"
        "              [--model-sha256 HEX] [--sha-cache FILE] [--about] [--serve-hash]\n"
        "  the spool is tailed as lane-contract v0.1 (t_mono_ns<TAB>lane<TAB>grain<TAB>text),\n"
        "  legacy (lane<TAB>text) or bare text (lane 'bo'); it resumes from <spool>.cursor unless told otherwise.\n"
        "  <out-dir>/fusord.state (off|shadow|live) is the operator's switch; the kernel never writes it.\n");
}

int main(int argc, char** argv) {
#if defined(_WIN32)
    SetConsoleOutputCP(CP_UTF8);
    setvbuf(stdout, nullptr, _IONBF, 0);
    SetConsoleCtrlHandler(ctrl_handler, TRUE);
#else
    setvbuf(stdout, nullptr, _IONBF, 0);
    std::signal(SIGINT, sig_handler); std::signal(SIGTERM, sig_handler);
#endif
    fusor::Kernel k;
    fusor::Config& c = k.cfg;
    bool want_hash = false, want_about = false;
    for (int i = 1; i < argc; ++i) {
        auto next = [&](const char* flag) -> const char* {
            if (!std::strcmp(argv[i], flag) && i + 1 < argc) return argv[++i];
            return nullptr;
        };
        const char* v;
        if      ((v = next("--model")))        c.model = v;
        else if ((v = next("--out-dir")))      c.out_dir = v;
        else if ((v = next("--out")))          c.out_dir = v;            // S0's flag name, kept
        else if ((v = next("--molt-wm")))      c.molt_wm = std::atol(v);
        else if ((v = next("--max-toks")))     c.max_toks = std::atol(v);
        else if ((v = next("--idle-tick-s")))  c.idle_tick_s = std::atol(v);
        else if ((v = next("--ckpt")))         c.ckpt = v;
        else if ((v = next("--ckpt-every-s"))) c.ckpt_every_s = std::atol(v);
        else if ((v = next("--ask-band")))     c.ask_band = (float)std::atof(v);
        else if ((v = next("--stale-tok")))    c.stale_tok = std::atol(v);
        else if ((v = next("--refractory-s"))) c.refractory_s = std::atol(v);
        else if ((v = next("--echo-window-s"))) c.echo_window_s = std::atol(v);
        else if ((v = next("--n-ctx")))         c.n_ctx = std::atol(v);
        else if ((v = next("--model-sha256")))  c.model_sha256 = v;
        else if ((v = next("--sha-cache")))     c.sha_cache = v;
        else if (!std::strcmp(argv[i], "--killed-next")) c.killed_full = false;
        else if (!std::strcmp(argv[i], "--allow-cpu")) c.allow_cpu = true;
        else if (!std::strcmp(argv[i], "--egress-unchecked")) c.egress_unchecked = true;
        else if (!std::strcmp(argv[i], "--about")) want_about = true;
        else if ((v = next("--wake-lanes"))) {
            c.wake_prefixes.clear(); std::string s = v; size_t p = 0;
            while (p <= s.size()) { size_t q = s.find(',', p); if (q == std::string::npos) q = s.size();
                if (q > p) c.wake_prefixes.push_back(s.substr(p, q - p)); p = q + 1; }
        }
        else if (!std::strcmp(argv[i], "--from-start")) c.from_start = true;
        else if (!std::strcmp(argv[i], "--from-end"))   c.from_end = true;
        else if (!std::strcmp(argv[i], "--pure"))       c.pure = true;
        else if (!std::strcmp(argv[i], "--kv-f16"))     c.kv_q8 = false;
        else if (!std::strcmp(argv[i], "--resume"))     c.resume = true;
        else if (!std::strcmp(argv[i], "--cold"))       c.cold = true;
        else if (!std::strcmp(argv[i], "--serve-hash")) want_hash = true;
        else if (argv[i][0] != '-') c.spool = argv[i];
        else { std::printf("unknown flag %s\n", argv[i]); usage(); return 1; }
    }
    if (want_hash) {   // train ≡ serve, checkable with no model and no spool
        const uint64_t h = fusor::serve_hash();
        std::printf("serve-bytes hash 0x%016llx · pinned 0x%016llx · %s\n", (unsigned long long)h,
                    (unsigned long long)fusor::SERVE_HASH_PIN, h == fusor::SERVE_HASH_PIN ? "MATCH" : "DRIFT");
        return h == fusor::SERVE_HASH_PIN ? 0 : 2;
    }
    if (want_about) return fusor::about(c);   // the process receipt: no model, no spool
    if (c.spool.empty()) { usage(); return 1; }
    {   // the trunk can never be asked to hold more than the context (K3' clamp, review §4.6)
        const long nctx = c.n_ctx > 0 ? c.n_ctx : (c.kv_q8 ? 65536 : 32768);
        if (nctx < 2048) { std::printf("--n-ctx %ld is below 2048; refused\n", nctx); return 1; }
        if (c.molt_wm > 0 && c.molt_wm > nctx - 2048) {
            std::printf("[fusord] molt_wm %ld exceeds n_ctx %ld - 2048; clamped to %ld\n", c.molt_wm, nctx, nctx - 2048);
            c.molt_wm = nctx - 2048;
        }
        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; }
    }

    // THE MARK: where the spool ends NOW, before the model loads. Nothing that lands during the
    // seed is ever skipped (S0 opened at EOF after the load and missed the first two minutes).
    fusor::LaneTail tail(c.spool);
    tail.mark_now();
    k.tail = &tail;

    const int rc = k.boot();
    if (rc) return rc;
    k.run();
    k.shutdown((c.max_toks && k.npast >= c.max_toks) ? "trunk_full" : "stopped");
    return 0;
}

// ---- end of segment 3 -------------------------------------------------------------------------------
