@native-sdk/cli 0.7.1 → 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 (94) hide show
  1. package/build/app.zig +273 -65
  2. package/build/ts_run.mjs +6 -8
  3. package/build.zig +341 -361
  4. package/native-sdk.d.ts +6 -3
  5. package/package.json +13 -11
  6. package/packages/core/compile-surface/core.ts +559 -0
  7. package/packages/core/package-lock.json +375 -12
  8. package/packages/core/package.json +9 -6
  9. package/packages/core/scripts/compiler_typecheck.mjs +58 -0
  10. package/packages/core/scripts/gen_case_tables.mjs +130 -0
  11. package/packages/core/scripts/gen_declarations.mjs +97 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +108 -0
  13. package/packages/core/scripts/stage_external_core.mjs +148 -0
  14. package/packages/core/sdk/core.d.ts +363 -0
  15. package/packages/core/sdk/events.d.ts +65 -0
  16. package/packages/core/sdk/text.d.ts +51 -0
  17. package/packages/core/src/checker.ts +3 -3
  18. package/packages/core/src/cli.ts +40 -38
  19. package/packages/core/src/contract.ts +749 -0
  20. package/packages/core/src/devhost.ts +4 -3
  21. package/packages/core/src/diagnostics.ts +5 -7
  22. package/packages/core/src/{transpile.ts → frontend.ts} +38 -50
  23. package/packages/core/src/infer.ts +1 -1
  24. package/packages/core/src/typed_ast.ts +16 -15
  25. package/packages/core/src/wyhash.ts +79 -0
  26. package/skill-data/native-ui/SKILL.md +4 -2
  27. package/skill-data/ts-core/SKILL.md +29 -29
  28. package/src/platform/macos/appkit_host.m +51 -3
  29. package/src/platform/types.zig +4 -0
  30. package/src/platform/windows/gpu_surface_renderer.cpp +2280 -0
  31. package/src/platform/windows/gpu_surface_renderer.h +86 -0
  32. package/src/platform/windows/root.zig +298 -20
  33. package/src/platform/windows/webview2_host.cpp +343 -33
  34. package/src/primitives/canvas/code.zig +50 -0
  35. package/src/primitives/canvas/code_tests.zig +174 -1
  36. package/src/primitives/canvas/frame.zig +45 -1
  37. package/src/primitives/canvas/gpu.zig +6 -0
  38. package/src/primitives/canvas/render_tests.zig +93 -0
  39. package/src/primitives/canvas/root.zig +2 -0
  40. package/src/primitives/canvas/serialization.zig +150 -21
  41. package/src/primitives/canvas/themes/geist.zig +51 -5
  42. package/src/primitives/canvas/tokens.zig +33 -4
  43. package/src/primitives/canvas/ui.zig +52 -7
  44. package/src/primitives/canvas/ui_markup.zig +38 -1
  45. package/src/primitives/canvas/ui_markup_compiled.zig +28 -0
  46. package/src/primitives/canvas/ui_markup_contract.zig +9 -0
  47. package/src/primitives/canvas/ui_markup_view.zig +28 -0
  48. package/src/primitives/canvas/ui_markup_view_tests.zig +10 -2
  49. package/src/primitives/canvas/ui_schema.zig +5 -0
  50. package/src/primitives/canvas/ui_schema_tests.zig +4 -3
  51. package/src/primitives/canvas/ui_tests.zig +14 -0
  52. package/src/primitives/canvas/widget_builtin_tests.zig +513 -13
  53. package/src/primitives/canvas/widget_invalidation.zig +11 -1
  54. package/src/primitives/canvas/widget_layout.zig +260 -21
  55. package/src/primitives/canvas/widget_metrics.zig +45 -9
  56. package/src/primitives/canvas/widget_render.zig +220 -70
  57. package/src/primitives/canvas/widget_render_controls.zig +79 -21
  58. package/src/primitives/canvas/widget_render_style.zig +52 -8
  59. package/src/primitives/canvas/widget_text_input.zig +2 -0
  60. package/src/primitives/canvas/widgets.zig +53 -2
  61. package/src/runtime/canvas_frame.zig +60 -7
  62. package/src/runtime/canvas_frame_invalidation_tests.zig +80 -0
  63. package/src/runtime/canvas_frame_packet_tests.zig +83 -9
  64. package/src/runtime/canvas_frame_patch_tests.zig +16 -0
  65. package/src/runtime/canvas_images.zig +8 -2
  66. package/src/runtime/canvas_widget_clipboard_tests.zig +1 -1
  67. package/src/runtime/canvas_widget_runtime.zig +11 -8
  68. package/src/runtime/effects.zig +6 -0
  69. package/src/runtime/effects_tests.zig +30 -0
  70. package/src/runtime/gpu_surface_events.zig +38 -7
  71. package/src/runtime/media_surface_tests.zig +1 -1
  72. package/src/runtime/runtime_event_tests.zig +74 -0
  73. package/src/runtime/ts_core_host.zig +38 -38
  74. package/src/runtime/ts_ui_app.zig +12 -12
  75. package/src/runtime/ui_app.zig +10 -8
  76. package/src/runtime/ui_app_tests.zig +67 -0
  77. package/src/runtime/view.zig +6 -0
  78. package/src/runtime/view_canvas.zig +15 -0
  79. package/src/runtime/view_widget_text.zig +6 -4
  80. package/src/runtime/window_view_runtime.zig +1 -0
  81. package/src/tooling/manifest.zig +32 -0
  82. package/src/tooling/raw_manifest.zig +4 -0
  83. package/src/tooling/templates.zig +34 -26
  84. package/src/tooling/ts_core.zig +55 -34
  85. package/src/tooling/verbs.zig +1 -1
  86. package/tools/corewire/core_abi.zig +169 -0
  87. package/tools/corewire/emit.zig +2418 -0
  88. package/tools/corewire/emit_facade.zig +3984 -0
  89. package/tools/corewire/emit_profile.zig +501 -0
  90. package/tools/corewire/main.zig +561 -0
  91. package/tools/corewire/shim_rt.zig +632 -0
  92. package/tools/corewire/sidecar.zig +2507 -0
  93. package/packages/core/rt/rt.zig +0 -1986
  94. package/packages/core/src/emitter.ts +0 -11898
@@ -0,0 +1,2507 @@
1
+ //! The contract-sidecar reader: parse `core.contract.json` (schema
2
+ //! format 1) into a typed value and validate it against the schema's
3
+ //! rules (V1-V14, as far as a reader can check them without the compiled
4
+ //! object in hand).
5
+ //!
6
+ //! The sidecar is the machine-readable contract a core-mode compile
7
+ //! emits beside the compiled object: the exported state type, the
8
+ //! message union with declaration-order wire tags, helper signatures,
9
+ //! channel declarations, and build identity. Its only consumers are the
10
+ //! shim generator (emit.zig turns it into a Zig mirror module) and the
11
+ //! checker; both refuse a malformed or unknown-generation sidecar
12
+ //! outright at tool time, with a teaching that names the exact field
13
+ //! path — never a silent skew that surfaces as wrong dispatch at
14
+ //! runtime.
15
+ //!
16
+ //! Forward compatibility (reader side, normative):
17
+ //! - Unknown FIELDS anywhere are ignored with a one-line warning naming
18
+ //! the field, so additive emitter-side facts can ship before this
19
+ //! reader learns them.
20
+ //! - An unknown `format` is refused whole-file: no partial reads of an
21
+ //! unknown schema.
22
+ //! - An unknown enum VALUE inside a known field (a TypeRef kind, a
23
+ //! payload-descriptor kind, a number class) is refused whole-file:
24
+ //! half-understanding a message arm is how wrong dispatch ships.
25
+ //!
26
+ //! std-only: the generator is a build-time tool and the validation tests
27
+ //! run in the plain unit-test suite.
28
+
29
+ const std = @import("std");
30
+
31
+ /// The sidecar schema generation this reader implements.
32
+ pub const supported_format: i64 = 1;
33
+
34
+ /// The command-wire vocabulary generation the SDK's bridge speaks
35
+ /// (rt.zig `cmd_format_version`). A sidecar declaring a different
36
+ /// generation is refused at generate time.
37
+ pub const supported_wire_version: i64 = 3;
38
+
39
+ /// The C-ABI generation of the core entry points this generator binds
40
+ /// (core_abi.zig `abi_version`).
41
+ pub const supported_abi_version: i64 = 1;
42
+
43
+ /// The snapshot-encoding generation the generated decoder implements.
44
+ pub const supported_snapshot_format: i64 = 1;
45
+
46
+ // ------------------------------------------------------------- schema
47
+
48
+ pub const TypeRef = union(enum) {
49
+ bool,
50
+ f64,
51
+ i64,
52
+ bytes,
53
+ void,
54
+ optional: *const TypeRef,
55
+ slice: *const TypeRef,
56
+ /// A named record stored by reference (`*const T` in the mirror).
57
+ node: []const u8,
58
+ /// A named record stored by value, inline.
59
+ value: []const u8,
60
+ enum_ref: []const u8,
61
+ union_ref: []const u8,
62
+ };
63
+
64
+ pub const Field = struct {
65
+ name: []const u8,
66
+ type: TypeRef,
67
+ };
68
+
69
+ pub const Struct = struct {
70
+ name: []const u8,
71
+ /// The declaring module of the type, entry-relative (an additive
72
+ /// origin fact; null on sidecars that predate it and for
73
+ /// synthesized names, which are declared nowhere).
74
+ origin: ?[]const u8 = null,
75
+ /// Whether the declaring module exports this table designation under
76
+ /// its own name. Absent on older sidecars, where true preserves the
77
+ /// historical import/re-export behavior.
78
+ exported: bool = true,
79
+ fields: []const Field,
80
+ };
81
+
82
+ pub const Enum = struct {
83
+ name: []const u8,
84
+ origin: ?[]const u8 = null,
85
+ exported: bool = true,
86
+ members: []const []const u8,
87
+ };
88
+
89
+ pub const UnionArm = struct {
90
+ name: []const u8,
91
+ /// The authored member name of a single-payload arm (an additive
92
+ /// fact; the payload descriptor erases the author's spelling, and a
93
+ /// consumer constructing arm values needs it back). Null for bare
94
+ /// and multi-field arms, and on sidecars that predate the fact.
95
+ member: ?[]const u8 = null,
96
+ payload: TypeRef,
97
+ };
98
+
99
+ pub const Union = struct {
100
+ name: []const u8,
101
+ origin: ?[]const u8 = null,
102
+ exported: bool = true,
103
+ arms: []const UnionArm,
104
+ };
105
+
106
+ pub const Types = struct {
107
+ structs: []const Struct,
108
+ enums: []const Enum,
109
+ unions: []const Union,
110
+ };
111
+
112
+ pub const NumberClass = enum { f64, i64 };
113
+
114
+ /// The closed v1 payload-descriptor family for message arms.
115
+ pub const Payload = union(enum) {
116
+ void,
117
+ bytes,
118
+ number: NumberClass,
119
+ number_bytes: struct {
120
+ number_field: []const u8,
121
+ number_class: NumberClass,
122
+ bytes_field: []const u8,
123
+ },
124
+ record: []const u8,
125
+ union_ref: []const u8,
126
+ enum_ref: []const u8,
127
+ scalar: TypeRef,
128
+ };
129
+
130
+ pub const MsgArm = struct {
131
+ name: []const u8,
132
+ /// The authored member name of a single-payload arm (see
133
+ /// UnionArm.member).
134
+ member: ?[]const u8 = null,
135
+ payload: Payload,
136
+ };
137
+
138
+ pub const Msg = struct {
139
+ name: []const u8,
140
+ arms: []const MsgArm,
141
+ unbound: []const []const u8,
142
+ };
143
+
144
+ pub const Helper = struct {
145
+ name: []const u8,
146
+ params: []const TypeRef,
147
+ returns: TypeRef,
148
+ arena: bool,
149
+ };
150
+
151
+ pub const EnvMsg = struct {
152
+ env: []const u8,
153
+ msg: []const u8,
154
+ };
155
+
156
+ pub const Channels = struct {
157
+ command_msg: bool,
158
+ frame_msg: bool,
159
+ key_msg: bool,
160
+ pinch_msg: bool,
161
+ appearance_msg: ?[]const u8,
162
+ chrome_msg: ?[]const u8,
163
+ env_msgs: []const EnvMsg,
164
+ };
165
+
166
+ pub const Abi = struct {
167
+ prefix: []const u8,
168
+ exports: []const []const u8,
169
+ snapshot_format: i64,
170
+ };
171
+
172
+ /// The resolved integer class an `integer_slots` entry attests. The
173
+ /// type table's one integer spelling is `i64`; the attestation refines
174
+ /// it — `u64` marks the slot's wire bytes as the unsigned twin (8-byte
175
+ /// unsigned LE instead of two's complement). `f64` never appears here:
176
+ /// it is the default class and is never attested.
177
+ pub const IntegerClass = enum { i64, u64 };
178
+
179
+ pub const IntegerSlot = struct {
180
+ slot: []const u8,
181
+ class: IntegerClass,
182
+ };
183
+
184
+ pub const Sidecar = struct {
185
+ format: i64,
186
+ wire_version: i64,
187
+ abi_version: i64,
188
+ compiler_version: []const u8,
189
+ entry: []const u8,
190
+ source_hash: u64,
191
+ build_id: u64,
192
+ types: Types,
193
+ model: []const u8,
194
+ model_helpers: []const Helper,
195
+ model_unbound: []const []const u8,
196
+ msg: Msg,
197
+ init_returns_cmd: bool,
198
+ update_returns_cmd: bool,
199
+ /// Whether initialModel/update may ALSO return the bare model (the
200
+ /// documented mixed idiom, `Model | [Model, Cmd<Msg>]`). Additive,
201
+ /// frontend-emitted facts: absent (an older document, or a
202
+ /// compiler's co-emitted sidecar) means the pair shape is
203
+ /// unconditional. The facade emitter keys its wrapper on them.
204
+ init_returns_bare: bool = false,
205
+ update_returns_bare: bool = false,
206
+ has_subscriptions: bool,
207
+ channels: Channels,
208
+ abi: Abi,
209
+ integer_slots: []const IntegerSlot,
210
+ deterministic: bool,
211
+ async_free: bool,
212
+ };
213
+
214
+ // ----------------------------------------------------- ABI vocabulary
215
+
216
+ /// The unconditional export suffixes of ABI version 1, in the NORMATIVE
217
+ /// canonical order the sidecar's `abi.exports` must list them: the two
218
+ /// identity getters, then the mode-provided entries (sink registration,
219
+ /// init, collect, result reset), then the program's entry-point map
220
+ /// (core_abi.zig binds the matching extern signatures). The four
221
+ /// conditional channel-entry suffixes follow, present exactly when the
222
+ /// matching channel is wired.
223
+ pub const unconditional_exports = [_][]const u8{
224
+ "abi_version",
225
+ "build_id",
226
+ "set_panic_sink",
227
+ "init",
228
+ "collect",
229
+ "frame_reset",
230
+ "boot_cmd",
231
+ "dispatch_void",
232
+ "dispatch_bytes",
233
+ "dispatch_number",
234
+ "dispatch_number_bytes",
235
+ "dispatch_bool",
236
+ "dispatch_enum",
237
+ "dispatch_record",
238
+ "dispatch_text_input",
239
+ "dispatch_scroll_state",
240
+ "subscriptions",
241
+ "model_snapshot",
242
+ "helper_call",
243
+ };
244
+
245
+ pub const conditional_exports = [_][]const u8{
246
+ "command_msg",
247
+ "frame_msg",
248
+ "key_msg",
249
+ "pinch_msg",
250
+ };
251
+
252
+ // ------------------------------------------------------------ reading
253
+
254
+ pub const max_sidecar_bytes: usize = 16 * 1024 * 1024;
255
+
256
+ /// A refusal or warning, carried with the exact field path it names.
257
+ pub const Diagnostic = struct {
258
+ /// Dotted/indexed path into the document ("msg.arms[4].payload").
259
+ path: []const u8,
260
+ message: []const u8,
261
+ severity: enum { @"error", warning },
262
+ };
263
+
264
+ pub const Diagnostics = struct {
265
+ arena: std.mem.Allocator,
266
+ list: std.ArrayListUnmanaged(Diagnostic) = .empty,
267
+
268
+ pub fn fail(self: *Diagnostics, path: []const u8, comptime fmt: []const u8, args: anytype) error{Refused} {
269
+ self.push(.@"error", path, fmt, args);
270
+ return error.Refused;
271
+ }
272
+
273
+ /// Record a refusal without unwinding, so validation can surface
274
+ /// every finding of a pass instead of only the first.
275
+ pub fn flag(self: *Diagnostics, path: []const u8, comptime fmt: []const u8, args: anytype) void {
276
+ self.push(.@"error", path, fmt, args);
277
+ }
278
+
279
+ pub fn warn(self: *Diagnostics, path: []const u8, comptime fmt: []const u8, args: anytype) void {
280
+ self.push(.warning, path, fmt, args);
281
+ }
282
+
283
+ fn push(self: *Diagnostics, severity: @FieldType(Diagnostic, "severity"), path: []const u8, comptime fmt: []const u8, args: anytype) void {
284
+ // A diagnostic that cannot be recorded must never vanish — a
285
+ // dropped refusal would let a malformed sidecar read as clean.
286
+ // The tool runs on an arena; exhaustion here is terminal.
287
+ const oom = "corewire: out of memory while recording a diagnostic";
288
+ const message = std.fmt.allocPrint(self.arena, fmt, args) catch @panic(oom);
289
+ const owned_path = self.arena.dupe(u8, path) catch @panic(oom);
290
+ self.list.append(self.arena, .{ .path = owned_path, .message = message, .severity = severity }) catch @panic(oom);
291
+ }
292
+
293
+ pub fn hasErrors(self: *const Diagnostics) bool {
294
+ for (self.list.items) |item| {
295
+ if (item.severity == .@"error") return true;
296
+ }
297
+ return false;
298
+ }
299
+
300
+ pub fn write(self: *const Diagnostics, file_label: []const u8, writer: *std.Io.Writer) !void {
301
+ for (self.list.items) |item| {
302
+ const tag = switch (item.severity) {
303
+ .@"error" => "error",
304
+ .warning => "warning",
305
+ };
306
+ if (item.path.len > 0) {
307
+ try writer.print("{s}: {s}: {s}: {s}\n", .{ file_label, tag, item.path, item.message });
308
+ } else {
309
+ try writer.print("{s}: {s}: {s}\n", .{ file_label, tag, item.message });
310
+ }
311
+ }
312
+ }
313
+ };
314
+
315
+ /// Parse and validate a sidecar document. On `error.Refused` the
316
+ /// diagnostics carry every teaching; the caller prints them and stops.
317
+ /// All returned memory lives in the caller's arena.
318
+ pub fn read(arena: std.mem.Allocator, source: []const u8, diags: *Diagnostics) error{ Refused, OutOfMemory }!Sidecar {
319
+ const root = std.json.parseFromSliceLeaky(std.json.Value, arena, source, .{}) catch |err| switch (err) {
320
+ // Memory pressure is not malformed input; keep the contract's
321
+ // error meanings honest.
322
+ error.OutOfMemory => return error.OutOfMemory,
323
+ else => return diags.fail("", "the sidecar is not valid JSON — it should be the core.contract.json a core-mode compile writes beside the compiled object", .{}),
324
+ };
325
+ var mapper = Mapper{ .arena = arena, .diags = diags };
326
+ const sidecar = try mapper.mapRoot(root);
327
+ try validate(arena, sidecar, diags);
328
+ if (diags.hasErrors()) return error.Refused;
329
+ return sidecar;
330
+ }
331
+
332
+ // ------------------------------------------------- JSON -> schema map
333
+
334
+ const Mapper = struct {
335
+ arena: std.mem.Allocator,
336
+ diags: *Diagnostics,
337
+
338
+ fn path(self: *Mapper, comptime fmt: []const u8, args: anytype) []const u8 {
339
+ return std.fmt.allocPrint(self.arena, fmt, args) catch "";
340
+ }
341
+
342
+ fn object(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!std.json.ObjectMap {
343
+ return switch (value) {
344
+ .object => |o| o,
345
+ else => self.diags.fail(at, "expected an object, found {s}", .{jsonKindName(value)}),
346
+ };
347
+ }
348
+
349
+ fn array(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!std.json.Array {
350
+ return switch (value) {
351
+ .array => |a| a,
352
+ else => self.diags.fail(at, "expected an array, found {s}", .{jsonKindName(value)}),
353
+ };
354
+ }
355
+
356
+ fn string(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }![]const u8 {
357
+ return switch (value) {
358
+ .string => |s| s,
359
+ else => self.diags.fail(at, "expected a string, found {s}", .{jsonKindName(value)}),
360
+ };
361
+ }
362
+
363
+ /// The ABI prefix rides straight into exported symbol spellings
364
+ /// (`@extern` names, linker entries), so it must be a symbol-safe
365
+ /// spelling: ASCII letters, digits, and underscores, not starting
366
+ /// with a digit. Anything else (an embedded NUL, unicode, spaces)
367
+ /// cannot be represented faithfully as an object-file symbol name.
368
+ fn symbolPrefix(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }![]const u8 {
369
+ const text = try self.nonEmptyString(value, at);
370
+ for (text, 0..) |byte, index| {
371
+ const ok = byte == '_' or std.ascii.isAlphabetic(byte) or (index > 0 and std.ascii.isDigit(byte));
372
+ if (!ok) {
373
+ return self.diags.fail(at, "byte 0x{x:0>2} at offset {d} cannot appear in a linker symbol name — the prefix is spelled verbatim into every exported symbol; use ASCII letters, digits, and underscores, not starting with a digit", .{ byte, index });
374
+ }
375
+ }
376
+ return text;
377
+ }
378
+
379
+ fn nonEmptyString(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }![]const u8 {
380
+ const text = try self.string(value, at);
381
+ if (text.len == 0) return self.diags.fail(at, "expected a non-empty string", .{});
382
+ return text;
383
+ }
384
+
385
+ fn boolean(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!bool {
386
+ return switch (value) {
387
+ .bool => |flag| flag,
388
+ else => self.diags.fail(at, "expected true or false, found {s}", .{jsonKindName(value)}),
389
+ };
390
+ }
391
+
392
+ fn integer(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!i64 {
393
+ return switch (value) {
394
+ .integer => |int| int,
395
+ else => self.diags.fail(at, "expected an integer, found {s}", .{jsonKindName(value)}),
396
+ };
397
+ }
398
+
399
+ /// 64-bit hashes ride as strings of exactly 16 lowercase hex digits
400
+ /// (JSON interchange cannot carry a u64 exactly) — V2.
401
+ fn hash64(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!u64 {
402
+ const text = switch (value) {
403
+ .string => |s| s,
404
+ .integer, .float => return self.diags.fail(at, "64-bit hashes are encoded as strings of exactly 16 lowercase hex digits, never JSON numbers (JSON cannot carry a u64 exactly)", .{}),
405
+ else => return self.diags.fail(at, "expected a 16-lowercase-hex-digit string, found {s}", .{jsonKindName(value)}),
406
+ };
407
+ if (text.len != 16) {
408
+ return self.diags.fail(at, "expected exactly 16 lowercase hex digits, found {d} characters (\"{s}\")", .{ text.len, text });
409
+ }
410
+ for (text) |char| {
411
+ const ok = (char >= '0' and char <= '9') or (char >= 'a' and char <= 'f');
412
+ if (!ok) return self.diags.fail(at, "expected lowercase hex digits only, found '{c}' in \"{s}\"", .{ char, text });
413
+ }
414
+ return std.fmt.parseInt(u64, text, 16) catch unreachable;
415
+ }
416
+
417
+ /// An OPTIONAL nonempty-string member: null when absent (additive
418
+ /// facts older emitters do not write), refused when present but not
419
+ /// a nonempty string.
420
+ fn optionalString(self: *Mapper, map: std.json.ObjectMap, name: []const u8, at: []const u8) error{ Refused, OutOfMemory }!?[]const u8 {
421
+ const value = map.get(name) orelse return null;
422
+ return try self.nonEmptyString(value, self.path("{s}.{s}", .{ at, name }));
423
+ }
424
+
425
+ /// An additive boolean member with its compatibility default.
426
+ fn optionalBoolean(self: *Mapper, map: std.json.ObjectMap, name: []const u8, at: []const u8, default: bool) error{ Refused, OutOfMemory }!bool {
427
+ const value = map.get(name) orelse return default;
428
+ return try self.boolean(value, self.path("{s}.{s}", .{ at, name }));
429
+ }
430
+
431
+ fn stringList(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }![]const []const u8 {
432
+ const items = try self.array(value, at);
433
+ const out = try self.arena.alloc([]const u8, items.items.len);
434
+ for (items.items, 0..) |item, index| {
435
+ out[index] = try self.nonEmptyString(item, self.path("{s}[{d}]", .{ at, index }));
436
+ }
437
+ return out;
438
+ }
439
+
440
+ /// Fetch a required member; warn about (and skip) unknown members —
441
+ /// the additive forward-compat rule.
442
+ const Members = struct {
443
+ mapper: *Mapper,
444
+ map: std.json.ObjectMap,
445
+ at: []const u8,
446
+ known: []const []const u8,
447
+
448
+ fn get(self: *const Members, name: []const u8) error{ Refused, OutOfMemory }!std.json.Value {
449
+ return self.map.get(name) orelse self.mapper.diags.fail(
450
+ self.mapper.path("{s}{s}{s}", .{ self.at, if (self.at.len > 0) "." else "", name }),
451
+ "required field missing",
452
+ .{},
453
+ );
454
+ }
455
+
456
+ fn warnUnknown(self: *const Members) void {
457
+ var it = self.map.iterator();
458
+ outer: while (it.next()) |entry| {
459
+ for (self.known) |name| {
460
+ if (std.mem.eql(u8, entry.key_ptr.*, name)) continue :outer;
461
+ }
462
+ self.mapper.diags.warn(
463
+ self.mapper.path("{s}{s}{s}", .{ self.at, if (self.at.len > 0) "." else "", entry.key_ptr.* }),
464
+ "unknown field ignored (an emitter newer than this reader may emit additive facts)",
465
+ .{},
466
+ );
467
+ }
468
+ }
469
+ };
470
+
471
+ fn members(self: *Mapper, value: std.json.Value, at: []const u8, known: []const []const u8) error{ Refused, OutOfMemory }!Members {
472
+ return .{ .mapper = self, .map = try self.object(value, at), .at = at, .known = known };
473
+ }
474
+
475
+ fn mapRoot(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }!Sidecar {
476
+ const top = try self.members(value, "", &.{
477
+ "format", "wire_version", "abi_version", "compiler_version", "entry",
478
+ "source_hash", "build_id", "types", "model", "model_helpers",
479
+ "model_unbound", "msg", "init_returns_cmd", "update_returns_cmd", "init_returns_bare",
480
+ "update_returns_bare", "has_subscriptions", "channels", "abi", "integer_slots",
481
+ "deterministic", "async_free",
482
+ });
483
+ top.warnUnknown();
484
+
485
+ // The format fence comes first: nothing else in an unknown
486
+ // generation may be half-read.
487
+ const format = try self.integer(try top.get("format"), "format");
488
+ if (format != supported_format) {
489
+ return self.diags.fail("format", "this reader implements sidecar format {d}, found {d} — upgrade the SDK tooling or pin the compiler release that matches it", .{ supported_format, format });
490
+ }
491
+
492
+ return .{
493
+ .format = format,
494
+ .wire_version = try self.integer(try top.get("wire_version"), "wire_version"),
495
+ .abi_version = try self.integer(try top.get("abi_version"), "abi_version"),
496
+ .compiler_version = try self.nonEmptyString(try top.get("compiler_version"), "compiler_version"),
497
+ .entry = try self.nonEmptyString(try top.get("entry"), "entry"),
498
+ .source_hash = try self.hash64(try top.get("source_hash"), "source_hash"),
499
+ .build_id = try self.hash64(try top.get("build_id"), "build_id"),
500
+ .types = try self.mapTypes(try top.get("types")),
501
+ .model = try self.nonEmptyString(try top.get("model"), "model"),
502
+ .model_helpers = try self.mapHelpers(try top.get("model_helpers")),
503
+ .model_unbound = try self.stringList(try top.get("model_unbound"), "model_unbound"),
504
+ .msg = try self.mapMsg(try top.get("msg")),
505
+ .init_returns_cmd = try self.boolean(try top.get("init_returns_cmd"), "init_returns_cmd"),
506
+ .update_returns_cmd = try self.boolean(try top.get("update_returns_cmd"), "update_returns_cmd"),
507
+ .init_returns_bare = try self.optionalBoolean(top.map, "init_returns_bare", "", false),
508
+ .update_returns_bare = try self.optionalBoolean(top.map, "update_returns_bare", "", false),
509
+ .has_subscriptions = try self.boolean(try top.get("has_subscriptions"), "has_subscriptions"),
510
+ .channels = try self.mapChannels(try top.get("channels")),
511
+ .abi = try self.mapAbi(try top.get("abi")),
512
+ .integer_slots = try self.mapIntegerSlots(try top.get("integer_slots")),
513
+ .deterministic = try self.boolean(try top.get("deterministic"), "deterministic"),
514
+ .async_free = try self.boolean(try top.get("async_free"), "async_free"),
515
+ };
516
+ }
517
+
518
+ fn mapTypes(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }!Types {
519
+ const table = try self.members(value, "types", &.{ "structs", "enums", "unions" });
520
+ table.warnUnknown();
521
+ return .{
522
+ .structs = try self.mapStructs(try table.get("structs")),
523
+ .enums = try self.mapEnums(try table.get("enums")),
524
+ .unions = try self.mapUnions(try table.get("unions")),
525
+ };
526
+ }
527
+
528
+ fn mapStructs(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }![]const Struct {
529
+ const items = try self.array(value, "types.structs");
530
+ const out = try self.arena.alloc(Struct, items.items.len);
531
+ for (items.items, 0..) |item, index| {
532
+ const at = self.path("types.structs[{d}]", .{index});
533
+ // "synthesized" is an additive marker some emitters place on
534
+ // records they named themselves. The current projection uses
535
+ // `origin` as the authoritative authored-vs-synthesized fact and
536
+ // retains the name-pattern fallback for old null-origin sidecars,
537
+ // so this older marker remains accepted and unused.
538
+ const entry = try self.members(item, at, &.{ "name", "origin", "exported", "synthesized", "fields" });
539
+ entry.warnUnknown();
540
+ const fields_value = try self.array(try entry.get("fields"), self.path("{s}.fields", .{at}));
541
+ const fields = try self.arena.alloc(Field, fields_value.items.len);
542
+ for (fields_value.items, 0..) |field_value, field_index| {
543
+ const field_at = self.path("{s}.fields[{d}]", .{ at, field_index });
544
+ const field = try self.members(field_value, field_at, &.{ "name", "type" });
545
+ field.warnUnknown();
546
+ fields[field_index] = .{
547
+ .name = try self.nonEmptyString(try field.get("name"), self.path("{s}.name", .{field_at})),
548
+ .type = try self.mapTypeRef(try field.get("type"), self.path("{s}.type", .{field_at})),
549
+ };
550
+ }
551
+ out[index] = .{
552
+ .name = try self.nonEmptyString(try entry.get("name"), self.path("{s}.name", .{at})),
553
+ .origin = try self.optionalString(entry.map, "origin", at),
554
+ .exported = try self.optionalBoolean(entry.map, "exported", at, true),
555
+ .fields = fields,
556
+ };
557
+ }
558
+ return out;
559
+ }
560
+
561
+ fn mapEnums(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }![]const Enum {
562
+ const items = try self.array(value, "types.enums");
563
+ const out = try self.arena.alloc(Enum, items.items.len);
564
+ for (items.items, 0..) |item, index| {
565
+ const at = self.path("types.enums[{d}]", .{index});
566
+ const entry = try self.members(item, at, &.{ "name", "origin", "exported", "members" });
567
+ entry.warnUnknown();
568
+ out[index] = .{
569
+ .name = try self.nonEmptyString(try entry.get("name"), self.path("{s}.name", .{at})),
570
+ .origin = try self.optionalString(entry.map, "origin", at),
571
+ .exported = try self.optionalBoolean(entry.map, "exported", at, true),
572
+ .members = try self.stringList(try entry.get("members"), self.path("{s}.members", .{at})),
573
+ };
574
+ }
575
+ return out;
576
+ }
577
+
578
+ fn mapUnions(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }![]const Union {
579
+ const items = try self.array(value, "types.unions");
580
+ const out = try self.arena.alloc(Union, items.items.len);
581
+ for (items.items, 0..) |item, index| {
582
+ const at = self.path("types.unions[{d}]", .{index});
583
+ const entry = try self.members(item, at, &.{ "name", "origin", "exported", "arms" });
584
+ entry.warnUnknown();
585
+ const arms_value = try self.array(try entry.get("arms"), self.path("{s}.arms", .{at}));
586
+ const arms = try self.arena.alloc(UnionArm, arms_value.items.len);
587
+ for (arms_value.items, 0..) |arm_value, arm_index| {
588
+ const arm_at = self.path("{s}.arms[{d}]", .{ at, arm_index });
589
+ const arm = try self.members(arm_value, arm_at, &.{ "name", "member", "payload" });
590
+ arm.warnUnknown();
591
+ arms[arm_index] = .{
592
+ .name = try self.nonEmptyString(try arm.get("name"), self.path("{s}.name", .{arm_at})),
593
+ .member = try self.optionalString(arm.map, "member", arm_at),
594
+ .payload = try self.mapTypeRef(try arm.get("payload"), self.path("{s}.payload", .{arm_at})),
595
+ };
596
+ }
597
+ out[index] = .{
598
+ .name = try self.nonEmptyString(try entry.get("name"), self.path("{s}.name", .{at})),
599
+ .origin = try self.optionalString(entry.map, "origin", at),
600
+ .exported = try self.optionalBoolean(entry.map, "exported", at, true),
601
+ .arms = arms,
602
+ };
603
+ }
604
+ return out;
605
+ }
606
+
607
+ fn mapTypeRef(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!TypeRef {
608
+ return self.mapTypeRefDepth(value, at, 0);
609
+ }
610
+
611
+ /// Structural nesting rides the recursion, so it is bounded: no
612
+ /// real contract wraps a slot 256 levels deep, and past the bound a
613
+ /// document is refused instead of exhausting the stack.
614
+ const max_typeref_nesting = 256;
615
+
616
+ fn mapTypeRefDepth(self: *Mapper, value: std.json.Value, at: []const u8, depth: usize) error{ Refused, OutOfMemory }!TypeRef {
617
+ if (depth > max_typeref_nesting) {
618
+ return self.diags.fail(at, "TypeRef nesting exceeds {d} levels — no real contract wraps a slot this deep; flatten the state in the core source", .{max_typeref_nesting});
619
+ }
620
+ const map = try self.object(value, at);
621
+ const kind_value = map.get("kind") orelse return self.diags.fail(self.path("{s}.kind", .{at}), "required field missing (every TypeRef carries a kind discriminator)", .{});
622
+ const kind = try self.string(kind_value, self.path("{s}.kind", .{at}));
623
+
624
+ if (std.mem.eql(u8, kind, "bool")) {
625
+ (try self.members(value, at, &.{"kind"})).warnUnknown();
626
+ return .bool;
627
+ }
628
+ if (std.mem.eql(u8, kind, "f64")) {
629
+ (try self.members(value, at, &.{"kind"})).warnUnknown();
630
+ return .f64;
631
+ }
632
+ if (std.mem.eql(u8, kind, "i64")) {
633
+ (try self.members(value, at, &.{"kind"})).warnUnknown();
634
+ return .i64;
635
+ }
636
+ if (std.mem.eql(u8, kind, "bytes")) {
637
+ (try self.members(value, at, &.{"kind"})).warnUnknown();
638
+ return .bytes;
639
+ }
640
+ if (std.mem.eql(u8, kind, "void")) {
641
+ (try self.members(value, at, &.{"kind"})).warnUnknown();
642
+ return .void;
643
+ }
644
+ if (std.mem.eql(u8, kind, "optional")) {
645
+ const entry = try self.members(value, at, &.{ "kind", "inner" });
646
+ entry.warnUnknown();
647
+ const inner = try self.arena.create(TypeRef);
648
+ inner.* = try self.mapTypeRefDepth(try entry.get("inner"), self.path("{s}.inner", .{at}), depth + 1);
649
+ return .{ .optional = inner };
650
+ }
651
+ if (std.mem.eql(u8, kind, "slice")) {
652
+ const entry = try self.members(value, at, &.{ "kind", "elem" });
653
+ entry.warnUnknown();
654
+ const elem = try self.arena.create(TypeRef);
655
+ elem.* = try self.mapTypeRefDepth(try entry.get("elem"), self.path("{s}.elem", .{at}), depth + 1);
656
+ return .{ .slice = elem };
657
+ }
658
+ if (std.mem.eql(u8, kind, "node") or std.mem.eql(u8, kind, "value") or
659
+ std.mem.eql(u8, kind, "enum") or std.mem.eql(u8, kind, "union"))
660
+ {
661
+ const entry = try self.members(value, at, &.{ "kind", "name" });
662
+ entry.warnUnknown();
663
+ const name = try self.nonEmptyString(try entry.get("name"), self.path("{s}.name", .{at}));
664
+ if (std.mem.eql(u8, kind, "node")) return .{ .node = name };
665
+ if (std.mem.eql(u8, kind, "value")) return .{ .value = name };
666
+ if (std.mem.eql(u8, kind, "enum")) return .{ .enum_ref = name };
667
+ return .{ .union_ref = name };
668
+ }
669
+ return self.diags.fail(self.path("{s}.kind", .{at}), "unknown TypeRef kind \"{s}\" — this reader is too old for this sidecar; upgrade the SDK tooling or pin the compiler release it was built for", .{kind});
670
+ }
671
+
672
+ fn mapNumberClass(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!NumberClass {
673
+ const text = try self.string(value, at);
674
+ if (std.mem.eql(u8, text, "f64")) return .f64;
675
+ if (std.mem.eql(u8, text, "i64")) return .i64;
676
+ return self.diags.fail(at, "unknown number class \"{s}\" — the v1 classes are \"f64\" and \"i64\"; this reader is too old for anything else", .{text});
677
+ }
678
+
679
+ /// The integer_slots class vocabulary is its own closed set:
680
+ /// payload descriptors spell "f64"/"i64" (V7), attestations spell
681
+ /// "i64"/"u64" — the unsigned class exists only as a per-slot
682
+ /// verdict, never as a TypeRef or descriptor spelling.
683
+ fn mapIntegerClass(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!IntegerClass {
684
+ const text = try self.string(value, at);
685
+ if (std.mem.eql(u8, text, "i64")) return .i64;
686
+ if (std.mem.eql(u8, text, "u64")) return .u64;
687
+ if (std.mem.eql(u8, text, "f64")) {
688
+ return self.diags.fail(at, "integer_slots records the compiler's integer-class verdicts; class \"f64\" has no place here (f64 is the default class and is never attested)", .{});
689
+ }
690
+ return self.diags.fail(at, "unknown integer class \"{s}\" — the format-1 classes are \"i64\" and \"u64\"; this reader is too old for anything else", .{text});
691
+ }
692
+
693
+ fn mapHelpers(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }![]const Helper {
694
+ const items = try self.array(value, "model_helpers");
695
+ const out = try self.arena.alloc(Helper, items.items.len);
696
+ for (items.items, 0..) |item, index| {
697
+ const at = self.path("model_helpers[{d}]", .{index});
698
+ const entry = try self.members(item, at, &.{ "name", "params", "returns", "arena" });
699
+ entry.warnUnknown();
700
+ const params_value = try self.array(try entry.get("params"), self.path("{s}.params", .{at}));
701
+ const params = try self.arena.alloc(TypeRef, params_value.items.len);
702
+ for (params_value.items, 0..) |param, param_index| {
703
+ params[param_index] = try self.mapTypeRef(param, self.path("{s}.params[{d}]", .{ at, param_index }));
704
+ }
705
+ out[index] = .{
706
+ .name = try self.nonEmptyString(try entry.get("name"), self.path("{s}.name", .{at})),
707
+ .params = params,
708
+ .returns = try self.mapTypeRef(try entry.get("returns"), self.path("{s}.returns", .{at})),
709
+ .arena = try self.boolean(try entry.get("arena"), self.path("{s}.arena", .{at})),
710
+ };
711
+ }
712
+ return out;
713
+ }
714
+
715
+ fn mapMsg(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }!Msg {
716
+ const entry = try self.members(value, "msg", &.{ "name", "arms", "unbound" });
717
+ entry.warnUnknown();
718
+ const arms_value = try self.array(try entry.get("arms"), "msg.arms");
719
+ const arms = try self.arena.alloc(MsgArm, arms_value.items.len);
720
+ for (arms_value.items, 0..) |arm_value, index| {
721
+ const at = self.path("msg.arms[{d}]", .{index});
722
+ const arm = try self.members(arm_value, at, &.{ "name", "member", "payload" });
723
+ arm.warnUnknown();
724
+ arms[index] = .{
725
+ .name = try self.nonEmptyString(try arm.get("name"), self.path("{s}.name", .{at})),
726
+ .member = try self.optionalString(arm.map, "member", at),
727
+ .payload = try self.mapPayload(try arm.get("payload"), self.path("{s}.payload", .{at})),
728
+ };
729
+ }
730
+ return .{
731
+ .name = try self.nonEmptyString(try entry.get("name"), "msg.name"),
732
+ .arms = arms,
733
+ .unbound = try self.stringList(try entry.get("unbound"), "msg.unbound"),
734
+ };
735
+ }
736
+
737
+ fn mapPayload(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!Payload {
738
+ const map = try self.object(value, at);
739
+ const kind_value = map.get("kind") orelse return self.diags.fail(self.path("{s}.kind", .{at}), "required field missing (every payload descriptor carries a kind discriminator)", .{});
740
+ const kind = try self.string(kind_value, self.path("{s}.kind", .{at}));
741
+
742
+ if (std.mem.eql(u8, kind, "void")) {
743
+ (try self.members(value, at, &.{"kind"})).warnUnknown();
744
+ return .void;
745
+ }
746
+ if (std.mem.eql(u8, kind, "bytes")) {
747
+ (try self.members(value, at, &.{"kind"})).warnUnknown();
748
+ return .bytes;
749
+ }
750
+ if (std.mem.eql(u8, kind, "number")) {
751
+ const entry = try self.members(value, at, &.{ "kind", "class" });
752
+ entry.warnUnknown();
753
+ return .{ .number = try self.mapNumberClass(try entry.get("class"), self.path("{s}.class", .{at})) };
754
+ }
755
+ if (std.mem.eql(u8, kind, "number_bytes")) {
756
+ const entry = try self.members(value, at, &.{ "kind", "number_field", "number_class", "bytes_field" });
757
+ entry.warnUnknown();
758
+ return .{ .number_bytes = .{
759
+ .number_field = try self.nonEmptyString(try entry.get("number_field"), self.path("{s}.number_field", .{at})),
760
+ .number_class = try self.mapNumberClass(try entry.get("number_class"), self.path("{s}.number_class", .{at})),
761
+ .bytes_field = try self.nonEmptyString(try entry.get("bytes_field"), self.path("{s}.bytes_field", .{at})),
762
+ } };
763
+ }
764
+ if (std.mem.eql(u8, kind, "record") or std.mem.eql(u8, kind, "union") or std.mem.eql(u8, kind, "enum")) {
765
+ const entry = try self.members(value, at, &.{ "kind", "name" });
766
+ entry.warnUnknown();
767
+ const name = try self.nonEmptyString(try entry.get("name"), self.path("{s}.name", .{at}));
768
+ if (std.mem.eql(u8, kind, "record")) return .{ .record = name };
769
+ if (std.mem.eql(u8, kind, "union")) return .{ .union_ref = name };
770
+ return .{ .enum_ref = name };
771
+ }
772
+ if (std.mem.eql(u8, kind, "scalar")) {
773
+ const entry = try self.members(value, at, &.{ "kind", "type" });
774
+ entry.warnUnknown();
775
+ return .{ .scalar = try self.mapTypeRef(try entry.get("type"), self.path("{s}.type", .{at})) };
776
+ }
777
+ return self.diags.fail(self.path("{s}.kind", .{at}), "unknown payload descriptor kind \"{s}\" — this reader is too old for this sidecar; upgrade the SDK tooling or pin the compiler release it was built for (half-understanding a message arm is how wrong dispatch ships)", .{kind});
778
+ }
779
+
780
+ fn mapChannels(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }!Channels {
781
+ const entry = try self.members(value, "channels", &.{
782
+ "command_msg", "frame_msg", "key_msg", "pinch_msg", "appearance_msg", "chrome_msg", "env_msgs",
783
+ });
784
+ entry.warnUnknown();
785
+ const env_value = try self.array(try entry.get("env_msgs"), "channels.env_msgs");
786
+ const env_msgs = try self.arena.alloc(EnvMsg, env_value.items.len);
787
+ for (env_value.items, 0..) |item, index| {
788
+ const at = self.path("channels.env_msgs[{d}]", .{index});
789
+ const env_entry = try self.members(item, at, &.{ "env", "msg" });
790
+ env_entry.warnUnknown();
791
+ env_msgs[index] = .{
792
+ .env = try self.nonEmptyString(try env_entry.get("env"), self.path("{s}.env", .{at})),
793
+ .msg = try self.nonEmptyString(try env_entry.get("msg"), self.path("{s}.msg", .{at})),
794
+ };
795
+ }
796
+ return .{
797
+ .command_msg = try self.boolean(try entry.get("command_msg"), "channels.command_msg"),
798
+ .frame_msg = try self.boolean(try entry.get("frame_msg"), "channels.frame_msg"),
799
+ .key_msg = try self.boolean(try entry.get("key_msg"), "channels.key_msg"),
800
+ .pinch_msg = try self.boolean(try entry.get("pinch_msg"), "channels.pinch_msg"),
801
+ .appearance_msg = try self.armNameOrNull(try entry.get("appearance_msg"), "channels.appearance_msg"),
802
+ .chrome_msg = try self.armNameOrNull(try entry.get("chrome_msg"), "channels.chrome_msg"),
803
+ .env_msgs = env_msgs,
804
+ };
805
+ }
806
+
807
+ fn armNameOrNull(self: *Mapper, value: std.json.Value, at: []const u8) error{ Refused, OutOfMemory }!?[]const u8 {
808
+ return switch (value) {
809
+ .null => null,
810
+ .string => try self.nonEmptyString(value, at),
811
+ else => self.diags.fail(at, "expected null or a message arm name string, found {s}", .{jsonKindName(value)}),
812
+ };
813
+ }
814
+
815
+ fn mapAbi(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }!Abi {
816
+ const entry = try self.members(value, "abi", &.{ "prefix", "exports", "snapshot_format" });
817
+ entry.warnUnknown();
818
+ return .{
819
+ .prefix = try self.symbolPrefix(try entry.get("prefix"), "abi.prefix"),
820
+ .exports = try self.stringList(try entry.get("exports"), "abi.exports"),
821
+ .snapshot_format = try self.integer(try entry.get("snapshot_format"), "abi.snapshot_format"),
822
+ };
823
+ }
824
+
825
+ fn mapIntegerSlots(self: *Mapper, value: std.json.Value) error{ Refused, OutOfMemory }![]const IntegerSlot {
826
+ const items = try self.array(value, "integer_slots");
827
+ const out = try self.arena.alloc(IntegerSlot, items.items.len);
828
+ for (items.items, 0..) |item, index| {
829
+ const at = self.path("integer_slots[{d}]", .{index});
830
+ const entry = try self.members(item, at, &.{ "slot", "class" });
831
+ entry.warnUnknown();
832
+ out[index] = .{
833
+ .slot = try self.nonEmptyString(try entry.get("slot"), self.path("{s}.slot", .{at})),
834
+ .class = try self.mapIntegerClass(try entry.get("class"), self.path("{s}.class", .{at})),
835
+ };
836
+ }
837
+ return out;
838
+ }
839
+ };
840
+
841
+ fn jsonKindName(value: std.json.Value) []const u8 {
842
+ return switch (value) {
843
+ .null => "null",
844
+ .bool => "a boolean",
845
+ .integer => "a number",
846
+ .float => "a number",
847
+ .number_string => "a number",
848
+ .string => "a string",
849
+ .array => "an array",
850
+ .object => "an object",
851
+ };
852
+ }
853
+
854
+ // --------------------------------------------------------- validation
855
+ //
856
+ // The schema's emitter self-check rules, enforced reader-side as far as
857
+ // a reader can without the compiled object:
858
+ // V1 required fields + format fence — the mapper (presence) and
859
+ // mapRoot (format).
860
+ // V2 hash encodings — the mapper's hash64.
861
+ // V3 name uniqueness — validateNames.
862
+ // V4 reference resolution + no
863
+ // unreachable table entries — validateReferences.
864
+ // V5 acyclicity — validateAcyclic.
865
+ // V6 tag density and arm bound — validateMsg (density is
866
+ // structural: tags are positions; the reader checks the bound).
867
+ // Source declaration order itself is only checkable against the
868
+ // source, i.e. by the emitter.
869
+ // V7 descriptor consistency — the mapper (classes) and
870
+ // validateMsg (field names,
871
+ // scalar shape).
872
+ // V8 unbound lists resolve — validateUnbound.
873
+ // V9 channel wiring — validateChannels.
874
+ // V10 integer-slot bijection — validateIntegerSlots: the
875
+ // one-to-one check both ways, plus structural resolution of every
876
+ // leftover entry's path (unresolvable, wrong spelling, or the
877
+ // grammar's slice-element gap each carry their own teaching).
878
+ // V11 export attestation — validateAbi checks the list
879
+ // against the profile's canonical vocabulary and order; the
880
+ // "exactly what the object exports" half needs the object and is
881
+ // enforced at link/boot time by the generated shim.
882
+ // V12 identity coherence — a boot-time check: the
883
+ // generated shim compares the sidecar's build_id against the
884
+ // object's identity getter before the first dispatch.
885
+ // V13 deterministic emission — an emitter-side property;
886
+ // the generator itself re-emits byte-identically from equal
887
+ // input (pinned by a test).
888
+ // V14 attestation honesty — an emitter-side property a
889
+ // reader cannot re-derive (the proof lives in the compiler; the
890
+ // sidecar records verdicts).
891
+
892
+ fn validate(arena: std.mem.Allocator, sidecar: Sidecar, diags: *Diagnostics) error{OutOfMemory}!void {
893
+ validateVersions(sidecar, diags);
894
+ try validateNames(arena, sidecar, diags);
895
+ // Reference checks assume the namespace is coherent; a broken
896
+ // namespace already carries its own teachings.
897
+ if (diags.hasErrors()) return;
898
+ try validateReferences(arena, sidecar, diags);
899
+ if (diags.hasErrors()) return;
900
+ try validateAcyclic(arena, sidecar, diags);
901
+ validateMsg(sidecar, diags);
902
+ validateVoidPositions(sidecar, diags);
903
+ validateUnbound(sidecar, diags);
904
+ validateChannels(sidecar, diags);
905
+ validateAbi(sidecar, diags);
906
+ try validateIntegerSlots(arena, sidecar, diags);
907
+ }
908
+
909
+ fn validateVersions(sidecar: Sidecar, diags: *Diagnostics) void {
910
+ if (sidecar.wire_version != supported_wire_version) {
911
+ diags.flag("wire_version", "this SDK's command-wire vocabulary is generation {d}, the sidecar declares {d} — the compiled core's effect builders speak a different wire; upgrade the SDK or pin the compiler release that matches it", .{ supported_wire_version, sidecar.wire_version });
912
+ }
913
+ if (sidecar.abi_version != supported_abi_version) {
914
+ diags.flag("abi_version", "this generator binds core ABI version {d}, the sidecar declares {d} — upgrade the SDK or pin the compiler release that matches it", .{ supported_abi_version, sidecar.abi_version });
915
+ }
916
+ if (sidecar.abi.snapshot_format != supported_snapshot_format) {
917
+ diags.flag("abi.snapshot_format", "this generator decodes snapshot format {d}, the sidecar declares {d} — upgrade the SDK or pin the compiler release that matches it", .{ supported_snapshot_format, sidecar.abi.snapshot_format });
918
+ }
919
+ }
920
+
921
+ const NameSet = std.StringArrayHashMapUnmanaged(void);
922
+
923
+ fn noteName(arena: std.mem.Allocator, set: *NameSet, name: []const u8, at: []const u8, what: []const u8, diags: *Diagnostics) error{OutOfMemory}!void {
924
+ const entry = try set.getOrPut(arena, name);
925
+ if (entry.found_existing) {
926
+ diags.flag(at, "duplicate {s} \"{s}\" — V3 requires unique names here", .{ what, name });
927
+ }
928
+ }
929
+
930
+ fn validateNames(arena: std.mem.Allocator, sidecar: Sidecar, diags: *Diagnostics) error{OutOfMemory}!void {
931
+ // One namespace across structs + enums + unions.
932
+ var table_names: NameSet = .empty;
933
+ for (sidecar.types.structs, 0..) |entry, index| {
934
+ try noteName(arena, &table_names, entry.name, pathOf(arena, "types.structs[{d}].name", .{index}), "type-table name", diags);
935
+ var field_names: NameSet = .empty;
936
+ for (entry.fields, 0..) |field, field_index| {
937
+ try noteName(arena, &field_names, field.name, pathOf(arena, "types.structs[{d}].fields[{d}].name", .{ index, field_index }), "field name", diags);
938
+ }
939
+ }
940
+ for (sidecar.types.enums, 0..) |entry, index| {
941
+ try noteName(arena, &table_names, entry.name, pathOf(arena, "types.enums[{d}].name", .{index}), "type-table name", diags);
942
+ var member_names: NameSet = .empty;
943
+ for (entry.members, 0..) |member, member_index| {
944
+ try noteName(arena, &member_names, member, pathOf(arena, "types.enums[{d}].members[{d}]", .{ index, member_index }), "enum member", diags);
945
+ }
946
+ }
947
+ for (sidecar.types.unions, 0..) |entry, index| {
948
+ try noteName(arena, &table_names, entry.name, pathOf(arena, "types.unions[{d}].name", .{index}), "type-table name", diags);
949
+ var arm_names: NameSet = .empty;
950
+ for (entry.arms, 0..) |arm, arm_index| {
951
+ try noteName(arena, &arm_names, arm.name, pathOf(arena, "types.unions[{d}].arms[{d}].name", .{ index, arm_index }), "union arm", diags);
952
+ }
953
+ }
954
+ var msg_arm_names: NameSet = .empty;
955
+ for (sidecar.msg.arms, 0..) |arm, index| {
956
+ try noteName(arena, &msg_arm_names, arm.name, pathOf(arena, "msg.arms[{d}].name", .{index}), "message arm", diags);
957
+ }
958
+ var helper_names: NameSet = .empty;
959
+ for (sidecar.model_helpers, 0..) |helper, index| {
960
+ try noteName(arena, &helper_names, helper.name, pathOf(arena, "model_helpers[{d}].name", .{index}), "helper name", diags);
961
+ }
962
+ var env_names: NameSet = .empty;
963
+ for (sidecar.channels.env_msgs, 0..) |entry, index| {
964
+ try noteName(arena, &env_names, entry.env, pathOf(arena, "channels.env_msgs[{d}].env", .{index}), "environment variable name", diags);
965
+ }
966
+ }
967
+
968
+ fn pathOf(arena: std.mem.Allocator, comptime fmt: []const u8, args: anytype) []const u8 {
969
+ return std.fmt.allocPrint(arena, fmt, args) catch "";
970
+ }
971
+
972
+ pub const TableKind = enum { @"struct", @"enum", @"union" };
973
+
974
+ pub fn lookupKind(types: Types, name: []const u8) ?TableKind {
975
+ if (findStruct(types, name) != null) return .@"struct";
976
+ if (findEnum(types, name) != null) return .@"enum";
977
+ if (findUnion(types, name) != null) return .@"union";
978
+ return null;
979
+ }
980
+
981
+ pub fn findStruct(types: Types, name: []const u8) ?*const Struct {
982
+ for (types.structs) |*entry| {
983
+ if (std.mem.eql(u8, entry.name, name)) return entry;
984
+ }
985
+ return null;
986
+ }
987
+
988
+ pub fn findEnum(types: Types, name: []const u8) ?*const Enum {
989
+ for (types.enums) |*entry| {
990
+ if (std.mem.eql(u8, entry.name, name)) return entry;
991
+ }
992
+ return null;
993
+ }
994
+
995
+ pub fn findUnion(types: Types, name: []const u8) ?*const Union {
996
+ for (types.unions) |*entry| {
997
+ if (std.mem.eql(u8, entry.name, name)) return entry;
998
+ }
999
+ return null;
1000
+ }
1001
+
1002
+ const Reach = struct {
1003
+ arena: std.mem.Allocator,
1004
+ types: Types,
1005
+ diags: *Diagnostics,
1006
+ seen: NameSet = .empty,
1007
+ /// The active visit's worklist, when a walk is in progress; a
1008
+ /// checkRef outside a walk visits directly.
1009
+ pending: ?*std.ArrayListUnmanaged([]const u8) = null,
1010
+
1011
+ fn enqueue(self: *Reach, name: []const u8) error{OutOfMemory}!void {
1012
+ if (self.pending) |worklist| {
1013
+ try worklist.append(self.arena, name);
1014
+ return;
1015
+ }
1016
+ try self.visit(name);
1017
+ }
1018
+
1019
+ fn checkRef(self: *Reach, ref: TypeRef, at: []const u8) error{OutOfMemory}!void {
1020
+ switch (ref) {
1021
+ .bool, .f64, .i64, .bytes, .void => {},
1022
+ .optional => |inner| try self.checkRef(inner.*, at),
1023
+ .slice => |elem| try self.checkRef(elem.*, at),
1024
+ .node, .value => |name| {
1025
+ if (findStruct(self.types, name) == null) {
1026
+ self.wrongKind(name, .@"struct", at);
1027
+ return;
1028
+ }
1029
+ try self.enqueue(name);
1030
+ },
1031
+ .enum_ref => |name| {
1032
+ if (findEnum(self.types, name) == null) {
1033
+ self.wrongKind(name, .@"enum", at);
1034
+ return;
1035
+ }
1036
+ try self.enqueue(name);
1037
+ },
1038
+ .union_ref => |name| {
1039
+ if (findUnion(self.types, name) == null) {
1040
+ self.wrongKind(name, .@"union", at);
1041
+ return;
1042
+ }
1043
+ try self.enqueue(name);
1044
+ },
1045
+ }
1046
+ }
1047
+
1048
+ fn wrongKind(self: *Reach, name: []const u8, wanted: TableKind, at: []const u8) void {
1049
+ if (lookupKind(self.types, name)) |found| {
1050
+ self.diags.flag(at, "\"{s}\" names {s} {s} in the type table, but this reference requires {s} {s} — V4", .{
1051
+ name, articleOf(found), @tagName(found), articleOf(wanted), @tagName(wanted),
1052
+ });
1053
+ } else {
1054
+ self.diags.flag(at, "\"{s}\" names no entry in the type table (no struct, enum, or union declares it) — V4", .{name});
1055
+ }
1056
+ }
1057
+
1058
+ /// Iterative: named-type chains can be as long as the document
1059
+ /// allows, so the walk carries its own worklist instead of the
1060
+ /// process stack (structural nesting within one reference stays
1061
+ /// recursive under the reader's 256-level bound).
1062
+ fn visit(self: *Reach, root: []const u8) error{OutOfMemory}!void {
1063
+ var worklist: std.ArrayListUnmanaged([]const u8) = .empty;
1064
+ try worklist.append(self.arena, root);
1065
+ while (worklist.pop()) |name| {
1066
+ const entry = try self.seen.getOrPut(self.arena, name);
1067
+ if (entry.found_existing) continue;
1068
+ self.pending = &worklist;
1069
+ defer self.pending = null;
1070
+ if (findStruct(self.types, name)) |record| {
1071
+ for (record.fields, 0..) |field, index| {
1072
+ try self.checkRef(field.type, pathOf(self.arena, "types.structs.{s}.fields[{d}].type", .{ name, index }));
1073
+ }
1074
+ continue;
1075
+ }
1076
+ if (findUnion(self.types, name)) |tagged| {
1077
+ for (tagged.arms, 0..) |arm, index| {
1078
+ try self.checkRef(arm.payload, pathOf(self.arena, "types.unions.{s}.arms[{d}].payload", .{ name, index }));
1079
+ }
1080
+ continue;
1081
+ }
1082
+ // Enums carry no references.
1083
+ }
1084
+ }
1085
+ };
1086
+
1087
+ fn articleOf(kind: TableKind) []const u8 {
1088
+ return switch (kind) {
1089
+ .@"enum" => "an",
1090
+ .@"struct", .@"union" => "a",
1091
+ };
1092
+ }
1093
+
1094
+ fn validateReferences(arena: std.mem.Allocator, sidecar: Sidecar, diags: *Diagnostics) error{OutOfMemory}!void {
1095
+ var reach = Reach{ .arena = arena, .types = sidecar.types, .diags = diags };
1096
+
1097
+ // The roots: model, msg arms, helper signatures, channels (channel
1098
+ // arm names resolve against msg arms in validateChannels; they add
1099
+ // no type references of their own).
1100
+ if (findStruct(sidecar.types, sidecar.model) == null) {
1101
+ if (lookupKind(sidecar.types, sidecar.model)) |found| {
1102
+ diags.flag("model", "\"{s}\" names {s} {s} in the type table, but the model root must be a struct — V4", .{ sidecar.model, articleOf(found), @tagName(found) });
1103
+ } else {
1104
+ diags.flag("model", "\"{s}\" names no struct in the type table — V4", .{sidecar.model});
1105
+ }
1106
+ } else {
1107
+ try reach.visit(sidecar.model);
1108
+ }
1109
+
1110
+ for (sidecar.msg.arms, 0..) |arm, index| {
1111
+ switch (arm.payload) {
1112
+ .void, .bytes, .number, .number_bytes => {},
1113
+ .record => |name| {
1114
+ if (findStruct(sidecar.types, name) == null) {
1115
+ reach.wrongKind(name, .@"struct", pathOf(arena, "msg.arms[{d}].payload.name", .{index}));
1116
+ } else try reach.visit(name);
1117
+ },
1118
+ .union_ref => |name| {
1119
+ if (findUnion(sidecar.types, name) == null) {
1120
+ reach.wrongKind(name, .@"union", pathOf(arena, "msg.arms[{d}].payload.name", .{index}));
1121
+ } else try reach.visit(name);
1122
+ },
1123
+ .enum_ref => |name| {
1124
+ if (findEnum(sidecar.types, name) == null) {
1125
+ reach.wrongKind(name, .@"enum", pathOf(arena, "msg.arms[{d}].payload.name", .{index}));
1126
+ } else try reach.visit(name);
1127
+ },
1128
+ .scalar => |ref| try reach.checkRef(ref, pathOf(arena, "msg.arms[{d}].payload.type", .{index})),
1129
+ }
1130
+ }
1131
+
1132
+ for (sidecar.model_helpers, 0..) |helper, index| {
1133
+ try reach.checkRef(helper.returns, pathOf(arena, "model_helpers[{d}].returns", .{index}));
1134
+ for (helper.params, 0..) |param, param_index| {
1135
+ try reach.checkRef(param, pathOf(arena, "model_helpers[{d}].params[{d}]", .{ index, param_index }));
1136
+ }
1137
+ }
1138
+
1139
+ // The table lists exactly the reachable types — nothing else (V4's
1140
+ // unreachable-entry half).
1141
+ for (sidecar.types.structs, 0..) |entry, index| {
1142
+ if (!reach.seen.contains(entry.name)) {
1143
+ diags.flag(pathOf(arena, "types.structs[{d}]", .{index}), "\"{s}\" is unreachable from model, msg, model_helpers, and channels — the type table lists exactly the reachable types, nothing else (V4)", .{entry.name});
1144
+ }
1145
+ }
1146
+ for (sidecar.types.enums, 0..) |entry, index| {
1147
+ if (!reach.seen.contains(entry.name)) {
1148
+ diags.flag(pathOf(arena, "types.enums[{d}]", .{index}), "\"{s}\" is unreachable from model, msg, model_helpers, and channels — the type table lists exactly the reachable types, nothing else (V4)", .{entry.name});
1149
+ }
1150
+ }
1151
+ for (sidecar.types.unions, 0..) |entry, index| {
1152
+ if (!reach.seen.contains(entry.name)) {
1153
+ diags.flag(pathOf(arena, "types.unions[{d}]", .{index}), "\"{s}\" is unreachable from model, msg, model_helpers, and channels — the type table lists exactly the reachable types, nothing else (V4)", .{entry.name});
1154
+ }
1155
+ }
1156
+ }
1157
+
1158
+ fn validateAcyclic(arena: std.mem.Allocator, sidecar: Sidecar, diags: *Diagnostics) error{OutOfMemory}!void {
1159
+ // Iterative colored depth-first walk with an explicit frame stack:
1160
+ // any back edge is a cycle, and named-type chains deeper than the
1161
+ // reader's bound refuse instead of exhausting every downstream
1162
+ // consumer's call stack (recursive state types are refused at
1163
+ // compile time by the emitter; a sidecar carrying one is malformed,
1164
+ // and nothing real chains hundreds of record types).
1165
+ const max_chain_depth = 256;
1166
+ const State = enum { unvisited, on_stack, done };
1167
+ var states: std.StringArrayHashMapUnmanaged(State) = .empty;
1168
+ var depths: std.StringArrayHashMapUnmanaged(usize) = .empty;
1169
+
1170
+ const Frame = struct {
1171
+ name: []const u8,
1172
+ shape: EntryShape,
1173
+ next_edge: usize,
1174
+ };
1175
+
1176
+ var roots: std.ArrayListUnmanaged([]const u8) = .empty;
1177
+ for (sidecar.types.structs) |entry| try roots.append(arena, entry.name);
1178
+ for (sidecar.types.unions) |entry| try roots.append(arena, entry.name);
1179
+
1180
+ var depth_refused = false;
1181
+ for (roots.items) |root| {
1182
+ if ((states.get(root) orelse .unvisited) != .unvisited) continue;
1183
+ var stack: std.ArrayListUnmanaged(Frame) = .empty;
1184
+ try states.put(arena, root, .on_stack);
1185
+ try stack.append(arena, .{ .name = root, .shape = try entryShape(arena, sidecar.types, root), .next_edge = 0 });
1186
+ while (stack.items.len > 0) {
1187
+ const top = &stack.items[stack.items.len - 1];
1188
+ if (top.next_edge < top.shape.edges.len) {
1189
+ const child = top.shape.edges[top.next_edge].name;
1190
+ top.next_edge += 1;
1191
+ switch (states.get(child) orelse .unvisited) {
1192
+ .on_stack => {
1193
+ var cycle: std.ArrayListUnmanaged(u8) = .empty;
1194
+ var started = false;
1195
+ for (stack.items) |frame| {
1196
+ if (!started and !std.mem.eql(u8, frame.name, child)) continue;
1197
+ started = true;
1198
+ try cycle.appendSlice(arena, frame.name);
1199
+ try cycle.appendSlice(arena, " -> ");
1200
+ }
1201
+ try cycle.appendSlice(arena, child);
1202
+ diags.flag("types", "the type reference graph has a cycle ({s}) — recursive state types are refused at compile time and can never be encoded (V5)", .{cycle.items});
1203
+ return;
1204
+ },
1205
+ .done => {},
1206
+ .unvisited => {
1207
+ try states.put(arena, child, .on_stack);
1208
+ try stack.append(arena, .{ .name = child, .shape = try entryShape(arena, sidecar.types, child), .next_edge = 0 });
1209
+ },
1210
+ }
1211
+ continue;
1212
+ }
1213
+ // Post-order: the deepest fully expanded value tree under
1214
+ // this entry. Structural wrapping and named chains multiply
1215
+ // when counted separately, so the bound is on their sum —
1216
+ // the depth every downstream walk (encoders, emitters,
1217
+ // sample builders) actually recurses to.
1218
+ var deepest: usize = top.shape.leaf_levels;
1219
+ for (top.shape.edges) |edge| {
1220
+ deepest = @max(deepest, edge.wrap + (depths.get(edge.name) orelse 0));
1221
+ }
1222
+ const depth = deepest + 1;
1223
+ try depths.put(arena, top.name, depth);
1224
+ try states.put(arena, top.name, .done);
1225
+ if (depth > max_chain_depth and !depth_refused) {
1226
+ depth_refused = true;
1227
+ diags.flag("types", "the value tree under \"{s}\" expands deeper than {d} levels (record chains and optional/slice wrapping both count) — no real contract nests state this deep, and every consumer bounds its walks; flatten the state in the core source", .{ top.name, max_chain_depth });
1228
+ }
1229
+ _ = stack.pop();
1230
+ }
1231
+ }
1232
+ }
1233
+
1234
+ /// One named-type edge leaving a table entry: the referenced name and
1235
+ /// the structural levels (optional/slice) wrapped around the reference
1236
+ /// at its use site.
1237
+ const Edge = struct { name: []const u8, wrap: usize };
1238
+
1239
+ const EntryShape = struct {
1240
+ edges: []const Edge,
1241
+ /// The deepest purely structural member (no named reference): its
1242
+ /// wrapper count plus the leaf itself.
1243
+ leaf_levels: usize,
1244
+ };
1245
+
1246
+ /// The shape of one table entry's members for depth accounting
1247
+ /// (structural nesting within a reference is bounded by the reader, so
1248
+ /// the collection recursion is bounded too).
1249
+ fn entryShape(arena: std.mem.Allocator, types: Types, name: []const u8) error{OutOfMemory}!EntryShape {
1250
+ var edges: std.ArrayListUnmanaged(Edge) = .empty;
1251
+ var leaf_levels: usize = 0;
1252
+ if (findStruct(types, name)) |record| {
1253
+ for (record.fields) |field| try measureRef(arena, &edges, &leaf_levels, field.type, 0);
1254
+ } else if (findUnion(types, name)) |tagged| {
1255
+ for (tagged.arms) |arm| try measureRef(arena, &edges, &leaf_levels, arm.payload, 0);
1256
+ }
1257
+ return .{ .edges = edges.items, .leaf_levels = leaf_levels };
1258
+ }
1259
+
1260
+ fn measureRef(arena: std.mem.Allocator, edges: *std.ArrayListUnmanaged(Edge), leaf_levels: *usize, ref: TypeRef, wrap: usize) error{OutOfMemory}!void {
1261
+ switch (ref) {
1262
+ .bool, .f64, .i64, .bytes, .void, .enum_ref => leaf_levels.* = @max(leaf_levels.*, wrap + 1),
1263
+ .optional => |inner| try measureRef(arena, edges, leaf_levels, inner.*, wrap + 1),
1264
+ .slice => |elem| try measureRef(arena, edges, leaf_levels, elem.*, wrap + 1),
1265
+ .node, .value, .union_ref => |edge| try edges.append(arena, .{ .name = edge, .wrap = wrap }),
1266
+ }
1267
+ }
1268
+
1269
+ fn validateMsg(sidecar: Sidecar, diags: *Diagnostics) void {
1270
+ // Tags are positional and dense by construction — there is no
1271
+ // explicit tag field to get wrong. The reader checks the u8 bound,
1272
+ // and the floor: a valueless union or enum has no declarable mirror
1273
+ // form (`union(enum) {}` is not a type) and nothing could ever
1274
+ // dispatch or encode it.
1275
+ if (sidecar.msg.arms.len == 0) {
1276
+ diags.flag("msg.arms", "the message union declares no arms — a core with no messages cannot dispatch; declare at least one arm", .{});
1277
+ }
1278
+ if (sidecar.msg.arms.len > 256) {
1279
+ diags.flag("msg.arms", "{d} arms exceed the 256-arm bound (wire tags ride a u8) — V6", .{sidecar.msg.arms.len});
1280
+ }
1281
+ // The same u8 bound governs every tabled union (the canonical value
1282
+ // encoding carries a one-byte arm index), and the mirror's enums
1283
+ // ride enum(u8) with member index = wire value.
1284
+ for (sidecar.types.unions, 0..) |entry, index| {
1285
+ if (entry.arms.len == 0) {
1286
+ diags.flag(pathOfStatic(diags, "types.unions[{d}]", .{index}), "union \"{s}\" declares no arms — a valueless union has no mirror form; declare at least one arm", .{entry.name});
1287
+ }
1288
+ if (entry.arms.len > 256) {
1289
+ diags.flag(pathOfStatic(diags, "types.unions[{d}]", .{index}), "union \"{s}\" has {d} arms; encoded union values carry a one-byte declaration-order arm index (256 arms at most)", .{ entry.name, entry.arms.len });
1290
+ }
1291
+ }
1292
+ for (sidecar.types.enums, 0..) |entry, index| {
1293
+ if (entry.members.len == 0) {
1294
+ diags.flag(pathOfStatic(diags, "types.enums[{d}]", .{index}), "enum \"{s}\" declares no members — a valueless enum has no mirror form; declare at least one member", .{entry.name});
1295
+ }
1296
+ if (entry.members.len > 256) {
1297
+ diags.flag(pathOfStatic(diags, "types.enums[{d}]", .{index}), "enum \"{s}\" has {d} members; the mirror's enums ride a u8 tag with member index = wire value (256 members at most)", .{ entry.name, entry.members.len });
1298
+ }
1299
+ }
1300
+ for (sidecar.msg.arms, 0..) |arm, index| {
1301
+ switch (arm.payload) {
1302
+ .number_bytes => |desc| {
1303
+ if (std.mem.eql(u8, desc.number_field, desc.bytes_field)) {
1304
+ diags.flag(pathOfStatic(diags, "msg.arms[{d}].payload", .{index}), "number_field and bytes_field are both \"{s}\" — the two field names must be distinct (V7)", .{desc.number_field});
1305
+ }
1306
+ },
1307
+ .scalar => |ref| switch (ref) {
1308
+ .void => diags.flag(pathOfStatic(diags, "msg.arms[{d}].payload.type", .{index}), "a scalar descriptor cannot carry void — bare arms use the void descriptor kind (V7)", .{}),
1309
+ .node, .value => diags.flag(pathOfStatic(diags, "msg.arms[{d}].payload.type", .{index}), "a scalar descriptor cannot carry a record — record payloads use the record descriptor kind (V7)", .{}),
1310
+ else => {},
1311
+ },
1312
+ else => {},
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ fn pathOfStatic(diags: *Diagnostics, comptime fmt: []const u8, args: anytype) []const u8 {
1318
+ return std.fmt.allocPrint(diags.arena, fmt, args) catch "";
1319
+ }
1320
+
1321
+ /// The void TypeRef means "no value" and exists for bare union arms
1322
+ /// only (the schema's stated scope); anywhere else the mirror would
1323
+ /// declare a valueless slot the snapshot encoding cannot carry.
1324
+ fn validateVoidPositions(sidecar: Sidecar, diags: *Diagnostics) void {
1325
+ for (sidecar.types.structs, 0..) |entry, index| {
1326
+ for (entry.fields, 0..) |field, field_index| {
1327
+ flagVoid(field.type, pathOfStatic(diags, "types.structs[{d}].fields[{d}].type", .{ index, field_index }), diags);
1328
+ }
1329
+ }
1330
+ for (sidecar.types.unions, 0..) |entry, index| {
1331
+ for (entry.arms, 0..) |arm, arm_index| {
1332
+ // A bare void arm is the one sanctioned use; void NESTED
1333
+ // inside an arm's payload is not.
1334
+ if (arm.payload == .void) continue;
1335
+ flagVoid(arm.payload, pathOfStatic(diags, "types.unions[{d}].arms[{d}].payload", .{ index, arm_index }), diags);
1336
+ }
1337
+ }
1338
+ for (sidecar.model_helpers, 0..) |helper, index| {
1339
+ flagVoid(helper.returns, pathOfStatic(diags, "model_helpers[{d}].returns", .{index}), diags);
1340
+ for (helper.params, 0..) |param, param_index| {
1341
+ flagVoid(param, pathOfStatic(diags, "model_helpers[{d}].params[{d}]", .{ index, param_index }), diags);
1342
+ }
1343
+ }
1344
+ for (sidecar.msg.arms, 0..) |arm, index| {
1345
+ switch (arm.payload) {
1346
+ .scalar => |ref| flagVoid(ref, pathOfStatic(diags, "msg.arms[{d}].payload.type", .{index}), diags),
1347
+ else => {},
1348
+ }
1349
+ }
1350
+ }
1351
+
1352
+ fn flagVoid(ref: TypeRef, at: []const u8, diags: *Diagnostics) void {
1353
+ switch (ref) {
1354
+ .void => diags.flag(at, "the void TypeRef carries no value and is legal only as a bare union arm payload — this slot needs a value type", .{}),
1355
+ .optional => |inner| flagVoid(inner.*, at, diags),
1356
+ .slice => |elem| flagVoid(elem.*, at, diags),
1357
+ else => {},
1358
+ }
1359
+ }
1360
+
1361
+ fn validateUnbound(sidecar: Sidecar, diags: *Diagnostics) void {
1362
+ const model = findStruct(sidecar.types, sidecar.model) orelse return;
1363
+ // The opt-out vocabulary spans everything a view could bind on the
1364
+ // model: its fields AND its exported helpers (helpers surface as
1365
+ // bindable model methods, so an author can declare one
1366
+ // intentionally unbound). The schema's V8 wording says "field";
1367
+ // the reader accepts the helper case the dead-state lint actually
1368
+ // covers — see SCHEMA-GAPS.md.
1369
+ outer: for (sidecar.model_unbound, 0..) |name, index| {
1370
+ for (model.fields) |field| {
1371
+ if (std.mem.eql(u8, field.name, name)) continue :outer;
1372
+ }
1373
+ for (sidecar.model_helpers) |helper| {
1374
+ if (std.mem.eql(u8, helper.name, name)) continue :outer;
1375
+ }
1376
+ diags.flag(pathOfStatic(diags, "model_unbound[{d}]", .{index}), "\"{s}\" is neither a field of the model struct \"{s}\" nor an exported helper (V8)", .{ name, sidecar.model });
1377
+ }
1378
+ outer: for (sidecar.msg.unbound, 0..) |name, index| {
1379
+ for (sidecar.msg.arms) |arm| {
1380
+ if (std.mem.eql(u8, arm.name, name)) continue :outer;
1381
+ }
1382
+ diags.flag(pathOfStatic(diags, "msg.unbound[{d}]", .{index}), "\"{s}\" is not an arm of the message union (V8)", .{name});
1383
+ }
1384
+ }
1385
+
1386
+ pub fn findArm(msg: Msg, name: []const u8) ?*const MsgArm {
1387
+ for (msg.arms) |*arm| {
1388
+ if (std.mem.eql(u8, arm.name, name)) return arm;
1389
+ }
1390
+ return null;
1391
+ }
1392
+
1393
+ fn exportListed(sidecar: Sidecar, suffix: []const u8) bool {
1394
+ for (sidecar.abi.exports) |entry| {
1395
+ if (std.mem.eql(u8, entry, suffix)) return true;
1396
+ }
1397
+ return false;
1398
+ }
1399
+
1400
+ fn validateChannels(sidecar: Sidecar, diags: *Diagnostics) void {
1401
+ const record_channels = [_]struct { name: []const u8, arm: ?[]const u8 }{
1402
+ .{ .name = "appearance_msg", .arm = sidecar.channels.appearance_msg },
1403
+ .{ .name = "chrome_msg", .arm = sidecar.channels.chrome_msg },
1404
+ };
1405
+ for (record_channels) |channel| {
1406
+ const arm_name = channel.arm orelse continue;
1407
+ const at = pathOfStatic(diags, "channels.{s}", .{channel.name});
1408
+ const arm = findArm(sidecar.msg, arm_name) orelse {
1409
+ diags.flag(at, "\"{s}\" names no arm of the message union (V9)", .{arm_name});
1410
+ continue;
1411
+ };
1412
+ switch (arm.payload) {
1413
+ .record, .union_ref, .enum_ref, .scalar => {},
1414
+ else => diags.flag(at, "arm \"{s}\" has a {s} payload descriptor, but this channel requires the named-type family (record/union/enum/scalar) — the host constructs the arm's payload itself, so it must learn the shape from the type table (V9)", .{ arm_name, @tagName(arm.payload) }),
1415
+ }
1416
+ }
1417
+
1418
+ outer: for (sidecar.channels.env_msgs, 0..) |entry, index| {
1419
+ const at = pathOfStatic(diags, "channels.env_msgs[{d}].msg", .{index});
1420
+ const arm = findArm(sidecar.msg, entry.msg) orelse {
1421
+ diags.flag(at, "\"{s}\" names no arm of the message union (V9)", .{entry.msg});
1422
+ continue :outer;
1423
+ };
1424
+ if (arm.payload != .bytes) {
1425
+ diags.flag(at, "arm \"{s}\" has a {s} payload descriptor, but environment channels deliver the variable's value as bytes, so the target arm's descriptor must be bytes (V9)", .{ entry.msg, @tagName(arm.payload) });
1426
+ }
1427
+ }
1428
+
1429
+ const function_channels = [_]struct { name: []const u8, wired: bool }{
1430
+ .{ .name = "command_msg", .wired = sidecar.channels.command_msg },
1431
+ .{ .name = "frame_msg", .wired = sidecar.channels.frame_msg },
1432
+ .{ .name = "key_msg", .wired = sidecar.channels.key_msg },
1433
+ .{ .name = "pinch_msg", .wired = sidecar.channels.pinch_msg },
1434
+ };
1435
+ for (function_channels) |channel| {
1436
+ const listed = exportListed(sidecar, channel.name);
1437
+ if (channel.wired and !listed) {
1438
+ diags.flag(pathOfStatic(diags, "channels.{s}", .{channel.name}), "the channel is declared wired but \"{s}\" is missing from abi.exports — presence is biconditional (V9)", .{channel.name});
1439
+ }
1440
+ if (!channel.wired and listed) {
1441
+ diags.flag("abi.exports", "\"{s}\" is listed but channels.{s} is false — presence is biconditional (V9)", .{ channel.name, channel.name });
1442
+ }
1443
+ }
1444
+ }
1445
+
1446
+ fn validateAbi(sidecar: Sidecar, diags: *Diagnostics) void {
1447
+ // The list must be exactly: every unconditional suffix, then the
1448
+ // wired conditional suffixes, in the normative canonical order —
1449
+ // identity getters, mode-provided entries (set_panic_sink, init,
1450
+ // collect, frame_reset), then the entry-point map. The "and the
1451
+ // object exports nothing else" half needs the object and runs at
1452
+ // link time.
1453
+ var cursor: usize = 0;
1454
+ for (unconditional_exports) |suffix| {
1455
+ if (cursor < sidecar.abi.exports.len and std.mem.eql(u8, sidecar.abi.exports[cursor], suffix)) {
1456
+ cursor += 1;
1457
+ } else {
1458
+ diags.flag(pathOfStatic(diags, "abi.exports[{d}]", .{cursor}), "expected the unconditional export \"{s}\" here — abi.exports lists every unconditional suffix, then the wired channel entries, in the canonical order: identity getters (abi_version, build_id), the mode-provided entries (set_panic_sink, init, collect, frame_reset), then the entry-point map (V11)", .{suffix});
1459
+ return;
1460
+ }
1461
+ }
1462
+ for (conditional_exports) |suffix| {
1463
+ if (cursor < sidecar.abi.exports.len and std.mem.eql(u8, sidecar.abi.exports[cursor], suffix)) {
1464
+ cursor += 1;
1465
+ }
1466
+ }
1467
+ if (cursor < sidecar.abi.exports.len) {
1468
+ diags.flag(pathOfStatic(diags, "abi.exports[{d}]", .{cursor}), "\"{s}\" is not an export suffix of ABI version {d} (or is out of canonical order) — V11", .{ sidecar.abi.exports[cursor], supported_abi_version });
1469
+ }
1470
+ }
1471
+
1472
+ pub const SlotPath = struct {
1473
+ path: []const u8,
1474
+ /// Whether any joined component itself contains a dot (the grammar
1475
+ /// cannot address such a slot unambiguously).
1476
+ components_dotted: bool,
1477
+ };
1478
+
1479
+ fn dotted(names: []const []const u8) bool {
1480
+ for (names) |name| {
1481
+ if (std.mem.indexOfScalar(u8, name, '.') != null) return true;
1482
+ }
1483
+ return false;
1484
+ }
1485
+
1486
+ /// The slot spellings V10's bijection is checked against: every i64
1487
+ /// spelling in the sidecar, at its schema-defined slot path.
1488
+ pub fn collectIntegerSlotPaths(arena: std.mem.Allocator, sidecar: Sidecar) error{OutOfMemory}![]const SlotPath {
1489
+ var paths: std.ArrayListUnmanaged(SlotPath) = .empty;
1490
+ for (sidecar.types.structs) |entry| {
1491
+ for (entry.fields) |field| {
1492
+ if (spellsInteger(field.type)) {
1493
+ try paths.append(arena, .{ .path = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, field.name }), .components_dotted = dotted(&.{ entry.name, field.name }) });
1494
+ }
1495
+ }
1496
+ }
1497
+ for (sidecar.types.unions) |entry| {
1498
+ for (entry.arms) |arm| {
1499
+ if (spellsInteger(arm.payload)) {
1500
+ try paths.append(arena, .{ .path = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, arm.name }), .components_dotted = dotted(&.{ entry.name, arm.name }) });
1501
+ }
1502
+ }
1503
+ }
1504
+ // The message-side path forms spell the union's AUTHORED name —
1505
+ // an app whose union is named Action spells its slots
1506
+ // `Action.<arm>`, never a literal `Msg` token.
1507
+ for (sidecar.msg.arms) |arm| {
1508
+ switch (arm.payload) {
1509
+ .number => |class| if (class == .i64) {
1510
+ try paths.append(arena, .{ .path = try std.fmt.allocPrint(arena, "{s}.{s}", .{ sidecar.msg.name, arm.name }), .components_dotted = dotted(&.{ sidecar.msg.name, arm.name }) });
1511
+ },
1512
+ .number_bytes => |desc| if (desc.number_class == .i64) {
1513
+ try paths.append(arena, .{ .path = try std.fmt.allocPrint(arena, "{s}.{s}.{s}", .{ sidecar.msg.name, arm.name, desc.number_field }), .components_dotted = dotted(&.{ sidecar.msg.name, arm.name, desc.number_field }) });
1514
+ },
1515
+ .scalar => |ref| if (spellsInteger(ref)) {
1516
+ try paths.append(arena, .{ .path = try std.fmt.allocPrint(arena, "{s}.{s}", .{ sidecar.msg.name, arm.name }), .components_dotted = dotted(&.{ sidecar.msg.name, arm.name }) });
1517
+ },
1518
+ else => {},
1519
+ }
1520
+ }
1521
+ for (sidecar.model_helpers) |helper| {
1522
+ if (spellsInteger(helper.returns)) {
1523
+ try paths.append(arena, .{ .path = try std.fmt.allocPrint(arena, "helpers.{s}.return", .{helper.name}), .components_dotted = dotted(&.{helper.name}) });
1524
+ }
1525
+ for (helper.params, 0..) |param, index| {
1526
+ if (spellsInteger(param)) {
1527
+ try paths.append(arena, .{ .path = try std.fmt.allocPrint(arena, "helpers.{s}.params[{d}]", .{ helper.name, index }), .components_dotted = dotted(&.{helper.name}) });
1528
+ }
1529
+ }
1530
+ }
1531
+ return paths.items;
1532
+ }
1533
+
1534
+ /// Whether a TypeRef spells i64 at its own slot (through optionals; a
1535
+ /// slice element is its own slot grammar problem and the schema defines
1536
+ /// no path for it, so a slice of i64 cannot be attested — the emitter
1537
+ /// spells such elements f64 until the schema grows a path form).
1538
+ fn spellsInteger(ref: TypeRef) bool {
1539
+ return switch (ref) {
1540
+ .i64 => true,
1541
+ .optional => |inner| spellsInteger(inner.*),
1542
+ else => false,
1543
+ };
1544
+ }
1545
+
1546
+ /// What an `integer_slots` entry's path names once resolved against the
1547
+ /// sidecar's own tables under the format-1 slot-path grammar.
1548
+ pub const SlotTarget = union(enum) {
1549
+ /// A slot the sidecar spells i64 — an attestable target.
1550
+ integer,
1551
+ /// A real slot, spelled or classed as described — not attestable.
1552
+ not_integer: []const u8,
1553
+ /// A sequence whose elements spell an integer: the format-1 grammar
1554
+ /// has no slice-element form, so no path can attest it.
1555
+ slice_element,
1556
+ /// No grammar form reaches a slot of this spelling.
1557
+ unresolved,
1558
+ };
1559
+
1560
+ fn refSpelling(ref: TypeRef) []const u8 {
1561
+ return switch (ref) {
1562
+ .bool => "bool",
1563
+ .f64 => "f64",
1564
+ .i64 => "i64",
1565
+ .bytes => "bytes",
1566
+ .void => "void",
1567
+ .optional => |inner| refSpelling(inner.*),
1568
+ .slice => "a slice",
1569
+ .node, .value => "a record",
1570
+ .enum_ref => "an enum",
1571
+ .union_ref => "a union",
1572
+ };
1573
+ }
1574
+
1575
+ fn wrapsInteger(ref: TypeRef) bool {
1576
+ return switch (ref) {
1577
+ .i64 => true,
1578
+ .optional => |inner| wrapsInteger(inner.*),
1579
+ .slice => |elem| wrapsInteger(elem.*),
1580
+ else => false,
1581
+ };
1582
+ }
1583
+
1584
+ /// Classify the TypeRef a resolved path lands on: i64 through optionals
1585
+ /// is the attestable shape; an integer buried under a slice is the
1586
+ /// grammar's known gap; everything else is a real slot of another
1587
+ /// spelling.
1588
+ fn classifyRef(ref: TypeRef) SlotTarget {
1589
+ return switch (ref) {
1590
+ .i64 => .integer,
1591
+ .optional => |inner| classifyRef(inner.*),
1592
+ .slice => |elem| if (wrapsInteger(elem.*)) .slice_element else .{ .not_integer = "a slice" },
1593
+ else => .{ .not_integer = refSpelling(ref) },
1594
+ };
1595
+ }
1596
+
1597
+ fn classifyNumberClass(class: NumberClass) SlotTarget {
1598
+ return switch (class) {
1599
+ .i64 => .integer,
1600
+ .f64 => .{ .not_integer = "f64" },
1601
+ };
1602
+ }
1603
+
1604
+ /// Resolve one slot path against the sidecar's tables. The grammar's
1605
+ /// forms, each segment the author's spelling: `<TypeName>.<field>` (a
1606
+ /// struct field, or a non-msg union arm's payload),
1607
+ /// `<msgName>.<arm>` (a scalar-number arm), `<msgName>.<arm>.<field>`
1608
+ /// (a number_bytes arm's number field), `helpers.<name>.return`, and
1609
+ /// `helpers.<name>.params[<index>]`.
1610
+ pub fn resolveSlotPath(sidecar: Sidecar, path: []const u8) SlotTarget {
1611
+ var segments: [4][]const u8 = undefined;
1612
+ var count: usize = 0;
1613
+ var it = std.mem.splitScalar(u8, path, '.');
1614
+ while (it.next()) |segment| {
1615
+ if (segment.len == 0) return .unresolved;
1616
+ if (count == segments.len) return .unresolved;
1617
+ segments[count] = segment;
1618
+ count += 1;
1619
+ }
1620
+
1621
+ if (count == 3 and std.mem.eql(u8, segments[0], "helpers")) {
1622
+ for (sidecar.model_helpers) |helper| {
1623
+ if (!std.mem.eql(u8, helper.name, segments[1])) continue;
1624
+ if (std.mem.eql(u8, segments[2], "return")) return classifyRef(helper.returns);
1625
+ if (std.mem.startsWith(u8, segments[2], "params[") and std.mem.endsWith(u8, segments[2], "]")) {
1626
+ const digits = segments[2]["params[".len .. segments[2].len - 1];
1627
+ const index = std.fmt.parseInt(usize, digits, 10) catch return .unresolved;
1628
+ if (index >= helper.params.len) return .unresolved;
1629
+ return classifyRef(helper.params[index]);
1630
+ }
1631
+ return .unresolved;
1632
+ }
1633
+ return .unresolved;
1634
+ }
1635
+
1636
+ if (std.mem.eql(u8, segments[0], sidecar.msg.name)) {
1637
+ if (count == 2) {
1638
+ if (findArm(sidecar.msg, segments[1])) |arm| {
1639
+ return switch (arm.payload) {
1640
+ .number => |class| classifyNumberClass(class),
1641
+ .scalar => |ref| classifyRef(ref),
1642
+ .void => .{ .not_integer = "void" },
1643
+ .bytes => .{ .not_integer = "bytes" },
1644
+ .number_bytes => .{ .not_integer = "a number_bytes record (its number field is the slot)" },
1645
+ .record => .{ .not_integer = "a record" },
1646
+ .union_ref => .{ .not_integer = "a union" },
1647
+ .enum_ref => .{ .not_integer = "an enum" },
1648
+ };
1649
+ }
1650
+ }
1651
+ if (count == 3) {
1652
+ if (findArm(sidecar.msg, segments[1])) |arm| {
1653
+ switch (arm.payload) {
1654
+ .number_bytes => |desc| {
1655
+ if (std.mem.eql(u8, segments[2], desc.number_field)) return classifyNumberClass(desc.number_class);
1656
+ if (std.mem.eql(u8, segments[2], desc.bytes_field)) return .{ .not_integer = "bytes" };
1657
+ },
1658
+ else => {},
1659
+ }
1660
+ }
1661
+ return .unresolved;
1662
+ }
1663
+ }
1664
+
1665
+ if (count == 2) {
1666
+ if (findStruct(sidecar.types, segments[0])) |record| {
1667
+ for (record.fields) |field| {
1668
+ if (std.mem.eql(u8, field.name, segments[1])) return classifyRef(field.type);
1669
+ }
1670
+ return .unresolved;
1671
+ }
1672
+ if (findUnion(sidecar.types, segments[0])) |tagged| {
1673
+ for (tagged.arms) |arm| {
1674
+ if (std.mem.eql(u8, arm.name, segments[1])) return classifyRef(arm.payload);
1675
+ }
1676
+ return .unresolved;
1677
+ }
1678
+ }
1679
+ return .unresolved;
1680
+ }
1681
+
1682
+ fn validateIntegerSlots(arena: std.mem.Allocator, sidecar: Sidecar, diags: *Diagnostics) error{OutOfMemory}!void {
1683
+ const expected = try collectIntegerSlotPaths(arena, sidecar);
1684
+
1685
+ // The path grammar joins components with dots, so a component
1686
+ // carrying its own dot would make two different slots spell one
1687
+ // path — the bijection would silently thin. Refuse the ambiguity at
1688
+ // its source.
1689
+ for (expected) |path| {
1690
+ if (path.components_dotted) {
1691
+ diags.flag("integer_slots", "the i64 slot at \"{s}\" involves a name containing '.', which the slot path grammar cannot address unambiguously — rename it in the core source (V10)", .{path.path});
1692
+ }
1693
+ }
1694
+ // Two DISTINCT slots spelling one path is the same ambiguity from
1695
+ // another direction (a message union named `helpers` whose
1696
+ // number_bytes field spells a helper's return slot, a table type
1697
+ // sharing the message union's name): the bijection would consume
1698
+ // entries interchangeably and one attestation would silently govern
1699
+ // both slots.
1700
+ for (expected, 0..) |path, index| {
1701
+ for (expected[0..index]) |earlier| {
1702
+ if (std.mem.eql(u8, earlier.path, path.path)) {
1703
+ diags.flag("integer_slots", "two distinct i64 slots spell the one path \"{s}\" — the slot-path grammar cannot address them separately, so their attestations cannot be told apart; rename one of the colliding surfaces in the core source (V10)", .{path.path});
1704
+ }
1705
+ }
1706
+ }
1707
+ if (diags.hasErrors()) return;
1708
+
1709
+ // One-to-one both ways: every expected slot consumes exactly one
1710
+ // entry, and no entry is left over or spent twice.
1711
+ const consumed = try arena.alloc(bool, sidecar.integer_slots.len);
1712
+ @memset(consumed, false);
1713
+ outer: for (expected) |path| {
1714
+ for (sidecar.integer_slots, 0..) |slot, index| {
1715
+ if (!consumed[index] and std.mem.eql(u8, slot.slot, path.path)) {
1716
+ consumed[index] = true;
1717
+ continue :outer;
1718
+ }
1719
+ }
1720
+ diags.flag("integer_slots", "the sidecar spells \"{s}\" i64 but attests no integer_slots entry for it — every i64 spelling has exactly one entry (V10)", .{path.path});
1721
+ }
1722
+ for (sidecar.integer_slots, 0..) |slot, index| {
1723
+ if (consumed[index]) continue;
1724
+ var duplicate = false;
1725
+ for (sidecar.integer_slots[0..index]) |earlier| {
1726
+ if (std.mem.eql(u8, earlier.slot, slot.slot)) duplicate = true;
1727
+ }
1728
+ const at = pathOfStatic(diags, "integer_slots[{d}].slot", .{index});
1729
+ if (duplicate) {
1730
+ diags.flag(at, "duplicate entry for \"{s}\" — every i64 slot has exactly one entry (V10)", .{slot.slot});
1731
+ continue;
1732
+ }
1733
+ // The entry consumed nothing: resolve its path structurally so
1734
+ // the teaching names what actually went wrong instead of one
1735
+ // generic mismatch.
1736
+ switch (resolveSlotPath(sidecar, slot.slot)) {
1737
+ .integer => diags.flag(at, "\"{s}\" resolves to no slot the sidecar spells i64 — every entry must name a real i64 slot (V10)", .{slot.slot}),
1738
+ .not_integer => |spelling| diags.flag(at, "\"{s}\" resolves to a slot the sidecar spells {s}, not i64 — an attested integer class must sit on an i64 spelling (V10)", .{ slot.slot, spelling }),
1739
+ .slice_element => diags.flag(at, "\"{s}\" addresses a sequence — the format-1 slot-path grammar has no slice-element form, so slice elements are never integer-attested; the emitter spells them f64 and readers exempt them from the bijection (V10)", .{slot.slot}),
1740
+ .unresolved => diags.flag(at, "\"{s}\" resolves against none of the sidecar's own tables — slot paths name a record field or union arm (<Type>.<name>), a message payload (\"{s}.<arm>\" or \"{s}.<arm>.<numberField>\"), or a helper signature slot (helpers.<name>.return, helpers.<name>.params[<index>]) (V10)", .{ slot.slot, sidecar.msg.name, sidecar.msg.name }),
1741
+ }
1742
+ }
1743
+ }
1744
+
1745
+ /// Restate a validated sidecar after applying record-slot f64 demotions.
1746
+ /// Mutating the dynamic document instead of serializing the typed reader
1747
+ /// preserves unknown additive fields for newer producers. The caller first
1748
+ /// validates each path against the typed contract, so a miss here is internal
1749
+ /// projection drift rather than user input.
1750
+ pub fn projectF64SlotsJson(arena: std.mem.Allocator, source: []const u8, f64_slots: []const []const u8) ![]const u8 {
1751
+ if (f64_slots.len == 0) return source;
1752
+
1753
+ var root = try std.json.parseFromSliceLeaky(std.json.Value, arena, source, .{});
1754
+ const types = root.object.getPtr("types").?;
1755
+ const structs = types.object.getPtr("structs").?;
1756
+ for (f64_slots) |slot_path| {
1757
+ const dot = std.mem.indexOfScalar(u8, slot_path, '.') orelse return error.ProjectionDrift;
1758
+ const container = slot_path[0..dot];
1759
+ const field_name = slot_path[dot + 1 ..];
1760
+ var changed = false;
1761
+ for (structs.array.items) |*entry| {
1762
+ if (!std.mem.eql(u8, entry.object.get("name").?.string, container)) continue;
1763
+ const fields = entry.object.getPtr("fields").?;
1764
+ for (fields.array.items) |*field| {
1765
+ if (!std.mem.eql(u8, field.object.get("name").?.string, field_name)) continue;
1766
+ const ref = field.object.getPtr("type").?;
1767
+ const kind = ref.object.getPtr("kind").?;
1768
+ if (std.mem.eql(u8, kind.string, "optional")) {
1769
+ const inner = ref.object.getPtr("inner").?;
1770
+ inner.object.getPtr("kind").?.* = .{ .string = "f64" };
1771
+ } else {
1772
+ kind.* = .{ .string = "f64" };
1773
+ }
1774
+ changed = true;
1775
+ break;
1776
+ }
1777
+ break;
1778
+ }
1779
+ if (!changed) return error.ProjectionDrift;
1780
+ }
1781
+
1782
+ const attestations = root.object.getPtr("integer_slots").?;
1783
+ var index: usize = 0;
1784
+ while (index < attestations.array.items.len) {
1785
+ const slot = attestations.array.items[index].object.get("slot").?.string;
1786
+ const demoted = for (f64_slots) |candidate| {
1787
+ if (std.mem.eql(u8, slot, candidate)) break true;
1788
+ } else false;
1789
+ if (demoted) {
1790
+ _ = attestations.array.orderedRemove(index);
1791
+ } else {
1792
+ index += 1;
1793
+ }
1794
+ }
1795
+
1796
+ var out: std.Io.Writer.Allocating = .init(arena);
1797
+ var json: std.json.Stringify = .{ .writer = &out.writer, .options = .{ .whitespace = .indent_2 } };
1798
+ try json.write(root);
1799
+ try out.writer.writeByte('\n');
1800
+ return out.written();
1801
+ }
1802
+
1803
+ // --------------------------------------------------------------- tests
1804
+
1805
+ const testing = std.testing;
1806
+
1807
+ /// A minimal valid sidecar the refusal tests perturb: one model struct,
1808
+ /// two message arms, no helpers, no channels.
1809
+ pub const minimal_valid_json =
1810
+ \\{
1811
+ \\ "format": 1,
1812
+ \\ "wire_version": 3,
1813
+ \\ "abi_version": 1,
1814
+ \\ "compiler_version": "0.0.1",
1815
+ \\ "entry": "src/core.ts",
1816
+ \\ "source_hash": "00000000c0ffee00",
1817
+ \\ "build_id": "00000000b01dface",
1818
+ \\ "types": {
1819
+ \\ "structs": [
1820
+ \\ {"name": "Model", "fields": [
1821
+ \\ {"name": "count", "type": {"kind": "i64"}},
1822
+ \\ {"name": "label", "type": {"kind": "bytes"}}
1823
+ \\ ]}
1824
+ \\ ],
1825
+ \\ "enums": [],
1826
+ \\ "unions": []
1827
+ \\ },
1828
+ \\ "model": "Model",
1829
+ \\ "model_helpers": [],
1830
+ \\ "model_unbound": [],
1831
+ \\ "msg": {
1832
+ \\ "name": "Msg",
1833
+ \\ "arms": [
1834
+ \\ {"name": "bump", "payload": {"kind": "void"}},
1835
+ \\ {"name": "label_set", "payload": {"kind": "bytes"}}
1836
+ \\ ],
1837
+ \\ "unbound": ["label_set"]
1838
+ \\ },
1839
+ \\ "init_returns_cmd": false,
1840
+ \\ "update_returns_cmd": true,
1841
+ \\ "has_subscriptions": false,
1842
+ \\ "channels": {
1843
+ \\ "command_msg": false,
1844
+ \\ "frame_msg": false,
1845
+ \\ "key_msg": false,
1846
+ \\ "pinch_msg": false,
1847
+ \\ "appearance_msg": null,
1848
+ \\ "chrome_msg": null,
1849
+ \\ "env_msgs": []
1850
+ \\ },
1851
+ \\ "abi": {
1852
+ \\ "prefix": "nsc_core_",
1853
+ \\ "exports": ["abi_version", "build_id", "set_panic_sink", "init", "collect",
1854
+ \\ "frame_reset", "boot_cmd", "dispatch_void", "dispatch_bytes", "dispatch_number",
1855
+ \\ "dispatch_number_bytes", "dispatch_bool", "dispatch_enum", "dispatch_record",
1856
+ \\ "dispatch_text_input", "dispatch_scroll_state", "subscriptions", "model_snapshot",
1857
+ \\ "helper_call"],
1858
+ \\ "snapshot_format": 1
1859
+ \\ },
1860
+ \\ "integer_slots": [
1861
+ \\ {"slot": "Model.count", "class": "i64"}
1862
+ \\ ],
1863
+ \\ "deterministic": true,
1864
+ \\ "async_free": true
1865
+ \\}
1866
+ ;
1867
+
1868
+ test "effective sidecar carries f64 demotions into its type table and attestations" {
1869
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1870
+ defer arena_state.deinit();
1871
+ const arena = arena_state.allocator();
1872
+ const projected = try projectF64SlotsJson(arena, minimal_valid_json, &.{"Model.count"});
1873
+ var diags = Diagnostics{ .arena = arena };
1874
+ const parsed = try read(arena, projected, &diags);
1875
+ const model = findStruct(parsed.types, "Model").?;
1876
+ try testing.expect(model.fields[0].type == .f64);
1877
+ try testing.expectEqual(@as(usize, 0), parsed.integer_slots.len);
1878
+ }
1879
+
1880
+ fn expectRefusal(source: []const u8, expected_path: []const u8, expected_fragment: []const u8) !void {
1881
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1882
+ defer arena_state.deinit();
1883
+ const arena = arena_state.allocator();
1884
+ var diags = Diagnostics{ .arena = arena };
1885
+ const result = read(arena, source, &diags);
1886
+ try testing.expectError(error.Refused, result);
1887
+ for (diags.list.items) |item| {
1888
+ if (item.severity != .@"error") continue;
1889
+ if (std.mem.eql(u8, item.path, expected_path) and std.mem.indexOf(u8, item.message, expected_fragment) != null) return;
1890
+ }
1891
+ std.debug.print("no refusal at \"{s}\" containing \"{s}\"; got:\n", .{ expected_path, expected_fragment });
1892
+ for (diags.list.items) |item| {
1893
+ std.debug.print(" [{s}] {s}: {s}\n", .{ @tagName(item.severity), item.path, item.message });
1894
+ }
1895
+ return error.TestExpectedRefusal;
1896
+ }
1897
+
1898
+ fn expectRefusalContaining(source: []const u8, expected_fragment: []const u8) !void {
1899
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1900
+ defer arena_state.deinit();
1901
+ const arena = arena_state.allocator();
1902
+ var diags = Diagnostics{ .arena = arena };
1903
+ const result = read(arena, source, &diags);
1904
+ try testing.expectError(error.Refused, result);
1905
+ for (diags.list.items) |item| {
1906
+ if (item.severity != .@"error") continue;
1907
+ if (std.mem.indexOf(u8, item.message, expected_fragment) != null) return;
1908
+ }
1909
+ std.debug.print("no refusal containing \"{s}\"; got:\n", .{expected_fragment});
1910
+ for (diags.list.items) |item| {
1911
+ std.debug.print(" [{s}] {s}: {s}\n", .{ @tagName(item.severity), item.path, item.message });
1912
+ }
1913
+ return error.TestExpectedRefusal;
1914
+ }
1915
+
1916
+ fn readValid(arena: std.mem.Allocator, source: []const u8) !Sidecar {
1917
+ var diags = Diagnostics{ .arena = arena };
1918
+ return read(arena, source, &diags) catch |err| {
1919
+ for (diags.list.items) |item| {
1920
+ std.debug.print(" [{s}] {s}: {s}\n", .{ @tagName(item.severity), item.path, item.message });
1921
+ }
1922
+ return err;
1923
+ };
1924
+ }
1925
+
1926
+ fn replaced(arena: std.mem.Allocator, original: []const u8, needle: []const u8, replacement: []const u8) ![]const u8 {
1927
+ const count = std.mem.replacementSize(u8, original, needle, replacement);
1928
+ const out = try arena.alloc(u8, count);
1929
+ _ = std.mem.replace(u8, original, needle, replacement, out);
1930
+ return out;
1931
+ }
1932
+
1933
+ test "the minimal sidecar reads clean" {
1934
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1935
+ defer arena_state.deinit();
1936
+ const arena = arena_state.allocator();
1937
+ const sidecar = try readValid(arena, minimal_valid_json);
1938
+ try testing.expectEqualStrings("Model", sidecar.model);
1939
+ try testing.expectEqual(@as(usize, 2), sidecar.msg.arms.len);
1940
+ try testing.expectEqual(@as(u64, 0x00000000c0ffee00), sidecar.source_hash);
1941
+ try testing.expect(sidecar.msg.arms[0].payload == .void);
1942
+ try testing.expect(sidecar.msg.arms[1].payload == .bytes);
1943
+ }
1944
+
1945
+ test "V1: an unknown format refuses whole-file with both versions named" {
1946
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1947
+ defer arena_state.deinit();
1948
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"format\": 1", "\"format\": 2");
1949
+ try expectRefusal(source, "format", "implements sidecar format 1, found 2");
1950
+ }
1951
+
1952
+ test "V1: a missing required field refuses with its path" {
1953
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1954
+ defer arena_state.deinit();
1955
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"deterministic\": true,", "");
1956
+ try expectRefusal(source, "deterministic", "required field missing");
1957
+ }
1958
+
1959
+ test "V2: a hash carried as a JSON number refuses with the encoding teaching" {
1960
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1961
+ defer arena_state.deinit();
1962
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"00000000b01dface\"", "12345");
1963
+ try expectRefusal(source, "build_id", "never JSON numbers");
1964
+ }
1965
+
1966
+ test "V2: uppercase hex refuses" {
1967
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1968
+ defer arena_state.deinit();
1969
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"00000000c0ffee00\"", "\"00000000C0FFEE00\"");
1970
+ try expectRefusal(source, "source_hash", "lowercase hex digits only");
1971
+ }
1972
+
1973
+ test "V3: a duplicate type-table name refuses with the exact entry path" {
1974
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1975
+ defer arena_state.deinit();
1976
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"enums\": []", "\"enums\": [{\"name\": \"Model\", \"members\": [\"a\"]}]");
1977
+ try expectRefusal(source, "types.enums[0].name", "duplicate type-table name \"Model\"");
1978
+ }
1979
+
1980
+ test "V4: a dangling node reference names the missing entry" {
1981
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1982
+ defer arena_state.deinit();
1983
+ const source = try replaced(
1984
+ arena_state.allocator(),
1985
+ minimal_valid_json,
1986
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
1987
+ "{\"name\": \"label\", \"type\": {\"kind\": \"node\", \"name\": \"Missing\"}}",
1988
+ );
1989
+ try expectRefusal(source, "types.structs.Model.fields[1].type", "\"Missing\" names no entry");
1990
+ }
1991
+
1992
+ test "V4: an unreachable table entry refuses" {
1993
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1994
+ defer arena_state.deinit();
1995
+ const source = try replaced(
1996
+ arena_state.allocator(),
1997
+ minimal_valid_json,
1998
+ "\"enums\": []",
1999
+ "\"enums\": [{\"name\": \"Orphan\", \"members\": [\"a\"]}]",
2000
+ );
2001
+ try expectRefusal(source, "types.enums[0]", "unreachable from model, msg, model_helpers, and channels");
2002
+ }
2003
+
2004
+ test "V5: a reference cycle refuses with the cycle spelled out" {
2005
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2006
+ defer arena_state.deinit();
2007
+ const source = try replaced(
2008
+ arena_state.allocator(),
2009
+ minimal_valid_json,
2010
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
2011
+ "{\"name\": \"label\", \"type\": {\"kind\": \"node\", \"name\": \"Model\"}}",
2012
+ );
2013
+ try expectRefusal(source, "types", "Model -> Model");
2014
+ }
2015
+
2016
+ test "V6: more than 256 arms refuses" {
2017
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2018
+ defer arena_state.deinit();
2019
+ const arena = arena_state.allocator();
2020
+ var arms: std.ArrayListUnmanaged(u8) = .empty;
2021
+ for (0..257) |index| {
2022
+ if (index > 0) try arms.appendSlice(arena, ",\n");
2023
+ const one = try std.fmt.allocPrint(arena, " {{\"name\": \"arm_{d}\", \"payload\": {{\"kind\": \"void\"}}}}", .{index});
2024
+ try arms.appendSlice(arena, one);
2025
+ }
2026
+ const source = try replaced(
2027
+ arena,
2028
+ minimal_valid_json,
2029
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"void\"}},\n {\"name\": \"label_set\", \"payload\": {\"kind\": \"bytes\"}}",
2030
+ arms.items,
2031
+ );
2032
+ // The unbound list must still resolve.
2033
+ const patched = try replaced(arena, source, "\"unbound\": [\"label_set\"]", "\"unbound\": []");
2034
+ try expectRefusal(patched, "msg.arms", "exceed the 256-arm bound");
2035
+ }
2036
+
2037
+ test "valueless message unions, tabled unions, and enums refuse" {
2038
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2039
+ defer arena_state.deinit();
2040
+ const arena = arena_state.allocator();
2041
+ const no_arms = try replaced(
2042
+ arena,
2043
+ minimal_valid_json,
2044
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"void\"}},\n {\"name\": \"label_set\", \"payload\": {\"kind\": \"bytes\"}}",
2045
+ "",
2046
+ );
2047
+ const patched = try replaced(arena, no_arms, "\"unbound\": [\"label_set\"]", "\"unbound\": []");
2048
+ try expectRefusal(patched, "msg.arms", "declares no arms");
2049
+
2050
+ const empty_enum = try replaced(
2051
+ arena,
2052
+ minimal_valid_json,
2053
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
2054
+ "{\"name\": \"label\", \"type\": {\"kind\": \"enum\", \"name\": \"Hollow\"}}",
2055
+ );
2056
+ const with_enum = try replaced(arena, empty_enum, "\"enums\": []", "\"enums\": [{\"name\": \"Hollow\", \"members\": []}]");
2057
+ try expectRefusal(with_enum, "types.enums[0]", "declares no members");
2058
+ }
2059
+
2060
+ test "a tabled union past the one-byte arm bound refuses" {
2061
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2062
+ defer arena_state.deinit();
2063
+ const arena = arena_state.allocator();
2064
+ var arms: std.ArrayListUnmanaged(u8) = .empty;
2065
+ for (0..257) |index| {
2066
+ if (index > 0) try arms.appendSlice(arena, ", ");
2067
+ const one = try std.fmt.allocPrint(arena, "{{\"name\": \"arm_{d}\", \"payload\": {{\"kind\": \"void\"}}}}", .{index});
2068
+ try arms.appendSlice(arena, one);
2069
+ }
2070
+ const union_entry = try std.fmt.allocPrint(arena, "\"unions\": [{{\"name\": \"Wide\", \"arms\": [{s}]}}]", .{arms.items});
2071
+ const with_union = try replaced(arena, minimal_valid_json, "\"unions\": []", union_entry);
2072
+ // Reference it so the reachability rule is satisfied.
2073
+ const source = try replaced(
2074
+ arena,
2075
+ with_union,
2076
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
2077
+ "{\"name\": \"label\", \"type\": {\"kind\": \"union\", \"name\": \"Wide\"}}",
2078
+ );
2079
+ try expectRefusal(source, "types.unions[0]", "one-byte declaration-order arm index");
2080
+ }
2081
+
2082
+ test "V7: number_bytes with matching field names refuses" {
2083
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2084
+ defer arena_state.deinit();
2085
+ const source = try replaced(
2086
+ arena_state.allocator(),
2087
+ minimal_valid_json,
2088
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"void\"}}",
2089
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"number_bytes\", \"number_field\": \"x\", \"number_class\": \"i64\", \"bytes_field\": \"x\"}}",
2090
+ );
2091
+ const patched = try replaced(arena_state.allocator(), source, "{\"slot\": \"Model.count\", \"class\": \"i64\"}", "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Msg.bump.x\", \"class\": \"i64\"}");
2092
+ try expectRefusal(patched, "msg.arms[0].payload", "must be distinct");
2093
+ }
2094
+
2095
+ test "V7: an unknown number class refuses as reader-too-old" {
2096
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2097
+ defer arena_state.deinit();
2098
+ const source = try replaced(
2099
+ arena_state.allocator(),
2100
+ minimal_valid_json,
2101
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"void\"}}",
2102
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"number\", \"class\": \"i128\"}}",
2103
+ );
2104
+ try expectRefusal(source, "msg.arms[0].payload.class", "unknown number class \"i128\"");
2105
+ }
2106
+
2107
+ test "the void TypeRef outside a bare union arm refuses" {
2108
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2109
+ defer arena_state.deinit();
2110
+ const source = try replaced(
2111
+ arena_state.allocator(),
2112
+ minimal_valid_json,
2113
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
2114
+ "{\"name\": \"label\", \"type\": {\"kind\": \"void\"}}",
2115
+ );
2116
+ try expectRefusal(source, "types.structs[0].fields[1].type", "legal only as a bare union arm payload");
2117
+ }
2118
+
2119
+ test "V8: model_unbound accepts exported helper names" {
2120
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2121
+ defer arena_state.deinit();
2122
+ const arena = arena_state.allocator();
2123
+ // A helper the author declared intentionally unbound: the opt-out
2124
+ // vocabulary spans everything a view could bind, methods included.
2125
+ const with_helper = try replaced(
2126
+ arena,
2127
+ minimal_valid_json,
2128
+ "\"model_helpers\": []",
2129
+ "\"model_helpers\": [{\"name\": \"summary\", \"params\": [], \"returns\": {\"kind\": \"bytes\"}, \"arena\": false}]",
2130
+ );
2131
+ const source = try replaced(arena, with_helper, "\"model_unbound\": []", "\"model_unbound\": [\"summary\", \"count\"]");
2132
+ const sidecar = try readValid(arena, source);
2133
+ try testing.expectEqual(@as(usize, 2), sidecar.model_unbound.len);
2134
+ }
2135
+
2136
+ test "V8: an unbound name that resolves nowhere refuses" {
2137
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2138
+ defer arena_state.deinit();
2139
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"model_unbound\": []", "\"model_unbound\": [\"ghost\"]");
2140
+ try expectRefusal(source, "model_unbound[0]", "\"ghost\" is neither a field of the model struct");
2141
+ }
2142
+
2143
+ test "V9: an env channel targeting a non-bytes arm refuses" {
2144
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2145
+ defer arena_state.deinit();
2146
+ const source = try replaced(
2147
+ arena_state.allocator(),
2148
+ minimal_valid_json,
2149
+ "\"env_msgs\": []",
2150
+ "\"env_msgs\": [{\"env\": \"APP_MODE\", \"msg\": \"bump\"}]",
2151
+ );
2152
+ try expectRefusal(source, "channels.env_msgs[0].msg", "must be bytes");
2153
+ }
2154
+
2155
+ test "V9: a wired function channel missing from abi.exports refuses" {
2156
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2157
+ defer arena_state.deinit();
2158
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"key_msg\": false", "\"key_msg\": true");
2159
+ try expectRefusal(source, "channels.key_msg", "missing from abi.exports");
2160
+ }
2161
+
2162
+ test "V10: a dotted name in an i64 slot path refuses as unaddressable" {
2163
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2164
+ defer arena_state.deinit();
2165
+ const arena = arena_state.allocator();
2166
+ // `A` with field `B.C` would spell the same path as `A.B` with
2167
+ // field `C`; the grammar cannot tell them apart.
2168
+ var source = try replaced(arena, minimal_valid_json, "{\"name\": \"count\", \"type\": {\"kind\": \"i64\"}}", "{\"name\": \"cou.nt\", \"type\": {\"kind\": \"i64\"}}");
2169
+ source = try replaced(arena, source, "{\"slot\": \"Model.count\", \"class\": \"i64\"}", "{\"slot\": \"Model.cou.nt\", \"class\": \"i64\"}");
2170
+ try expectRefusal(source, "integer_slots", "cannot address unambiguously");
2171
+ }
2172
+
2173
+ test "V10: an i64 spelling without an integer_slots entry refuses" {
2174
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2175
+ defer arena_state.deinit();
2176
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "{\"slot\": \"Model.count\", \"class\": \"i64\"}", "");
2177
+ try expectRefusal(source, "integer_slots", "spells \"Model.count\" i64 but attests no integer_slots entry");
2178
+ }
2179
+
2180
+ test "V10: an entry on a slot of another spelling refuses with that spelling named" {
2181
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2182
+ defer arena_state.deinit();
2183
+ const source = try replaced(
2184
+ arena_state.allocator(),
2185
+ minimal_valid_json,
2186
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2187
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Model.label\", \"class\": \"i64\"}",
2188
+ );
2189
+ try expectRefusal(source, "integer_slots[1].slot", "resolves to a slot the sidecar spells bytes, not i64");
2190
+ }
2191
+
2192
+ test "V10: an unresolvable slot path refuses with the grammar's forms" {
2193
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2194
+ defer arena_state.deinit();
2195
+ const arena = arena_state.allocator();
2196
+ const ghost = try replaced(
2197
+ arena,
2198
+ minimal_valid_json,
2199
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2200
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Ghost.count\", \"class\": \"i64\"}",
2201
+ );
2202
+ try expectRefusal(ghost, "integer_slots[1].slot", "resolves against none of the sidecar's own tables");
2203
+ // An element-indexing spelling has no grammar form either — the
2204
+ // format-1 grammar cannot address inside a sequence.
2205
+ const indexed = try replaced(
2206
+ arena,
2207
+ minimal_valid_json,
2208
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2209
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Model.ids[0]\", \"class\": \"i64\"}",
2210
+ );
2211
+ try expectRefusal(indexed, "integer_slots[1].slot", "resolves against none of the sidecar's own tables");
2212
+ // A missing helper signature slot is the same refusal.
2213
+ const helper = try replaced(
2214
+ arena,
2215
+ minimal_valid_json,
2216
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2217
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"helpers.rowCount.return\", \"class\": \"i64\"}",
2218
+ );
2219
+ try expectRefusal(helper, "integer_slots[1].slot", "resolves against none of the sidecar's own tables");
2220
+ }
2221
+
2222
+ test "V10: a slot path landing on a slice refuses as the grammar's element gap" {
2223
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2224
+ defer arena_state.deinit();
2225
+ const arena = arena_state.allocator();
2226
+ // A slice of i64 is a legal spelling (its elements are exempt from
2227
+ // the bijection), but no entry may claim it: the grammar has no
2228
+ // slice-element form, so the checker refuses rather than
2229
+ // half-supporting element attestation.
2230
+ var source = try replaced(
2231
+ arena,
2232
+ minimal_valid_json,
2233
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
2234
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}, {\"name\": \"ids\", \"type\": {\"kind\": \"slice\", \"elem\": {\"kind\": \"i64\"}}}",
2235
+ );
2236
+ source = try replaced(
2237
+ arena,
2238
+ source,
2239
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2240
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Model.ids\", \"class\": \"i64\"}",
2241
+ );
2242
+ try expectRefusal(source, "integer_slots[1].slot", "no slice-element form");
2243
+ }
2244
+
2245
+ test "V10: a duplicate entry refuses with the exact index" {
2246
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2247
+ defer arena_state.deinit();
2248
+ const source = try replaced(
2249
+ arena_state.allocator(),
2250
+ minimal_valid_json,
2251
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2252
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Model.count\", \"class\": \"u64\"}",
2253
+ );
2254
+ try expectRefusal(source, "integer_slots[1].slot", "duplicate entry for \"Model.count\"");
2255
+ }
2256
+
2257
+ test "V10: the u64 class is accepted and carried" {
2258
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2259
+ defer arena_state.deinit();
2260
+ const arena = arena_state.allocator();
2261
+ const source = try replaced(arena, minimal_valid_json, "{\"slot\": \"Model.count\", \"class\": \"i64\"}", "{\"slot\": \"Model.count\", \"class\": \"u64\"}");
2262
+ const sidecar = try readValid(arena, source);
2263
+ try testing.expectEqual(@as(usize, 1), sidecar.integer_slots.len);
2264
+ try testing.expectEqual(IntegerClass.u64, sidecar.integer_slots[0].class);
2265
+ }
2266
+
2267
+ test "V10: class f64 in integer_slots refuses (the default class is never attested)" {
2268
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2269
+ defer arena_state.deinit();
2270
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "{\"slot\": \"Model.count\", \"class\": \"i64\"}", "{\"slot\": \"Model.count\", \"class\": \"f64\"}");
2271
+ try expectRefusal(source, "integer_slots[0].class", "never attested");
2272
+ }
2273
+
2274
+ test "V10: an unknown integer class refuses as reader-too-old" {
2275
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2276
+ defer arena_state.deinit();
2277
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "{\"slot\": \"Model.count\", \"class\": \"i64\"}", "{\"slot\": \"Model.count\", \"class\": \"i128\"}");
2278
+ try expectRefusal(source, "integer_slots[0].class", "unknown integer class \"i128\"");
2279
+ }
2280
+
2281
+ test "V10: message-side slot paths spell the union's authored name" {
2282
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2283
+ defer arena_state.deinit();
2284
+ const arena = arena_state.allocator();
2285
+ var source = try replaced(arena, minimal_valid_json, "\"name\": \"Msg\"", "\"name\": \"Event\"");
2286
+ source = try replaced(
2287
+ arena,
2288
+ source,
2289
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"void\"}}",
2290
+ "{\"name\": \"tick\", \"payload\": {\"kind\": \"number\", \"class\": \"i64\"}}",
2291
+ );
2292
+ // The authored spelling resolves.
2293
+ const authored = try replaced(
2294
+ arena,
2295
+ source,
2296
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2297
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Event.tick\", \"class\": \"i64\"}",
2298
+ );
2299
+ const sidecar = try readValid(arena, authored);
2300
+ try testing.expectEqual(@as(usize, 2), sidecar.integer_slots.len);
2301
+ // A literal `Msg` token does not: the grammar's message forms use
2302
+ // the designated union's own name.
2303
+ const literal = try replaced(
2304
+ arena,
2305
+ source,
2306
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2307
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"Msg.tick\", \"class\": \"i64\"}",
2308
+ );
2309
+ try expectRefusal(literal, "integer_slots", "spells \"Event.tick\" i64 but attests no integer_slots entry");
2310
+ }
2311
+
2312
+ test "V10: two distinct slots spelling one path refuse as unaddressable" {
2313
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2314
+ defer arena_state.deinit();
2315
+ const arena = arena_state.allocator();
2316
+ // A message union named "helpers" whose number_bytes arm "peak"
2317
+ // declares its number field "return", beside an exported helper
2318
+ // "peak" returning i64: both slots spell "helpers.peak.return", so
2319
+ // no attestation can be told apart from the other's.
2320
+ var source = try replaced(arena, minimal_valid_json, "\"name\": \"Msg\"", "\"name\": \"helpers\"");
2321
+ source = try replaced(
2322
+ arena,
2323
+ source,
2324
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"void\"}}",
2325
+ "{\"name\": \"peak\", \"payload\": {\"kind\": \"number_bytes\", \"number_field\": \"return\", \"number_class\": \"i64\", \"bytes_field\": \"body\"}}",
2326
+ );
2327
+ source = try replaced(
2328
+ arena,
2329
+ source,
2330
+ "\"model_helpers\": []",
2331
+ "\"model_helpers\": [{\"name\": \"peak\", \"params\": [], \"returns\": {\"kind\": \"i64\"}, \"arena\": false}]",
2332
+ );
2333
+ source = try replaced(
2334
+ arena,
2335
+ source,
2336
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}",
2337
+ "{\"slot\": \"Model.count\", \"class\": \"i64\"}, {\"slot\": \"helpers.peak.return\", \"class\": \"i64\"}, {\"slot\": \"helpers.peak.return\", \"class\": \"u64\"}",
2338
+ );
2339
+ try expectRefusal(source, "integer_slots", "two distinct i64 slots spell the one path \"helpers.peak.return\"");
2340
+ }
2341
+
2342
+ test "V10: an empty integer_slots list is valid when nothing spells i64" {
2343
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2344
+ defer arena_state.deinit();
2345
+ const arena = arena_state.allocator();
2346
+ // The f64-only sequencing: an emitter predating integer inference
2347
+ // spells every numeric slot f64 and attests the empty list.
2348
+ var source = try replaced(arena, minimal_valid_json, "{\"name\": \"count\", \"type\": {\"kind\": \"i64\"}}", "{\"name\": \"count\", \"type\": {\"kind\": \"f64\"}}");
2349
+ source = try replaced(arena, source, "{\"slot\": \"Model.count\", \"class\": \"i64\"}", "");
2350
+ const sidecar = try readValid(arena, source);
2351
+ try testing.expectEqual(@as(usize, 0), sidecar.integer_slots.len);
2352
+ }
2353
+
2354
+ test "V11: an unknown export suffix refuses" {
2355
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2356
+ defer arena_state.deinit();
2357
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"helper_call\"]", "\"helper_call\", \"mystery_entry\"]");
2358
+ try expectRefusal(source, "abi.exports[19]", "not an export suffix of ABI version 1");
2359
+ }
2360
+
2361
+ test "V11: a missing unconditional export refuses with the expected suffix" {
2362
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2363
+ defer arena_state.deinit();
2364
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"init\", \"collect\",", "\"init\",");
2365
+ try expectRefusal(source, "abi.exports[4]", "expected the unconditional export \"collect\"");
2366
+ }
2367
+
2368
+ test "unknown TypeRef kinds refuse as reader-too-old" {
2369
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2370
+ defer arena_state.deinit();
2371
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "{\"kind\": \"bytes\"}}", "{\"kind\": \"decimal128\"}}");
2372
+ try expectRefusal(source, "types.structs[0].fields[1].type.kind", "unknown TypeRef kind \"decimal128\"");
2373
+ }
2374
+
2375
+ test "unknown payload descriptor kinds refuse as reader-too-old" {
2376
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2377
+ defer arena_state.deinit();
2378
+ const source = try replaced(
2379
+ arena_state.allocator(),
2380
+ minimal_valid_json,
2381
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"void\"}}",
2382
+ "{\"name\": \"bump\", \"payload\": {\"kind\": \"tensor\"}}",
2383
+ );
2384
+ try expectRefusal(source, "msg.arms[0].payload.kind", "unknown payload descriptor kind \"tensor\"");
2385
+ }
2386
+
2387
+ test "wire and abi version mismatches refuse with both values named" {
2388
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2389
+ defer arena_state.deinit();
2390
+ const source = try replaced(arena_state.allocator(), minimal_valid_json, "\"wire_version\": 3", "\"wire_version\": 4");
2391
+ try expectRefusal(source, "wire_version", "generation 3, the sidecar declares 4");
2392
+ }
2393
+
2394
+ test "unknown fields warn and are ignored" {
2395
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2396
+ defer arena_state.deinit();
2397
+ const arena = arena_state.allocator();
2398
+ const source = try replaced(arena, minimal_valid_json, "\"deterministic\": true,", "\"deterministic\": true,\n \"novel_fact\": 7,");
2399
+ var diags = Diagnostics{ .arena = arena };
2400
+ _ = try read(arena, source, &diags);
2401
+ try testing.expect(!diags.hasErrors());
2402
+ var warned = false;
2403
+ for (diags.list.items) |item| {
2404
+ if (item.severity == .warning and std.mem.eql(u8, item.path, "novel_fact")) warned = true;
2405
+ }
2406
+ try testing.expect(warned);
2407
+ }
2408
+
2409
+ test "structural nesting past the bound refuses instead of exhausting the stack" {
2410
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2411
+ defer arena_state.deinit();
2412
+ const arena = arena_state.allocator();
2413
+
2414
+ var wrapped: std.ArrayListUnmanaged(u8) = .empty;
2415
+ const wraps = 300;
2416
+ var index: usize = 0;
2417
+ while (index < wraps) : (index += 1) {
2418
+ try wrapped.appendSlice(arena, "{\"kind\": \"optional\", \"inner\": ");
2419
+ }
2420
+ try wrapped.appendSlice(arena, "{\"kind\": \"bool\"}");
2421
+ index = 0;
2422
+ while (index < wraps) : (index += 1) {
2423
+ try wrapped.append(arena, '}');
2424
+ }
2425
+ const source = try replaced(arena, minimal_valid_json, "{\"kind\": \"i64\"}", wrapped.items);
2426
+ try expectRefusalContaining(source, "nesting exceeds 256 levels");
2427
+ }
2428
+
2429
+ test "record chains past the depth bound refuse with a teaching" {
2430
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2431
+ defer arena_state.deinit();
2432
+ const arena = arena_state.allocator();
2433
+
2434
+ // Chain0 -> Chain1 -> ... : acyclic and small on disk, but deeper
2435
+ // than any bounded consumer can walk.
2436
+ var chain: std.ArrayListUnmanaged(u8) = .empty;
2437
+ const links = 300;
2438
+ var index: usize = 0;
2439
+ while (index < links) : (index += 1) {
2440
+ const entry = if (index + 1 < links)
2441
+ try std.fmt.allocPrint(arena, "{{\"name\": \"Chain{d}\", \"fields\": [{{\"name\": \"next\", \"type\": {{\"kind\": \"value\", \"name\": \"Chain{d}\"}}}}]}},\n", .{ index, index + 1 })
2442
+ else
2443
+ try std.fmt.allocPrint(arena, "{{\"name\": \"Chain{d}\", \"fields\": [{{\"name\": \"leaf\", \"type\": {{\"kind\": \"i64\"}}}}]}},\n", .{index});
2444
+ try chain.appendSlice(arena, entry);
2445
+ }
2446
+ var source = try replaced(
2447
+ arena,
2448
+ minimal_valid_json,
2449
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
2450
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}, {\"name\": \"head\", \"type\": {\"kind\": \"value\", \"name\": \"Chain0\"}}",
2451
+ );
2452
+ const model_open = "{\"name\": \"Model\", \"fields\": [";
2453
+ source = try replaced(arena, source, model_open, try std.fmt.allocPrint(arena, "{s}{s}", .{ chain.items, model_open }));
2454
+ try expectRefusalContaining(source, "expands deeper than 256 levels");
2455
+ }
2456
+
2457
+ test "compound wrapping and chaining refuse on expanded depth" {
2458
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2459
+ defer arena_state.deinit();
2460
+ const arena = arena_state.allocator();
2461
+
2462
+ // 16 records chained through 32 slice wrappers each: chain length
2463
+ // and per-reference nesting both sit far under their own bounds,
2464
+ // but the expanded value tree is ~528 levels deep.
2465
+ var chain: std.ArrayListUnmanaged(u8) = .empty;
2466
+ const links = 16;
2467
+ const wraps = 32;
2468
+ var index: usize = 0;
2469
+ while (index < links) : (index += 1) {
2470
+ var wrapped: std.ArrayListUnmanaged(u8) = .empty;
2471
+ var level: usize = 0;
2472
+ while (level < wraps) : (level += 1) {
2473
+ try wrapped.appendSlice(arena, "{\"kind\": \"slice\", \"elem\": ");
2474
+ }
2475
+ if (index + 1 < links) {
2476
+ try wrapped.appendSlice(arena, try std.fmt.allocPrint(arena, "{{\"kind\": \"value\", \"name\": \"Deep{d}\"}}", .{index + 1}));
2477
+ } else {
2478
+ try wrapped.appendSlice(arena, "{\"kind\": \"i64\"}");
2479
+ }
2480
+ level = 0;
2481
+ while (level < wraps) : (level += 1) {
2482
+ try wrapped.append(arena, '}');
2483
+ }
2484
+ try chain.appendSlice(arena, try std.fmt.allocPrint(arena, "{{\"name\": \"Deep{d}\", \"fields\": [{{\"name\": \"next\", \"type\": {s}}}]}},\n", .{ index, wrapped.items }));
2485
+ }
2486
+ var source = try replaced(
2487
+ arena,
2488
+ minimal_valid_json,
2489
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}",
2490
+ "{\"name\": \"label\", \"type\": {\"kind\": \"bytes\"}}, {\"name\": \"head\", \"type\": {\"kind\": \"value\", \"name\": \"Deep0\"}}",
2491
+ );
2492
+ const model_open = "{\"name\": \"Model\", \"fields\": [";
2493
+ source = try replaced(arena, source, model_open, try std.fmt.allocPrint(arena, "{s}{s}", .{ chain.items, model_open }));
2494
+ try expectRefusalContaining(source, "expands deeper than 256 levels");
2495
+ }
2496
+
2497
+ test "an abi prefix with symbol-unsafe bytes refuses" {
2498
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
2499
+ defer arena_state.deinit();
2500
+ const arena = arena_state.allocator();
2501
+ const nul = try replaced(arena, minimal_valid_json, "\"prefix\": \"nsc_core_\"", "\"prefix\": \"nsc_core_\\u0000\"");
2502
+ try expectRefusal(nul, "abi.prefix", "cannot appear in a linker symbol name");
2503
+ const digit = try replaced(arena, minimal_valid_json, "\"prefix\": \"nsc_core_\"", "\"prefix\": \"9core_\"");
2504
+ try expectRefusal(digit, "abi.prefix", "cannot appear in a linker symbol name");
2505
+ const space = try replaced(arena, minimal_valid_json, "\"prefix\": \"nsc_core_\"", "\"prefix\": \"nsc core \"");
2506
+ try expectRefusal(space, "abi.prefix", "cannot appear in a linker symbol name");
2507
+ }