@native-sdk/cli 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/build/app.zig +265 -65
  2. package/build/ts_run.mjs +6 -8
  3. package/build.zig +292 -349
  4. package/package.json +13 -11
  5. package/packages/core/compile-surface/core.ts +559 -0
  6. package/packages/core/package-lock.json +375 -12
  7. package/packages/core/package.json +9 -6
  8. package/packages/core/scripts/compiler_typecheck.mjs +58 -0
  9. package/packages/core/scripts/gen_case_tables.mjs +130 -0
  10. package/packages/core/scripts/gen_declarations.mjs +97 -0
  11. package/packages/core/scripts/run_external_core_compiler.mjs +108 -0
  12. package/packages/core/scripts/stage_external_core.mjs +148 -0
  13. package/packages/core/sdk/core.d.ts +363 -0
  14. package/packages/core/sdk/events.d.ts +65 -0
  15. package/packages/core/sdk/text.d.ts +51 -0
  16. package/packages/core/src/checker.ts +3 -3
  17. package/packages/core/src/cli.ts +40 -38
  18. package/packages/core/src/contract.ts +749 -0
  19. package/packages/core/src/devhost.ts +4 -3
  20. package/packages/core/src/diagnostics.ts +5 -7
  21. package/packages/core/src/{transpile.ts → frontend.ts} +38 -50
  22. package/packages/core/src/infer.ts +1 -1
  23. package/packages/core/src/typed_ast.ts +16 -15
  24. package/packages/core/src/wyhash.ts +79 -0
  25. package/skill-data/ts-core/SKILL.md +29 -29
  26. package/src/runtime/ts_core_host.zig +38 -38
  27. package/src/runtime/ts_ui_app.zig +12 -12
  28. package/src/tooling/manifest.zig +32 -0
  29. package/src/tooling/raw_manifest.zig +4 -0
  30. package/src/tooling/templates.zig +25 -20
  31. package/src/tooling/ts_core.zig +55 -34
  32. package/src/tooling/verbs.zig +1 -1
  33. package/tools/corewire/core_abi.zig +169 -0
  34. package/tools/corewire/emit.zig +2418 -0
  35. package/tools/corewire/emit_facade.zig +3984 -0
  36. package/tools/corewire/emit_profile.zig +501 -0
  37. package/tools/corewire/main.zig +561 -0
  38. package/tools/corewire/shim_rt.zig +632 -0
  39. package/tools/corewire/sidecar.zig +2507 -0
  40. package/packages/core/rt/rt.zig +0 -1986
  41. package/packages/core/src/emitter.ts +0 -11898
@@ -0,0 +1,632 @@
1
+ //! The shim-side runtime for a compiled core: the frame arena the
2
+ //! decoded mirror values live in, and the canonical value encoding the
3
+ //! ABI's buffers ride (snapshots, record dispatch payloads, helper
4
+ //! results, channel-entry messages).
5
+ //!
6
+ //! Staged beside the generated core_shim.zig by the build, like the
7
+ //! transpiler lane stages rt.zig beside its emitted core. The generated
8
+ //! shim's `rt` block forwards the three kernel entries the host layer
9
+ //! uses (frameAlloc/frameReset/resetAll) into this module's arena.
10
+ //!
11
+ //! The canonical value encoding, in full (one encoding for every
12
+ //! ABI-owned buffer; byte-oriented, little-endian, headerless, and
13
+ //! schema-driven — both ends derive the layout from the sidecar's type
14
+ //! table, so no field headers or tags ride the wire):
15
+ //!
16
+ //! f64 8 bytes, IEEE 754 double, LE. Every NaN
17
+ //! canonicalizes to the quiet pattern
18
+ //! (0x7ff8000000000000): payload bits are not
19
+ //! values in either source language, and engines
20
+ //! may rewrite them at any store, so an encoder
21
+ //! that preserved them could never be
22
+ //! deterministic across producers.
23
+ //! i64 8 bytes, two's complement, LE (never a bit
24
+ //! reinterpretation of the f64)
25
+ //! u64 8 bytes, unsigned, LE — the unsigned twin, for
26
+ //! slots whose integer_slots attestation refines
27
+ //! the i64 spelling to the u64 class
28
+ //! bool u8, 0 or 1
29
+ //! bytes u32 LE length + the bytes
30
+ //! enum u32 LE declaration-order member index
31
+ //! optional u8 presence (0 absent, 1 present) + the value
32
+ //! slice u32 LE count + the elements, in order
33
+ //! record fields concatenated in declaration order, no
34
+ //! headers; nested records inline. By-reference
35
+ //! fields (*const T in the mirror) encode inline
36
+ //! as their record value: pointer sharing is
37
+ //! storage, not semantics, and decode
38
+ //! materializes fresh values (value equality
39
+ //! preserved, aliasing not).
40
+ //! union u8 declaration-order arm index + the arm's
41
+ //! payload
42
+ //!
43
+ //! Buffers carry no alignment guarantee: every multi-byte read below is
44
+ //! an unaligned little-endian load.
45
+
46
+ const std = @import("std");
47
+
48
+ // ---------------------------------------------------------- the arena
49
+
50
+ var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
51
+
52
+ pub fn frameAllocator() std.mem.Allocator {
53
+ return arena_state.allocator();
54
+ }
55
+
56
+ pub fn frameAlloc(comptime T: type, n: usize) []T {
57
+ return arena_state.allocator().alloc(T, n) catch
58
+ @panic("the core shim's frame arena is out of memory — a decoded snapshot or helper result did not fit");
59
+ }
60
+
61
+ pub fn frameCreate(comptime T: type, value: T) *T {
62
+ const out = frameAlloc(T, 1);
63
+ out[0] = value;
64
+ return &out[0];
65
+ }
66
+
67
+ /// End-of-cycle reset: frees every decoded mirror, helper result, and
68
+ /// copied command buffer of the cycle. The generated shim's
69
+ /// `rt.frameReset` calls this and then the core's own frame_reset — the
70
+ /// two arenas reset together, exactly one cycle boundary.
71
+ pub fn frameReset() void {
72
+ _ = arena_state.reset(.retain_capacity);
73
+ }
74
+
75
+ /// Full reset (the deterministic re-init seam): every arena; the
76
+ /// core's own state resets through its init entry.
77
+ pub fn resetAll() void {
78
+ _ = arena_state.reset(.retain_capacity);
79
+ for (&model_arenas) |*arena| _ = arena.reset(.retain_capacity);
80
+ }
81
+
82
+ // The decoded committed model lives in its own storage: it must survive
83
+ // frame resets (views read it between cycles, exactly as they read the
84
+ // transpiler lane's committed heap). TWO arenas, flipped per decode, so
85
+ // the previously returned root also survives the decode that replaces
86
+ // it — the transpiler lane gives the same one-generation grace (an old
87
+ // root stays readable until the heap's next compaction), and the bridge
88
+ // leans on it when a boot path derives twice before adopting a root.
89
+ var model_arenas = [2]std.heap.ArenaAllocator{
90
+ std.heap.ArenaAllocator.init(std.heap.page_allocator),
91
+ std.heap.ArenaAllocator.init(std.heap.page_allocator),
92
+ };
93
+ var model_arena_index: u1 = 0;
94
+
95
+ /// Decode a committed-model snapshot into a fresh mirror root. The
96
+ /// PREVIOUS decode's root stays valid until the decode after this one;
97
+ /// anything older is gone (the host holds exactly one committed root at
98
+ /// a time, the shipped bridge contract).
99
+ pub fn decodeSnapshot(comptime T: type, bytes: []const u8) *const T {
100
+ model_arena_index +%= 1;
101
+ const arena = &model_arenas[model_arena_index];
102
+ _ = arena.reset(.retain_capacity);
103
+ const allocator = arena.allocator();
104
+ const out = allocator.create(T) catch @panic("the core shim's model arena is out of memory — the decoded snapshot did not fit");
105
+ out.* = decodeExact(T, bytes, allocator);
106
+ return out;
107
+ }
108
+
109
+ // ------------------------------------------------------------ encode
110
+
111
+ pub fn encodeAlloc(comptime T: type, value: T, allocator: std.mem.Allocator) []const u8 {
112
+ var out: std.ArrayListUnmanaged(u8) = .empty;
113
+ encodeInto(T, value, allocator, &out) catch
114
+ @panic("the core shim's frame arena is out of memory while encoding a dispatch payload");
115
+ return out.items;
116
+ }
117
+
118
+ fn encodeInto(comptime T: type, value: T, allocator: std.mem.Allocator, out: *std.ArrayListUnmanaged(u8)) error{OutOfMemory}!void {
119
+ switch (@typeInfo(T)) {
120
+ .bool => try out.append(allocator, @intFromBool(value)),
121
+ .int => {
122
+ comptime std.debug.assert(T == i64 or T == u64);
123
+ try appendInt(u64, @bitCast(value), allocator, out);
124
+ },
125
+ .float => {
126
+ comptime std.debug.assert(T == f64);
127
+ const bits: u64 = if (std.math.isNan(value)) 0x7ff8000000000000 else @bitCast(value);
128
+ try appendInt(u64, bits, allocator, out);
129
+ },
130
+ .@"enum" => |info| {
131
+ // Positional: the wire value is the declaration-order
132
+ // member INDEX, never the enum's numeric value (mirror
133
+ // enums make them equal; the codec must not rely on it).
134
+ const member_index: u32 = blk: {
135
+ inline for (info.fields, 0..) |field, field_index| {
136
+ if (value == @field(T, field.name)) break :blk @intCast(field_index);
137
+ }
138
+ unreachable;
139
+ };
140
+ try appendInt(u32, member_index, allocator, out);
141
+ },
142
+ .optional => |info| {
143
+ if (value) |inner| {
144
+ try out.append(allocator, 1);
145
+ try encodeInto(info.child, inner, allocator, out);
146
+ } else {
147
+ try out.append(allocator, 0);
148
+ }
149
+ },
150
+ .pointer => |info| switch (info.size) {
151
+ .slice => {
152
+ if (info.child == u8) {
153
+ try appendInt(u32, @intCast(value.len), allocator, out);
154
+ try out.appendSlice(allocator, value);
155
+ } else {
156
+ try appendInt(u32, @intCast(value.len), allocator, out);
157
+ for (value) |element| try encodeInto(info.child, element, allocator, out);
158
+ }
159
+ },
160
+ .one => try encodeInto(info.child, value.*, allocator, out),
161
+ else => @compileError("the canonical value encoding has no form for " ++ @typeName(T)),
162
+ },
163
+ .@"struct" => |info| {
164
+ inline for (info.fields) |field| {
165
+ try encodeInto(field.type, @field(value, field.name), allocator, out);
166
+ }
167
+ },
168
+ .@"union" => |info| {
169
+ comptime std.debug.assert(info.tag_type != null);
170
+ switch (value) {
171
+ inline else => |payload, tag| {
172
+ // Positional, like enums: the declaration-order arm
173
+ // index rides the wire, never the tag's numeric
174
+ // value.
175
+ const arm_index: u8 = comptime blk: {
176
+ for (info.fields, 0..) |field, field_index| {
177
+ if (std.mem.eql(u8, field.name, @tagName(tag))) break :blk @intCast(field_index);
178
+ }
179
+ unreachable;
180
+ };
181
+ try out.append(allocator, arm_index);
182
+ if (@TypeOf(payload) != void) {
183
+ try encodeInto(@TypeOf(payload), payload, allocator, out);
184
+ }
185
+ },
186
+ }
187
+ },
188
+ .void => {},
189
+ else => @compileError("the canonical value encoding has no form for " ++ @typeName(T)),
190
+ }
191
+ }
192
+
193
+ fn appendInt(comptime T: type, value: T, allocator: std.mem.Allocator, out: *std.ArrayListUnmanaged(u8)) error{OutOfMemory}!void {
194
+ var raw: [@sizeOf(T)]u8 = undefined;
195
+ std.mem.writeInt(T, &raw, value, .little);
196
+ try out.appendSlice(allocator, &raw);
197
+ }
198
+
199
+ // ------------------------------------------------------------ decode
200
+
201
+ pub const Reader = struct {
202
+ bytes: []const u8,
203
+ index: usize = 0,
204
+
205
+ fn take(self: *Reader, n: usize) []const u8 {
206
+ if (self.bytes.len - self.index < n) {
207
+ @panic("a core buffer ended mid-value — the compiled core and the generated shim disagree about a type's layout; rebuild the app so both come from one compile");
208
+ }
209
+ const out = self.bytes[self.index..][0..n];
210
+ self.index += n;
211
+ return out;
212
+ }
213
+
214
+ fn int(self: *Reader, comptime T: type) T {
215
+ return std.mem.readInt(T, self.take(@sizeOf(T))[0..@sizeOf(T)], .little);
216
+ }
217
+ };
218
+
219
+ /// Decode one value of mirror type `T`, materializing referenced
220
+ /// records and slices into `allocator` (the shim frame arena in the
221
+ /// dispatch path).
222
+ pub fn decode(comptime T: type, reader: *Reader, allocator: std.mem.Allocator) T {
223
+ switch (@typeInfo(T)) {
224
+ .bool => {
225
+ const raw = reader.take(1)[0];
226
+ if (raw > 1) {
227
+ @panic("a core buffer carries a boolean discriminant past 1 — the compiled core and the generated shim disagree about a type's layout; rebuild the app so both come from one compile");
228
+ }
229
+ return raw == 1;
230
+ },
231
+ .int => {
232
+ comptime std.debug.assert(T == i64 or T == u64);
233
+ // The wire type is 8 bytes: every bit pattern decodes (the
234
+ // compiler-provable crossing range is narrower, but the
235
+ // decoder is total over the encoding).
236
+ return @bitCast(reader.int(u64));
237
+ },
238
+ .float => {
239
+ comptime std.debug.assert(T == f64);
240
+ return @bitCast(reader.int(u64));
241
+ },
242
+ .@"enum" => |info| {
243
+ const member_index = reader.int(u32);
244
+ if (member_index >= info.fields.len) {
245
+ @panic("a core buffer carries an enum member index past the declared members — the compiled core and the generated shim disagree about the contract; rebuild the app");
246
+ }
247
+ // Positional: index into declaration order, never the
248
+ // enum's numeric value.
249
+ inline for (info.fields, 0..) |field, field_index| {
250
+ if (member_index == field_index) return @field(T, field.name);
251
+ }
252
+ unreachable;
253
+ },
254
+ .optional => |info| {
255
+ const present = reader.take(1)[0];
256
+ if (present == 0) return null;
257
+ if (present != 1) {
258
+ @panic("a core buffer carries a presence discriminant past 1 — the compiled core and the generated shim disagree about a type's layout; rebuild the app so both come from one compile");
259
+ }
260
+ return decode(info.child, reader, allocator);
261
+ },
262
+ .pointer => |info| switch (info.size) {
263
+ .slice => {
264
+ const count = reader.int(u32);
265
+ if (info.child == u8) {
266
+ const copied = allocator.alloc(u8, count) catch @panic("the core shim's frame arena is out of memory while decoding");
267
+ @memcpy(copied, reader.take(count));
268
+ return copied;
269
+ }
270
+ const out = allocator.alloc(info.child, count) catch @panic("the core shim's frame arena is out of memory while decoding");
271
+ for (out) |*element| element.* = decode(info.child, reader, allocator);
272
+ return out;
273
+ },
274
+ .one => {
275
+ const out = allocator.create(info.child) catch @panic("the core shim's frame arena is out of memory while decoding");
276
+ out.* = decode(info.child, reader, allocator);
277
+ return out;
278
+ },
279
+ else => @compileError("the canonical value encoding has no form for " ++ @typeName(T)),
280
+ },
281
+ .@"struct" => |info| {
282
+ var out: T = undefined;
283
+ inline for (info.fields) |field| {
284
+ @field(out, field.name) = decode(field.type, reader, allocator);
285
+ }
286
+ return out;
287
+ },
288
+ .@"union" => |info| {
289
+ comptime std.debug.assert(info.tag_type != null);
290
+ const arm = reader.take(1)[0];
291
+ inline for (info.fields, 0..) |field, index| {
292
+ if (arm == index) {
293
+ if (field.type == void) return @unionInit(T, field.name, {});
294
+ return @unionInit(T, field.name, decode(field.type, reader, allocator));
295
+ }
296
+ }
297
+ @panic("a core buffer carries a union arm index past the declared arms — the compiled core and the generated shim disagree about the contract; rebuild the app");
298
+ },
299
+ .void => return {},
300
+ else => @compileError("the canonical value encoding has no form for " ++ @typeName(T)),
301
+ }
302
+ }
303
+
304
+ /// Decode a whole buffer as one value; trailing bytes are the same
305
+ /// layout-skew teaching as a short read.
306
+ pub fn decodeExact(comptime T: type, bytes: []const u8, allocator: std.mem.Allocator) T {
307
+ var reader = Reader{ .bytes = bytes };
308
+ const out = decode(T, &reader, allocator);
309
+ if (reader.index != bytes.len) {
310
+ @panic("a core buffer carries bytes past the decoded value — the compiled core and the generated shim disagree about a type's layout; rebuild the app so both come from one compile");
311
+ }
312
+ return out;
313
+ }
314
+
315
+ // -------------------------------------------------------- boot fences
316
+
317
+ /// The boot-time pairing fence, run before the panic sink and init,
318
+ /// using only the pure identity getters: a sidecar and an object that
319
+ /// are not outputs of one compile must never reach the first dispatch.
320
+ pub fn verifyIdentity(
321
+ core_abi_version: u32,
322
+ core_build_id: u64,
323
+ sidecar_abi_version: u32,
324
+ sidecar_build_id: u64,
325
+ ) void {
326
+ if (core_abi_version != sidecar_abi_version) {
327
+ var message: [160]u8 = undefined;
328
+ @panic(std.fmt.bufPrint(&message, "this app's compiled core speaks ABI version {d} but its contract sidecar declares {d} — rebuild the app so both come from one compile", .{ core_abi_version, sidecar_abi_version }) catch "core/sidecar ABI version mismatch — rebuild the app");
329
+ }
330
+ if (core_build_id != sidecar_build_id) {
331
+ var message: [192]u8 = undefined;
332
+ @panic(std.fmt.bufPrint(&message, "this app's compiled core and its contract sidecar are from different builds (core {x:0>16}, sidecar {x:0>16}) — rebuild the app", .{ core_build_id, sidecar_build_id }) catch "core/sidecar build pairing mismatch — rebuild the app");
333
+ }
334
+ }
335
+
336
+ /// The registered trap sink: route the core's teaching message into the
337
+ /// process panic path (the same capture surface the wiring installs for
338
+ /// shim/SDK code). Must not return.
339
+ pub fn panicSink(ctx: ?*anyopaque, msg: [*]const u8, msg_len: usize, address: u64) callconv(.c) void {
340
+ _ = ctx;
341
+ _ = address;
342
+ @panic(msg[0..msg_len]);
343
+ }
344
+
345
+ /// The scalar dispatch entries carry numbers as f64; an integer-classed
346
+ /// value must cross exactly, and the f64 grid is only dense through
347
+ /// 2^53 - 1 — past it, distinct integers alias one wire value, so there
348
+ /// is no honest number to send. The shipped bridge refuses such values
349
+ /// before they ever reach a dispatch; the mirror holds the same line.
350
+ pub fn exactF64(value: i64) f64 {
351
+ const bound: i64 = 9007199254740992; // 2^53: the first alias point.
352
+ if (value >= bound or value <= -bound) {
353
+ @panic("an integer message payload is at or past 2^53 — the f64 wire aliases such values, so dispatching one would corrupt it silently; keep integer payloads within +-(2^53 - 1)");
354
+ }
355
+ return @floatFromInt(value);
356
+ }
357
+
358
+ /// The unsigned twin, for u64-attested slots: the same 2^53 exactness
359
+ /// line, one-sided.
360
+ pub fn exactF64Unsigned(value: u64) f64 {
361
+ const bound: u64 = 9007199254740992; // 2^53: the first alias point.
362
+ if (value >= bound) {
363
+ @panic("an integer message payload is at or past 2^53 — the f64 wire aliases such values, so dispatching one would corrupt it silently; keep integer payloads within +-(2^53 - 1)");
364
+ }
365
+ return @floatFromInt(value);
366
+ }
367
+
368
+ /// A bare (void) message arm carries zero payload bytes by the
369
+ /// canonical encoding; anything else is layout skew, refused like every
370
+ /// other malformed core buffer.
371
+ pub fn assertVoidPayload(payload: []const u8) void {
372
+ if (payload.len != 0) {
373
+ @panic("a channel message carries payload bytes on a bare arm — the compiled core and the generated shim disagree about the contract; rebuild the app so both come from one compile");
374
+ }
375
+ }
376
+
377
+ /// The defined pre-call state for a channel entry's out-pointer pair:
378
+ /// the generated wrappers point at this byte with length zero before
379
+ /// calling, so an entry that returns without writing — a contract
380
+ /// violation — can never hand back a slice of undefined memory.
381
+ /// channelEnvelopeBytes reads the pair back.
382
+ pub const channel_out_guard = [1]u8{0};
383
+
384
+ /// Assemble a channel entry's returned envelope from the out pair,
385
+ /// closing every non-writing shape BEFORE a slice forms: an entry that
386
+ /// wrote neither slot yields the guard at length zero (refused
387
+ /// downstream as a short envelope), and an entry that wrote a length
388
+ /// without a pointer — the guard address with a nonzero length —
389
+ /// panics here with a teaching, never an out-of-bounds read of the
390
+ /// guard.
391
+ pub fn channelEnvelopeBytes(ptr: [*]const u8, len: usize) []const u8 {
392
+ if (len != 0 and ptr == @as([*]const u8, @ptrCast(&channel_out_guard))) {
393
+ @panic("a channel entry wrote an envelope length without an envelope pointer — the compiled core and the generated shim disagree about the channel contract; rebuild the app so both come from one compile");
394
+ }
395
+ return ptr[0..len];
396
+ }
397
+
398
+ /// A channel entry's split bytes envelope: whether a message was
399
+ /// produced, the produced arm's declaration-order wire tag, and the arm
400
+ /// payload bytes (canonical value encoding of the arm's mirror payload
401
+ /// type).
402
+ pub const ChannelEnvelope = struct {
403
+ produced: bool,
404
+ tag: u8,
405
+ payload: []const u8,
406
+ };
407
+
408
+ /// Split a channel entry's bytes envelope — [produced u8][tag u8]
409
+ /// [payload…]. A malformed envelope is a contract violation, never a
410
+ /// silent no-message, so every framing fault panics with a teaching:
411
+ /// fewer than the two header bytes, a produced byte past 1, or payload
412
+ /// bytes behind a nothing-produced header. (The tag byte is meaningless
413
+ /// when nothing was produced; a tag past the declared arms is the
414
+ /// generated unpacker's refusal — it owns the arm table.)
415
+ pub fn channelEnvelope(bytes: []const u8) ChannelEnvelope {
416
+ if (bytes.len < 2) {
417
+ @panic("a channel entry returned fewer than the envelope's two header bytes ([produced u8][tag u8]) — the compiled core and the generated shim disagree about the channel contract; rebuild the app so both come from one compile");
418
+ }
419
+ if (bytes[0] > 1) {
420
+ @panic("a channel envelope's produced byte is past 1 — the compiled core and the generated shim disagree about the channel contract; rebuild the app so both come from one compile");
421
+ }
422
+ if (bytes[0] == 0 and bytes.len != 2) {
423
+ @panic("a channel envelope carries payload bytes behind a nothing-produced header — the compiled core and the generated shim disagree about the channel contract; rebuild the app so both come from one compile");
424
+ }
425
+ return .{ .produced = bytes[0] == 1, .tag = bytes[1], .payload = bytes[2..] };
426
+ }
427
+
428
+ // --------------------------------------------------------------- tests
429
+
430
+ const testing = std.testing;
431
+
432
+ test "scalar encodings match the stated byte layout" {
433
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
434
+ defer arena.deinit();
435
+ const a = arena.allocator();
436
+
437
+ // Golden vectors pin the encoding itself, not just the round trip.
438
+ try testing.expectEqualSlices(u8, &.{1}, encodeAlloc(bool, true, a));
439
+ try testing.expectEqualSlices(u8, &.{ 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, encodeAlloc(i64, -2, a));
440
+ try testing.expectEqualSlices(u8, &.{ 0, 0, 0, 0, 0, 0, 0xf0, 0x3f }, encodeAlloc(f64, 1.0, a));
441
+ try testing.expectEqualSlices(u8, &.{ 3, 0, 0, 0, 'a', 'b', 'c' }, encodeAlloc([]const u8, "abc", a));
442
+ const Scheme = enum(u8) { light = 0, dark = 1 };
443
+ try testing.expectEqualSlices(u8, &.{ 1, 0, 0, 0 }, encodeAlloc(Scheme, .dark, a));
444
+ // Every NaN — negative, payload-bearing — encodes as the one quiet
445
+ // pattern; payload bits are not values.
446
+ const canonical_nan = [_]u8{ 0, 0, 0, 0, 0, 0, 0xf8, 0x7f };
447
+ try testing.expectEqualSlices(u8, &canonical_nan, encodeAlloc(f64, std.math.nan(f64), a));
448
+ try testing.expectEqualSlices(u8, &canonical_nan, encodeAlloc(f64, -std.math.nan(f64), a));
449
+ const payload_nan: f64 = @bitCast(@as(u64, 0x7ff800000000beef));
450
+ try testing.expectEqualSlices(u8, &canonical_nan, encodeAlloc(f64, payload_nan, a));
451
+ try testing.expectEqualSlices(u8, &.{0}, encodeAlloc(?i64, null, a));
452
+ try testing.expectEqualSlices(u8, &.{ 1, 5, 0, 0, 0, 0, 0, 0, 0 }, encodeAlloc(?i64, 5, a));
453
+ }
454
+
455
+ test "records, slices, references, and unions round-trip" {
456
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
457
+ defer arena.deinit();
458
+ const a = arena.allocator();
459
+
460
+ const Role = enum(u8) { user = 0, assistant = 1 };
461
+ const Turn = struct { id: i64, role: Role, text: []const u8 };
462
+ const Event = union(enum) {
463
+ insert_text: []const u8,
464
+ clear,
465
+ move: struct { direction: i64, extend: bool },
466
+ };
467
+ const Model = struct {
468
+ turns: []const *const Turn,
469
+ cursor: ?i64,
470
+ last: Event,
471
+ score: f64,
472
+ };
473
+
474
+ const turn_a = Turn{ .id = 1, .role = .user, .text = "hi" };
475
+ const turn_b = Turn{ .id = 2, .role = .assistant, .text = "hello" };
476
+ const original = Model{
477
+ .turns = &.{ &turn_a, &turn_b },
478
+ .cursor = 7,
479
+ .last = .{ .move = .{ .direction = -1, .extend = true } },
480
+ .score = 0.5,
481
+ };
482
+
483
+ const encoded = encodeAlloc(Model, original, a);
484
+ const decoded = decodeExact(Model, encoded, a);
485
+
486
+ try testing.expectEqual(@as(usize, 2), decoded.turns.len);
487
+ // Decode materializes fresh records: value equality, not aliasing.
488
+ try testing.expect(decoded.turns[0] != &turn_a);
489
+ try testing.expectEqual(@as(i64, 1), decoded.turns[0].id);
490
+ try testing.expectEqual(Role.assistant, decoded.turns[1].role);
491
+ try testing.expectEqualStrings("hello", decoded.turns[1].text);
492
+ try testing.expectEqual(@as(?i64, 7), decoded.cursor);
493
+ try testing.expectEqual(@as(i64, -1), decoded.last.move.direction);
494
+ try testing.expect(decoded.last.move.extend);
495
+ try testing.expectEqual(@as(f64, 0.5), decoded.score);
496
+ }
497
+
498
+ test "exactF64 carries every in-range integer and matches the wire grid" {
499
+ try testing.expectEqual(@as(f64, 9007199254740991.0), exactF64(9007199254740991));
500
+ try testing.expectEqual(@as(f64, -9007199254740991.0), exactF64(-9007199254740991));
501
+ try testing.expectEqual(@as(f64, 0.0), exactF64(0));
502
+ try testing.expectEqual(@as(f64, 9007199254740991.0), exactF64Unsigned(9007199254740991));
503
+ try testing.expectEqual(@as(f64, 0.0), exactF64Unsigned(0));
504
+ }
505
+
506
+ test "integer slots encode as hand-computed 8-byte little-endian vectors" {
507
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
508
+ defer arena.deinit();
509
+ const a = arena.allocator();
510
+
511
+ // The compiler-provable extremes: +-(2^53 - 1) = 0x1fffffffffffff.
512
+ try testing.expectEqualSlices(u8, &.{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00 }, encodeAlloc(i64, 9007199254740991, a));
513
+ try testing.expectEqualSlices(u8, &.{ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff }, encodeAlloc(i64, -9007199254740991, a));
514
+ try testing.expectEqualSlices(u8, &.{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00 }, encodeAlloc(u64, 9007199254740991, a));
515
+
516
+ // Sign handling: two's complement for i64, plain magnitude for u64.
517
+ try testing.expectEqualSlices(u8, &.{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, encodeAlloc(i64, -1, a));
518
+ try testing.expectEqualSlices(u8, &.{ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, encodeAlloc(u64, 1, a));
519
+
520
+ // The wire type is 8 bytes: the full i64/u64 range encodes, past
521
+ // the f64-exact crossing bound.
522
+ try testing.expectEqualSlices(u8, &.{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80 }, encodeAlloc(i64, std.math.minInt(i64), a));
523
+ try testing.expectEqualSlices(u8, &.{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }, encodeAlloc(i64, std.math.maxInt(i64), a));
524
+ try testing.expectEqualSlices(u8, &.{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, encodeAlloc(u64, std.math.maxInt(u64), a));
525
+ }
526
+
527
+ test "the full 8-byte wire range decodes and round-trips for both integer classes" {
528
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
529
+ defer arena.deinit();
530
+ const a = arena.allocator();
531
+
532
+ // Every bit pattern is a value of the wire type: the same bytes
533
+ // read signed or unsigned per the attested class.
534
+ const all_ones = [_]u8{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
535
+ try testing.expectEqual(@as(i64, -1), decodeExact(i64, &all_ones, a));
536
+ try testing.expectEqual(@as(u64, 18446744073709551615), decodeExact(u64, &all_ones, a));
537
+ const high_bit = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80 };
538
+ try testing.expectEqual(@as(i64, std.math.minInt(i64)), decodeExact(i64, &high_bit, a));
539
+ try testing.expectEqual(@as(u64, 9223372036854775808), decodeExact(u64, &high_bit, a));
540
+
541
+ const i64_values = [_]i64{ 0, 1, -1, 9007199254740991, -9007199254740991, std.math.minInt(i64), std.math.maxInt(i64) };
542
+ for (i64_values) |value| {
543
+ try testing.expectEqual(value, decodeExact(i64, encodeAlloc(i64, value, a), a));
544
+ }
545
+ const u64_values = [_]u64{ 0, 1, 9007199254740991, 9007199254740992, 9223372036854775808, std.math.maxInt(u64) };
546
+ for (u64_values) |value| {
547
+ try testing.expectEqual(value, decodeExact(u64, encodeAlloc(u64, value, a), a));
548
+ }
549
+
550
+ // Wrapped shapes carry the class through: optionals and record
551
+ // fields decode per the slot's own integer class.
552
+ try testing.expectEqualSlices(u8, &.{ 1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, encodeAlloc(?u64, std.math.maxInt(u64), a));
553
+ try testing.expectEqual(@as(?u64, std.math.maxInt(u64)), decodeExact(?u64, &.{ 1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, a));
554
+ const Pair = struct { id: u64, delta: i64 };
555
+ const pair = Pair{ .id = 9007199254740991, .delta = -9007199254740991 };
556
+ const encoded = encodeAlloc(Pair, pair, a);
557
+ try testing.expectEqualSlices(u8, &.{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff }, encoded);
558
+ try testing.expectEqual(pair, decodeExact(Pair, encoded, a));
559
+ }
560
+
561
+ test "a decoded model root survives exactly one subsequent decode" {
562
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
563
+ defer arena.deinit();
564
+ const a = arena.allocator();
565
+ const Model = struct { label: []const u8, count: i64 };
566
+
567
+ const first_bytes = encodeAlloc(Model, .{ .label = "first", .count = 1 }, a);
568
+ const second_bytes = encodeAlloc(Model, .{ .label = "second", .count = 2 }, a);
569
+
570
+ const first = decodeSnapshot(Model, first_bytes);
571
+ const second = decodeSnapshot(Model, second_bytes);
572
+ // The boot path may derive a fresh root while a consumer still
573
+ // holds the previous one; both generations must read correctly.
574
+ try testing.expectEqualStrings("first", first.label);
575
+ try testing.expectEqual(@as(i64, 1), first.count);
576
+ try testing.expectEqualStrings("second", second.label);
577
+ try testing.expectEqual(@as(i64, 2), second.count);
578
+ resetAll();
579
+ }
580
+
581
+ test "discriminants ride declaration-order positions, not numeric values" {
582
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
583
+ defer arena.deinit();
584
+ const a = arena.allocator();
585
+ const Sparse = enum(u8) { low = 5, high = 9 };
586
+ try testing.expectEqualSlices(u8, &.{ 1, 0, 0, 0 }, encodeAlloc(Sparse, .high, a));
587
+ try testing.expectEqual(Sparse.high, decodeExact(Sparse, &.{ 1, 0, 0, 0 }, a));
588
+ const Tagged = union(enum(u8)) { first: i64 = 3, second = 7 };
589
+ try testing.expectEqualSlices(u8, &.{1}, encodeAlloc(Tagged, .second, a));
590
+ try testing.expect(decodeExact(Tagged, &.{1}, a) == .second);
591
+ }
592
+
593
+ test "void union arms ride as the bare arm index" {
594
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
595
+ defer arena.deinit();
596
+ const a = arena.allocator();
597
+ const Event = union(enum) { insert_text: []const u8, clear };
598
+ try testing.expectEqualSlices(u8, &.{1}, encodeAlloc(Event, .clear, a));
599
+ const decoded = decodeExact(Event, &.{1}, a);
600
+ try testing.expect(decoded == .clear);
601
+ // A bare arm's canonical payload is zero bytes exactly.
602
+ assertVoidPayload(&.{});
603
+ }
604
+
605
+ test "channel out pairs assemble through the guard-aware reader" {
606
+ // A written pair passes through untouched.
607
+ const written = [_]u8{ 1, 0 };
608
+ try testing.expectEqualSlices(u8, &written, channelEnvelopeBytes(&written, written.len));
609
+ // The untouched pre-call state (guard pointer, zero length) reads
610
+ // as the empty buffer — refused downstream as a short envelope,
611
+ // never an undefined slice.
612
+ const untouched = channelEnvelopeBytes(@ptrCast(&channel_out_guard), 0);
613
+ try testing.expectEqual(@as(usize, 0), untouched.len);
614
+ }
615
+
616
+ test "channel envelopes split into produced flag, tag, and payload" {
617
+ // Nothing produced: exactly the two header bytes, tag ignored.
618
+ const none = channelEnvelope(&.{ 0, 0 });
619
+ try testing.expect(!none.produced);
620
+ try testing.expectEqual(@as(usize, 0), none.payload.len);
621
+ // A produced bare arm: header only, empty payload.
622
+ const bare = channelEnvelope(&.{ 1, 3 });
623
+ try testing.expect(bare.produced);
624
+ try testing.expectEqual(@as(u8, 3), bare.tag);
625
+ try testing.expectEqual(@as(usize, 0), bare.payload.len);
626
+ // A produced payload arm: the tail is the arm's canonical payload
627
+ // bytes, untouched.
628
+ const produced = channelEnvelope(&.{ 1, 1, 2, 0, 0, 0, 0, 0, 0, 0 });
629
+ try testing.expect(produced.produced);
630
+ try testing.expectEqual(@as(u8, 1), produced.tag);
631
+ try testing.expectEqualSlices(u8, &.{ 2, 0, 0, 0, 0, 0, 0, 0 }, produced.payload);
632
+ }