/*
 * kido-sched.c — Kido cooperative round-robin scheduler.
 *
 * The first module where Kido becomes multi-tasking. Portable policy
 * (queue, states, carving, accounting) lives here; register transfer
 * is kido_ctx_switch — real ARM64 asm in kido-sched-arm64.S, or the
 * hosted test double below (register switching is ARM64-only).
 *
 * Design (deliberations/2026-10-14-kido-sched-design.md,
 *        deliberations/2026-10-14-kido-alloc-sched-integration.md):
 *  P1 cooperative round-robin — no fake preemption (GIC/timer IRQ are
 *     loud stubs in the HAL).
 *  P2 static TCB table — the scheduler never allocates directly.
 *  P3 allocator-backed stacks (integrated 2026-10-14, fence fulfilled):
 *     each task gets a fixed 16 KiB stack from kido-alloc (16-aligned
 *     payload). kido_sched_init initializes the allocator from
 *     kido-mem's region list (hosted: the static arena as a synthetic
 *     region) — one place, documented in kido-sched.h. DONE slots keep
 *     their stacks on recycle (provably idle); exhaustion is loud.
 *  P4 minimal callee-saved context (x19-x28, FP, SP, LR) in .S.
 *  P5 HAL timer ticks are accounting, never preemption.
 *  P6 empty run queue halts LOUD (D1 code mapping, documented).
 *
 * TESTING: KIDO_HOSTED_TEST builds the test double + portable core.
 *  gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST \
 *      -DKIDO_SCHED_SELFTEST modules/kido-sched.c modules/kido-alloc.c \
 *      modules/kido-image.c modules/kido-reloc.c -o /tmp/kido-sched-test
 * (kido-reloc.c: the reservation consumes the ACTUAL image bounds —
 * linked + relocation delta; the self-test injects a delta for the
 * shifted-carve section.)
 * Cross (ARM64, real asm): aarch64-linux-gnu-gcc -ffreestanding -c
 *  modules/kido-sched-arm64.S  (encoding verification)
 */

#include "kido-sched.h"
/* kido-alloc.h comes via kido-sched.h: task stacks are allocator clients. */
#include "kido-image.h"  /* image bounds -> allocator reservation (D2) */
#include "kido-reloc.h"  /* relocation delta -> actual image bounds (phase 2) */

#if !defined(KIDO_HOSTED_TEST)
#include "kido-mem.h"  /* region list feeding kido_alloc_init */
#endif

#if defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
extern void kido_task_trampoline(void);  /* kido-sched-arm64.S */
#endif

/* ------------------------------------------------------------------ */
/* Static state. No allocation, ever (P2).                             */
/* ------------------------------------------------------------------ */
static kido_task_t       sched_tasks[KIDO_SCHED_MAX_TASKS];
static kido_task_t      *sched_current;
static const kido_hal_t *sched_hal;
static uint32_t          sched_rr_cursor;
static uint64_t          sched_last_ticks;   /* accounting anchor (P5) */

#if defined(KIDO_HOSTED_TEST)
/* Hosted backing store: the firmware addresses in the hosted caps are
 * test values, not real memory — kido_alloc_init takes this arena as a
 * synthetic single region, so the portable core is genuinely testable. */
static uint8_t sched_alloc_arena[512u * 1024u] __attribute__((aligned(16)));
#else
/* Bare metal: the allocator takes kido-mem's region list directly.
 * D2 CLOSED 2026-10-16: kido_sched_init reserves the linker-script
 * image bounds (kido-image) before any stack is allocated. */
#endif

/* Idle context: kido_sched_run switches FROM it once; nothing ever
 * switches back (an empty queue halts instead). */
static kido_task_ctx_t sched_idle_ctx;

#ifdef KIDO_HOSTED_TEST
/* Test double: register switching is ARM64-only. Records the attempt
 * so the self-test can observe scheduling decisions; the portable
 * policy around it is fully real. */
static uint64_t sched_testdouble_switches;
void kido_ctx_switch(kido_task_ctx_t *old_ctx, kido_task_ctx_t *new_ctx)
{
    (void)old_ctx;
    (void)new_ctx;
    sched_testdouble_switches++;
}
#endif

/* ------------------------------------------------------------------ */
kido_status_t kido_sched_init(const kido_hal_t *hal)
{
    uint32_t i;
    kido_status_t st;
    if (hal == NULL)
        return KIDO_ERR_EARLY_ENV;
    for (i = 0; i < KIDO_SCHED_MAX_TASKS; i++) {
        sched_tasks[i].state = KIDO_TASK_EMPTY;
        sched_tasks[i].id    = i;
    }
    sched_current   = NULL;
    sched_hal       = hal;
    sched_rr_cursor = 0;
    sched_last_ticks = 0;
    /* Allocator first (P3): the scheduler is kido-alloc's first client.
     * The image reservation closes sched D2 (2026-10-16): the kernel
     * image (boot stack included) is carved out of the allocator's
     * regions, so no task stack can ever overlap it. Bare metal reads
     * the bounds from the linker symbols via kido-image; hosted has
     * no image — an uninjected query refuses (STUB_REACHED) and the
     * reservation is vacuously 0,0, because there is no image to
     * protect (deliberated P4; the self-test injects a fake image to
     * exercise the real carve path). Phase 2 (2026-10-17): the
     * reservation consumes the ACTUAL bounds (linked + relocation
     * delta) — the carve follows the image wherever it really runs;
     * zero allocator changes, the reserve parameter already takes
     * base+size. A failed bounds query on bare metal means a
     * mislinked image: propagate loud and never run the allocator
     * on it. No usable backing -> NO_MEMORY, loud — stacks cannot
     * exist without it. */
    {
        kido_status_t ist;
        uint64_t img_base = 0u, img_size = 0u;
        const kido_mem_region_t *regions;
        size_t n;
#if defined(KIDO_HOSTED_TEST)
        kido_mem_region_t arena_region;
#endif

        ist = kido_image_actual_bounds(&img_base, &img_size);
#if defined(KIDO_HOSTED_TEST)
        if (ist == KIDO_ERR_STUB_REACHED) {
            img_base = 0u;   /* vacuous: hosted has no image */
            img_size = 0u;
            ist = KIDO_OK;
        }
#endif
        if (ist != KIDO_OK)
            return ist;  /* mislinked image: loud, no allocation at all */

#if defined(KIDO_HOSTED_TEST)
        arena_region.base = (uint64_t)(uintptr_t)&sched_alloc_arena[0];
        arena_region.size = (uint64_t)sizeof(sched_alloc_arena);
        regions = &arena_region;
        n = 1;
#else
        n = kido_mem_region_count();
        regions = kido_mem_regions();
        if (n == 0 || regions == NULL)
            return KIDO_ERR_NO_MEMORY;
#endif
        st = kido_alloc_init(regions, n, img_base, img_size);
    }
    if (st != KIDO_OK)
        return st;  /* allocator failure propagates unchanged */
    if (hal->timer_ticks != NULL)
        sched_last_ticks = hal->timer_ticks();
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
kido_status_t kido_sched_create(kido_task_fn entry, void *arg,
                                const char *name, uint32_t *id_out)
{
    uint32_t i, n;
    kido_task_t *t = NULL;
    uint64_t stack_base;
    uint8_t reuse_stack;  /* DONE slots keep their allocated stack (P2) */
    kido_status_t st;

    if (entry == NULL || id_out == NULL)
        return KIDO_ERR_EARLY_ENV;
    if (sched_hal == NULL)
        return KIDO_ERR_EARLY_ENV;  /* init not called */

    for (i = 0; i < KIDO_SCHED_MAX_TASKS; i++) {
        if (sched_tasks[i].state == KIDO_TASK_EMPTY ||
            sched_tasks[i].state == KIDO_TASK_DONE) {
            t = &sched_tasks[i];
            break;
        }
    }
    if (t == NULL)
        return KIDO_ERR_NO_MEMORY;  /* table full: loud, not silent */

    /* A DONE task's stack is provably idle (it is never scheduled
     * again), so recycling reuses it instead of allocating fresh —
     * otherwise churn would grow the allocator without bound. The reuse
     * stays visible in kido_alloc_stats (deliberation C3). */
    reuse_stack = (t->state == KIDO_TASK_DONE);
    if (reuse_stack) {
        stack_base = t->stack_base;
    } else {
        /* Allocate the stack from kido-alloc (P3). 16 KiB payload,
         * 16-byte aligned for AAPCS64. On failure the slot is left
         * EMPTY — the TCB is filled only after the stack exists, so
         * there is never a half-created task. */
        void *stack_ptr = NULL;
        st = kido_alloc((uint64_t)KIDO_SCHED_STACK_SIZE, 16u, &stack_ptr);
        if (st != KIDO_OK)
            return st;  /* NO_MEMORY (or EARLY_ENV): loud, slot untouched */
        stack_base = (uint64_t)(uintptr_t)stack_ptr;
    }

    t->entry      = entry;
    t->arg        = arg;
    t->stack_base = stack_base;
    t->stack_size = KIDO_SCHED_STACK_SIZE;
    t->ticks_run  = 0;
    t->switches   = 0;
    /* Bounded name copy (no libc on bare metal). */
    for (n = 0; n < KIDO_SCHED_NAME_LEN - 1 && name != NULL && name[n] != '\0'; n++)
        t->name[n] = name[n];
    t->name[n] = '\0';

#if defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
    /* Craft the first-run context: restore lands in the trampoline
     * with entry/arg in x19/x20, on the fresh stack (P4). */
    {
        uint64_t stack_top = stack_base + KIDO_SCHED_STACK_SIZE;
        for (i = 0; i < 10; i++)
            t->ctx.x[i] = 0u;
        t->ctx.x[0] = (uint64_t)(uintptr_t)entry;  /* x19 */
        t->ctx.x[1] = (uint64_t)(uintptr_t)arg;    /* x20 */
        t->ctx.fp   = 0u;
        t->ctx.lr   = (uint64_t)(uintptr_t)kido_task_trampoline;
        t->ctx.sp   = stack_top;  /* 16-aligned by construction */
    }
#else
    for (i = 0; i < 13; i++)
        t->ctx.opaque[i] = 0u;
#endif

    t->state = KIDO_TASK_READY;
    *id_out  = t->id;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
kido_task_t *kido_sched_pick_next(void)
{
    uint32_t i, idx;
    for (i = 0; i < KIDO_SCHED_MAX_TASKS; i++) {
        idx = (sched_rr_cursor + i) % KIDO_SCHED_MAX_TASKS;
        if (sched_tasks[idx].state == KIDO_TASK_READY) {
            sched_rr_cursor = (idx + 1) % KIDO_SCHED_MAX_TASKS;
            return &sched_tasks[idx];
        }
    }
    return NULL;
}

/* ------------------------------------------------------------------ */
void kido_sched_yield(void)
{
    kido_task_t *cur = sched_current;
    kido_task_t *nxt;
    uint64_t now;

    if (cur == NULL)
        return;  /* no current task: no-op, documented */

    nxt = kido_sched_pick_next();
    if (nxt == NULL) {
        /* Nothing runnable. A DONE current task means the queue has
         * emptied -> loud halt (D1 mapping). Otherwise the current
         * task simply continues. */
        if (cur->state == KIDO_TASK_DONE)
            kido_halt(KIDO_ERR_STUB_REACHED);
        return;
    }
    if (nxt == cur)
        return;  /* sole runnable task keeps running */

    /* P5: credit the outgoing task for elapsed HAL ticks. */
    if (sched_hal != NULL && sched_hal->timer_ticks != NULL) {
        now = sched_hal->timer_ticks();
        if (now >= sched_last_ticks)
            cur->ticks_run += now - sched_last_ticks;
        sched_last_ticks = now;
    }

    if (cur->state == KIDO_TASK_RUNNING)
        cur->state = KIDO_TASK_READY;
    nxt->state    = KIDO_TASK_RUNNING;
    nxt->switches++;
    sched_current = nxt;
    kido_ctx_switch(&cur->ctx, &nxt->ctx);
    /* Resume here when this task is re-scheduled. kido_ctx_switch is
     * opaque to the compiler, so globals are re-read from memory;
     * callee-saved locals survived via the saved context (P4). */
}

/* ------------------------------------------------------------------ */
void kido_sched_run(void)
{
    kido_task_t *t;
    for (;;) {
        t = kido_sched_pick_next();
        if (t == NULL)
            kido_halt(KIDO_ERR_STUB_REACHED);  /* D1: queue empty */
        t->state    = KIDO_TASK_RUNNING;
        t->switches++;
        sched_current = t;
        kido_ctx_switch(&sched_idle_ctx, &t->ctx);
        /* Unreachable in practice: tasks yield among themselves, and
         * an emptied queue halts in yield(). Defensive loop. */
    }
}

/* ------------------------------------------------------------------ */
kido_status_t kido_sched_destroy(void)
{
    uint32_t i, j;

    if (sched_hal == NULL)
        return KIDO_ERR_EARLY_ENV;  /* init never called, or destroy already ran */

    /* Refusal gate (P2): teardown over live tasks has no safe default.
     * Checked BEFORE any free, so a refusal leaves the table and the
     * allocator byte-identical to how the caller found them. */
    for (i = 0; i < KIDO_SCHED_MAX_TASKS; i++) {
        if (sched_tasks[i].state == KIDO_TASK_READY ||
            sched_tasks[i].state == KIDO_TASK_RUNNING)
            return KIDO_ERR_EARLY_ENV;
    }

    /* Free what the scheduler owns (P1/P3): every non-EMPTY slot holds
     * a scheduler-allocated stack. Free FIRST, then clear the slot —
     * kido_free needs the stack_base the slot holds (C2). DONE slots
     * are teardown-eligible by construction (never scheduled again);
     * EMPTY slots hold no stack. */
    for (i = 0; i < KIDO_SCHED_MAX_TASKS; i++) {
        kido_status_t st;
        if (sched_tasks[i].state == KIDO_TASK_EMPTY)
            continue;
        st = kido_free((void *)(uintptr_t)sched_tasks[i].stack_base);
        if (st != KIDO_OK)
            return st;  /* fail-stop: this slot kept, partial teardown visible */
        sched_tasks[i].state      = KIDO_TASK_EMPTY;
        sched_tasks[i].id         = 0u;   /* re-assigned by the next init */
        sched_tasks[i].entry      = NULL;
        sched_tasks[i].arg        = NULL;
        sched_tasks[i].stack_base = 0u;
        sched_tasks[i].stack_size = 0u;
        sched_tasks[i].ticks_run  = 0u;
        sched_tasks[i].switches   = 0u;
        sched_tasks[i].name[0]    = '\0';
#if defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
        for (j = 0; j < 10; j++)
            sched_tasks[i].ctx.x[j] = 0u;
        sched_tasks[i].ctx.fp = 0u;
        sched_tasks[i].ctx.lr = 0u;
        sched_tasks[i].ctx.sp = 0u;
#else
        for (j = 0; j < 13; j++)
            sched_tasks[i].ctx.opaque[j] = 0u;
#endif
    }

    /* Back to never-initialized (C4): create goes loud until init runs
     * again; the allocator and its image carve-out are NOT sched's
     * property and are left alone (P3). */
    sched_current    = NULL;
    sched_hal        = NULL;
    sched_rr_cursor  = 0;
    sched_last_ticks = 0;
#if defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
    for (j = 0; j < 10; j++)
        sched_idle_ctx.x[j] = 0u;
    sched_idle_ctx.fp = 0u;
    sched_idle_ctx.lr = 0u;
    sched_idle_ctx.sp = 0u;
#else
    for (j = 0; j < 13; j++)
        sched_idle_ctx.opaque[j] = 0u;
#endif
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* First-run entry. On ARM64, entered via kido_task_trampoline (.S);   */
/* on hosted, the self-test calls it directly. NEVER RETURNS.          */
/* ------------------------------------------------------------------ */
void kido_task_start(kido_task_fn entry, void *arg)
{
    kido_task_t *t = sched_current;
    entry(arg);
    /* Entry returned: the task is done. The yield below either moves
     * to the next READY task or halts LOUD when none remain (D1). */
    if (t != NULL)
        t->state = KIDO_TASK_DONE;
    for (;;)
        kido_sched_yield();
}

/* ------------------------------------------------------------------ */
size_t kido_sched_task_count(void)
{
    uint32_t i;
    size_t n = 0;
    for (i = 0; i < KIDO_SCHED_MAX_TASKS; i++) {
        if (sched_tasks[i].state == KIDO_TASK_READY ||
            sched_tasks[i].state == KIDO_TASK_RUNNING)
            n++;
    }
    return n;
}

const kido_task_t *kido_sched_task(uint32_t id)
{
    if (id >= KIDO_SCHED_MAX_TASKS)
        return NULL;
    return &sched_tasks[id];
}

kido_task_t *kido_sched_current_task(void)
{
    return sched_current;
}

/* ================================================================== */
/* Hosted self-test.                                                  */
/* ================================================================== */
#ifdef KIDO_SCHED_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_SCHED_SELFTEST needs KIDO_HOSTED_TEST."
#endif

#include <stdio.h>
#include <setjmp.h>

static int test_failures = 0;
static int test_count = 0;
#define CHECK(cond, label) do { \
    test_count++; \
    if (cond) { printf("[ ok ] %s\n", label); } \
    else { printf("[FAIL] %s\n", label); test_failures++; } \
} while (0)

/* Test-local kido_halt: record the code, escape via longjmp. The real
 * halt spins forever and cannot be unit-tested. */
static jmp_buf halt_jmp;
static kido_status_t halt_code;
static int halt_hit;
void kido_halt(kido_status_t code)
{
    halt_code = code;
    halt_hit = 1;
    longjmp(halt_jmp, 1);
}

/* Fake HAL: timer ticks increment on every read. */
static uint64_t fake_ticks_count;
static uint64_t fake_ticks(void) { return ++fake_ticks_count; }
static uint32_t fake_hz(void)    { return 1000; }
static void fake_putc(char c)    { (void)c; }
static void fake_puts(const char *s) { (void)s; }
static const kido_hal_t fake_hal = { fake_putc, fake_puts, fake_ticks, fake_hz };

static int body_ran;
static void *body_arg_seen;
static void test_body(void *arg)
{
    body_ran = 1;
    body_arg_seen = arg;
}

int main(void)
{
    uint32_t id0, id1, id2, idx, tmp;
    kido_task_t *p;
    const kido_task_t *tp;

    printf("== kido-sched self-test (hosted) ==\n");

    /* 1-2: init guards */
    CHECK(kido_sched_init(NULL) == KIDO_ERR_EARLY_ENV, "init NULL hal -> EARLY_ENV");
    CHECK(kido_sched_init(&fake_hal) == KIDO_OK, "init with fake hal -> OK");

    /* 3-5: create guards */
    CHECK(kido_sched_create(NULL, NULL, "x", &tmp) == KIDO_ERR_EARLY_ENV,
          "create NULL entry -> EARLY_ENV");
    CHECK(kido_sched_create(test_body, NULL, "x", NULL) == KIDO_ERR_EARLY_ENV,
          "create NULL id_out -> EARLY_ENV");

    /* 6-10: create three tasks; check TCBs + carving */
    CHECK(kido_sched_create(test_body, (void *)0xA1, "alpha", &id0) == KIDO_OK, "create alpha");
    CHECK(kido_sched_create(test_body, (void *)0xB2, "beta-with-a-very-long-name", &id1) == KIDO_OK,
          "create beta (long name)");
    CHECK(kido_sched_create(test_body, NULL, "gamma", &id2) == KIDO_OK, "create gamma");
    CHECK(id0 == 0 && id1 == 1 && id2 == 2, "ids assigned 0,1,2");
    tp = kido_sched_task(0);
    CHECK(tp != NULL && tp->state == KIDO_TASK_READY, "alpha READY");
    tp = kido_sched_task(1);
    CHECK(tp != NULL && tp->name[15] == '\0', "beta name truncated + NUL-terminated");
    {
        const kido_task_t *a = kido_sched_task(0);
        const kido_task_t *b = kido_sched_task(1);
        const kido_task_t *c = kido_sched_task(2);
        uint64_t lo = (uint64_t)(uintptr_t)&sched_alloc_arena[0];
        uint64_t hi = lo + sizeof(sched_alloc_arena);
        CHECK(a->stack_base >= lo && a->stack_base + a->stack_size <= hi,
              "alpha stack inside allocator arena");
        CHECK((a->stack_base & 15u) == 0, "alpha stack 16-aligned");
        /* First-fit allocates low-to-high from the address-ordered free
         * list (deliberation C2): the invariant is order + non-overlap,
         * not carve direction. */
        CHECK(a->stack_base < b->stack_base && b->stack_base < c->stack_base,
              "stacks allocated in increasing address order");
        CHECK(a->stack_base + a->stack_size <= b->stack_base &&
              b->stack_base + b->stack_size <= c->stack_base,
              "stacks non-overlapping");
    }
    CHECK(kido_sched_task_count() == 3, "task_count == 3");

    /* 11: round-robin order over 6 picks */
    {
        uint32_t order[6];
        for (idx = 0; idx < 6; idx++) {
            p = kido_sched_pick_next();
            order[idx] = (p == NULL) ? 99u : p->id;
        }
        CHECK(order[0] == 0 && order[1] == 1 && order[2] == 2 &&
              order[3] == 0 && order[4] == 1 && order[5] == 2,
              "round-robin order 0,1,2,0,1,2");
    }

    /* 12: pick skips DONE */
    sched_tasks[1].state = KIDO_TASK_DONE;
    {
        uint32_t order[4];
        for (idx = 0; idx < 4; idx++) {
            p = kido_sched_pick_next();
            order[idx] = (p == NULL) ? 99u : p->id;
        }
        CHECK(order[0] == 0 && order[1] == 2 && order[2] == 0 && order[3] == 2,
              "pick skips DONE task");
    }
    sched_tasks[1].state = KIDO_TASK_READY;  /* restore */

    /* 13-16: yield switches current, updates states, accounts ticks */
    sched_current = &sched_tasks[0];
    sched_tasks[0].state = KIDO_TASK_RUNNING;
    {
        uint64_t before = fake_ticks_count;
        uint64_t switches_before = sched_testdouble_switches;
        kido_sched_yield();
        CHECK(sched_current == &sched_tasks[1], "yield moved current 0 -> 1");
        CHECK(sched_tasks[0].state == KIDO_TASK_READY, "yielder back to READY");
        CHECK(sched_tasks[1].state == KIDO_TASK_RUNNING, "next is RUNNING");
        CHECK(sched_testdouble_switches == switches_before + 1, "switch attempted");
        CHECK(sched_tasks[0].ticks_run == (fake_ticks_count - before),
              "yielder credited elapsed ticks");
        (void)before;
    }

    /* 17: yield with sole READY task is a no-op */
    sched_tasks[1].state = KIDO_TASK_DONE;
    sched_tasks[2].state = KIDO_TASK_DONE;
    sched_current = &sched_tasks[0];
    sched_tasks[0].state = KIDO_TASK_RUNNING;
    {
        uint64_t sw = sched_testdouble_switches;
        kido_sched_yield();
        CHECK(sched_current == &sched_tasks[0] && sched_testdouble_switches == sw,
              "sole runnable task: yield is a no-op");
    }

    /* 18: yield with no current task is a no-op */
    sched_current = NULL;
    kido_sched_yield();
    CHECK(1, "yield with NULL current does not crash");

    /* 19-20: kido_task_start on hosted is testable only in the
     * last-task configuration: with another READY task present, the
     * backstop yield loop cannot transfer control under the no-op
     * switch double (register transfer is ARM64-only; true task
     * interleaving is queued for the QEMU integration test). The
     * last-task path below proves body execution + DONE + loud halt. */

    /* 21: DONE slot recycled (slot 0 is RUNNING, so slot 1 is first).
     * The recycled slot keeps its stack: no fresh allocation, so churn
     * cannot grow the allocator without bound. Verified through the
     * allocator's own accounting (deliberation C3). */
    {
        uint64_t beta_stack = kido_sched_task(1)->stack_base;
        kido_alloc_stats_t s_before, s_after;
        CHECK(kido_alloc_stats(&s_before) == KIDO_OK, "allocator stats readable");
        CHECK(kido_sched_create(test_body, NULL, "delta", &tmp) == KIDO_OK && tmp == 1,
              "DONE slot 1 recycled by create");
        CHECK(kido_sched_task(1)->state == KIDO_TASK_READY, "recycled slot READY");
        CHECK(kido_sched_task(1)->stack_base == beta_stack,
              "recycled slot keeps its stack");
        CHECK(kido_alloc_stats(&s_after) == KIDO_OK, "allocator stats readable (2)");
        CHECK(s_after.allocated_bytes == s_before.allocated_bytes &&
              s_after.allocs == s_before.allocs,
              "recycle adds no allocation (reuse via allocator accounting)");
    }

    /* 22: table-full is loud */
    {
        kido_status_t st = KIDO_OK;
        uint32_t j;
        for (j = 3; j <= KIDO_SCHED_MAX_TASKS; j++)  /* 14 fills: slots 2..15 */
            st = kido_sched_create(test_body, NULL, "fill", &tmp);
        CHECK(st == KIDO_OK, "table filled to 16");
        CHECK(kido_sched_create(test_body, NULL, "over", &tmp) == KIDO_ERR_NO_MEMORY,
              "17th create -> NO_MEMORY (loud)");
    }

    /* 23: run() with zero runnable tasks halts LOUD (D1 mapping) */
    {
        uint32_t j;
        for (j = 0; j < KIDO_SCHED_MAX_TASKS; j++)
            sched_tasks[j].state = KIDO_TASK_DONE;
        halt_hit = 0;
        if (setjmp(halt_jmp) == 0) {
            kido_sched_run();
            CHECK(0, "run() returned (impossible)");
        } else {
            CHECK(halt_hit && halt_code == KIDO_ERR_STUB_REACHED,
                  "empty run queue -> loud halt STUB_REACHED (D1)");
        }
    }

    /* 24: solo task via kido_task_start: body runs, DONE, loud halt */
    kido_sched_init(&fake_hal);
    CHECK(kido_sched_create(test_body, (void *)0xAB, "solo", &tmp) == KIDO_OK, "re-init + create solo");
    sched_current = &sched_tasks[0];
    sched_tasks[0].state = KIDO_TASK_RUNNING;
    body_ran = 0;
    body_arg_seen = NULL;
    halt_hit = 0;
    if (setjmp(halt_jmp) == 0) {
        kido_task_start(test_body, (void *)0xAB);  /* returns -> DONE -> yield -> halt */
        CHECK(0, "task_start returned (impossible)");
    } else {
        CHECK(body_ran == 1 && body_arg_seen == (void *)0xAB, "task body ran with arg");
        CHECK(sched_tasks[0].state == KIDO_TASK_DONE, "returned task marked DONE");
        CHECK(halt_hit && halt_code == KIDO_ERR_STUB_REACHED,
              "last task done -> loud halt STUB_REACHED (D1)");
    }

    /* 25-29: allocator integration. Clean slate: re-init resets both
     * the table and the allocator (deliberation C1 — coherent because
     * every TCB returns to EMPTY). */
    kido_sched_init(&fake_hal);
    {
        kido_alloc_stats_t s;
        void *scratch = NULL;
        uint64_t base_before;
        uint32_t j;
        CHECK(kido_alloc_stats(&s) == KIDO_OK && s.allocs == 0 && s.allocated_bytes == 0,
              "fresh init: allocator accounting at zero");
        CHECK(kido_sched_create(test_body, NULL, "i0", &tmp) == KIDO_OK, "integ create 0");
        CHECK(kido_sched_create(test_body, NULL, "i1", &tmp) == KIDO_OK, "integ create 1");
        CHECK(kido_sched_create(test_body, NULL, "i2", &tmp) == KIDO_OK, "integ create 2");
        CHECK(kido_alloc_stats(&s) == KIDO_OK && s.allocs == 3 &&
              s.allocated_bytes == 3u * KIDO_SCHED_STACK_SIZE,
              "3 stacks allocated via kido-alloc (accounting exact)");
        /* Churn: DONE all three, recycle all three — reuse must keep
         * the allocator flat (the anti-leak property, now accounted). */
        for (j = 0; j < 3; j++)
            sched_tasks[j].state = KIDO_TASK_DONE;
        base_before = s.allocated_bytes;
        CHECK(kido_sched_create(test_body, NULL, "r0", &tmp) == KIDO_OK, "integ recycle 0");
        CHECK(kido_sched_create(test_body, NULL, "r1", &tmp) == KIDO_OK, "integ recycle 1");
        CHECK(kido_sched_create(test_body, NULL, "r2", &tmp) == KIDO_OK, "integ recycle 2");
        CHECK(kido_alloc_stats(&s) == KIDO_OK && s.allocs == 3 &&
              s.allocated_bytes == base_before,
              "churn recycle: no new allocations, no leak");
        /* Exhaustion is loud and leaves the system consistent: a huge
         * direct alloc fails, and task creation still works after. */
        CHECK(kido_alloc(1ULL << 40, 16u, &scratch) == KIDO_ERR_NO_MEMORY && scratch == NULL,
              "oversize alloc -> NO_MEMORY, out stays NULL");
        for (j = 0; j < 3; j++)
            sched_tasks[j].state = KIDO_TASK_DONE;
        CHECK(kido_sched_create(test_body, NULL, "after-exhaust", &tmp) == KIDO_OK,
              "create works after exhaustion (system consistent)");
        /* The free path is live in the integrated tree (deliberation
         * C4): scratch alloc/free returns accounting to baseline, and
         * misuse is loud. */
        CHECK(kido_alloc_stats(&s) == KIDO_OK, "stats before scratch");
        base_before = s.allocated_bytes;
        CHECK(kido_alloc(1024u, 64u, &scratch) == KIDO_OK && scratch != NULL &&
              ((uint64_t)(uintptr_t)scratch & 63u) == 0,
              "scratch alloc 1024/64 -> OK, 64-aligned");
        CHECK(kido_free(scratch) == KIDO_OK, "scratch free -> OK");
        CHECK(kido_alloc_stats(&s) == KIDO_OK && s.allocated_bytes == base_before,
              "free returns accounting to baseline");
        CHECK(kido_free(NULL) == KIDO_ERR_EARLY_ENV, "free(NULL) -> EARLY_ENV (loud)");
        CHECK(kido_free(scratch) == KIDO_ERR_EARLY_ENV, "double free -> EARLY_ENV (loud)");
    }

    /* 30-39: image-bounds reservation (D2 closed 2026-10-16). Inject
     * a fake image at the arena's base; the reservation must carve it
     * out of the allocator exactly, and no task stack may overlap it.
     * This is the last section: the injection is test-harness state
     * and persists (like the arena itself). */
    {
        kido_alloc_stats_t s;
        uint64_t arena_lo = (uint64_t)(uintptr_t)&sched_alloc_arena[0];
        uint64_t arena_hi = arena_lo + (uint64_t)sizeof(sched_alloc_arena);
        uint64_t img_size = 4096u;
        uint32_t j;
        CHECK(kido_image_test_set_bounds(arena_lo, img_size) == KIDO_OK,
              "inject fake image (arena base, 4KiB) -> OK");
        CHECK(kido_sched_init(&fake_hal) == KIDO_OK,
              "re-init with injected image bounds -> OK");
        CHECK(kido_alloc_stats(&s) == KIDO_OK &&
              s.total_bytes == (uint64_t)sizeof(sched_alloc_arena) - img_size,
              "allocator total_bytes reduced by exactly the image size");
        CHECK(kido_alloc_stats(&s) == KIDO_OK && s.allocs == 0 &&
              s.allocated_bytes == 0,
              "fresh init: accounting at zero (image carved, nothing live)");
        for (j = 0; j < 3; j++)
            CHECK(kido_sched_create(test_body, NULL, "img", &tmp) == KIDO_OK,
                  "create with image reserved -> OK");
        for (j = 0; j < 3; j++) {
            const kido_task_t *t = kido_sched_task(j);
            CHECK(t != NULL && t->stack_base >= arena_lo + img_size &&
                  t->stack_base + t->stack_size <= arena_hi,
                  "task stack avoids the reserved image range");
        }
    }

    /* 40-49: relocated image reservation (phase 2, 2026-10-17). The
     * carve follows the ACTUAL image location: inject the fake image
     * at the arena base AND a relocation delta of +0x1000 — the
     * reservation must carve [arena_lo+0x1000, +0x2000), and no task
     * stack may overlap the shifted range. The carve SIZE is
     * unchanged (translation-invariant); only its position moves.
     * Zero allocator changes: the shift flows through
     * kido_image_actual_bounds. This is the last section: both
     * injections are test-harness state and persist. */
    {
        kido_alloc_stats_t s;
        uint64_t arena_lo = (uint64_t)(uintptr_t)&sched_alloc_arena[0];
        uint64_t arena_hi = arena_lo + (uint64_t)sizeof(sched_alloc_arena);
        uint64_t img_size = 4096u;
        uint64_t shift = 0x1000u;
        uint32_t j;
        kido_reloc_info_t rinfo;  /* detect() populates kido_reloc_last(),
                                     mirroring the entry's real order */
        CHECK(kido_image_test_set_bounds(arena_lo, img_size) == KIDO_OK,
              "re-inject fake image (arena base, 4KiB) -> OK");
        CHECK(kido_reloc_test_set_delta((int64_t)shift) == KIDO_OK &&
              kido_reloc_detect(&rinfo) == KIDO_OK,
              "inject relocation delta +0x1000 -> OK");
        CHECK(kido_sched_init(&fake_hal) == KIDO_OK,
              "re-init with relocated image bounds -> OK");
        CHECK(kido_alloc_stats(&s) == KIDO_OK &&
              s.total_bytes == (uint64_t)sizeof(sched_alloc_arena) - img_size,
              "carve size unchanged by relocation (translation-invariant)");
        for (j = 0; j < 3; j++)
            CHECK(kido_sched_create(test_body, NULL, "reloc", &tmp) == KIDO_OK,
                  "create with relocated image reserved -> OK");
        for (j = 0; j < 3; j++) {
            const kido_task_t *t = kido_sched_task(j);
            uint64_t carve_lo = arena_lo + shift;
            uint64_t carve_hi = carve_lo + img_size;
            uint64_t no_overlap =
                (t->stack_base + t->stack_size <= carve_lo) ||
                (t->stack_base >= carve_hi);
            CHECK(t != NULL && no_overlap &&
                  t->stack_base >= arena_lo &&
                  t->stack_base + t->stack_size <= arena_hi,
                  "task stack avoids the SHIFTED image range");
        }
        /* Positive evidence the carve MOVED (not just grew): with
         * the unshifted carve, first-fit would place stack 0 at
         * arena_lo+0x1000 — inside the shifted range, failing the
         * loop above. A stack base at/after the shifted carve end
         * proves the reservation follows the image. (The 4 KiB hole
         * before the shifted carve cannot fit a 16 KiB stack, so
         * first-fit skips it regardless of header layout.) */
        {
            const kido_task_t *t0 = kido_sched_task(0);
            CHECK(t0 != NULL &&
                  t0->stack_base >= arena_lo + shift + img_size,
                  "first stack starts at/after the shifted carve end");
        }
    }

    /* 50-59: teardown at rest (2026-10-21, session 20: session-6 D1
     * specified). The tree enters this section with 3 READY "reloc"
     * tasks; the image + relocation injections persist (test-harness
     * state, like the arena). */
    {
        kido_alloc_stats_t s;
        uint64_t total_before, allocs_before, frees_before;
        uint32_t j;

        /* 50: destroy over READY tasks refuses LOUD and touches nothing. */
        CHECK(kido_alloc_stats(&s) == KIDO_OK, "stats before refusal tests");
        total_before = s.total_bytes; allocs_before = s.allocs;
        frees_before = s.frees;
        CHECK(kido_sched_destroy() == KIDO_ERR_EARLY_ENV,
              "destroy with READY tasks -> EARLY_ENV (refusal law)");
        CHECK(kido_alloc_stats(&s) == KIDO_OK &&
              s.total_bytes == total_before && s.allocs == allocs_before &&
              s.frees == frees_before,
              "refused destroy: allocator byte-identical");
        CHECK(kido_sched_task_count() == 3, "refused destroy: tasks untouched");

        /* 51: the self-destruction shape — a RUNNING task with the
         * current-task pointer set. Refuses the same way. */
        sched_tasks[0].state = KIDO_TASK_RUNNING;
        sched_current = &sched_tasks[0];
        CHECK(kido_sched_destroy() == KIDO_ERR_EARLY_ENV,
              "destroy with a RUNNING task (self-shape) -> EARLY_ENV");
        CHECK(sched_tasks[0].state == KIDO_TASK_RUNNING &&
              sched_current == &sched_tasks[0],
              "refused destroy: running task and cursor untouched");
        CHECK(kido_alloc_stats(&s) == KIDO_OK && s.allocs == allocs_before,
              "refused destroy: no stack freed");

        /* 52: happy path — all DONE, teardown at rest. */
        for (j = 0; j < 3; j++)
            sched_tasks[j].state = KIDO_TASK_DONE;
        sched_current = NULL;
        CHECK(kido_sched_destroy() == KIDO_OK, "destroy at rest -> OK");
        for (j = 0; j < KIDO_SCHED_MAX_TASKS; j++)
            CHECK(sched_tasks[j].state == KIDO_TASK_EMPTY, "post-destroy: slot EMPTY");
        CHECK(kido_sched_task_count() == 0, "post-destroy: task count 0");
        CHECK(kido_alloc_stats(&s) == KIDO_OK &&
              s.allocs == s.frees && s.allocated_bytes == 0,
              "destroy: every stack freed (allocs == frees, bytes 0)");
        CHECK(s.total_bytes == total_before,
              "destroy: image carve-out untouched (not sched's property)");

        /* 53-54: post-destroy the scheduler is never-initialized. */
        CHECK(kido_sched_create(test_body, NULL, "post", &tmp) == KIDO_ERR_EARLY_ENV,
              "create after destroy (no re-init) -> EARLY_ENV");
        CHECK(kido_sched_destroy() == KIDO_ERR_EARLY_ENV,
              "destroy twice -> EARLY_ENV");

        /* 55: re-init is the only way back; then teardown again to
         * leave the tree at rest. */
        CHECK(kido_sched_init(&fake_hal) == KIDO_OK,
              "re-init after destroy -> OK");
        CHECK(kido_alloc_stats(&s) == KIDO_OK && s.allocs == 0 && s.frees == 0 &&
              s.allocated_bytes == 0,
              "re-init: allocator reset (existing law), carve still carved");
        CHECK(s.total_bytes == total_before,
              "re-init: image carve-out survives re-init");
        CHECK(kido_sched_create(test_body, NULL, "back", &tmp) == KIDO_OK,
              "create after re-init -> OK");
        sched_tasks[0].state = KIDO_TASK_DONE;
        CHECK(kido_sched_destroy() == KIDO_OK,
              "final teardown at rest -> OK");
        CHECK(kido_sched_task_count() == 0 &&
              kido_alloc_stats(&s) == KIDO_OK && s.allocs == s.frees,
              "tree ends at rest: table EMPTY, allocator flat");
    }

    printf("== %d checks, %d failures ==\n", test_count, test_failures);
    return test_failures == 0 ? 0 : 1;
}
#endif /* KIDO_SCHED_SELFTEST */
