// fusord.cpp
//
// FUSOR · THE RESIDENT KERNEL — v-next (Alpha sandbox rewrite, 2026-09-04)
//
// Lineage: fusord.cpp S0/Phase A (2026-08-11 → 08-12, two versions, both read in full). Everything
// those two versions PROVED is kept, byte-exact where the tune is conditioned on it; everything
// they MEASURED as a defect is fixed here by construction; and the four acts the estate's laws
// demand of a resident that the S0 kernel could not yet perform are added. Nothing else.
//
//   THE RULE THAT BREAKS EVERYTHING IF VIOLATED (train ≡ serve): SEED_SYS + SEED_EXAMPLES +
//   SEED_OPEN, the seat names and mandates, the "\n[SEAT — mandate]\nwatcher:" probe frame and
//   the speak-cue frame are VERBATIM from the v11 tune's serve format. The serve-bytes hash is
//   pinned (0xe7ffa5704ba31076) and asserted before the model loads. Exit 2 on drift.
//
// WHAT IS STRICTLY BETTER, and the law each item serves:
//
//   1. THE UN-SAY INSIDE THE BLIND WINDOW. S0 generated a whole sentence (≤28 tokens) blind: no
//      percept could land while a seat spoke. Here intake is drained after EVERY generated token;
//      a percept that lands mid-sentence is ingested at once (percepts are never dropped, judgment
//      may be delayed), the speaking seat is re-probed on a fresh fork of the updated trunk, and
//      if the world answered first the forming line is KILLED mid-word — the killed continuation,
//      the prefix that reached the surface, and the cause all go on the tape. Only commits kill.
//   2. OWN SPEECH IS A PERCEPT, HEARD NOT JUDGED, PLACED AFTER THE LINE IT ILLUMINATES. S0 spliced
//      "\n[SEAT] line" into the MIDDLE of the operator's line it was judging (the rest of that
//      line then continued with no lane prefix — a serve-format drift the tune never saw). Here a
//      seat's line is surfaced the instant it is said but COMMITS to the trunk after the world's
//      current line closes, on the seat's own lane; the gate never runs on it (no self-judging),
//      and spool frames on seat lanes / `self` are counted as already-heard, never double-entered.
//   3. THE TAPE IS HASH-CHAINED (BLAKE2b-256) AND THE CHAIN SURVIVES RESTARTS. Every record carries
//      prev/h; the previous head is recovered from the file at open. Same record kinds and keys as
//      S0 (hdr b e e_suppressed e_rearm e_resolved tick molt end) so `soak --brief/--review` read it
//      unchanged; new kinds are additive (unsaid brief counsel discard cursor ckpt vram).
//   4. THE LANE CONTRACT v0.1, READ NATIVELY. `#lane-contract v0.1 <venue> <t0_mono_ns>` header;
//      `t_mono_ns \t lane \t grain \t text` frames; legacy `lane \t text` and bare text still eat.
//      No 496-byte payload cap, no 15-char lane cap, no first-tab misparse. Torn last line waits.
//   5. A PERSISTED CURSOR, AND NOTHING LANDS WHILE THE MODEL LOADS. S0 opened at EOF after the
//      ~2-minute seed, so lines that landed during load were never seen; `--from-start` replayed
//      all history every restart. Here the spool offset is MARKED at process start (before the
//      model loads), the tail begins from the mark, the cursor is persisted with a prefix hash so
//      rotation/truncation is detected, and a restart resumes exactly where it stopped.
//   6. THE RING CANNOT DROP. S0 counted overflow loudly. Here the producer BLOCKS on a full ring —
//      the spool on disk is the backlog, so a percept is delayed, never lost. `ring_dropped` is 0
//      by construction and the stall count is printed instead.
//   7. THE VERDICT WIRE (ADDENDUM-F §3.3). Every seat, every boundary, one row: hold | emit | wake |
//      flag | abort, with margin, lane, seat, provenance, steer="unsteered", and the switch state.
//      Silence is on the record with its margin. Consumers gate under a writ; the kernel acts on
//      nothing. There is no `allow` verb and no action verb anywhere in this file.
//   8. TWO GEARS, AT THE SEAM. A thin margin (|m| < ask-band) writes a BRIEF (clause, held tail,
//      the question) to briefs.jsonl. Counsel returns on the spool as lane `counsel` tagged with the
//      brief id; it is ingested as testimony-with-a-source ONLY if the trunk moved less than the
//      staleness envelope since dispatch — otherwise DISCARDED, and the discard is a typed negative
//      on the tape. The kernel never opens a socket. Remote proposes; local disposes.
//   9. THE SWITCH AND THE PILL. `fusord.state` (off | shadow | live) is a file only the operator
//      writes; the kernel reads it every beat and never writes it. `off` = watch, judge, record;
//      no surface, no wire, no briefs (inert to the world mid-flight). `fusord.heartbeat.json` is
//      rewritten atomically every beat; staleness > 3 beats = STALLED, fail-loud for any reader.
//  10. THE TRUNK IS AN ASSET. `--ckpt` saves seq-0 KV + the token list at every molt, every N s,
//      and at stop; `--resume` reloads it so the resident's held state outlives the process; the
//      twin (`--cold`) rebuilds from the seed and is LABELED a twin on the tape.
//  11. VRAM ON THE TAPE. Free device memory at boot and periodically, beside every probe latency,
//      so a slow probe is never again mistaken for a dumb resident when the card was merely full.
//  12. CONDITION GRAIN, COUNTED. Conditions opened / resolved / expired / re-armed are counted and
//      printed; emits÷boundaries and emits÷conditions both print, never one ratio for both grains.
//  13. THE NERVE ON THE RIGHT DISTRIBUTION. S0 read surprisal off the context's last logits, which
//      after a probe or a fork decode belonged to DECIDE or GEN, not the trunk. The trunk's frontier
//      is copied at every trunk decode and the nerve reads the copy; generation likewise samples
//      from a saved copy of its own logits, which is what makes interleaved intake legal at all.
//
// WHAT IS UNCHANGED from S0 (all measured on 2026-08-12 and kept): the segmenter's boundary set
// (. ! ? newline EOG — not ; :), the flush law (boundary | 24 tok | 1500 ms, coarsened under
// backlog and COUNTED), the three-seat dial-0 probe, the one-sentence hard cap, the molt with the
// scribe rung and the verbatim tail, ticks-as-world, the nerve LOGGED and gating NOTHING, repeat
// suppression with TTL / evidence re-arm / targeted resolution, `--pure`, q8_0 KV by default.
//
// WHAT IS NOT CLAIMED: this file is written, not compiled. Two API families are used that the S0
// kernel did not touch and must be checked against the pinned llama.cpp headers on first build:
// `llama_state_seq_save_file / llama_state_seq_load_file` (the checkpoint) and
// `ggml_backend_dev_count / ggml_backend_dev_get / ggml_backend_dev_memory` (VRAM). Both exist in
// llama.cpp since 2024/2025; their exact signatures are the only thing to verify. No number in
// this file is a measurement of this file.
//
// Run:  fusord.exe <spool> [--model p] [--out-dir d] [--molt-wm N] [--idle-tick-s N]
//                          [--from-start | --from-end] [--max-toks N] [--pure] [--kv-f16]
//                          [--ckpt p] [--resume] [--cold] [--ask-band F] [--stale-tok N]
//                          [--wake-lanes a,b,c] [--ckpt-every-s N]
//
// Files under --out-dir (default runs/): fusor_ledger.jsonl (the tape) · verdicts.jsonl (the
// wire) · briefs.jsonl (gear-2 out) · fusord.state (the switch, operator-only) ·
// fusord.heartbeat.json (the pill) · <spool>.cursor (beside the spool).

#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>
#else
#  include <csignal>
#  include <unistd.h>
#endif

#include <algorithm>
#include <atomic>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#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();
}
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;
}
// 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.
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;
#if defined(_WIN32)
    return MoveFileExA(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING) != 0;
#else
    return std::rename(tmp.c_str(), path.c_str()) == 0;
#endif
}

// 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)
    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>
//   legacy : <lane>\t<text>
//   bare   : <text>                       -> lane "bo", grain commit
// Cursor: <spool>.cursor = "<offset>\t<fnv of the ≤4096 bytes before offset>\n". On resume the
// prefix hash must match, else the spool was rotated/truncated and the tail restarts at 0 (logged).
// The offset advances only after a frame is IN the ring (at-least-once on a crash mid-push; the
// tape is append-only so a replayed frame is visible, never silent).
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> 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.
    std::string resolve_start(TailFrom from, bool resume_cursor) {
        read_header();
        uint64_t n = 0; file_size_of(path, n);
        if (resume_cursor) {
            const std::string c = read_all(cursor_path, 256);
            if (!c.empty()) {
                const uint64_t off = std::strtoull(c.c_str(), nullptr, 10);
                const char* tab = std::strchr(c.c_str(), '\t');
                const uint64_t want = tab ? std::strtoull(tab + 1, nullptr, 16) : 0;
                if (off <= n && prefix_hash(off) == want) { offset.store(off); return "cursor"; }
                reset_events.fetch_add(1);
                offset.store(0); return "cursor_mismatch_rotation_reset";
            }
        }
        if (from == TailFrom::Start) { offset.store(0); return "from_start"; }
        if (from == TailFrom::End)   { offset.store(n); return "from_end"; }
        offset.store(std::min(mark.load(), n)); return "from_mark";
    }
    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 = offset.load();
        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; }
                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);   // advanced only once the frame is in the ring
            }
            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); }
    void write(bool final_beat) {
        char b[1024];
        std::snprintf(b, sizeof(b),
            "{\"state\":\"%s\",\"ts_ms\":%llu,\"t_mono_ns\":%llu,\"pid\":%d,\"final\":%s,"
            "\"npast\":%llu,\"deltas\":%llu,\"boundaries\":%llu,\"emits\":%llu,\"holds\":%llu,"
            "\"unsaid\":%llu,\"briefs\":%llu,\"counsel_in\":%llu,\"counsel_discarded\":%llu,"
            "\"probe_ms_last\":%llu,\"probe_ms_max\":%llu,\"lat_ms_last\":%llu,"
            "\"mib_free\":%llu,\"mib_total\":%llu,\"spool_offset\":%llu,\"spool_unread\":%llu,"
            "\"molts\":%llu,\"coarse\":%llu,\"beat_ms\":%llu}\n",
            switch_name((Switch)v->sw.load()), (unsigned long long)wall_ms(), (unsigned long long)mono_ns(),
            pid, final_beat ? "true" : "false",
            (unsigned long long)v->npast.load(), (unsigned long long)v->deltas.load(),
            (unsigned long long)v->boundaries.load(), (unsigned long long)v->emits.load(),
            (unsigned long long)v->holds.load(), (unsigned long long)v->unsaid.load(),
            (unsigned long long)v->briefs.load(), (unsigned long long)v->counsel_in.load(),
            (unsigned long long)v->counsel_discarded.load(), (unsigned long long)v->probe_ms_last.load(),
            (unsigned long long)v->probe_ms_max.load(), (unsigned long long)v->lat_ms_last.load(),
            (unsigned long long)v->mib_free.load(), (unsigned long long)v->mib_total.load(),
            (unsigned long long)v->spool_offset.load(), (unsigned long long)v->spool_unread.load(),
            (unsigned long long)v->molts.load(), (unsigned long long)v->coarse.load(),
            (unsigned long long)beat_ms);
        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;

    bool open(const std::string& p) {
        path = p;
        // Recover the chain head from the last record already on disk (a resident's tape outlives one
        // process; the chain must not restart at genesis or a reader sees a fork).
        uint64_t sz = 0;
        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);
                const size_t k = tail.rfind("\"h\":\"");
                if (k != std::string::npos && k + 5 + 64 <= tail.size()) prev = tail.substr(k + 5, 64);
            }
        }
        f = std::fopen(p.c_str(), "ab");
        return f != nullptr;
    }
    // body = a JSON object WITHOUT its closing brace, e.g. {"k":"tick","ms":12
    void put(const std::string& body) {
        if (!f) return;
        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;
    }
    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)
// =====================================================================================================

static void err_log(ggml_log_level level, const char* text, void*) {
    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
    std::vector<std::string> wake_prefixes = {"dsh-", "agent", "claude"};   // emit on these lanes → wake
};

// =====================================================================================================
// §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;

    // 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)
    std::deque<std::pair<std::string, int>> tailq; size_t tail_wc = 0;
    static constexpr size_t TAIL_MAX_WORDS = 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; };
    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

    // 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; }
    }

    // ---- 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);

    // ---- 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& cause,
               uint64_t& gen_ms);
    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);
}

// 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);
    dec(ctx, ct, SCRIBE, npast, true);
    llama_pos spos = npast + (llama_pos)ct.size();
    std::string rung; int rtoks = 0;
    for (int t = 0; t < 600; ++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};
        dec(ctx, one, SCRIBE, spos, true); ++spos; ++rtoks;
    }
    llama_memory_seq_rm(mem, SCRIBE, -1, -1);
    llama_memory_seq_rm(mem, TRUNK, -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);
    trunk_toks.clear(); npast = 0;
    dec(ctx, rt, TRUNK, 0, true);
    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()) checkpoint("molt");
}

// ---- the trunk is an asset: checkpoint and restore ---------------------------------------------------
// Sidecar <ckpt>.meta (line-oriented, no JSON parser needed):
//   model\t<path>  serve\t<hex>  npast\t<n>  prev\t<chain head>  t\t<wall_ms>  tail\t<line>...
bool Kernel::checkpoint(const char* why) {
    const uint64_t c0 = wall_ms();
    // NOTE: verify signature against the pinned llama.h on first build:
    //   bool llama_state_seq_save_file(ctx, filepath, seq_id, const llama_token* tokens, size_t n_token_count)
    const bool ok = llama_state_seq_save_file(ctx, cfg.ckpt.c_str(), TRUNK,
                                              trunk_toks.data(), trunk_toks.size()) != 0;   // returns bytes written
    if (ok) {
        std::string meta;
        char h[32]; std::snprintf(h, sizeof(h), "%016llx", (unsigned long long)serve_hash());
        meta += "model\t" + cfg.model + "\n";
        meta += std::string("serve\t") + h + "\n";
        meta += "npast\t" + std::to_string((long long)npast) + "\n";
        meta += "prev\t" + tape.prev + "\n";
        meta += "t\t" + std::to_string((unsigned long long)wall_ms()) + "\n";
        for (auto& p : tailq) meta += "tail\t" + p.first + "\n";
        write_atomic(cfg.ckpt + ".meta", meta);
    }
    last_ckpt_ms = wall_ms();
    char b[256];
    std::snprintf(b, sizeof(b), "{\"k\":\"ckpt\",\"ms\":%.0f,\"why\":\"%s\",\"toks\":%d,\"ok\":%s,\"dur_ms\":%llu",
                  rel_ms(), why, (int)npast, ok ? "true" : "false", (unsigned long long)(wall_ms() - c0));
    tape.put(b);
    return ok;
}
bool Kernel::restore() {
    const std::string meta = read_all(cfg.ckpt + ".meta", 1 << 20);
    if (meta.empty()) return false;
    std::string model_line, serve_line; std::vector<std::string> tails;
    size_t p = 0;
    while (p < meta.size()) {
        size_t q = meta.find('\n', p); if (q == std::string::npos) q = meta.size();
        const std::string ln = meta.substr(p, q - p); p = q + 1;
        if (starts_with(ln, "model\t")) model_line = ln.substr(6);
        else if (starts_with(ln, "serve\t")) serve_line = ln.substr(6);
        else if (starts_with(ln, "tail\t")) tails.push_back(ln.substr(5));
    }
    char h[32]; std::snprintf(h, sizeof(h), "%016llx", (unsigned long long)serve_hash());
    if (model_line != cfg.model || serve_line != h) {
        std::printf("[resume] checkpoint belongs to another model or serve format — starting cold (the twin).\n");
        return false;
    }
    std::vector<llama_token> buf((size_t)llama_n_ctx(ctx));
    size_t n = 0;
    // NOTE: verify signature against the pinned llama.h on first build:
    //   size_t llama_state_seq_load_file(ctx, filepath, dest_seq_id, llama_token* tokens_out,
    //                                    size_t n_token_capacity, size_t* n_token_count_out)
    const size_t got = llama_state_seq_load_file(ctx, cfg.ckpt.c_str(), TRUNK, buf.data(), buf.size(), &n);
    if (got == 0 || n == 0) { std::printf("[resume] checkpoint load failed — starting cold (the twin).\n"); return false; }
    buf.resize(n); trunk_toks = buf; npast = (llama_pos)n; vitals.npast.store((uint64_t)npast);
    have_logZ = false;                        // no frontier until the next decode
    for (auto& t : tails) tail_push_line(t);  // the verbatim tail comes back with the trunk
    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
    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; }
    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 (v-next · Alpha) =====\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
    ggml_backend_load_all_from_path(AURICLE_LLAMA_DIR);
    llama_log_set(err_log, nullptr); ggml_log_set(err_log, nullptr);
    llama_backend_init();
    read_vram(true);   // before the weights land: the room the resident is walking into

    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; }
    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.kv_q8 ? 65536 : 32768;   // 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 restored: %d tokens held. The mind picks up where it stopped.\n", (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)) { std::printf("seed FAILED\n"); return 1; }
        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
    }
    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, or from the cursor
    tail_start_reason = tail->resolve_start(cfg.from_start ? TailFrom::Start : cfg.from_end ? TailFrom::End : TailFrom::Mark,
                                            !cfg.from_start && !cfg.from_end);
    tail->start();
    pill.start();

    last_flush_ms = wall_ms(); last_delta_ms = last_flush_ms; last_ckpt_ms = last_flush_ms;
    char b[2048];
    std::snprintf(b, sizeof(b),
        "{\"k\":\"hdr\",\"src\":\"%s\",\"live\":true,\"dial\":0,\"mode\":\"%s\",\"molt_wm\":%ld,"
        "\"model\":\"%s\",\"seed_toks\":%d,\"t0_wall\":%llu,\"kv\":\"%s\",\"n_ctx\":%u,"
        "\"serve_hash\":\"0x%016llx\","
        "\"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\":\"%s\",\"kernel\":\"v-next-alpha\",\"venue\":\"%s\",\"lane_contract\":%s,"
        "\"tail_start\":\"%s\",\"spool_offset\":%llu,\"mib_free\":%llu,\"mib_total\":%llu,"
        "\"state\":\"%s\",\"resumed\":%s,\"twin\":%s,\"ask_band\":%.2f,\"stale_tok\":%ld,\"t_mono_ns\":%llu",
        jesc(cfg.spool).c_str(), cfg.pure ? "pure" : "room", cfg.molt_wm, jesc(cfg.model).c_str(), seed_toks,
        (unsigned long long)wall_ms(), cfg.kv_q8 ? "q8_0" : "f16", llama_n_ctx(ctx),
        (unsigned long long)serve_hash(), SELF_REF_DESC, jesc(tail->venue).c_str(), tail->v01 ? "true" : "false",
        tail_start_reason.c_str(), (unsigned long long)tail->offset.load(),
        (unsigned long long)vitals.mib_free.load(), (unsigned long long)vitals.mib_total.load(),
        switch_name((Switch)vitals.sw.load()), resumed ? "true" : "false", twin ? "true" : "false",
        cfg.ask_band, cfg.stale_tok, (unsigned long long)mono_ns());
    tape.put(b);
    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
// hybrid: a fork can be truncated in the attention layers, but its recurrent state cannot be rewound
// — `llama_memory_seq_rm(fork, at, -1)` refuses (measured 2026-09-04: the removal was a silent no-op,
// the probe then failed with "inconsistent sequence positions", and a probe that ignored the failure
// returned stale logits as if they were margins). So a DELAYED judgment is a judgment about now, and
// the record says so (`late`, `at`, `covers`). The corollary is a design rule, not a workaround:
// defer as little as possible — the only deferral left is a seat's own sentence.
//
// A probe that cannot decode is FATAL, never a stale number: a resident that quietly stops judging
// is the unsafe direction.
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). `cause` names why it died.
bool Kernel::speak(int m, float margin, std::string& say, std::string& aired, 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);
    dec(ctx, ct, GEN, npast, true);
    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;
        say += piece;
        if (surface_on) { std::fputs(piece.c_str(), stdout); aired = say; }   // the forming plane, visible as it forms
        std::vector<llama_token> one{tok};
        dec(ctx, one, GEN, gpos, true); ++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 char lc = say.empty() ? 0 : say[say.size() - 1];
            if (lc == '.' || lc == '!' || lc == '?') break;
        }
        // THE WINDOW IN THE BLIND WINDOW. Percepts never wait for a sentence to finish.
        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 (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;
                break;
            }
        }
    }
    --gen_depth;
    llama_memory_seq_rm(mem, GEN, -1, -1);
    gen_ms = wall_ms() - g0;
    if (surface_on) {
        if (aborted) std::printf(" ⟵ [un-said: %s]\n  └─\n", cause.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;
    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], 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], causes[m], gen_ms_a[m]);
        says[m] = say;
        if (!whole) {
            // THE UN-SAY. The killed continuation, the aired prefix, and the cause go on the tape.
            // Whatever reached the air IS a percept and commits on the seat's lane; the rest never
            // existed in the world. Only commits kill; the record shows exactly which words did.
            ++n_unsaid; vitals.unsaid.store((uint64_t)n_unsaid); unsaid_a[m] = true;
            char b[512];
            std::snprintf(b, sizeof(b), "{\"k\":\"unsaid\",\"i\":%ld,\"ms\":%.0f,\"mind\":\"%s\",\"m\":%.2f,\"gen_ms\":%llu,\"cause\":\"%s\",\"killed\":\"",
                          boundaries, rel_ms(), MINDS[m].name, margins[m], (unsigned long long)gen_ms_a[m], jesc(causes[m]).c_str());
            tape.put(std::string(b) + jesc(say) + "\",\"aired\":\"" + jesc(aired[m]) + "\",\"clause\":\"" + jesc(judged) + "\"");
            write_verdict(judged_lane, m, "abort", margins[m], say, causes[m].c_str());
            if (!aired[m].empty() && !cfg.pure) pending_commits.push_back(std::string("\n[") + MINDS[m].name + "] " + aired[m]);
            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
        // disposition to say a thing ONCE is a fine-tune target, not something to fake in the harness
        // (S0's own finding); the harness does the honest minimum — one surfaced line per seat per
        // window, the rest LOGGED and FLAGGED, never dropped. Evidence re-arm overrides it.
        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);
        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,\"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]);
    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
// =====================================================================================================

void Kernel::begin_line(const Delta& d) {
    // silence before this delta becomes world (ticks-as-world, not a poll)
    const uint64_t gap = d.arrive_ms > last_delta_ms ? d.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);
        char b[128]; std::snprintf(b, sizeof(b), "{\"k\":\"tick\",\"ms\":%.0f,\"gap_s\":%llu", rel_ms(), (unsigned long long)(gap / 1000));
        tape.put(b);
    }
    last_delta_ms = d.arrive_ms; cur_delta_arrival = d.arrive_ms; cur_delta_t_mono = d.t_mono_ns;
    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);
    // Seat lanes and `self` are ALREADY HEARD: the kernel committed its own words in-process at the
    // moment they reached the air. A spool echo of them is not a second percept. Counted, skipped.
    if (seat_of_lane(d.lane) >= 0) { ++echo_skipped; 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});
    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
// position: separate probes would read the same state and return the same margins, and a seat
// that fired on each of them would fire N times about one instant (measured 2026-09-04: the SENTINEL
// fired four times on clauses that predate the risky line it was firing about). The live accumulator
// is LATER than everything in the queue (a judgment or a deferral always clears it), so it is
// stashed, the window is judged, and it is merged back with anything that gathered meanwhile.
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};
        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.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;
            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;
        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);
    }
    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;
        backlog_now = tail->pending();
        if (tail->poll(d)) {
            ingest_delta(d);
            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);
            if (!cfg.ckpt.empty() && cfg.ckpt_every_s > 0 && now - last_ckpt_ms > (uint64_t)cfg.ckpt_every_s * 1000ull && !line_open)
                checkpoint("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();
    char b[2048];
    std::snprintf(b, sizeof(b),
        "{\"k\":\"end\",\"words\":%ld,\"toks\":%d,\"boundaries\":%ld,\"holds\":%ld,\"emits\":%ld,\"ticks\":%ld,"
        "\"molts\":%ld,\"molt_outage_ms\":%llu,\"deltas\":%ld,\"echo_skipped\":%ld,\"self_ref_boundaries\":%ld,"
        "\"suppressed_repeats\":%ld,\"coarse_boundaries\":%ld,\"deferred_boundaries\":%ld,\"ring_dropped\":0,"
        "\"ring_stalls\":%llu,\"spool_lines\":%llu,\"spool_resets\":%llu,\"unsaid\":%ld,\"briefs\":%ld,"
        "\"counsel_in\":%ld,\"counsel_discarded\":%ld,\"forming_frames\":%ld,"
        "\"conditions_opened\":%ld,\"conditions_resolved\":%ld,\"conditions_expired\":%ld,\"conditions_rearmed\":%ld,"
        "\"emits_per_boundary\":%.4f,\"emits_per_condition\":%.4f,"
        "\"surp_mean_all\":%.3f,\"mean_lat_ms\":%.0f,\"max_lat_ms\":%llu,\"mib_free\":%llu,\"wall_ms\":%.0f,\"stopped\":\"%s\"",
        words, (int)npast, boundaries, holds, n_emits, ticks, n_molts, (unsigned long long)molt_outage_total,
        n_deltas, echo_skipped, n_self_ref, n_supp, coarse_boundaries, n_deferred,
        (unsigned long long)tail->stalls.load(), (unsigned long long)tail->lines.load(), (unsigned long long)tail->reset_events.load(),
        n_unsaid, n_briefs, n_counsel, n_discard, n_forming,
        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,
        all_surp_n ? all_surp_sum / (double)all_surp_n : 0.0,
        boundaries ? (double)lat_sum / (double)boundaries : 0.0, (unsigned long long)lat_max,
        (unsigned long long)vitals.mib_free.load(), total, 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) std::printf("already-heard frames skipped: %ld\n", echo_skipped);
    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"
        "  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;
    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("--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 (c.spool.empty()) { usage(); return 1; }

    // 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 -------------------------------------------------------------------------------
