@native-sdk/cli 0.5.3 → 0.6.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 (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -0,0 +1,689 @@
1
+ //! Session blob store: content-addressed payload storage beside the
2
+ //! session journal.
3
+ //!
4
+ //! Some effect results are too big — and too binary — to inline in
5
+ //! journal records: an image load's ENCODED source bytes are the whole
6
+ //! effect result, and replaying them byte-identically is the point. So
7
+ //! the journal record carries only a content address (the first 16
8
+ //! bytes of the payload's SHA-256, the `audioCachePath` hashing
9
+ //! convention) plus the length, and the bytes live as one file per
10
+ //! distinct payload under `blobs/` next to the journal file:
11
+ //!
12
+ //! <session_dir>/session.journal
13
+ //! <session_dir>/blobs/<32-hex-chars>
14
+ //!
15
+ //! Content addressing gives deduplication for free — recording the same
16
+ //! bytes twice (a cache hit replaying the same image, two loads of one
17
+ //! asset) writes one blob — and makes the store verifiable at BOTH
18
+ //! ends: replay re-hashes what it reads and refuses a store whose bytes
19
+ //! do not match their name, and recording's dedup probe reads the
20
+ //! existing file back before trusting it, repairing a mismatch in place
21
+ //! through the same atomic install a fresh write uses. A damaged blob
22
+ //! is a repairable state while the true bytes are in hand — recording
23
+ //! self-heals it instead of sealing a journal that replay must refuse.
24
+ //!
25
+ //! Two type-erased seams keep the recorder and replayer storage-
26
+ //! agnostic: `SessionBlobSink` (recording) and `SessionBlobSource`
27
+ //! (replay). `DirBlobStore` backs them with a directory over `std.Io`
28
+ //! (the app runner's wiring); `MemoryBlobStore` backs them in memory
29
+ //! for tests.
30
+
31
+ const std = @import("std");
32
+ const runtime_effects = @import("effects.zig");
33
+
34
+ const blob_log = std.log.scoped(.zero_session_blobs);
35
+
36
+ /// Bytes of a blob's content address (SHA-256 prefix); hex-encoded it
37
+ /// is the blob's file name.
38
+ pub const hash_len: usize = runtime_effects.effect_image_blob_hash_len;
39
+
40
+ /// The largest payload one blob may hold — the largest journaled effect
41
+ /// payload that goes out of line (an image load's encoded source).
42
+ pub const max_blob_bytes: usize = runtime_effects.max_effect_image_bytes;
43
+
44
+ pub const BlobHash = [hash_len]u8;
45
+
46
+ /// Content address of `bytes`.
47
+ pub fn hashBytes(bytes: []const u8) BlobHash {
48
+ var digest: [32]u8 = undefined;
49
+ std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{});
50
+ return digest[0..hash_len].*;
51
+ }
52
+
53
+ /// A blob's file name: the address in lowercase hex, no extension (the
54
+ /// bytes are an opaque payload; decoders sniff content, not names).
55
+ pub fn hexName(hash: BlobHash) [hash_len * 2]u8 {
56
+ return std.fmt.bytesToHex(hash, .lower);
57
+ }
58
+
59
+ /// The temp path one blob write stages before its atomic rename into
60
+ /// the addressed name. `token` is the write's own random draw, and it
61
+ /// carries the WHOLE writer-uniqueness: the directory is shared between
62
+ /// recorders and the name is the content hash, so every other component
63
+ /// is identical when two recorders write the same blob — a temp built
64
+ /// without the token is one file both writers fight over. The name
65
+ /// stays recognizable install debris (`<hash>.<token>.partial` beside
66
+ /// its blob) for a hard crash to leave behind. A pure formatter: the
67
+ /// entropy lives with the caller.
68
+ fn blobPartialPath(buffer: []u8, dir_path: []const u8, name: []const u8, token: u64) ![]const u8 {
69
+ return std.fmt.bufPrint(buffer, "{s}/{s}.{x:0>16}.partial", .{ dir_path, name, token });
70
+ }
71
+
72
+ pub const BlobError = error{
73
+ /// The store has no blob under this address — the journal names
74
+ /// bytes the store never received (a moved journal without its
75
+ /// blobs directory, or a damaged store).
76
+ BlobMissing,
77
+ /// The stored bytes do not hash to their address, or their length
78
+ /// disagrees with the journal record: the store was damaged or
79
+ /// hand-edited.
80
+ BlobCorrupt,
81
+ /// The blob claims a payload beyond `max_blob_bytes`.
82
+ BlobOverBudget,
83
+ /// The store could not be written (recording) or read (replay).
84
+ BlobIoFailed,
85
+ };
86
+
87
+ /// Where recorded blobs go. `write_fn` must be idempotent per address —
88
+ /// content addressing means a repeat write of the same bytes is a no-op
89
+ /// by construction, and implementations should skip the copy AFTER
90
+ /// verifying the stored bytes really are these bytes (a damaged blob is
91
+ /// repaired from the bytes in hand, never trusted by name).
92
+ pub const SessionBlobSink = struct {
93
+ context: *anyopaque,
94
+ write_fn: *const fn (context: *anyopaque, hash: BlobHash, bytes: []const u8) BlobError!void,
95
+ };
96
+
97
+ /// Where replayed blobs come from. `read_fn` fills `buffer` and returns
98
+ /// the blob's bytes (a prefix of `buffer`); implementations verify the
99
+ /// content hash before answering.
100
+ pub const SessionBlobSource = struct {
101
+ context: *anyopaque,
102
+ read_fn: *const fn (context: *anyopaque, hash: BlobHash, buffer: []u8) BlobError![]const u8,
103
+ };
104
+
105
+ /// A directory-backed blob store over `std.Io` — the app runner's
106
+ /// implementation for both recording and replay. Writes are atomic
107
+ /// (beside-then-rename, the cache-install discipline) and deduplicated
108
+ /// by a VERIFYING probe — an existing file under the address is read
109
+ /// back and must hold exactly the incoming bytes, or the write repairs
110
+ /// it in place; reads re-hash and refuse mismatches.
111
+ ///
112
+ /// The directory is a SHARED medium: two recorders (two app processes,
113
+ /// or two stores in one process) may write the same blob into one
114
+ /// blobs/ directory concurrently. Two disciplines keep that safe:
115
+ /// every write stages through a WRITER-unique temp (a random token in
116
+ /// the name — a temp named by the hash alone would be one file both
117
+ /// writers truncate and rename out from under each other), and a
118
+ /// rename that still fails gets the content-addressed grace — when the
119
+ /// addressed name already holds exactly the bytes being written, some
120
+ /// writer won with THIS content, so the write succeeded (only a
121
+ /// verified mismatch or absence stays `BlobIoFailed`).
122
+ pub const DirBlobStore = struct {
123
+ io: std.Io,
124
+ dir_storage: [max_dir_bytes]u8 = undefined,
125
+ dir_len: usize = 0,
126
+
127
+ pub const max_dir_bytes: usize = 1024;
128
+
129
+ pub fn init(io: std.Io, dir_path: []const u8) error{BlobDirTooLong}!DirBlobStore {
130
+ if (dir_path.len == 0 or dir_path.len > max_dir_bytes) return error.BlobDirTooLong;
131
+ var store: DirBlobStore = .{ .io = io };
132
+ @memcpy(store.dir_storage[0..dir_path.len], dir_path);
133
+ store.dir_len = dir_path.len;
134
+ return store;
135
+ }
136
+
137
+ pub fn dir(self: *const DirBlobStore) []const u8 {
138
+ return self.dir_storage[0..self.dir_len];
139
+ }
140
+
141
+ pub fn sink(self: *DirBlobStore) SessionBlobSink {
142
+ return .{ .context = self, .write_fn = writeErased };
143
+ }
144
+
145
+ pub fn source(self: *DirBlobStore) SessionBlobSource {
146
+ return .{ .context = self, .read_fn = readErased };
147
+ }
148
+
149
+ pub fn write(self: *DirBlobStore, hash: BlobHash, bytes: []const u8) BlobError!void {
150
+ if (bytes.len > max_blob_bytes) return error.BlobOverBudget;
151
+ const cwd = std.Io.Dir.cwd();
152
+ var path_buffer: [max_dir_bytes + hash_len * 2 + 16]u8 = undefined;
153
+ const name = hexName(hash);
154
+ const blob_path = std.fmt.bufPrint(&path_buffer, "{s}/{s}", .{ self.dir(), name }) catch return error.BlobIoFailed;
155
+ // Content addressing dedups by name, but recording never TRUSTS
156
+ // the name alone: replay verifies what it reads, so a damaged
157
+ // blob accepted here would seal a journal replay must refuse.
158
+ // The probe reads the existing file back (bounded by the bytes
159
+ // in hand, themselves under max_blob_bytes) and skips the write
160
+ // only on an exact match; anything else — damage, truncation,
161
+ // an unreadable file — is a repairable state while the true
162
+ // bytes are right here, so it falls through to the same atomic
163
+ // partial+rename a fresh write uses. Cost: a dedup hit is one
164
+ // bounded read instead of one existence probe.
165
+ switch (self.probeExisting(blob_path, bytes)) {
166
+ .matches => return,
167
+ .absent => {},
168
+ .mismatch => blob_log.debug("blob {s} does not hold its addressed bytes; repairing in place", .{name}),
169
+ }
170
+ cwd.createDirPath(self.io, self.dir()) catch return error.BlobIoFailed;
171
+ // The temp name must be WRITER-unique, not merely blob-unique:
172
+ // two recorders sharing one blobs/ directory write the same
173
+ // blob under the same hash, and a temp named by the hash alone
174
+ // is ONE file both writers truncate mid-write and rename out
175
+ // from under each other (the loser's rename then fails a
176
+ // correct recording). The token is the write's own random draw
177
+ // from the store's io (the CSPRNG seam the executor's cache
178
+ // installs already use), unique across stores and processes
179
+ // alike.
180
+ var token_bytes: [8]u8 = undefined;
181
+ self.io.random(&token_bytes);
182
+ const token = std.mem.readInt(u64, &token_bytes, .little);
183
+ var partial_buffer: [max_dir_bytes + hash_len * 2 + 48]u8 = undefined;
184
+ const partial_path = blobPartialPath(&partial_buffer, self.dir(), &name, token) catch return error.BlobIoFailed;
185
+ cwd.writeFile(self.io, .{ .sub_path = partial_path, .data = bytes }) catch {
186
+ cwd.deleteFile(self.io, partial_path) catch {};
187
+ return error.BlobIoFailed;
188
+ };
189
+ return self.installPartial(partial_path, blob_path, bytes);
190
+ }
191
+
192
+ /// The atomic tail of `write`: rename the writer-unique temp into
193
+ /// the blob's addressed name. A failed rename is not yet a failed
194
+ /// WRITE — the store is content-addressed, so if the addressed name
195
+ /// already holds exactly these bytes, a concurrent writer won the
196
+ /// install with the same content and this write SUCCEEDED (its
197
+ /// bytes are durable under their address; only who renamed them
198
+ /// there differs). Re-running the verifying probe decides: a match
199
+ /// returns cleanly, a verified mismatch or absence is the honest
200
+ /// `BlobIoFailed`. The loser's temp is deleted on every failure
201
+ /// path so no `.partial` debris outlives the write.
202
+ fn installPartial(self: *DirBlobStore, partial_path: []const u8, blob_path: []const u8, bytes: []const u8) BlobError!void {
203
+ const cwd = std.Io.Dir.cwd();
204
+ cwd.rename(partial_path, cwd, blob_path, self.io) catch {
205
+ defer cwd.deleteFile(self.io, partial_path) catch {};
206
+ switch (self.probeExisting(blob_path, bytes)) {
207
+ .matches => return,
208
+ .absent, .mismatch => return error.BlobIoFailed,
209
+ }
210
+ };
211
+ }
212
+
213
+ const ProbeResult = enum { absent, matches, mismatch };
214
+
215
+ /// The verifying half of the dedup probe: whether the file at
216
+ /// `blob_path` holds exactly `bytes`. Compared chunk-wise against
217
+ /// the incoming bytes (equality against the caller's bytes IS the
218
+ /// hash check — their address is the file's name), so no
219
+ /// blob-sized buffer is ever staged. A read failure mid-probe
220
+ /// counts as a mismatch: the repair path rewrites the file whole.
221
+ fn probeExisting(self: *DirBlobStore, blob_path: []const u8, bytes: []const u8) ProbeResult {
222
+ var file = std.Io.Dir.cwd().openFile(self.io, blob_path, .{}) catch return .absent;
223
+ defer file.close(self.io);
224
+ var chunk: [4096]u8 = undefined;
225
+ var at: usize = 0;
226
+ while (true) {
227
+ const len = file.readPositionalAll(self.io, &chunk, at) catch return .mismatch;
228
+ if (len == 0) break;
229
+ if (at + len > bytes.len) return .mismatch;
230
+ if (!std.mem.eql(u8, chunk[0..len], bytes[at .. at + len])) return .mismatch;
231
+ at += len;
232
+ if (len < chunk.len) break;
233
+ }
234
+ return if (at == bytes.len) .matches else .mismatch;
235
+ }
236
+
237
+ pub fn read(self: *DirBlobStore, hash: BlobHash, buffer: []u8) BlobError![]const u8 {
238
+ const cwd = std.Io.Dir.cwd();
239
+ var path_buffer: [max_dir_bytes + hash_len * 2 + 16]u8 = undefined;
240
+ const name = hexName(hash);
241
+ const blob_path = std.fmt.bufPrint(&path_buffer, "{s}/{s}", .{ self.dir(), name }) catch return error.BlobIoFailed;
242
+ var file = cwd.openFile(self.io, blob_path, .{}) catch return error.BlobMissing;
243
+ defer file.close(self.io);
244
+ const len = file.readPositionalAll(self.io, buffer, 0) catch return error.BlobIoFailed;
245
+ if (len == buffer.len) {
246
+ // A full buffer is ambiguous: `readPositionalAll` stops at
247
+ // `buffer.len`, so the blob is either exactly buffer-sized
248
+ // (the designed case — callers size the buffer from the
249
+ // journal record's byte length) or larger. Probe one byte
250
+ // past the end to tell them apart — the effects layer's
251
+ // one-spare-byte idiom, and a probe rather than a stat so
252
+ // no size/read race can disagree with what was just read.
253
+ var spare: [1]u8 = undefined;
254
+ const extra = file.readPositionalAll(self.io, &spare, buffer.len) catch return error.BlobIoFailed;
255
+ if (extra != 0) return error.BlobOverBudget;
256
+ }
257
+ const bytes = buffer[0..len];
258
+ if (!std.mem.eql(u8, &hashBytes(bytes), &hash)) return error.BlobCorrupt;
259
+ return bytes;
260
+ }
261
+
262
+ fn writeErased(context: *anyopaque, hash: BlobHash, bytes: []const u8) BlobError!void {
263
+ const self: *DirBlobStore = @ptrCast(@alignCast(context));
264
+ return self.write(hash, bytes);
265
+ }
266
+
267
+ fn readErased(context: *anyopaque, hash: BlobHash, buffer: []u8) BlobError![]const u8 {
268
+ const self: *DirBlobStore = @ptrCast(@alignCast(context));
269
+ return self.read(hash, buffer);
270
+ }
271
+ };
272
+
273
+ /// An in-memory blob store for tests: allocator-backed, bounded, and
274
+ /// honest about capacity. Write dedups by address with the directory
275
+ /// store's verifying probe (an entry that no longer holds its
276
+ /// addressed bytes is repaired in place); read verifies the hash like
277
+ /// the directory store, so a test store misbehaves exactly as loudly
278
+ /// as the real one. The directory store's two-writer race has no
279
+ /// analogue here: this store's medium is its own `entries` array, not
280
+ /// a shared directory — two recorders can never address one
281
+ /// MemoryBlobStore from two processes, and within one process each
282
+ /// recorder's sink drives its own store instance on its own thread —
283
+ /// so there is no shared temp to fight over and no rename to lose.
284
+ pub const MemoryBlobStore = struct {
285
+ allocator: std.mem.Allocator,
286
+ entries: [max_entries]Entry = undefined,
287
+ count: usize = 0,
288
+ /// How many writes found their address already present — the dedup
289
+ /// evidence tests assert on.
290
+ dedup_hits: usize = 0,
291
+
292
+ pub const max_entries: usize = 32;
293
+
294
+ const Entry = struct {
295
+ hash: BlobHash,
296
+ bytes: []u8,
297
+ };
298
+
299
+ pub fn init(allocator: std.mem.Allocator) MemoryBlobStore {
300
+ return .{ .allocator = allocator };
301
+ }
302
+
303
+ pub fn deinit(self: *MemoryBlobStore) void {
304
+ for (self.entries[0..self.count]) |entry| self.allocator.free(entry.bytes);
305
+ self.count = 0;
306
+ }
307
+
308
+ pub fn sink(self: *MemoryBlobStore) SessionBlobSink {
309
+ return .{ .context = self, .write_fn = writeErased };
310
+ }
311
+
312
+ pub fn source(self: *MemoryBlobStore) SessionBlobSource {
313
+ return .{ .context = self, .read_fn = readErased };
314
+ }
315
+
316
+ pub fn write(self: *MemoryBlobStore, hash: BlobHash, bytes: []const u8) BlobError!void {
317
+ if (bytes.len > max_blob_bytes) return error.BlobOverBudget;
318
+ if (self.find(hash)) |entry| {
319
+ // The dir store's verifying dedup, in memory: an entry that
320
+ // still holds its addressed bytes is the dedup hit; one
321
+ // that no longer does (a tampering test — the dir store's
322
+ // damaged-file case) is repaired in place rather than
323
+ // trusted or refused.
324
+ if (std.mem.eql(u8, entry.bytes, bytes)) {
325
+ self.dedup_hits += 1;
326
+ return;
327
+ }
328
+ const copy = self.allocator.dupe(u8, bytes) catch return error.BlobIoFailed;
329
+ self.allocator.free(entry.bytes);
330
+ entry.bytes = copy;
331
+ return;
332
+ }
333
+ if (self.count == max_entries) return error.BlobIoFailed;
334
+ const copy = self.allocator.dupe(u8, bytes) catch return error.BlobIoFailed;
335
+ self.entries[self.count] = .{ .hash = hash, .bytes = copy };
336
+ self.count += 1;
337
+ }
338
+
339
+ pub fn read(self: *MemoryBlobStore, hash: BlobHash, buffer: []u8) BlobError![]const u8 {
340
+ const entry = self.find(hash) orelse return error.BlobMissing;
341
+ if (entry.bytes.len > buffer.len) return error.BlobOverBudget;
342
+ @memcpy(buffer[0..entry.bytes.len], entry.bytes);
343
+ const bytes = buffer[0..entry.bytes.len];
344
+ if (!std.mem.eql(u8, &hashBytes(bytes), &hash)) return error.BlobCorrupt;
345
+ return bytes;
346
+ }
347
+
348
+ fn find(self: *MemoryBlobStore, hash: BlobHash) ?*Entry {
349
+ for (self.entries[0..self.count]) |*entry| {
350
+ if (std.mem.eql(u8, &entry.hash, &hash)) return entry;
351
+ }
352
+ return null;
353
+ }
354
+
355
+ fn writeErased(context: *anyopaque, hash: BlobHash, bytes: []const u8) BlobError!void {
356
+ const self: *MemoryBlobStore = @ptrCast(@alignCast(context));
357
+ return self.write(hash, bytes);
358
+ }
359
+
360
+ fn readErased(context: *anyopaque, hash: BlobHash, buffer: []u8) BlobError![]const u8 {
361
+ const self: *MemoryBlobStore = @ptrCast(@alignCast(context));
362
+ return self.read(hash, buffer);
363
+ }
364
+ };
365
+
366
+ // -------------------------------------------------------------- tests
367
+
368
+ const testing = std.testing;
369
+
370
+ test "content addresses are stable and hex names filesystem-safe" {
371
+ const hash = hashBytes("the same bytes");
372
+ try testing.expectEqualSlices(u8, &hash, &hashBytes("the same bytes"));
373
+ try testing.expect(!std.mem.eql(u8, &hash, &hashBytes("different bytes")));
374
+ const name = hexName(hash);
375
+ for (name) |char| {
376
+ try testing.expect((char >= '0' and char <= '9') or (char >= 'a' and char <= 'f'));
377
+ }
378
+ }
379
+
380
+ test "memory store round-trips, dedups identical bytes, and refuses damage" {
381
+ var store = MemoryBlobStore.init(testing.allocator);
382
+ defer store.deinit();
383
+
384
+ const bytes = "png bytes, say";
385
+ const hash = hashBytes(bytes);
386
+ try store.write(hash, bytes);
387
+ try store.write(hash, bytes);
388
+ try testing.expectEqual(@as(usize, 1), store.count);
389
+ try testing.expectEqual(@as(usize, 1), store.dedup_hits);
390
+
391
+ var buffer: [64]u8 = undefined;
392
+ const read_back = try store.read(hash, &buffer);
393
+ try testing.expectEqualStrings(bytes, read_back);
394
+
395
+ try testing.expectError(error.BlobMissing, store.read(hashBytes("never written"), &buffer));
396
+ // A tampered entry no longer hashes to its address.
397
+ store.entries[0].bytes[0] ^= 0x40;
398
+ try testing.expectError(error.BlobCorrupt, store.read(hash, &buffer));
399
+ }
400
+
401
+ test "memory store repairs a tampered entry on the next same-bytes write" {
402
+ var store = MemoryBlobStore.init(testing.allocator);
403
+ defer store.deinit();
404
+
405
+ const bytes = "encoded image bytes";
406
+ const hash = hashBytes(bytes);
407
+ try store.write(hash, bytes);
408
+ store.entries[0].bytes[0] ^= 0x40;
409
+ var buffer: [64]u8 = undefined;
410
+ try testing.expectError(error.BlobCorrupt, store.read(hash, &buffer));
411
+
412
+ // Recording the same bytes again finds the address occupied but
413
+ // VERIFIES before trusting it: the damaged entry heals in place
414
+ // (no dedup hit — a repair is not a dedup), and replay succeeds.
415
+ try store.write(hash, bytes);
416
+ try testing.expectEqual(@as(usize, 0), store.dedup_hits);
417
+ try testing.expectEqual(@as(usize, 1), store.count);
418
+ const read_back = try store.read(hash, &buffer);
419
+ try testing.expectEqualStrings(bytes, read_back);
420
+ }
421
+
422
+ test "dir store writes atomically, dedups by existence, and verifies on read" {
423
+ var tmp = testing.tmpDir(.{});
424
+ defer tmp.cleanup();
425
+ const io = testing.io;
426
+
427
+ var dir_buffer: [256]u8 = undefined;
428
+ const dir_path = try std.fmt.bufPrint(&dir_buffer, ".zig-cache/tmp/{s}/blobs", .{tmp.sub_path[0..]});
429
+ var store = try DirBlobStore.init(io, dir_path);
430
+
431
+ const bytes = "encoded image bytes";
432
+ const hash = hashBytes(bytes);
433
+ try store.write(hash, bytes);
434
+ try store.write(hash, bytes);
435
+
436
+ var read_buffer: [4096]u8 = undefined;
437
+ const read_back = try store.read(hash, &read_buffer);
438
+ try testing.expectEqualStrings(bytes, read_back);
439
+
440
+ // Exactly one blob file, no .partial debris.
441
+ var blob_dir = try tmp.dir.openDir(io, "blobs", .{ .iterate = true });
442
+ defer blob_dir.close(io);
443
+ var iterator = blob_dir.iterate();
444
+ var file_count: usize = 0;
445
+ while (try iterator.next(io)) |entry| {
446
+ try testing.expect(!std.mem.endsWith(u8, entry.name, ".partial"));
447
+ file_count += 1;
448
+ }
449
+ try testing.expectEqual(@as(usize, 1), file_count);
450
+
451
+ try testing.expectError(error.BlobMissing, store.read(hashBytes("absent"), &read_buffer));
452
+
453
+ // Damaged bytes are refused, never returned as the payload.
454
+ const name = hexName(hash);
455
+ var damaged: [64]u8 = undefined;
456
+ @memcpy(damaged[0..bytes.len], bytes);
457
+ damaged[0] ^= 0x40;
458
+ var path_buffer: [300]u8 = undefined;
459
+ const rel = try std.fmt.bufPrint(&path_buffer, "blobs/{s}", .{name});
460
+ try tmp.dir.writeFile(io, .{ .sub_path = rel, .data = damaged[0..bytes.len] });
461
+ try testing.expectError(error.BlobCorrupt, store.read(hash, &read_buffer));
462
+ }
463
+
464
+ test "both stores accept an exact-fit buffer and refuse one byte under" {
465
+ // The SessionBlobSource contract lets callers size the buffer from
466
+ // the journal record's byte length — an exact-fit read is the
467
+ // designed case, not an over-budget one. Over-budget is a buffer
468
+ // the blob does NOT fit in, even by one byte.
469
+ var tmp = testing.tmpDir(.{});
470
+ defer tmp.cleanup();
471
+ const io = testing.io;
472
+
473
+ var dir_buffer: [256]u8 = undefined;
474
+ const dir_path = try std.fmt.bufPrint(&dir_buffer, ".zig-cache/tmp/{s}/blobs", .{tmp.sub_path[0..]});
475
+ var dir_store = try DirBlobStore.init(io, dir_path);
476
+
477
+ const bytes = "encoded image bytes";
478
+ const hash = hashBytes(bytes);
479
+ try dir_store.write(hash, bytes);
480
+
481
+ var buffer: [bytes.len]u8 = undefined;
482
+ try testing.expectEqualStrings(bytes, try dir_store.read(hash, &buffer));
483
+ try testing.expectError(error.BlobOverBudget, dir_store.read(hash, buffer[0 .. bytes.len - 1]));
484
+
485
+ // Store parity: the memory store answers the same three sizes the
486
+ // same way, so a test against it exercises the real contract.
487
+ var memory_store = MemoryBlobStore.init(testing.allocator);
488
+ defer memory_store.deinit();
489
+ try memory_store.write(hash, bytes);
490
+ try testing.expectEqualStrings(bytes, try memory_store.read(hash, &buffer));
491
+ try testing.expectError(error.BlobOverBudget, memory_store.read(hash, buffer[0 .. bytes.len - 1]));
492
+ }
493
+
494
+ test "an exact-fit read of damaged bytes is BlobCorrupt, not BlobOverBudget" {
495
+ // The budget check must not mask corruption detection: a blob that
496
+ // fills the buffer exactly still gets re-hashed, and damage is
497
+ // reported as damage.
498
+ var tmp = testing.tmpDir(.{});
499
+ defer tmp.cleanup();
500
+ const io = testing.io;
501
+
502
+ var dir_buffer: [256]u8 = undefined;
503
+ const dir_path = try std.fmt.bufPrint(&dir_buffer, ".zig-cache/tmp/{s}/blobs", .{tmp.sub_path[0..]});
504
+ var dir_store = try DirBlobStore.init(io, dir_path);
505
+
506
+ const bytes = "encoded image bytes";
507
+ const hash = hashBytes(bytes);
508
+ try dir_store.write(hash, bytes);
509
+ var damaged: [bytes.len]u8 = undefined;
510
+ @memcpy(&damaged, bytes);
511
+ damaged[0] ^= 0x40;
512
+ const name = hexName(hash);
513
+ var path_buffer: [300]u8 = undefined;
514
+ const rel = try std.fmt.bufPrint(&path_buffer, "blobs/{s}", .{name});
515
+ try tmp.dir.writeFile(io, .{ .sub_path = rel, .data = &damaged });
516
+
517
+ var buffer: [bytes.len]u8 = undefined;
518
+ try testing.expectError(error.BlobCorrupt, dir_store.read(hash, &buffer));
519
+
520
+ var memory_store = MemoryBlobStore.init(testing.allocator);
521
+ defer memory_store.deinit();
522
+ try memory_store.write(hash, bytes);
523
+ memory_store.entries[0].bytes[0] ^= 0x40;
524
+ try testing.expectError(error.BlobCorrupt, memory_store.read(hash, &buffer));
525
+ }
526
+
527
+ test "two recorders sharing one blobs directory both record the same blob successfully" {
528
+ var tmp = testing.tmpDir(.{});
529
+ defer tmp.cleanup();
530
+ const io = testing.io;
531
+
532
+ var dir_buffer: [256]u8 = undefined;
533
+ const dir_path = try std.fmt.bufPrint(&dir_buffer, ".zig-cache/tmp/{s}/blobs", .{tmp.sub_path[0..]});
534
+
535
+ // Two DirBlobStore INSTANCES over one directory — the designed
536
+ // shared layout when two recorders journal into one session
537
+ // directory. Both write the same bytes (the same image loaded in
538
+ // both recordings addresses the same blob) and BOTH writes must
539
+ // succeed: a failure here invalidates a correct recording.
540
+ var first_recorder = try DirBlobStore.init(io, dir_path);
541
+ var second_recorder = try DirBlobStore.init(io, dir_path);
542
+
543
+ const bytes = "encoded image bytes both sessions loaded";
544
+ const hash = hashBytes(bytes);
545
+ try first_recorder.write(hash, bytes);
546
+ try second_recorder.write(hash, bytes);
547
+
548
+ // One intact blob, readable through either store, zero temp debris.
549
+ var read_buffer: [4096]u8 = undefined;
550
+ try testing.expectEqualStrings(bytes, try first_recorder.read(hash, &read_buffer));
551
+ try testing.expectEqualStrings(bytes, try second_recorder.read(hash, &read_buffer));
552
+ var blob_dir = try tmp.dir.openDir(io, "blobs", .{ .iterate = true });
553
+ defer blob_dir.close(io);
554
+ var iterator = blob_dir.iterate();
555
+ var file_count: usize = 0;
556
+ while (try iterator.next(io)) |entry| {
557
+ try testing.expect(!std.mem.endsWith(u8, entry.name, ".partial"));
558
+ file_count += 1;
559
+ }
560
+ try testing.expectEqual(@as(usize, 1), file_count);
561
+ }
562
+
563
+ test "blob write temps are writer-unique, so concurrent recorders never share one" {
564
+ // Two writes of the same blob into the same directory agree on
565
+ // every name component except the token: dir (shared layout), name
566
+ // (the content hash). A temp built without the token would be ONE
567
+ // file both writers truncate mid-write and rename out from under
568
+ // each other — the loser's rename fails and a correct recording is
569
+ // refused. The token carries the whole uniqueness, so this pin
570
+ // fails if it ever leaves the name.
571
+ var first_buffer: [256]u8 = undefined;
572
+ var second_buffer: [256]u8 = undefined;
573
+ const name = "aabbccddeeff00112233445566778899";
574
+ const first = try blobPartialPath(&first_buffer, "session/blobs", name, 0x1111);
575
+ const second = try blobPartialPath(&second_buffer, "session/blobs", name, 0x2222);
576
+ try testing.expect(!std.mem.eql(u8, first, second));
577
+ // Both stay recognizable install debris beside their blob.
578
+ try testing.expect(std.mem.startsWith(u8, first, "session/blobs/aabbccddeeff00112233445566778899."));
579
+ try testing.expect(std.mem.endsWith(u8, first, ".partial"));
580
+ try testing.expect(std.mem.endsWith(u8, second, ".partial"));
581
+ }
582
+
583
+ test "a losing writer's failed rename succeeds through the content-addressed grace" {
584
+ var tmp = testing.tmpDir(.{});
585
+ defer tmp.cleanup();
586
+ const io = testing.io;
587
+
588
+ var dir_buffer: [256]u8 = undefined;
589
+ const dir_path = try std.fmt.bufPrint(&dir_buffer, ".zig-cache/tmp/{s}/blobs", .{tmp.sub_path[0..]});
590
+ var winner = try DirBlobStore.init(io, dir_path);
591
+ var loser = try DirBlobStore.init(io, dir_path);
592
+
593
+ const bytes = "encoded image bytes";
594
+ const hash = hashBytes(bytes);
595
+ const name = hexName(hash);
596
+ var blob_path_buffer: [512]u8 = undefined;
597
+ const blob_path = try std.fmt.bufPrint(&blob_path_buffer, "{s}/{s}", .{ dir_path, name });
598
+ var partial_buffer: [512]u8 = undefined;
599
+ const partial_path = try blobPartialPath(&partial_buffer, dir_path, &name, 0xdead);
600
+
601
+ // The loser's exact state at the rename boundary, staged directly
602
+ // (one `write` call cannot be paused mid-window, so the window is
603
+ // pinned at the install seam): its probe saw the address ABSENT,
604
+ // the winner then installed the addressed bytes, and the loser's
605
+ // rename fails (here: the temp is gone — the shared-name theft this
606
+ // fix's unique tokens prevent, and the one rename failure POSIX
607
+ // makes deterministic). The bytes ARE durable under their address,
608
+ // so the write must report success, not refuse a correct recording.
609
+ try winner.write(hash, bytes);
610
+ try loser.installPartial(partial_path, blob_path, bytes);
611
+ var read_buffer: [4096]u8 = undefined;
612
+ try testing.expectEqualStrings(bytes, try loser.read(hash, &read_buffer));
613
+
614
+ // The grace VERIFIES: an address occupied by different bytes means
615
+ // the write's bytes are NOT durable — that stays BlobIoFailed
616
+ // (write's earlier repair path handles mismatches while the rename
617
+ // can still deliver; here it cannot).
618
+ const other = "different bytes at the same staged path";
619
+ try testing.expectError(error.BlobIoFailed, loser.installPartial(partial_path, blob_path, other));
620
+
621
+ // ...and an absent address after a failed rename is a plain failed
622
+ // write.
623
+ var absent_path_buffer: [512]u8 = undefined;
624
+ const absent_name = hexName(hashBytes(other));
625
+ const absent_path = try std.fmt.bufPrint(&absent_path_buffer, "{s}/{s}", .{ dir_path, absent_name });
626
+ var absent_partial_buffer: [512]u8 = undefined;
627
+ const absent_partial = try blobPartialPath(&absent_partial_buffer, dir_path, &absent_name, 0xbeef);
628
+ try testing.expectError(error.BlobIoFailed, loser.installPartial(absent_partial, absent_path, other));
629
+
630
+ // No temp debris outlives any of it.
631
+ var blob_dir = try tmp.dir.openDir(io, "blobs", .{ .iterate = true });
632
+ defer blob_dir.close(io);
633
+ var iterator = blob_dir.iterate();
634
+ var file_count: usize = 0;
635
+ while (try iterator.next(io)) |entry| {
636
+ try testing.expect(!std.mem.endsWith(u8, entry.name, ".partial"));
637
+ file_count += 1;
638
+ }
639
+ try testing.expectEqual(@as(usize, 1), file_count);
640
+ }
641
+
642
+ test "dir store verifies the dedup probe and repairs a damaged blob in place" {
643
+ var tmp = testing.tmpDir(.{});
644
+ defer tmp.cleanup();
645
+ const io = testing.io;
646
+
647
+ var dir_buffer: [256]u8 = undefined;
648
+ const dir_path = try std.fmt.bufPrint(&dir_buffer, ".zig-cache/tmp/{s}/blobs", .{tmp.sub_path[0..]});
649
+ var store = try DirBlobStore.init(io, dir_path);
650
+
651
+ const bytes = "encoded image bytes";
652
+ const hash = hashBytes(bytes);
653
+ const name = hexName(hash);
654
+ var path_buffer: [300]u8 = undefined;
655
+ const rel = try std.fmt.bufPrint(&path_buffer, "blobs/{s}", .{name});
656
+ try store.write(hash, bytes);
657
+
658
+ // Flip one byte on disk: the blob's name lies about its content.
659
+ // Without the true bytes in hand this is replay's BlobCorrupt; the
660
+ // next same-bytes RECORDING has them, so the dedup probe detects
661
+ // the mismatch and repairs in place instead of sealing a journal
662
+ // replay must refuse.
663
+ var damaged: [64]u8 = undefined;
664
+ @memcpy(damaged[0..bytes.len], bytes);
665
+ damaged[3] ^= 0x40;
666
+ try tmp.dir.writeFile(io, .{ .sub_path = rel, .data = damaged[0..bytes.len] });
667
+ var read_buffer: [4096]u8 = undefined;
668
+ try testing.expectError(error.BlobCorrupt, store.read(hash, &read_buffer));
669
+ try store.write(hash, bytes);
670
+ try testing.expectEqualStrings(bytes, try store.read(hash, &read_buffer));
671
+
672
+ // A truncated blob (a different length, not just different bytes)
673
+ // repairs the same way.
674
+ try tmp.dir.writeFile(io, .{ .sub_path = rel, .data = bytes[0 .. bytes.len - 3] });
675
+ try store.write(hash, bytes);
676
+ try testing.expectEqualStrings(bytes, try store.read(hash, &read_buffer));
677
+
678
+ // The repair went through the atomic partial+rename path: exactly
679
+ // one blob file, no .partial debris.
680
+ var blob_dir = try tmp.dir.openDir(io, "blobs", .{ .iterate = true });
681
+ defer blob_dir.close(io);
682
+ var iterator = blob_dir.iterate();
683
+ var file_count: usize = 0;
684
+ while (try iterator.next(io)) |entry| {
685
+ try testing.expect(!std.mem.endsWith(u8, entry.name, ".partial"));
686
+ file_count += 1;
687
+ }
688
+ try testing.expectEqual(@as(usize, 1), file_count);
689
+ }