interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

GitHub aien-dev/omega-mv#140 (code only)

closed derived 40214e638a5d051a #140

Imported from GitHub aien-dev/omega-mv#140 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base d6837d49187818eeabaa3446cd9957099e147db6 · Head 27314dfaab1a6ef2c6e1ba9ac2480ed9deeb3864

Apply it

git checkout -b patch-40214e638a5d051a d6837d49187818eeabaa3446cd9957099e147db6
curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/40214e638a5d051a.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/omega-mv
140
27314dfaab1a6ef2c6e1ba9ac2480ed9deeb3864
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":140,"url":"https://github.com/aien-dev/omega-mv/pull/140","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:30Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.github/workflows/host-suites.yml b/.github/workflows/host-suites.yml
index 38b8e98b5..0c87c5036 100644
--- a/.github/workflows/host-suites.yml
+++ b/.github/workflows/host-suites.yml
@@ -16,7 +16,7 @@ name: Host suites
 #       (+ builds only of the R13/R14 living hosts)
 #   turing-yield.yml : turing-yield turing-energy
 #   this file : searchtrace, estimation est-tools estimation-v3 est3c-tools,
-#       numeric-cpu numeric-qualify
+#       numeric-cpu numeric-qualify, train (M22 substrate, Lane 21)
 #
 # Deliberately NOT on GitHub (no GB10, no resident seat, no quiet flag here):
 #   test-composition-gate-gpu, test-r12-silicon, test-r13-silicon,
@@ -59,6 +59,10 @@ on:
       - 'tools/numeric_*'
       - 'tools/m19r_qualify.sh'
       - 'tools/json_canon.c'
+      # train (M22 optimizer substrate + E5 provenance)
+      - 'src/train/**'
+      - 'tests/train/**'
+      - 'mk/train.mk'
 
 jobs:
   searchtrace:
@@ -101,3 +105,14 @@ jobs:
         run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-numeric-cpu
       - name: Gate 5 qualifier and receipt writer (host-only, fake descriptors)
         run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-numeric-qualify
+
+  train:
+    runs-on: ubuntu-24.04-arm
+    timeout-minutes: 15
+    steps:
+      - uses: actions/checkout@v4
+        with:
+          ref: ${{ github.event.pull_request.head.sha || github.sha }}
+          fetch-depth: 0
+      - name: M22 substrate (generation store, crash matrix, provenance, SGD), plain + ASan/UBSan
+        run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-train
diff --git a/docs/train/M22_SUBSTRATE.md b/docs/train/M22_SUBSTRATE.md
new file mode 100644
index 000000000..a4716dcd1
--- /dev/null
+++ b/docs/train/M22_SUBSTRATE.md
@@ -0,0 +1,98 @@
+# M22 optimizer substrate and E5 training provenance (Lane 21)
+
+Status: **M22 NOT QUALIFIED.** This is the transactional parameter-state
+substrate and an SGD path over plain byte buffers. There is no tensor or
+autodiff integration yet; that waits for M20 OMEGA_TENSOR and M21
+OMEGA_AUTODIFF. Plan reference: aien-architecture `CURRENT_EXECUTION_PLAN.md`
+sections E4 (M22) and E5 (training provenance).
+
+## What exists
+
+| Piece | File | Plan item |
+|---|---|---|
+| Generation store (shadow, validate, one atomic switch, recovery) | `src/train/tg_store.[ch]` | E4: shadow state, validation before one atomic switch, OLD or NEW |
+| SGD updater (float32, optional heavy-ball momentum) | `src/train/tg_sgd.[ch]` | E4: SGD first |
+| Two-tier provenance | `src/train/tg_store.[ch]` | E5 |
+| Exit tests, plain + ASan/UBSan | `tests/train/test_train.c`, `make test-train` | E4/E5 exit gate (substrate level) |
+| Receipt | `tests/train/train_receipt.sh`, `make train-receipt` -> `evidence/M22/receipts/` | |
+
+## On-disk layout (one directory per store)
+
+- `gen-<20 digits>.bin`: one immutable generation. 152-byte little-endian
+  header (magic `OMTRGEN1`, version, generation, step, parameter bytes,
+  optimizer bytes, dispatch-log length and chain head at commit, previous
+  generation digest, digest) followed by parameter bytes and optimizer bytes.
+  Digest = SHA-256 over the first 120 header bytes + parameters + optimizer.
+- `CURRENT`: the pointer, exactly 95 bytes: `OMTRCUR1 <generation> <digest hex>\n`.
+  A reader checks the generation file's digest against the pointer.
+- `dispatch.log`: tier (a) records, 192 bytes each, hash-chained.
+- `refusals.log`: one line per refused operation (`REFUSE <code> gen=<g> <why>`).
+- `LOCK`: `flock` for the single writer.
+
+## Commit protocol
+
+1. Refuse if the shadow is not open (double switch), its base is not the
+   current generation (stale), or sizes differ. Run the validation callback;
+   refuse on reject. Every refusal is appended to `refusals.log`.
+2. Append the shadow's dispatch records to `dispatch.log`, chained, `fsync`.
+3. Compute the full state digest (tier b; the only place the model is hashed).
+4. Write `shadow-N.tmp`, `fsync`, read it back and verify the digest.
+5. `rename` to `gen-N.bin`, `fsync` the directory.
+6. Write `CURRENT.tmp`, `fsync`, `rename` to `CURRENT` (the one atomic
+   switch), `fsync` the directory.
+
+Recovery (`tg_open`): verify the generation `CURRENT` names (size, digest,
+pointer digest), delete `*.tmp` and generation files newer than `CURRENT`,
+truncate `dispatch.log` to the committed length and verify its chain against
+the committed head. A generation that does not verify is refused, never
+silently rolled back.
+
+## Provenance tiers (E5)
+
+- (a) Per dispatch: step, op id, two scalar arguments (SGD: learning rate and
+  momentum bit patterns; gradient reference id), up to three input references
+  (buffer id, offset, length) and the base generation's digest, by reference.
+  Cost is one SHA-256 over 192 bytes per record, independent of model size
+  (tested at 1 Ki and 256 Ki parameters).
+- (b) Full parameter + optimizer digest, only at committed generations,
+  linked by previous-digest into a verifiable history (`tg_verify_history`).
+
+## What the tests prove (host, single core)
+
+- Crash at each of 8 injected points inside commit (child process `_exit`):
+  points before the pointer rename recover to exactly OLD; points after it
+  recover to exactly NEW; digests verified; redoing the step from OLD gives
+  the same NEW digest. Torn-file variants (not-yet-current files truncated
+  after the crash) also recover to OLD.
+- A lock-free reader racing 150 commits never sees a torn or unverified state
+  and never sees the generation go backwards.
+- Refusals: corrupted shadow, truncated generation (payload and header),
+  payload digest mismatch, pointer digest mismatch, validation reject, double
+  switch, stale shadow, tampered and truncated dispatch log, second writer,
+  re-create, bad SGD arguments.
+- Replay: the same 25-step SGD sequence from G0 gives a byte-identical G25
+  digest and dispatch chain head, in two stores and across the -O2 and
+  ASan/UBSan -O1 builds; each committed step re-derived from its base
+  generation plus its dispatch record matches the committed payload byte for
+  byte.
+- SGD (plain and momentum) cuts a fixed quadratic loss by more than 10x in
+  40 committed steps.
+
+## Not done / limits
+
+- **Not a power-loss test.** Faults are process crashes; `fsync` ordering is
+  by construction and code review, not by cutting power.
+- **Gradients are hand-written** (quadratic loss). No autodiff (M21), no
+  tensor API (M20); no GPU path.
+- **Adam/AdamW deferred** (plan E4: "SGD first; Adam/AdamW after"). The
+  optimizer state is opaque bytes, so they fit the same substrate later.
+- Reproducibility is claimed for the same binary and for the two test builds
+  on this host (AArch64, `-ffp-contract=off`), not across ISAs or compilers.
+- No garbage collection of old generations (all are kept; history is
+  verifiable end to end).
+- Dispatch records are held with the shadow and written at commit, so work
+  that is never committed leaves no tier (a) record.
+- If the pointer rename succeeds but the directory `fsync` after it fails,
+  the commit returns `E_IO`, readers already see NEW, and the writer refuses
+  every further commit until the store is reopened (recovery decides).
+  This path is not exercised by a test (it needs a failing `fsync`).
diff --git a/evidence/M22/receipts/eaa0cdeae9f348b19b80377baaeb5e5dea6a6577e9385e7a2a3c15caab24c5c8.json b/evidence/M22/receipts/eaa0cdeae9f348b19b80377baaeb5e5dea6a6577e9385e7a2a3c15caab24c5c8.json
new file mode 100644
index 000000000..ced8b6803
--- /dev/null
+++ b/evidence/M22/receipts/eaa0cdeae9f348b19b80377baaeb5e5dea6a6577e9385e7a2a3c15caab24c5c8.json
@@ -0,0 +1,24 @@
+{
+  "schema": "omega.m22.train-substrate.receipt.v1",
+  "gate": "M22_SUBSTRATE",
+  "m22_status": "M22 NOT QUALIFIED: optimizer substrate + SGD path only; no tensor/autodiff integration (waits M20/M21)",
+  "substrate_tests_verdict": "PASS",
+  "reasons": "",
+  "scope": "host-only, single core; process-crash fault injection (fork + _exit at 8 points, plus torn-file simulation of not-yet-current files); NOT a power-loss test, NOT a GPU or hardware qualification; SGD with caller-supplied gradients (hand-written quadratic), Adam/AdamW deferred",
+  "commit": "b381370bb35debfe57429f6933ebe775037fccd7",
+  "tree": "26f5535b4d34126db3df9c1f36c35df5f7fc4141",
+  "tree_clean": true,
+  "run_id": "20261001T072142Z",
+  "command": "make test-train (twice, clean build/train each time; each run = plain -O2 build + ASan/UBSan -O1 build)",
+  "checks_per_binary_run": "266",
+  "replay_digest_run1": "f161fad7bfe124ca0d03688d8b7226ee5ac4e1f0813ea889127bd2508f3b6e3d",
+  "replay_digest_run2": "f161fad7bfe124ca0d03688d8b7226ee5ac4e1f0813ea889127bd2508f3b6e3d",
+  "replay_dispatch_head": "ccd77c5c35a8a2fdc6778424c77b24c7b32f94aca11525fcbf47f79f9328bb1f",
+  "replay_steps_reverified": "25/25",
+  "crash_matrix": {"recovered_old": 9, "recovered_new": 2},
+  "reader_race": "reader_race reads 57409 bad 0 backwards 0 last_gen 150",
+  "provenance_cost": "cost n=1024 dispatch_records 3 dispatch_hashed_per_record 192 commit_hashed_bytes 24936;cost n=262144 dispatch_records 3 dispatch_hashed_per_record 192 commit_hashed_bytes 6291816;",
+  "train_sources_sha256": "236566ecb649c868fe5a7746c69fc9c2490984389e44f2666d0aa5db6a75c539",
+  "logs_sha256": "42981327677d377c8f76cadec5d7193abecb29add8b11fcfcb606be5a9d98fad",
+  "host": "Linux 7.0.0-1019-nvidia aarch64"
+}
diff --git a/mk/train.mk b/mk/train.mk
new file mode 100644
index 000000000..3042bb354
--- /dev/null
+++ b/mk/train.mk
@@ -0,0 +1,49 @@
+# M22 OMEGA_OPTIMIZER substrate + E5 training provenance (Lane 21, 2026-10-01).
+# Transactional generation store over plain byte buffers (src/train/tg_store.*),
+# SGD as the first updater (src/train/tg_sgd.*). No tensor/autodiff dependency
+# (M20/M21 integration waits). New files only: src/train/, tests/train/,
+# docs/train/, evidence/M22/. Picked up by `-include mk/*.mk`; not part of
+# `all` or `test`. Host only, single core, no GPU, no quiet flag.
+#
+# test-train      purity check, then the exit tests plain and with ASan/UBSan;
+#                 both builds must print the same replay digest
+# train-purity    src/train includes only libc, sha256.h and src/train headers
+# train-receipt   digest-named receipt under evidence/M22/receipts (clean tree only)
+#
+# The receipt says M22 NOT QUALIFIED: this is the substrate + SGD path only.
+ifndef TRAIN_MK
+TRAIN_MK := 1
+.PHONY: test-train train-purity train-receipt
+TRAIN_DIR = $(OUT_DIR)/train
+TRAIN_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -ffp-contract=off -Isrc
+TRAIN_ASAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all
+TRAIN_SRCS = src/train/tg_store.c src/train/tg_sgd.c src/sha256.c
+TRAIN_HDRS = src/train/tg_store.h src/train/tg_sgd.h src/sha256.h
+
+$(TRAIN_DIR)/test_train: tests/train/test_train.c $(TRAIN_SRCS) $(TRAIN_HDRS)
+	@mkdir -p $(TRAIN_DIR)
+	$(CC) $(TRAIN_CFLAGS) -o $@ tests/train/test_train.c $(TRAIN_SRCS) -lm
+
+$(TRAIN_DIR)/test_train_asan: tests/train/test_train.c $(TRAIN_SRCS) $(TRAIN_HDRS)
+	@mkdir -p $(TRAIN_DIR)
+	$(CC) $(TRAIN_CFLAGS) $(TRAIN_ASAN) -o $@ tests/train/test_train.c $(TRAIN_SRCS) -lm
+
+train-purity:
+	@bad=$$(grep -hE '^[[:space:]]*#[[:space:]]*include' src/train/*.c src/train/*.h | \
+		grep -vE '#[[:space:]]*include[[:space:]]+(<[a-z/]+\.h>|"sha256\.h"|"train/tg_[a-z]+\.h")' || true); \
+	if [ -n "$$bad" ]; then echo "train-purity: FAIL, unexpected includes:"; echo "$$bad"; exit 1; fi; \
+	echo "train-purity: src/train depends only on libc, sha256 and itself"
+
+test-train: train-purity $(TRAIN_DIR)/test_train $(TRAIN_DIR)/test_train_asan
+	./$(TRAIN_DIR)/test_train $(TRAIN_DIR)/scratch > $(TRAIN_DIR)/plain.log 2>&1; rc=$$?; \
+		grep -vE '^crash |^cost |^sgd_' $(TRAIN_DIR)/plain.log; [ $$rc -eq 0 ]
+	./$(TRAIN_DIR)/test_train_asan $(TRAIN_DIR)/scratch-asan > $(TRAIN_DIR)/asan.log 2>&1; rc=$$?; \
+		grep -vE '^crash |^cost |^sgd_' $(TRAIN_DIR)/asan.log; [ $$rc -eq 0 ]
+	@a=$$(awk '$$1=="replay_digest"{print $$2}' $(TRAIN_DIR)/plain.log); \
+	 b=$$(awk '$$1=="replay_digest"{print $$2}' $(TRAIN_DIR)/asan.log); \
+	 if [ -z "$$a" ] || [ "$$a" != "$$b" ]; then echo "test-train: replay digest differs between builds"; exit 1; fi; \
+	 echo "test-train: plain and ASan/UBSan PASS, replay digest equal across builds"
+
+train-receipt:
+	bash tests/train/train_receipt.sh
+endif
diff --git a/src/train/tg_sgd.c b/src/train/tg_sgd.c
new file mode 100644
index 000000000..f4696b3a4
--- /dev/null
+++ b/src/train/tg_sgd.c
@@ -0,0 +1,44 @@
+/* tg_sgd.c -- plain C float32 SGD over a tg_store shadow. See tg_sgd.h. */
+#include "train/tg_sgd.h"
+
+#include <math.h>
+#include <string.h>
+
+static uint32_t fbits(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
+
+int tg_sgd_step(tg_store *st, tg_shadow *sh, const float *grad, size_t n,
+                float lr, float momentum, uint64_t grad_ref)
+{
+    if (!st || !sh || !grad || n == 0 || n > (SIZE_MAX / 4)) return TG_E_ARG;
+    if (!isfinite(lr) || !isfinite(momentum) || lr <= 0.0f || momentum < 0.0f || momentum >= 1.0f)
+        return TG_E_ARG;
+    if (sh->param_bytes != n * 4) return TG_E_ARG;
+    int use_v = momentum != 0.0f;
+    if (use_v && sh->opt_bytes != n * 4) return TG_E_ARG;
+
+    tg_ref refs[TG_MAX_REFS];
+    uint32_t nr = 0;
+    refs[nr++] = (tg_ref){TG_BUF_PARAMS, 0, (uint64_t)n * 4};
+    if (use_v) refs[nr++] = (tg_ref){TG_BUF_OPT, 0, (uint64_t)n * 4};
+    refs[nr++] = (tg_ref){TG_BUF_EXTERNAL, grad_ref, (uint64_t)n * 4};
+    uint64_t arg0 = (uint64_t)fbits(lr) | ((uint64_t)fbits(momentum) << 32);
+    int r = tg_dispatch(st, sh, TG_OP_SGD, arg0, grad_ref, refs, nr);
+    if (r) return r;
+
+    float *p = (float *)(void *)sh->params;
+    if (!use_v) {
+        for (size_t i = 0; i < n; i++) {
+            float step = lr * grad[i];
+            p[i] = p[i] - step;
+        }
+    } else {
+        float *v = (float *)(void *)sh->opt;
+        for (size_t i = 0; i < n; i++) {
+            float mv = momentum * v[i];
+            v[i] = mv + grad[i];
+            float step = lr * v[i];
+            p[i] = p[i] - step;
+        }
+    }
+    return TG_OK;
+}
diff --git a/src/train/tg_sgd.h b/src/train/tg_sgd.h
new file mode 100644
index 000000000..446d153d4
--- /dev/null
+++ b/src/train/tg_sgd.h
@@ -0,0 +1,23 @@
+/* tg_sgd.h -- M22 "SGD first": plain float32 SGD (optional heavy-ball
+ * momentum) applied to a tg_store SHADOW. The gradient comes from the caller
+ * (no autodiff exists yet; M21). Adam/AdamW are deliberately deferred.
+ *
+ * Update, per element i, in this exact order (no FMA contraction; the
+ * translation unit is built with -ffp-contract=off):
+ *   momentum == 0:  p[i] = p[i] - lr * g[i]                (opt state untouched)
+ *   momentum != 0:  v[i] = momentum * v[i] + g[i];  p[i] = p[i] - lr * v[i]
+ *                   (v = optimizer state, n float32)
+ * Each call appends one tier (a) dispatch record: op TG_OP_SGD, arg0 = lr and
+ * momentum bit patterns, arg1 = caller's gradient reference id, input refs =
+ * params, velocity (if used), external gradient. Nothing is hashed here. */
+#ifndef OMEGA_TG_SGD_H
+#define OMEGA_TG_SGD_H
+
+#include "train/tg_store.h"
+
+#define TG_OP_SGD 0x00444753u /* bytes "SGD\0" little-endian */
+
+int tg_sgd_step(tg_store *st, tg_shadow *sh, const float *grad, size_t n,
+                float lr, float momentum, uint64_t grad_ref);
+
+#endif
diff --git a/src/train/tg_store.c b/src/train/tg_store.c
new file mode 100644
index 000000000..69274766a
--- /dev/null
+++ b/src/train/tg_store.c
@@ -0,0 +1,730 @@
+/* tg_store.c -- M22 transactional parameter-state substrate. See tg_store.h. */
+#include "train/tg_store.h"
+#include "sha256.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define GEN_MAGIC "OMTRGEN1"
+#define GEN_VERSION 1u
+#define GEN_HDR 152u          /* bytes; digest is the last 32 */
+#define GEN_HASHED_HDR 120u   /* header bytes covered by the digest */
+#define CUR_MAGIC "OMTRCUR1"
+#define CUR_LEN 95u           /* "OMTRCUR1 <20 digits> <64 hex>\n" */
+#define REC_MAGIC 0x31444754u /* "TGD1" */
+#define REC_SIZE 192u
+#define REC_HASHED 160u       /* record bytes before the chain field */
+#define PATHMAX 4096
+
+enum { SH_OPEN = 1, SH_COMMITTED = 2, SH_DISCARDED = 3 };
+
+struct tg_store {
+    char dir[PATHMAX];
+    int lock_fd;
+    int log_fd;
+    tg_snapshot cur;
+    tg_stats stats;
+    int poisoned;   /* a switch is visible but not known durable: no commits until reopen */
+};
+
+/* ---- fail points ------------------------------------------------------ */
+static tg_failpoint g_fp = TG_FP_NONE;
+static tg_fpmode g_fpmode = TG_FPMODE_EXIT;
+
+void tg_failpoint_arm(tg_failpoint fp, tg_fpmode mode) { g_fp = fp; g_fpmode = mode; }
+void tg_failpoint_disarm(void) { g_fp = TG_FP_NONE; }
+
+static void fp_hit(tg_failpoint fp)
+{
+    if (g_fp == fp && g_fpmode == TG_FPMODE_EXIT)
+        _exit(TG_FP_EXIT_CODE);
+}
+
+const char *tg_failpoint_name(tg_failpoint fp)
+{
+    static const char *n[TG_FP_COUNT] = {
+        "none", "before_shadow_write", "mid_shadow_write", "after_shadow_write",
+        "after_gen_rename", "mid_switch", "before_switch_rename",
+        "after_switch_before_fsync", "after_switch"};
+    return (fp >= 0 && fp < TG_FP_COUNT) ? n[fp] : "?";
+}
+
+const char *tg_err_name(int e)
+{
+    switch (e) {
+    case TG_OK: return "OK";
+    case TG_E_ARG: return "E_ARG";
+    case TG_E_IO: return "E_IO";
+    case TG_E_NOSTORE: return "E_NOSTORE";
+    case TG_E_FORMAT: return "E_FORMAT";
+    case TG_E_TRUNC: return "E_TRUNC";
+    case TG_E_DIGEST: return "E_DIGEST";
+    case TG_E_CHAIN: return "E_CHAIN";
+    case TG_E_REJECT: return "E_REJECT";
+    case TG_E_STATE: return "E_STATE";
+    case TG_E_STALE: return "E_STALE";
+    case TG_E_SHADOW: return "E_SHADOW";
+    case TG_E_LOCKED: return "E_LOCKED";
+    case TG_E_EXISTS: return "E_EXISTS";
+    case TG_E_NOMEM: return "E_NOMEM";
+    }
+    return "E_UNKNOWN";
+}
+
+/* ---- small helpers ---------------------------------------------------- */
+static void put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }
+static void put64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); }
+static uint32_t get32(const uint8_t *p) { uint32_t v = 0; for (int i = 3; i >= 0; i--) v = (v << 8) | p[i]; return v; }
+static uint64_t get64(const uint8_t *p) { uint64_t v = 0; for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; return v; }
+
+void tg_hex(const uint8_t d[TG_DIGEST], char out[2 * TG_DIGEST + 1])
+{
+    static const char hx[] = "0123456789abcdef";
+    for (int i = 0; i < TG_DIGEST; i++) { out[2 * i] = hx[d[i] >> 4]; out[2 * i + 1] = hx[d[i] & 15]; }
+    out[2 * TG_DIGEST] = 0;
+}
+
+static int unhex(const char *s, uint8_t d[TG_DIGEST])
+{
+    for (int i = 0; i < 2 * TG_DIGEST; i++) {
+        char c = s[i]; int v;
+        if (c >= '0' && c <= '9') v = c - '0';
+        else if (c >= 'a' && c <= 'f') v = c - 'a' + 10;
+        else return -1;
+        if (i & 1) d[i / 2] = (uint8_t)(d[i / 2] | v); else d[i / 2] = (uint8_t)(v << 4);
+    }
+    return 0;
+}
+
+static int path_of(char *out, const char *dir, const char *name)
+{
+    int n = snprintf(out, PATHMAX, "%s/%s", dir, name);
+    return (n > 0 && n < PATHMAX) ? 0 : -1;
+}
+
+static int gen_name(char *out, const char *dir, const char *pfx, uint64_t g, const char *sfx)
+{
+    int n = snprintf(out, PATHMAX, "%s/%s%020llu%s", dir, pfx, (unsigned long long)g, sfx);
+    return (n > 0 && n < PATHMAX) ? 0 : -1;
+}
+
+static int write_all(int fd, const uint8_t *p, size_t n)
+{
+    while (n) {
+        ssize_t w = write(fd, p, n);
+        if (w < 0) { if (errno == EINTR) continue; return -1; }
+        p += w; n -= (size_t)w;
+    }
+    return 0;
+}
+
+static int read_full(int fd, uint8_t *p, size_t n, size_t *got)
+{
+    size_t t = 0;
+    while (t < n) {
+        ssize_t r = read(fd, p + t, n - t);
+        if (r < 0) { if (errno == EINTR) continue; return -1; }
+        if (r == 0) break;
+        t += (size_t)r;
+    }
+    *got = t;
+    return 0;
+}
+
+static int fsync_dir(const char *dir)
+{
+    int fd = open(dir, O_RDONLY | O_DIRECTORY);
+    if (fd < 0) return -1;
+    int r = fsync(fd);
+    close(fd);
+    return r;
+}
+
+static void record_refusal(const char *dir, int err, uint64_t gen, const char *detail)
+{
+    char p[PATHMAX], line[512];
+    if (!dir || path_of(p, dir, "refusals.log")) return;
+    int fd = open(p, O_WRONLY | O_CREAT | O_APPEND, 0644);
+    if (fd < 0) return;
+    int n = snprintf(line, sizeof line, "REFUSE %s gen=%llu %s\n", tg_err_name(err),
+                     (unsigned long long)gen, detail ? detail : "");
+    if (n > 0) (void)!write(fd, line, (size_t)n < sizeof line ? (size_t)n : sizeof line - 1);
+    close(fd);
+}
+
+/* ---- generation file -------------------------------------------------- */
+static void gen_header(uint8_t h[GEN_HDR], uint64_t gen, uint64_t step, size_t pb, size_t ob,
+                       uint64_t dlen, const uint8_t dhead[TG_DIGEST], const uint8_t prev[TG_DIGEST])
+{
+    memset(h, 0, GEN_HDR);
+    memcpy(h, GEN_MAGIC, 8);
+    put32(h + 8, GEN_VERSION);
+    put32(h + 12, 0);
+    put64(h + 16, gen);
+    put64(h + 24, step);
+    put64(h + 32, (uint64_t)pb);
+    put64(h + 40, (uint64_t)ob);
+    put64(h + 48, dlen);
+    memcpy(h + 56, dhead, TG_DIGEST);
+    memcpy(h + 88, prev, TG_DIGEST);
+}
+
+static void gen_digest(const uint8_t h[GEN_HDR], const uint8_t *p, size_t pb, const uint8_t *o, size_t ob,
+                       uint8_t d[TG_DIGEST])
+{
+    sha256_ctx c;
+    sha256_init(&c);
+    sha256_update(&c, h, GEN_HASHED_HDR);
+    if (pb) sha256_update(&c, p, pb);
+    if (ob) sha256_update(&c, o, ob);
+    sha256_final(&c, d);
+}
+
+void tg_snapshot_free(tg_snapshot *s)
+{
+    if (!s) return;
+    free(s->params); free(s->opt);
+    s->params = s->opt = NULL;
+    s->param_bytes = s->opt_bytes = 0;
+}
+
+/* Load and fully verify one generation file. expect_digest may be NULL. */
+static int load_gen(const char *path, uint64_t expect_gen, const uint8_t *expect_digest, tg_snapshot *out)
+{
+    memset(out, 0, sizeof *out);
+    int fd = open(path, O_RDONLY);
+    if (fd < 0) return errno == ENOENT ? TG_E_NOSTORE : TG_E_IO;
+    struct stat sb;
+    if (fstat(fd, &sb) < 0) { close(fd); return TG_E_IO; }
+    uint8_t h[GEN_HDR];
+    size_t got;
+    if (read_full(fd, h, GEN_HDR, &got) < 0) { close(fd); return TG_E_IO; }
+    if (got < GEN_HDR) { close(fd); return TG_E_TRUNC; }
+    if (memcmp(h, GEN_MAGIC, 8) || get32(h + 8) != GEN_VERSION || get32(h + 12) != 0) { close(fd); return TG_E_FORMAT; }
+    uint64_t pb = get64(h + 32), ob = get64(h + 40);
+    /* Each length is capped at 2^40 before the sum, so `want` cannot overflow
+     * and the file-size check below bounds every allocation. */
+    if (pb > (1ull << 40) || ob > (1ull << 40)) { close(fd); return TG_E_FORMAT; }
+    uint64_t want = GEN_HDR + pb + ob;
+    if ((uint64_t)sb.st_size < want) { close(fd); return TG_E_TRUNC; }
+    if ((uint64_t)sb.st_size > want) { close(fd); return TG_E_FORMAT; }
+    if (get64(h + 16) != expect_gen) { close(fd); return TG_E_FORMAT; }
+    out->params = malloc(pb ? pb : 1);
+    out->opt = malloc(ob ? ob : 1);
+    if (!out->params || !out->opt) { close(fd); tg_snapshot_free(out); return TG_E_NOMEM; }
+    size_t g1 = 0, g2 = 0;
+    if (read_full(fd, out->params, pb, &g1) < 0 || read_full(fd, out->opt, ob, &g2) < 0) {
+        close(fd); tg_snapshot_free(out); return TG_E_IO;
+    }
+    close(fd);
+    if (g1 != pb || g2 != ob) { tg_snapshot_free(out); return TG_E_TRUNC; }
+    uint8_t d[TG_DIGEST];
+    gen_digest(h, out->params, pb, out->opt, ob, d);
+    if (memcmp(d, h + 120, TG_DIGEST) || (expect_digest && memcmp(d, expect_digest, TG_DIGEST))) {
+        tg_snapshot_free(out); return TG_E_DIGEST;
+    }
+    out->gen = expect_gen;
+    out->step = get64(h + 24);
+    out->param_bytes = pb;
+    out->opt_bytes = ob;
+    out->dispatch_len = get64(h + 48);
+    memcpy(out->dispatch_head, h + 56, TG_DIGEST);
+    memcpy(out->prev_digest, h + 88, TG_DIGEST);
+    memcpy(out->digest, d, TG_DIGEST);
+    return TG_OK;
+}
+
+/* Write a complete generation file at `path` (fails at the injected points). */
+static int write_gen_file(const char *path, const uint8_t h[GEN_HDR], const uint8_t *p, size_t pb,
+                          const uint8_t *o, size_t ob, int with_fp)
+{
+    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+    if (fd < 0) return TG_E_IO;
+    if (write_all(fd, h, GEN_HDR)) goto io;
+    if (with_fp && g_fp == TG_FP_MID_SHADOW_WRITE) {
+        size_t half = pb / 2;
+        if (write_all(fd, p, half)) goto io;
+        fp_hit(TG_FP_MID_SHADOW_WRITE);
+        if (write_all(fd, p + half, pb - half)) goto io;
+    } else if (pb && write_all(fd, p, pb)) goto io;
+    if (ob && write_all(fd, o, ob)) goto io;
+    if (fsync(fd)) goto io;
+    return close(fd) ? TG_E_IO : TG_OK;
+io:
+    close(fd);
+    return TG_E_IO;
+}
+
+static int write_pointer(const char *dir, uint64_t gen, const uint8_t d[TG_DIGEST], int with_fp)
+{
+    char tmp[PATHMAX], cur[PATHMAX], hx[2 * TG_DIGEST + 1], buf[CUR_LEN + 1];
+    if (path_of(tmp, dir, "CURRENT.tmp") || path_of(cur, dir, "CURRENT")) return TG_E_ARG;
+    tg_hex(d, hx);
+    int n = snprintf(buf, sizeof buf, CUR_MAGIC " %020llu %s\n", (unsigned long long)gen, hx);
+    if (n != (int)CUR_LEN) return TG_E_ARG;
+    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+    if (fd < 0) return TG_E_IO;
+    if (with_fp && g_fp == TG_FP_MID_SWITCH) {
+        if (write_all(fd, (const uint8_t *)buf, CUR_LEN / 2)) { close(fd); return TG_E_IO; }
+        fp_hit(TG_FP_MID_SWITCH);
+        if (write_all(fd, (const uint8_t *)buf + CUR_LEN / 2, CUR_LEN - CUR_LEN / 2)) { close(fd); return TG_E_IO; }
+    } else if (write_all(fd, (const uint8_t *)buf, CUR_LEN)) { close(fd); return TG_E_IO; }
+    if (fsync(fd) || close(fd)) return TG_E_IO;
+    if (with_fp) fp_hit(TG_FP_BEFORE_SWITCH_RENAME);
+    if (rename(tmp, cur)) return TG_E_IO;           /* THE atomic switch */
+    if (with_fp) fp_hit(TG_FP_AFTER_SWITCH_BEFORE_FSYNC);
+    if (fsync_dir(dir)) return 1;               /* switched; directory fsync failed */
+    return TG_OK;
+}
+
+static int read_pointer(const char *dir, uint64_t *gen, uint8_t d[TG_DIGEST])
+{
+    char p[PATHMAX];
+    char buf[CUR_LEN + 8];
+    if (path_of(p, dir, "CURRENT")) return TG_E_ARG;
+    int fd = open(p, O_RDONLY);
+    if (fd < 0) return errno == ENOENT ? TG_E_NOSTORE : TG_E_IO;
+    size_t got;
+    int r = read_full(fd, (uint8_t *)buf, sizeof buf, &got);
+    close(fd);
+    if (r < 0) return TG_E_IO;
+    if (got != CUR_LEN || memcmp(buf, CUR_MAGIC " ", 9) || buf[29] != ' ' || buf[CUR_LEN - 1] != '\n')
+        return TG_E_FORMAT;
+    uint64_t g = 0;
+    for (int i = 9; i < 29; i++) {
+        if (buf[i] < '0' || buf[i] > '9') return TG_E_FORMAT;
+        g = g * 10 + (uint64_t)(buf[i] - '0');
+    }
+    if (unhex(buf + 30, d)) return TG_E_FORMAT;
+    *gen = g;
+    return TG_OK;
+}
+
+/* ---- dispatch chain --------------------------------------------------- */
+static void chain_step(const uint8_t prev[TG_DIGEST], const uint8_t *rec, uint8_t out[TG_DIGEST])
+{
+    sha256_ctx c;
+    sha256_init(&c);
+    sha256_update(&c, prev, TG_DIGEST);
+    sha256_update(&c, rec, REC_HASHED);
+    sha256_final(&c, out);
+}
+
+int tg_dispatch_chain(const char *dir, uint64_t len, uint8_t head[TG_DIGEST], uint64_t *n_records)
+{
+    char p[PATHMAX];
+    if (len % REC_SIZE) return TG_E_CHAIN;
+    if (path_of(p, dir, "dispatch.log")) return TG_E_ARG;
+    memset(head, 0, TG_DIGEST);
+    if (n_records) *n_records = 0;
+    int fd = open(p, O_RDONLY);
+    if (fd < 0) return len == 0 ? TG_OK : TG_E_CHAIN;
+    uint8_t rec[REC_SIZE];
+    for (uint64_t i = 0; i < len / REC_SIZE; i++) {
+        size_t got;
+        if (read_full(fd, rec, REC_SIZE, &got) < 0 || got != REC_SIZE) { close(fd); return TG_E_CHAIN; }
+        if (get32(rec) != REC_MAGIC || get64(rec + 8) != i) { close(fd); return TG_E_CHAIN; }
+        uint8_t nh[TG_DIGEST];
+        chain_step(head, rec, nh);
+        if (memcmp(nh, rec + REC_HASHED, TG_DIGEST)) { close(fd); return TG_E_CHAIN; }
+        memcpy(head, nh, TG_DIGEST);
+    }
+    close(fd);
+    if (n_records) *n_records = len / REC_SIZE;
+    return TG_OK;
+}
+
+/* ---- create / open / close -------------------------------------------- */
+static int take_lock(const char *dir, int *fd_out)
+{
+    char p[PATHMAX];
+    if (path_of(p, dir, "LOCK")) return TG_E_ARG;
+    int fd = open(p, O_RDWR | O_CREAT, 0644);
+    if (fd < 0) return TG_E_IO;
+    if (flock(fd, LOCK_EX | LOCK_NB)) { close(fd); return TG_E_LOCKED; }
+    *fd_out = fd;
+    return TG_OK;
+}
+
+int tg_create(const char *dir, const void *params, size_t pb, const void *opt, size_t ob)
+{
+    char p[PATHMAX], g[PATHMAX];
+    uint64_t gen;
+    uint8_t d[TG_DIGEST], zero[TG_DIGEST] = {0};
+    if (!dir || (pb && !params) || (ob && !opt)) return TG_E_ARG;
+    if (mkdir(dir, 0755) && errno != EEXIST) return TG_E_IO;
+    if (read_pointer(dir, &gen, d) != TG_E_NOSTORE) return TG_E_EXISTS;
+    int lk;
+    int r = take_lock(dir, &lk);
+    if (r) return r;
+    if (path_of(p, dir, "dispatch.log")) { close(lk); return TG_E_ARG; }
+    int lf = open(p, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+    if (lf < 0 || fsync(lf)) { if (lf >= 0) close(lf); close(lk); return TG_E_IO; }
+    close(lf);
+    uint8_t h[GEN_HDR];
+    gen_header(h, 0, 0, pb, ob, 0, zero, zero);
+    gen_digest(h, params, pb, opt, ob, d);
+    memcpy(h + 120, d, TG_DIGEST);
+    if (gen_name(p, dir, "shadow-", 0, ".tmp") || gen_name(g, dir, "gen-", 0, ".bin")) { close(lk); return TG_E_ARG; }
+    r = write_gen_file(p, h, params, pb, opt, ob, 0);
+    if (!r && rename(p, g)) r = TG_E_IO;
+    if (!r && fsync_dir(dir)) r = TG_E_IO;
+    if (!r) r = write_pointer(dir, 0, d, 0);
+    close(lk);
+    return r;
+}
+
+/* Remove leftovers of an interrupted commit: *.tmp and generations newer than CURRENT. */
+static int sweep(const char *dir, uint64_t cur_gen, tg_recovery *rec)
+{
+    DIR *dp = opendir(dir);
+    if (!dp) return TG_E_IO;
+    struct dirent *e;
+    char p[PATHMAX];
+    int changed = 0;
+    while ((e = readdir(dp))) {
+        const char *n = e->d_name;
+        size_t l = strlen(n);
+        if (l > 4 && !strcmp(n + l - 4, ".tmp")) {
+            if (!path_of(p, dir, n) && !unlink(p)) { rec->removed_tmp++; changed = 1; }
+        } else if (l == 28 && !strncmp(n, "gen-", 4) && !strcmp(n + 24, ".bin")) {
+            uint64_t g = strtoull(n + 4, NULL, 10);
+            if (g > cur_gen && !path_of(p, dir, n) && !unlink(p)) { rec->removed_orphan_gen++; changed = 1; }
+        }
+    }
+    closedir(dp);
+    if (changed && fsync_dir(dir)) return TG_E_IO;
+    return TG_OK;
+}
+
+int tg_open(const char *dir, tg_store **out, tg_recovery *rec_out)
+{
+    tg_recovery rec = {0, 0, 0};
+    char p[PATHMAX];
+    uint64_t gen;
+    uint8_t pd[TG_DIGEST];
+    if (!dir || !out) return TG_E_ARG;
+    *out = NULL;
+    tg_store *st = calloc(1, sizeof *st);
+    if (!st) return TG_E_NOMEM;
+    st->lock_fd = st->log_fd = -1;
+    if (snprintf(st->dir, sizeof st->dir, "%s", dir) >= (int)sizeof st->dir) { free(st); return TG_E_ARG; }
+    int r = take_lock(dir, &st->lock_fd);
+    if (r) { free(st); return r; }
+    r = read_pointer(dir, &gen, pd);
+    if (!r && gen_name(p, dir, "gen-", gen, ".bin")) r = TG_E_ARG;
+    if (!r) r = load_gen(p, gen, pd, &st->cur);
+    if (r) {
+        char det[64];
+        snprintf(det, sizeof det, "open: committed generation does not verify");
+        record_refusal(dir, r, gen, det);
+        tg_close(st);
+        return r;
+    }
+    /* Dispatch log: verify the committed prefix first. Nothing in the store is
+     * modified until the committed generation AND its chain both verify. */
+    if (path_of(p, dir, "dispatch.log")) { tg_close(st); return TG_E_ARG; }
+    st->log_fd = open(p, O_RDWR);
+    struct stat sb;
+    if (st->log_fd < 0 || fstat(st->log_fd, &sb)) { tg_close(st); return TG_E_IO; }
+    if ((uint64_t)sb.st_size < st->cur.dispatch_len) {
+        record_refusal(dir, TG_E_CHAIN, gen, "open: dispatch log shorter than committed length");
+        tg_close(st);
+        return TG_E_CHAIN;
+    }
+    uint8_t head[TG_DIGEST];
+    r = tg_dispatch_chain(dir, st->cur.dispatch_len, head, NULL);
+    if (!r && memcmp(head, st->cur.dispatch_head, TG_DIGEST)) r = TG_E_CHAIN;
+    if (r) {
+        record_refusal(dir, r, gen, "open: dispatch chain does not match committed head");
+        tg_close(st);
+        return r;
+    }
+    /* Then drop leftovers of an interrupted commit. */
+    if ((uint64_t)sb.st_size > st->cur.dispatch_len) {
+        rec.dispatch_truncated = (uint64_t)sb.st_size - st->cur.dispatch_len;
+        if (ftruncate(st->log_fd, (off_t)st->cur.dispatch_len) || fsync(st->log_fd)) { tg_close(st); return TG_E_IO; }
+    }
+    if ((r = sweep(dir, gen, &rec))) { tg_close(st); return r; }
+    if (rec_out) *rec_out = rec;
+    *out = st;
+    return TG_OK;
+}
+
+void tg_close(tg_store *st)
+{
+    if (!st) return;
+    tg_snapshot_free(&st->cur);
+    if (st->log_fd >= 0) close(st->log_fd);
+    if (st->lock_fd >= 0) close(st->lock_fd);
+    free(st);
+}
+
+const tg_snapshot *tg_committed(const tg_store *st) { return &st->cur; }
+const tg_stats *tg_get_stats(const tg_store *st) { return &st->stats; }
+
+/* ---- shadow ----------------------------------------------------------- */
+int tg_shadow_begin(tg_store *st, tg_shadow *sh)
+{
+    if (!st || !sh) return TG_E_ARG;
+    memset(sh, 0, sizeof *sh);
+    sh->params = malloc(st->cur.param_bytes ? st->cur.param_bytes : 1);
+    sh->opt = malloc(st->cur.opt_bytes ? st->cur.opt_bytes : 1);
+    if (!sh->params || !sh->opt) { free(sh->params); free(sh->opt); return TG_E_NOMEM; }
+    memcpy(sh->params, st->cur.params, st->cur.param_bytes);
+    memcpy(sh->opt, st->cur.opt, st->cur.opt_bytes);
+    sh->param_bytes = st->cur.param_bytes;
+    sh->opt_bytes = st->cur.opt_bytes;
+    sh->base_gen = st->cur.gen;
+    sh->base_step = st->cur.step;
+    memcpy(sh->base_digest, st->cur.digest, TG_DIGEST);
+    sh->recs = NULL;
+    sh->rec_cap = 0;
+    sh->state = SH_OPEN;
+    return TG_OK;
+}
+
+void tg_shadow_discard(tg_shadow *sh)
+{
+    if (!sh) return;
+    free(sh->params); free(sh->opt); free(sh->recs);
+    sh->params = sh->opt = sh->recs = NULL;
+    sh->n_dispatch = sh->rec_cap = 0;
+    if (sh->state == SH_OPEN) sh->state = SH_DISCARDED;
+}
+
+int tg_dispatch(tg_store *st, tg_shadow *sh, uint32_t op_id, uint64_t arg0, uint64_t arg1,
+                const tg_ref *refs, uint32_t n_refs)
+{
+    if (!st || !sh || n_refs > TG_MAX_REFS || (n_refs && !refs)) return TG_E_ARG;
+    if (sh->state != SH_OPEN) return TG_E_STATE;
+    if (sh->n_dispatch == sh->rec_cap) {
+        uint32_t nc = sh->rec_cap ? sh->rec_cap * 2 : 8;
+        uint8_t *n = realloc(sh->recs, (size_t)nc * REC_SIZE);
+        if (!n) return TG_E_NOMEM;
+        sh->recs = n; sh->rec_cap = nc;
+    }
+    uint8_t *r = sh->recs + (size_t)sh->n_dispatch * REC_SIZE;
+    memset(r, 0, REC_SIZE);
+    put32(r, REC_MAGIC);
+    put32(r + 4, op_id);
+    /* r+8 seq: assigned at commit */
+    put64(r + 16, sh->base_step + 1);
+    put64(r + 24, sh->base_gen);
+    put64(r + 32, arg0);
+    put64(r + 40, arg1);
+    put32(r + 48, n_refs);
+    for (uint32_t i = 0; i < n_refs; i++) {
+        uint8_t *q = r + 56 + 24 * i;
+        put32(q, refs[i].buf);
+        put64(q + 8, refs[i].off);
+        put64(q + 16, refs[i].len);
+    }
+    memcpy(r + 128, sh->base_digest, TG_DIGEST); /* inputs by reference to the base generation */
+    sh->n_dispatch++;
+    return TG_OK;
+}
+
+/* ---- commit ----------------------------------------------------------- */
+static int refuse(tg_store *st, tg_shadow *sh, int err, const char *detail)
+{
+    st->stats.refusals++;
+    record_refusal(st->dir, err, st->cur.gen, detail);
+    if (sh && sh->state == SH_OPEN) tg_shadow_discard(sh);
+    return err;
+}
+
+int tg_commit(tg_store *st, tg_shadow *sh, tg_validate_fn validate, void *ctx)
+{
+    char sp[PATHMAX], gp[PATHMAX];
+    if (!st || !sh) return TG_E_ARG;
+    if (st->poisoned)
+        return refuse(st, sh, TG_E_STATE, "commit: previous switch not known durable; reopen the store to recover");
+    if (sh->state != SH_OPEN) {
+        st->stats.refusals++;
+        record_refusal(st->dir, TG_E_STATE, st->cur.gen, "commit: shadow already committed or discarded (double switch)");
+        return TG_E_STATE;
+    }
+    if (sh->base_gen != st->cur.gen || memcmp(sh->base_digest, st->cur.digest, TG_DIGEST))
+        return refuse(st, sh, TG_E_STALE, "commit: shadow base is not the current generation");
+    if (sh->param_bytes != st->cur.param_bytes || sh->opt_bytes != st->cur.opt_bytes)
+        return refuse(st, sh, TG_E_ARG, "commit: shadow size differs from committed state");
+    if (validate && validate(sh, &st->cur, ctx) != 0)
+        return refuse(st, sh, TG_E_REJECT, "commit: validation callback rejected the shadow");
+
+    uint64_t ng = st->cur.gen + 1, nstep = st->cur.step + 1;
+    uint64_t base_len = st->cur.dispatch_len;
+    uint8_t head[TG_DIGEST];
+    memcpy(head, st->cur.dispatch_head, TG_DIGEST);
+
+    /* Tier (a): append this step's dispatch records, chained, then fsync. */
+    for (uint32_t i = 0; i < sh->n_dispatch; i++) {
+        uint8_t *r = sh->recs + (size_t)i * REC_SIZE;
+        put64(r + 8, base_len / REC_SIZE + i);
+        chain_step(head, r, r + REC_HASHED);
+        memcpy(head, r + REC_HASHED, TG_DIGEST);
+        st->stats.dispatch_records++;
+        st->stats.dispatch_hashed_bytes += TG_DIGEST + REC_HASHED;
+    }
+    uint64_t new_len = base_len + (uint64_t)sh->n_dispatch * REC_SIZE;
+    if (sh->n_dispatch) {
+        size_t n = (size_t)sh->n_dispatch * REC_SIZE;
+        if (pwrite(st->log_fd, sh->recs, n, (off_t)base_len) != (ssize_t)n || fsync(st->log_fd))
+            goto io_undo;
+    }
+
+    /* Tier (b): full digest of the new state, only here. */
+    uint8_t h[GEN_HDR], d[TG_DIGEST];
+    gen_header(h, ng, nstep, sh->param_bytes, sh->opt_bytes, new_len, head, st->cur.digest);
+    gen_digest(h, sh->params, sh->param_bytes, sh->opt, sh->opt_bytes, d);
+    memcpy(h + 120, d, TG_DIGEST);
+    st->stats.commit_hashed_bytes += GEN_HASHED_HDR + sh->param_bytes + sh->opt_bytes;
+
+    if (gen_name(sp, st->dir, "shadow-", ng, ".tmp") || gen_name(gp, st->dir, "gen-", ng, ".bin"))
+        return refuse(st, sh, TG_E_ARG, "commit: path too long");
+    fp_hit(TG_FP_BEFORE_SHADOW_WRITE);
+    if (write_gen_file(sp, h, sh->params, sh->param_bytes, sh->opt, sh->opt_bytes, 1)) goto io_undo;
+
+    /* Read the shadow file back and verify it before it can become a generation. */
+    if (g_fp == TG_FP_AFTER_SHADOW_WRITE && g_fpmode == TG_FPMODE_CORRUPT) {
+        int fd = open(sp, O_RDWR);
+        uint8_t b;
+        off_t at = GEN_HDR + (off_t)(sh->param_bytes / 3);
+        if (fd >= 0 && pread(fd, &b, 1, at) == 1) { b ^= 0x5a; (void)!pwrite(fd, &b, 1, at); }
+        if (fd >= 0) close(fd);
+    }
+    {
+        tg_snapshot chk;
+        int vr = load_gen(sp, ng, d, &chk);
+        tg_snapshot_free(&chk);
+        if (vr) {
+            unlink(sp);
+            (void)!ftruncate(st->log_fd, (off_t)base_len);
+            (void)!fsync(st->log_fd);
+            return refuse(st, sh, TG_E_SHADOW, "commit: shadow file read-back did not verify (corrupted shadow)");
+        }
+    }
+    fp_hit(TG_FP_AFTER_SHADOW_WRITE);
+    if (rename(sp, gp)) goto io_undo;
+    if (fsync_dir(st->dir)) { unlink(gp); goto io_undo; }
+    fp_hit(TG_FP_AFTER_GEN_RENAME);
+    int wp = write_pointer(st->dir, ng, d, 1);
+    if (wp < 0) { unlink(gp); goto io_undo; }
+    if (wp == 0) fp_hit(TG_FP_AFTER_SWITCH);
+
+    /* Adopt the shadow as the committed in-memory state. */
+    tg_snapshot_free(&st->cur);
+    st->cur.gen = ng;
+    st->cur.step = nstep;
+    memcpy(st->cur.prev_digest, sh->base_digest, TG_DIGEST);
+    memcpy(st->cur.digest, d, TG_DIGEST);
+    memcpy(st->cur.dispatch_head, head, TG_DIGEST);
+    st->cur.dispatch_len = new_len;
+    st->cur.params = sh->params; st->cur.param_bytes = sh->param_bytes;
+    st->cur.opt = sh->opt; st->cur.opt_bytes = sh->opt_bytes;
+    sh->params = sh->opt = NULL;
+    free(sh->recs); sh->recs = NULL;
+    sh->state = SH_COMMITTED;
+    if (wp > 0) {
+        st->poisoned = 1;
+        /* The switch is visible (readers see NEW) but its directory entry may not
+         * be durable yet: report it, never undo it. */
+        st->stats.refusals++;
+        record_refusal(st->dir, TG_E_IO, ng, "commit: switched, directory fsync failed (durability unknown)");
+        return TG_E_IO;
+    }
+    return TG_OK;
+
+io_undo:
+    unlink(sp);
+    (void)!ftruncate(st->log_fd, (off_t)base_len);
+    return refuse(st, sh, TG_E_IO, "commit: I/O error before switch");
+}
+
+/* ---- readers ---------------------------------------------------------- */
+int tg_read_current(const char *dir, tg_snapshot *out)
+{
+    char p[PATHMAX];
+    uint64_t gen;
+    uint8_t d[TG_DIGEST];
+    if (!dir || !out) return TG_E_ARG;
+    memset(out, 0, sizeof *out);
+    int r = read_pointer(dir, &gen, d);
+    if (r) return r;
+    if (gen_name(p, dir, "gen-", gen, ".bin")) return TG_E_ARG;
+    return load_gen(p, gen, d, out);
+}
+
+int tg_verify_history(const char *dir, uint64_t *n_verified)
+{
+    char p[PATHMAX];
+    uint64_t gen;
+    uint8_t d[TG_DIGEST], zero[TG_DIGEST] = {0};
+    if (n_verified) *n_verified = 0;
+    int r = read_pointer(dir, &gen, d);
+    if (r) return r;
+    uint64_t later_len = UINT64_MAX;
+    for (;;) {
+        tg_snapshot s;
+        if (gen_name(p, dir, "gen-", gen, ".bin")) return TG_E_ARG;
+        if ((r = load_gen(p, gen, d, &s))) return r;
+        int bad = s.dispatch_len > later_len || (gen == 0 && (memcmp(s.prev_digest, zero, TG_DIGEST) || s.step != 0));
+        later_len = s.dispatch_len;
+        memcpy(d, s.prev_digest, TG_DIGEST);
+        tg_snapshot_free(&s);
+        if (bad) return TG_E_CHAIN;
+        if (n_verified) (*n_verified)++;
+        if (gen == 0) return TG_OK;
+        gen--;
+    }
+}
+
+int tg_dispatch_read(const char *dir, uint64_t seq, tg_dispatch_rec *out)
+{
+    uint8_t head[TG_DIGEST];
+    char p[PATHMAX];
+    if (!dir || !out || seq > (UINT64_MAX / REC_SIZE) - 1) return TG_E_ARG;
+    int r = tg_dispatch_chain(dir, (seq + 1) * REC_SIZE, head, NULL);
+    if (r) return r;
+    if (path_of(p, dir, "dispatch.log")) return TG_E_ARG;
+    int fd = open(p, O_RDONLY);
+    if (fd < 0) return TG_E_IO;
+    uint8_t rec[REC_SIZE];
+    ssize_t g = pread(fd, rec, REC_SIZE, (off_t)(seq * REC_SIZE));
+    close(fd);
+    if (g != REC_SIZE) return TG_E_CHAIN;
+    memset(out, 0, sizeof *out);
+    out->op_id = get32(rec + 4);
+    out->seq = get64(rec + 8);
+    out->step = get64(rec + 16);
+    out->base_gen = get64(rec + 24);
+    out->arg0 = get64(rec + 32);
+    out->arg1 = get64(rec + 40);
+    out->n_refs = get32(rec + 48);
+    if (out->n_refs > TG_MAX_REFS) return TG_E_FORMAT;
+    for (uint32_t i = 0; i < out->n_refs; i++) {
+        const uint8_t *q = rec + 56 + 24 * i;
+        out->refs[i].buf = get32(q);
+        out->refs[i].off = get64(q + 8);
+        out->refs[i].len = get64(q + 16);
+    }
+    memcpy(out->base_digest, rec + 128, TG_DIGEST);
+    memcpy(out->chain, rec + REC_HASHED, TG_DIGEST);
+    return TG_OK;
+}
+
+int tg_read_gen(const char *dir, uint64_t gen, const uint8_t *expect_digest, tg_snapshot *out)
+{
+    char p[PATHMAX];
+    if (!dir || !out) return TG_E_ARG;
+    memset(out, 0, sizeof *out);
+    if (gen_name(p, dir, "gen-", gen, ".bin")) return TG_E_ARG;
+    return load_gen(p, gen, expect_digest, out);
+}
diff --git a/src/train/tg_store.h b/src/train/tg_store.h
new file mode 100644
index 000000000..f01e38df3
--- /dev/null
+++ b/src/train/tg_store.h
@@ -0,0 +1,180 @@
+/* tg_store.h -- M22 transactional parameter-state substrate (Lane 21).
+ *
+ * A training "generation" is one committed, content-addressed state:
+ *   parameters (opaque bytes, usually N float32) + optimizer state (opaque
+ *   bytes) + step counter + SHA-256 digest + previous generation's digest
+ *   + the head of the per-dispatch provenance chain at commit time.
+ *
+ * Writer protocol (one writer per store directory, enforced by flock):
+ *   tg_shadow_begin   copy the committed state into a private SHADOW
+ *   (updaters)        mutate only the shadow; each update adds one small
+ *                     per-dispatch provenance record (tier a), held with the
+ *                     shadow and appended + fsynced to dispatch.log at commit
+ *   tg_commit         validation callback must accept, then: write shadow
+ *                     file, fsync, read back + verify digest, rename to
+ *                     gen-N.bin, fsync dir, write CURRENT.tmp, fsync, rename
+ *                     to CURRENT (the ONE atomic switch), fsync dir.
+ * Readers (tg_read_current) take no lock and always get OLD or NEW, digest
+ * verified against the pointer, never a mix.
+ *
+ * Provenance has two tiers, kept separate (CURRENT_EXECUTION_PLAN E5):
+ *   (a) dispatch.log: fixed-size, append-only, hash-chained records holding
+ *       step, op id, scalar args and input REFERENCES (buffer id, offset,
+ *       length, base generation digest). Hashing cost per record is constant
+ *       and independent of model size; the model is never hashed here.
+ *   (b) the full parameter + optimizer digest, computed only at commit.
+ *
+ * Plain C, no tensor/autodiff dependency (M20/M21 integration is later).
+ * This substrate does NOT qualify M22. */
+#ifndef OMEGA_TG_STORE_H
+#define OMEGA_TG_STORE_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define TG_DIGEST 32
+#define TG_MAX_REFS 3
+
+typedef enum {
+    TG_OK = 0,
+    TG_E_ARG = -1,        /* bad argument / size mismatch */
+    TG_E_IO = -2,         /* filesystem error */
+    TG_E_NOSTORE = -3,    /* no CURRENT pointer */
+    TG_E_FORMAT = -4,     /* bad magic / version / pointer syntax / extra bytes */
+    TG_E_TRUNC = -5,      /* generation file shorter than its header declares */
+    TG_E_DIGEST = -6,     /* recomputed digest != header digest or != pointer digest */
+    TG_E_CHAIN = -7,      /* dispatch provenance chain does not match the commit */
+    TG_E_REJECT = -8,     /* validation callback refused the shadow */
+    TG_E_STATE = -9,      /* shadow already committed or discarded (double switch) */
+    TG_E_STALE = -10,     /* shadow base generation is not the current generation */
+    TG_E_SHADOW = -11,    /* shadow file read-back did not verify (corrupted shadow) */
+    TG_E_LOCKED = -12,    /* another writer holds the store */
+    TG_E_EXISTS = -13,    /* tg_create on a non-empty store */
+    TG_E_NOMEM = -14
+} tg_err;
+
+const char *tg_err_name(int err);
+
+/* Injectable crash points inside tg_commit (test harness only; default off). */
+typedef enum {
+    TG_FP_NONE = 0,
+    TG_FP_BEFORE_SHADOW_WRITE = 1,
+    TG_FP_MID_SHADOW_WRITE = 2,      /* header + half of the parameter bytes written */
+    TG_FP_AFTER_SHADOW_WRITE = 3,    /* shadow fsynced and verified, not yet renamed */
+    TG_FP_AFTER_GEN_RENAME = 4,      /* gen-N.bin exists, pointer not switched */
+    TG_FP_MID_SWITCH = 5,            /* CURRENT.tmp half written */
+    TG_FP_BEFORE_SWITCH_RENAME = 6,  /* CURRENT.tmp complete + fsynced, not renamed */
+    TG_FP_AFTER_SWITCH_BEFORE_FSYNC = 7, /* CURRENT renamed, directory not fsynced */
+    TG_FP_AFTER_SWITCH = 8,          /* everything durable, in-memory state not updated */
+    TG_FP_COUNT = 9
+} tg_failpoint;
+
+typedef enum {
+    TG_FPMODE_EXIT = 1,     /* _exit(TG_FP_EXIT_CODE) at the point */
+    TG_FPMODE_CORRUPT = 2   /* only at AFTER_SHADOW_WRITE's read-back: flip one shadow byte on disk */
+} tg_fpmode;
+
+#define TG_FP_EXIT_CODE 77
+
+void tg_failpoint_arm(tg_failpoint fp, tg_fpmode mode);
+void tg_failpoint_disarm(void);
+const char *tg_failpoint_name(tg_failpoint fp);
+
+/* Input reference for a dispatch record: buffer id + byte range. */
+typedef struct {
+    uint32_t buf;      /* TG_BUF_* or caller-defined id */
+    uint64_t off;
+    uint64_t len;
+} tg_ref;
+
+enum { TG_BUF_PARAMS = 1, TG_BUF_OPT = 2, TG_BUF_EXTERNAL = 3 };
+
+typedef struct {
+    uint8_t *params;
+    size_t param_bytes;
+    uint8_t *opt;
+    size_t opt_bytes;
+    uint64_t base_gen;
+    uint64_t base_step;
+    uint8_t base_digest[TG_DIGEST];
+    uint32_t n_dispatch;
+    uint32_t rec_cap;
+    uint8_t *recs;      /* pending dispatch records, appended to dispatch.log at commit */
+    int state;          /* internal: open / committed / discarded */
+} tg_shadow;
+
+typedef struct {
+    uint32_t removed_tmp;       /* shadow-*.tmp and CURRENT.tmp removed */
+    uint32_t removed_orphan_gen;/* gen files newer than CURRENT removed */
+    uint64_t dispatch_truncated;/* uncommitted dispatch-log bytes dropped */
+} tg_recovery;
+
+typedef struct {
+    uint64_t gen;
+    uint64_t step;
+    uint8_t digest[TG_DIGEST];
+    uint8_t prev_digest[TG_DIGEST];
+    uint8_t dispatch_head[TG_DIGEST];
+    uint64_t dispatch_len;
+    uint8_t *params;
+    size_t param_bytes;
+    uint8_t *opt;
+    size_t opt_bytes;
+} tg_snapshot;
+
+typedef int (*tg_validate_fn)(const tg_shadow *sh, const tg_snapshot *committed, void *ctx);
+
+typedef struct tg_store tg_store;
+
+/* Bytes hashed for tier (a) provenance and for tier (b), for the cost test. */
+typedef struct {
+    uint64_t dispatch_records;
+    uint64_t dispatch_hashed_bytes;
+    uint64_t commit_hashed_bytes;
+    uint64_t refusals;
+} tg_stats;
+
+int tg_create(const char *dir, const void *params, size_t param_bytes,
+              const void *opt, size_t opt_bytes);
+int tg_open(const char *dir, tg_store **out, tg_recovery *rec);
+void tg_close(tg_store *st);
+
+const tg_snapshot *tg_committed(const tg_store *st);
+const tg_stats *tg_get_stats(const tg_store *st);
+
+int tg_shadow_begin(tg_store *st, tg_shadow *sh);
+void tg_shadow_discard(tg_shadow *sh);
+/* Append a tier (a) record for an update applied to `sh`. */
+int tg_dispatch(tg_store *st, tg_shadow *sh, uint32_t op_id, uint64_t arg0, uint64_t arg1,
+                const tg_ref *refs, uint32_t n_refs);
+/* Validate, then switch. On success `sh` is consumed (state committed). */
+int tg_commit(tg_store *st, tg_shadow *sh, tg_validate_fn validate, void *ctx);
+
+/* Lock-free reader: current generation, digest verified against CURRENT. */
+int tg_read_current(const char *dir, tg_snapshot *out);
+void tg_snapshot_free(tg_snapshot *s);
+
+/* Read one generation by number (verified; expect_digest may be NULL). */
+int tg_read_gen(const char *dir, uint64_t gen, const uint8_t *expect_digest, tg_snapshot *out);
+
+/* Walk the prev-digest chain from CURRENT back to generation 0 (every
+ * generation file must be present and verify). */
+int tg_verify_history(const char *dir, uint64_t *n_verified);
+
+/* Decoded tier (a) record (read back from dispatch.log, chain verified up to it). */
+typedef struct {
+    uint64_t seq, step, base_gen, arg0, arg1;
+    uint32_t op_id, n_refs;
+    tg_ref refs[TG_MAX_REFS];
+    uint8_t base_digest[TG_DIGEST];
+    uint8_t chain[TG_DIGEST];
+} tg_dispatch_rec;
+
+int tg_dispatch_read(const char *dir, uint64_t seq, tg_dispatch_rec *out);
+
+/* Recompute the dispatch-log chain over its first `len` bytes. */
+int tg_dispatch_chain(const char *dir, uint64_t len, uint8_t head[TG_DIGEST], uint64_t *n_records);
+
+void tg_hex(const uint8_t d[TG_DIGEST], char out[2 * TG_DIGEST + 1]);
+
+#endif
diff --git a/tests/train/test_train.c b/tests/train/test_train.c
new file mode 100644
index 000000000..a0db13e85
--- /dev/null
+++ b/tests/train/test_train.c
@@ -0,0 +1,534 @@
+/* test_train.c -- M22 substrate exit tests (Lane 21). Host only, one core.
+ *
+ *   test_train <scratch-dir>
+ *
+ * Sections: basic commit + history; SGD training on a fixed quadratic;
+ * crash matrix (fork + _exit at every injectable point, recovery yields
+ * exactly OLD or NEW, digest verified; plus torn-file simulation); lock-free
+ * reader racing a writer; negatives (corrupted shadow, truncated generation,
+ * digest mismatch, pointer mismatch, validation reject, double switch, stale
+ * shadow, dispatch tamper, truncated dispatch log, second writer, re-create);
+ * provenance cost (tier a constant per record, tier b only at commit);
+ * replay (same update sequence from G0 -> byte-identical G_n, and each
+ * committed step re-derived from its dispatch record). Prints
+ * "replay_digest <hex>" and the verdict line M22_SUBSTRATE_TESTS_PASS. */
+#define _XOPEN_SOURCE 700
+#include "train/tg_sgd.h"
+#include "train/tg_store.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <ftw.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+static int g_checks, g_fail;
+#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_fail++; fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \
+    fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0)
+
+static char g_base[1024];
+static int g_dirn;
+
+static int rm_cb(const char *p, const struct stat *sb, int f, struct FTW *fw)
+{ (void)sb; (void)f; (void)fw; return remove(p); }
+static void rmtree(const char *d) { nftw(d, rm_cb, 16, FTW_DEPTH | FTW_PHYS); }
+
+static void newdir(char *out, size_t n, const char *tag)
+{
+    snprintf(out, n, "%s/%02d-%s", g_base, g_dirn++, tag);
+    rmtree(out);
+}
+
+/* ---- deterministic fixture: quadratic L = 0.5 * sum (p - t)^2 ---------- */
+static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; }
+static float urand(uint32_t *s) { return (float)(lcg(s) >> 8) / 16777216.0f - 0.5f; }
+
+static void init_params(float *p, size_t n, uint32_t seed) { for (size_t i = 0; i < n; i++) p[i] = 4.0f * urand(&seed); }
+static void target(float *t, size_t n) { uint32_t s = 0xC0FFEEu; for (size_t i = 0; i < n; i++) t[i] = urand(&s); }
+
+static void grad_of(const float *p, const float *t, float *g, size_t n)
+{ for (size_t i = 0; i < n; i++) g[i] = p[i] - t[i]; }
+
+static double loss_of(const float *p, const float *t, size_t n)
+{ double l = 0; for (size_t i = 0; i < n; i++) { double d = (double)p[i] - t[i]; l += 0.5 * d * d; } return l; }
+
+static int v_finite(const tg_shadow *sh, const tg_snapshot *c, void *ctx)
+{
+    (void)c; (void)ctx;
+    const float *p = (const float *)(const void *)sh->params;
+    for (size_t i = 0; i < sh->param_bytes / 4; i++) if (!isfinite(p[i])) return 1;
+    return 0;
+}
+static int v_reject(const tg_shadow *sh, const tg_snapshot *c, void *ctx) { (void)sh; (void)c; (void)ctx; return 1; }
+
+#define N_SMALL 1024
+static const float LR = 0.05f, MOM = 0.9f;
+
+static int make_store(const char *dir, size_t n, int momentum)
+{
+    float *p = calloc(n, 4), *v = calloc(n, 4);
+    init_params(p, n, 12345u);
+    int r = tg_create(dir, p, n * 4, v, momentum ? n * 4 : 0);
+    free(p); free(v);
+    return r;
+}
+
+/* One SGD step on an open store; returns commit result. */
+static int sgd_commit(tg_store *st, const float *t, size_t n, float mom, uint64_t ref)
+{
+    tg_shadow sh;
+    int r = tg_shadow_begin(st, &sh);
+    if (r) return r;
+    float *g = malloc(n * 4);
+    grad_of((const float *)(const void *)tg_committed(st)->params, t, g, n);
+    r = tg_sgd_step(st, &sh, g, n, LR, mom, ref);
+    free(g);
+    if (r) { tg_shadow_discard(&sh); return r; }
+    return tg_commit(st, &sh, v_finite, NULL);
+}
+
+static int count_refusals(const char *dir, const char *code)
+{
+    char p[1200], line[512], key[64];
+    snprintf(p, sizeof p, "%s/refusals.log", dir);
+    snprintf(key, sizeof key, "REFUSE %s ", code);
+    FILE *f = fopen(p, "r");
+    if (!f) return 0;
+    int c = 0;
+    while (fgets(line, sizeof line, f)) if (!strncmp(line, key, strlen(key))) c++;
+    fclose(f);
+    return c;
+}
+
+static int file_exists(const char *dir, const char *name)
+{ char p[1200]; snprintf(p, sizeof p, "%s/%s", dir, name); return access(p, F_OK) == 0; }
+
+static off_t file_size(const char *dir, const char *name)
+{ char p[1200]; struct stat sb; snprintf(p, sizeof p, "%s/%s", dir, name); return stat(p, &sb) ? -1 : sb.st_size; }
+
+static void gen_file(char *out, size_t n, const char *dir, uint64_t g)
+{ snprintf(out, n, "%s/gen-%020llu.bin", dir, (unsigned long long)g); }
+
+static void flip_byte(const char *path, off_t at)
+{
+    int fd = open(path, O_RDWR);
+    uint8_t b = 0;
+    if (fd < 0) return;
+    if (pread(fd, &b, 1, at) == 1) { b ^= 0x01; (void)!pwrite(fd, &b, 1, at); }
+    close(fd);
+}
+
+/* ---- 1. basic --------------------------------------------------------- */
+static void t_basic(const float *t)
+{
+    char d[1100];
+    newdir(d, sizeof d, "basic");
+    CHECK(make_store(d, N_SMALL, 1) == TG_OK, "create");
+    tg_store *st; tg_recovery rec;
+    CHECK(tg_open(d, &st, &rec) == TG_OK, "open");
+    if (!st) return;
+    CHECK(tg_committed(st)->gen == 0 && tg_committed(st)->step == 0, "gen0");
+    uint8_t d0[TG_DIGEST]; memcpy(d0, tg_committed(st)->digest, TG_DIGEST);
+    CHECK(sgd_commit(st, t, N_SMALL, MOM, 1) == TG_OK, "commit 1");
+    CHECK(tg_committed(st)->gen == 1 && tg_committed(st)->step == 1, "gen1");
+    CHECK(!memcmp(tg_committed(st)->prev_digest, d0, TG_DIGEST), "prev digest links to gen0");
+    tg_snapshot s;
+    CHECK(tg_read_current(d, &s) == TG_OK && s.gen == 1 && !memcmp(s.digest, tg_committed(st)->digest, TG_DIGEST),
+          "reader sees gen1");
+    tg_snapshot_free(&s);
+    tg_close(st);
+    uint64_t nv;
+    CHECK(tg_verify_history(d, &nv) == TG_OK && nv == 2, "history 2 gens");
+    CHECK(!file_exists(d, "CURRENT.tmp"), "no pointer tmp left");
+}
+
+/* ---- 2. SGD training ---------------------------------------------------- */
+static void t_training(const float *t)
+{
+    char d[1100];
+    for (int m = 0; m < 2; m++) {
+        newdir(d, sizeof d, m ? "sgd-momentum" : "sgd-plain");
+        float mom = m ? MOM : 0.0f;
+        CHECK(make_store(d, N_SMALL, m) == TG_OK, "create");
+        tg_store *st;
+        CHECK(tg_open(d, &st, NULL) == TG_OK, "open");
+        if (!st) return;
+        double l0 = loss_of((const float *)(const void *)tg_committed(st)->params, t, N_SMALL);
+        for (int k = 0; k < 40; k++) CHECK(sgd_commit(st, t, N_SMALL, mom, 100 + (uint64_t)k) == TG_OK, "step %d", k);
+        double l1 = loss_of((const float *)(const void *)tg_committed(st)->params, t, N_SMALL);
+        printf("sgd_%s loss_g0 %.6f loss_g40 %.6f\n", m ? "momentum" : "plain", l0, l1);
+        CHECK(l1 < l0 * 0.1, "loss fell by 10x (%f -> %f)", l0, l1);
+        CHECK(tg_committed(st)->gen == 40, "40 generations");
+        tg_close(st);
+        uint64_t nv;
+        CHECK(tg_verify_history(d, &nv) == TG_OK && nv == 41, "history 41");
+    }
+}
+
+/* ---- 3. crash matrix ---------------------------------------------------- */
+static void t_crash(const float *t)
+{
+    /* Reference: OLD = gen1, NEW = gen2 with the same step applied cleanly. */
+    char ref[1100];
+    newdir(ref, sizeof ref, "crash-ref");
+    tg_store *st;
+    uint8_t dold[TG_DIGEST], dnew[TG_DIGEST];
+    make_store(ref, N_SMALL, 1);
+    CHECK(tg_open(ref, &st, NULL) == TG_OK, "ref open");
+    if (!st) return;
+    sgd_commit(st, t, N_SMALL, MOM, 1);
+    memcpy(dold, tg_committed(st)->digest, TG_DIGEST);
+    CHECK(sgd_commit(st, t, N_SMALL, MOM, 2) == TG_OK, "ref new");
+    memcpy(dnew, tg_committed(st)->digest, TG_DIGEST);
+    tg_close(st);
+
+    for (int torn = 0; torn < 2; torn++)
+    for (int fp = 1; fp < TG_FP_COUNT; fp++) {
+        if (torn && fp != TG_FP_AFTER_SHADOW_WRITE && fp != TG_FP_AFTER_GEN_RENAME && fp != TG_FP_BEFORE_SWITCH_RENAME) continue;
+        char d[1100];
+        newdir(d, sizeof d, "crash");
+        make_store(d, N_SMALL, 1);
+        CHECK(tg_open(d, &st, NULL) == TG_OK, "open");
+        if (!st) return;
+        sgd_commit(st, t, N_SMALL, MOM, 1);
+        CHECK(!memcmp(tg_committed(st)->digest, dold, TG_DIGEST), "old digest reproducible");
+        tg_close(st);
+
+        fflush(NULL);
+        pid_t pid = fork();
+        if (pid == 0) {
+            tg_store *w;
+            if (tg_open(d, &w, NULL)) _exit(2);
+            tg_failpoint_arm((tg_failpoint)fp, TG_FPMODE_EXIT);
+            sgd_commit(w, t, N_SMALL, MOM, 2);
+            _exit(3); /* fail point not reached */
+        }
+        int status = 0;
+        waitpid(pid, &status, 0);
+        CHECK(WIFEXITED(status) && WEXITSTATUS(status) == TG_FP_EXIT_CODE, "fp %s: child exit %d",
+              tg_failpoint_name((tg_failpoint)fp), WIFEXITED(status) ? WEXITSTATUS(status) : -1);
+
+        if (torn) { /* simulate partial persistence of the not-yet-current files */
+            char p[1200];
+            if (fp == TG_FP_AFTER_SHADOW_WRITE) snprintf(p, sizeof p, "%s/shadow-%020llu.tmp", d, 2ull);
+            else if (fp == TG_FP_AFTER_GEN_RENAME) gen_file(p, sizeof p, d, 2);
+            else snprintf(p, sizeof p, "%s/CURRENT.tmp", d);
+            struct stat sb;
+            CHECK(stat(p, &sb) == 0 && truncate(p, sb.st_size / 2) == 0, "torn %s", p);
+        }
+
+        int expect_new = fp >= TG_FP_AFTER_SWITCH_BEFORE_FSYNC;
+        const uint8_t *want = expect_new ? dnew : dold;
+        tg_snapshot s;
+        int rr = tg_read_current(d, &s); /* reader before recovery */
+        CHECK(rr == TG_OK && s.gen == (expect_new ? 2u : 1u) && !memcmp(s.digest, want, TG_DIGEST),
+              "fp %s torn=%d: reader before recovery sees %s (rc %s)", tg_failpoint_name((tg_failpoint)fp), torn,
+              expect_new ? "NEW" : "OLD", tg_err_name(rr));
+        tg_snapshot_free(&s);
+
+        tg_recovery rec = {0, 0, 0};
+        CHECK(tg_open(d, &st, &rec) == TG_OK, "fp %s: recovery open", tg_failpoint_name((tg_failpoint)fp));
+        if (!st) continue;
+        CHECK(tg_committed(st)->gen == (expect_new ? 2u : 1u) && !memcmp(tg_committed(st)->digest, want, TG_DIGEST),
+              "fp %s torn=%d: recovered state is exactly %s", tg_failpoint_name((tg_failpoint)fp), torn, expect_new ? "NEW" : "OLD");
+        CHECK(!file_exists(d, "CURRENT.tmp"), "pointer tmp swept");
+        CHECK(expect_new || !file_exists(d, "gen-00000000000000000002.bin"), "orphan NEW generation swept");
+        if (!expect_new && fp >= TG_FP_BEFORE_SHADOW_WRITE)
+            CHECK(rec.dispatch_truncated == 192, "fp %s: uncommitted dispatch record dropped (%llu)",
+                  tg_failpoint_name((tg_failpoint)fp), (unsigned long long)rec.dispatch_truncated);
+        printf("crash fp=%s torn=%d recovered=%s tmp=%u orphan=%u dispatch_dropped=%llu\n",
+               tg_failpoint_name((tg_failpoint)fp), torn, expect_new ? "NEW" : "OLD", rec.removed_tmp,
+               rec.removed_orphan_gen, (unsigned long long)rec.dispatch_truncated);
+        /* Store remains usable; redoing the step from OLD lands on the same NEW digest. */
+        if (!expect_new) {
+            CHECK(sgd_commit(st, t, N_SMALL, MOM, 2) == TG_OK && !memcmp(tg_committed(st)->digest, dnew, TG_DIGEST),
+                  "fp %s: redo from OLD reproduces NEW", tg_failpoint_name((tg_failpoint)fp));
+        }
+        tg_close(st);
+        uint64_t nv;
+        CHECK(tg_verify_history(d, &nv) == TG_OK && nv == 3, "history after crash");
+    }
+}
+
+/* ---- 4. reader racing a writer --------------------------------------- */
+static void t_reader_race(const float *t)
+{
+    char d[1100];
+    newdir(d, sizeof d, "race");
+    make_store(d, N_SMALL, 1);
+    int stop[2], res[2];
+    if (pipe(stop) || pipe(res)) { CHECK(0, "pipe"); return; }
+    fflush(NULL);
+    pid_t pid = fork();
+    if (pid == 0) {
+        close(stop[1]); close(res[0]);
+        fcntl(stop[0], F_SETFL, O_NONBLOCK);
+        long reads = 0, bad = 0, backwards = 0, last = -1;
+        for (;;) {
+            char c;
+            ssize_t r = read(stop[0], &c, 1);
+            tg_snapshot s;
+            int rc = tg_read_current(d, &s);
+            if (rc) bad++;
+            else { if ((long)s.gen < last) backwards++; last = (long)s.gen; tg_snapshot_free(&s); }
+            reads++;
+            if (r == 0) break;
+        }
+        long out[4] = {reads, bad, backwards, last};
+        (void)!write(res[1], out, sizeof out);
+        _exit(0);
+    }
+    close(stop[0]); close(res[1]);
+    tg_store *st;
+    CHECK(tg_open(d, &st, NULL) == TG_OK, "open");
+    for (int k = 0; k < 150 && st; k++) {
+        sgd_commit(st, t, N_SMALL, MOM, (uint64_t)k);
+        if (k % 8 == 0) usleep(200);
+    }
+    tg_close(st);
+    close(stop[1]);
+    long out[4] = {0, -1, -1, -1};
+    CHECK(read(res[0], out, sizeof out) == (ssize_t)sizeof out, "reader result");
+    waitpid(pid, NULL, 0);
+    printf("reader_race reads %ld bad %ld backwards %ld last_gen %ld\n", out[0], out[1], out[2], out[3]);
+    CHECK(out[0] > 0 && out[1] == 0 && out[2] == 0 && out[3] == 150, "reader saw only whole, verified, monotonic generations");
+}
+
+/* ---- 5. negatives ------------------------------------------------------- */
+static void t_negatives(const float *t)
+{
+    char d[1100], p[1200];
+    tg_store *st, *st2;
+    tg_shadow a, b;
+    float *g = malloc(N_SMALL * 4);
+
+    /* corrupted shadow */
+    newdir(d, sizeof d, "neg-shadow");
+    make_store(d, N_SMALL, 1);
+    tg_open(d, &st, NULL);
+    off_t log0 = file_size(d, "dispatch.log");
+    tg_failpoint_arm(TG_FP_AFTER_SHADOW_WRITE, TG_FPMODE_CORRUPT);
+    int r = sgd_commit(st, t, N_SMALL, MOM, 1);
+    tg_failpoint_disarm();
+    CHECK(r == TG_E_SHADOW, "corrupted shadow refused (%s)", tg_err_name(r));
+    CHECK(tg_committed(st)->gen == 0 && file_size(d, "dispatch.log") == log0, "state and dispatch log unchanged");
+    CHECK(!file_exists(d, "shadow-00000000000000000001.tmp") && !file_exists(d, "gen-00000000000000000001.bin"), "no shadow left");
+    CHECK(sgd_commit(st, t, N_SMALL, MOM, 1) == TG_OK, "clean retry commits");
+    CHECK(count_refusals(d, "E_SHADOW") == 1, "E_SHADOW recorded");
+
+    /* validation reject */
+    tg_shadow_begin(st, &a);
+    grad_of((const float *)(const void *)tg_committed(st)->params, t, g, N_SMALL);
+    tg_sgd_step(st, &a, g, N_SMALL, LR, MOM, 9);
+    r = tg_commit(st, &a, v_reject, NULL);
+    CHECK(r == TG_E_REJECT && tg_committed(st)->gen == 1, "validation reject refused");
+    CHECK(count_refusals(d, "E_REJECT") == 1, "E_REJECT recorded");
+    CHECK(tg_commit(st, &a, NULL, NULL) == TG_E_STATE, "rejected shadow cannot be committed later");
+
+    /* double switch */
+    tg_shadow_begin(st, &a);
+    tg_sgd_step(st, &a, g, N_SMALL, LR, MOM, 10);
+    CHECK(tg_commit(st, &a, NULL, NULL) == TG_OK && tg_committed(st)->gen == 2, "first switch");
+    CHECK(tg_commit(st, &a, NULL, NULL) == TG_E_STATE && tg_committed(st)->gen == 2, "double switch refused");
+    CHECK(count_refusals(d, "E_STATE") == 2, "E_STATE recorded");
+
+    /* stale shadow */
+    tg_shadow_begin(st, &a);
+    tg_shadow_begin(st, &b);
+    CHECK(tg_commit(st, &a, NULL, NULL) == TG_OK, "A commits");
+    CHECK(tg_commit(st, &b, NULL, NULL) == TG_E_STALE && tg_committed(st)->gen == 3, "stale B refused");
+    CHECK(count_refusals(d, "E_STALE") == 1, "E_STALE recorded");
+
+    /* second writer, re-create */
+    CHECK(tg_open(d, &st2, NULL) == TG_E_LOCKED, "second writer refused");
+    tg_close(st);
+    CHECK(make_store(d, N_SMALL, 1) == TG_E_EXISTS, "re-create refused");
+    uint64_t nv;
+    CHECK(tg_verify_history(d, &nv) == TG_OK && nv == 4, "history 4 after refusals");
+
+    /* truncated generation file */
+    newdir(d, sizeof d, "neg-trunc");
+    make_store(d, N_SMALL, 1);
+    tg_open(d, &st, NULL); sgd_commit(st, t, N_SMALL, MOM, 1); tg_close(st);
+    gen_file(p, sizeof p, d, 1);
+    struct stat sb; stat(p, &sb);
+    CHECK(truncate(p, sb.st_size - 10) == 0, "truncate");
+    tg_snapshot s;
+    CHECK(tg_read_current(d, &s) == TG_E_TRUNC, "reader refuses truncated");
+    CHECK(tg_open(d, &st, NULL) == TG_E_TRUNC, "open refuses truncated");
+    CHECK(count_refusals(d, "E_TRUNC") == 1, "E_TRUNC recorded");
+    CHECK(truncate(p, 100) == 0 && tg_open(d, &st, NULL) == TG_E_TRUNC, "header-truncated refused");
+
+    /* digest mismatch: payload byte flipped; then pointer names another digest */
+    newdir(d, sizeof d, "neg-digest");
+    make_store(d, N_SMALL, 1);
+    tg_open(d, &st, NULL); sgd_commit(st, t, N_SMALL, MOM, 1); tg_close(st);
+    gen_file(p, sizeof p, d, 1);
+    flip_byte(p, 152 + 777);
+    CHECK(tg_read_current(d, &s) == TG_E_DIGEST, "reader refuses flipped payload");
+    CHECK(tg_open(d, &st, NULL) == TG_E_DIGEST, "open refuses flipped payload");
+    flip_byte(p, 152 + 777);
+    CHECK(tg_open(d, &st, NULL) == TG_OK, "restored file opens");
+    tg_close(st);
+    snprintf(p, sizeof p, "%s/CURRENT", d);
+    flip_byte(p, 40); /* inside the hex digest: '0'..'9'/'a'..'f' xor 1 stays hex */
+    CHECK(tg_open(d, &st, NULL) == TG_E_DIGEST, "pointer digest mismatch refused");
+    CHECK(count_refusals(d, "E_DIGEST") == 2, "E_DIGEST recorded");
+
+    /* dispatch log tamper and truncation */
+    newdir(d, sizeof d, "neg-chain");
+    make_store(d, N_SMALL, 1);
+    tg_open(d, &st, NULL); sgd_commit(st, t, N_SMALL, MOM, 1); sgd_commit(st, t, N_SMALL, MOM, 2); tg_close(st);
+    snprintf(p, sizeof p, "%s/dispatch.log", d);
+    off_t committed_len = file_size(d, "dispatch.log");
+    {   /* uncommitted tail present: a refused open must not modify the store */
+        int fd = open(p, O_WRONLY | O_APPEND);
+        uint8_t junk[192]; memset(junk, 0xab, sizeof junk);
+        CHECK(fd >= 0 && write(fd, junk, sizeof junk) == (ssize_t)sizeof junk, "append tail");
+        if (fd >= 0) close(fd);
+    }
+    flip_byte(p, 192 + 33);
+    CHECK(tg_open(d, &st, NULL) == TG_E_CHAIN, "tampered dispatch record refused");
+    CHECK(file_size(d, "dispatch.log") == committed_len + 192, "refused open left the dispatch log untouched");
+    flip_byte(p, 192 + 33);
+    CHECK(tg_open(d, &st, NULL) == TG_OK && file_size(d, "dispatch.log") == committed_len, "valid open drops the tail");
+    tg_close(st);
+    CHECK(truncate(p, 192) == 0 && tg_open(d, &st, NULL) == TG_E_CHAIN, "truncated dispatch log refused");
+    CHECK(count_refusals(d, "E_CHAIN") == 2, "E_CHAIN recorded");
+
+    /* bad updater arguments */
+    newdir(d, sizeof d, "neg-args");
+    make_store(d, N_SMALL, 0);
+    tg_open(d, &st, NULL);
+    tg_shadow_begin(st, &a);
+    CHECK(tg_sgd_step(st, &a, g, N_SMALL, LR, MOM, 1) == TG_E_ARG, "momentum without optimizer state refused");
+    CHECK(tg_sgd_step(st, &a, g, N_SMALL - 1, LR, 0, 1) == TG_E_ARG, "size mismatch refused");
+    CHECK(tg_sgd_step(st, &a, g, N_SMALL, NAN, 0, 1) == TG_E_ARG, "NaN lr refused");
+    tg_shadow_discard(&a);
+    CHECK(tg_commit(st, &a, NULL, NULL) == TG_E_STATE, "discarded shadow refused");
+    tg_close(st);
+    free(g);
+}
+
+/* ---- 6. provenance cost ------------------------------------------------- */
+static void t_cost(void)
+{
+    size_t sizes[2] = {1024, 262144};
+    double per[2];
+    for (int k = 0; k < 2; k++) {
+        char d[1100];
+        newdir(d, sizeof d, "cost");
+        size_t n = sizes[k];
+        float *tt = malloc(n * 4); target(tt, n);
+        make_store(d, n, 1);
+        tg_store *st; tg_open(d, &st, NULL);
+        for (int i = 0; i < 3; i++) sgd_commit(st, tt, n, MOM, (uint64_t)i);
+        const tg_stats *s = tg_get_stats(st);
+        per[k] = (double)s->dispatch_hashed_bytes / (double)s->dispatch_records;
+        printf("cost n=%zu dispatch_records %llu dispatch_hashed_per_record %.0f commit_hashed_bytes %llu\n", n,
+               (unsigned long long)s->dispatch_records, per[k], (unsigned long long)s->commit_hashed_bytes);
+        CHECK(s->commit_hashed_bytes == 3 * (120 + 2 * n * 4), "tier b hashes the full state once per commit");
+        tg_close(st);
+        free(tt);
+    }
+    CHECK(per[0] == 192 && per[1] == 192, "tier a per-record hashing is constant (independent of model size)");
+}
+
+/* ---- 7. replay ---------------------------------------------------------- */
+static void run_seq(const char *d, const float *t, int steps, uint8_t out[TG_DIGEST], uint8_t head[TG_DIGEST])
+{
+    make_store(d, N_SMALL, 1);
+    tg_store *st;
+    if (tg_open(d, &st, NULL)) { memset(out, 0, TG_DIGEST); return; }
+    for (int k = 0; k < steps; k++) sgd_commit(st, t, N_SMALL, k < steps / 2 ? MOM : 0.5f, 1000 + (uint64_t)k);
+    memcpy(out, tg_committed(st)->digest, TG_DIGEST);
+    memcpy(head, tg_committed(st)->dispatch_head, TG_DIGEST);
+    tg_close(st);
+}
+
+static void t_replay(const float *t)
+{
+    char a[1100], b[1100], dk[1200], hx[65], hh[65];
+    uint8_t da[TG_DIGEST], db[TG_DIGEST], ha[TG_DIGEST], hb[TG_DIGEST];
+    const int STEPS = 25;
+    newdir(a, sizeof a, "replay-a");
+    newdir(b, sizeof b, "replay-b");
+    run_seq(a, t, STEPS, da, ha);
+    run_seq(b, t, STEPS, db, hb);
+    CHECK(!memcmp(da, db, TG_DIGEST) && !memcmp(ha, hb, TG_DIGEST),
+          "same sequence from G0 gives byte-identical G_n and dispatch chain");
+    tg_hex(da, hx); tg_hex(ha, hh);
+    printf("replay_digest %s\nreplay_dispatch_head %s\n", hx, hh);
+
+    /* Each committed step k re-derived from G_{k-1} (digest-verified, and equal
+     * to the base digest its dispatch record references) plus the recorded
+     * scalar arguments: the new parameters + optimizer state must be
+     * byte-identical to the committed G_k payload. */
+    int ok = 0;
+    snprintf(dk, sizeof dk, "%s-stepcheck", a);
+    for (uint64_t k = 1; k <= (uint64_t)STEPS; k++) {
+        tg_snapshot gp, gk;
+        tg_dispatch_rec rec;
+        if (tg_read_gen(a, k, NULL, &gk)) break;
+        int good = tg_read_gen(a, k - 1, gk.prev_digest, &gp) == TG_OK
+                && tg_dispatch_read(a, k - 1, &rec) == TG_OK
+                && rec.op_id == TG_OP_SGD && rec.step == k && rec.base_gen == k - 1
+                && rec.arg1 == 1000 + k - 1 && !memcmp(rec.base_digest, gp.digest, TG_DIGEST);
+        if (good) {
+            float lr, mom;
+            uint32_t u = (uint32_t)rec.arg0; memcpy(&lr, &u, 4);
+            u = (uint32_t)(rec.arg0 >> 32); memcpy(&mom, &u, 4);
+            rmtree(dk);
+            tg_store *st;
+            good = tg_create(dk, gp.params, gp.param_bytes, gp.opt, gp.opt_bytes) == TG_OK
+                && tg_open(dk, &st, NULL) == TG_OK;
+            if (good) {
+                tg_shadow sh;
+                float *g = malloc(N_SMALL * 4);
+                tg_shadow_begin(st, &sh);
+                grad_of((const float *)(const void *)gp.params, t, g, N_SMALL);
+                good = tg_sgd_step(st, &sh, g, N_SMALL, lr, mom, rec.arg1) == TG_OK
+                    && tg_commit(st, &sh, NULL, NULL) == TG_OK
+                    && tg_committed(st)->param_bytes == gk.param_bytes && tg_committed(st)->opt_bytes == gk.opt_bytes
+                    && !memcmp(tg_committed(st)->params, gk.params, gk.param_bytes)
+                    && !memcmp(tg_committed(st)->opt, gk.opt, gk.opt_bytes);
+                free(g);
+                tg_close(st);
+            }
+            tg_snapshot_free(&gp);
+        }
+        tg_snapshot_free(&gk);
+        if (good) ok++;
+    }
+    rmtree(dk);
+    printf("replay_steps_reverified %d/%d\n", ok, STEPS);
+    CHECK(ok == STEPS, "each committed step re-derived from its base generation + dispatch record (%d/%d)", ok, STEPS);
+}
+
+int main(int argc, char **argv)
+{
+    if (argc != 2) { fprintf(stderr, "usage: test_train <scratch-dir>\n"); return 2; }
+    snprintf(g_base, sizeof g_base, "%s", argv[1]);
+    rmtree(g_base);
+    if (mkdir(g_base, 0755) && errno != EEXIST) { perror("mkdir"); return 2; }
+    float *t = malloc(N_SMALL * 4);
+    target(t, N_SMALL);
+    t_basic(t);
+    t_training(t);
+    t_crash(t);
+    t_reader_race(t);
+    t_negatives(t);
+    t_cost();
+    t_replay(t);
+    free(t);
+    printf("checks %d failed %d\n", g_checks, g_fail);
+    if (g_fail) { printf("M22_SUBSTRATE_TESTS_FAIL\n"); return 1; }
+    rmtree(g_base);
+    printf("M22_SUBSTRATE_TESTS_PASS\n");
+    return 0;
+}
diff --git a/tests/train/train_receipt.sh b/tests/train/train_receipt.sh
new file mode 100755
index 000000000..31a413769
--- /dev/null
+++ b/tests/train/train_receipt.sh
@@ -0,0 +1,97 @@
+#!/bin/bash
+# train_receipt.sh -- receipt for the M22 optimizer substrate + E5 provenance
+# tests (mk/train.mk).
+#
+#   tests/train/train_receipt.sh [out-dir]     (default: evidence/M22/receipts)
+#
+# Refuses a dirty tree. Runs `make test-train` twice from a clean build dir;
+# both runs (plain + ASan/UBSan builds each) must print the same replay digest.
+# Writes a NEW file named by the SHA-256 of its own bytes; never rewrites one.
+# Verdict vocabulary: the SUBSTRATE tests PASS or FAIL; M22 itself is always
+# NOT QUALIFIED here (no tensor/autodiff integration; waits M20/M21).
+# Host-only, single core. Shell + coreutils only.
+set -u
+HERE=$(cd "$(dirname "$0")/../.." && pwd)
+cd "$HERE" || exit 2
+OUTDIR=${1:-evidence/M22/receipts}
+
+if [ -n "$(git status --porcelain)" ]; then
+    echo "train_receipt: refusing: working tree is dirty (commit first)" >&2
+    exit 3
+fi
+head0=$(git rev-parse HEAD)
+tree0=$(git rev-parse 'HEAD^{tree}')
+run_id=$(date -u +%Y%m%dT%H%M%SZ)
+W=$(mktemp -d)
+trap 'rm -rf "$W"' EXIT
+
+run() {   # $1 = label
+    rm -rf build/train
+    make --no-print-directory test-train > "$W/$1.log" 2>&1
+    local rc=$?
+    cp build/train/plain.log "$W/$1.plain.log" 2>/dev/null
+    echo $rc
+}
+rc1=$(run run1)
+rc2=$(run run2)
+dig() { awk -v k="$2" '$1 == k {print $2}' "$W/$1" | tail -n 1; }
+d1=$(dig run1.log replay_digest); d2=$(dig run2.log replay_digest)
+h1=$(dig run1.log replay_dispatch_head)
+pass1=$(grep -c '^M22_SUBSTRATE_TESTS_PASS$' "$W/run1.log"); pass2=$(grep -c '^M22_SUBSTRATE_TESTS_PASS$' "$W/run2.log")
+both=$(grep -c '^test-train: plain and ASan/UBSan PASS, replay digest equal across builds$' "$W/run1.log")
+checks=$(awk '$1 == "checks" {print $2; exit}' "$W/run1.log")
+reverified=$(dig run1.log replay_steps_reverified)
+race=$(grep '^reader_race ' "$W/run1.plain.log" | head -n 1)
+crash_old=$(grep -c '^crash .*recovered=OLD' "$W/run1.plain.log")
+crash_new=$(grep -c '^crash .*recovered=NEW' "$W/run1.plain.log")
+cost=$(grep '^cost ' "$W/run1.plain.log" | sed 's/"//g' | tr '\n' ';')
+head1=$(git rev-parse HEAD)
+dirty1=$(git status --porcelain | grep -v '^?? build/' || true)
+
+reasons=""
+[ "$rc1" = 0 ] && [ "$rc2" = 0 ] || reasons="$reasons make-failed($rc1,$rc2)"
+[ "$pass1" = 2 ] && [ "$pass2" = 2 ] || reasons="$reasons verdict-line-missing"
+[ "$both" = 1 ] || reasons="$reasons cross-build-replay-missing"
+[ -n "$d1" ] && [ "$d1" = "$d2" ] || reasons="$reasons replay-digest-differs"
+[ "$crash_old" = 9 ] && [ "$crash_new" = 2 ] || reasons="$reasons crash-matrix($crash_old,$crash_new)"
+[ "$head0" = "$head1" ] || reasons="$reasons head-moved"
+[ -z "$dirty1" ] || reasons="$reasons tree-dirty-after"
+verdict=PASS; [ -z "$reasons" ] || verdict=FAIL
+
+log_sha=$(cat "$W/run1.log" "$W/run2.log" | sha256sum | awk '{print $1}')
+src_sha=$(cat src/train/*.c src/train/*.h tests/train/test_train.c mk/train.mk | sha256sum | awk '{print $1}')
+mkdir -p "$OUTDIR"
+cat > "$W/receipt.json" <<JSON
+{
+  "schema": "omega.m22.train-substrate.receipt.v1",
+  "gate": "M22_SUBSTRATE",
+  "m22_status": "M22 NOT QUALIFIED: optimizer substrate + SGD path only; no tensor/autodiff integration (waits M20/M21)",
+  "substrate_tests_verdict": "$verdict",
+  "reasons": "$(echo $reasons)",
+  "scope": "host-only, single core; process-crash fault injection (fork + _exit at 8 points, plus torn-file simulation of not-yet-current files); NOT a power-loss test, NOT a GPU or hardware qualification; SGD with caller-supplied gradients (hand-written quadratic), Adam/AdamW deferred",
+  "commit": "$head0",
+  "tree": "$tree0",
+  "tree_clean": true,
+  "run_id": "$run_id",
+  "command": "make test-train (twice, clean build/train each time; each run = plain -O2 build + ASan/UBSan -O1 build)",
+  "checks_per_binary_run": "${checks:-null}",
+  "replay_digest_run1": "${d1:-null}",
+  "replay_digest_run2": "${d2:-null}",
+  "replay_dispatch_head": "${h1:-null}",
+  "replay_steps_reverified": "${reverified:-null}",
+  "crash_matrix": {"recovered_old": $crash_old, "recovered_new": $crash_new},
+  "reader_race": "$race",
+  "provenance_cost": "$cost",
+  "train_sources_sha256": "$src_sha",
+  "logs_sha256": "$log_sha",
+  "host": "$(uname -srm)"
+}
+JSON
+name=$(sha256sum "$W/receipt.json" | awk '{print $1}')
+if [ -e "$OUTDIR/$name.json" ]; then
+    echo "train_receipt: $OUTDIR/$name.json already exists; not rewritten" >&2
+    exit 0
+fi
+cp "$W/receipt.json" "$OUTDIR/$name.json"
+echo "train_receipt: $verdict -> $OUTDIR/$name.json"
+[ "$verdict" = PASS ]