@native-sdk/cli 0.8.4 → 0.9.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 (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1847 -16
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +82 -16
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. package/tools/corewire/sidecar.zig +26 -15
@@ -74,10 +74,24 @@ const canvas_limits = @import("canvas_limits.zig");
74
74
  const platform = @import("../platform/root.zig");
75
75
  const validation = @import("validation.zig");
76
76
  const runtime_clock = @import("clock.zig");
77
+ const persist_store = @import("persist_store.zig");
78
+ const record_store = @import("record_store.zig");
79
+ const relational_store = @import("relational_store.zig");
80
+ const credentials_store = @import("credentials_store.zig");
77
81
  const pty_transport = @import("pty.zig");
78
82
 
79
83
  /// Maximum in-flight effects (spawn slots / worker threads).
80
84
  pub const max_effects: usize = 16;
85
+ /// Record-store effects have their own capacity: a large batch or a busy
86
+ /// database cannot consume the spawn/fetch/file family's sixteen slots.
87
+ pub const max_store_effects: usize = 16;
88
+ /// Keychain calls can block while an OS keyring unlocks, so credentials own
89
+ /// a small worker family instead of consuming file/fetch or SQLite slots.
90
+ pub const max_credentials_effects: usize = 4;
91
+ const total_effect_slots: usize = max_effects + max_store_effects + max_credentials_effects;
92
+ /// Relational queries and transactions have their own loop-side capacity;
93
+ /// they never consume file/fetch workers or record-store request slots.
94
+ pub const max_db_effects: usize = 16;
81
95
  /// Maximum argv entries per spawn.
82
96
  pub const max_effect_argv: usize = 16;
83
97
  /// Maximum total bytes across all argv entries of one spawn.
@@ -165,6 +179,81 @@ pub const max_effect_file_path_bytes: usize = 1024;
165
179
  /// write would corrupt the file on disk, which truncation flags cannot
166
180
  /// undo.
167
181
  pub const max_effect_file_bytes: usize = 1024 * 1024;
182
+ /// Model persistence owns a separate payload family and bound; it does not
183
+ /// consume a file-effect slot or inherit the raw-file cap.
184
+ pub const max_effect_persist_snapshot_bytes: usize = persist_store.max_snapshot_bytes;
185
+ pub const EffectPersistOutcome = persist_store.Outcome;
186
+ pub const max_effect_store_key_bytes: usize = record_store.max_key_bytes;
187
+ pub const max_effect_store_value_bytes: usize = record_store.max_value_bytes;
188
+ pub const max_effect_store_batch_entries: usize = record_store.max_batch_entries;
189
+ pub const max_effect_store_batch_bytes: usize = record_store.max_batch_bytes;
190
+ pub const max_effect_store_result_bytes: usize = record_store.max_result_bytes;
191
+ pub const default_effect_store_scan_limit: u32 = record_store.default_scan_limit;
192
+ pub const max_effect_store_scan_limit: u32 = record_store.max_scan_limit;
193
+ pub const EffectStoreOutcome = record_store.Outcome;
194
+ pub const EffectCredentialsOperation = credentials_store.Operation;
195
+ pub const EffectCredentialsOutcome = credentials_store.Outcome;
196
+ /// One terminal from an app-scoped credential effect. Secret bytes exist
197
+ /// only on a successful get and are valid only for the receiving update.
198
+ pub const EffectCredentialsResult = struct {
199
+ key: u64,
200
+ operation: EffectCredentialsOperation,
201
+ outcome: EffectCredentialsOutcome,
202
+ bytes: []const u8 = "",
203
+ };
204
+ pub const CredentialsStoreBinding = credentials_store.Binding;
205
+ pub const max_effect_credentials_key_bytes: usize = credentials_store.max_key_bytes;
206
+ pub const max_effect_credentials_secret_bytes: usize = credentials_store.max_secret_bytes;
207
+ pub const EffectStoreOp = record_store.Operation;
208
+ pub const RecordStoreBinding = record_store.Binding;
209
+ pub const max_effect_db_sql_bytes: usize = relational_store.max_sql_bytes;
210
+ pub const max_effect_db_parameters: usize = relational_store.max_parameters;
211
+ pub const max_effect_db_exec_statements: usize = relational_store.max_exec_statements;
212
+ pub const max_effect_db_parameter_bytes: usize = relational_store.max_parameter_bytes;
213
+ pub const max_effect_db_exec_parameter_bytes: usize = relational_store.max_exec_parameter_bytes;
214
+ pub const default_effect_db_page_rows: usize = relational_store.default_page_rows;
215
+ pub const max_effect_db_page_bytes: usize = relational_store.max_page_bytes;
216
+ pub const max_effect_db_result_rows: usize = relational_store.max_result_rows;
217
+ pub const max_effect_db_result_bytes: usize = relational_store.max_result_bytes;
218
+ pub const max_effect_db_live_tables: usize = relational_store.max_changed_tables;
219
+ pub const EffectDbValue = relational_store.Value;
220
+ pub const EffectDbStatement = relational_store.Statement;
221
+ pub const EffectDbOutcome = relational_store.Outcome;
222
+ pub const RelationalStoreBinding = relational_store.Binding;
223
+
224
+ /// One relational delivery. Queries produce one or more `.page` events and
225
+ /// exactly one `.done`; an exec transaction produces exactly one `.exec`.
226
+ /// A non-ok outcome is terminal regardless of kind and carries no bytes.
227
+ pub const EffectDbResultKind = enum(u8) { page, done, exec };
228
+
229
+ pub const EffectDbResult = struct {
230
+ key: u64,
231
+ kind: EffectDbResultKind,
232
+ outcome: EffectDbOutcome = .ok,
233
+ /// Encoded row page for `.page`; drain scratch, valid through the update
234
+ /// that receives it. Empty for terminal events.
235
+ bytes: []const u8 = "",
236
+ };
237
+
238
+ pub fn dbJournalCode(kind: EffectDbResultKind, outcome: EffectDbOutcome) i32 {
239
+ return @as(i32, @intFromEnum(kind)) | (@as(i32, @intFromEnum(outcome)) << 8);
240
+ }
241
+
242
+ pub fn dbKindFromJournalCode(code: i32) ?EffectDbResultKind {
243
+ return std.enums.fromInt(EffectDbResultKind, @as(u8, @intCast(code & 0xff)));
244
+ }
245
+
246
+ pub fn dbOutcomeFromJournalCode(code: i32) ?EffectDbOutcome {
247
+ return std.enums.fromInt(EffectDbOutcome, @as(u8, @intCast((code >> 8) & 0xff)));
248
+ }
249
+ /// The one boot-time model-restore result delivered to a persistence-enabled
250
+ /// Zig core. Successful bytes contain the generated snapshot body; every
251
+ /// other outcome carries an empty slice. The bytes are instance-lived, so an
252
+ /// app may retain them while decoding or migrating its model.
253
+ pub const EffectPersistResult = struct {
254
+ outcome: EffectPersistOutcome,
255
+ bytes: []const u8 = "",
256
+ };
168
257
  /// How long teardown waits (total, in milliseconds) for file workers
169
258
  /// stuck in blocking I/O before abandoning them — the default of the
170
259
  /// channel's injectable `file_join_deadline_ms`. File I/O is the one
@@ -178,6 +267,12 @@ pub const max_effect_file_bytes: usize = 1024 * 1024;
178
267
  /// meets this bound.
179
268
  pub const default_effect_file_join_deadline_ms: u64 = 15_000;
180
269
 
270
+ /// How long teardown lets an OS credential call remain blocked (for
271
+ /// example behind an interactive keyring unlock) before fencing it off from
272
+ /// the runtime and detaching its worker. The platform is told to preserve
273
+ /// the callback context in that exceptional path.
274
+ pub const default_credentials_join_deadline_ms: u64 = 15_000;
275
+
181
276
  /// Teardown budget for one channel's in-flight host wake call (see
182
277
  /// `Effects.channel_wake_join_deadline_ms` and `quiesceChannelWake`).
183
278
  /// A CONFORMING `wake_fn` is a bounded enqueue that returns in
@@ -269,10 +364,23 @@ pub const WindowActionBinding = struct {
269
364
  context: *anyopaque,
270
365
  close_fn: *const fn (context: *anyopaque, window_label: []const u8) bool,
271
366
  minimize_fn: *const fn (context: *anyopaque, window_label: []const u8) bool,
367
+ hide_fn: *const fn (context: *anyopaque, window_label: []const u8) bool,
272
368
  show_fn: *const fn (context: *anyopaque, window_label: []const u8) bool,
369
+ dock_presence_fn: *const fn (context: *anyopaque, visible: bool) bool,
273
370
  quit_fn: *const fn (context: *anyopaque) bool,
274
371
  };
275
372
 
373
+ /// Runtime-owned platform-service entry points used by the intrinsic
374
+ /// `native-sdk.*` named commands. Binding the Runtime methods—not the raw
375
+ /// PlatformServices table—keeps validation and external-link policy in the
376
+ /// same place for TypeScript effects, Zig callers, and built-in bridge calls.
377
+ pub const SystemServiceBinding = struct {
378
+ context: *anyopaque,
379
+ open_external_url_fn: *const fn (context: *anyopaque, url: []const u8) anyerror!void,
380
+ reveal_path_fn: *const fn (context: *anyopaque, path: []const u8) anyerror!void,
381
+ format_local_time_fn: *const fn (context: *anyopaque, timestamp_ms: i64, style: platform.LocalTimeStyle, buffer: []u8) anyerror![]const u8,
382
+ };
383
+
276
384
  /// Type-erased handle to the embedding host's named-command services,
277
385
  /// bound onto the effects channel (`bindHostCalls`). This is the seam
278
386
  /// behind `hostRequest`/`hostSend` — the generic named host call a
@@ -294,6 +402,33 @@ pub const HostCallBinding = struct {
294
402
  /// cancelled — any late `feedHostResult` for it reports
295
403
  /// `error.EffectNotFound` and delivers nothing.
296
404
  cancel_fn: ?*const fn (context: *anyopaque, key: u64) void = null,
405
+ /// Service transports join the spawn/stream keyed discipline: a second
406
+ /// live request rejects without replacing the first. Legacy embedding
407
+ /// bindings retain the generic host seam's replacement behavior.
408
+ reject_duplicate_keys: bool = false,
409
+ /// Optional worker-carrier completion seam. `bytes` stays valid until
410
+ /// the next poll; Effects copies it immediately on the loop thread.
411
+ poll_fn: ?*const fn (context: *anyopaque) ?HostCallCompletion = null,
412
+ pending_fn: ?*const fn (context: *anyopaque) bool = null,
413
+ /// Supplies the platform's thread-safe wake handle after UiApp binds it.
414
+ bind_services_fn: ?*const fn (context: *anyopaque, services: *const platform.PlatformServices) void = null,
415
+ /// Service transports acquire an already-open external channel on the
416
+ /// loop thread, then retain its thread-safe handle while a streaming
417
+ /// operation posts interim frames.
418
+ bind_channels_fn: ?*const fn (context: *anyopaque, channels: HostChannelBinding) void = null,
419
+ /// Quiesce carrier workers/children before PlatformServices is severed.
420
+ shutdown_fn: ?*const fn (context: *anyopaque) void = null,
421
+ };
422
+
423
+ pub const HostChannelBinding = struct {
424
+ context: *anyopaque,
425
+ acquire_fn: *const fn (context: *anyopaque, key: u64) ?ChannelHandle,
426
+ };
427
+
428
+ pub const HostCallCompletion = struct {
429
+ key: u64,
430
+ ok: bool,
431
+ bytes: []const u8,
297
432
  };
298
433
 
299
434
  /// Window-action label capacity (`Effects.closeWindow`/`minimizeWindow`/
@@ -308,7 +443,10 @@ pub const max_window_action_label = 64;
308
443
  pub const WindowActionState = struct {
309
444
  close_count: u32 = 0,
310
445
  minimize_count: u32 = 0,
446
+ hide_count: u32 = 0,
311
447
  show_count: u32 = 0,
448
+ dock_presence_count: u32 = 0,
449
+ dock_visible: bool = true,
312
450
  quit_count: u32 = 0,
313
451
  last_label_buffer: [max_window_action_label]u8 = @splat(0),
314
452
  last_label_len: usize = 0,
@@ -1837,6 +1975,21 @@ pub const EffectResultKind = enum(u8) {
1837
1975
  /// opposite of the channel records' inline argument. Exit records
1838
1976
  /// ride `code`/`exit_reason` plus the pty fields.
1839
1977
  pty = 15,
1978
+ /// One boot model-restore outcome. Successful canonical model bytes ride
1979
+ /// `payload` at the live boundary and move to the session blob store;
1980
+ /// replay feeds those exact bytes before the installing app-start event.
1981
+ persist = 16,
1982
+ /// One relational page or terminal. Small page bytes ride `payload`; the
1983
+ /// session recorder spills large pages to `db_blob_hash`/`db_blob_len`.
1984
+ /// Result kind and closed outcome are packed into `code` by
1985
+ /// `dbJournalCode`. Admission rejections mark
1986
+ /// `exit_reason == .rejected` and regenerate.
1987
+ db = 17,
1988
+ /// One app-scoped credential result. A successful get's live secret is
1989
+ /// present in `payload` only until the recorder replaces it with a
1990
+ /// salted digest and length; replay synthesizes same-length placeholder
1991
+ /// bytes and never consults an OS keychain.
1992
+ credentials = 18,
1840
1993
  };
1841
1994
 
1842
1995
  /// Journaled wall-clock reads buffered for replay (`Effects.wallMs`).
@@ -1884,6 +2037,11 @@ pub const ReplayEnvEntry = struct {
1884
2037
  value: []const u8,
1885
2038
  };
1886
2039
 
2040
+ pub const ReplayPersistEntry = struct {
2041
+ outcome: EffectPersistOutcome,
2042
+ bytes: []const u8,
2043
+ };
2044
+
1887
2045
  /// One drained effect result, flattened for the session journal: the
1888
2046
  /// exact payload `update` received, Msg-type-erased so the recorder and
1889
2047
  /// replayer need no knowledge of the app's Msg union. Only the fields
@@ -1981,6 +2139,25 @@ pub const EffectResultRecord = struct {
1981
2139
  /// when it moves `payload` out of line (the image convention).
1982
2140
  pty_blob_hash: [effect_image_blob_hash_len]u8 = @splat(0),
1983
2141
  pty_blob_len: u64 = 0,
2142
+ /// `.persist` records: the closed restore outcome and the content address
2143
+ /// of successful canonical model bytes (empty models honestly use no
2144
+ /// blob). The recorder moves non-empty payloads out of line.
2145
+ persist_outcome: EffectPersistOutcome = .none,
2146
+ persist_blob_hash: [effect_image_blob_hash_len]u8 = @splat(0),
2147
+ persist_blob_len: u64 = 0,
2148
+ /// `.db` page records may move a large encoded page out of line. Small
2149
+ /// pages stay inline in `payload`; terminals use neither representation.
2150
+ db_blob_hash: [effect_image_blob_hash_len]u8 = @splat(0),
2151
+ db_blob_len: u64 = 0,
2152
+ /// `.credentials` records: the operation and closed outcome. Successful
2153
+ /// get bytes never persist; the recorder stores only their length, a
2154
+ /// per-session salt, and a replay-placeholder digest independent of the
2155
+ /// secret (so recordings are not offline guessing oracles).
2156
+ credentials_operation: EffectCredentialsOperation = .get,
2157
+ credentials_outcome: EffectCredentialsOutcome = .ok,
2158
+ credentials_secret_len: u64 = 0,
2159
+ credentials_salt: [16]u8 = @splat(0),
2160
+ credentials_digest: [32]u8 = @splat(0),
1984
2161
  };
1985
2162
 
1986
2163
  /// Type-erased sink the drain reports every delivered result to while a
@@ -2494,11 +2671,14 @@ pub fn Effects(comptime Msg: type) type {
2494
2671
  pub const ExitMsgFn = *const fn (exit: EffectExit) Msg;
2495
2672
  pub const ResponseMsgFn = *const fn (response: EffectResponse) Msg;
2496
2673
  pub const FileMsgFn = *const fn (result: EffectFileResult) Msg;
2674
+ pub const PersistMsgFn = *const fn (result: EffectPersistResult) Msg;
2497
2675
  pub const ClipboardMsgFn = *const fn (result: EffectClipboardResult) Msg;
2498
2676
  pub const TimerMsgFn = *const fn (timer: EffectTimer) Msg;
2499
2677
  pub const AudioMsgFn = *const fn (event: EffectAudio) Msg;
2500
2678
  pub const VideoMsgFn = *const fn (event: EffectVideo) Msg;
2501
2679
  pub const HostMsgFn = *const fn (result: EffectHostResult) Msg;
2680
+ pub const CredentialsMsgFn = *const fn (result: EffectCredentialsResult) Msg;
2681
+ pub const DbMsgFn = *const fn (result: EffectDbResult) Msg;
2502
2682
  pub const ImageMsgFn = *const fn (result: EffectImageResult) Msg;
2503
2683
  pub const ChannelMsgFn = *const fn (event: EffectChannelEvent) Msg;
2504
2684
  pub const PtyMsgFn = *const fn (event: EffectPtyEvent) Msg;
@@ -2550,6 +2730,27 @@ pub fn Effects(comptime Msg: type) type {
2550
2730
  }.make;
2551
2731
  }
2552
2732
 
2733
+ /// Comptime Msg constructor for credential effects. The variant's
2734
+ /// payload type must be `native_sdk.EffectCredentialsResult`.
2735
+ pub fn credentialsMsg(comptime tag: std.meta.Tag(Msg)) CredentialsMsgFn {
2736
+ return struct {
2737
+ fn make(result: EffectCredentialsResult) Msg {
2738
+ return @unionInit(Msg, @tagName(tag), result);
2739
+ }
2740
+ }.make;
2741
+ }
2742
+
2743
+ /// Comptime Msg constructor for model restore delivery:
2744
+ /// `persistMsg(.restored)` builds `Msg{ .restored = result }` — the
2745
+ /// variant's payload type must be `native_sdk.EffectPersistResult`.
2746
+ pub fn persistMsg(comptime tag: std.meta.Tag(Msg)) PersistMsgFn {
2747
+ return struct {
2748
+ fn make(result: EffectPersistResult) Msg {
2749
+ return @unionInit(Msg, @tagName(tag), result);
2750
+ }
2751
+ }.make;
2752
+ }
2753
+
2553
2754
  /// Comptime Msg constructor for `on_result` of clipboard
2554
2755
  /// effects: `clipboardMsg(.copied)` builds
2555
2756
  /// `Msg{ .copied = result }` — the variant's payload type must
@@ -2610,6 +2811,15 @@ pub fn Effects(comptime Msg: type) type {
2610
2811
  }.make;
2611
2812
  }
2612
2813
 
2814
+ /// Comptime Msg constructor for relational pages and terminals.
2815
+ pub fn dbMsg(comptime tag: std.meta.Tag(Msg)) DbMsgFn {
2816
+ return struct {
2817
+ fn make(result: EffectDbResult) Msg {
2818
+ return @unionInit(Msg, @tagName(tag), result);
2819
+ }
2820
+ }.make;
2821
+ }
2822
+
2613
2823
  /// Comptime Msg constructor for `on_result` of image loads:
2614
2824
  /// `imageMsg(.cover_loaded)` builds
2615
2825
  /// `Msg{ .cover_loaded = result }` — the variant's payload type
@@ -2832,6 +3042,89 @@ pub fn Effects(comptime Msg: type) type {
2832
3042
  on_result: ?HostMsgFn = null,
2833
3043
  };
2834
3044
 
3045
+ pub const StoreEntry = struct {
3046
+ key: []const u8,
3047
+ bytes: []const u8,
3048
+ };
3049
+
3050
+ pub const StoreSetOptions = struct {
3051
+ key: u64,
3052
+ record_key: []const u8,
3053
+ bytes: []const u8,
3054
+ on_result: ?HostMsgFn = null,
3055
+ };
3056
+
3057
+ pub const StoreGetOptions = struct {
3058
+ key: u64,
3059
+ record_key: []const u8,
3060
+ on_result: ?HostMsgFn = null,
3061
+ };
3062
+
3063
+ pub const StoreDeleteOptions = StoreGetOptions;
3064
+
3065
+ pub const StoreScanOptions = struct {
3066
+ key: u64,
3067
+ prefix: []const u8,
3068
+ limit: u32 = default_effect_store_scan_limit,
3069
+ after: []const u8 = "",
3070
+ on_result: ?HostMsgFn = null,
3071
+ };
3072
+
3073
+ pub const StoreSetManyOptions = struct {
3074
+ key: u64,
3075
+ entries: []const StoreEntry,
3076
+ on_result: ?HostMsgFn = null,
3077
+ };
3078
+
3079
+ /// App-scoped secure credential operations. `credential_key` is the
3080
+ /// only authored identifier; the bound app identity supplies the OS
3081
+ /// keychain service namespace. Set/delete route empty bytes on ok,
3082
+ /// get routes the secret bytes, and every terminal carries one closed
3083
+ /// `EffectCredentialsOutcome` in `EffectCredentialsResult`.
3084
+ pub const CredentialsSetOptions = struct {
3085
+ key: u64,
3086
+ credential_key: []const u8,
3087
+ secret: []const u8,
3088
+ on_result: ?CredentialsMsgFn = null,
3089
+ /// Internal adapter for the TypeScript request wire.
3090
+ host_result: ?HostMsgFn = null,
3091
+ };
3092
+
3093
+ pub const CredentialsGetOptions = struct {
3094
+ key: u64,
3095
+ credential_key: []const u8,
3096
+ on_result: ?CredentialsMsgFn = null,
3097
+ host_result: ?HostMsgFn = null,
3098
+ };
3099
+
3100
+ pub const CredentialsDeleteOptions = struct {
3101
+ key: u64,
3102
+ credential_key: []const u8,
3103
+ on_result: ?CredentialsMsgFn = null,
3104
+ host_result: ?HostMsgFn = null,
3105
+ };
3106
+
3107
+ pub const DbQueryOptions = struct {
3108
+ key: u64,
3109
+ sql: []const u8,
3110
+ params: []const EffectDbValue = &.{},
3111
+ on_result: ?DbMsgFn = null,
3112
+ };
3113
+
3114
+ pub const DbExecOptions = struct {
3115
+ key: u64,
3116
+ statements: []const EffectDbStatement,
3117
+ on_result: ?DbMsgFn = null,
3118
+ };
3119
+
3120
+ pub const DbSubscribeOptions = struct {
3121
+ key: u64,
3122
+ sql: []const u8,
3123
+ params: []const EffectDbValue = &.{},
3124
+ tables: []const []const u8,
3125
+ on_result: ?DbMsgFn = null,
3126
+ };
3127
+
2835
3128
  /// A recorded host request, exposed by the fake executor for
2836
3129
  /// test assertions. Slices point into slot storage and stay
2837
3130
  /// valid until the request retires.
@@ -3431,13 +3724,34 @@ pub fn Effects(comptime Msg: type) type {
3431
3724
  volume: f32,
3432
3725
  };
3433
3726
 
3434
- /// `draining`: the worker is done and the terminal entry is
3727
+ /// `draining`: the effect work is done and the terminal entry is
3435
3728
  /// queued, but the slot still owns a heap buffer (a fetch's body
3436
3729
  /// or a collect spawn's stdout) until the drain delivers (and
3437
- /// thereby retires) it.
3730
+ /// thereby retires) it. A consumer that dequeues a worker-fed
3731
+ /// terminal may publish this state before the producer thread's
3732
+ /// post-enqueue epilogue finishes; reclaim joins that epilogue.
3438
3733
  const SlotState = enum(u8) { idle, running, done, draining };
3439
3734
 
3440
- const SlotKind = enum(u8) { spawn, fetch, file, clipboard, host, image };
3735
+ const SlotKind = enum(u8) { spawn, fetch, file, clipboard, host, store, credentials, image };
3736
+
3737
+ const DbSlotKind = enum(u8) { query, exec, live };
3738
+
3739
+ const DbLiveContext = struct {
3740
+ sql: []u8,
3741
+ params: []EffectDbValue,
3742
+ tables: [][]u8,
3743
+ };
3744
+
3745
+ const DbSlot = struct {
3746
+ active: bool = false,
3747
+ fake: bool = false,
3748
+ dirty: bool = false,
3749
+ key: u64 = 0,
3750
+ generation: u64 = 0,
3751
+ kind: DbSlotKind = .query,
3752
+ on_result: ?DbMsgFn = null,
3753
+ live: ?*DbLiveContext = null,
3754
+ };
3441
3755
 
3442
3756
  const EntryKind = enum(u8) { line, exit, response, file, clipboard, host, image, channel, pty };
3443
3757
 
@@ -3525,6 +3839,7 @@ pub fn Effects(comptime Msg: type) type {
3525
3839
  file_fn: ?FileMsgFn = null,
3526
3840
  clipboard_fn: ?ClipboardMsgFn = null,
3527
3841
  host_fn: ?HostMsgFn = null,
3842
+ credentials_fn: ?CredentialsMsgFn = null,
3528
3843
  image_fn: ?ImageMsgFn = null,
3529
3844
  /// `.line` entries whose payload exceeds the inline buffer
3530
3845
  /// (a raised `max_line_bytes` bound): the bytes ride in this
@@ -3556,6 +3871,11 @@ pub fn Effects(comptime Msg: type) type {
3556
3871
  /// replay) and feed fallbacks. Bytes here are never a host
3557
3872
  /// answer's — those ride the queue with their slot buffer.
3558
3873
  host: struct { result: EffectHostResult, host_fn: ?HostMsgFn, rejected: bool },
3874
+ credentials: struct {
3875
+ result: EffectCredentialsResult,
3876
+ credentials_fn: ?CredentialsMsgFn,
3877
+ host_fn: ?HostMsgFn,
3878
+ },
3559
3879
  /// `resolve`: a fed audio event (fake executor / replay)
3560
3880
  /// whose key and handler come from the live channel at
3561
3881
  /// delivery time — exactly how a platform event resolves in
@@ -3598,6 +3918,7 @@ pub fn Effects(comptime Msg: type) type {
3598
3918
  /// `.rejected` names the parked channel-table slot it
3599
3919
  /// retires at delivery (see `PendingChannel`).
3600
3920
  channel: struct { event: EffectChannelEvent, channel_fn: ?ChannelMsgFn, regenerates: bool, retire_slot: ?usize = null, retire_generation: u64 = 0 },
3921
+ db: PendingDb,
3601
3922
  /// A fully formed Msg staged on the loop thread by a
3602
3923
  /// caller-side validator (`stageLoopMsg` — the TS bridge's
3603
3924
  /// synchronous refusals). Always regenerating by contract:
@@ -3628,6 +3949,7 @@ pub fn Effects(comptime Msg: type) type {
3628
3949
  // EffectHostResult carries none: its terminals are
3629
3950
  // one-per-request by construction.
3630
3951
  .host => {},
3952
+ .credentials => {},
3631
3953
  // Image terminals never enter the ring (they stage
3632
3954
  // in the non-lossy `pending_images`), so neither
3633
3955
  // overflow arm can ever see one. EffectImageResult
@@ -3643,6 +3965,7 @@ pub fn Effects(comptime Msg: type) type {
3643
3965
  // `pending_channels` for the same reason —
3644
3966
  // exactly one `.rejected` per refused open.
3645
3967
  .channel => unreachable,
3968
+ .db => unreachable,
3646
3969
  // Staged Msgs live in the non-lossy
3647
3970
  // `pending_staged` — one per caller-side refusal,
3648
3971
  // and no counter to fold a loss into.
@@ -3660,10 +3983,12 @@ pub fn Effects(comptime Msg: type) type {
3660
3983
  .audio => 0,
3661
3984
  .pty => 0,
3662
3985
  .host => 0,
3986
+ .credentials => 0,
3663
3987
  // Never in the ring; see `addDropped`.
3664
3988
  .video => unreachable,
3665
3989
  .image => unreachable,
3666
3990
  .channel => unreachable,
3991
+ .db => unreachable,
3667
3992
  .staged => unreachable,
3668
3993
  };
3669
3994
  }
@@ -3819,6 +4144,22 @@ pub fn Effects(comptime Msg: type) type {
3819
4144
  msg: Msg,
3820
4145
  };
3821
4146
 
4147
+ /// One copied relational page or terminal awaiting the next drain.
4148
+ /// Pages are non-lossy and independently journaled; the owned buffer
4149
+ /// survives until the Msg has run through update.
4150
+ const PendingDb = struct {
4151
+ seq: u64,
4152
+ key: u64,
4153
+ generation: u64,
4154
+ kind: EffectDbResultKind,
4155
+ outcome: EffectDbOutcome,
4156
+ bytes: ?[]u8 = null,
4157
+ db_fn: ?DbMsgFn,
4158
+ regenerates: bool,
4159
+ /// Rejections that never acquired a DB slot do not retire one.
4160
+ transient: bool = false,
4161
+ };
4162
+
3822
4163
  /// Everything a real spawn worker's BLOCKING phase may touch,
3823
4164
  /// held out-of-line from the channel on its own heap block —
3824
4165
  /// the spawn twin of `FileWorkerContext`, and the same
@@ -3928,6 +4269,40 @@ pub fn Effects(comptime Msg: type) type {
3928
4269
  }
3929
4270
  };
3930
4271
 
4272
+ /// Immutable input and bounded result storage for one record-store
4273
+ /// write. The worker owns this block until `joinWorker`; keeping the
4274
+ /// SQLite input out of the slot lets a replaced request become
4275
+ /// logically cancelled without racing the write that must still run
4276
+ /// before its replacement.
4277
+ const StoreWorkerContext = struct {
4278
+ binding: RecordStoreBinding,
4279
+ operation: EffectStoreOp,
4280
+ sequence: u64,
4281
+ sequence_ready: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
4282
+ payload: []u8,
4283
+ output: [32]u8 = undefined,
4284
+ outcome: EffectStoreOutcome = .rejected,
4285
+ output_len: usize = 0,
4286
+ };
4287
+
4288
+ /// Private inputs and output for one blocking keychain call. All
4289
+ /// storage is process-lived until the worker joins (or frees it after
4290
+ /// an abandon), so the platform call never borrows runtime-owned
4291
+ /// service, namespace, command, or result storage.
4292
+ const CredentialsWorkerContext = struct {
4293
+ mutex: SpinMutex = .{},
4294
+ abandoned: bool = false,
4295
+ committed: bool = false,
4296
+ services: platform.PlatformServices,
4297
+ service: []u8,
4298
+ permitted: bool,
4299
+ operation: EffectCredentialsOperation,
4300
+ key: []u8,
4301
+ secret: []u8,
4302
+ output: []u8,
4303
+ execution: credentials_store.Execution = .{ .outcome = .rejected },
4304
+ };
4305
+
3931
4306
  const Slot = struct {
3932
4307
  state: std.atomic.Value(SlotState) = std.atomic.Value(SlotState).init(.idle),
3933
4308
  generation: u32 = 0,
@@ -3940,6 +4315,7 @@ pub fn Effects(comptime Msg: type) type {
3940
4315
  on_file: ?FileMsgFn = null,
3941
4316
  on_clipboard: ?ClipboardMsgFn = null,
3942
4317
  on_host: ?HostMsgFn = null,
4318
+ on_credentials: ?CredentialsMsgFn = null,
3943
4319
  /// Set by `cancel` before any kill attempt; read by the
3944
4320
  /// worker so a cancel that lands before the process spawns
3945
4321
  /// still kills it.
@@ -3976,6 +4352,13 @@ pub fn Effects(comptime Msg: type) type {
3976
4352
  /// handshake — the loop thread only dereferences it while
3977
4353
  /// the channel is alive.
3978
4354
  spawn_ctx: ?*SpawnWorkerContext = null,
4355
+ /// The private input/result block of an off-loop record-store
4356
+ /// write. Store workers are always joined before teardown can
4357
+ /// release the host-owned database binding.
4358
+ store_ctx: ?*StoreWorkerContext = null,
4359
+ /// Off-loop OS keychain operation; joined before the runtime or
4360
+ /// its PlatformServices vtable can be released.
4361
+ credentials_ctx: ?*CredentialsWorkerContext = null,
3979
4362
  /// Producer-side drop accounting (worker in real mode, loop
3980
4363
  /// thread in fake mode; never both).
3981
4364
  dropped_pending: u32 = 0,
@@ -3983,8 +4366,11 @@ pub fn Effects(comptime Msg: type) type {
3983
4366
  argv_slices: [max_effect_argv][]const u8 = undefined,
3984
4367
  argv_count: usize = 0,
3985
4368
  argv_storage: [max_effect_argv_bytes]u8 = undefined,
3986
- stdin_storage: [max_effect_stdin_bytes]u8 = undefined,
3987
- stdin_len: usize = 0,
4369
+ /// Spawn stdin is copied only for an accepted occupancy. Keeping
4370
+ /// the 4 KiB bound inline in every general/store/credential slot
4371
+ /// inflated the whole `Effects` value even though almost every
4372
+ /// slot has no stdin at all.
4373
+ stdin_buffer: ?[]u8 = null,
3988
4374
  // ---- line-framing fields (.lines spawns, .stream fetches) ----
3989
4375
  /// Effective per-line bound: the default or the accepted
3990
4376
  /// `max_line_bytes` override.
@@ -4025,6 +4411,14 @@ pub fn Effects(comptime Msg: type) type {
4025
4411
  file_op: EffectFileOp = .read,
4026
4412
  // ---- clipboard-only fields (kind == .clipboard) ----
4027
4413
  clipboard_op: EffectClipboardOp = .write,
4414
+ // ---- credentials-only fields (kind == .credentials) ----
4415
+ credentials_op: EffectCredentialsOperation = .get,
4416
+ /// Real credential operations execute one at a time in issue
4417
+ /// order. A waiting replacement owns a slot but no thread, so a
4418
+ /// burst under one route coalesces instead of exhausting all four
4419
+ /// credential slots or letting an older set finish last.
4420
+ credentials_waiting: bool = false,
4421
+ credentials_sequence: u64 = 0,
4028
4422
  // ---- image-only fields (kind == .image) ----
4029
4423
  on_image: ?ImageMsgFn = null,
4030
4424
  /// The local source path (the URL rides `url_storage`, a
@@ -4079,7 +4473,7 @@ pub fn Effects(comptime Msg: type) type {
4079
4473
  }
4080
4474
 
4081
4475
  fn stdinBytes(slot: *const Slot) []const u8 {
4082
- return slot.stdin_storage[0..slot.stdin_len];
4476
+ return slot.stdin_buffer orelse "";
4083
4477
  }
4084
4478
 
4085
4479
  fn fetchUrl(slot: *const Slot) []const u8 {
@@ -4204,6 +4598,15 @@ pub fn Effects(comptime Msg: type) type {
4204
4598
  replay_env: [max_effect_replay_env_entries]ReplayEnvEntry = undefined,
4205
4599
  replay_env_head: usize = 0,
4206
4600
  replay_env_len: usize = 0,
4601
+ /// Exactly one restore outcome is owed to a persistence-enabled boot.
4602
+ /// A two-entry queue makes a damaged duplicate journal detectable at
4603
+ /// replay settle instead of overwriting the first outcome. Payloads
4604
+ /// are copied at the journal handoff: session replay's blob scratch
4605
+ /// expires with the installing event.
4606
+ replay_persist: [2]ReplayPersistEntry = undefined,
4607
+ replay_persist_bytes: [2]?[]u8 = @splat(null),
4608
+ replay_persist_head: usize = 0,
4609
+ replay_persist_len: usize = 0,
4207
4610
  /// Set once from the loop thread before the first dispatch;
4208
4611
  /// workers call `services.wake()` through it (the one
4209
4612
  /// thread-safe PlatformServices entry). Loop-thread reads only
@@ -4274,12 +4677,26 @@ pub fn Effects(comptime Msg: type) type {
4274
4677
  /// by `UiApp` alongside the services — the seam behind
4275
4678
  /// app-drawn window controls (loop-thread only).
4276
4679
  window_actions: ?WindowActionBinding = null,
4680
+ /// Runtime system services with their validation/policy layer intact.
4681
+ /// Intrinsic platform commands use this binding; generic host calls
4682
+ /// continue to use `host_calls` below.
4683
+ system_services: ?SystemServiceBinding = null,
4277
4684
  /// The embedding host's named-command services (`hostSend` /
4278
4685
  /// `hostRequest`), bound by whoever hosts a transpiled app core
4279
4686
  /// (loop-thread only). Null means no host services: sends drop,
4280
4687
  /// requests reject loudly in real mode, and the fake executor
4281
4688
  /// parks requests for `feedHostResult` regardless.
4282
4689
  host_calls: ?HostCallBinding = null,
4690
+ /// Capability-installed record-store service. Store commands are
4691
+ /// SDK-reserved routed requests, so their results reuse the request
4692
+ /// journal/replay path while the database handle stays host-owned.
4693
+ record_store_binding: ?RecordStoreBinding = null,
4694
+ /// App-namespaced OS credential store. Permission is captured in the
4695
+ /// binding at install; denied effects never reach a platform worker.
4696
+ credentials_store_binding: ?CredentialsStoreBinding = null,
4697
+ /// Capability-installed Tier-3 relational database. Queries execute
4698
+ /// synchronously on the loop thread and stage bounded page results.
4699
+ relational_store_binding: ?RelationalStoreBinding = null,
4283
4700
  /// Window-action mirror: counts and the last requested label,
4284
4701
  /// observable in tests (`windowActionState`).
4285
4702
  window_action_state: WindowActionState = .{},
@@ -4330,6 +4747,12 @@ pub fn Effects(comptime Msg: type) type {
4330
4747
  /// bounded, warned leak — see `SpawnWorkerContext`). The seam
4331
4748
  /// tests assert against: zero on every healthy teardown.
4332
4749
  abandoned_spawn_workers: u32 = 0,
4750
+ /// Teardown budget for a synchronous OS credential call. Unlike a
4751
+ /// fetch, keychain APIs have no portable cancellation primitive.
4752
+ credentials_join_deadline_ms: u64 = default_credentials_join_deadline_ms,
4753
+ /// Number of credential workers detached after that deadline. A
4754
+ /// healthy platform call always leaves this at zero.
4755
+ abandoned_credentials_workers: u32 = 0,
4333
4756
  /// Teardown budget (milliseconds, per channel) for a host wake
4334
4757
  /// call still inside the embedder's `wake_fn` when the channel
4335
4758
  /// sweep quiesces it — see `quiesceChannelWake` for why the
@@ -4360,6 +4783,7 @@ pub fn Effects(comptime Msg: type) type {
4360
4783
  /// drained.
4361
4784
  fetch_start_rejections: std.atomic.Value(u32) = std.atomic.Value(u32).init(0),
4362
4785
  next_generation: u32 = 1,
4786
+ next_credentials_sequence: u64 = 1,
4363
4787
  /// The channel family's OWN generation counter — u64 and
4364
4788
  /// monotonic for the process's lifetime, never the shared u32
4365
4789
  /// `next_generation` above: channel handles live on app-owned
@@ -4373,7 +4797,10 @@ pub fn Effects(comptime Msg: type) type {
4373
4797
  /// process-lifetime posting handles. Seedable in tests to pin
4374
4798
  /// the non-wrapping guarantee without 2^32 opens.
4375
4799
  channel_generation: u64 = 0,
4376
- slots: [max_effects]Slot = [_]Slot{.{}} ** max_effects,
4800
+ slots: [total_effect_slots]Slot = [_]Slot{.{}} ** total_effect_slots,
4801
+ db_slots: [max_db_effects]DbSlot = [_]DbSlot{.{}} ** max_db_effects,
4802
+ next_db_generation: u64 = 1,
4803
+ db_revision: u64 = 0,
4377
4804
  /// Fixed fx timer table (see `max_effect_timers`): timers live
4378
4805
  /// beside the effect slots, never in them. Loop-thread only.
4379
4806
  timer_slots: [max_effect_timers]TimerSlot = [_]TimerSlot{.{}} ** max_effect_timers,
@@ -4518,6 +4945,10 @@ pub fn Effects(comptime Msg: type) type {
4518
4945
  pending_staged_spill: []PendingStaged = &.{},
4519
4946
  pending_staged_head: usize = 0,
4520
4947
  pending_staged_len: usize = 0,
4948
+ pending_dbs: [max_effect_pending_images_inline]PendingDb = undefined,
4949
+ pending_db_spill: []PendingDb = &.{},
4950
+ pending_db_head: usize = 0,
4951
+ pending_db_len: usize = 0,
4521
4952
  /// INTERNED backing for the KEY bytes a staged Msg carries (a TS
4522
4953
  /// bridge spawn-rejection names the app's requested key). A
4523
4954
  /// staged Msg outlives the caller's frame arena, the caller has
@@ -4530,6 +4961,9 @@ pub fn Effects(comptime Msg: type) type {
4530
4961
  /// vocabulary, not its rejection count.
4531
4962
  staged_keys: [][]u8 = &.{},
4532
4963
  staged_keys_len: usize = 0,
4964
+ /// Stable backing for the single boot restore Msg. Unlike ordinary
4965
+ /// drain scratch, a model may retain this slice after update commits.
4966
+ persist_restore_bytes: ?[]u8 = null,
4533
4967
  /// Scratch the drained entry is copied into so its line slice
4534
4968
  /// stays valid while `update` runs (recycled per drained Msg).
4535
4969
  drain_scratch: Entry = .{},
@@ -4544,6 +4978,11 @@ pub fn Effects(comptime Msg: type) type {
4544
4978
  /// when the next response or file result drains, or at
4545
4979
  /// `deinit`).
4546
4980
  drain_fetch_body: ?[]u8 = null,
4981
+ /// The current drain buffer contains a credential request/result and
4982
+ /// must be securely zeroed before it is returned to the allocator.
4983
+ drain_fetch_body_sensitive: bool = false,
4984
+ /// Owned page bytes for the most recently delivered relational Msg.
4985
+ drain_db_bytes: ?[]u8 = null,
4547
4986
  /// The collect buffer of the most recently delivered collect
4548
4987
  /// exit, keeping `EffectExit.output` valid while `update` runs
4549
4988
  /// (freed when the next collect exit drains, or at `deinit`).
@@ -4559,7 +4998,7 @@ pub fn Effects(comptime Msg: type) type {
4559
4998
  /// unconditional — fetch supervisors cancel on the shutdown
4560
4999
  /// flag (and an exchange that cannot start cancellably is
4561
5000
  /// rejected up front), so no fetch worker survives this call.
4562
- /// Spawn and file workers get a deadline each
5001
+ /// Spawn and file workers get deadlines
4563
5002
  /// (`spawn_join_deadline_ms` / `file_join_deadline_ms`), with
4564
5003
  /// a best-effort cancel of the blocked task at the halfway
4565
5004
  /// mark: a spawn normally converges from the process-group
@@ -4567,17 +5006,21 @@ pub fn Effects(comptime Msg: type) type {
4567
5006
  /// group (`setsid`, a shell's `set -m` background job) keeps
4568
5007
  /// the stdout pipe open past every kill, and file I/O has no
4569
5008
  /// converging force at all (a write to a FIFO with no reader,
4570
- /// a stalled network filesystem). A worker still stuck when
5009
+ /// a stalled network filesystem). Credential calls use their
5010
+ /// own `credentials_join_deadline_ms`: OS keyrings expose no
5011
+ /// portable cancellation while they wait for an unlock. A worker still stuck when
4571
5012
  /// its budget expires is ABANDONED — thread detached, its
4572
5013
  /// out-of-line context, private buffers, and the executor io
4573
- /// deliberately leaked, one warning naming the stuck op (see
5014
+ /// deliberately leaked, one warning naming the stuck op (credential
5015
+ /// workers instead self-destroy their private context when the OS
5016
+ /// call returns, while the platform callback context is preserved; see
4574
5017
  /// `FileWorkerContext` / `SpawnWorkerContext` for the
4575
5018
  /// invariant). Either way the owner may free the channel's
4576
5019
  /// memory — and tear down the allocator behind it — the moment
4577
5020
  /// this returns: nothing an abandoned worker can still reach
4578
5021
  /// lives in the channel or in caller-allocator storage (the
4579
5022
  /// leakable set is allocated from `process_allocator`). All
4580
- /// three worker classes share one terminal guarantee: teardown
5023
+ /// four worker classes share one terminal guarantee: teardown
4581
5024
  /// returns bounded, and every byte a live thread can still
4582
5025
  /// touch stays valid forever.
4583
5026
  ///
@@ -4827,6 +5270,91 @@ pub fn Effects(comptime Msg: type) type {
4827
5270
  slot.generation = 0;
4828
5271
  }
4829
5272
  }
5273
+ // Store writes use std.Thread directly rather than the shared
5274
+ // threaded-I/O executor. Let them finish and join before their
5275
+ // runtime-owned SQLite binding is released. Ordered writes must
5276
+ // all be allowed to progress together, so wait for the family as
5277
+ // a set, then join.
5278
+ if (comptime io_threaded_supported) {
5279
+ while (true) {
5280
+ var store_running = false;
5281
+ for (&self.slots) |*slot| {
5282
+ if (slot.kind == .store and !slot.fake and slot.worker_thread != null and slot.state.load(.acquire) == .running) {
5283
+ store_running = true;
5284
+ break;
5285
+ }
5286
+ }
5287
+ if (!store_running) break;
5288
+ std.Thread.yield() catch {};
5289
+ }
5290
+ for (&self.slots) |*slot| {
5291
+ if (slot.kind == .store) joinWorker(slot);
5292
+ }
5293
+
5294
+ // Credential APIs may wait forever for an interactive OS
5295
+ // keyring unlock. Bound that wait, then use the context's
5296
+ // commit/abandon fence: a committed worker is already in its
5297
+ // short runtime epilogue and is joined; an uncommitted one is
5298
+ // detached and can touch only its process-lived private block.
5299
+ const credentials_start_ns = runtime_clock.monotonicNanoseconds();
5300
+ while (true) {
5301
+ var credentials_running = false;
5302
+ for (&self.slots) |*slot| {
5303
+ if (slot.kind == .credentials and !slot.fake and slot.worker_thread != null and slot.state.load(.acquire) == .running) {
5304
+ credentials_running = true;
5305
+ break;
5306
+ }
5307
+ }
5308
+ if (!credentials_running) break;
5309
+ const elapsed_ms = (runtime_clock.monotonicNanoseconds() - credentials_start_ns) / std.time.ns_per_ms;
5310
+ if (elapsed_ms >= self.credentials_join_deadline_ms) break;
5311
+ std.Thread.yield() catch {};
5312
+ }
5313
+ for (&self.slots) |*slot| {
5314
+ if (slot.kind != .credentials or slot.fake or slot.worker_thread == null) continue;
5315
+ if (slot.state.load(.acquire) != .running) continue;
5316
+ const ctx = slot.credentials_ctx orelse continue;
5317
+ ctx.mutex.lock();
5318
+ const committed = ctx.committed;
5319
+ if (committed) {
5320
+ ctx.mutex.unlock();
5321
+ continue;
5322
+ }
5323
+ ctx.abandoned = true;
5324
+ // Keep the fence locked through the last teardown-side
5325
+ // context access. Once it unlocks, a concurrently
5326
+ // returning detached worker may scrub and free `ctx`.
5327
+ ctx.services.noteBlockingCallAbandoned();
5328
+ if (comptime builtin.os.tag != .freestanding) {
5329
+ std.debug.print(
5330
+ "effects teardown: credential {s} for key '{s}' is still blocked in the OS store after {d}ms; abandoning its worker and preserving the platform callback context so teardown can return safely\n",
5331
+ .{ @tagName(slot.credentials_op), ctx.key, self.credentials_join_deadline_ms },
5332
+ );
5333
+ }
5334
+ if (slot.worker_thread) |thread| {
5335
+ slot.worker_thread = null;
5336
+ thread.detach();
5337
+ }
5338
+ // The detached worker owns and securely destroys `ctx`
5339
+ // after its OS call returns. The runtime-owned command /
5340
+ // result copy is independent and can be scrubbed now.
5341
+ slot.credentials_ctx = null;
5342
+ slot.credentials_waiting = false;
5343
+ slot.generation = 0;
5344
+ ctx.mutex.unlock();
5345
+ self.releaseFetchSlot(slot);
5346
+ self.abandoned_credentials_workers += 1;
5347
+ }
5348
+ for (&self.slots) |*slot| {
5349
+ if (slot.kind != .credentials) continue;
5350
+ joinWorker(slot);
5351
+ if (slot.state.load(.acquire) == .running or slot.credentials_waiting) {
5352
+ slot.credentials_waiting = false;
5353
+ slot.generation = 0;
5354
+ self.releaseFetchSlot(slot);
5355
+ }
5356
+ }
5357
+ }
4830
5358
  for (&self.slots) |*slot| {
4831
5359
  if (slot.state.load(.acquire) == .running and !slot.fake) {
4832
5360
  slot.cancel_requested.store(true, .release);
@@ -5023,6 +5551,7 @@ pub fn Effects(comptime Msg: type) type {
5023
5551
  self.clearQueue();
5024
5552
  for (&self.slots) |*slot| {
5025
5553
  if (slot.fetch_buffer) |buffer| {
5554
+ if (slot.kind == .credentials) std.crypto.secureZero(u8, buffer);
5026
5555
  self.allocator.free(buffer);
5027
5556
  slot.fetch_buffer = null;
5028
5557
  }
@@ -5034,10 +5563,15 @@ pub fn Effects(comptime Msg: type) type {
5034
5563
  self.allocator.free(buffer);
5035
5564
  slot.line_buffer = null;
5036
5565
  }
5566
+ if (slot.stdin_buffer) |buffer| {
5567
+ self.allocator.free(buffer);
5568
+ slot.stdin_buffer = null;
5569
+ }
5037
5570
  }
5038
- if (self.drain_fetch_body) |buffer| {
5571
+ self.releaseDrainFetchBody();
5572
+ if (self.drain_db_bytes) |buffer| {
5039
5573
  self.allocator.free(buffer);
5040
- self.drain_fetch_body = null;
5574
+ self.drain_db_bytes = null;
5041
5575
  }
5042
5576
  if (self.drain_collect_output) |buffer| {
5043
5577
  self.allocator.free(buffer);
@@ -5094,12 +5628,37 @@ pub fn Effects(comptime Msg: type) type {
5094
5628
  }
5095
5629
  self.pending_staged_head = 0;
5096
5630
  self.pending_staged_len = 0;
5631
+ const pending_db_storage = self.pendingDbStorage();
5632
+ for (0..self.pending_db_len) |offset| {
5633
+ if (pending_db_storage[(self.pending_db_head + offset) % pending_db_storage.len].bytes) |bytes| {
5634
+ self.allocator.free(bytes);
5635
+ }
5636
+ }
5637
+ if (self.pending_db_spill.len > 0) {
5638
+ self.allocator.free(self.pending_db_spill);
5639
+ self.pending_db_spill = &.{};
5640
+ }
5641
+ self.pending_db_head = 0;
5642
+ self.pending_db_len = 0;
5643
+ for (&self.db_slots) |*slot| self.freeDbLive(slot);
5644
+ self.db_slots = [_]DbSlot{.{}} ** max_db_effects;
5645
+ self.db_revision = 0;
5097
5646
  // The durable key buffers those staged Msgs referenced.
5098
5647
  self.releaseStagedKeys();
5099
5648
  if (self.staged_keys.len > 0) {
5100
5649
  self.allocator.free(self.staged_keys);
5101
5650
  self.staged_keys = &.{};
5102
5651
  }
5652
+ if (self.persist_restore_bytes) |bytes| {
5653
+ self.allocator.free(bytes);
5654
+ self.persist_restore_bytes = null;
5655
+ }
5656
+ for (&self.replay_persist_bytes) |*bytes| {
5657
+ if (bytes.*) |owned| self.allocator.free(owned);
5658
+ bytes.* = null;
5659
+ }
5660
+ self.replay_persist_head = 0;
5661
+ self.replay_persist_len = 0;
5103
5662
  // And an undrained replay write-verdict spill.
5104
5663
  if (self.replay_pty_write_spill.len > 0) {
5105
5664
  self.allocator.free(self.replay_pty_write_spill);
@@ -5107,6 +5666,11 @@ pub fn Effects(comptime Msg: type) type {
5107
5666
  }
5108
5667
  self.replay_pty_write_head = 0;
5109
5668
  self.replay_pty_write_len = 0;
5669
+ // A worker-backed host carrier may still be blocked in a child
5670
+ // read. Quiesce it while the platform wake binding remains live.
5671
+ if (self.host_calls) |binding| {
5672
+ if (binding.shutdown_fn) |shutdown_fn| shutdown_fn(binding.context);
5673
+ }
5110
5674
  // Sever the services binding last: the platform this pointer
5111
5675
  // reaches into may be destroyed before the next call arrives
5112
5676
  // (main's deferred app deinit runs after the runner's platform
@@ -5138,6 +5702,10 @@ pub fn Effects(comptime Msg: type) type {
5138
5702
  // Sever the host-call binding for the same reason: its
5139
5703
  // context belongs to the embedding host.
5140
5704
  self.host_calls = null;
5705
+ self.record_store_binding = null;
5706
+ self.credentials_store_binding = null;
5707
+ self.relational_store_binding = null;
5708
+ self.system_services = null;
5141
5709
  }
5142
5710
 
5143
5711
  /// Discard every queued completion, freeing heap line payloads
@@ -5221,6 +5789,9 @@ pub fn Effects(comptime Msg: type) type {
5221
5789
  pub fn bindServices(self: *Self, services: *const platform.PlatformServices) void {
5222
5790
  if (self.services != null) return;
5223
5791
  self.services = services;
5792
+ if (self.host_calls) |binding| {
5793
+ if (binding.bind_services_fn) |bind_fn| bind_fn(binding.context, services);
5794
+ }
5224
5795
  // Open-before-bind: a channel wake header is already armed
5225
5796
  // and its producer may already be posting, so this bind IS
5226
5797
  // the publication site. Bind-before-open publishes at the
@@ -5464,11 +6035,58 @@ pub fn Effects(comptime Msg: type) type {
5464
6035
  if (self.window_actions == null) self.window_actions = binding;
5465
6036
  }
5466
6037
 
6038
+ /// Bind runtime-validated platform services for the SDK-reserved
6039
+ /// named command family. Loop-thread only; the first bind sticks.
6040
+ pub fn bindSystemServices(self: *Self, binding: SystemServiceBinding) void {
6041
+ if (self.system_services == null) self.system_services = binding;
6042
+ }
6043
+
5467
6044
  /// Point named host commands at the embedding host's services
5468
6045
  /// (see `HostCallBinding`). Loop-thread only; the first bind
5469
6046
  /// sticks.
5470
6047
  pub fn bindHostCalls(self: *Self, binding: HostCallBinding) void {
5471
- if (self.host_calls == null) self.host_calls = binding;
6048
+ if (self.host_calls != null) return;
6049
+ self.host_calls = binding;
6050
+ if (binding.bind_channels_fn) |bind_fn| bind_fn(binding.context, .{
6051
+ .context = self,
6052
+ .acquire_fn = acquireHostChannel,
6053
+ });
6054
+ if (self.services) |services| {
6055
+ if (binding.bind_services_fn) |bind_fn| bind_fn(binding.context, services);
6056
+ }
6057
+ }
6058
+
6059
+ /// Whether this host binding uses reject-on-duplicate admission for
6060
+ /// keyed requests. Bridges consult this before rewriting their route
6061
+ /// table so a rejection cannot orphan the original completion.
6062
+ pub fn rejectsDuplicateHostRequestKeys(self: *const Self) bool {
6063
+ return self.host_calls != null and self.host_calls.?.reject_duplicate_keys;
6064
+ }
6065
+
6066
+ fn acquireHostChannel(context: *anyopaque, key: u64) ?ChannelHandle {
6067
+ const self: *Self = @ptrCast(@alignCast(context));
6068
+ return self.channelHandle(key);
6069
+ }
6070
+
6071
+ /// Bind the engine-owned Tier-2 store. Loop-thread only; first bind
6072
+ /// sticks. Apps without the `store` capability never install it and
6073
+ /// receive a closed `rejected` outcome if a command is smuggled in.
6074
+ pub fn bindRecordStore(self: *Self, binding: RecordStoreBinding) void {
6075
+ if (self.record_store_binding == null) self.record_store_binding = binding;
6076
+ }
6077
+
6078
+ /// Bind the app-scoped credential store. The binding captures both
6079
+ /// the manifest identity and the credentials permission; a missing or
6080
+ /// denied binding produces `.denied` without entering the OS.
6081
+ pub fn bindCredentialsStore(self: *Self, binding: CredentialsStoreBinding) void {
6082
+ if (self.credentials_store_binding == null) self.credentials_store_binding = binding;
6083
+ }
6084
+
6085
+ /// Bind the engine-owned Tier-3 relational database. Loop-thread
6086
+ /// only; first bind sticks. An app without the `sqlite` capability
6087
+ /// never installs this binding and every smuggled command rejects.
6088
+ pub fn bindRelationalStore(self: *Self, binding: RelationalStoreBinding) void {
6089
+ if (self.relational_store_binding == null) self.relational_store_binding = binding;
5472
6090
  }
5473
6091
 
5474
6092
  /// Switch this channel into session-replay mode: the fake
@@ -5661,6 +6279,15 @@ pub fn Effects(comptime Msg: type) type {
5661
6279
  }
5662
6280
  return error.ReplayDivergence;
5663
6281
  }
6282
+ if (self.replay_persist_len > 0) {
6283
+ if (comptime builtin.os.tag != .freestanding) {
6284
+ std.debug.print(
6285
+ "replay diverged: {d} journaled model-restore record(s) were never consumed - the replayed app no longer drains its persistence route\n",
6286
+ .{self.replay_persist_len},
6287
+ );
6288
+ }
6289
+ return error.ReplayDivergence;
6290
+ }
5664
6291
  // Fed results still awaiting delivery — EVERY kind, not one
5665
6292
  // family: the recorder journals every result at its live
5666
6293
  // DELIVERY (inside a dispatched event that follows it in the
@@ -5792,6 +6419,89 @@ pub fn Effects(comptime Msg: type) type {
5792
6419
  return entry;
5793
6420
  }
5794
6421
 
6422
+ /// Journal the one boot restore outcome. Successful bytes are moved to
6423
+ /// the content-addressed session blob store by SessionRecorder.
6424
+ pub fn journalPersistRestore(self: *Self, outcome: EffectPersistOutcome, bytes: []const u8) void {
6425
+ self.journalNote(.{ .kind = .persist, .key = 0, .payload = bytes, .persist_outcome = outcome });
6426
+ }
6427
+
6428
+ /// Queue a journaled boot restore for the persistence adapter. Copy
6429
+ /// successful bytes because the replay blob scratch that supplies
6430
+ /// them expires with the installing event.
6431
+ pub fn pushReplayPersist(self: *Self, outcome: EffectPersistOutcome, bytes: []const u8) error{EffectNotFound}!void {
6432
+ if (self.replay_persist_len >= self.replay_persist.len) return error.EffectNotFound;
6433
+ const index = (self.replay_persist_head + self.replay_persist_len) % self.replay_persist.len;
6434
+ std.debug.assert(self.replay_persist_bytes[index] == null);
6435
+ const owned = if (bytes.len > 0)
6436
+ self.allocator.dupe(u8, bytes) catch
6437
+ @panic("effects: out of memory retaining a replayed model restore payload")
6438
+ else
6439
+ null;
6440
+ self.replay_persist_bytes[index] = owned;
6441
+ self.replay_persist[index] = .{ .outcome = outcome, .bytes = if (owned) |copy| copy else "" };
6442
+ self.replay_persist_len += 1;
6443
+ }
6444
+
6445
+ pub fn takeReplayPersist(self: *Self) ?ReplayPersistEntry {
6446
+ if (self.replay_persist_len == 0) return null;
6447
+ const index = self.replay_persist_head;
6448
+ const entry = self.replay_persist[index];
6449
+ const owned = self.replay_persist_bytes[index];
6450
+ self.replay_persist_bytes[index] = null;
6451
+ if (self.persist_restore_bytes) |old| self.allocator.free(old);
6452
+ self.persist_restore_bytes = owned;
6453
+ self.replay_persist_head = (self.replay_persist_head + 1) % self.replay_persist.len;
6454
+ self.replay_persist_len -= 1;
6455
+ return entry;
6456
+ }
6457
+
6458
+ /// Deliver the engine-resolved boot snapshot through the ordinary
6459
+ /// effect stream. Live delivery journals exactly what reaches the
6460
+ /// Msg. Replay ignores the live app-data result and consumes the
6461
+ /// recorded restore instead, so replay never depends on or mutates
6462
+ /// the current snapshot store. The Msg is staged at this call's
6463
+ /// command-stream position and therefore runs only after the current
6464
+ /// model commit.
6465
+ ///
6466
+ /// Call once from `init_fx` after the host has resolved the snapshot.
6467
+ /// Under replay, no queued `.persist` record means an older recording
6468
+ /// with no persistence delivery, so no Msg is staged.
6469
+ pub fn deliverPersistRestore(
6470
+ self: *Self,
6471
+ live_outcome: EffectPersistOutcome,
6472
+ live_bytes: []const u8,
6473
+ on_result: PersistMsgFn,
6474
+ ) void {
6475
+ const entry = if (self.replay)
6476
+ self.takeReplayPersist() orelse return
6477
+ else
6478
+ ReplayPersistEntry{ .outcome = live_outcome, .bytes = live_bytes };
6479
+ const source_bytes = if (entry.outcome == .ok) entry.bytes else "";
6480
+ if (source_bytes.len > max_effect_persist_snapshot_bytes) {
6481
+ if (!self.replay) self.journalPersistRestore(.rejected, "");
6482
+ self.stagePendingStaged(.{
6483
+ .seq = self.nextPendingSeq(),
6484
+ .msg = on_result(.{ .outcome = .rejected }),
6485
+ });
6486
+ return;
6487
+ }
6488
+ const stable = if (self.replay)
6489
+ source_bytes
6490
+ else blk: {
6491
+ if (self.persist_restore_bytes) |old| self.allocator.free(old);
6492
+ const copy = self.allocator.dupe(u8, source_bytes) catch
6493
+ @panic("effects: out of memory retaining the model restore payload");
6494
+ self.persist_restore_bytes = copy;
6495
+ break :blk copy;
6496
+ };
6497
+ const result: EffectPersistResult = .{ .outcome = entry.outcome, .bytes = stable };
6498
+ if (!self.replay) self.journalPersistRestore(result.outcome, result.bytes);
6499
+ self.stagePendingStaged(.{
6500
+ .seq = self.nextPendingSeq(),
6501
+ .msg = on_result(result),
6502
+ });
6503
+ }
6504
+
5795
6505
  // ------------------------------------------------------------- API
5796
6506
 
5797
6507
  /// Register (or replace) decoded straight-alpha RGBA8 pixels
@@ -5875,8 +6585,14 @@ pub fn Effects(comptime Msg: type) type {
5875
6585
  slot.argv_slices[index] = slot.argv_storage[offset .. offset + arg.len];
5876
6586
  offset += arg.len;
5877
6587
  }
5878
- @memcpy(slot.stdin_storage[0..stdin_bytes.len], stdin_bytes);
5879
- slot.stdin_len = stdin_bytes.len;
6588
+ if (slot.stdin_buffer) |old| {
6589
+ self.allocator.free(old);
6590
+ slot.stdin_buffer = null;
6591
+ }
6592
+ if (stdin_bytes.len > 0) {
6593
+ slot.stdin_buffer = self.allocator.dupe(u8, stdin_bytes) catch
6594
+ return self.reject(options);
6595
+ }
5880
6596
  slot.output_mode = options.output;
5881
6597
  slot.collect_len = 0;
5882
6598
  slot.collect_truncated = false;
@@ -5896,6 +6612,10 @@ pub fn Effects(comptime Msg: type) type {
5896
6612
  // from the worker context at commit; fake mode
5897
6613
  // accumulates into it directly).
5898
6614
  slot.collect_buffer = self.allocator.alloc(u8, max_effect_collect_bytes) catch {
6615
+ if (slot.stdin_buffer) |buffer| {
6616
+ self.allocator.free(buffer);
6617
+ slot.stdin_buffer = null;
6618
+ }
5899
6619
  return self.reject(options);
5900
6620
  };
5901
6621
  }
@@ -7555,66 +8275,669 @@ pub fn Effects(comptime Msg: type) type {
7555
8275
  pub fn hostSend(self: *Self, name: []const u8, payload: []const u8) void {
7556
8276
  if (self.replay) return;
7557
8277
  if (name.len == 0 or name.len > max_effect_host_name_bytes) return;
8278
+ if (isNativeHostSendName(name)) {
8279
+ if (self.executor == .fake) return;
8280
+ self.performNativeHostSend(name, payload);
8281
+ return;
8282
+ }
7558
8283
  const binding = self.host_calls orelse return;
7559
8284
  binding.send_fn(binding.context, name, payload);
7560
8285
  }
7561
8286
 
7562
- /// A keyed, routed host command — the generic named host call
7563
- /// behind a transpiled core's `request` wire records: the host
7564
- /// performs `name` with `payload` and answers with exactly one
7565
- /// `feedHostResult(key, ok, bytes)`, delivered as one
7566
- /// `on_result` Msg (`EffectHostResult`) on the next drain. Key
7567
- /// discipline differs from spawn/fetch/file/clipboard on
7568
- /// purpose (the wire contract): issuing a key whose host
7569
- /// request is still in flight REPLACES it — the old request's
7570
- /// result is dropped, silently — and `cancelHostRequest` drops
7571
- /// one without dispatching anything. Rejection is never silent:
7572
- /// an over-bound name/payload, a key colliding with another
7573
- /// effect kind, a full slot table, or a real-mode channel with
7574
- /// no bound host services delivers exactly one err-route Msg
7575
- /// (`ok = false`, bytes `"rejected"`). Under the fake executor
7576
- /// the request parks in its slot (inspect with `pendingHostAt`,
7577
- /// answer with `feedHostResult`).
7578
- pub fn hostRequest(self: *Self, options: HostRequestOptions) void {
7579
- self.reclaimSlots();
7580
- const fake = self.executor == .fake;
7581
- if (options.name.len == 0 or options.name.len > max_effect_host_name_bytes or
7582
- options.payload.len > max_effect_host_payload_bytes)
8287
+ /// Request an engine-owned snapshot of the committed app model. This
8288
+ /// is the Zig-core twin of TypeScript `Cmd.persist()`: fire-and-forget
8289
+ /// command data, performed only after the model commit. A Zig host
8290
+ /// binding owns the model codec/source and therefore receives no app
8291
+ /// payload; the generated TS host supplies its canonical bytes at the
8292
+ /// same named-service seam.
8293
+ pub fn persist(self: *Self) void {
8294
+ self.hostSend("core.persist", "");
8295
+ }
8296
+
8297
+ /// Upsert one record. Store keys are UTF-8 (1..512 bytes), values are
8298
+ /// bounded at 1 MiB, and the result uses the request shape: `ok=true`
8299
+ /// with empty bytes on success, otherwise `ok=false` with one closed
8300
+ /// StoreOutcome name (`bad_key`, `over_bound`, `io_failed`, `busy`, or
8301
+ /// `rejected`).
8302
+ pub fn storeSet(self: *Self, options: StoreSetOptions) void {
8303
+ if (!record_store.validKey(options.record_key)) return self.rejectStore(options.key, options.on_result, .bad_key);
8304
+ if (options.bytes.len > max_effect_store_value_bytes) return self.rejectStore(options.key, options.on_result, .over_bound);
8305
+ const payload = self.storeFieldsPayload(&.{ options.record_key, options.bytes }) orelse
8306
+ return self.rejectStore(options.key, options.on_result, .rejected);
8307
+ defer self.allocator.free(payload);
8308
+ self.startHostRequest(.{
8309
+ .key = options.key,
8310
+ .name = "core.store.set",
8311
+ .payload = payload,
8312
+ .on_result = options.on_result,
8313
+ }, max_effect_store_value_bytes + max_effect_store_key_bytes + 16, 32, .set, null, null);
8314
+ }
8315
+
8316
+ /// Read one record. The ok payload is a one-byte presence envelope:
8317
+ /// `[1][value...]` for a hit and `[0]` for a miss. The tag keeps an
8318
+ /// empty stored value distinct from absence while retaining the
8319
+ /// existing RequestRoute/EffectHostResult surface.
8320
+ pub fn storeGet(self: *Self, options: StoreGetOptions) void {
8321
+ if (!record_store.validKey(options.record_key)) return self.rejectStore(options.key, options.on_result, .bad_key);
8322
+ const payload = self.storeFieldsPayload(&.{options.record_key}) orelse
8323
+ return self.rejectStore(options.key, options.on_result, .rejected);
8324
+ defer self.allocator.free(payload);
8325
+ self.startHostRequest(.{
8326
+ .key = options.key,
8327
+ .name = "core.store.get",
8328
+ .payload = payload,
8329
+ .on_result = options.on_result,
8330
+ }, max_effect_store_key_bytes + 8, max_effect_store_value_bytes + 1, .get, null, null);
8331
+ }
8332
+
8333
+ /// Delete one record. Missing keys succeed.
8334
+ pub fn storeDelete(self: *Self, options: StoreDeleteOptions) void {
8335
+ if (!record_store.validKey(options.record_key)) return self.rejectStore(options.key, options.on_result, .bad_key);
8336
+ const payload = self.storeFieldsPayload(&.{options.record_key}) orelse
8337
+ return self.rejectStore(options.key, options.on_result, .rejected);
8338
+ defer self.allocator.free(payload);
8339
+ self.startHostRequest(.{
8340
+ .key = options.key,
8341
+ .name = "core.store.delete",
8342
+ .payload = payload,
8343
+ .on_result = options.on_result,
8344
+ }, max_effect_store_key_bytes + 8, 32, .delete, null, null);
8345
+ }
8346
+
8347
+ /// Scan a byte-lexicographic prefix page. The ok payload is
8348
+ /// `[count u32][count * (key_len u32,key,value_len u32,value)]`
8349
+ /// followed by `[next_len u32,next]`; an empty next ends iteration.
8350
+ pub fn storeScan(self: *Self, options: StoreScanOptions) void {
8351
+ if (!record_store.validPrefix(options.prefix) or
8352
+ (options.after.len > 0 and !record_store.validKey(options.after)))
7583
8353
  {
7584
- return self.rejectHost(options.key, options.on_result);
8354
+ return self.rejectStore(options.key, options.on_result, .bad_key);
8355
+ }
8356
+ if (options.limit > max_effect_store_scan_limit) return self.rejectStore(options.key, options.on_result, .over_bound);
8357
+ const len = std.math.add(usize, 16, options.prefix.len) catch
8358
+ return self.rejectStore(options.key, options.on_result, .over_bound);
8359
+ const total = std.math.add(usize, len, options.after.len) catch
8360
+ return self.rejectStore(options.key, options.on_result, .over_bound);
8361
+ const payload = self.allocator.alloc(u8, total) catch
8362
+ return self.rejectStore(options.key, options.on_result, .rejected);
8363
+ defer self.allocator.free(payload);
8364
+ var at: usize = 0;
8365
+ writeStoreU32(payload, &at, 0);
8366
+ writeStoreField(payload, &at, options.prefix);
8367
+ writeStoreU32(payload, &at, options.limit);
8368
+ writeStoreField(payload, &at, options.after);
8369
+ self.startHostRequest(.{
8370
+ .key = options.key,
8371
+ .name = "core.store.scan",
8372
+ .payload = payload,
8373
+ .on_result = options.on_result,
8374
+ }, max_effect_store_key_bytes * 2 + 16, max_effect_store_result_bytes, .scan, null, null);
8375
+ }
8376
+
8377
+ /// Atomically upsert a bounded batch. Validation happens before the
8378
+ /// request starts, and SQLite applies every entry in one transaction.
8379
+ pub fn storeSetMany(self: *Self, options: StoreSetManyOptions) void {
8380
+ if (options.entries.len == 0 or options.entries.len > max_effect_store_batch_entries) {
8381
+ return self.rejectStore(options.key, options.on_result, .over_bound);
8382
+ }
8383
+ var len: usize = 8;
8384
+ for (options.entries) |entry| {
8385
+ if (!record_store.validKey(entry.key)) return self.rejectStore(options.key, options.on_result, .bad_key);
8386
+ if (entry.bytes.len > max_effect_store_value_bytes) return self.rejectStore(options.key, options.on_result, .over_bound);
8387
+ len = std.math.add(usize, len, 8) catch return self.rejectStore(options.key, options.on_result, .over_bound);
8388
+ len = std.math.add(usize, len, entry.key.len) catch return self.rejectStore(options.key, options.on_result, .over_bound);
8389
+ len = std.math.add(usize, len, entry.bytes.len) catch return self.rejectStore(options.key, options.on_result, .over_bound);
8390
+ }
8391
+ if (len > max_effect_store_batch_bytes) return self.rejectStore(options.key, options.on_result, .over_bound);
8392
+ const payload = self.allocator.alloc(u8, len) catch
8393
+ return self.rejectStore(options.key, options.on_result, .rejected);
8394
+ defer self.allocator.free(payload);
8395
+ var at: usize = 0;
8396
+ writeStoreU32(payload, &at, 0);
8397
+ writeStoreU32(payload, &at, @intCast(options.entries.len));
8398
+ for (options.entries) |entry| {
8399
+ writeStoreField(payload, &at, entry.key);
8400
+ writeStoreField(payload, &at, entry.bytes);
8401
+ }
8402
+ self.startHostRequest(.{
8403
+ .key = options.key,
8404
+ .name = "core.store.setMany",
8405
+ .payload = payload,
8406
+ .on_result = options.on_result,
8407
+ }, max_effect_store_batch_bytes, 32, .set_many, null, null);
8408
+ }
8409
+
8410
+ /// Store one secret in the OS credential manager under this app's
8411
+ /// manifest identity. Keychain work is blocking and therefore runs
8412
+ /// in the credential-only worker family. Reissuing `key` replaces
8413
+ /// the old effect; permission and validation refusals are staged so
8414
+ /// a `Cmd.batch` observes them in command-stream order.
8415
+ pub fn credentialsSet(self: *Self, options: CredentialsSetOptions) void {
8416
+ const binding = self.credentials_store_binding orelse
8417
+ return self.rejectCredentials(options.key, .set, options.on_result, options.host_result, .denied);
8418
+ if (!binding.permitted) return self.rejectCredentials(options.key, .set, options.on_result, options.host_result, .denied);
8419
+ if (!credentials_store.validKey(options.credential_key) or options.secret.len > max_effect_credentials_secret_bytes) {
8420
+ return self.rejectCredentials(options.key, .set, options.on_result, options.host_result, .over_bound);
8421
+ }
8422
+ const payload = self.credentialsFieldsPayload(&.{ options.credential_key, options.secret }) orelse
8423
+ return self.rejectCredentials(options.key, .set, options.on_result, options.host_result, .rejected);
8424
+ defer secureFree(self.allocator, payload);
8425
+ self.startHostRequest(.{
8426
+ .key = options.key,
8427
+ .name = "core.credentials.set",
8428
+ .payload = payload,
8429
+ .on_result = options.host_result,
8430
+ }, max_effect_credentials_key_bytes + max_effect_credentials_secret_bytes + 8, 32, null, .set, options.on_result);
8431
+ }
8432
+
8433
+ /// Read one app-scoped secret. A miss is the closed `miss` error
8434
+ /// outcome; successful bytes are ephemeral drain scratch and must not
8435
+ /// be retained outside the receiving update.
8436
+ pub fn credentialsGet(self: *Self, options: CredentialsGetOptions) void {
8437
+ const binding = self.credentials_store_binding orelse
8438
+ return self.rejectCredentials(options.key, .get, options.on_result, options.host_result, .denied);
8439
+ if (!binding.permitted) return self.rejectCredentials(options.key, .get, options.on_result, options.host_result, .denied);
8440
+ if (!credentials_store.validKey(options.credential_key)) {
8441
+ return self.rejectCredentials(options.key, .get, options.on_result, options.host_result, .over_bound);
8442
+ }
8443
+ const payload = self.credentialsFieldsPayload(&.{options.credential_key}) orelse
8444
+ return self.rejectCredentials(options.key, .get, options.on_result, options.host_result, .rejected);
8445
+ defer secureFree(self.allocator, payload);
8446
+ self.startHostRequest(.{
8447
+ .key = options.key,
8448
+ .name = "core.credentials.get",
8449
+ .payload = payload,
8450
+ .on_result = options.host_result,
8451
+ }, max_effect_credentials_key_bytes + 4, max_effect_credentials_secret_bytes, null, .get, options.on_result);
8452
+ }
8453
+
8454
+ /// Delete one app-scoped secret. Deleting a missing entry succeeds.
8455
+ pub fn credentialsDelete(self: *Self, options: CredentialsDeleteOptions) void {
8456
+ const binding = self.credentials_store_binding orelse
8457
+ return self.rejectCredentials(options.key, .delete, options.on_result, options.host_result, .denied);
8458
+ if (!binding.permitted) return self.rejectCredentials(options.key, .delete, options.on_result, options.host_result, .denied);
8459
+ if (!credentials_store.validKey(options.credential_key)) {
8460
+ return self.rejectCredentials(options.key, .delete, options.on_result, options.host_result, .over_bound);
8461
+ }
8462
+ const payload = self.credentialsFieldsPayload(&.{options.credential_key}) orelse
8463
+ return self.rejectCredentials(options.key, .delete, options.on_result, options.host_result, .rejected);
8464
+ defer secureFree(self.allocator, payload);
8465
+ self.startHostRequest(.{
8466
+ .key = options.key,
8467
+ .name = "core.credentials.delete",
8468
+ .payload = payload,
8469
+ .on_result = options.host_result,
8470
+ }, max_effect_credentials_key_bytes + 4, 32, null, .delete, options.on_result);
8471
+ }
8472
+
8473
+ fn credentialsFieldsPayload(self: *Self, fields: []const []const u8) ?[]u8 {
8474
+ var len: usize = 0;
8475
+ for (fields) |field| {
8476
+ len = std.math.add(usize, len, 4) catch return null;
8477
+ len = std.math.add(usize, len, field.len) catch return null;
7585
8478
  }
7586
- if (!fake and self.host_calls == null) return self.rejectHost(options.key, options.on_result);
7587
- // A staged non-regenerating image terminal holds the key
7588
- // exactly like the slot windows below (see
7589
- // `stagedImageOccupiesKey`): under replay that image
7590
- // request is still parked until its journaled terminal
7591
- // feeds, and the parked fake is what rejects this request
7592
- // there.
7593
- if (self.stagedImageOccupiesKey(options.key)) return self.rejectHost(options.key, options.on_result);
7594
- // Channel occupancies hold the shared key space the same
7595
- // way: from open (or a staged executor-truth rejection)
7596
- // until the terminal delivers, live and replayed alike.
7597
- if (self.channelOccupiesKey(options.key) or self.stagedChannelOccupiesKey(options.key)) {
7598
- return self.rejectHost(options.key, options.on_result);
8479
+ const payload = self.allocator.alloc(u8, len) catch return null;
8480
+ var at: usize = 0;
8481
+ for (fields) |field| writeStoreField(payload, &at, field);
8482
+ return payload;
8483
+ }
8484
+
8485
+ fn storeFieldsPayload(self: *Self, fields: []const []const u8) ?[]u8 {
8486
+ var len: usize = 4;
8487
+ for (fields) |field| {
8488
+ len = std.math.add(usize, len, 4) catch return null;
8489
+ len = std.math.add(usize, len, field.len) catch return null;
7599
8490
  }
7600
- // Pty occupancies too: from spawn until the `.exit`
7601
- // terminal delivers, plus the staged executor-truth
7602
- // start-failure window — the same shared-namespace rule
7603
- // every other keyed issuer applies through
7604
- // `keyOccupiedUntilDelivery` (this pre-flight enumerates
7605
- // the families inline only because a same-key HOST
7606
- // occupancy is replaced, never rejected).
7607
- if (self.ptyOccupiesKey(options.key) or self.stagedPtyOccupiesKey(options.key)) {
7608
- return self.rejectHost(options.key, options.on_result);
8491
+ const payload = self.allocator.alloc(u8, len) catch return null;
8492
+ var at: usize = 0;
8493
+ writeStoreU32(payload, &at, 0);
8494
+ for (fields) |field| writeStoreField(payload, &at, field);
8495
+ return payload;
8496
+ }
8497
+
8498
+ fn writeStoreU32(buffer: []u8, at: *usize, value: u32) void {
8499
+ std.mem.writeInt(u32, buffer[at.*..][0..4], value, .little);
8500
+ at.* += 4;
8501
+ }
8502
+
8503
+ fn writeStoreField(buffer: []u8, at: *usize, bytes: []const u8) void {
8504
+ writeStoreU32(buffer, at, @intCast(bytes.len));
8505
+ @memcpy(buffer[at.*..][0..bytes.len], bytes);
8506
+ at.* += bytes.len;
8507
+ }
8508
+
8509
+ fn rejectStore(self: *Self, key: u64, on_result: ?HostMsgFn, outcome: EffectStoreOutcome) void {
8510
+ self.deliverLoopHost(.{ .key = key, .ok = false, .bytes = record_store.outcomeName(outcome) }, on_result, true);
8511
+ }
8512
+
8513
+ fn rejectCredentials(
8514
+ self: *Self,
8515
+ key: u64,
8516
+ operation: EffectCredentialsOperation,
8517
+ credentials_fn: ?CredentialsMsgFn,
8518
+ host_fn: ?HostMsgFn,
8519
+ outcome: EffectCredentialsOutcome,
8520
+ ) void {
8521
+ self.deliverLoopCredentials(.{
8522
+ .key = key,
8523
+ .operation = operation,
8524
+ .outcome = outcome,
8525
+ }, credentials_fn, host_fn);
8526
+ }
8527
+
8528
+ /// Run one read-only SQL statement and stage bounded row pages followed
8529
+ /// by one terminal. Same-key queries replace silently; the already
8530
+ /// staged pages of the older generation are discarded at drain.
8531
+ pub fn dbQuery(self: *Self, options: DbQueryOptions) void {
8532
+ if (!validDbSql(options.sql) or !validDbParams(options.params, relational_store.max_parameter_bytes)) {
8533
+ return self.rejectDb(options.key, .done, options.on_result);
7609
8534
  }
7610
- const slot_index = blk: {
7611
- // In flight = running (no answer yet) OR draining with
7612
- // an undelivered answer: both are replaced, dropping
7613
- // the old result silently (its queued entry dies by
7614
- // generation mismatch at drain). An occupancy of
7615
- // another kind is a key collision and rejects — while
7616
- // running AND through its posted-but-undelivered
7617
- // terminal window (under session replay that request
8535
+ const slot_index = self.claimDbSlot(options.key, .query, options.on_result) orelse {
8536
+ return self.rejectDb(options.key, .done, options.on_result);
8537
+ };
8538
+ const slot = &self.db_slots[slot_index];
8539
+ slot.fake = self.executor == .fake;
8540
+ if (slot.fake) return;
8541
+ self.runDbRead(slot_index, options.sql, options.params);
8542
+ }
8543
+
8544
+ /// Register a long-lived read query. Its initial pages arrive
8545
+ /// immediately; after each successful transaction the engine reruns
8546
+ /// it only when SQLite's update hook named one of `tables`. The slot
8547
+ /// remains parked across `.done` deliveries so replay can feed every
8548
+ /// recorded re-delivery without opening a database.
8549
+ pub fn dbSubscribe(self: *Self, options: DbSubscribeOptions) void {
8550
+ if (!validDbSql(options.sql) or !validDbParams(options.params, relational_store.max_parameter_bytes) or
8551
+ options.tables.len == 0 or options.tables.len > max_effect_db_live_tables)
8552
+ {
8553
+ return self.rejectDb(options.key, .done, options.on_result);
8554
+ }
8555
+ for (options.tables) |table| {
8556
+ if (table.len == 0 or table.len > relational_store.max_table_name_bytes or !std.unicode.utf8ValidateSlice(table))
8557
+ return self.rejectDb(options.key, .done, options.on_result);
8558
+ }
8559
+ if (self.findDbSlot(options.key) != null) return self.rejectDb(options.key, .done, options.on_result);
8560
+ const slot_index = self.claimDbSlot(options.key, .live, options.on_result) orelse
8561
+ return self.rejectDb(options.key, .done, options.on_result);
8562
+ const slot = &self.db_slots[slot_index];
8563
+ slot.live = self.copyDbLive(options) orelse {
8564
+ slot.active = false;
8565
+ return self.rejectDb(options.key, .done, options.on_result);
8566
+ };
8567
+ slot.fake = self.executor == .fake;
8568
+ if (slot.fake) return;
8569
+ self.runDbRead(slot_index, slot.live.?.sql, slot.live.?.params);
8570
+ }
8571
+
8572
+ /// Execute every statement as one atomic transaction. Exec joins the
8573
+ /// spawn discipline: a duplicate live key rejects loudly and never
8574
+ /// replaces a write whose commit is already represented by the Cmd.
8575
+ pub fn dbExec(self: *Self, options: DbExecOptions) void {
8576
+ if (!validDbStatements(options.statements)) return self.rejectDb(options.key, .exec, options.on_result);
8577
+ const slot_index = self.claimDbSlot(options.key, .exec, options.on_result) orelse {
8578
+ return self.rejectDb(options.key, .exec, options.on_result);
8579
+ };
8580
+ const slot = &self.db_slots[slot_index];
8581
+ slot.fake = self.executor == .fake;
8582
+ if (slot.fake) return;
8583
+ const binding = self.relational_store_binding orelse {
8584
+ slot.active = false;
8585
+ return self.rejectDb(options.key, .exec, options.on_result);
8586
+ };
8587
+ const outcome = binding.exec_fn(binding.context, options.statements);
8588
+ self.stageDb(.{
8589
+ .seq = self.nextPendingSeq(),
8590
+ .key = options.key,
8591
+ .generation = slot.generation,
8592
+ .kind = .exec,
8593
+ .outcome = outcome,
8594
+ .db_fn = options.on_result,
8595
+ .regenerates = false,
8596
+ });
8597
+ if (outcome == .ok) self.markDbSubscriptions(binding);
8598
+ }
8599
+
8600
+ /// Silently cancel a read query. Transactions are deliberately not
8601
+ /// cancellable through this API: once issued they either commit whole
8602
+ /// or report a terminal outcome.
8603
+ pub fn cancelDbQuery(self: *Self, key: u64) void {
8604
+ const index = self.findDbSlot(key) orelse return;
8605
+ const slot = &self.db_slots[index];
8606
+ if (slot.kind != .query) return;
8607
+ self.discardPendingDbGeneration(slot.key, slot.generation);
8608
+ slot.active = false;
8609
+ slot.generation = self.takeDbGeneration();
8610
+ }
8611
+
8612
+ pub fn dbUnsubscribe(self: *Self, key: u64) void {
8613
+ const index = self.findDbSlot(key) orelse return;
8614
+ const slot = &self.db_slots[index];
8615
+ if (slot.kind != .live) return;
8616
+ self.discardPendingDbGeneration(slot.key, slot.generation);
8617
+ self.freeDbLive(slot);
8618
+ slot.active = false;
8619
+ slot.generation = self.takeDbGeneration();
8620
+ }
8621
+
8622
+ fn runDbRead(self: *Self, slot_index: usize, sql: []const u8, params: []const EffectDbValue) void {
8623
+ const slot = &self.db_slots[slot_index];
8624
+ const binding = self.relational_store_binding orelse {
8625
+ if (slot.kind != .live) slot.active = false;
8626
+ return self.rejectDb(slot.key, .done, slot.on_result);
8627
+ };
8628
+ var page_context: DbPageContext = .{ .effects = self, .slot_index = slot_index, .generation = slot.generation };
8629
+ const pending_start = self.pending_db_len;
8630
+ const outcome = binding.query_fn(binding.context, sql, params, &page_context, dbPageBound);
8631
+ if (outcome != .ok) self.discardPendingDbTail(pending_start);
8632
+ self.stageDb(.{
8633
+ .seq = self.nextPendingSeq(),
8634
+ .key = slot.key,
8635
+ .generation = slot.generation,
8636
+ .kind = .done,
8637
+ .outcome = outcome,
8638
+ .db_fn = slot.on_result,
8639
+ .regenerates = false,
8640
+ });
8641
+ }
8642
+
8643
+ /// Re-run every live query dirtied by transactions since the previous
8644
+ /// flush. Hosts call this once after walking a whole Cmd batch, so a
8645
+ /// hot table touched by several transactions still produces one
8646
+ /// subscribed result set in the frame.
8647
+ pub fn flushDbSubscriptions(self: *Self) void {
8648
+ for (&self.db_slots, 0..) |*slot, index| {
8649
+ if (!slot.active or slot.kind != .live or slot.fake or !slot.dirty) continue;
8650
+ slot.dirty = false;
8651
+ const live = slot.live orelse continue;
8652
+ self.runDbRead(index, live.sql, live.params);
8653
+ }
8654
+ }
8655
+
8656
+ fn markDbSubscriptions(self: *Self, binding: RelationalStoreBinding) void {
8657
+ const changes = binding.changes_fn(binding.context, self.db_revision);
8658
+ self.db_revision = changes.revision;
8659
+ if (changes.tables.len == 0 and !changes.all_tables) return;
8660
+ for (&self.db_slots) |*slot| {
8661
+ if (!slot.active or slot.kind != .live or slot.fake) continue;
8662
+ if (changes.all_tables) {
8663
+ slot.dirty = true;
8664
+ continue;
8665
+ }
8666
+ const live = slot.live orelse continue;
8667
+ for (live.tables) |dependency| {
8668
+ for (changes.tables) |changed| {
8669
+ if (std.mem.eql(u8, dependency, changed.name())) {
8670
+ slot.dirty = true;
8671
+ break;
8672
+ }
8673
+ }
8674
+ if (slot.dirty) break;
8675
+ }
8676
+ }
8677
+ }
8678
+
8679
+ fn copyDbLive(self: *Self, options: DbSubscribeOptions) ?*DbLiveContext {
8680
+ const context = self.allocator.create(DbLiveContext) catch return null;
8681
+ context.* = .{
8682
+ .sql = self.allocator.dupe(u8, options.sql) catch {
8683
+ self.allocator.destroy(context);
8684
+ return null;
8685
+ },
8686
+ .params = &.{},
8687
+ .tables = &.{},
8688
+ };
8689
+ context.params = self.allocator.alloc(EffectDbValue, options.params.len) catch {
8690
+ self.allocator.free(context.sql);
8691
+ self.allocator.destroy(context);
8692
+ return null;
8693
+ };
8694
+ var copied_params: usize = 0;
8695
+ for (options.params, 0..) |value, index| {
8696
+ context.params[index] = switch (value) {
8697
+ .text => |bytes| .{ .text = self.allocator.dupe(u8, bytes) catch {
8698
+ freeCopiedDbParams(self, context.params[0..copied_params]);
8699
+ self.allocator.free(context.params);
8700
+ self.allocator.free(context.sql);
8701
+ self.allocator.destroy(context);
8702
+ return null;
8703
+ } },
8704
+ .blob => |bytes| .{ .blob = self.allocator.dupe(u8, bytes) catch {
8705
+ freeCopiedDbParams(self, context.params[0..copied_params]);
8706
+ self.allocator.free(context.params);
8707
+ self.allocator.free(context.sql);
8708
+ self.allocator.destroy(context);
8709
+ return null;
8710
+ } },
8711
+ else => value,
8712
+ };
8713
+ copied_params += 1;
8714
+ }
8715
+ context.tables = self.allocator.alloc([]u8, options.tables.len) catch {
8716
+ freeCopiedDbParams(self, context.params);
8717
+ self.allocator.free(context.params);
8718
+ self.allocator.free(context.sql);
8719
+ self.allocator.destroy(context);
8720
+ return null;
8721
+ };
8722
+ var copied_tables: usize = 0;
8723
+ for (options.tables, 0..) |table, index| {
8724
+ context.tables[index] = self.allocator.dupe(u8, table) catch {
8725
+ for (context.tables[0..copied_tables]) |owned| self.allocator.free(owned);
8726
+ self.allocator.free(context.tables);
8727
+ freeCopiedDbParams(self, context.params);
8728
+ self.allocator.free(context.params);
8729
+ self.allocator.free(context.sql);
8730
+ self.allocator.destroy(context);
8731
+ return null;
8732
+ };
8733
+ copied_tables += 1;
8734
+ }
8735
+ return context;
8736
+ }
8737
+
8738
+ fn freeCopiedDbParams(self: *Self, params: []EffectDbValue) void {
8739
+ for (params) |value| switch (value) {
8740
+ .text => |bytes| self.allocator.free(bytes),
8741
+ .blob => |bytes| self.allocator.free(bytes),
8742
+ else => {},
8743
+ };
8744
+ }
8745
+
8746
+ fn freeDbLive(self: *Self, slot: *DbSlot) void {
8747
+ const context = slot.live orelse return;
8748
+ for (context.tables) |table| self.allocator.free(table);
8749
+ if (context.tables.len > 0) self.allocator.free(context.tables);
8750
+ freeCopiedDbParams(self, context.params);
8751
+ if (context.params.len > 0) self.allocator.free(context.params);
8752
+ self.allocator.free(context.sql);
8753
+ self.allocator.destroy(context);
8754
+ slot.live = null;
8755
+ }
8756
+
8757
+ fn claimDbSlot(self: *Self, key: u64, kind: DbSlotKind, on_result: ?DbMsgFn) ?usize {
8758
+ if (self.findDbSlot(key)) |index| {
8759
+ const existing = &self.db_slots[index];
8760
+ if (kind != .query or existing.kind != .query) return null;
8761
+ self.discardPendingDbGeneration(existing.key, existing.generation);
8762
+ existing.generation = self.takeDbGeneration();
8763
+ existing.on_result = on_result;
8764
+ existing.fake = false;
8765
+ return index;
8766
+ }
8767
+ for (&self.db_slots, 0..) |*slot, index| {
8768
+ if (slot.active) continue;
8769
+ slot.* = .{
8770
+ .active = true,
8771
+ .key = key,
8772
+ .generation = self.takeDbGeneration(),
8773
+ .kind = kind,
8774
+ .on_result = on_result,
8775
+ };
8776
+ return index;
8777
+ }
8778
+ return null;
8779
+ }
8780
+
8781
+ fn findDbSlot(self: *Self, key: u64) ?usize {
8782
+ for (&self.db_slots, 0..) |*slot, index| {
8783
+ if (slot.active and slot.key == key) return index;
8784
+ }
8785
+ return null;
8786
+ }
8787
+
8788
+ fn takeDbGeneration(self: *Self) u64 {
8789
+ const generation = self.next_db_generation;
8790
+ self.next_db_generation +%= 1;
8791
+ if (self.next_db_generation == 0) self.next_db_generation = 1;
8792
+ return generation;
8793
+ }
8794
+
8795
+ const DbPageContext = struct {
8796
+ effects: *Self,
8797
+ slot_index: usize,
8798
+ generation: u64,
8799
+ };
8800
+
8801
+ fn dbPageBound(context: *anyopaque, bytes: []const u8) void {
8802
+ const page: *DbPageContext = @ptrCast(@alignCast(context));
8803
+ const slot = &page.effects.db_slots[page.slot_index];
8804
+ page.effects.stageDb(.{
8805
+ .seq = page.effects.nextPendingSeq(),
8806
+ .key = slot.key,
8807
+ .generation = page.generation,
8808
+ .kind = .page,
8809
+ .outcome = .ok,
8810
+ .bytes = if (bytes.len == 0) null else page.effects.allocator.dupe(u8, bytes) catch
8811
+ @panic("effects: out of memory staging a relational row page - a query page is an effect result and must never be dropped"),
8812
+ .db_fn = slot.on_result,
8813
+ .regenerates = false,
8814
+ });
8815
+ }
8816
+
8817
+ fn rejectDb(self: *Self, key: u64, kind: EffectDbResultKind, on_result: ?DbMsgFn) void {
8818
+ self.stageDb(.{
8819
+ .seq = self.nextPendingSeq(),
8820
+ .key = key,
8821
+ .generation = 0,
8822
+ .kind = kind,
8823
+ .outcome = .rejected,
8824
+ .db_fn = on_result,
8825
+ .regenerates = true,
8826
+ .transient = true,
8827
+ });
8828
+ }
8829
+
8830
+ fn validDbSql(sql: []const u8) bool {
8831
+ return sql.len > 0 and sql.len <= max_effect_db_sql_bytes and std.mem.indexOfScalar(u8, sql, 0) == null;
8832
+ }
8833
+
8834
+ fn validDbParams(params: []const EffectDbValue, byte_limit: usize) bool {
8835
+ if (params.len > max_effect_db_parameters) return false;
8836
+ var total: usize = 0;
8837
+ for (params) |value| switch (value) {
8838
+ .text => |bytes| {
8839
+ if (!std.unicode.utf8ValidateSlice(bytes)) return false;
8840
+ total = std.math.add(usize, total, bytes.len) catch return false;
8841
+ },
8842
+ .blob => |bytes| total = std.math.add(usize, total, bytes.len) catch return false,
8843
+ .real => |number| if (!std.math.isFinite(number)) return false,
8844
+ else => {},
8845
+ };
8846
+ return total <= byte_limit;
8847
+ }
8848
+
8849
+ fn validDbStatements(statements: []const EffectDbStatement) bool {
8850
+ if (statements.len == 0 or statements.len > max_effect_db_exec_statements) return false;
8851
+ var total: usize = 0;
8852
+ for (statements) |statement| {
8853
+ if (!validDbSql(statement.sql) or statement.params.len > max_effect_db_parameters) return false;
8854
+ for (statement.params) |value| switch (value) {
8855
+ .text => |bytes| {
8856
+ if (!std.unicode.utf8ValidateSlice(bytes)) return false;
8857
+ total = std.math.add(usize, total, bytes.len) catch return false;
8858
+ },
8859
+ .blob => |bytes| total = std.math.add(usize, total, bytes.len) catch return false,
8860
+ .real => |number| if (!std.math.isFinite(number)) return false,
8861
+ else => {},
8862
+ };
8863
+ if (total > relational_store.max_exec_parameter_bytes) return false;
8864
+ }
8865
+ return true;
8866
+ }
8867
+
8868
+ /// A keyed, routed host command — the generic named host call
8869
+ /// behind a transpiled core's `request` wire records: the host
8870
+ /// performs `name` with `payload` and answers with exactly one
8871
+ /// `feedHostResult(key, ok, bytes)`, delivered as one
8872
+ /// `on_result` Msg (`EffectHostResult`) on the next drain. Key
8873
+ /// discipline is selected by the binding: legacy generic host
8874
+ /// bindings replace a still-live same-key request, while the
8875
+ /// service carrier joins spawn/stream discipline and rejects the
8876
+ /// duplicate without disturbing the first. `cancelHostRequest`
8877
+ /// drops one without dispatching anything. Rejection is never silent:
8878
+ /// an over-bound name/payload, a key colliding with another
8879
+ /// effect kind, a full slot table, or a real-mode channel with
8880
+ /// no bound host services delivers exactly one err-route Msg
8881
+ /// (`ok = false`, bytes `"rejected"`). Under the fake executor
8882
+ /// the request parks in its slot (inspect with `pendingHostAt`,
8883
+ /// answer with `feedHostResult`).
8884
+ pub fn hostRequest(self: *Self, options: HostRequestOptions) void {
8885
+ self.startHostRequest(options, max_effect_host_payload_bytes, max_effect_host_result_bytes, null, null, null);
8886
+ }
8887
+
8888
+ fn startHostRequest(
8889
+ self: *Self,
8890
+ options: HostRequestOptions,
8891
+ payload_limit: usize,
8892
+ result_limit: usize,
8893
+ store_op: ?EffectStoreOp,
8894
+ credentials_op: ?EffectCredentialsOperation,
8895
+ credentials_fn: ?CredentialsMsgFn,
8896
+ ) void {
8897
+ self.reclaimSlots();
8898
+ const fake = self.executor == .fake;
8899
+ const store_request = store_op != null;
8900
+ const credentials_request = credentials_op != null;
8901
+ const native_request = isNativeHostRequestName(options.name);
8902
+ if (options.name.len == 0 or options.name.len > max_effect_host_name_bytes or
8903
+ options.payload.len > payload_limit)
8904
+ {
8905
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
8906
+ }
8907
+ if (!fake and self.host_calls == null and !native_request and !credentials_request) {
8908
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
8909
+ }
8910
+ // A staged non-regenerating image terminal holds the key
8911
+ // exactly like the slot windows below (see
8912
+ // `stagedImageOccupiesKey`): under replay that image
8913
+ // request is still parked until its journaled terminal
8914
+ // feeds, and the parked fake is what rejects this request
8915
+ // there.
8916
+ if (self.stagedImageOccupiesKey(options.key)) return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
8917
+ // Channel occupancies hold the shared key space the same
8918
+ // way: from open (or a staged executor-truth rejection)
8919
+ // until the terminal delivers, live and replayed alike.
8920
+ if (self.channelOccupiesKey(options.key) or self.stagedChannelOccupiesKey(options.key)) {
8921
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
8922
+ }
8923
+ // Pty occupancies too: from spawn until the `.exit`
8924
+ // terminal delivers, plus the staged executor-truth
8925
+ // start-failure window — the same shared-namespace rule
8926
+ // every other keyed issuer applies through
8927
+ // `keyOccupiedUntilDelivery` (this pre-flight enumerates
8928
+ // the families inline only because a same-key HOST
8929
+ // occupancy is replaced, never rejected).
8930
+ if (self.ptyOccupiesKey(options.key) or self.stagedPtyOccupiesKey(options.key)) {
8931
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
8932
+ }
8933
+ const slot_index = blk: {
8934
+ // In flight = running (no answer yet) OR draining with
8935
+ // an undelivered answer: both are replaced, dropping
8936
+ // the old result silently (its queued entry dies by
8937
+ // generation mismatch at drain). An occupancy of
8938
+ // another kind is a key collision and rejects — while
8939
+ // running AND through its posted-but-undelivered
8940
+ // terminal window (under session replay that request
7618
8941
  // is still a parked `.running` fake until its
7619
8942
  // journaled terminal feeds, so accepting the key here
7620
8943
  // live would diverge); a drained one is fully
@@ -7624,39 +8947,69 @@ pub fn Effects(comptime Msg: type) type {
7624
8947
  const state = slot.state.load(.acquire);
7625
8948
  if (state != .running and state != .draining) continue;
7626
8949
  if (slot.key != options.key) continue;
7627
- if (slot.kind != .host) {
8950
+ const expected_kind: SlotKind = if (store_request) .store else if (credentials_request) .credentials else .host;
8951
+ if (slot.kind != expected_kind) {
7628
8952
  if (state == .running or slotTerminalUndelivered(slot)) {
7629
- return self.rejectHost(options.key, options.on_result);
8953
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
7630
8954
  }
7631
8955
  continue;
7632
8956
  }
8957
+ // Work already handed to SQLite or the credential
8958
+ // manager is only logically cancelled: its terminal is
8959
+ // swallowed. A credential replacement which has not
8960
+ // reached the platform yet is reusable, however; this
8961
+ // coalesces a burst to the newest request while the one
8962
+ // active keychain call finishes.
8963
+ if ((slot.kind == .store or slot.kind == .credentials) and state == .running and !slot.fake and slot.worker_thread != null) {
8964
+ slot.cancelled_generation = slot.generation;
8965
+ slot.cancel_requested.store(true, .release);
8966
+ continue;
8967
+ }
8968
+ if (!native_request and self.host_calls != null and self.host_calls.?.reject_duplicate_keys) {
8969
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
8970
+ }
7633
8971
  // Tell the host first: a late answer for the old
7634
8972
  // occupancy must find nothing.
7635
- if (state == .running and !slot.fake) self.notifyHostCancel(options.key);
8973
+ if (slot.kind == .host and state == .running and !slot.fake) self.notifyHostCancel(options.key);
8974
+ if ((slot.kind == .store or slot.kind == .credentials) and state == .draining) joinWorker(slot);
7636
8975
  self.releaseFetchSlot(slot);
7637
8976
  slot.generation = 0;
7638
8977
  replaced = index;
7639
8978
  }
7640
8979
  break :blk replaced orelse
7641
- (self.findIdleSlot() orelse return self.rejectHost(options.key, options.on_result));
8980
+ ((if (store_request) self.findIdleStoreSlot() else if (credentials_request) self.findIdleCredentialsSlot() else self.findIdleSlot()) orelse
8981
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn));
7642
8982
  };
7643
8983
 
7644
8984
  const slot = &self.slots[slot_index];
7645
8985
  // The buffer holds the payload copy, then the result space.
7646
- const buffer = self.allocator.alloc(u8, options.payload.len + max_effect_host_result_bytes) catch {
7647
- return self.rejectHost(options.key, options.on_result);
8986
+ const total_buffer_len = std.math.add(usize, options.payload.len, result_limit) catch {
8987
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
8988
+ };
8989
+ const buffer = self.allocator.alloc(u8, total_buffer_len) catch {
8990
+ return self.rejectStartedHost(options.key, options.on_result, credentials_op, credentials_fn);
7648
8991
  };
7649
8992
  slot.generation = self.next_generation;
7650
8993
  self.next_generation +%= 1;
7651
8994
  if (self.next_generation == 0) self.next_generation = 1;
7652
8995
  slot.key = options.key;
7653
- slot.kind = .host;
8996
+ slot.kind = if (store_request) .store else if (credentials_request) .credentials else .host;
8997
+ if (credentials_op) |operation| {
8998
+ slot.credentials_op = operation;
8999
+ slot.credentials_sequence = self.next_credentials_sequence;
9000
+ self.next_credentials_sequence +%= 1;
9001
+ if (self.next_credentials_sequence == 0) self.next_credentials_sequence = 1;
9002
+ slot.credentials_waiting = !fake;
9003
+ } else {
9004
+ slot.credentials_waiting = false;
9005
+ }
7654
9006
  slot.on_line = null;
7655
9007
  slot.on_exit = null;
7656
9008
  slot.on_response = null;
7657
9009
  slot.on_file = null;
7658
9010
  slot.on_clipboard = null;
7659
9011
  slot.on_host = options.on_result;
9012
+ slot.on_credentials = credentials_fn;
7660
9013
  slot.cancel_requested.store(false, .release);
7661
9014
  // `cancelled_generation` stays sticky, exactly as in `spawn`.
7662
9015
  slot.dropped_pending = 0;
@@ -7667,7 +9020,10 @@ pub fn Effects(comptime Msg: type) type {
7667
9020
  self.allocator.free(old);
7668
9021
  slot.line_buffer = null;
7669
9022
  }
7670
- if (slot.fetch_buffer) |old| self.allocator.free(old);
9023
+ if (slot.fetch_buffer) |old| {
9024
+ if (credentials_request) std.crypto.secureZero(u8, old);
9025
+ self.allocator.free(old);
9026
+ }
7671
9027
  slot.fetch_buffer = buffer;
7672
9028
  @memcpy(buffer[0..options.payload.len], options.payload);
7673
9029
  slot.payload_len = options.payload.len;
@@ -7678,10 +9034,445 @@ pub fn Effects(comptime Msg: type) type {
7678
9034
  // Fake mode (tests and session replay) parks here: the feed
7679
9035
  // is the only terminal source.
7680
9036
  if (fake) return;
9037
+ if (store_op) |operation| {
9038
+ if (operation == .get or operation == .scan) {
9039
+ self.performBoundStoreRequest(slot.hostName(), options.key, slot.fetchPayload());
9040
+ } else {
9041
+ self.startStoreWorker(slot_index, operation);
9042
+ }
9043
+ return;
9044
+ }
9045
+ if (credentials_op != null) {
9046
+ self.startNextCredentialsWorker();
9047
+ return;
9048
+ }
9049
+ if (native_request) {
9050
+ self.performNativeHostRequest(slot.hostName(), options.key, slot.fetchPayload());
9051
+ return;
9052
+ }
7681
9053
  const binding = self.host_calls.?;
7682
9054
  binding.request_fn(binding.context, slot.hostName(), options.key, slot.fetchPayload());
7683
9055
  }
7684
9056
 
9057
+ fn isNativeHostRequestName(name: []const u8) bool {
9058
+ return std.mem.startsWith(u8, name, "core.store.") or
9059
+ std.mem.eql(u8, name, "native-sdk.launch-at-login.status") or
9060
+ std.mem.eql(u8, name, "native-sdk.launch-at-login.set") or
9061
+ std.mem.eql(u8, name, "native-sdk.time.formatLocal");
9062
+ }
9063
+
9064
+ fn isNativeHostSendName(name: []const u8) bool {
9065
+ return std.mem.eql(u8, name, "native-sdk.os.openUrl") or
9066
+ std.mem.eql(u8, name, "native-sdk.os.revealPath");
9067
+ }
9068
+
9069
+ fn performNativeHostSend(self: *Self, name: []const u8, payload: []const u8) void {
9070
+ const binding = self.system_services orelse return;
9071
+ if (std.mem.eql(u8, name, "native-sdk.os.openUrl")) {
9072
+ binding.open_external_url_fn(binding.context, payload) catch {};
9073
+ } else {
9074
+ binding.reveal_path_fn(binding.context, payload) catch {};
9075
+ }
9076
+ }
9077
+
9078
+ fn performNativeHostRequest(self: *Self, name: []const u8, key: u64, payload: []const u8) void {
9079
+ if (std.mem.startsWith(u8, name, "core.store.")) {
9080
+ self.performBoundStoreRequest(name, key, payload);
9081
+ return;
9082
+ }
9083
+ if (std.mem.eql(u8, name, "native-sdk.time.formatLocal")) {
9084
+ self.performBoundSystemRequest(name, key, payload);
9085
+ return;
9086
+ }
9087
+ const services = self.services orelse {
9088
+ self.feedHostResult(key, false, "unsupported") catch {};
9089
+ return;
9090
+ };
9091
+ if (std.mem.eql(u8, name, "native-sdk.launch-at-login.status")) {
9092
+ if (payload.len != 0) {
9093
+ self.feedHostResult(key, false, "invalid_request") catch {};
9094
+ return;
9095
+ }
9096
+ const status = services.launchAtLoginStatus() catch |err| {
9097
+ self.feedHostResult(key, false, launchAtLoginErrorName(err)) catch {};
9098
+ return;
9099
+ };
9100
+ self.feedHostResult(key, true, launchAtLoginStatusName(status)) catch {};
9101
+ return;
9102
+ }
9103
+ if (payload.len != 1 or payload[0] > 1) {
9104
+ self.feedHostResult(key, false, "invalid_request") catch {};
9105
+ return;
9106
+ }
9107
+ const status = services.setLaunchAtLogin(payload[0] == 1) catch |err| {
9108
+ self.feedHostResult(key, false, launchAtLoginErrorName(err)) catch {};
9109
+ return;
9110
+ };
9111
+ self.feedHostResult(key, true, launchAtLoginStatusName(status)) catch {};
9112
+ }
9113
+
9114
+ fn performBoundStoreRequest(self: *Self, name: []const u8, key: u64, payload: []const u8) void {
9115
+ const binding = self.record_store_binding orelse {
9116
+ self.feedHostResult(key, false, "rejected") catch {};
9117
+ return;
9118
+ };
9119
+ const op: EffectStoreOp = if (std.mem.eql(u8, name, "core.store.set"))
9120
+ .set
9121
+ else if (std.mem.eql(u8, name, "core.store.get"))
9122
+ .get
9123
+ else if (std.mem.eql(u8, name, "core.store.delete"))
9124
+ .delete
9125
+ else if (std.mem.eql(u8, name, "core.store.scan"))
9126
+ .scan
9127
+ else if (std.mem.eql(u8, name, "core.store.setMany"))
9128
+ .set_many
9129
+ else {
9130
+ self.feedHostResult(key, false, "rejected") catch {};
9131
+ return;
9132
+ };
9133
+ const output = self.allocator.alloc(u8, max_effect_store_result_bytes) catch {
9134
+ self.feedHostResult(key, false, "rejected") catch {};
9135
+ return;
9136
+ };
9137
+ defer self.allocator.free(output);
9138
+ const execution = binding.execute_fn(binding.context, op, payload, output);
9139
+ if (execution.len > output.len) {
9140
+ self.feedHostResult(key, false, "over_bound") catch {};
9141
+ return;
9142
+ }
9143
+ switch (execution.outcome) {
9144
+ .ok, .miss => self.feedHostResult(key, true, output[0..execution.len]) catch {},
9145
+ else => self.feedHostResult(key, false, record_store.outcomeName(execution.outcome)) catch {},
9146
+ }
9147
+ }
9148
+
9149
+ /// Start one store write on the store-reserved worker family. The
9150
+ /// binding reserves a monotonic SQLite position on this loop thread;
9151
+ /// workers therefore commit in command-stream order even if the OS
9152
+ /// schedules their threads differently.
9153
+ fn startStoreWorker(self: *Self, slot_index: usize, operation: EffectStoreOp) void {
9154
+ const slot = &self.slots[slot_index];
9155
+ if (comptime !io_threaded_supported) {
9156
+ self.feedHostResult(slot.key, false, "rejected") catch {};
9157
+ return;
9158
+ }
9159
+ const binding = self.record_store_binding orelse {
9160
+ self.feedHostResult(slot.key, false, "rejected") catch {};
9161
+ return;
9162
+ };
9163
+ const payload = process_allocator.dupe(u8, slot.fetchPayload()) catch {
9164
+ self.feedHostResult(slot.key, false, "rejected") catch {};
9165
+ return;
9166
+ };
9167
+ const ctx = process_allocator.create(StoreWorkerContext) catch {
9168
+ process_allocator.free(payload);
9169
+ self.feedHostResult(slot.key, false, "rejected") catch {};
9170
+ return;
9171
+ };
9172
+ ctx.* = .{
9173
+ .binding = binding,
9174
+ .operation = operation,
9175
+ .sequence = 0,
9176
+ .payload = payload,
9177
+ };
9178
+ slot.store_ctx = ctx;
9179
+ const thread = std.Thread.spawn(.{}, storeWorkerMain, .{ self, slot_index, slot.generation, ctx }) catch {
9180
+ slot.store_ctx = null;
9181
+ process_allocator.free(payload);
9182
+ process_allocator.destroy(ctx);
9183
+ self.feedHostResult(slot.key, false, "rejected") catch {};
9184
+ return;
9185
+ };
9186
+ slot.worker_thread = thread;
9187
+ ctx.sequence = binding.reserve_write_fn(binding.context);
9188
+ ctx.sequence_ready.store(true, .release);
9189
+ }
9190
+
9191
+ fn storeWorkerMain(self: *Self, slot_index: usize, generation: u32, ctx: *StoreWorkerContext) void {
9192
+ while (!ctx.sequence_ready.load(.acquire)) std.atomic.spinLoopHint();
9193
+ const execution = ctx.binding.execute_write_fn(
9194
+ ctx.binding.context,
9195
+ ctx.sequence,
9196
+ ctx.operation,
9197
+ ctx.payload,
9198
+ &ctx.output,
9199
+ );
9200
+ ctx.outcome = execution.outcome;
9201
+ ctx.output_len = @min(execution.len, ctx.output.len);
9202
+
9203
+ const slot = &self.slots[slot_index];
9204
+ const buffer = slot.fetch_buffer orelse {
9205
+ slot.state.store(.done, .release);
9206
+ return;
9207
+ };
9208
+ const result: []const u8 = switch (execution.outcome) {
9209
+ .ok, .miss => ctx.output[0..ctx.output_len],
9210
+ else => record_store.outcomeName(execution.outcome),
9211
+ };
9212
+ const capacity = buffer.len - slot.payload_len;
9213
+ const within_bound = execution.len <= ctx.output.len and result.len <= capacity;
9214
+ const delivered = if (within_bound) result else "over_bound";
9215
+ @memcpy(buffer[slot.payload_len..][0..delivered.len], delivered);
9216
+ slot.body_len = delivered.len;
9217
+ var entry: Entry = .{
9218
+ .kind = .host,
9219
+ .slot_index = @intCast(slot_index),
9220
+ .generation = generation,
9221
+ .key = slot.key,
9222
+ .line_len = @intCast(delivered.len),
9223
+ .host_ok = within_bound and (execution.outcome == .ok or execution.outcome == .miss),
9224
+ .host_fn = slot.on_host,
9225
+ };
9226
+ while (!self.enqueue(&entry)) {
9227
+ if (self.shutdown.load(.acquire)) {
9228
+ slot.state.store(.done, .release);
9229
+ return;
9230
+ }
9231
+ std.atomic.spinLoopHint();
9232
+ }
9233
+ slot.state.store(.draining, .release);
9234
+ self.wakeHost();
9235
+ }
9236
+
9237
+ /// Start the oldest queued real credential operation when no other
9238
+ /// keychain call is active. Serial execution preserves command issue
9239
+ /// order across platform APIs that provide no ordering of their own.
9240
+ fn startNextCredentialsWorker(self: *Self) void {
9241
+ if (comptime !io_threaded_supported) return;
9242
+ if (self.shutdown.load(.acquire)) return;
9243
+ for (&self.slots) |*slot| {
9244
+ if (slot.kind != .credentials or slot.fake or slot.worker_thread == null) continue;
9245
+ if (slot.state.load(.acquire) == .running) return;
9246
+ joinWorker(slot);
9247
+ }
9248
+ var oldest: ?usize = null;
9249
+ for (&self.slots, 0..) |*slot, index| {
9250
+ if (slot.kind != .credentials or slot.fake or !slot.credentials_waiting) continue;
9251
+ if (slot.state.load(.acquire) != .running) continue;
9252
+ if (oldest == null or slot.credentials_sequence < self.slots[oldest.?].credentials_sequence) oldest = index;
9253
+ }
9254
+ const slot_index = oldest orelse return;
9255
+ const slot = &self.slots[slot_index];
9256
+ slot.credentials_waiting = false;
9257
+ self.startCredentialsWorker(slot_index, slot.credentials_op);
9258
+ }
9259
+
9260
+ fn startCredentialsWorker(self: *Self, slot_index: usize, operation: EffectCredentialsOperation) void {
9261
+ const slot = &self.slots[slot_index];
9262
+ if (comptime !io_threaded_supported) {
9263
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.locked)) catch {};
9264
+ return;
9265
+ }
9266
+ const binding = self.credentials_store_binding orelse {
9267
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.denied)) catch {};
9268
+ return;
9269
+ };
9270
+ // A blocking platform call can outlive the runtime only when the
9271
+ // platform supplies the destruction latch that preserves its
9272
+ // callback context. First-party hosts all wire this seam.
9273
+ if (binding.services.note_blocking_call_abandoned_fn == null) {
9274
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.locked)) catch {};
9275
+ return;
9276
+ }
9277
+ var at: usize = 0;
9278
+ const credential_key = takeNativeRequestBytes(slot.fetchPayload(), &at) orelse {
9279
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9280
+ return;
9281
+ };
9282
+ const secret = if (operation == .set)
9283
+ takeNativeRequestBytes(slot.fetchPayload(), &at) orelse {
9284
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9285
+ return;
9286
+ }
9287
+ else
9288
+ "";
9289
+ if (at != slot.payload_len) {
9290
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9291
+ return;
9292
+ }
9293
+ const key_copy = process_allocator.dupe(u8, credential_key) catch {
9294
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9295
+ return;
9296
+ };
9297
+ const secret_copy = process_allocator.dupe(u8, secret) catch {
9298
+ process_allocator.free(key_copy);
9299
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9300
+ return;
9301
+ };
9302
+ const service_copy = process_allocator.dupe(u8, binding.service) catch {
9303
+ secureFree(process_allocator, secret_copy);
9304
+ process_allocator.free(key_copy);
9305
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9306
+ return;
9307
+ };
9308
+ const output = process_allocator.alloc(u8, max_effect_credentials_secret_bytes) catch {
9309
+ process_allocator.free(service_copy);
9310
+ secureFree(process_allocator, secret_copy);
9311
+ process_allocator.free(key_copy);
9312
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9313
+ return;
9314
+ };
9315
+ const ctx = process_allocator.create(CredentialsWorkerContext) catch {
9316
+ secureFree(process_allocator, output);
9317
+ process_allocator.free(service_copy);
9318
+ secureFree(process_allocator, secret_copy);
9319
+ process_allocator.free(key_copy);
9320
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9321
+ return;
9322
+ };
9323
+ ctx.* = .{
9324
+ .services = binding.services.*,
9325
+ .service = service_copy,
9326
+ .permitted = binding.permitted,
9327
+ .operation = operation,
9328
+ .key = key_copy,
9329
+ .secret = secret_copy,
9330
+ .output = output,
9331
+ };
9332
+ slot.credentials_ctx = ctx;
9333
+ const thread = std.Thread.spawn(.{}, credentialsWorkerMain, .{ self, slot_index, slot.generation, ctx }) catch {
9334
+ slot.credentials_ctx = null;
9335
+ destroyCredentialsContext(ctx);
9336
+ self.feedHostResult(slot.key, false, credentials_store.outcomeName(.rejected)) catch {};
9337
+ return;
9338
+ };
9339
+ slot.worker_thread = thread;
9340
+ }
9341
+
9342
+ fn credentialsWorkerMain(self: *Self, slot_index: usize, generation: u32, ctx: *CredentialsWorkerContext) void {
9343
+ ctx.execution = credentials_store.execute(.{
9344
+ .services = &ctx.services,
9345
+ .service = ctx.service,
9346
+ .permitted = ctx.permitted,
9347
+ }, ctx.operation, ctx.key, ctx.secret, ctx.output);
9348
+ // Core delete is idempotent. The shared adapter preserves `.miss`
9349
+ // so the existing WebView bridge can keep returning false for a
9350
+ // missing entry; only this core-effect surface promotes it to ok.
9351
+ if (ctx.operation == .delete and ctx.execution.outcome == .miss) {
9352
+ ctx.execution = .{ .outcome = .ok };
9353
+ }
9354
+ // Commit to touching the runtime only while teardown still owns
9355
+ // it. If teardown won this fence, the detached worker owns and
9356
+ // scrubs its private block when the OS call eventually returns.
9357
+ ctx.mutex.lock();
9358
+ if (ctx.abandoned) {
9359
+ ctx.mutex.unlock();
9360
+ destroyCredentialsContext(ctx);
9361
+ return;
9362
+ }
9363
+ ctx.committed = true;
9364
+ ctx.mutex.unlock();
9365
+ const slot = &self.slots[slot_index];
9366
+ const buffer = slot.fetch_buffer orelse {
9367
+ slot.state.store(.done, .release);
9368
+ return;
9369
+ };
9370
+ const result: []const u8 = if (ctx.execution.outcome == .ok)
9371
+ ctx.output[0..@min(ctx.execution.len, ctx.output.len)]
9372
+ else
9373
+ credentials_store.outcomeName(ctx.execution.outcome);
9374
+ const capacity = buffer.len - slot.payload_len;
9375
+ const within_bound = ctx.execution.len <= ctx.output.len and result.len <= capacity;
9376
+ const delivered = if (within_bound) result else credentials_store.outcomeName(.over_bound);
9377
+ @memcpy(buffer[slot.payload_len..][0..delivered.len], delivered);
9378
+ slot.body_len = delivered.len;
9379
+ var entry: Entry = .{
9380
+ .kind = .host,
9381
+ .slot_index = @intCast(slot_index),
9382
+ .generation = generation,
9383
+ .key = slot.key,
9384
+ .line_len = @intCast(delivered.len),
9385
+ .host_ok = within_bound and ctx.execution.outcome == .ok,
9386
+ .host_fn = slot.on_host,
9387
+ .credentials_fn = slot.on_credentials,
9388
+ };
9389
+ while (!self.enqueue(&entry)) {
9390
+ if (self.shutdown.load(.acquire)) {
9391
+ slot.state.store(.done, .release);
9392
+ return;
9393
+ }
9394
+ std.atomic.spinLoopHint();
9395
+ }
9396
+ slot.state.store(.draining, .release);
9397
+ self.wakeHost();
9398
+ }
9399
+
9400
+ fn performBoundSystemRequest(self: *Self, name: []const u8, key: u64, payload: []const u8) void {
9401
+ const binding = self.system_services orelse {
9402
+ self.feedHostResult(key, false, "unsupported") catch {};
9403
+ return;
9404
+ };
9405
+
9406
+ if (std.mem.eql(u8, name, "native-sdk.time.formatLocal")) {
9407
+ if (payload.len != 16) return self.feedInvalidNativeRequest(key);
9408
+ const style_value: f64 = @bitCast(std.mem.readInt(u64, payload[0..8], .little));
9409
+ const timestamp_value: f64 = @bitCast(std.mem.readInt(u64, payload[8..16], .little));
9410
+ if (!std.math.isFinite(style_value) or style_value != @floor(style_value) or style_value < 0 or style_value > 2 or
9411
+ !std.math.isFinite(timestamp_value) or timestamp_value != @floor(timestamp_value) or
9412
+ timestamp_value < -8_640_000_000_000_000 or timestamp_value > 8_640_000_000_000_000)
9413
+ {
9414
+ return self.feedInvalidNativeRequest(key);
9415
+ }
9416
+ const style: platform.LocalTimeStyle = @enumFromInt(@as(u8, @intFromFloat(style_value)));
9417
+ const timestamp_ms: i64 = @intFromFloat(timestamp_value);
9418
+ var result_buffer: [platform.max_local_time_text_bytes]u8 = undefined;
9419
+ const result = binding.format_local_time_fn(binding.context, timestamp_ms, style, &result_buffer) catch |err| {
9420
+ self.feedHostResult(key, false, systemServiceErrorName(err)) catch {};
9421
+ return;
9422
+ };
9423
+ if (result.len == 0 or result.len > result_buffer.len) return self.feedInvalidNativeRequest(key);
9424
+ self.feedHostResult(key, true, result) catch {};
9425
+ return;
9426
+ }
9427
+
9428
+ self.feedInvalidNativeRequest(key);
9429
+ }
9430
+
9431
+ fn takeNativeRequestBytes(payload: []const u8, at: *usize) ?[]const u8 {
9432
+ if (at.* > payload.len or payload.len - at.* < 4) return null;
9433
+ const len: usize = std.mem.readInt(u32, payload[at.*..][0..4], .little);
9434
+ at.* += 4;
9435
+ if (len > payload.len - at.*) return null;
9436
+ const bytes = payload[at.*..][0..len];
9437
+ at.* += len;
9438
+ return bytes;
9439
+ }
9440
+
9441
+ fn feedInvalidNativeRequest(self: *Self, key: u64) void {
9442
+ self.feedHostResult(key, false, "invalid_request") catch {};
9443
+ }
9444
+
9445
+ fn systemServiceErrorName(err: anyerror) []const u8 {
9446
+ return switch (err) {
9447
+ error.UnsupportedService => "unsupported",
9448
+ error.InvalidCredentialOptions,
9449
+ error.CredentialFieldTooLarge,
9450
+ error.InvalidExternalUrl,
9451
+ error.ExternalUrlTooLarge,
9452
+ error.InvalidRevealPath,
9453
+ error.RevealPathTooLarge,
9454
+ => "invalid_request",
9455
+ error.CredentialNotFound => "not_found",
9456
+ else => "failed",
9457
+ };
9458
+ }
9459
+
9460
+ fn launchAtLoginStatusName(status: platform.LaunchAtLoginStatus) []const u8 {
9461
+ return switch (status) {
9462
+ .disabled => "disabled",
9463
+ .enabled => "enabled",
9464
+ .requires_approval => "requires_approval",
9465
+ .not_found => "not_found",
9466
+ };
9467
+ }
9468
+
9469
+ fn launchAtLoginErrorName(err: anyerror) []const u8 {
9470
+ return switch (err) {
9471
+ error.UnsupportedService => "unsupported",
9472
+ else => "failed",
9473
+ };
9474
+ }
9475
+
7685
9476
  /// Drop the in-flight host request with `key` without
7686
9477
  /// dispatching either route — the wire contract's `cancel`
7687
9478
  /// record. Silent by design (unlike `cancel`, which delivers a
@@ -7693,8 +9484,14 @@ pub fn Effects(comptime Msg: type) type {
7693
9484
  for (&self.slots) |*slot| {
7694
9485
  const state = slot.state.load(.acquire);
7695
9486
  if (state != .running and state != .draining) continue;
7696
- if (slot.kind != .host or slot.key != key) continue;
7697
- if (state == .running and !slot.fake) self.notifyHostCancel(key);
9487
+ if ((slot.kind != .host and slot.kind != .store and slot.kind != .credentials) or slot.key != key) continue;
9488
+ if ((slot.kind == .store or slot.kind == .credentials) and state == .running and !slot.fake and slot.worker_thread != null) {
9489
+ slot.cancelled_generation = slot.generation;
9490
+ slot.cancel_requested.store(true, .release);
9491
+ continue;
9492
+ }
9493
+ if (slot.kind == .host and state == .running and !slot.fake) self.notifyHostCancel(key);
9494
+ if ((slot.kind == .store or slot.kind == .credentials) and state == .draining) joinWorker(slot);
7698
9495
  self.releaseFetchSlot(slot);
7699
9496
  // A queued result entry (fed, undrained) dies by
7700
9497
  // generation mismatch; zero marks "no occupancy".
@@ -7714,6 +9511,19 @@ pub fn Effects(comptime Msg: type) type {
7714
9511
  self.deliverLoopHost(.{ .key = key, .ok = false, .bytes = "rejected" }, host_fn, true);
7715
9512
  }
7716
9513
 
9514
+ fn rejectStartedHost(
9515
+ self: *Self,
9516
+ key: u64,
9517
+ host_fn: ?HostMsgFn,
9518
+ credentials_op: ?EffectCredentialsOperation,
9519
+ credentials_fn: ?CredentialsMsgFn,
9520
+ ) void {
9521
+ if (credentials_op) |operation| {
9522
+ return self.rejectCredentials(key, operation, credentials_fn, host_fn, .rejected);
9523
+ }
9524
+ self.rejectHost(key, host_fn);
9525
+ }
9526
+
7717
9527
  /// Queue a host terminal produced on the loop thread
7718
9528
  /// (rejections and feed fallbacks) for the next drain. Bytes
7719
9529
  /// here are always static.
@@ -7722,6 +9532,20 @@ pub fn Effects(comptime Msg: type) type {
7722
9532
  self.deliverPending(.{ .host = .{ .result = result, .host_fn = host_fn, .rejected = rejected } });
7723
9533
  }
7724
9534
 
9535
+ fn deliverLoopCredentials(
9536
+ self: *Self,
9537
+ result: EffectCredentialsResult,
9538
+ credentials_fn: ?CredentialsMsgFn,
9539
+ host_fn: ?HostMsgFn,
9540
+ ) void {
9541
+ if (credentials_fn == null and host_fn == null) return;
9542
+ self.deliverPending(.{ .credentials = .{
9543
+ .result = result,
9544
+ .credentials_fn = credentials_fn,
9545
+ .host_fn = host_fn,
9546
+ } });
9547
+ }
9548
+
7725
9549
  /// Cancel a running effect by key. After this returns, no
7726
9550
  /// further `on_line` Msgs for that spawn are dispatched; one
7727
9551
  /// `on_exit` Msg with reason `.cancelled` follows once the
@@ -7743,7 +9567,7 @@ pub fn Effects(comptime Msg: type) type {
7743
9567
  return;
7744
9568
  };
7745
9569
  const slot = &self.slots[slot_index];
7746
- if (slot.kind == .host) return self.cancelHostRequest(key);
9570
+ if (slot.kind == .host or slot.kind == .store or slot.kind == .credentials) return self.cancelHostRequest(key);
7747
9571
  slot.cancelled_generation = slot.generation;
7748
9572
  slot.cancel_requested.store(true, .release);
7749
9573
  if (slot.fake) {
@@ -8041,6 +9865,16 @@ pub fn Effects(comptime Msg: type) type {
8041
9865
  _ = binding.minimize_fn(binding.context, window_label);
8042
9866
  }
8043
9867
 
9868
+ /// Hide a live window by its declared label while retaining its
9869
+ /// native identity and views. `showWindow` is the inverse.
9870
+ pub fn hideWindow(self: *Self, window_label: []const u8) void {
9871
+ self.window_action_state.hide_count += 1;
9872
+ self.window_action_state.record(window_label);
9873
+ if (self.executor == .fake) return;
9874
+ const binding = self.window_actions orelse return;
9875
+ _ = binding.hide_fn(binding.context, window_label);
9876
+ }
9877
+
8044
9878
  /// Show a window by its declared label: unhide + order front,
8045
9879
  /// activating by default and remaining passive for an
8046
9880
  /// `activate_on_show = false` overlay. It is the counterpart to
@@ -8057,6 +9891,17 @@ pub fn Effects(comptime Msg: type) type {
8057
9891
  _ = binding.show_fn(binding.context, window_label);
8058
9892
  }
8059
9893
 
9894
+ /// Control the app's Dock/app-switcher presence. On macOS this
9895
+ /// switches between regular and accessory activation policies;
9896
+ /// unsupported hosts safely ignore it.
9897
+ pub fn setDockPresence(self: *Self, visible: bool) void {
9898
+ self.window_action_state.dock_presence_count += 1;
9899
+ self.window_action_state.dock_visible = visible;
9900
+ if (self.executor == .fake) return;
9901
+ const binding = self.window_actions orelse return;
9902
+ _ = binding.dock_presence_fn(binding.context, visible);
9903
+ }
9904
+
8060
9905
  /// Quit the app for real — the graceful terminate, and the tray
8061
9906
  /// "Quit" consequence of the menu-bar-app loop. Rides the same
8062
9907
  /// shutdown event path as today's last-window close (the host
@@ -9024,9 +10869,26 @@ pub fn Effects(comptime Msg: type) type {
9024
10869
  self.pending_video_len > 0 or
9025
10870
  self.pending_pty_len > 0 or
9026
10871
  self.pending_staged_len > 0 or
10872
+ self.pending_db_len > 0 or
9027
10873
  self.channel_pending_count.load(.seq_cst) > 0 or
9028
10874
  self.pty_pending_count.load(.seq_cst) > 0 or
9029
- self.queue_count.load(.seq_cst) > 0;
10875
+ self.queue_count.load(.seq_cst) > 0 or
10876
+ (if (self.host_calls) |binding|
10877
+ if (binding.pending_fn) |pending_fn| pending_fn(binding.context) else false
10878
+ else
10879
+ false);
10880
+ }
10881
+
10882
+ /// Move carrier-owned terminals into the ordinary host-result queue
10883
+ /// on the loop thread. A late terminal for a cancelled/replaced key
10884
+ /// finds no slot and retires silently, exactly like every other keyed
10885
+ /// effect family.
10886
+ fn adoptHostCompletions(self: *Self) void {
10887
+ const binding = self.host_calls orelse return;
10888
+ const poll_fn = binding.poll_fn orelse return;
10889
+ while (poll_fn(binding.context)) |completion| {
10890
+ self.feedHostResult(completion.key, completion.ok, completion.bytes) catch {};
10891
+ }
9030
10892
  }
9031
10893
 
9032
10894
  /// One drain pass's causal boundary: a snapshot of the
@@ -9073,6 +10935,7 @@ pub fn Effects(comptime Msg: type) type {
9073
10935
  /// Snapshot the completion backlog at the start of one drain
9074
10936
  /// pass. Loop-thread only, like the drain itself.
9075
10937
  pub fn drainBoundary(self: *Self) DrainBoundary {
10938
+ self.adoptHostCompletions();
9076
10939
  // Advance the pass clock and release replay-side retired
9077
10940
  // video identities whose window closed (`sweepRetiredVideos`
9078
10941
  // has the full argument). Cheap and empty outside replay.
@@ -9121,6 +10984,7 @@ pub fn Effects(comptime Msg: type) type {
9121
10984
  /// this form serves callers that own their delivery timing —
9122
10985
  /// tests driving the channel directly.
9123
10986
  pub fn takeMsg(self: *Self) ?Msg {
10987
+ self.adoptHostCompletions();
9124
10988
  var unbounded: DrainBoundary = .{
9125
10989
  .pending_before = std.math.maxInt(u64),
9126
10990
  .queue_budget = std.math.maxInt(usize),
@@ -9134,6 +10998,10 @@ pub fn Effects(comptime Msg: type) type {
9134
10998
  /// `boundary` deliver; anything produced after the snapshot
9135
10999
  /// waits for the wake its producer already nudged.
9136
11000
  pub fn takeMsgWithin(self: *Self, boundary: *DrainBoundary) ?Msg {
11001
+ if (self.drain_db_bytes) |bytes| {
11002
+ self.allocator.free(bytes);
11003
+ self.drain_db_bytes = null;
11004
+ }
9137
11005
  self.reclaimSlots();
9138
11006
  while (true) {
9139
11007
  if (self.takePendingMsg(boundary.pending_before)) |pending| {
@@ -9214,6 +11082,53 @@ pub fn Effects(comptime Msg: type) type {
9214
11082
  });
9215
11083
  return host_fn(entry.result);
9216
11084
  },
11085
+ .credentials => |entry| {
11086
+ if (entry.credentials_fn) |credentials_fn| return credentials_fn(entry.result);
11087
+ const host_fn = entry.host_fn orelse continue;
11088
+ return host_fn(.{
11089
+ .key = entry.result.key,
11090
+ .ok = entry.result.outcome == .ok,
11091
+ .bytes = if (entry.result.outcome == .ok)
11092
+ entry.result.bytes
11093
+ else
11094
+ credentials_store.outcomeName(entry.result.outcome),
11095
+ });
11096
+ },
11097
+ .db => |entry| {
11098
+ if (!entry.transient) {
11099
+ const slot_index = self.findDbSlot(entry.key) orelse {
11100
+ if (entry.bytes) |bytes| self.allocator.free(bytes);
11101
+ continue;
11102
+ };
11103
+ const slot = &self.db_slots[slot_index];
11104
+ if (slot.generation != entry.generation) {
11105
+ if (entry.bytes) |bytes| self.allocator.free(bytes);
11106
+ continue;
11107
+ }
11108
+ if ((entry.kind != .page or entry.outcome != .ok) and slot.kind != .live) slot.active = false;
11109
+ }
11110
+ self.drain_db_bytes = entry.bytes;
11111
+ const bytes: []const u8 = if (self.drain_db_bytes) |owned| owned else "";
11112
+ const result: EffectDbResult = .{
11113
+ .key = entry.key,
11114
+ .kind = entry.kind,
11115
+ .outcome = entry.outcome,
11116
+ .bytes = bytes,
11117
+ };
11118
+ self.journalNote(.{
11119
+ .kind = .db,
11120
+ .key = entry.key,
11121
+ .payload = bytes,
11122
+ .code = dbJournalCode(entry.kind, entry.outcome),
11123
+ .exit_reason = if (entry.regenerates) .rejected else .exited,
11124
+ });
11125
+ const db_fn = entry.db_fn orelse {
11126
+ if (self.drain_db_bytes) |owned| self.allocator.free(owned);
11127
+ self.drain_db_bytes = null;
11128
+ continue;
11129
+ };
11130
+ return db_fn(result);
11131
+ },
9217
11132
  .audio => |entry| {
9218
11133
  var event = entry.event;
9219
11134
  var audio_fn = entry.audio_fn;
@@ -9549,8 +11464,9 @@ pub fn Effects(comptime Msg: type) type {
9549
11464
  // Take body ownership so the slot can be reused
9550
11465
  // while `update` still reads the slice; the
9551
11466
  // buffer is freed when the next response drains.
9552
- if (self.drain_fetch_body) |old| self.allocator.free(old);
11467
+ self.releaseDrainFetchBody();
9553
11468
  self.drain_fetch_body = slot.fetch_buffer;
11469
+ self.drain_fetch_body_sensitive = false;
9554
11470
  slot.fetch_buffer = null;
9555
11471
  const payload_len = slot.payload_len;
9556
11472
  const response_fn = entry.response_fn orelse continue;
@@ -9594,8 +11510,9 @@ pub fn Effects(comptime Msg: type) type {
9594
11510
  slot.state.store(.draining, .release);
9595
11511
  // Take buffer ownership so the slot can be
9596
11512
  // reused while `update` still reads the bytes.
9597
- if (self.drain_fetch_body) |old| self.allocator.free(old);
11513
+ self.releaseDrainFetchBody();
9598
11514
  self.drain_fetch_body = slot.fetch_buffer;
11515
+ self.drain_fetch_body_sensitive = false;
9599
11516
  slot.fetch_buffer = null;
9600
11517
  const payload_len = slot.payload_len;
9601
11518
  const file_fn = entry.file_fn orelse continue;
@@ -9635,8 +11552,9 @@ pub fn Effects(comptime Msg: type) type {
9635
11552
  if (entry.generation != slot.generation) continue;
9636
11553
  // Take buffer ownership so the slot can be
9637
11554
  // reused while `update` still reads the text.
9638
- if (self.drain_fetch_body) |old| self.allocator.free(old);
11555
+ self.releaseDrainFetchBody();
9639
11556
  self.drain_fetch_body = slot.fetch_buffer;
11557
+ self.drain_fetch_body_sensitive = false;
9640
11558
  slot.fetch_buffer = null;
9641
11559
  const payload_len = slot.payload_len;
9642
11560
  const text: []const u8 = if (self.drain_fetch_body) |buffer|
@@ -9676,21 +11594,34 @@ pub fn Effects(comptime Msg: type) type {
9676
11594
  // `.response`: a mismatched generation means the
9677
11595
  // occupant was already retired (replaced or
9678
11596
  // cancelled — its result drops silently, per the
9679
- // request contract). No consumer-side
9680
- // `.draining` store is needed here (unlike the
9681
- // worker-fed arms): host answers are fed on the
9682
- // loop thread with the store sequenced before
9683
- // the enqueue — and a same-key host request
9684
- // REPLACES an in-flight one rather than
9685
- // rejecting, so no handler retry hinges on the
9686
- // state either way.
11597
+ // request contract).
9687
11598
  if (entry.generation != slot.generation) continue;
11599
+ // Ordinary host answers are fed on the loop
11600
+ // thread with `.draining` sequenced before the
11601
+ // enqueue. Store WRITES reuse this entry family,
11602
+ // but their workers post first and store
11603
+ // `.draining` immediately afterward so a full
11604
+ // queue cannot make a joinable slot block its own
11605
+ // producer. The drain can therefore race ahead of
11606
+ // that store. Retire a store occupancy here before
11607
+ // its terminal reaches update, matching the file
11608
+ // and image worker-fed arms: a handler that issues
11609
+ // another store command under the same key must be
11610
+ // able to reuse this slot instead of consuming a
11611
+ // second store slot (or rejecting at capacity).
11612
+ // The worker's later re-store is idempotent.
11613
+ if (slot.kind == .store or slot.kind == .credentials) slot.state.store(.draining, .release);
9688
11614
  // Take buffer ownership so the slot can be
9689
11615
  // reused while `update` still reads the bytes.
9690
- if (self.drain_fetch_body) |old| self.allocator.free(old);
11616
+ self.releaseDrainFetchBody();
9691
11617
  self.drain_fetch_body = slot.fetch_buffer;
11618
+ self.drain_fetch_body_sensitive = slot.kind == .credentials;
9692
11619
  slot.fetch_buffer = null;
9693
11620
  const payload_len = slot.payload_len;
11621
+ if (slot.kind == .credentials and !slot.fake) {
11622
+ joinWorker(slot);
11623
+ self.startNextCredentialsWorker();
11624
+ }
9694
11625
  // A cancel that raced the feed (the entry was
9695
11626
  // already queued) still drops silently — on
9696
11627
  // both sides: live never journals it, and the
@@ -9712,13 +11643,36 @@ pub fn Effects(comptime Msg: type) type {
9712
11643
  // session replay the request is a parked fake
9713
11644
  // that only this record's feed retires. Only
9714
11645
  // the Msg depends on the handler.
9715
- self.journalNote(.{
9716
- .kind = .host,
9717
- .key = result.key,
9718
- .payload = result.bytes,
9719
- // `.host` journal encoding: route in `code`.
9720
- .code = @intFromBool(!result.ok),
9721
- });
11646
+ if (slot.kind == .credentials) {
11647
+ const credentials_outcome: EffectCredentialsOutcome = if (result.ok)
11648
+ .ok
11649
+ else
11650
+ credentials_store.outcomeFromName(result.bytes) orelse .rejected;
11651
+ const credentials_result: EffectCredentialsResult = .{
11652
+ .key = result.key,
11653
+ .operation = slot.credentials_op,
11654
+ .outcome = credentials_outcome,
11655
+ .bytes = if (credentials_outcome == .ok) result.bytes else "",
11656
+ };
11657
+ self.journalNote(.{
11658
+ .kind = .credentials,
11659
+ .key = result.key,
11660
+ .payload = credentials_result.bytes,
11661
+ .credentials_operation = slot.credentials_op,
11662
+ .credentials_outcome = credentials_outcome,
11663
+ });
11664
+ if (entry.credentials_fn) |credentials_fn| return credentials_fn(credentials_result);
11665
+ const host_fn = entry.host_fn orelse continue;
11666
+ return host_fn(result);
11667
+ } else {
11668
+ self.journalNote(.{
11669
+ .kind = .host,
11670
+ .key = result.key,
11671
+ .payload = result.bytes,
11672
+ // `.host` journal encoding: route in `code`.
11673
+ .code = @intFromBool(!result.ok),
11674
+ });
11675
+ }
9722
11676
  const host_fn = entry.host_fn orelse continue;
9723
11677
  return host_fn(result);
9724
11678
  },
@@ -9730,8 +11684,9 @@ pub fn Effects(comptime Msg: type) type {
9730
11684
  // Take buffer ownership so the slot can be
9731
11685
  // reused while `update` (and the journal sink)
9732
11686
  // still read the bytes.
9733
- if (self.drain_fetch_body) |old| self.allocator.free(old);
11687
+ self.releaseDrainFetchBody();
9734
11688
  self.drain_fetch_body = slot.fetch_buffer;
11689
+ self.drain_fetch_body_sensitive = false;
9735
11690
  slot.fetch_buffer = null;
9736
11691
  // Retire the slot BEFORE the terminal reaches any
9737
11692
  // handler. The real worker stores `.draining`
@@ -10763,11 +12718,51 @@ pub fn Effects(comptime Msg: type) type {
10763
12718
  self.wakeHost();
10764
12719
  }
10765
12720
 
12721
+ /// Feed one recorded/test relational delivery into the parked fake
12722
+ /// request. Replay never opens SQLite: row pages and terminal outcomes
12723
+ /// come exclusively through this seam.
12724
+ pub fn feedDbResult(
12725
+ self: *Self,
12726
+ key: u64,
12727
+ kind: EffectDbResultKind,
12728
+ outcome: EffectDbOutcome,
12729
+ bytes: []const u8,
12730
+ ) error{ EffectNotFound, ReplayDamagedRecord }!void {
12731
+ const slot_index = self.findDbSlot(key) orelse return error.EffectNotFound;
12732
+ const slot = &self.db_slots[slot_index];
12733
+ if (!slot.fake) return error.EffectNotFound;
12734
+ if (kind == .page) {
12735
+ if ((slot.kind != .query and slot.kind != .live) or outcome != .ok or !relational_store.validEncodedPage(bytes)) return error.ReplayDamagedRecord;
12736
+ } else {
12737
+ if (bytes.len != 0) return error.ReplayDamagedRecord;
12738
+ if ((kind == .done) != (slot.kind == .query or slot.kind == .live)) return error.ReplayDamagedRecord;
12739
+ }
12740
+ self.stageDb(.{
12741
+ .seq = self.nextPendingSeq(),
12742
+ .key = key,
12743
+ .generation = slot.generation,
12744
+ .kind = kind,
12745
+ .outcome = outcome,
12746
+ .bytes = if (bytes.len == 0) null else self.allocator.dupe(u8, bytes) catch
12747
+ @panic("effects: out of memory feeding a replayed relational page - every journaled result must be delivered"),
12748
+ .db_fn = slot.on_result,
12749
+ .regenerates = false,
12750
+ });
12751
+ }
12752
+
12753
+ pub fn pendingDbCount(self: *Self) usize {
12754
+ var count: usize = 0;
12755
+ for (&self.db_slots) |*slot| if (slot.active and slot.fake) {
12756
+ count += 1;
12757
+ };
12758
+ return count;
12759
+ }
12760
+
10766
12761
  /// Number of parked (still-active) fake host requests.
10767
12762
  pub fn pendingHostCount(self: *Self) usize {
10768
12763
  var count: usize = 0;
10769
12764
  for (&self.slots) |*slot| {
10770
- if (slot.fake and slot.kind == .host and slot.state.load(.acquire) == .running) count += 1;
12765
+ if (slot.fake and (slot.kind == .host or slot.kind == .store or slot.kind == .credentials) and slot.state.load(.acquire) == .running) count += 1;
10771
12766
  }
10772
12767
  return count;
10773
12768
  }
@@ -10776,7 +12771,7 @@ pub fn Effects(comptime Msg: type) type {
10776
12771
  pub fn pendingHostAt(self: *Self, index: usize) ?HostRequest {
10777
12772
  var seen: usize = 0;
10778
12773
  for (&self.slots) |*slot| {
10779
- if (!(slot.fake and slot.kind == .host and slot.state.load(.acquire) == .running)) continue;
12774
+ if (!(slot.fake and (slot.kind == .host or slot.kind == .store or slot.kind == .credentials) and slot.state.load(.acquire) == .running)) continue;
10780
12775
  if (seen == index) {
10781
12776
  return .{
10782
12777
  .key = slot.key,
@@ -10803,7 +12798,7 @@ pub fn Effects(comptime Msg: type) type {
10803
12798
  pub fn feedHostResult(self: *Self, key: u64, ok: bool, bytes: []const u8) error{EffectNotFound}!void {
10804
12799
  const slot_index = blk: {
10805
12800
  const index = self.findActiveSlot(key) orelse return error.EffectNotFound;
10806
- if (self.slots[index].kind != .host) return error.EffectNotFound;
12801
+ if (self.slots[index].kind != .host and self.slots[index].kind != .store and self.slots[index].kind != .credentials) return error.EffectNotFound;
10807
12802
  break :blk index;
10808
12803
  };
10809
12804
  const slot = &self.slots[slot_index];
@@ -10825,16 +12820,63 @@ pub fn Effects(comptime Msg: type) type {
10825
12820
  .line_len = @intCast(delivered.len),
10826
12821
  .host_ok = delivered_ok,
10827
12822
  .host_fn = slot.on_host,
12823
+ .credentials_fn = slot.on_credentials,
10828
12824
  };
10829
12825
  slot.state.store(.draining, .release);
10830
12826
  if (!self.enqueue(&entry)) {
10831
12827
  const host_fn = slot.on_host;
12828
+ const credentials_fn = slot.on_credentials;
12829
+ const kind = slot.kind;
12830
+ const operation = slot.credentials_op;
10832
12831
  self.releaseFetchSlot(slot);
10833
- self.deliverLoopHost(.{ .key = entry.key, .ok = false }, host_fn, false);
12832
+ if (kind == .credentials) {
12833
+ self.deliverLoopCredentials(.{
12834
+ .key = entry.key,
12835
+ .operation = operation,
12836
+ .outcome = .rejected,
12837
+ }, credentials_fn, host_fn);
12838
+ } else {
12839
+ self.deliverLoopHost(.{ .key = entry.key, .ok = false }, host_fn, false);
12840
+ }
10834
12841
  }
10835
12842
  self.wakeHost();
10836
12843
  }
10837
12844
 
12845
+ /// Replay one redacted credential result. A successful get receives a
12846
+ /// deterministic same-length placeholder derived from the recorded
12847
+ /// digest; no keychain is touched and no live secret is recoverable
12848
+ /// from the journal. Other outcomes reconstruct their closed enum
12849
+ /// name as the err-route bytes.
12850
+ pub fn feedCredentialsResult(
12851
+ self: *Self,
12852
+ key: u64,
12853
+ operation: EffectCredentialsOperation,
12854
+ outcome: EffectCredentialsOutcome,
12855
+ secret_len: u64,
12856
+ digest: [32]u8,
12857
+ ) anyerror!void {
12858
+ const slot_index = self.findActiveSlot(key) orelse return error.EffectNotFound;
12859
+ const slot = &self.slots[slot_index];
12860
+ if (slot.kind != .credentials or slot.credentials_op != operation or !slot.fake) return error.ReplayDamagedRecord;
12861
+ if (outcome != .ok) {
12862
+ if (secret_len != 0) return error.ReplayDamagedRecord;
12863
+ return self.feedHostResult(key, false, credentials_store.outcomeName(outcome));
12864
+ }
12865
+ if (operation != .get) {
12866
+ if (secret_len != 0) return error.ReplayDamagedRecord;
12867
+ return self.feedHostResult(key, true, "");
12868
+ }
12869
+ const len = std.math.cast(usize, secret_len) orelse return error.ReplayDamagedRecord;
12870
+ if (len > max_effect_credentials_secret_bytes) return error.ReplayDamagedRecord;
12871
+ const placeholder = self.allocator.alloc(u8, len) catch
12872
+ @panic("effects: out of memory synthesizing a redacted credential replay placeholder");
12873
+ defer secureFree(self.allocator, placeholder);
12874
+ for (placeholder, 0..) |*byte, index| {
12875
+ byte.* = digest[index % digest.len] ^ @as(u8, @truncate(index));
12876
+ }
12877
+ return self.feedHostResult(key, true, placeholder);
12878
+ }
12879
+
10838
12880
  /// Number of recorded (still-armed) fake fx timers.
10839
12881
  pub fn pendingTimerCount(self: *Self) usize {
10840
12882
  var count: usize = 0;
@@ -11767,6 +13809,7 @@ pub fn Effects(comptime Msg: type) type {
11767
13809
  /// only.
11768
13810
  fn releaseFetchSlot(self: *Self, slot: *Slot) void {
11769
13811
  if (slot.fetch_buffer) |buffer| {
13812
+ if (slot.kind == .credentials) std.crypto.secureZero(u8, buffer);
11770
13813
  self.allocator.free(buffer);
11771
13814
  slot.fetch_buffer = null;
11772
13815
  }
@@ -11774,13 +13817,32 @@ pub fn Effects(comptime Msg: type) type {
11774
13817
  self.allocator.free(buffer);
11775
13818
  slot.line_buffer = null;
11776
13819
  }
13820
+ if (slot.kind == .credentials) slot.credentials_waiting = false;
11777
13821
  slot.state.store(.idle, .release);
11778
13822
  }
11779
13823
 
13824
+ fn releaseDrainFetchBody(self: *Self) void {
13825
+ if (self.drain_fetch_body) |buffer| {
13826
+ if (self.drain_fetch_body_sensitive) std.crypto.secureZero(u8, buffer);
13827
+ self.allocator.free(buffer);
13828
+ self.drain_fetch_body = null;
13829
+ }
13830
+ self.drain_fetch_body_sensitive = false;
13831
+ }
13832
+
13833
+ fn secureFree(allocator: std.mem.Allocator, bytes: []u8) void {
13834
+ std.crypto.secureZero(u8, bytes);
13835
+ allocator.free(bytes);
13836
+ }
13837
+
11780
13838
  /// Free a spawn slot's collect and line buffers (if any) and
11781
13839
  /// return it to `.idle` (spawn-time failures, fake cancels, and
11782
13840
  /// feed fallbacks). Loop-thread only.
11783
13841
  fn releaseSpawnSlot(self: *Self, slot: *Slot) void {
13842
+ if (slot.stdin_buffer) |buffer| {
13843
+ self.allocator.free(buffer);
13844
+ slot.stdin_buffer = null;
13845
+ }
11784
13846
  if (slot.collect_buffer) |buffer| {
11785
13847
  self.allocator.free(buffer);
11786
13848
  slot.collect_buffer = null;
@@ -12176,6 +14238,84 @@ pub fn Effects(comptime Msg: type) type {
12176
14238
  self.staged_keys_len = 0;
12177
14239
  }
12178
14240
 
14241
+ fn pendingDbStorage(self: *Self) []PendingDb {
14242
+ if (self.pending_db_spill.len > 0) return self.pending_db_spill;
14243
+ return &self.pending_dbs;
14244
+ }
14245
+
14246
+ fn stageDb(self: *Self, entry: PendingDb) void {
14247
+ const storage = self.pendingDbStorage();
14248
+ if (self.pending_db_len == storage.len) {
14249
+ const grown = self.allocator.alloc(PendingDb, storage.len * 2) catch
14250
+ @panic("effects: out of memory staging a relational result - every query page and terminal must be delivered");
14251
+ for (grown[0..self.pending_db_len], 0..) |*slot, index| {
14252
+ slot.* = storage[(self.pending_db_head + index) % storage.len];
14253
+ }
14254
+ if (self.pending_db_spill.len > 0) self.allocator.free(self.pending_db_spill);
14255
+ self.pending_db_spill = grown;
14256
+ self.pending_db_head = 0;
14257
+ }
14258
+ const active = self.pendingDbStorage();
14259
+ active[(self.pending_db_head + self.pending_db_len) % active.len] = entry;
14260
+ self.pending_db_len += 1;
14261
+ self.wakeHost();
14262
+ }
14263
+
14264
+ fn discardPendingDbTail(self: *Self, retained_len: usize) void {
14265
+ std.debug.assert(retained_len <= self.pending_db_len);
14266
+ const storage = self.pendingDbStorage();
14267
+ while (self.pending_db_len > retained_len) {
14268
+ const index = (self.pending_db_head + self.pending_db_len - 1) % storage.len;
14269
+ if (storage[index].bytes) |bytes| self.allocator.free(bytes);
14270
+ self.pending_db_len -= 1;
14271
+ }
14272
+ if (self.pending_db_len == 0) {
14273
+ self.pending_db_head = 0;
14274
+ if (self.pending_db_spill.len > 0) {
14275
+ self.allocator.free(self.pending_db_spill);
14276
+ self.pending_db_spill = &.{};
14277
+ }
14278
+ }
14279
+ }
14280
+
14281
+ fn discardPendingDbGeneration(self: *Self, key: u64, generation: u64) void {
14282
+ const storage = self.pendingDbStorage();
14283
+ const original_len = self.pending_db_len;
14284
+ var kept: usize = 0;
14285
+ for (0..original_len) |offset| {
14286
+ const entry = storage[(self.pending_db_head + offset) % storage.len];
14287
+ if (entry.key == key and entry.generation == generation) {
14288
+ if (entry.bytes) |bytes| self.allocator.free(bytes);
14289
+ continue;
14290
+ }
14291
+ storage[(self.pending_db_head + kept) % storage.len] = entry;
14292
+ kept += 1;
14293
+ }
14294
+ self.pending_db_len = kept;
14295
+ if (kept == 0) {
14296
+ self.pending_db_head = 0;
14297
+ if (self.pending_db_spill.len > 0) {
14298
+ self.allocator.free(self.pending_db_spill);
14299
+ self.pending_db_spill = &.{};
14300
+ }
14301
+ }
14302
+ }
14303
+
14304
+ fn takePendingDb(self: *Self) PendingDb {
14305
+ const storage = self.pendingDbStorage();
14306
+ const entry = storage[self.pending_db_head];
14307
+ self.pending_db_head = (self.pending_db_head + 1) % storage.len;
14308
+ self.pending_db_len -= 1;
14309
+ if (self.pending_db_len == 0) {
14310
+ self.pending_db_head = 0;
14311
+ if (self.pending_db_spill.len > 0) {
14312
+ self.allocator.free(self.pending_db_spill);
14313
+ self.pending_db_spill = &.{};
14314
+ }
14315
+ }
14316
+ return entry;
14317
+ }
14318
+
12179
14319
  /// The caller-staged Msg stage's current backing storage —
12180
14320
  /// `pendingImageStorage`'s twin.
12181
14321
  fn pendingStagedStorage(self: *Self) []PendingStaged {
@@ -12327,7 +14467,11 @@ pub fn Effects(comptime Msg: type) type {
12327
14467
  self.pendingPtyStorage()[self.pending_pty_head].seq
12328
14468
  else
12329
14469
  no_seq;
12330
- const min_seq = @min(@min(@min(ring_seq, staged_seq), video_seq), @min(@min(image_seq, channel_seq_head), pty_seq_head));
14470
+ const db_seq: u64 = if (self.pending_db_len > 0)
14471
+ self.pendingDbStorage()[self.pending_db_head].seq
14472
+ else
14473
+ no_seq;
14474
+ const min_seq = @min(@min(@min(ring_seq, staged_seq), @min(video_seq, db_seq)), @min(@min(image_seq, channel_seq_head), pty_seq_head));
12331
14475
  if (min_seq == no_seq or min_seq >= before) return null;
12332
14476
  if (min_seq == staged_seq) {
12333
14477
  return .{ .staged = self.takePendingStaged().msg };
@@ -12369,6 +14513,7 @@ pub fn Effects(comptime Msg: type) type {
12369
14513
  .retire_generation = staged.retire_generation,
12370
14514
  } };
12371
14515
  }
14516
+ if (min_seq == db_seq) return .{ .db = self.takePendingDb() };
12372
14517
  const pending = self.pending_exits[self.pending_exit_head];
12373
14518
  self.pending_exit_head = (self.pending_exit_head + 1) % max_effect_pending_exits;
12374
14519
  self.pending_exit_len -= 1;
@@ -12376,7 +14521,22 @@ pub fn Effects(comptime Msg: type) type {
12376
14521
  }
12377
14522
 
12378
14523
  fn findIdleSlot(self: *Self) ?usize {
12379
- for (&self.slots, 0..) |*slot, index| {
14524
+ for (self.slots[0..max_effects], 0..) |*slot, index| {
14525
+ if (slot.state.load(.acquire) == .idle) return index;
14526
+ }
14527
+ return null;
14528
+ }
14529
+
14530
+ fn findIdleStoreSlot(self: *Self) ?usize {
14531
+ for (self.slots[max_effects .. max_effects + max_store_effects], max_effects..) |*slot, index| {
14532
+ if (slot.state.load(.acquire) == .idle) return index;
14533
+ }
14534
+ return null;
14535
+ }
14536
+
14537
+ fn findIdleCredentialsSlot(self: *Self) ?usize {
14538
+ const first = max_effects + max_store_effects;
14539
+ for (self.slots[first..], first..) |*slot, index| {
12380
14540
  if (slot.state.load(.acquire) == .idle) return index;
12381
14541
  }
12382
14542
  return null;
@@ -12474,7 +14634,7 @@ pub fn Effects(comptime Msg: type) type {
12474
14634
  fn slotTerminalUndelivered(slot: *const Slot) bool {
12475
14635
  return switch (slot.kind) {
12476
14636
  .spawn => slot.collect_buffer != null or slot.exit_undelivered,
12477
- .fetch, .file, .clipboard, .host, .image => slot.fetch_buffer != null,
14637
+ .fetch, .file, .clipboard, .host, .store, .credentials, .image => slot.fetch_buffer != null,
12478
14638
  };
12479
14639
  }
12480
14640
 
@@ -12499,10 +14659,13 @@ pub fn Effects(comptime Msg: type) type {
12499
14659
  }
12500
14660
 
12501
14661
  /// Join a finished worker's thread and clear its handle.
12502
- /// Loop-thread only. The reclaim path reaches this only after
12503
- /// the worker published a non-running slot state — its last
12504
- /// slot access — so the join blocks for the thread's epilogue
12505
- /// (a wake nudge and the OS exit), never on child I/O. The
14662
+ /// Loop-thread only. The reclaim path reaches this after either
14663
+ /// the worker published a non-running slot state or the consumer
14664
+ /// dequeued its terminal and idempotently published `.draining`.
14665
+ /// In the latter case the successful enqueue proves the effect
14666
+ /// work and result production are complete, so the join waits
14667
+ /// only for the producer's post-enqueue epilogue (a state store,
14668
+ /// wake nudge, and OS exit), never on child I/O. The
12506
14669
  /// teardown path (`deinit`) may join a still-running worker;
12507
14670
  /// convergence there is the kill's and the shutdown flag's
12508
14671
  /// doing, as documented at that call site.
@@ -12525,6 +14688,15 @@ pub fn Effects(comptime Msg: type) type {
12525
14688
  destroySpawnContext(ctx);
12526
14689
  slot.spawn_ctx = null;
12527
14690
  }
14691
+ if (slot.store_ctx) |ctx| {
14692
+ process_allocator.free(ctx.payload);
14693
+ process_allocator.destroy(ctx);
14694
+ slot.store_ctx = null;
14695
+ }
14696
+ if (slot.credentials_ctx) |ctx| {
14697
+ destroyCredentialsContext(ctx);
14698
+ slot.credentials_ctx = null;
14699
+ }
12528
14700
  }
12529
14701
  }
12530
14702
 
@@ -12537,6 +14709,14 @@ pub fn Effects(comptime Msg: type) type {
12537
14709
  process_allocator.destroy(ctx);
12538
14710
  }
12539
14711
 
14712
+ fn destroyCredentialsContext(ctx: *CredentialsWorkerContext) void {
14713
+ secureFree(process_allocator, ctx.output);
14714
+ secureFree(process_allocator, ctx.secret);
14715
+ secureFree(process_allocator, ctx.key);
14716
+ process_allocator.free(ctx.service);
14717
+ process_allocator.destroy(ctx);
14718
+ }
14719
+
12540
14720
  fn reclaimSlots(self: *Self) void {
12541
14721
  for (&self.slots) |*slot| {
12542
14722
  switch (slot.state.load(.acquire)) {
@@ -12547,8 +14727,9 @@ pub fn Effects(comptime Msg: type) type {
12547
14727
  // A draining slot is reusable once the drain
12548
14728
  // delivered its terminal (took the fetch body or
12549
14729
  // collected stdout, or cleared a `.lines` exit's
12550
- // marker). Its worker is already finished either
12551
- // way: retire the thread now.
14730
+ // marker). Its effect work is already finished either
14731
+ // way; retire the thread now (the join may wait for a
14732
+ // producer's short post-enqueue epilogue).
12552
14733
  .draining => {
12553
14734
  joinWorker(slot);
12554
14735
  if (slot.fetch_buffer == null and slot.collect_buffer == null and !slot.exit_undelivered) {
@@ -12558,6 +14739,7 @@ pub fn Effects(comptime Msg: type) type {
12558
14739
  else => {},
12559
14740
  }
12560
14741
  }
14742
+ self.startNextCredentialsWorker();
12561
14743
  }
12562
14744
 
12563
14745
  fn enqueue(self: *Self, entry: *const Entry) bool {