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63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/*
 * lit_main.c — the product's world main: the foolproof world interface.
 *
 * The world is the only thing customized here.  LIT is fixed: the host
 * supplies the world's root, actions, and oracle; the operator owns the
 * global tree, the frontier, the comparison, and the seen set.  There is
 * no score, no attention, no pruning, and no branch stack here.
 *
 * Usage:
 *   lit [go [rows [cols]]]       default: go 19 (19 x 19 board)
 *   lit dense [x y z]            default: dense 4 4 64
 *
 * The go world is the gel {black,white} x {black,white} x board_cells:
 * the causal pair (a,b) is the smallest predecessor/successor state, and
 * the board cells are the orthogonal time axis.
 *
 * The search is global.  The operator picks the next node from the whole
 * tree; the host does not walk branches.  As soon as a node reaches the
 * last time slice it has stopped; the player's IF is the halt judge.
 * A win is the goal and stops the search; a non-win is an ordinary leaf
 * and the global search continues.  The whole tree is saved as JSON and
 * safetensors.
 */
#include "dense.h"
#include "lit_operator.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct {
    dense world;
    lit_action *acts;        /* one time slice of actions */
    size_t nacts;
    int (*win)(void *ctx, const lit_action *path, size_t path_len);
    void *win_ctx;
    uint64_t wins;
} world_host;

static int parse_u64(const char *s, uint64_t *out)
{
    char *end;
    unsigned long long v;

    if (!s || !*s || *s == '-') {
        return -1;
    }
    v = strtoull(s, &end, 10);
    if (end == s || *end != '\0') {
        return -1;
    }
    *out = (uint64_t)v;
    return 0;
}

static int host_init(world_host *h, uint32_t symbols, uint64_t steps)
{
    memset(h, 0, sizeof(*h));
    if (dense_init(&h->world, symbols, steps, NULL, NULL) != 0) {
        return -1;
    }
    if (symbols == 0 || (size_t)symbols > SIZE_MAX / symbols) {
        dense_free(&h->world);
        return -1;
    }
    h->nacts = (size_t)symbols * symbols;
    if (h->nacts == 0 || h->nacts > SIZE_MAX / sizeof(*h->acts)) {
        dense_free(&h->world);
        return -1;
    }
    h->acts = malloc(h->nacts * sizeof(*h->acts));
    if (!h->acts) {
        dense_free(&h->world);
        return -1;
    }
    return 0;
}

static void host_free(world_host *h)
{
    free(h->acts);
    h->acts = NULL;
    dense_free(&h->world);
}

/* The world root is virtual: it is not a cell.  Its actions are all
 * cells of time 0, so every cell of the world is reachable. */
static int host_root(void *ctx, lit_key *key, int *goal, int *dead)
{
    (void)ctx;
    key->hi = UINT64_MAX;
    key->lo = 0;
    *goal = 0;
    *dead = 0;
    return 0;
}

/* Every action is one cell of the next time slice.  The operator never
 * interprets the cell; the world names it and the oracle decides. */
static int host_actions(void *ctx, const lit_action *path, size_t path_len,
                        const lit_action **acts, size_t *n)
{
    world_host *h = ctx;
    uint64_t nt = path_len
        ? (uint64_t)path[path_len - 1].kind + 1 : 0;
    size_t i = 0;

    if (nt >= h->world.steps) {
        *acts = NULL;
        *n = 0;
        return 0;
    }
    for (uint32_t a = 0; a < h->world.symbols; a++) {
        for (uint32_t b = 0; b < h->world.symbols; b++) {
            h->acts[i].kind = (uint32_t)nt;
            h->acts[i].id = 0;
            h->acts[i].x = a;
            h->acts[i].y = b;
            h->acts[i].cost = 1;
            i++;
        }
    }
    *acts = h->acts;
    *n = i;
    return 0;
}

/* The judge is one line of IF: when a node reaches the last time slice
 * it has stopped, and the player's IF decides whether the stop is a
 * win.  A win is the goal (the search returns the path); a non-win is an
 * ordinary leaf and the global search simply continues. */
static int halt_goal(const world_host *h, const lit_action *act)
{
    if ((uint64_t)act->kind + 1 < h->world.steps) {
        return 0;
    }
    return act->y == 0;
}

/* The world oracle has no goal; the gel cut is the only structural
 * mask.  Key is the cell, so the operator's seen set dedupes the world.
 * This is called per action, before the seen check; it has no side
 * effects and never judges a win. */
static int host_eval(void *ctx, const lit_action *path, size_t path_len,
                     const lit_action *act, uint64_t child_g,
                     lit_key *child, int *goal, int *dead)
{
    world_host *h = ctx;
    uint64_t cell = dense_index(&h->world, act->x, act->y, act->kind);

    (void)path;
    (void)path_len;
    (void)child_g;
    if (cell == UINT64_MAX) {
        child->hi = 0;
        child->lo = 0;
        *goal = 0;
        *dead = 1;
        return 0;
    }
    child->hi = cell;
    child->lo = 0;
    *goal = halt_goal(h, act);
    *dead = dense_cut(&h->world, cell);
    return 0;
}

/* Batch expansion: one host round trip per parent instead of one per
 * action.  The same world oracle as host_eval, filled for every action
 * at once; this is the shape a GPU/NPU/robot host wants. */
static int host_expand(void *ctx, const lit_action *path, size_t path_len,
                       const lit_action *acts, const uint64_t *child_g,
                       size_t nacts, lit_key *keys, int *goals, int *deads)
{
    world_host *h = ctx;

    (void)path;
    (void)path_len;
    (void)child_g;
    for (size_t i = 0; i < nacts; i++) {
        uint64_t cell = dense_index(&h->world, acts[i].x, acts[i].y,
                                    acts[i].kind);

        if (cell == UINT64_MAX) {
            keys[i].hi = 0;
            keys[i].lo = 0;
            goals[i] = 0;
            deads[i] = 1;
            continue;
        }
        keys[i].hi = cell;
        keys[i].lo = 0;
        goals[i] = halt_goal(h, &acts[i]);
        deads[i] = dense_cut(&h->world, cell);
    }
    return 0;
}

/* The player's win IF, run at the halt.  A win is the halt judge and
 * stops the search; a non-win is an ordinary leaf and the search
 * continues.  Replace this one line to change the win judgment. */
static int player_win(void *ctx, const lit_action *path, size_t path_len)
{
    (void)ctx;
    if (path_len == 0) {
        return 0;
    }
    return path[path_len - 1].y == 0;   /* example: last stone black */
}

/* Observation only.  The operator calls it after expanding a node.  The
 * halt judge is set in eval/expand (the goal); this callback only
 * reports the stopped nodes that were not goals. */
static void host_event(void *ctx, const lit_action *path, size_t path_len,
                       uint64_t pops, uint64_t nodes, size_t open,
                       double g, double score, int goal)
{
    world_host *h = ctx;

    (void)pops;
    (void)nodes;
    (void)open;
    (void)g;
    (void)score;
    (void)goal;
    if ((uint64_t)path_len == h->world.steps && h->win &&
        h->win(h->win_ctx, path, path_len)) {
        h->wins++;
        printf("win-stop: depth %zu\n", path_len);
    }
}

int main(int argc, char **argv)
{
    int go = 1;
    int base = 1;
    uint64_t rows = 19;
    uint64_t cols = 19;
    uint64_t x = 4;
    uint64_t y = 4;
    uint64_t z = 64;
    uint64_t symbols;
    uint64_t steps;
    const char *stem;
    char json_path[64];
    char st_path[64];
    world_host h;
    lit_host lh;
    lit_search_opts opts;
    lit_path path;
    lit_search *s;
    int rc;
    int eval_mode = 0;
    struct timespec t0, t1;

    /* --eval keeps the per-action host path; the default is the batch
       expand path.  Remove the flags so the positional world arguments
       keep their positions. */
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "--eval") == 0) {
            eval_mode = 1;
        } else if (strcmp(argv[i], "--expand") == 0) {
            eval_mode = 0;
        } else {
            continue;
        }
        for (int j = i; j < argc - 1; j++) {
            argv[j] = argv[j + 1];
        }
        argc--;
        i--;
    }

    if (argc > 1) {
        if (strcmp(argv[1], "dense") == 0) {
            go = 0;
            base = 2;
        } else if (strcmp(argv[1], "go") == 0) {
            go = 1;
            base = 2;
        } else {
            fprintf(stderr, "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n",
                    argv[0]);
            return 2;
        }
    }

    if (go) {
        if (argc > base && parse_u64(argv[base], &rows) != 0) {
            fprintf(stderr,
                    "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n",
                    argv[0]);
            return 2;
        }
        cols = rows;
        if (argc > base + 1 && parse_u64(argv[base + 1], &cols) != 0) {
            fprintf(stderr,
                    "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n",
                    argv[0]);
            return 2;
        }
        if (rows == 0 || cols == 0 ||
            rows > UINT32_MAX || cols > UINT32_MAX ||
            rows > UINT32_MAX / cols) {
            fprintf(stderr, "go world needs 0 < rows*cols <= %u\n",
                    UINT32_MAX);
            return 2;
        }
        symbols = 2;
        steps = rows * cols;
        stem = "lit_go";
    } else {
        if (argc > base && parse_u64(argv[base], &x) != 0) {
            fprintf(stderr,
                    "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n",
                    argv[0]);
            return 2;
        }
        y = x;
        if (argc > base + 1) {
            if (parse_u64(argv[base + 1], &y) != 0) {
                fprintf(stderr,
                        "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n",
                        argv[0]);
                return 2;
            }
        }
        if (argc > base + 2 && parse_u64(argv[base + 2], &z) != 0) {
            fprintf(stderr,
                    "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n",
                    argv[0]);
            return 2;
        }
        if (x == 0 || y == 0 || z == 0 || x != y ||
            x > UINT32_MAX || y > UINT32_MAX || z > UINT32_MAX) {
            fprintf(stderr,
                    "dense world needs 0 < x == y <= %u and 0 < z <= %u\n",
                    UINT32_MAX, UINT32_MAX);
            return 2;
        }
        symbols = x;
        steps = z;
        stem = "lit_dense";
    }

    if (host_init(&h, (uint32_t)symbols, steps) != 0) {
        fprintf(stderr, "world init failed\n");
        return 1;
    }
    h.win = player_win;
    h.win_ctx = &h;

    if (go) {
        printf("world: go\n");
        printf("board: %llu x %llu = %llu cells\n",
               (unsigned long long)rows, (unsigned long long)cols,
               (unsigned long long)steps);
        printf("causal: 2 x 2 (black/white)\n");
        printf("shape: 2 x 2 x %llu\n", (unsigned long long)steps);
    } else {
        printf("world: dense\n");
        printf("shape: %llu x %llu x %llu\n",
               (unsigned long long)x, (unsigned long long)y,
               (unsigned long long)z);
    }
    printf("gel: dense\n");
    printf("cells: %llu\n", (unsigned long long)dense_cells(&h.world));
    printf("stop: judged as soon as a node reaches the last time slice\n");
    printf("judge: player IF at the halt (win stops, non-win continues)\n");

    memset(&lh, 0, sizeof(lh));
    lh.ctx = &h;
    lh.root = host_root;
    lh.actions = host_actions;
    lh.eval = host_eval;
    if (!eval_mode) {
        lh.expand = host_expand;
    }
    lh.event = host_event;

    memset(&opts, 0, sizeof(opts));
    memset(&path, 0, sizeof(path));

    s = lit_search_new(&lh);
    if (!s) {
        fprintf(stderr, "lit_search_new failed\n");
        host_free(&h);
        return 1;
    }
    timespec_get(&t0, TIME_UTC);
    rc = lit_search_continue(s, &opts, &path);
    timespec_get(&t1, TIME_UTC);

    printf("search: %s  pops: %llu  nodes: %llu\n",
           rc == LIT_SEARCH_EMPTY ? "exhausted (all worlds explored)" :
           rc == LIT_SEARCH_BUDGET ? "budget" :
           rc == LIT_SEARCH_FOUND ? "found" : "error",
           (unsigned long long)path.pops,
           (unsigned long long)path.nodes);
    {
        long long ns = (long long)(t1.tv_sec - t0.tv_sec) * 1000000000LL +
                       (t1.tv_nsec - t0.tv_nsec);
        double nodes = (double)path.nodes;

        if (ns < 0) {
            ns = 0;
        }
        printf("time: %.3f ms  %.1f ns/node  %.0f nodes/s  [%s]\n",
               (double)ns / 1e6,
               path.nodes ? (double)ns / nodes : 0.0,
               ns ? nodes * 1e9 / (double)ns : 0.0,
               eval_mode ? "eval" : "expand");
    }
    if (rc == LIT_SEARCH_FOUND && path.n > 0) {
        const lit_action *last = &path.acts[path.n - 1];

        printf("halt: depth %zu  last cell (%u,%u,%u)  judge: win\n",
               path.n, last->kind, last->x, last->y);
    } else {
        printf("judge: no win at the halt; the search would continue\n");
    }

    snprintf(json_path, sizeof(json_path), "%s.json", stem);
    snprintf(st_path, sizeof(st_path), "%s.safetensors", stem);
    if (lit_search_save_json(s, json_path) != 0) {
        fprintf(stderr, "save json failed\n");
    } else {
        printf("tree: %s\n", json_path);
    }
    if (lit_search_save_safetensors(s, st_path) != 0) {
        fprintf(stderr, "save safetensors failed\n");
    } else {
        printf("tree: %s\n", st_path);
    }

    lit_path_free(&path);
    lit_search_free(s);
    host_free(&h);
    return (rc == LIT_SEARCH_EMPTY || rc == LIT_SEARCH_FOUND) ? 0 : 1;
}