@native-sdk/cli 0.10.1 → 0.11.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 (462) hide show
  1. package/README.md +8 -6
  2. package/bin/native.js +2 -1
  3. package/build/app.zig +320 -60
  4. package/build/corewire.zig +53 -0
  5. package/build/test_shards.zig +49 -0
  6. package/build/ts_run.mjs +3 -3
  7. package/build.zig +1796 -83
  8. package/package.json +19 -14
  9. package/packages/core/compile-surface/core.ts +134 -72
  10. package/packages/core/package-lock.json +75 -357
  11. package/packages/core/package.json +25 -4
  12. package/packages/core/scripts/compiler_command.mjs +17 -12
  13. package/packages/core/scripts/compiler_typecheck.mjs +1 -0
  14. package/packages/core/scripts/gen_declarations.mjs +3 -2
  15. package/packages/core/scripts/gen_service_surface.mjs +22 -10
  16. package/packages/core/scripts/install_scriptc.mjs +182 -0
  17. package/packages/core/scripts/invoke_scriptc.mjs +18 -0
  18. package/packages/core/scripts/merge_static_archives.mjs +6 -1
  19. package/packages/core/scripts/npm_static_spike.mjs +2 -2
  20. package/packages/core/scripts/run_external_core_compiler.mjs +22 -10
  21. package/packages/core/scripts/run_external_service_compiler.mjs +15 -15
  22. package/packages/core/scripts/run_library_compiler.mjs +51 -0
  23. package/packages/core/scripts/run_native_tests.mjs +22 -0
  24. package/packages/core/scripts/scriptc-toolchain.json +101 -0
  25. package/packages/core/scripts/scriptc_toolchain.mjs +121 -0
  26. package/packages/core/scripts/stage_external_core.mjs +57 -1
  27. package/packages/core/scripts/surface_manifest_diff.mjs +19 -12
  28. package/packages/core/sdk/bytes.d.ts +2 -0
  29. package/packages/core/sdk/bytes.ts +86 -0
  30. package/packages/core/sdk/core.d.ts +308 -4
  31. package/packages/core/sdk/core.ts +320 -84
  32. package/packages/core/sdk/events.d.ts +247 -0
  33. package/packages/core/sdk/events.ts +230 -2
  34. package/packages/core/sdk/internal/image_identity.d.ts +7 -0
  35. package/packages/core/sdk/internal/image_identity.ts +71 -0
  36. package/packages/core/sdk/internal/markdown_policy.d.ts +5 -0
  37. package/packages/core/sdk/internal/markdown_policy.ts +878 -0
  38. package/packages/core/sdk/text.d.ts +27 -0
  39. package/packages/core/sdk/text.ts +206 -15
  40. package/packages/core/sdk/theme.d.ts +251 -0
  41. package/packages/core/sdk/theme.ts +267 -0
  42. package/packages/core/src/authorization.ts +137 -0
  43. package/packages/core/src/automation_commands.ts +201 -0
  44. package/packages/core/src/automation_interactions.ts +92 -0
  45. package/packages/core/src/bridge_descriptors.ts +104 -0
  46. package/packages/core/src/builtin_coordination.ts +172 -0
  47. package/packages/core/src/canvas_frame_coordination.ts +81 -0
  48. package/packages/core/src/canvas_presentation_lifecycle.ts +84 -0
  49. package/packages/core/src/canvas_scene_observation.ts +145 -0
  50. package/packages/core/src/chart_content.ts +161 -0
  51. package/packages/core/src/chart_plans.ts +432 -0
  52. package/packages/core/src/checker.ts +166 -19
  53. package/packages/core/src/code_content.ts +580 -0
  54. package/packages/core/src/command_coordination.ts +140 -0
  55. package/packages/core/src/component_composition.ts +94 -0
  56. package/packages/core/src/component_construction.ts +149 -0
  57. package/packages/core/src/contract.ts +25 -7
  58. package/packages/core/src/control_appearance.ts +232 -0
  59. package/packages/core/src/control_commands.ts +115 -0
  60. package/packages/core/src/control_content.ts +105 -0
  61. package/packages/core/src/control_geometry.ts +107 -0
  62. package/packages/core/src/control_payloads.ts +119 -0
  63. package/packages/core/src/control_primitives.ts +134 -0
  64. package/packages/core/src/devhost.ts +82 -7
  65. package/packages/core/src/devhost_journal.mjs +30 -7
  66. package/packages/core/src/effect_plans.ts +71 -0
  67. package/packages/core/src/flow_measurement.ts +121 -0
  68. package/packages/core/src/font_registry.ts +37 -0
  69. package/packages/core/src/glyph_atlas.ts +86 -0
  70. package/packages/core/src/gpu_packet_preparation.ts +130 -0
  71. package/packages/core/src/gpu_planning.ts +123 -0
  72. package/packages/core/src/gpu_presentation.ts +55 -0
  73. package/packages/core/src/host_flow.ts +89 -0
  74. package/packages/core/src/host_input_regions.ts +165 -0
  75. package/packages/core/src/image_registry.ts +66 -0
  76. package/packages/core/src/indicator_plans.ts +132 -0
  77. package/packages/core/src/infer.ts +150 -8
  78. package/packages/core/src/input_composition.ts +116 -0
  79. package/packages/core/src/intrinsic_measure.ts +100 -0
  80. package/packages/core/src/layout_coordination.ts +207 -0
  81. package/packages/core/src/leaf_plans.ts +134 -0
  82. package/packages/core/src/markup_development.ts +160 -0
  83. package/packages/core/src/measurement_coordination.ts +185 -0
  84. package/packages/core/src/modules.ts +1 -1
  85. package/packages/core/src/motion_sampling.ts +100 -0
  86. package/packages/core/src/paragraph_layout.ts +192 -0
  87. package/packages/core/src/portable_sources.json +74 -0
  88. package/packages/core/src/portable_sources.ts +17 -0
  89. package/packages/core/src/registered_font.ts +93 -0
  90. package/packages/core/src/render_animation_lifecycle.ts +128 -0
  91. package/packages/core/src/render_coordination.ts +170 -0
  92. package/packages/core/src/render_resources.ts +234 -0
  93. package/packages/core/src/runtime_policy.ts +3930 -0
  94. package/packages/core/src/scalar_text.ts +84 -0
  95. package/packages/core/src/service_contract.ts +2 -1
  96. package/packages/core/src/session_codecs.ts +309 -0
  97. package/packages/core/src/shell_admission.ts +126 -0
  98. package/packages/core/src/shell_coordination.ts +93 -0
  99. package/packages/core/src/sqlite_cli.ts +11 -0
  100. package/packages/core/src/status_validation.ts +232 -0
  101. package/packages/core/src/stream_policy.ts +63 -0
  102. package/packages/core/src/surface_recipes.ts +136 -0
  103. package/packages/core/src/system_admission.ts +60 -0
  104. package/packages/core/src/terminal_paint.ts +436 -0
  105. package/packages/core/src/text_document_width.ts +81 -0
  106. package/packages/core/src/text_measurement_cache.ts +69 -0
  107. package/packages/core/src/text_query_layout.ts +179 -0
  108. package/packages/core/src/text_run_layout.ts +410 -0
  109. package/packages/core/src/text_span_queries.ts +355 -0
  110. package/packages/core/src/typed_ast.ts +18 -1
  111. package/packages/core/src/types.ts +7 -5
  112. package/packages/core/src/vector_effects.ts +98 -0
  113. package/packages/core/src/vector_raster.ts +243 -0
  114. package/packages/core/src/view_components.ts +2415 -0
  115. package/packages/core/src/view_coordination.ts +198 -0
  116. package/packages/core/src/view_frontend.ts +980 -0
  117. package/packages/core/src/widget_audits.ts +202 -0
  118. package/packages/core/src/widget_changes.ts +258 -0
  119. package/packages/core/src/widget_metrics.ts +139 -0
  120. package/packages/core/src/widget_motion.ts +171 -0
  121. package/packages/core/src/widget_paint.ts +272 -0
  122. package/packages/core/src/widget_paint_walk.ts +203 -0
  123. package/packages/core/src/widget_presentation.ts +141 -0
  124. package/packages/core/src/widget_routing.ts +262 -0
  125. package/packages/core/src/window_lifecycle.ts +92 -0
  126. package/packages/core/testing/index.ts +430 -0
  127. package/schemas/app.schema.json +13 -0
  128. package/skill-data/core/SKILL.md +2 -2
  129. package/skill-data/native-ui/SKILL.md +76 -17
  130. package/skill-data/ts-core/SKILL.md +113 -9
  131. package/skill-data/ts-services/SKILL.md +1 -1
  132. package/skill-data/ts-services/references/service-surface.md +264 -144
  133. package/src/app_runner/root.zig +25 -12
  134. package/src/app_runner/ts_compiled_view.zig +1631 -0
  135. package/src/app_runner/ts_core_main.zig +143 -10
  136. package/src/app_runner/ts_core_mobile.zig +24 -12
  137. package/src/automation/server.zig +1 -3
  138. package/src/automation/snapshot.zig +9 -637
  139. package/src/automation/snapshot_reference.zig +656 -0
  140. package/src/automation/snapshot_serialization.zig +566 -0
  141. package/src/platform/linux/gtk_host.c +36 -24
  142. package/src/platform/linux/gtk_pixels.h +118 -0
  143. package/src/platform/linux/gtk_pixels_test.c +241 -0
  144. package/src/platform/linux/root.zig +2 -0
  145. package/src/platform/macos/appkit_host.m +188 -30
  146. package/src/platform/macos/pointer_motion_test.m +96 -0
  147. package/src/platform/macos/scroll_driver_test.m +105 -0
  148. package/src/platform/macos/spectrum_bins.h +34 -0
  149. package/src/platform/macos/spectrum_bins_test.c +56 -0
  150. package/src/platform/macos/text_keyboard_test.m +80 -0
  151. package/src/platform/macos/widget_focus_test.m +66 -0
  152. package/src/platform/null_platform.zig +26 -2
  153. package/src/platform/null_platform_tests.zig +13 -0
  154. package/src/platform/root.zig +1 -0
  155. package/src/platform/types.zig +13 -0
  156. package/src/platform/windows/root.zig +2 -0
  157. package/src/platform/windows/webview2_host.cpp +7 -2
  158. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  159. package/src/primitives/app_manifest/root.zig +2 -0
  160. package/src/primitives/app_manifest/tests.zig +4 -1
  161. package/src/primitives/app_manifest/validation.zig +2 -0
  162. package/src/primitives/canvas/a11y_audit.zig +3 -1
  163. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  164. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  165. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  166. package/src/primitives/canvas/code_content_policy.zig +162 -0
  167. package/src/primitives/canvas/commands.zig +29 -1
  168. package/src/primitives/canvas/component_composition.zig +125 -0
  169. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  170. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  171. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  172. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  173. package/src/primitives/canvas/control_command_policy.zig +75 -0
  174. package/src/primitives/canvas/control_content_policy.zig +90 -0
  175. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  176. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  177. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  178. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  179. package/src/primitives/canvas/events.zig +1027 -1
  180. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  181. package/src/primitives/canvas/frame.zig +92 -23
  182. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  183. package/src/primitives/canvas/gpu.zig +10 -0
  184. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  185. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  186. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  187. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  188. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  189. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  190. package/src/primitives/canvas/intrinsic_measure_policy.zig +128 -0
  191. package/src/primitives/canvas/layout_audit.zig +5 -2
  192. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  193. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  194. package/src/primitives/canvas/markdown.zig +13 -3
  195. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  196. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  197. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  198. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  199. package/src/primitives/canvas/reference.zig +12 -6
  200. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  201. package/src/primitives/canvas/render.zig +48 -0
  202. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  203. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  204. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  205. package/src/primitives/canvas/render_effects.zig +14 -0
  206. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  207. package/src/primitives/canvas/render_images.zig +14 -0
  208. package/src/primitives/canvas/render_layers.zig +14 -0
  209. package/src/primitives/canvas/render_override_policy.zig +119 -0
  210. package/src/primitives/canvas/render_paths.zig +14 -0
  211. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  212. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  213. package/src/primitives/canvas/root.zig +100 -0
  214. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  215. package/src/primitives/canvas/serialization.zig +8 -1
  216. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  217. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  218. package/src/primitives/canvas/terminal_grid.zig +10 -696
  219. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  220. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  221. package/src/primitives/canvas/text.zig +1 -0
  222. package/src/primitives/canvas/text_atlas.zig +113 -0
  223. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  224. package/src/primitives/canvas/text_document_policy.zig +120 -0
  225. package/src/primitives/canvas/text_layout.zig +51 -2
  226. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  227. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  228. package/src/primitives/canvas/text_layout_types.zig +3 -0
  229. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  230. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  231. package/src/primitives/canvas/text_metrics.zig +23 -0
  232. package/src/primitives/canvas/text_query_policy.zig +156 -0
  233. package/src/primitives/canvas/text_run_policy.zig +252 -0
  234. package/src/primitives/canvas/text_scalar_policy.zig +156 -0
  235. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  236. package/src/primitives/canvas/text_spans.zig +280 -8
  237. package/src/primitives/canvas/text_tests.zig +10 -0
  238. package/src/primitives/canvas/tokens.zig +38 -0
  239. package/src/primitives/canvas/ui.zig +250 -83
  240. package/src/primitives/canvas/ui_markup.zig +139 -33
  241. package/src/primitives/canvas/ui_markup_compiled.zig +319 -59
  242. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  243. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  244. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  245. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  246. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  247. package/src/primitives/canvas/ui_markup_view.zig +258 -32
  248. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  249. package/src/primitives/canvas/ui_schema.zig +13 -1
  250. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  251. package/src/primitives/canvas/ui_tests.zig +1 -0
  252. package/src/primitives/canvas/vector.zig +36 -2
  253. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  254. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  255. package/src/primitives/canvas/virtual_extent_policy.zig +292 -0
  256. package/src/primitives/canvas/virtual_extents.zig +99 -3
  257. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  258. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  259. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  260. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  261. package/src/primitives/canvas/widget_layout.zig +673 -128
  262. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  263. package/src/primitives/canvas/widget_metric_policy.zig +126 -0
  264. package/src/primitives/canvas/widget_metrics.zig +45 -6
  265. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  266. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  267. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  268. package/src/primitives/canvas/widget_render.zig +744 -74
  269. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  270. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  271. package/src/primitives/canvas/widget_render_style.zig +94 -0
  272. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  273. package/src/primitives/canvas/widget_routing.zig +75 -0
  274. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  275. package/src/primitives/canvas/widget_runtime.zig +20 -1
  276. package/src/primitives/canvas/widget_semantics.zig +25 -0
  277. package/src/primitives/canvas/widget_text_input.zig +86 -23
  278. package/src/primitives/canvas/widget_text_select.zig +1 -0
  279. package/src/primitives/canvas/widget_tree.zig +8 -1
  280. package/src/primitives/canvas/widgets.zig +42 -12
  281. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  282. package/src/root.zig +21 -0
  283. package/src/runtime/accessibility_policy.zig +122 -0
  284. package/src/runtime/api.zig +28 -0
  285. package/src/runtime/app_dispatch_policy.zig +68 -0
  286. package/src/runtime/authorization_policy.zig +150 -0
  287. package/src/runtime/automation_command_policy.zig +241 -0
  288. package/src/runtime/automation_interaction_policy.zig +107 -0
  289. package/src/runtime/automation_snapshot.zig +52 -22
  290. package/src/runtime/automation_snapshot_reference.zig +290 -0
  291. package/src/runtime/automation_widget_dispatch.zig +267 -355
  292. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  293. package/src/runtime/blob_policy.zig +58 -0
  294. package/src/runtime/blob_reference.zig +64 -0
  295. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  296. package/src/runtime/builtin_bridge.zig +180 -44
  297. package/src/runtime/builtin_coordination_policy.zig +121 -0
  298. package/src/runtime/callback_policy_test_reference.zig +97 -0
  299. package/src/runtime/canvas_drag_policy.zig +94 -0
  300. package/src/runtime/canvas_fonts.zig +38 -10
  301. package/src/runtime/canvas_frame.zig +590 -134
  302. package/src/runtime/canvas_frame_helpers.zig +1 -0
  303. package/src/runtime/canvas_hover_policy.zig +131 -0
  304. package/src/runtime/canvas_images.zig +59 -30
  305. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  306. package/src/runtime/canvas_limits.zig +1 -1
  307. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  308. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  309. package/src/runtime/canvas_widget_context_menu.zig +4 -4
  310. package/src/runtime/canvas_widget_display.zig +110 -9
  311. package/src/runtime/canvas_widget_events.zig +718 -328
  312. package/src/runtime/canvas_widget_runtime.zig +437 -81
  313. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  314. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  315. package/src/runtime/canvas_widget_state.zig +93 -56
  316. package/src/runtime/channel_sources.zig +80 -0
  317. package/src/runtime/command_policy.zig +161 -0
  318. package/src/runtime/component_policy.zig +83 -0
  319. package/src/runtime/core.zig +156 -6
  320. package/src/runtime/desktop_files.zig +189 -0
  321. package/src/runtime/effects.zig +466 -29
  322. package/src/runtime/effects_tests.zig +28 -0
  323. package/src/runtime/file_policy_test_reference.zig +113 -0
  324. package/src/runtime/flow.zig +418 -341
  325. package/src/runtime/flow_reference.zig +1426 -0
  326. package/src/runtime/font_registry_policy.zig +72 -0
  327. package/src/runtime/frame_profile.zig +24 -33
  328. package/src/runtime/gpu_surface_events.zig +97 -35
  329. package/src/runtime/host_event_pump.zig +303 -0
  330. package/src/runtime/host_event_pump_reference.zig +268 -0
  331. package/src/runtime/host_flow_policy.zig +155 -0
  332. package/src/runtime/host_input_regions_policy.zig +156 -0
  333. package/src/runtime/image_registry_policy.zig +94 -0
  334. package/src/runtime/input_composition_policy.zig +138 -0
  335. package/src/runtime/journal_policy.zig +66 -0
  336. package/src/runtime/journal_reference.zig +53 -0
  337. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  338. package/src/runtime/markup_development_policy.zig +91 -0
  339. package/src/runtime/media_surface.zig +40 -1
  340. package/src/runtime/motion_sampling_policy.zig +159 -0
  341. package/src/runtime/recording_policy.zig +42 -0
  342. package/src/runtime/render_animation_policy.zig +206 -0
  343. package/src/runtime/replay_policy.zig +66 -0
  344. package/src/runtime/replay_policy_reference.zig +326 -0
  345. package/src/runtime/replay_progress_policy.zig +64 -0
  346. package/src/runtime/replay_progress_reference.zig +34 -0
  347. package/src/runtime/request_policy_test_reference.zig +188 -0
  348. package/src/runtime/root.zig +13 -0
  349. package/src/runtime/session_blobs.zig +157 -58
  350. package/src/runtime/session_blobs_reference.zig +692 -0
  351. package/src/runtime/session_codec.zig +361 -0
  352. package/src/runtime/session_codec_reference.zig +1027 -0
  353. package/src/runtime/session_journal.zig +246 -983
  354. package/src/runtime/session_record.zig +224 -45
  355. package/src/runtime/session_replay.zig +157 -415
  356. package/src/runtime/session_tests.zig +552 -0
  357. package/src/runtime/shell_admission_policy.zig +225 -0
  358. package/src/runtime/shell_coordination_policy.zig +138 -0
  359. package/src/runtime/shell_layout.zig +126 -1
  360. package/src/runtime/snapshot_policy.zig +60 -0
  361. package/src/runtime/snapshot_reference.zig +64 -0
  362. package/src/runtime/state.zig +16 -0
  363. package/src/runtime/status_validation.zig +190 -0
  364. package/src/runtime/system_admission_policy.zig +140 -0
  365. package/src/runtime/system_services.zig +46 -36
  366. package/src/runtime/tests.zig +1 -0
  367. package/src/runtime/ts_canvas_hooks.zig +261 -0
  368. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  369. package/src/runtime/ts_canvas_icons.zig +234 -0
  370. package/src/runtime/ts_core_host.zig +2325 -411
  371. package/src/runtime/ts_core_host_tests.zig +1982 -0
  372. package/src/runtime/ts_test_host.zig +699 -0
  373. package/src/runtime/ts_ui_app.zig +1087 -45
  374. package/src/runtime/ui_app.zig +1117 -629
  375. package/src/runtime/ui_app_provenance.zig +147 -5
  376. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  377. package/src/runtime/ui_app_tests.zig +619 -9
  378. package/src/runtime/ui_app_window_tests.zig +89 -0
  379. package/src/runtime/view.zig +25 -0
  380. package/src/runtime/view_canvas.zig +30 -6
  381. package/src/runtime/view_coordination_policy.zig +147 -0
  382. package/src/runtime/view_widget_control.zig +51 -14
  383. package/src/runtime/view_widget_scroll.zig +16 -5
  384. package/src/runtime/view_widget_text.zig +153 -68
  385. package/src/runtime/view_widget_tree.zig +460 -56
  386. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  387. package/src/runtime/widget_motion_policy.zig +238 -0
  388. package/src/runtime/window_command_bridge_tests.zig +63 -0
  389. package/src/runtime/window_lifecycle_policy.zig +127 -0
  390. package/src/runtime/window_storage.zig +74 -8
  391. package/src/runtime/window_view_runtime.zig +148 -33
  392. package/src/runtime/window_views.zig +163 -10
  393. package/src/tooling/components/identity_tests.zig +62 -36
  394. package/src/tooling/components/stepper.native +24 -0
  395. package/src/tooling/components/stepper.zig +0 -19
  396. package/src/tooling/components/timeline-item.native +22 -0
  397. package/src/tooling/components/timeline.native +5 -3
  398. package/src/tooling/components/timeline_item.zig +0 -32
  399. package/src/tooling/eject_components.zig +76 -8
  400. package/src/tooling/ios.zig +66 -12
  401. package/src/tooling/manifest.zig +35 -0
  402. package/src/tooling/raw_manifest.zig +6 -0
  403. package/src/tooling/templates.zig +15 -3
  404. package/src/tooling/ts_core.zig +13 -3
  405. package/src/tooling/verbs.zig +22 -0
  406. package/tools/corewire/build_profile.mjs +54 -0
  407. package/tools/corewire/contract_intake.ts +303 -0
  408. package/tools/corewire/contract_intake.zig +82 -0
  409. package/tools/corewire/core.test.ts +166 -0
  410. package/tools/corewire/core_abi.zig +51 -0
  411. package/tools/corewire/core_cases.ts +233 -0
  412. package/tools/corewire/core_contract.ts +407 -0
  413. package/tools/corewire/core_emission.ts +136 -0
  414. package/tools/corewire/core_emission.zig +69 -0
  415. package/tools/corewire/core_goldens.json +3110 -0
  416. package/tools/corewire/core_policy.ts +14 -0
  417. package/tools/corewire/core_policy.zig +48 -0
  418. package/tools/corewire/core_projection.ts +360 -0
  419. package/tools/corewire/core_vocabulary.ts +6 -0
  420. package/tools/corewire/emit.zig +19 -1590
  421. package/tools/corewire/emit_facade.ts +714 -0
  422. package/tools/corewire/emit_facade.zig +10 -3752
  423. package/tools/corewire/emit_mirror.ts +290 -0
  424. package/tools/corewire/emit_profile.ts +50 -0
  425. package/tools/corewire/emit_service.ts +331 -0
  426. package/tools/corewire/emit_service.zig +23 -842
  427. package/tools/corewire/entry.test.ts +95 -0
  428. package/tools/corewire/entry_coordination.ts +127 -0
  429. package/tools/corewire/entry_coordination.zig +190 -0
  430. package/tools/corewire/facade_templates.ts +85 -0
  431. package/tools/corewire/filesystem.test.ts +166 -0
  432. package/tools/corewire/filesystem_coordination.ts +213 -0
  433. package/tools/corewire/filesystem_coordination.zig +245 -0
  434. package/tools/corewire/intake.test.ts +35 -0
  435. package/tools/corewire/intake_cases.ts +55 -0
  436. package/tools/corewire/intake_goldens.json +12237 -0
  437. package/tools/corewire/invocation.test.ts +24 -0
  438. package/tools/corewire/invocation.ts +175 -0
  439. package/tools/corewire/invocation.zig +136 -0
  440. package/tools/corewire/invocation_cases.ts +60 -0
  441. package/tools/corewire/invocation_fixture.ts +33 -0
  442. package/tools/corewire/invocation_goldens.json +1143 -0
  443. package/tools/corewire/invocation_tests.zig +111 -0
  444. package/tools/corewire/invocation_usage.ts +2 -0
  445. package/tools/corewire/lossless_projection.ts +96 -0
  446. package/tools/corewire/main.zig +7 -680
  447. package/tools/corewire/main_reference.zig +415 -0
  448. package/tools/corewire/mirror_templates.ts +55 -0
  449. package/tools/corewire/profile.test.ts +248 -0
  450. package/tools/corewire/profile.zig +56 -0
  451. package/tools/corewire/profile_emission.ts +202 -0
  452. package/tools/corewire/profile_library.json +29 -0
  453. package/tools/corewire/profile_tests.zig +136 -0
  454. package/tools/corewire/service.test.ts +75 -0
  455. package/tools/corewire/service_cases.ts +61 -0
  456. package/tools/corewire/service_contract.zig +40 -146
  457. package/tools/corewire/service_goldens.json +650 -0
  458. package/tools/corewire/service_projection.zig +52 -0
  459. package/tools/corewire/service_templates.ts +14 -0
  460. package/tools/corewire/shim_rt.zig +9 -0
  461. package/tools/corewire/sidecar.zig +267 -1438
  462. package/tools/corewire/emit_profile.zig +0 -521
@@ -0,0 +1,3930 @@
1
+ /** Status-item reconciliation over eight native-owned slots. Operations 0/1
2
+ * return retirement masks or ordered admission decisions. Operation 2 compares
3
+ * three opaque eight-byte hashes independently; no hash crosses as a number.
4
+ * Native applies OS results before the next admission, owns capability failures
5
+ * and retains frame lifetime until all borrowed commands have been consumed.
6
+ */
7
+ export function native_status_policy(request: Uint8Array): Uint8Array {
8
+ const result = new Uint8Array(2); result[1] = 255;
9
+ if (request[0] === 2) {
10
+ if (request.length !== 49) throw new Error("invalid status patch request");
11
+ for (let field = 0; field < 3; field++) {
12
+ let changed = false;
13
+ for (let byte = 0; byte < 8; byte++) {
14
+ if (request[1 + field * 8 + byte] !== request[25 + field * 8 + byte]) changed = true;
15
+ }
16
+ if (changed) result[0] = result[0]! | (1 << field);
17
+ }
18
+ return result;
19
+ }
20
+ if (request.length < 44 || (request[0] !== 0 && request[0] !== 1)) throw new Error("invalid status policy request");
21
+ const operation = request[0]!, index = request[1]!, count = request[2]!, appliedCount = request[3]!;
22
+ if (count > 8 || appliedCount > 8 || request.length !== 44 + count * 4 || (operation === 1 && index >= count)) {
23
+ throw new Error("invalid status declaration table");
24
+ }
25
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
26
+ const ids: number[] = [];
27
+ for (let i = 0; i < count; i++) ids.push(data.getUint32(4 + i * 4, true));
28
+ const active: boolean[] = [], stored: number[] = [];
29
+ for (let slot = 0; slot < 8; slot++) {
30
+ const at = 4 + count * 4 + slot * 5;
31
+ if (request[at]! > 1) throw new Error("invalid status slot");
32
+ active.push(request[at] === 1); stored.push(data.getUint32(at + 1, true));
33
+ }
34
+ if (operation === 0) {
35
+ for (let slot = 0; slot < 8; slot++) {
36
+ let keep = false;
37
+ for (const id of ids) if (id === stored[slot]) keep = true;
38
+ if (active[slot] && !keep) result[0] = result[0]! | (1 << slot);
39
+ }
40
+ return result;
41
+ }
42
+ const id = ids[index]!;
43
+ if (id === 0) return result;
44
+ for (let i = 0; i < index; i++) if (ids[i] === id) return result;
45
+ // Retained lookup precedes the count guard and first-free admission.
46
+ for (let slot = 0; slot < 8; slot++) if (active[slot] && stored[slot] === id) {
47
+ result[0] = 3; result[1] = slot; return result;
48
+ }
49
+ if (appliedCount < 8) for (let slot = 0; slot < 8; slot++) if (!active[slot]) {
50
+ result[0] = 2; result[1] = slot; return result;
51
+ }
52
+ result[0] = 1; return result;
53
+ }
54
+
55
+ /** Portable stock-theme decisions. Native retains owned token registers, OS
56
+ * appearance facts and surface scale. Results are copied without resetting
57
+ * the dispatch arena: a theme helper may still own borrowed accent bytes.
58
+ * Operations: 0 exact #rrggbb parsing; 1 pack/scheme/accent resolution;
59
+ * 2 complete-token precedence and appearance/rebuild coordination.
60
+ */
61
+ export function native_theme_policy(request: Uint8Array): Uint8Array {
62
+ const result = new Uint8Array(4);
63
+ if (request[0] === 0) {
64
+ if (request.length !== 8 || request[1] !== 35) return result;
65
+ for (let channel = 0; channel < 3; channel++) {
66
+ const hi = themeHexNibble(request[2 + channel * 2]!);
67
+ const lo = themeHexNibble(request[3 + channel * 2]!);
68
+ if (hi < 0 || lo < 0) return new Uint8Array(4);
69
+ result[channel + 1] = hi * 16 + lo;
70
+ }
71
+ result[0] = 1;
72
+ return result;
73
+ }
74
+ if (request[0] === 1) {
75
+ if (request.length !== 8 || request[1]! > 2 || request[2]! < 1 || request[2]! > 2 || request[3]! > 2) {
76
+ throw new Error("invalid stock theme request");
77
+ }
78
+ for (let i = 4; i < 8; i++) if (request[i]! > 1) throw new Error("invalid theme appearance flag");
79
+ result[0] = request[1] === 0 ? request[2]! : request[1]!;
80
+ result[1] = request[3] === 0 ? request[4]! : request[3]! - 1;
81
+ result[2] = request[5] === 1 ? 0 : request[6] === 1 ? 1 : request[7] === 1 ? 2 : 0;
82
+ return result;
83
+ }
84
+ if (request[0] === 2) {
85
+ if ((request.length !== 5 && request.length !== 6) || request[4]! > 2 || (request.length === 6 && request[5]! > 1)) throw new Error("invalid theme control request");
86
+ for (let i = 1; i < 4; i++) if (request[i]! > 1) throw new Error("invalid theme control flag");
87
+ result[0] = request[1] === 1 ? 1 : request[2] === 1 ? 2 : 0;
88
+ result[1] = result[0] === 0 && (request[3] === 0 || request[4] === 0) ? 1 : 0;
89
+ const overrides = request.length === 6 && request[5] === 1;
90
+ result[2] = request[1] === 1 || request[3] === 1 || result[1] === 1 || overrides ? 1 : 0;
91
+ return result;
92
+ }
93
+ throw new Error("unknown theme policy operation");
94
+ }
95
+
96
+ function themeHexNibble(byte: number): number {
97
+ if (byte >= 48 && byte <= 57) return byte - 48;
98
+ if (byte >= 65 && byte <= 70) return byte - 65 + 10;
99
+ if (byte >= 97 && byte <= 102) return byte - 97 + 10;
100
+ return -1;
101
+ }
102
+
103
+ /** An engine identity remains two exact words. Only a bounded table offset
104
+ * becomes a number; adjacent namespaces and max-u64 must never alias a slot.
105
+ */
106
+ function completionSlot(request: Uint8Array, keyAt: number, baseAt: number): number {
107
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
108
+ const keyLower = wire.getUint32(keyAt, true), keyUpper = wire.getUint32(keyAt + 4, true);
109
+ const baseLower = wire.getUint32(baseAt, true), baseUpper = wire.getUint32(baseAt + 4, true);
110
+ if (keyUpper < baseUpper || keyUpper === baseUpper && keyLower < baseLower)
111
+ throw new Error("completion outside key namespace");
112
+ const difference = keyLower - baseLower;
113
+ const upper = keyUpper - baseUpper - (difference < 0 ? 1 : 0);
114
+ const slot = difference < 0 ? difference + 4294967296 : difference;
115
+ if (upper !== 0 || slot >= 16) throw new Error("completion outside owner table");
116
+ return slot;
117
+ }
118
+
119
+ /** Buffered callbacks (17): legacy file, complete file, buffered fetch and
120
+ * clipboard read. A 24-byte header carries family, operation, outcome,
121
+ * truncation and exact key/base words; sixteen records hold used/dropped and
122
+ * the two routes. The eight-byte plan owns slot, route, payload, reason,
123
+ * retirement and silent-drop decisions. Native copies borrowed payloads.
124
+ */
125
+ function bufferedCompletionPolicy(request: Uint8Array): Uint8Array {
126
+ if (request.length !== 88 || request[1]! > 3 || request[4]! > 1 || request[5] !== 0 || request[6] !== 0 || request[7] !== 0)
127
+ throw new Error("invalid buffered completion header");
128
+ const family = request[1]!, operation = request[2]!, outcome = request[3]!;
129
+ if (family <= 1 ? operation > 8 || outcome > 8 : operation !== 0 || outcome > (family === 2 ? 6 : 3))
130
+ throw new Error("invalid buffered completion enum");
131
+ for (let at = 24; at < 88; at += 4)
132
+ if (request[at]! > 1 || request[at + 1]! > 1) throw new Error("invalid buffered completion slot");
133
+ const slot = completionSlot(request, 8, 16), owner = 24 + slot * 4;
134
+ if (request[owner] !== 1) throw new Error("buffered completion owner is not tracked");
135
+ const result = new Uint8Array(8);
136
+ result[0] = slot; result[4] = 1;
137
+ const dropped = request[owner + 1] === 1;
138
+ if (family === 1) {
139
+ result[1] = request[owner + (dropped ? 3 : 2)]!;
140
+ result[2] = 6; result[5] = dropped ? 1 : 0;
141
+ return result;
142
+ }
143
+ if (dropped) { result[1] = request[owner + 3]!; result[5] = 1; return result; }
144
+ const cut = family === 2 && request[4] === 1;
145
+ const success = outcome === 0 && !cut;
146
+ result[1] = request[owner + (success ? 2 : 3)]!;
147
+ result[2] = success ? family === 2 ? 4 : family === 3 || operation === 0 ? 2 : operation === 3 ? 3 : 1 : 5;
148
+ result[3] = success ? 0 : outcome === 0 && cut ? 2 : 1;
149
+ return result;
150
+ }
151
+
152
+ /** Timer callbacks (7): delay or subscription, outcome, exact key/timestamp/
153
+ * base words, then sixteen used/full-result/mode/route records. The complete
154
+ * 40-byte plan returns slot, route, payload, retirement, exact decimal
155
+ * timestamp and the legacy fractional-millisecond value. Subscription fires
156
+ * intentionally retain the old queued-fire behavior for an unused slot.
157
+ */
158
+ function timerCompletionPolicy(request: Uint8Array): Uint8Array {
159
+ if (request.length !== 96 || request[1]! > 1 || request[2]! > 1 || request[3] !== 0)
160
+ throw new Error("invalid timer completion header");
161
+ for (let i = 28; i < 32; i++) if (request[i] !== 0) throw new Error("invalid timer completion reserved byte");
162
+ for (let at = 32; at < 96; at += 4)
163
+ if (request[at]! > 1 || request[at + 1]! > 1 || request[at + 2]! > 1) throw new Error("invalid timer completion slot");
164
+ const subscription = request[1] === 1, rejected = request[2] === 1;
165
+ if (subscription && rejected) throw new Error("platform rejected subscription timer");
166
+ const slot = completionSlot(request, 4, 20), owner = 32 + slot * 4;
167
+ if (!subscription && request[owner] !== 1) throw new Error("delay completion owner is not armed");
168
+ const full = !subscription && request[owner + 1] === 1;
169
+ if (!subscription && !full && rejected) throw new Error("platform rejected legacy delay");
170
+ const result = new Uint8Array(40), wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
171
+ result[0] = slot; result[1] = request[owner + 3]!; result[2] = full ? 1 : 0;
172
+ result[3] = !subscription && (!full || request[owner + 2] === 0 || rejected) ? 1 : 0;
173
+ let lower = wire.getUint32(12, true), upper = wire.getUint32(16, true);
174
+ new DataView(result.buffer).setFloat64(8, (upper * 4294967296 + lower) / 1000000, true);
175
+ const reversed = new Uint8Array(20);
176
+ let length = 0;
177
+ do {
178
+ const quotientUpper = Math.floor(upper / 10);
179
+ const combined = (upper - quotientUpper * 10) * 4294967296 + lower;
180
+ const quotientLower = Math.floor(combined / 10);
181
+ reversed[length++] = 48 + combined - quotientLower * 10;
182
+ upper = quotientUpper; lower = quotientLower;
183
+ } while (upper !== 0 || lower !== 0);
184
+ result[4] = length;
185
+ for (let i = 0; i < length; i++) result[16 + i] = reversed[length - i - 1]!;
186
+ return result;
187
+ }
188
+
189
+ /** Window set reconciliation over ordered native-owned slots. Operation 0
190
+ * selects the first stale slot; the caller removes it (swapping the last slot)
191
+ * and asks again before creating anything. Operation 1 handles one descriptor
192
+ * against the current table, so failed OS creates never reserve an identity.
193
+ * Labels are opaque bytes. Existing labels only update the owned close message;
194
+ * their creation-time canvas, title, geometry and close policy stay fixed.
195
+ */
196
+ export function native_window_policy(request: Uint8Array): Uint8Array {
197
+ if (request[0] === 82) return nscvImageRegistry(request);
198
+ if (request[0] === 83) return nscvFontRegistry(request);
199
+ if (request[0] === 84) return nscvShellCoordination(request);
200
+ if (request[0] === 85) return nscvShellAdmission(request);
201
+ if (request[0] === 86) return nscvSystemAdmission(request);
202
+ if (request[0] === 87) return nscvBridgeDescriptors(request);
203
+ if (request[0] === 88) return nscvAuthorization(request);
204
+ if (request[0] === 90) return nscvAutomationCommands(request);
205
+ if (request[0] === 91) return nscvAutomationInteractions(request);
206
+ if (request[0] === 89) return nscvBuiltinCoordination(request);
207
+ if (request[0] === 81) return nscvWindowLifecycle(request);
208
+ if (request[0] === 80) return nscvViewCoordination(request);
209
+ if (request[0] === 2) return nscvShellLayout(request);
210
+ if (request[0] === 3) return nscvSurfaceLayout(request);
211
+ if (request[0] === 4) return nscvGridLayout(request);
212
+ if (request[0] === 5) return nscvContainerLayout(request);
213
+ if (request[0] === 6) return nscvIntrinsicLayout(request);
214
+ if (request[0] === 7) return nscvWrappedLayout(request);
215
+ if (request[0] === 8) return nscvVirtualFlow(request);
216
+ if (request[0] === 9) return nscvSemanticTree(request);
217
+ if (request[0] === 10) return nscvExtentPolicy(request);
218
+ if (request[0] === 11) return nscvTextCachePolicy(request);
219
+ if (request[0] === 12) return nscvRenderCachePolicy(request);
220
+ if (request[0] === 13) return nscvRenderPlanPolicy(request);
221
+ if (request[0] === 14) return nscvRenderOverridePolicy(request);
222
+ if (request[0] === 15) return nscvRenderDamagePolicy(request);
223
+ if (request[0] === 16) return nscvControlAppearance(request);
224
+ if (request[0] === 17) return nscvConstructionPolicy(request);
225
+ if (request[0] === 18) return nscvWidgetMotion(request);
226
+ if (request[0] === 19) return nscvCompositionPolicy(request);
227
+ if (request[0] === 20) return nscvCodeContentPolicy(request);
228
+ if (request[0] === 21) return nscvChartContentPolicy(request);
229
+ if (request[0] === 22) return nscvMarkdownContentPolicy(request);
230
+ if (request[0] === 23) return nscvWidgetAudits(request);
231
+ if (request[0] === 24) return nscvWidgetRouting(request);
232
+ if (request[0] === 25) return nscvWidgetChanges(request);
233
+ if (request[0] === 26) return nscvWidgetPaint(request);
234
+ if (request[0] === 27) return nscvWidgetPresentation(request);
235
+ if (request[0] === 28) return nscvWidgetPaintWalk(request);
236
+ if (request[0] === 29) return nscvControlGeometry(request);
237
+ if (request[0] === 30) return nscvControlContent(request);
238
+ if (request[0] === 31) return nscvSurfaceRecipes(request);
239
+ if (request[0] === 32) return nscvWidgetMetrics(request);
240
+ if (request[0] === 33) return nscvIntrinsicMeasure(request);
241
+ if (request[0] === 34) return nscvWrappedMeasure(request);
242
+ if (request[0] === 35) return nscvAxisChildMeasure(request);
243
+ if (request[0] === 36) return nscvSpanSubtree(request);
244
+ if (request[0] === 37) return nscvAxisMeasure(request);
245
+ if (request[0] === 38) return nscvGridMeasure(request);
246
+ if (request[0] === 39) return nscvFlowMeasure(request);
247
+ if (request[0] === 40) return nscvLayoutAdmission(request);
248
+ if (request[0] === 41) return nscvLayoutChildren(request);
249
+ if (request[0] === 42) return nscvLayoutRetained(request);
250
+ if (request[0] === 43) return nscvRenderRecipe(request);
251
+ if (request[0] === 44) return nscvRenderChildren(request);
252
+ if (request[0] === 45) return nscvControlCommands(request);
253
+ if (request[0] === 46) return nscvControlPayloads(request);
254
+ if (request[0] === 47) return nscvControlPrimitives(request);
255
+ if (request[0] === 48) return nscvControlVectors(request);
256
+ if (request[0] === 49) return nscvLeafPlans(request);
257
+ if (request[0] === 50) return nscvChartPlans(request);
258
+ if (request[0] === 51) return nscvIndicatorPlans(request);
259
+ if (request[0] === 52) return nscvEffectPlans(request);
260
+ if (request[0] === 53) return nscvParagraphLayout(request);
261
+ if (request[0] === 54) return nscvTextRunLayout(request);
262
+ if (request[0] === 55) return nscvTextQueryLayout(request);
263
+ if (request[0] === 56) return nscvTextSpanQueries(request);
264
+ if (request[0] === 57) return nscvTextSpanBounds(request);
265
+ if (request[0] === 58) return nscvTextMeasurementCache(request);
266
+ if (request[0] === 59) return nscvTextDocumentWidth(request);
267
+ if (request[0] === 60) return nscvScalarText(request);
268
+ if (request[0] === 61) return nscvGlyphAtlasPlan(request);
269
+ if (request[0] === 62) return nscvRegisteredFont(request);
270
+ if (request[0] === 63) return nscvVectorEffects(request);
271
+ if (request[0] === 65) return nscvGpuPlanning(request);
272
+ if (request[0] === 67) return nscvChromeComposition(request);
273
+ if (request[0] === 66) return nscvVectorRaster(request);
274
+ if (request[0] === 64) return nscvRenderResources(request);
275
+ if (request[0] === 68) return nscvAccessibility(request);
276
+ if (request[0] === 69) return nscvCommandCoordination(request);
277
+ if (request[0] === 70) return nscvStatusValidation(request);
278
+ if (request[0] === 71) return nscvGpuPacketPreparation(request);
279
+ if (request[0] === 74) return nscvGpuPresentation(request);
280
+ if (request[0] === 75) return nscvCanvasFrameCoordination(request);
281
+ if (request[0] === 76) return nscvCanvasSceneObservation(request);
282
+ if (request[0] === 78) return nscvTerminalPaint(request);
283
+ if (request[0] === 77) return nscvCanvasPresentationLifecycle(request);
284
+ if (request[0] === 72) return nscvAnimationLifecycle(request);
285
+ if (request[0] === 73) return nscvMotionSampling(request);
286
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
287
+ let at = 0;
288
+ const byte = (): number => {
289
+ if (at >= request.length) throw new Error("truncated window policy request");
290
+ return request[at++]!;
291
+ };
292
+ const label = (): Uint8Array => {
293
+ if (at + 4 > request.length) throw new Error("truncated window policy label");
294
+ const length = data.getUint32(at, true); at += 4;
295
+ if (length > request.length - at) throw new Error("truncated window policy label");
296
+ const value = request.subarray(at, at + length); at += length; return value;
297
+ };
298
+ const equal = (a: Uint8Array, b: Uint8Array): boolean => {
299
+ if (a.length !== b.length) return false;
300
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
301
+ return true;
302
+ };
303
+ const operation = byte();
304
+ if (operation > 1) throw new Error("invalid window policy operation");
305
+ const declared: Uint8Array[] = [];
306
+ let main: Uint8Array = new Uint8Array(0), name: Uint8Array = new Uint8Array(0), canvas: Uint8Array = new Uint8Array(0);
307
+ if (operation === 0) {
308
+ const count = byte();
309
+ if (count > 4) throw new Error("invalid window declaration count");
310
+ for (let i = 0; i < count; i++) declared.push(label());
311
+ } else { main = label(); name = label(); canvas = label(); }
312
+ const count = byte();
313
+ if (count > 4) throw new Error("invalid live window count");
314
+ const names: Uint8Array[] = [], canvases: Uint8Array[] = [];
315
+ for (let i = 0; i < count; i++) { names.push(label()); canvases.push(label()); }
316
+ if (at !== request.length) throw new Error("trailing window policy bytes");
317
+ const result = new Uint8Array(2); result[1] = 255;
318
+ if (operation === 0) {
319
+ for (let i = 0; i < count; i++) {
320
+ let keep = false;
321
+ for (const candidate of declared) if (equal(candidate, names[i]!)) keep = true;
322
+ if (!keep) { result[1] = i; break; }
323
+ }
324
+ return result;
325
+ }
326
+ // Lookup precedes admission: duplicate descriptors update the same slot
327
+ // even when the table is full or their later creation fields are invalid.
328
+ for (let i = 0; i < count; i++) if (equal(name, names[i]!)) {
329
+ result[0] = 1; result[1] = i; return result;
330
+ }
331
+ if (count === 4) { result[0] = 2; return result; }
332
+ if (name.length === 0 || name.length > 64 || canvas.length === 0 || canvas.length > 64) {
333
+ result[0] = 3; return result;
334
+ }
335
+ let collision = equal(canvas, main);
336
+ for (const value of canvases) if (equal(canvas, value)) collision = true;
337
+ if (collision) result[0] = 4;
338
+ return result;
339
+ }
340
+
341
+ /** Platform accessibility projection and publication over copied semantic facts.
342
+ * Identities and fingerprints remain eight opaque bytes. Native retains strings,
343
+ * history storage, OS elements and the last successfully published fingerprint.
344
+ */
345
+ function nscvAccessibility(request: Uint8Array): Uint8Array {
346
+ if (request.length < 4 || request[1]! > 2) throw new Error("invalid accessibility operation");
347
+ const operation = request[1]!;
348
+ if (operation === 1) {
349
+ if (request.length !== 20 || request[2]! > 1 || request[3]! > 3) throw new Error("invalid accessibility publication facts");
350
+ let equal = request[2] === 1;
351
+ for (let i = 0; i < 8; i++) if (request[4 + i] !== request[12 + i]) equal = false;
352
+ const out = new Uint8Array(4);
353
+ out[0] = equal ? 0 : request[3] === 3 ? 1 : 2;
354
+ return out;
355
+ }
356
+ if (operation === 2) {
357
+ if (request.length !== 4 || request[2]! > 1 || request[3]! > 3) throw new Error("invalid accessibility flush facts");
358
+ const out = new Uint8Array(4);
359
+ out[0] = request[2] === 1 && ((request[3]! & 2) !== 0 || (request[3]! & 1) === 0) ? 1 : 0;
360
+ return out;
361
+ }
362
+ if (request.length < 40 || request[2]! > 1 || request[3]! > 1) throw new Error("invalid accessibility projection header");
363
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
364
+ const count = wire.getUint32(4, true), capacity = wire.getUint32(8, true);
365
+ if (count > 1024 || capacity > 64 || request.length !== 40 + count * 32 || wire.getUint32(12, true) !== 0) throw new Error("invalid accessibility projection table");
366
+ const length = Math.min(count, capacity), out = new Uint8Array(8 + length * 28), result = new DataView(out.buffer);
367
+ result.setUint32(0, length, true);
368
+ const roles = [0, 1, 2, 4, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 21, 17, 18, 19, 3, 10, 11, 1];
369
+ for (let i = 0; i < count; i++) {
370
+ const at = 40 + i * 32, role = wire.getUint32(at + 12, true), state = wire.getUint32(at + 16, true), fields = wire.getUint32(at + 20, true), actions = wire.getUint32(at + 28, true);
371
+ if (role >= roles.length || state > 255 || fields > 63 || actions > 2047) throw new Error("invalid accessibility semantic facts");
372
+ if (i >= length) continue;
373
+ let zero = true, focusedId = true, hoveredId = true, pressedId = true;
374
+ for (let b = 0; b < 8; b++) {
375
+ if (request[at + b] !== 0) zero = false;
376
+ if (request[at + b] !== request[16 + b]) focusedId = false;
377
+ if (request[at + b] !== request[24 + b]) hoveredId = false;
378
+ if (request[at + b] !== request[32 + b]) pressedId = false;
379
+ }
380
+ const roleSelected = role === 17 || role === 18 || role === 20 || role === 12 || role === 15 || role === 16;
381
+ const selected = (state & 16) !== 0 || ((fields & 4) !== 0 && !(wire.getFloat32(at + 24, true) < 0.5) && roleSelected);
382
+ const flags = ((state & 8) === 0 ? 1 : 0) |
383
+ ((state & 4) !== 0 || (request[2] === 1 && request[3] === 1 && focusedId) ? 2 : 0) |
384
+ ((state & 1) !== 0 || (!zero && hoveredId) ? 4 : 0) |
385
+ ((state & 2) !== 0 || (!zero && pressedId) ? 8 : 0) |
386
+ (selected ? 16 : 0) | ((state & 32) !== 0 ? 32 : 0) |
387
+ ((state & 64) !== 0 ? 64 : 0) | ((state & 128) !== 0 ? 128 : 0) |
388
+ ((fields & 16) !== 0 ? 256 : 0) | ((fields & 32) !== 0 ? 512 : 0) | ((fields & 8) !== 0 ? 1024 : 0);
389
+ const target = 8 + i * 28, parent = wire.getUint32(at + 8, true);
390
+ if (parent < count) {
391
+ for (let b = 0; b < 8; b++) out[target + b] = request[40 + parent * 32 + b]!;
392
+ result.setUint32(target + 8, 1, true);
393
+ }
394
+ result.setUint32(target + 12, roles[role]!, true);
395
+ result.setUint32(target + 16, flags, true);
396
+ result.setUint32(target + 20, fields & 3, true);
397
+ result.setUint32(target + 24, actions, true);
398
+ }
399
+ return out;
400
+ }
401
+
402
+ /** Portable decisions over native-owned timer tables.
403
+ * Operations 0/1 reconcile subscriptions; 2 arms a delay, 3 looks up its key,
404
+ * and 4 routes a one-shot completion and retires its slot. The cycle owns both
405
+ * arenas; callers copy results without resetting bytes between records.
406
+ */
407
+
408
+ export function native_timer_policy(request: Uint8Array): Uint8Array {
409
+ if (request[0] === 7) return timerCompletionPolicy(request);
410
+ if (request[0] === 2 || request[0] === 3 || request[0] === 6 || request[0] === 8) return delayDeclaration(request);
411
+ if (request[0] === 4) {
412
+ if (request.length !== 20 || request[1]! >= 16) throw new Error("invalid delay completion request");
413
+ const slot = request[1]!;
414
+ const used = new DataView(request.buffer, request.byteOffset, request.byteLength).getUint16(2, true);
415
+ if ((used & (1 << slot)) === 0) throw new Error("delay completion slot is not armed");
416
+ const result = new Uint8Array(2);
417
+ result[0] = slot;
418
+ result[1] = request[4 + slot]!;
419
+ return result;
420
+ }
421
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
422
+ if (request.length === 5 && request[0] === 1) {
423
+ const used = data.getUint16(1, true), seen = data.getUint16(3, true);
424
+ const result = new Uint8Array(2);
425
+ new DataView(result.buffer).setUint16(0, used & ~seen, true);
426
+ return result;
427
+ }
428
+ if (request.length < 13 || request[0] !== 0) throw new Error("invalid timer policy request");
429
+ const seen = data.getUint16(1, true), keyLength = request[3]!;
430
+ const valueAt = 4 + keyLength;
431
+ if (valueAt + 9 > request.length) throw new Error("truncated timer policy declaration");
432
+ const every = data.getFloat64(valueAt, true), tag = request[valueAt + 8]!;
433
+ if (!(every >= 1 && every <= 31536000000)) throw new Error("timer interval must be between 1ms and one year");
434
+ let at = valueAt + 9, matching = -1, free = -1, previous = 0;
435
+ for (let slot = 0; slot < 16; slot++) {
436
+ if (at + 2 > request.length) throw new Error("truncated timer policy table");
437
+ const used = request[at]!, length = request[at + 1]!;
438
+ at += 2;
439
+ if (used > 1 || at + length + 8 > request.length) throw new Error("invalid timer policy slot");
440
+ let equal = used === 1 && length === keyLength;
441
+ for (let i = 0; i < length; i++) if (request[at + i] !== request[4 + i]) equal = false;
442
+ const interval = data.getFloat64(at + length, true);
443
+ if (used === 1 && !(interval >= 1 && interval <= 31536000000)) throw new Error("invalid timer policy interval");
444
+ if (equal) { matching = slot; previous = interval; }
445
+ if (used === 0 && free < 0) free = slot;
446
+ at += length + 8;
447
+ }
448
+ if (at !== request.length) throw new Error("trailing timer policy bytes");
449
+ const slot = matching >= 0 ? matching : free;
450
+ if (slot < 0) throw new Error("more than 16 subscription timers");
451
+ const result = new Uint8Array(14), output = new DataView(result.buffer);
452
+ result[0] = slot;
453
+ result[1] = matching < 0 || previous !== every ? 1 : 0;
454
+ result[2] = tag;
455
+ const whole = Math.floor(every);
456
+ output.setFloat64(4, every - whole >= 0.5 ? whole + 1 : whole, true);
457
+ output.setUint16(12, seen | (1 << slot), true);
458
+ return result;
459
+ }
460
+
461
+ /** Delays match the first live key; empty keys always allocate when arming.
462
+ * Each table record is [used, key length, key bytes, route]. Interval history
463
+ * is unnecessary: every arm restarts even when its cadence and route agree.
464
+ */
465
+ function delayDeclaration(request: Uint8Array): Uint8Array {
466
+ if (request.length < 2) throw new Error("invalid delay policy request");
467
+ const rejectable = request[0] === 6 || request[0] === 8;
468
+ const arm = request[0] === 2 || rejectable, keyLength = request[1]!;
469
+ let at = 2 + keyLength;
470
+ if (at + (arm ? 10 : 0) > request.length) throw new Error("truncated delay declaration");
471
+ let after = 0, tag = 0, blocked = 0;
472
+ if (arm) {
473
+ after = new DataView(request.buffer, request.byteOffset, request.byteLength).getFloat64(at, true);
474
+ tag = request[at + 8]!;
475
+ if (!(after >= 1 && after <= (request[0] === 8 ? 18446744073709 : 31536000000))) {
476
+ if (!rejectable) throw new Error("delay interval must be between 1ms and one year");
477
+ blocked = 1;
478
+ }
479
+ const externalBlocked = request[at + 9]!;
480
+ blocked = Math.max(blocked, externalBlocked);
481
+ if (externalBlocked > 1) throw new Error("invalid delay admission fact");
482
+ at += 10;
483
+ }
484
+ let matching = -1, free = -1;
485
+ for (let slot = 0; slot < 16; slot++) {
486
+ if (at + 2 > request.length) throw new Error("truncated delay policy table");
487
+ const used = request[at]!, length = request[at + 1]!;
488
+ at += 2;
489
+ if (used > 1 || at + length + 1 > request.length) throw new Error("invalid delay policy slot");
490
+ let equal = used === 1 && length === keyLength;
491
+ for (let i = 0; i < length; i++) if (request[at + i] !== request[2 + i]) equal = false;
492
+ if (equal && matching < 0) matching = slot;
493
+ if (used === 0 && free < 0) free = slot;
494
+ at += length + 1;
495
+ }
496
+ if (at !== request.length) throw new Error("trailing delay policy bytes");
497
+ if (!arm) {
498
+ const result = new Uint8Array(1);
499
+ result[0] = matching < 0 ? 255 : matching;
500
+ return result;
501
+ }
502
+ const slot = blocked === 1 ? 255 : keyLength > 0 && matching >= 0 ? matching : free;
503
+ if (slot < 0 && !rejectable) throw new Error("more than 16 armed delays");
504
+ const result = new Uint8Array(10);
505
+ result[0] = slot < 0 ? 255 : slot;
506
+ result[1] = tag;
507
+ const whole = Math.floor(after);
508
+ new DataView(result.buffer).setFloat64(2, after - whole >= 0.5 ? whole + 1 : whole, true);
509
+ return result;
510
+ }
511
+
512
+ /** Live-query reconciliation over a native-owned database table. Operation 0
513
+ * finds a key, 1 retains declared live keys before allocation, and 2 plans one
514
+ * declaration. Fingerprints are opaque bytes: preserve the reference host's
515
+ * equality semantics without rounding its 64-bit hash through a JS number.
516
+ * Inputs are borrowed; the host copies results and owns the cycle reset.
517
+ */
518
+ export function native_db_policy(request: Uint8Array): Uint8Array {
519
+ if (request.length < 2 || request[0]! > 2) throw new Error("invalid database policy request");
520
+ const op = request[0]!;
521
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
522
+ let keyStart = 2, keyLength = request[1]!, tableStart = keyStart + keyLength;
523
+ let keysEnd = 0, seen = 0, signatureAt = 0;
524
+ if (op === 1) {
525
+ if (request.length < 5) throw new Error("truncated database retention request");
526
+ keysEnd = 5 + data.getUint32(1, true);
527
+ if (keysEnd > request.length) throw new Error("truncated database retention request");
528
+ tableStart = keysEnd;
529
+ let at = 5;
530
+ while (at < keysEnd) {
531
+ const length = request[at]!;
532
+ if (length === 0 || at + 1 + length > keysEnd) throw new Error("invalid live-query key list");
533
+ at += 1 + length;
534
+ }
535
+ } else if (op === 2) {
536
+ if (request.length < 4) throw new Error("truncated database declaration request");
537
+ seen = data.getUint16(1, true);
538
+ keyLength = request[3]!;
539
+ keyStart = 4;
540
+ signatureAt = keyStart + keyLength;
541
+ tableStart = signatureAt + 11;
542
+ if (keyLength === 0) throw new Error("a live query requires a non-empty subscription key");
543
+ }
544
+ if (tableStart > request.length) throw new Error("truncated database policy request");
545
+ const offsets = new Uint8Array(64);
546
+ const positions = new DataView(offsets.buffer);
547
+ let at = tableStart, free = -1;
548
+ for (let slot = 0; slot < 16; slot++) {
549
+ if (at + 3 > request.length) throw new Error("truncated database policy table");
550
+ const used = request[at]!, live = request[at + 1]!, length = request[at + 2]!;
551
+ if (used > 1 || live > 1 || at + 11 + length > request.length) throw new Error("invalid database policy slot");
552
+ positions.setUint32(slot * 4, at, true);
553
+ if (used === 0 && free < 0) free = slot;
554
+ at += 11 + length;
555
+ }
556
+ if (at !== request.length) throw new Error("trailing database policy bytes");
557
+ if (op === 1) {
558
+ let retained = 0;
559
+ for (let keyAt = 5; keyAt < keysEnd; keyAt += 1 + request[keyAt]!) {
560
+ const slot = dbPolicyLookup(request, positions, keyAt + 1, request[keyAt]!);
561
+ if (slot >= 0 && request[positions.getUint32(slot * 4, true) + 1] === 1) retained |= 1 << slot;
562
+ }
563
+ const result = new Uint8Array(2);
564
+ new DataView(result.buffer).setUint16(0, retained, true);
565
+ return result;
566
+ }
567
+ const matching = dbPolicyLookup(request, positions, keyStart, keyLength);
568
+ if (op === 0) {
569
+ const result = new Uint8Array(1);
570
+ result[0] = matching < 0 ? 255 : matching;
571
+ return result;
572
+ }
573
+ const slot = matching >= 0 ? matching : free;
574
+ if (slot < 0) throw new Error("database slot family is full");
575
+ const entry = positions.getUint32(slot * 4, true), used = request[entry] === 1;
576
+ if (used && request[entry + 1] !== 1) throw new Error("a live-query key collides with an in-flight database command");
577
+ if ((seen & (1 << slot)) !== 0) throw new Error("duplicate live-query subscription key");
578
+ let changed = !used;
579
+ const storedSignature = entry + 3 + request[entry + 2]!;
580
+ for (let i = 0; i < 8; i++) if (request[signatureAt + i] !== request[storedSignature + i]) changed = true;
581
+ const result = new Uint8Array(8);
582
+ result[0] = slot;
583
+ result[1] = changed ? 1 : 0;
584
+ result[2] = used && changed ? 1 : 0;
585
+ result[3] = request[signatureAt + 8]!;
586
+ result[4] = request[signatureAt + 9]!;
587
+ result[5] = request[signatureAt + 10]!;
588
+ new DataView(result.buffer).setUint16(6, seen | (1 << slot), true);
589
+ return result;
590
+ }
591
+
592
+ function dbPolicyLookup(request: Uint8Array, positions: DataView, keyStart: number, keyLength: number): number {
593
+ if (keyLength === 0) return -1;
594
+ for (let slot = 0; slot < 16; slot++) {
595
+ const at = positions.getUint32(slot * 4, true);
596
+ if (request[at] !== 1 || request[at + 2] !== keyLength) continue;
597
+ let equal = true;
598
+ for (let i = 0; i < keyLength; i++) if (request[at + 3 + i] !== request[keyStart + i]) equal = false;
599
+ if (equal) return slot;
600
+ }
601
+ return -1;
602
+ }
603
+
604
+ /** Named buffered effects over native-owned slots. Admission returns both the
605
+ * predecessor to drop and the first free slot: dropping precedes capacity
606
+ * refusal, and a dropped predecessor stays occupied until its terminal drains.
607
+ * Completion selects a route/payload and retires one slot. This pure callback
608
+ * neither mutates its borrowed input nor resets the dispatch frame.
609
+ */
610
+ export function native_effect_policy(request: Uint8Array): Uint8Array {
611
+ if (request[0] === 32) return markupDevelopmentPolicy(request);
612
+ if (request[0] === 31) return hostFlowPolicy(request);
613
+ if (request[0] === 30) return sessionCodecPolicy(request);
614
+ if (request[0] === 29) return snapshotSerializationPolicy(request);
615
+ if (request.length < 2 || request[0]! > 29) throw new Error("invalid effect policy request");
616
+ if (request[0] === 28) return sessionBlobPolicy(request);
617
+ if (request[0] === 27) return snapshotCoordinationPolicy(request);
618
+ if (request[0] === 26) return sessionJournalPolicy(request);
619
+ if (request[0] === 25) return replayProgressPolicy(request);
620
+ if (request[0] === 24) return sessionRecordingPolicy(request);
621
+ if (request[0] === 22) return componentCoordinationPolicy(request);
622
+ if (request[0] === 23) return scrollReachPolicy(request);
623
+ if (request[0] === 21) return replayCoordinationPolicy(request);
624
+ if (request[0] === 20) return sessionReplayPolicy(request);
625
+ if (request[0] === 19) return appDispatchPolicy(request);
626
+ if (request[0] === 18) return appLifecyclePolicy(request);
627
+ if (request[0] === 17) return bufferedCompletionPolicy(request);
628
+ if (request[0] === 15) return fileStreamPolicy(request);
629
+ if (request[0] === 16) return clipboardWritePolicy(request);
630
+ if (request[0] === 11) return requestCoordinationPolicy(request);
631
+ if (request[0] === 12) return cancellationPolicy(request);
632
+ if (request[0] === 13) return credentialRecordPolicy(request);
633
+ if (request[0] === 14) return dbCommandPolicy(request);
634
+ if (request[0] === 8) return playbackLoadPolicy(request);
635
+ if (request[0] === 9) return ptyCoordinationPolicy(request);
636
+ if (request[0] === 10) return playbackEventPolicy(request);
637
+ if (request[0] === 6) return mediaTransportPolicy(request);
638
+ if (request[0]! >= 3) return mediaSlotPolicy(request);
639
+ if (request[0] === 2) {
640
+ if (request.length !== 69 || request[1]! >= 16 || request[2]! > 3 || request[3]! > 1 || request[4]! > 1)
641
+ throw new Error("invalid effect completion request");
642
+ for (let at = 5; at < request.length; at += 4)
643
+ if (request[at]! > 1 || request[at + 1]! > 1) throw new Error("invalid effect completion slot");
644
+ const slot = request[1]!, at = 5 + slot * 4;
645
+ if (request[at] !== 1) throw new Error("effect completion slot is not tracked");
646
+ const result = new Uint8Array(4);
647
+ result[0] = slot;
648
+ if (request[at + 1] === 1) {
649
+ result[1] = request[at + 3]!;
650
+ return result; // Swallow; the inert stand-in uses the error arm.
651
+ }
652
+ const cut = request[2] === 3 && request[4] === 1;
653
+ const success = request[3] === 1 && !cut;
654
+ result[1] = request[at + (success ? 2 : 3)]!;
655
+ result[2] = success ? request[2]! + 1 : 5;
656
+ result[3] = success ? 0 : request[3] === 1 && cut ? 2 : 1;
657
+ return result;
658
+ }
659
+ const arm = request[0] === 0, length = request[1]!;
660
+ let at = 2 + length;
661
+ if (at + (arm ? 3 : 0) > request.length) throw new Error("truncated effect declaration");
662
+ let blocked = 0, ok = 0, err = 0;
663
+ if (arm) {
664
+ blocked = request[at]!; ok = request[at + 1]!; err = request[at + 2]!;
665
+ if (blocked > 1) throw new Error("invalid effect admission fact");
666
+ at += 3;
667
+ }
668
+ let matching = -1, free = -1;
669
+ for (let slot = 0; slot < 16; slot++) {
670
+ if (at + 3 > request.length) throw new Error("truncated effect policy table");
671
+ const used = request[at]!, dropped = request[at + 1]!, size = request[at + 2]!;
672
+ if (used > 1 || dropped > 1 || at + 5 + size > request.length) throw new Error("invalid effect policy slot");
673
+ let equal = used === 1 && dropped === 0 && size === length;
674
+ for (let i = 0; i < size; i++) if (request[at + 3 + i] !== request[2 + i]) equal = false;
675
+ if (equal && matching < 0) matching = slot;
676
+ if (used === 0 && free < 0) free = slot;
677
+ at += 5 + size;
678
+ }
679
+ if (at !== request.length) throw new Error("trailing effect policy bytes");
680
+ if (!arm) {
681
+ const result = new Uint8Array(1);
682
+ result[0] = matching < 0 ? 255 : matching;
683
+ return result;
684
+ }
685
+ const result = new Uint8Array(5);
686
+ result[0] = blocked === 0 ? 1 : 0;
687
+ result[1] = blocked === 1 || free < 0 ? 255 : free;
688
+ result[2] = blocked === 1 || length === 0 || matching < 0 ? 255 : matching;
689
+ result[3] = ok; result[4] = err;
690
+ return result;
691
+ }
692
+
693
+ /** App coordination over native-owned capabilities. Operation 18 returns a
694
+ * copied 32-byte plan without resetting the frame. Suboperations: 0 lifecycle
695
+ * flush, 1 ordered installation, 2 restore source, 3 restore completion,
696
+ * 4 restore route/reason, 5 store-channel reason, 6 ordered launch values,
697
+ * 7 service carrier routing. Sizes and indices cross as exact u64 word pairs.
698
+ * Native retains buffers, migration versions, channel handles and typed Msgs.
699
+ */
700
+ function appLifecyclePolicy(request: Uint8Array): Uint8Array {
701
+ const mode = request[1]!;
702
+ const size = mode === 0 ? 6 : mode === 1 ? 6 : mode === 2 ? 5 :
703
+ mode === 3 ? 16 : mode === 4 || mode === 5 ? 3 : mode === 6 ? 32 : 0;
704
+ if (mode > 7 || (mode === 7 ? request.length < 3 : request.length !== size))
705
+ throw new Error("invalid app lifecycle request");
706
+ const result = new Uint8Array(32);
707
+ if (mode === 0) {
708
+ if (request[2]! > 5 || request[3]! > 1 || request[4]! > 1 || request[5] !== 0)
709
+ throw new Error("invalid app lifecycle flush facts");
710
+ const pending = request[4] === 1;
711
+ if (request[2] === 5) { result[1] = pending ? 1 : 0; return result; }
712
+ const terminal = request[2] === 2 || request[2] === 4;
713
+ result[0] = terminal && request[3] === 1 ? 1 : pending ? 1 : 0;
714
+ result[1] = terminal && request[3] === 0 ? 1 : 0;
715
+ return result;
716
+ }
717
+ if (mode === 1) {
718
+ for (let i = 2; i < 6; i++) if (request[i]! > 1) throw new Error("invalid app installation facts");
719
+ // Carrier precedence, then assets/channel/restore, boot, outcome, env, root.
720
+ result[0] = request[2] === 1 ? 1 : request[3] === 1 ? 2 : request[4] === 1 ? 3 : 0;
721
+ let at = result[0] === 0 ? 0 : 1;
722
+ result[at++] = 4;
723
+ if (request[4] === 1 && request[5] === 1) result[at++] = 5;
724
+ if (request[4] === 1) result[at++] = 6;
725
+ result[at++] = 7; result[at++] = 8; result[at++] = 9; result[at] = 10;
726
+ return result;
727
+ }
728
+ if (mode === 2) {
729
+ for (let i = 2; i < 5; i++) if (request[i]! > 1) throw new Error("invalid app restore source facts");
730
+ result[0] = request[2] === 0 ? 0 : request[3] === 1 ? 1 : request[4] === 1 ? 2 : 3;
731
+ return result;
732
+ }
733
+ if (mode === 3) {
734
+ if (request[2]! > 2 || request[3]! > 1 || request[4]! > 1 || request[5]! > 6 ||
735
+ request[6] !== 0 || request[7] !== 0) throw new Error("invalid app restore completion facts");
736
+ result[0] = 255;
737
+ if (request[3] === 0) return result;
738
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
739
+ const migrated = request[2] === 2;
740
+ const refused = data.getUint32(12, true) !== 0 || data.getUint32(8, true) > 16777216;
741
+ const outcome = migrated ? request[4] === 0 ? 4 : refused ? 6 : 0 : request[5]!;
742
+ result[0] = outcome;
743
+ // Actions 1 restore, 2 save, 3 journal. Refused migrations journal empty.
744
+ let at = 1;
745
+ if (outcome === 0) result[at++] = 1;
746
+ if (migrated && outcome === 0) result[at++] = 2;
747
+ if (request[2] !== 0) result[at] = 3;
748
+ result[5] = migrated && outcome !== 0 ? 0 : 1;
749
+ return result;
750
+ }
751
+ if (mode === 4) {
752
+ if (request[2]! > 6) throw new Error("invalid app persistence outcome");
753
+ result[0] = request[2] === 0 ? 1 : request[2] === 1 ? 2 : 3;
754
+ if (result[0] === 3) {
755
+ const reason = request[2] === 2 ? "corrupt" : request[2] === 3 ? "version_unknown" :
756
+ request[2] === 4 ? "migrate_failed" : request[2] === 5 ? "io_failed" : "rejected";
757
+ result[1] = reason.length;
758
+ for (let i = 0; i < reason.length; i++) result[2 + i] = reason.charCodeAt(i);
759
+ }
760
+ return result;
761
+ }
762
+ if (mode === 5) {
763
+ if (request[2]! > 2) throw new Error("invalid app persistence channel event");
764
+ if (request[2] === 0) return result; // Borrow the complete incoming bytes.
765
+ const reason = request[2] === 1 ? "io_failed" : "rejected";
766
+ result[0] = 1; result[1] = reason.length;
767
+ for (let i = 0; i < reason.length; i++) result[2 + i] = reason.charCodeAt(i);
768
+ return result;
769
+ }
770
+ if (mode === 6) {
771
+ if (request[2]! > 1) throw new Error("invalid app launch replay flag");
772
+ for (let i = 3; i < 8; i++) if (request[i] !== 0) throw new Error("invalid app launch reserved byte");
773
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
774
+ const replay = request[2] === 1 && (data.getUint32(8, true) !== 0 || data.getUint32(12, true) !== 0);
775
+ const countAt = replay ? 8 : 16, low = data.getUint32(24, true), high = data.getUint32(28, true);
776
+ const countLow = data.getUint32(countAt, true), countHigh = data.getUint32(countAt + 4, true);
777
+ if (high > countHigh || (high === countHigh && low >= countLow)) return result;
778
+ result[0] = replay ? 2 : 1; result[1] = replay ? 0 : 1;
779
+ const output = new DataView(result.buffer);
780
+ output.setUint32(8, low, true); output.setUint32(12, high, true);
781
+ output.setUint32(16, (low + 1) >>> 0, true); output.setUint32(20, high + (low === 4294967295 ? 1 : 0), true);
782
+ return result;
783
+ }
784
+ if (request[2]! > 7) throw new Error("invalid app service carrier operation");
785
+ if (request[2]! >= 2) {
786
+ if (request.length !== 3) throw new Error("invalid app service carrier facts");
787
+ result[0] = 1;
788
+ if (request[2]! >= 5) result[1] = 2;
789
+ return result;
790
+ }
791
+ const persist = "core.persist", flush = "core.persist.flush";
792
+ let isPersist = request.length === persist.length + 3, isFlush = request.length === flush.length + 3;
793
+ for (let i = 3; i < request.length; i++) {
794
+ if (isPersist && request[i] !== persist.charCodeAt(i - 3)) isPersist = false;
795
+ if (isFlush && request[i] !== flush.charCodeAt(i - 3)) isFlush = false;
796
+ }
797
+ result[0] = isPersist || isFlush ? 2 : 1;
798
+ return result;
799
+ }
800
+
801
+ /** Media lifecycle operations share the effect ABI and borrow native-owned
802
+ * tables. 3 admits a numeric owner; 4 resolves a numeric control; 5 routes and
803
+ * retires a complete event; 7 performs an opaque u64 lookup. Header: operation,
804
+ * family (image/channel/capture), count, event, tag, source, channels, reserved,
805
+ * key (f64 for 3/4, opaque u64 otherwise), u32 rate, f64 expected bytes. Slots:
806
+ * used, opaque u64 key, tag, source, u32 rate, channels. Results are owned bytes;
807
+ * keys/tokens never pass through a lossy floating-point conversion.
808
+ */
809
+ function mediaSlotPolicy(request: Uint8Array): Uint8Array {
810
+ if (request.length < 28 || ![3, 4, 5, 7].includes(request[0]!)) throw new Error("invalid media slot operation");
811
+ const operation = request[0]!, family = request[1]!, count = request[2]!;
812
+ if (family > 2 || count > (family === 0 ? 16 : 8) || request.length !== 28 + count * 16 || request[7]! > 1 || request[7] === 1 && (family !== 0 || operation !== 3 && operation !== 4) || request[5]! > 1)
813
+ throw new Error("invalid media slot request");
814
+ if (operation === 5 && (family === 0 ? request[3] !== 0 : family === 1 ? request[3]! > 2 : request[3]! > 4))
815
+ throw new Error("invalid media event kind");
816
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
817
+ const result = new Uint8Array(28), out = new DataView(result.buffer);
818
+ result[1] = 255; result[2] = request[4]!; result[4] = request[5]!; result[5] = request[6]!;
819
+ out.setUint32(24, wire.getUint32(16, true), true);
820
+ const words = request[7] === 1;
821
+ const numberKey = !words && (operation === 3 || operation === 4);
822
+ const key = wire.getFloat64(8, true);
823
+ const upper = wire.getUint32(12, true), lower = wire.getUint32(8, true);
824
+ const valid = words ? upper < 0x80000000 && (upper !== 0 || lower !== 0)
825
+ : !numberKey || Number.isFinite(key) && key >= 1 && key < 9007199254740992 && Math.floor(key) === key;
826
+ result[0] = valid ? 1 : 0;
827
+ if (valid) for (let i = 0; i < 8; i++) result[8 + i] = request[8 + i]!;
828
+ // f64 wire keys become exact u64 words only after the representability gate.
829
+ if (numberKey && valid) {
830
+ out.setUint32(8, key % 4294967296, true); out.setUint32(12, Math.floor(key / 4294967296), true);
831
+ }
832
+ const expected = wire.getFloat64(20, true);
833
+ if (Number.isFinite(expected) && expected >= 1 && expected < 9007199254740992 && Math.floor(expected) === expected) {
834
+ out.setUint32(16, expected % 4294967296, true); out.setUint32(20, Math.floor(expected / 4294967296), true);
835
+ }
836
+ let matching = -1, free = -1;
837
+ for (let slot = 0; slot < count; slot++) {
838
+ const at = 28 + slot * 16;
839
+ if (request[at]! > 1 || request[at + 10]! > 1) throw new Error("invalid media slot fact");
840
+ let equal = valid && request[at] === 1;
841
+ for (let i = 0; i < 8; i++) if (request[at + 1 + i] !== result[8 + i]) equal = false;
842
+ if (equal && matching < 0) matching = slot;
843
+ if (request[at] === 0 && free < 0) free = slot;
844
+ }
845
+ if (operation === 3) {
846
+ const rate = wire.getUint32(16, true), channels = request[6]!;
847
+ const format = family !== 2 || (rate === 16000 || rate === 24000 || rate === 48000) && (channels === 1 || channels === 2);
848
+ if (valid && format && matching < 0 && free >= 0) result[1] = free;
849
+ return result;
850
+ }
851
+ if (matching < 0) {
852
+ if (operation === 5) throw new Error("media event has no tracked owner");
853
+ return result;
854
+ }
855
+ result[1] = matching;
856
+ const at = 28 + matching * 16;
857
+ result[2] = request[at + 9]!;
858
+ if (operation === 5) {
859
+ result[3] = family === 0 || family === 1 && request[3] !== 0 || family === 2 && request[3]! >= 3 ? 1 : 0;
860
+ if (family === 2) {
861
+ result[4] = request[at + 10]!;
862
+ if (request[6] === 0) result[5] = request[at + 15]!;
863
+ if (wire.getUint32(16, true) === 0) out.setUint32(24, wire.getUint32(at + 11, true), true);
864
+ }
865
+ }
866
+ return result;
867
+ }
868
+
869
+ /** Operation 6 plans playback controls from opaque key equality and native
870
+ * ownership facts (foreign/owned/idle). Native retains exact owner tokens,
871
+ * stops only the named token, and applies OS calls in command order. Result:
872
+ * action (255 = no-op), retirement, re-key, reserved, scalar f64.
873
+ */
874
+ function mediaTransportPolicy(request: Uint8Array): Uint8Array {
875
+ if (request.length < 15 || request[1]! > 1 || request[2]! > 1 || request[3]! > 2 || request.length !== 15 + request[5]! + request[6]!)
876
+ throw new Error("invalid media transport request");
877
+ const result = new Uint8Array(12); result[0] = 255;
878
+ const video = request[1] === 1, verb = request[4]!;
879
+ let matches = request[2] === 1 && request[5] === request[6];
880
+ if (matches) for (let i = 0; i < request[5]!; i++) if (request[15 + i] !== request[15 + request[5]! + i]) matches = false;
881
+ if (!matches) return result;
882
+ // Stop cancels this stream's staged results even after a foreign replacement.
883
+ // Volume may update a remembered preference while the channel is idle.
884
+ if (video && verb !== 2 && request[3] !== 1 && !(verb === 4 && request[3] === 2)) return result;
885
+ if (verb > (video ? 7 : 4)) throw new Error("unknown media transport verb");
886
+ result[0] = verb; result[1] = verb === 2 ? 1 : 0; result[2] = video && verb === 7 ? 1 : 0;
887
+ for (let i = 0; i < 8; i++) result[4 + i] = request[7 + i]!;
888
+ const value = new DataView(request.buffer, request.byteOffset, request.byteLength).getFloat64(7, true);
889
+ const out = new DataView(result.buffer);
890
+ if (verb === 3) {
891
+ const seek = value >= 0 && value <= 9007199254740992 ? Math.trunc(value) : video && value > 9007199254740992 && Number.isFinite(value) ? 9007199254740991 : 0;
892
+ out.setFloat64(4, seek === 0 ? 0 : seek, true);
893
+ }
894
+ else if (video && (verb === 5 || verb === 6)) out.setFloat64(4, value !== 0 ? 1 : 0, true);
895
+ return result;
896
+ }
897
+
898
+ /** Playback load preparation (8): family, route, flags, four reserved bytes,
899
+ * f64 size/surface, u32 path length, u32 URL length, then at most 1024 URL bytes.
900
+ * Audio intentionally truncates sizes and admits 2^53. Video preserves the
901
+ * native URI grammar, including opaque paths and permissive authorities.
902
+ * Results own admission, route, flags and exact u64 surface/size words.
903
+ */
904
+ function playbackLoadPolicy(request: Uint8Array): Uint8Array {
905
+ if (request.length < 24 || request[1]! > 1) throw new Error("invalid playback load request");
906
+ for (let i = 4; i < 8; i++) if (request[i] !== 0) throw new Error("invalid playback load reserved byte");
907
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
908
+ const pathLength = wire.getUint32(16, true), urlLength = wire.getUint32(20, true);
909
+ if (request.length !== 24 + Math.min(urlLength, 1024)) throw new Error("invalid playback URL length");
910
+ const result = new Uint8Array(24), out = new DataView(result.buffer);
911
+ result[1] = request[2]!; result[2] = request[3]! & 7;
912
+ const value = wire.getFloat64(8, true);
913
+ if (request[1] === 0) {
914
+ result[0] = 1;
915
+ if (value >= 1 && value <= 9007199254740992) {
916
+ const size = Math.trunc(value);
917
+ out.setUint32(16, size % 4294967296, true); out.setUint32(20, Math.floor(size / 4294967296), true);
918
+ }
919
+ } else {
920
+ if (value >= 1 && value < 9007199254740992 && Math.floor(value) === value) {
921
+ out.setUint32(8, value % 4294967296, true); out.setUint32(12, Math.floor(value / 4294967296), true);
922
+ if ((pathLength !== 0 || urlLength !== 0) && pathLength <= 1024 && urlLength <= 1024 &&
923
+ (urlLength === 0 || playbackHttpUri(request.subarray(24)))) result[0] = 1;
924
+ }
925
+ }
926
+ return result;
927
+ }
928
+
929
+ // Match std.Uri.parse's HTTP(S) acceptance over bytes, without URL canonicalization.
930
+ function playbackHttpUri(url: Uint8Array): boolean {
931
+ let colon = -1;
932
+ for (let i = 0; i < url.length; i++) if (url[i] === 58) { colon = i; break; }
933
+ if (colon !== 4 && colon !== 5) return false;
934
+ const scheme = [104, 116, 116, 112, 115];
935
+ for (let i = 0; i < colon; i++) {
936
+ const byte = url[i]!;
937
+ if ((byte >= 65 && byte <= 90 ? byte + 32 : byte) !== scheme[i]) return false;
938
+ }
939
+ const start = colon + 1;
940
+ if (start + 1 >= url.length || url[start] !== 47 || url[start + 1] !== 47) return true;
941
+ const authorityStart = start + 2;
942
+ let end = authorityStart;
943
+ while (end < url.length && url[end] !== 47 && url[end] !== 63 && url[end] !== 35) end++;
944
+ if (end === authorityStart) return authorityStart < url.length && url[authorityStart] === 47;
945
+ let host = authorityStart;
946
+ for (let i = authorityStart; i < end; i++) if (url[i] === 64) { host = i + 1; break; }
947
+ if (host === end) return true;
948
+ if (url[host] === 93) return false;
949
+ let hostEnd = end, port = -1;
950
+ if (url[host] === 91) {
951
+ let bracket = -1;
952
+ for (let i = authorityStart; i < end; i++) if (url[i] === 93) bracket = i;
953
+ if (bracket < 0) return false;
954
+ hostEnd = bracket + 1;
955
+ for (let i = authorityStart; i < end; i++) if (url[i] === 58) port = i;
956
+ if (port < hostEnd) port = -1;
957
+ } else {
958
+ for (let i = authorityStart; i < end; i++) if (url[i] === 58) port = i;
959
+ if (port < host) port = -1;
960
+ }
961
+ if (port >= 0) {
962
+ hostEnd = Math.min(hostEnd, port);
963
+ let i = port + 1, negative = false, value = 0;
964
+ if (i < end && (url[i] === 43 || url[i] === 45)) { negative = url[i] === 45; i++; }
965
+ if (i >= end || url[i] === 95 || url[end - 1] === 95) return false;
966
+ for (; i < end; i++) {
967
+ const byte = url[i]!;
968
+ if (byte === 95) continue;
969
+ if (byte < 48 || byte > 57) return false;
970
+ value = value * 10 + byte - 48;
971
+ if (value > 65535 || negative && value !== 0) return false;
972
+ }
973
+ }
974
+ return host < hostEnd;
975
+ }
976
+
977
+ /** PTY operation 9 plans spawn, lookup, resize, named binding and event routing
978
+ * (actions 0..4). Header: action/count/blocked/kind/tag/key length/reserved,
979
+ * opaque event u64, f64 cols/rows, then key and [used,bound,tag,key length,key]
980
+ * slots. Ended bound identities remain reserved. Native owns key storage,
981
+ * staged refusal lifetimes and the OS transport; all result bytes are owned.
982
+ */
983
+ function ptyCoordinationPolicy(request: Uint8Array): Uint8Array {
984
+ if (request.length < 32 || request[1]! > 4 || request[2] !== 4 || request[3]! > 1 || request[7] !== 0 ||
985
+ (request[1] === 4 && request[4]! > 1)) throw new Error("invalid PTY coordination request");
986
+ const action = request[1]!, length = request[6]!;
987
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
988
+ const result = new Uint8Array(16), out = new DataView(result.buffer); result[0] = 255; result[1] = request[5]!;
989
+ const cols = wire.getFloat64(16, true), rows = wire.getFloat64(24, true);
990
+ out.setUint16(4, cols >= 1 && cols <= 65535 && Math.floor(cols) === cols ? cols : 0, true);
991
+ out.setUint16(6, rows >= 1 && rows <= 65535 && Math.floor(rows) === rows ? rows : 0, true);
992
+ let at = 32 + length, live = -1, bound = -1, free = -1, binding = -1;
993
+ if (at > request.length) throw new Error("truncated PTY key");
994
+ const positions: number[] = [];
995
+ for (let slot = 0; slot < 4; slot++) {
996
+ if (at + 4 > request.length || request[at]! > 1 || request[at + 1]! > 1) throw new Error("invalid PTY slot");
997
+ const size = request[at + 3]!; positions.push(at);
998
+ if (at + 4 + size > request.length) throw new Error("truncated PTY slot key");
999
+ let equal = size === length;
1000
+ for (let i = 0; i < size; i++) if (request[at + 4 + i] !== request[32 + i]) equal = false;
1001
+ const used = request[at] === 1, retained = request[at + 1] === 1;
1002
+ if (equal && length > 0 && used && live < 0) live = slot;
1003
+ if (equal && !used && retained && bound < 0) bound = slot;
1004
+ if (!used && !retained && free < 0) free = slot;
1005
+ if (equal && length > 0 && (used || retained) && binding < 0) binding = slot;
1006
+ at += 4 + size;
1007
+ }
1008
+ if (at !== request.length) throw new Error("trailing PTY coordination bytes");
1009
+ let selected = -1;
1010
+ if (action === 0) {
1011
+ if (!(length > 0 && (live >= 0 || request[3] === 1))) selected = bound >= 0 ? bound : free;
1012
+ } else if (action === 1) selected = live;
1013
+ else if (action === 2) { if (out.getUint16(4, true) !== 0 && out.getUint16(6, true) !== 0) selected = live; }
1014
+ else if (action === 3) { selected = binding; if (selected >= 0) result[3] = 1; }
1015
+ else {
1016
+ const slot = wire.getUint32(8, true);
1017
+ if (wire.getUint32(12, true) !== 0x54535054 || slot >= 4 || request[positions[slot]!] !== 1)
1018
+ throw new Error("PTY event has no tracked owner");
1019
+ selected = slot; result[2] = request[4] === 1 ? 1 : 0;
1020
+ }
1021
+ if (selected >= 0) {
1022
+ result[0] = selected;
1023
+ if (action !== 0) result[1] = request[positions[selected]! + 2]!;
1024
+ out.setUint32(8, selected, true); out.setUint32(12, 0x54535054, true);
1025
+ }
1026
+ return result;
1027
+ }
1028
+
1029
+ /** Playback events (10) retain audio's active-entry route and video's original
1030
+ * low-byte route even across replacement. Terminal events do not retire either.
1031
+ */
1032
+ function playbackEventPolicy(request: Uint8Array): Uint8Array {
1033
+ if (request.length !== 12 || request[1]! > 1 || request[2]! > 1) throw new Error("invalid playback event request");
1034
+ if (request[1] === 0 && request[2] === 0) throw new Error("audio event has no tracked owner");
1035
+ const result = new Uint8Array(1); result[0] = request[1] === 1 ? request[4]! : request[3]!;
1036
+ return result;
1037
+ }
1038
+
1039
+ /** Operation 2 of the window ABI plans a complete shell in stable declaration
1040
+ * passes. Labels remain opaque bytes; f32 rounding happens at each native
1041
+ * arithmetic step. A missing/cyclic parent returns the valid prefix, so the
1042
+ * host observes the same ordered OS calls and rollback boundary as before.
1043
+ * Header: opcode, u16 count, four f32 bounds. Each declaration carries kind,
1044
+ * edge (255 = absent), axis, fill, an eight-bit optional-geometry mask, eight
1045
+ * f32 values, u16-sized label and parent (65535 = absent). Result: refusal,
1046
+ * u16 count, then u16 declaration index + local/absolute/platform rectangles.
1047
+ */
1048
+ interface NscShellRect { x: number; y: number; width: number; height: number }
1049
+ interface NscShellView {
1050
+ kind: number; edge: number; axis: number; fill: boolean; mask: number;
1051
+ values: number[]; label: Uint8Array; parent: Uint8Array | null;
1052
+ }
1053
+ interface NscShellResolved {
1054
+ index: number; view: NscShellView; frame: NscShellRect; absolute: NscShellRect;
1055
+ }
1056
+
1057
+ function nscvShellLayout(request: Uint8Array): Uint8Array {
1058
+ if (request.length < 19) throw new Error("truncated shell layout request");
1059
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
1060
+ const count = wire.getUint16(1, true);
1061
+ if (count > 128) throw new Error("invalid shell layout count");
1062
+ let at = 3;
1063
+ const readRect = (): NscShellRect => {
1064
+ const value = { x: wire.getFloat32(at, true), y: wire.getFloat32(at + 4, true),
1065
+ width: wire.getFloat32(at + 8, true), height: wire.getFloat32(at + 12, true) };
1066
+ at += 16; return value;
1067
+ };
1068
+ const readLabel = (nullable: boolean): Uint8Array | null => {
1069
+ if (at + 2 > request.length) throw new Error("truncated shell label");
1070
+ const length = wire.getUint16(at, true); at += 2;
1071
+ if (nullable && length === 65535) return null;
1072
+ if (length > request.length - at) throw new Error("truncated shell label");
1073
+ const value = request.subarray(at, at + length); at += length; return value;
1074
+ };
1075
+ let remaining = readRect();
1076
+ const views: NscShellView[] = [];
1077
+ for (let index = 0; index < count; index++) {
1078
+ if (at + 37 > request.length) throw new Error("truncated shell declaration");
1079
+ const kind = request[at++]!, edge = request[at++]!, axis = request[at++]!, fill = request[at++]!, mask = request[at++]!;
1080
+ if (kind > 18 || edge !== 255 && edge > 3 || axis > 1 || fill > 1) throw new Error("invalid shell declaration");
1081
+ const values: number[] = [];
1082
+ for (let field = 0; field < 8; field++) { values.push(wire.getFloat32(at, true)); at += 4; }
1083
+ const label = readLabel(false)!;
1084
+ views.push({ kind, edge, axis, fill: fill === 1, mask, values, label, parent: readLabel(true) });
1085
+ }
1086
+ if (at !== request.length) throw new Error("trailing shell layout bytes");
1087
+ let fill = remaining;
1088
+ for (const view of views) if (view.parent === null && !view.fill && view.edge !== 255) {
1089
+ fill = nscvShellConsume(fill, view.edge, nscvShellDock(fill, view));
1090
+ }
1091
+ const resolved: NscShellResolved[] = [];
1092
+ const created: boolean[] = [];
1093
+ const parents: string[] = [];
1094
+ const first = new Map<string, number>();
1095
+ const cursorX: number[] = [], cursorY: number[] = [];
1096
+ // Hex keys preserve every opaque byte, including NUL and invalid UTF-8.
1097
+ // Resolve each parent through the first recorded declaration, so duplicates
1098
+ // share cursors exactly as the reference does without repeated label scans.
1099
+ const keys: string[] = [];
1100
+ for (let i = 0; i < count; i++) {
1101
+ created.push(false); cursorX.push(8); cursorY.push(8);
1102
+ keys.push(nscvShellKey(views[i]!.label));
1103
+ parents.push(views[i]!.parent === null ? "" : nscvShellKey(views[i]!.parent!));
1104
+ }
1105
+ while (resolved.length < count) {
1106
+ let progressed = false;
1107
+ for (let index = 0; index < count; index++) {
1108
+ if (created[index]) continue;
1109
+ const view = views[index]!;
1110
+ const parentIndex = view.parent === null ? -1 : first.get(parents[index]!) ?? -1;
1111
+ if (view.parent !== null && parentIndex === -1) continue;
1112
+ let frame: NscShellRect;
1113
+ if (parentIndex >= 0) {
1114
+ const parent = resolved[parentIndex]!;
1115
+ const split = parent.view.kind === 5, row = parent.view.axis === 0;
1116
+ const x = nscvShellValue(view, 0, row ? cursorX[parentIndex]! : split ? 0 : 8);
1117
+ let y: number, width: number, height: number;
1118
+ if (split) {
1119
+ y = nscvShellValue(view, 1, row ? 0 : cursorY[parentIndex]!);
1120
+ const availableWidth = nscvShellMax(Math.fround(parent.frame.width - x), 0);
1121
+ const availableHeight = nscvShellMax(Math.fround(parent.frame.height - y), 0);
1122
+ width = nscvShellWidth(view, nscvShellValue(view, 2, row ? view.fill ? availableWidth : nscvShellDefaultWidth(view.kind) : availableWidth));
1123
+ height = nscvShellHeight(view, nscvShellValue(view, 3, row ? availableHeight : view.fill ? availableHeight : nscvShellDefaultHeight(view.kind, parent.frame.height)));
1124
+ if (row) cursorX[parentIndex] = nscvShellMax(cursorX[parentIndex]!, Math.fround(x + width));
1125
+ else cursorY[parentIndex] = nscvShellMax(cursorY[parentIndex]!, Math.fround(y + height));
1126
+ } else {
1127
+ width = nscvShellWidth(view, nscvShellValue(view, 2, nscvShellDefaultWidth(view.kind)));
1128
+ height = nscvShellHeight(view, nscvShellValue(view, 3, nscvShellDefaultHeight(view.kind, parent.frame.height)));
1129
+ y = nscvShellValue(view, 1, row ? parent.frame.height <= height ? 0 : Math.fround(Math.fround(parent.frame.height - height) / 2) : cursorY[parentIndex]!);
1130
+ if (row && (view.mask & 1) === 0) cursorX[parentIndex] = Math.fround(Math.fround(x + width) + 8);
1131
+ if (!row && (view.mask & 2) === 0) cursorY[parentIndex] = Math.fround(Math.fround(y + height) + 8);
1132
+ }
1133
+ frame = { x, y, width, height };
1134
+ } else if (view.fill) {
1135
+ frame = { x: nscvShellValue(view, 0, fill.x), y: nscvShellValue(view, 1, fill.y),
1136
+ width: nscvShellWidth(view, nscvShellValue(view, 2, fill.width)), height: nscvShellHeight(view, nscvShellValue(view, 3, fill.height)) };
1137
+ } else if (view.edge !== 255) {
1138
+ frame = nscvShellDock(remaining, view); remaining = nscvShellConsume(remaining, view.edge, frame);
1139
+ } else {
1140
+ frame = { x: nscvShellValue(view, 0, 0), y: nscvShellValue(view, 1, 0),
1141
+ width: nscvShellWidth(view, nscvShellValue(view, 2, nscvShellDefaultWidth(view.kind))),
1142
+ height: nscvShellHeight(view, nscvShellValue(view, 3, nscvShellDefaultHeight(view.kind, 0))) };
1143
+ }
1144
+ const absolute = parentIndex < 0 ? frame : { ...frame,
1145
+ x: Math.fround(frame.x + resolved[parentIndex]!.absolute.x), y: Math.fround(frame.y + resolved[parentIndex]!.absolute.y) };
1146
+ const next = resolved.length;
1147
+ resolved.push({ index, view, frame, absolute });
1148
+ cursorX[next] = view.kind === 5 ? 0 : 8; cursorY[next] = view.kind === 5 ? 0 : 8;
1149
+ if (!first.has(keys[index]!)) first.set(keys[index]!, next);
1150
+ created[index] = true; progressed = true;
1151
+ }
1152
+ if (!progressed) break;
1153
+ }
1154
+ const output = new Uint8Array(3 + resolved.length * 50);
1155
+ const out = new DataView(output.buffer);
1156
+ output[0] = resolved.length === count ? 0 : 1; out.setUint16(1, resolved.length, true);
1157
+ at = 3;
1158
+ const writeRect = (frame: NscShellRect): void => {
1159
+ out.setFloat32(at, frame.x, true); out.setFloat32(at + 4, frame.y, true);
1160
+ out.setFloat32(at + 8, frame.width, true); out.setFloat32(at + 12, frame.height, true); at += 16;
1161
+ };
1162
+ for (const item of resolved) {
1163
+ out.setUint16(at, item.index, true); at += 2;
1164
+ writeRect(item.frame); writeRect(item.absolute);
1165
+ const initial = resolved[first.get(keys[item.index]!)!]!;
1166
+ const main = nscvShellEqual(item.view.label, new Uint8Array([109, 97, 105, 110]));
1167
+ writeRect(item.view.kind === 0 && item.view.parent !== null && main ? initial.absolute : item.frame);
1168
+ }
1169
+ return output;
1170
+ }
1171
+
1172
+ function nscvShellKey(label: Uint8Array): string {
1173
+ const chunks: string[] = [];
1174
+ for (const byte of label) chunks.push(byte.toString(16).padStart(2, "0"));
1175
+ return chunks.join("");
1176
+ }
1177
+ function nscvShellEqual(a: Uint8Array, b: Uint8Array): boolean {
1178
+ if (a.length !== b.length) return false;
1179
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1180
+ return true;
1181
+ }
1182
+ // Zig's min/max ignore one NaN operand. All arithmetic operands already carry
1183
+ // native f32 values, and the explicit rounds preserve native evaluation order.
1184
+ function nscvShellMax(a: number, b: number): number { return Number.isNaN(a) ? b : Number.isNaN(b) ? a : Math.max(a, b); }
1185
+ function nscvShellMin(a: number, b: number): number { return Number.isNaN(a) ? b : Number.isNaN(b) ? a : Math.min(a, b); }
1186
+ function nscvShellValue(view: NscShellView, field: number, fallback: number): number {
1187
+ return (view.mask & (1 << field)) === 0 ? fallback : view.values[field]!;
1188
+ }
1189
+ function nscvShellWidth(view: NscShellView, value: number): number {
1190
+ let width = value;
1191
+ if ((view.mask & 16) !== 0) width = nscvShellMax(width, view.values[4]!);
1192
+ if ((view.mask & 64) !== 0) width = nscvShellMin(width, view.values[6]!);
1193
+ return width;
1194
+ }
1195
+ function nscvShellHeight(view: NscShellView, value: number): number {
1196
+ let height = value;
1197
+ if ((view.mask & 32) !== 0) height = nscvShellMax(height, view.values[5]!);
1198
+ if ((view.mask & 128) !== 0) height = nscvShellMin(height, view.values[7]!);
1199
+ return height;
1200
+ }
1201
+ function nscvShellDock(remaining: NscShellRect, view: NscShellView): NscShellRect {
1202
+ const vertical = view.edge === 0 || view.edge === 2;
1203
+ const width = nscvShellWidth(view, nscvShellValue(view, 2, vertical ? remaining.width : nscvShellDefaultWidth(view.kind)));
1204
+ const height = nscvShellHeight(view, nscvShellValue(view, 3, vertical ? nscvShellDefaultHeight(view.kind, 0) : remaining.height));
1205
+ return { x: view.edge === 1 ? Math.fround(remaining.x + nscvShellMax(Math.fround(remaining.width - width), 0)) : remaining.x,
1206
+ y: view.edge === 2 ? Math.fround(remaining.y + nscvShellMax(Math.fround(remaining.height - height), 0)) : remaining.y, width, height };
1207
+ }
1208
+ function nscvShellConsume(remaining: NscShellRect, edge: number, frame: NscShellRect): NscShellRect {
1209
+ return { x: edge === 3 ? Math.fround(remaining.x + frame.width) : remaining.x,
1210
+ y: edge === 0 ? Math.fround(remaining.y + frame.height) : remaining.y,
1211
+ width: edge === 1 || edge === 3 ? nscvShellMax(Math.fround(remaining.width - frame.width), 0) : remaining.width,
1212
+ height: edge === 0 || edge === 2 ? nscvShellMax(Math.fround(remaining.height - frame.height), 0) : remaining.height };
1213
+ }
1214
+ function nscvShellDefaultWidth(kind: number): number {
1215
+ switch (kind) {
1216
+ case 7: case 10: case 11: return 96;
1217
+ case 8: return 32;
1218
+ case 9: case 13: case 14: return 220;
1219
+ case 12: return 168;
1220
+ case 15: return 160;
1221
+ case 16: return 12;
1222
+ case 18: return 24;
1223
+ case 3: return 240;
1224
+ default: return 0;
1225
+ }
1226
+ }
1227
+ function nscvShellDefaultHeight(kind: number, parent: number): number {
1228
+ switch (kind) {
1229
+ case 7: case 8: case 9: case 10: case 11: case 12: return 32;
1230
+ case 15: case 18: return 24;
1231
+ case 16: return nscvShellMax(parent, 1);
1232
+ case 13: case 14: case 4: return 28;
1233
+ case 1: return 48;
1234
+ case 2: return 36;
1235
+ default: return 0;
1236
+ }
1237
+ }
1238
+
1239
+ /** Floating-surface placement over measured native geometry. The existing
1240
+ * window ABI's operation 3 carries modal, anchored, and caption-clearance
1241
+ * requests. Each arithmetic intermediate preserves native f32 ordering.
1242
+ * Consumers copy the result; the enclosing view/cycle owns arena collection.
1243
+ */
1244
+ interface NscSurfaceRect { readonly x: number; readonly y: number; readonly width: number; readonly height: number; }
1245
+ function nscvSurfaceMax(a: number, b: number): number { return Number.isNaN(a) ? b : Number.isNaN(b) ? a : Math.max(a, b); }
1246
+ function nscvSurfaceMin(a: number, b: number): number { return Number.isNaN(a) ? b : Number.isNaN(b) ? a : Math.min(a, b); }
1247
+ function nscvSurfaceClamp(v: number, lo: number, hi: number, keepsLowerZero: boolean): number {
1248
+ // The native numeric capability preserves the target's zero endpoint sign.
1249
+ const result = nscvSurfaceMax(lo, nscvSurfaceMin(v, hi));
1250
+ return keepsLowerZero && result === lo ? lo : result;
1251
+ }
1252
+ function nscvSurfaceBound(v: number, lo: number, hi: number): number { return nscvSurfaceMax(lo, hi > 0 ? nscvSurfaceMin(v, hi) : v); }
1253
+ function nscvSurfaceNormalize(r: NscSurfaceRect): NscSurfaceRect {
1254
+ return { x: r.width < 0 ? Math.fround(r.x + r.width) : r.x, y: r.height < 0 ? Math.fround(r.y + r.height) : r.y,
1255
+ width: r.width < 0 ? -r.width : r.width, height: r.height < 0 ? -r.height : r.height };
1256
+ }
1257
+ function nscvSurfaceRight(r: NscSurfaceRect): number { return Math.fround(r.x + r.width); }
1258
+ function nscvSurfaceBottom(r: NscSurfaceRect): number { return Math.fround(r.y + r.height); }
1259
+ function nscvSurfaceLayout(request: Uint8Array): Uint8Array {
1260
+ if (request.length < 4 || request[0] !== 3) throw new Error("invalid surface layout request");
1261
+ const operation = request[1]!, a = request[2]!, b = request[3]!;
1262
+ const length = operation === 0 ? 56 : operation === 1 ? 80 : operation === 2 ? 36 : 0;
1263
+ if (request.length !== length) throw new Error("invalid surface layout length");
1264
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
1265
+ const v: number[] = [];
1266
+ for (let at = 4; at < request.length; at += 4) v.push(wire.getFloat32(at, true));
1267
+ const bounds = nscvSurfaceNormalize({ x: v[0]!, y: v[1]!, width: v[2]!, height: v[3]! });
1268
+ let frame: NscSurfaceRect = bounds, present = true;
1269
+ if (operation === 0) {
1270
+ // Kind 0/1/2 is dialog/drawer/sheet; 255 preserves unsupported-kind null.
1271
+ if (a !== 0 && a !== 1 && a !== 2 && a !== 255 || b > 1) throw new Error("invalid modal layout flags");
1272
+ if (a === 255 || bounds.width <= 0 || bounds.height <= 0) present = false;
1273
+ else {
1274
+ let width = v[4]!, height = v[5]!;
1275
+ if (b === 1) {
1276
+ width = nscvSurfaceBound(width > 0 ? width : v[6]!, v[8]!, v[10]!);
1277
+ height = nscvSurfaceBound(height > 0 ? height : v[7]!, v[9]!, v[11]!);
1278
+ }
1279
+ width = Number.isFinite(width) && width > 0 ? width : a === 0 ? 420 : a === 1 ? 360 : 320;
1280
+ height = Number.isFinite(height) && height > 0 ? height : a === 0 ? 220 : a === 1 ? 280 : 420;
1281
+ if (a === 0) {
1282
+ const margin = nscvSurfaceMin(nscvSurfaceMax(0, Number.isFinite(v[12]!) ? v[12]! : 0), Math.fround(nscvSurfaceMin(bounds.width, bounds.height) * 0.5));
1283
+ width = nscvSurfaceMin(width, nscvSurfaceMax(1, Math.fround(bounds.width - Math.fround(margin * 2))));
1284
+ height = nscvSurfaceMin(height, nscvSurfaceMax(1, Math.fround(bounds.height - Math.fround(margin * 2))));
1285
+ frame = { x: Math.fround(bounds.x + Math.fround(Math.fround(bounds.width - width) * 0.5)), y: Math.fround(bounds.y + Math.fround(Math.fround(bounds.height - height) * 0.5)), width, height };
1286
+ } else if (a === 1) {
1287
+ height = nscvSurfaceMin(nscvSurfaceMax(0, height), nscvSurfaceMax(1, bounds.height));
1288
+ frame = { x: bounds.x, y: Math.fround(nscvSurfaceBottom(bounds) - height), width: nscvSurfaceMax(1, bounds.width), height };
1289
+ } else {
1290
+ width = nscvSurfaceMin(nscvSurfaceMax(0, width), nscvSurfaceMax(1, bounds.width));
1291
+ frame = { x: Math.fround(nscvSurfaceRight(bounds) - width), y: bounds.y, width, height: nscvSurfaceMax(1, bounds.height) };
1292
+ }
1293
+ }
1294
+ } else if (operation === 1) {
1295
+ if (a > 1 || b > 14) throw new Error("invalid anchor layout flags");
1296
+ const point = (b & 4) !== 0, alignment = b & 3, keepsLowerZero = (b & 8) !== 0;
1297
+ if (alignment > 2) throw new Error("invalid anchor alignment");
1298
+ const anchor = point ? { x: nscvSurfaceClamp(v[17]!, bounds.x, nscvSurfaceRight(bounds), keepsLowerZero), y: nscvSurfaceClamp(v[18]!, bounds.y, nscvSurfaceBottom(bounds), keepsLowerZero), width: 0, height: 0 }
1299
+ : nscvSurfaceNormalize({ x: v[4]!, y: v[5]!, width: v[6]!, height: v[7]! });
1300
+ let width = v[8]! > 0 ? v[8]! : v[10]!;
1301
+ if (alignment === 2) width = nscvSurfaceMax(width, anchor.width);
1302
+ width = nscvSurfaceMin(nscvSurfaceBound(width, v[12]!, v[14]!), bounds.width);
1303
+ let height = nscvSurfaceBound(v[9]! > 0 ? v[9]! : v[11]!, v[13]!, v[15]!);
1304
+ const offset = nscvSurfaceMax(0, v[16]!);
1305
+ const belowSpace = Math.fround(Math.fround(nscvSurfaceBottom(bounds) - nscvSurfaceBottom(anchor)) - offset);
1306
+ const aboveSpace = Math.fround(Math.fround(anchor.y - bounds.y) - offset);
1307
+ const preferred = a === 0 ? belowSpace : aboveSpace, other = a === 0 ? aboveSpace : belowSpace;
1308
+ const below = (a === 0) !== (height > preferred && other > preferred);
1309
+ height = nscvSurfaceMin(height, nscvSurfaceMax(0, below ? belowSpace : aboveSpace));
1310
+ const y = below ? Math.fround(nscvSurfaceBottom(anchor) + offset) : Math.fround(Math.fround(anchor.y - offset) - height);
1311
+ const x = alignment === 1 ? Math.fround(nscvSurfaceRight(anchor) - width) : anchor.x;
1312
+ frame = { x: nscvSurfaceClamp(x, bounds.x, nscvSurfaceMax(bounds.x, Math.fround(nscvSurfaceRight(bounds) - width)), keepsLowerZero),
1313
+ y: nscvSurfaceClamp(y, bounds.y, nscvSurfaceMax(bounds.y, Math.fround(nscvSurfaceBottom(bounds) - height)), keepsLowerZero), width, height };
1314
+ } else {
1315
+ if (a > 1 || b > 1) throw new Error("invalid caption clearance flags");
1316
+ // Content is already normalized by the layout. Preserve it verbatim
1317
+ // when reservation is absent or the native control cluster misses it.
1318
+ frame = { x: v[0]!, y: v[1]!, width: v[2]!, height: v[3]! };
1319
+ const controls = nscvSurfaceNormalize({ x: v[4]!, y: v[5]!, width: v[6]!, height: v[7]! });
1320
+ const x0 = nscvSurfaceMax(frame.x, controls.x), y0 = nscvSurfaceMax(frame.y, controls.y);
1321
+ const x1 = nscvSurfaceMin(nscvSurfaceRight(frame), nscvSurfaceRight(controls)), y1 = nscvSurfaceMin(nscvSurfaceBottom(frame), nscvSurfaceBottom(controls));
1322
+ const misses = x1 <= x0 || y1 <= y0;
1323
+ const emptyIntersection = Math.fround(x1 - x0) <= 0 || Math.fround(y1 - y0) <= 0;
1324
+ if (a === 1 && b === 1 && !(controls.width <= 0 || controls.height <= 0) && !misses && !emptyIntersection) {
1325
+ if (Math.fround(controls.x + Math.fround(controls.width / 2)) >= Math.fround(frame.x + Math.fround(frame.width / 2))) {
1326
+ frame = { x: frame.x, y: frame.y, width: nscvSurfaceMax(0, Math.fround(nscvSurfaceMin(nscvSurfaceRight(frame), controls.x) - frame.x)), height: frame.height };
1327
+ } else {
1328
+ const start = nscvSurfaceMin(nscvSurfaceRight(frame), nscvSurfaceMax(frame.x, nscvSurfaceRight(controls)));
1329
+ frame = { x: start, y: frame.y, width: nscvSurfaceMax(0, Math.fround(nscvSurfaceRight(frame) - start)), height: frame.height };
1330
+ }
1331
+ }
1332
+ }
1333
+ const result = new Uint8Array(17);result[0] = present ? 1 : 0;
1334
+ const output = new DataView(result.buffer);
1335
+ output.setFloat32(1, frame.x, true);output.setFloat32(5, frame.y, true);output.setFloat32(9, frame.width, true);output.setFloat32(13, frame.height, true);
1336
+ return result;
1337
+ }
1338
+
1339
+ /** Grid geometry over native-owned children and measured row extents.
1340
+ * Operation 0 plans the grid and virtual row window; operation 1 places one
1341
+ * flow child. Integer lanes preserve declared usize columns even above the
1342
+ * exact JS number range; native conversion facts preserve u64-to-f32 rounding.
1343
+ * Results are owned bytes, collected only by the enclosing view/cycle.
1344
+ */
1345
+ function nscvGridLayout(request: Uint8Array): Uint8Array {
1346
+ if (request.length < 4 || request[0] !== 4 || request[3] !== 0) throw new Error("invalid grid layout request");
1347
+ const op = request[1]!, flags = request[2]!;
1348
+ if ((op !== 0 && op !== 1) || request.length !== 76 || flags > (op === 0 ? 7 : 3))
1349
+ throw new Error("invalid grid layout operation, length or flags");
1350
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
1351
+ const integer = (at: number): number => wire.getUint32(at, true) + wire.getUint32(at + 4, true) * 4294967296;
1352
+ const float = (at: number): number => wire.getFloat32(at, true);
1353
+ const virtual = (flags & 1) !== 0;
1354
+ const f = Math.fround;
1355
+ if (op === 0) {
1356
+ const count = integer(4), declared = integer(12), overscan = integer(20);
1357
+ if (!Number.isSafeInteger(count)) throw new Error("invalid grid child count");
1358
+ const columns = count === 0 ? 0 : declared > 0 ? declared : count;
1359
+ const rows = columns === 0 ? 0 : 1 + Math.floor((count - 1) / columns);
1360
+ const columnsF = count === 0 ? 0 : declared > 0 ? float(64) : float(60);
1361
+ const gap = nscvSurfaceMax(0, float(44));
1362
+ const width = columns > 0 ? f(nscvSurfaceMax(0, f(float(36) - f(gap * (declared > 0 ? float(72) : float(68))))) / columnsF) : 0;
1363
+ let height = rows > 0 ? f(nscvSurfaceMax(0, f(float(40) - f(gap * f(rows - 1)))) / f(rows)) : 0;
1364
+ let start = 0, end = count, offset = 0, extent = 0;
1365
+ if (virtual) {
1366
+ extent = float(48) > 0 ? float(48) : float(52);
1367
+ const range = nscvFlowRange(nscvFlowSmall(rows), f(rows), extent, gap, float(40), float(56), nscvFlowInteger(wire, 20), flags >> 1);
1368
+ start = range.start.low + range.start.high * 4294967296;
1369
+ end = range.end.low + range.end.high * 4294967296;
1370
+ offset = range.offset; extent = range.extent; height = range.extent;
1371
+ }
1372
+ const result = new Uint8Array(52), out = new DataView(result.buffer);
1373
+ // Preserve all integer bits of the chosen declared column count.
1374
+ if (count > 0) result.set(request.subarray(declared > 0 ? 12 : 4, declared > 0 ? 20 : 12), 0);
1375
+ for (const [at, value] of [[8, rows], [16, start], [24, end]]) {
1376
+ out.setUint32(at!, value! % 4294967296, true); out.setUint32(at! + 4, Math.floor(value! / 4294967296), true);
1377
+ }
1378
+ for (const [at, value] of [[32, width], [36, height], [40, gap], [44, offset], [48, extent]]) out.setFloat32(at!, value!, true);
1379
+ return result;
1380
+ }
1381
+ const index = integer(4), columns = integer(12);
1382
+ if (!Number.isSafeInteger(index) || columns === 0) throw new Error("invalid grid cell index or columns");
1383
+ const row = Math.floor(index / columns), column = index - row * columns;
1384
+ const x = f(float(20) + f(f(column) * f(float(28) + float(36))));
1385
+ let y = f(float(24) + f(f(row) * f(float(32) + float(36))));
1386
+ if (virtual) y = f(y - float(40));
1387
+ let width = float(52) > 0 ? float(52) : float(28);
1388
+ if ((flags & 2) !== 0) width = nscvSurfaceMax(width, nscvSurfaceMax(0, f(float(28) - float(44))));
1389
+ width = nscvSurfaceBound(width, float(60), float(68));
1390
+ const height = nscvSurfaceBound(float(56) > 0 ? float(56) : float(32), float(64), float(72));
1391
+ const result = new Uint8Array(17), out = new DataView(result.buffer); result[0] = 1;
1392
+ out.setFloat32(1, f(x + float(44)), true); out.setFloat32(5, f(y + float(48)), true);
1393
+ out.setFloat32(9, width, true); out.setFloat32(13, height, true); return result;
1394
+ }
1395
+
1396
+ function nscvGridCount(value: number): number {
1397
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("invalid grid columns");
1398
+ return value;
1399
+ }
1400
+
1401
+ type NscContainerChild = {
1402
+ flags: number; grow: number; main: number; cross: number; offsetMain: number; offsetCross: number;
1403
+ minMain: number; maxMain: number; minCross: number; maxCross: number;
1404
+ measuredMain: number; measuredCross: number;
1405
+ };
1406
+
1407
+ /** Container allocation over owned native measurement facts. A cross-size
1408
+ * pass supplies the width for wrapped text before the final allocation pass.
1409
+ * The same allocation chooses row measurement widths; stacking is operation 3.
1410
+ * Every arithmetic boundary follows the native f32 evaluation order.
1411
+ */
1412
+ function nscvContainerLayout(request: Uint8Array): Uint8Array {
1413
+ if (request.length < 36 || request[0] !== 5) throw new Error("invalid container layout request");
1414
+ const op = request[1]!, axis = request[2]!, main = request[3]!, cross = request[4]!;
1415
+ if (op > 3 || axis > 1 || main > 3 || cross > 3 || request[5] !== 0 || request[6] !== 0 || request[7] !== 0)
1416
+ throw new Error("invalid container layout operation or flags");
1417
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength), count = wire.getUint32(8, true);
1418
+ if (request.length !== 36 + count * 48 || op === 3 && (count !== 1 || axis !== 0)) throw new Error("invalid container layout length");
1419
+ const f = Math.fround, max = nscvSurfaceMax, min = nscvSurfaceMin;
1420
+ const x = wire.getFloat32(12, true), y = wire.getFloat32(16, true);
1421
+ const available = wire.getFloat32(axis === 0 ? 20 : 24, true), band = wire.getFloat32(axis === 0 ? 24 : 20, true);
1422
+ const gap = max(0, wire.getFloat32(28, true));
1423
+ if (wire.getUint32(32, true) !== 0) throw new Error("invalid container layout reserved bytes");
1424
+ const children: NscContainerChild[] = [];
1425
+ for (let i = 0; i < count; i++) {
1426
+ const at = 36 + i * 48, flags = wire.getUint32(at, true);
1427
+ if (flags > 31 || op === 3 && (flags & 28) !== 0) throw new Error("invalid container child flags");
1428
+ children.push({ flags, grow: max(0, wire.getFloat32(at + 4, true)), main: wire.getFloat32(at + 8, true),
1429
+ cross: wire.getFloat32(at + 12, true), offsetMain: wire.getFloat32(at + 16, true), offsetCross: wire.getFloat32(at + 20, true),
1430
+ minMain: wire.getFloat32(at + 24, true), maxMain: wire.getFloat32(at + 28, true), minCross: wire.getFloat32(at + 32, true),
1431
+ maxCross: wire.getFloat32(at + 36, true), measuredMain: wire.getFloat32(at + 40, true), measuredCross: wire.getFloat32(at + 44, true) });
1432
+ }
1433
+ const result = new Uint8Array(12 + count * (op === 0 ? 4 : 16)), out = new DataView(result.buffer);
1434
+ out.setUint32(0, count, true);
1435
+ if (op === 3) {
1436
+ const child = children[0]!, left = f(x + child.offsetMain), top = f(y + child.offsetCross);
1437
+ let width = nscvSurfaceBound(child.main > 0 ? child.main : available, child.minMain, child.maxMain);
1438
+ const height = nscvSurfaceBound(child.cross > 0 ? child.cross : band, child.minCross, child.maxCross);
1439
+ if ((child.flags & 2) !== 0) width = nscvSurfaceBound(max(width, max(0, f(f(x + available) - left))), child.minMain, child.maxMain);
1440
+ out.setFloat32(12, left, true); out.setFloat32(16, top, true); out.setFloat32(20, width, true); out.setFloat32(24, height, true);
1441
+ return result;
1442
+ }
1443
+ if (op === 0) {
1444
+ for (let i = 0; i < count; i++) out.setFloat32(12 + i * 4, (children[i]!.flags & 1) !== 0 ? nscvContainerCross(children[i]!, axis, band, cross) : 0, true);
1445
+ return result;
1446
+ }
1447
+ let flowCount = 0, fillCount = 0, fixed = 0, growTotal = 0;
1448
+ const preferred: number[] = [];
1449
+ for (const child of children) {
1450
+ let extent = nscvSurfaceBound(child.main > 0 ? child.main : child.measuredMain, max(0, child.minMain), child.maxMain);
1451
+ if (axis === 0 && (child.flags & 8) !== 0 && child.main <= 0 && child.maxMain <= 0 && available > 0)
1452
+ extent = min(extent, max(f(available * f(0.8)), max(0, child.minMain)));
1453
+ preferred.push(extent);
1454
+ if ((child.flags & 1) === 0) continue;
1455
+ flowCount++;
1456
+ if ((child.flags & 2) !== 0 && child.grow === 0) fillCount++;
1457
+ else if (child.grow > 0) growTotal = f(growTotal + child.grow);
1458
+ else fixed = f(fixed + extent);
1459
+ }
1460
+ const totalGap = flowCount > 0 ? f(gap * f(flowCount - 1)) : 0;
1461
+ const flexible = max(0, f(f(available - fixed) - totalGap));
1462
+ const fillShare = fillCount > 0 ? f(flexible / f(fillCount)) : 0;
1463
+ let fillExtent = 0;
1464
+ const extents: number[] = [];
1465
+ for (let i = 0; i < count; i++) {
1466
+ const child = children[i]!;
1467
+ const fills = (child.flags & 2) !== 0 && child.grow === 0;
1468
+ const extent = fills ? nscvSurfaceBound(max(preferred[i]!, fillShare), max(0, child.minMain), child.maxMain) : preferred[i]!;
1469
+ extents.push(extent);
1470
+ if ((child.flags & 1) !== 0 && fills) fillExtent = f(fillExtent + extent);
1471
+ }
1472
+ const remaining = max(0, f(flexible - fillExtent));
1473
+ let assigned = f(fixed + fillExtent);
1474
+ if (growTotal > 0) {
1475
+ for (let i = 0; i < count; i++) {
1476
+ const child = children[i]!;
1477
+ if ((child.flags & 1) === 0 || child.grow <= 0) continue;
1478
+ const extent = nscvSurfaceBound(f(f(remaining * child.grow) / growTotal), max(0, child.minMain), child.maxMain);
1479
+ extents[i] = extent; assigned = f(assigned + extent);
1480
+ }
1481
+ }
1482
+ const used = f(assigned + totalGap), free = max(0, f(available - used));
1483
+ const overflow = f(used - available);
1484
+ out.setFloat32(4, used, true); out.setFloat32(8, overflow <= 0.5 ? 0 : overflow, true);
1485
+ const childGap = main === 3 && flowCount > 1 ? f(gap + f(free / f(flowCount - 1))) : gap;
1486
+ let cursor = f((axis === 0 ? x : y) + (main === 1 ? f(free * 0.5) : main === 2 ? free : 0));
1487
+ for (let i = 0; i < count; i++) {
1488
+ const child = children[i]!;
1489
+ if ((child.flags & 1) === 0) continue;
1490
+ const size = nscvContainerCross(child, axis, band, cross);
1491
+ const delta = f(band - size), shift = cross === 2 ? f(delta * 0.5) : cross === 3 ? max(0, delta) : 0;
1492
+ const origin = f(f((axis === 0 ? y : x) + child.offsetCross) + shift);
1493
+ const at = 12 + i * 16;
1494
+ out.setFloat32(at, axis === 0 ? cursor : origin, true); out.setFloat32(at + 4, axis === 0 ? origin : cursor, true);
1495
+ out.setFloat32(at + 8, axis === 0 ? extents[i]! : size, true); out.setFloat32(at + 12, axis === 0 ? size : extents[i]!, true);
1496
+ cursor = f(cursor + f(extents[i]! + childGap));
1497
+ }
1498
+ return result;
1499
+ }
1500
+
1501
+ function nscvContainerCross(child: NscContainerChild, axis: number, available: number, alignment: number): number {
1502
+ const f = Math.fround, max = nscvSurfaceMax, min = nscvSurfaceMin;
1503
+ if ((child.flags & 16) !== 0) return nscvSurfaceBound(available, child.minCross, child.maxCross);
1504
+ if (axis === 1 && (child.flags & 4) !== 0)
1505
+ return nscvSurfaceBound(max(child.cross, max(0, f(available - child.offsetCross))), child.minCross, child.maxCross);
1506
+ if (child.cross > 0) return nscvSurfaceBound(child.cross, child.minCross, child.maxCross);
1507
+ if (axis === 1 && (child.flags & 8) !== 0 && child.cross <= 0 && child.maxCross <= 0 && available > 0) {
1508
+ const fitted = min(available, child.measuredCross);
1509
+ return nscvSurfaceBound(min(fitted, max(f(available * f(0.8)), max(0, child.minCross))), child.minCross, child.maxCross);
1510
+ }
1511
+ if (alignment === 0) return nscvSurfaceBound(available, child.minCross, child.maxCross);
1512
+ return nscvSurfaceBound(axis === 0 && alignment === 2 ? child.measuredCross : min(available, child.measuredCross), child.minCross, child.maxCross);
1513
+ }
1514
+
1515
+ /** Intrinsic composition over native text/leaf measurements. Child bounds,
1516
+ * separator contributions, flow aggregation, padding and surface chrome are
1517
+ * portable policy. Native copies every result before recursive measurement;
1518
+ * collection belongs to the enclosing app cycle, never to this operation.
1519
+ */
1520
+ function nscvIntrinsicLayout(request: Uint8Array, numericFlags: number = -1, signalingFlags: number = 0, maximumWords: number = 0): Uint8Array {
1521
+ if (request.length < 96 || request[0] !== 6) throw new Error("invalid intrinsic layout request");
1522
+ const op = request[1]!, axis = request[2]!, flags = request[3]!;
1523
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength), count = wire.getUint32(4, true);
1524
+ if (op > 10 || axis > 1 || flags > 3 || wire.getUint32(92, true) !== 0 || request.length !== 96 + count * 40)
1525
+ throw new Error("invalid intrinsic layout operation, flags or length");
1526
+ const f = Math.fround;
1527
+ const max = (a: number, b: number): number => numericFlags < 0 ? nscvSurfaceMax(a, b) : nscvRenderExtreme(a, b, numericFlags, true);
1528
+ const min = (a: number, b: number): number => numericFlags < 0 ? nscvSurfaceMin(a, b) : nscvRenderExtreme(a, b, numericFlags, false);
1529
+ const v = (at: number): number => wire.getFloat32(at, true);
1530
+ const signalingAt = (at: number): boolean => {
1531
+ const word = wire.getUint32(at, true);
1532
+ return (word & 0x7f800000) === 0x7f800000 && (word & 0x007fffff) !== 0 && (word & 0x00400000) === 0;
1533
+ };
1534
+ const rightMax = (value: number, at: number): number => (signalingFlags & 16) !== 0 && signalingAt(at) ? v(at) : max(value, v(at));
1535
+ const minWidth = v(24), minHeight = v(28), left = v(32), right = v(36), top = v(40), bottom = v(44);
1536
+ const gap = rightMax(0, 48), stopped = (flags & 1) !== 0, hasTitle = (flags & 2) !== 0;
1537
+ const result = new Uint8Array(12 + count * 12), out = new DataView(result.buffer); out.setUint32(0, count, true);
1538
+ let flows = 0, width = 0, height = 0;
1539
+ for (let i = 0; i < count; i++) {
1540
+ const at = 96 + i * 40, childFlags = wire.getUint32(at, true);
1541
+ if (childFlags > 3) throw new Error("invalid intrinsic child flags");
1542
+ if ((childFlags & 1) === 0) continue;
1543
+ flows++;
1544
+ let w = nscvSurfaceBound(max(v(at + 4), max(0, v(at + 12))), v(at + 20), v(at + 28));
1545
+ let h = nscvSurfaceBound(max(v(at + 8), max(0, v(at + 16))), v(at + 24), v(at + 32));
1546
+ if (op === 1 && axis === 0 && (childFlags & 2) !== 0 && v(at + 12) <= 0) {
1547
+ const thin = min(w, h); w = max(max(0, v(at + 20)), thin); h = max(max(0, v(at + 24)), thin);
1548
+ }
1549
+ out.setFloat32(12 + i * 12, w, true); out.setFloat32(16 + i * 12, h, true);
1550
+ out.setFloat32(20 + i * 12, v(at + 12) > 0 ? v(at + 12) : w, true);
1551
+ if (op === 1) {
1552
+ width = axis === 0 ? f(width + w) : max(width, w);
1553
+ height = axis === 0 ? max(height, h) : f(height + h);
1554
+ } else { width = max(width, w); height = max(height, op === 3 ? v(at + 36) : h); }
1555
+ }
1556
+ if (op === 0) return result;
1557
+ const paddedWidth = (w: number): number => rightMax(f(f(w + left) + right), 24);
1558
+ const paddedHeight = (h: number): number => rightMax(f(f(h + top) + bottom), 28);
1559
+ if (op === 6) { width = paddedWidth(v(52)); height = paddedHeight(v(56)); }
1560
+ else if (op === 7) {
1561
+ width = paddedWidth(width); height = paddedHeight(f(f(v(64) + (height > 0 ? gap : 0)) + height));
1562
+ } else if (op >= 8) {
1563
+ const childrenWidth = width, childrenHeight = height;
1564
+ width = max(v(68), f(v(60) + f(v(76) * 2)));
1565
+ height = max(v(72), hasTitle ? f(v(64) + f(v(76) * 2)) : 0);
1566
+ if (op === 10) {
1567
+ width = max(v(68), f(f(f(f(v(60) + left) + right) + v(80)) + v(84)));
1568
+ height = max(v(72), f(f(v(64) + top) + bottom));
1569
+ if (childrenHeight > 0) {
1570
+ if (hasTitle) {
1571
+ height = max(height, f(f(f(f(v(64) + v(88)) + childrenHeight) + top) + bottom));
1572
+ width = max(width, f(f(f(f(childrenWidth + v(80)) + v(84)) + left) + right));
1573
+ } else { height = max(height, f(f(childrenHeight + top) + bottom)); width = max(width, f(f(childrenWidth + left) + right)); }
1574
+ }
1575
+ } else if (childrenHeight > 0) {
1576
+ const childHeight = f(f(childrenHeight + top) + bottom);
1577
+ height = op === 8 ? max(height, childHeight) : hasTitle ? max(childHeight, f(v(64) + f(v(76) * 2))) : childHeight;
1578
+ width = max(width, f(f(childrenWidth + left) + right));
1579
+ }
1580
+ } else if (op === 5) {
1581
+ if (stopped) { width = 0; height = 0; }
1582
+ } else if (stopped || count === 0 || (op === 1 || op === 4) && flows === 0) {
1583
+ width = op === 3 ? 0 : rightMax(0, 24); height = rightMax(0, 28);
1584
+ } else {
1585
+ if (op === 1) {
1586
+ const gaps = f(gap * f(flows - 1));
1587
+ if (axis === 0) width = f(width + gaps); else height = f(height + gaps);
1588
+ } else if (op === 4) {
1589
+ const declared = wire.getUint32(8, true) + wire.getUint32(12, true) * 4294967296;
1590
+ const columns = declared > 0 ? declared : flows, rows = 1 + Math.floor((flows - 1) / columns);
1591
+ const columnsF = declared > 0 ? v(16) : f(flows), columnsMinusF = declared > 0 ? v(20) : f(flows - 1);
1592
+ width = f(f(width * columnsF) + f(gap * columnsMinusF));
1593
+ height = f(f(height * f(rows)) + f(gap * f(rows - 1)));
1594
+ }
1595
+ width = op === 3 ? 0 : paddedWidth(width); height = paddedHeight(height);
1596
+ }
1597
+ out.setFloat32(4, width, true); out.setFloat32(8, height, true);
1598
+ if (op !== 5 && op < 8) {
1599
+ if (op !== 3 && signalingAt(24) && ((maximumWords & 2) !== 0 || (maximumWords & 1) !== 0 && Number.isNaN(width))) result.set(request.subarray(24, 28), 4);
1600
+ if (signalingAt(28) && ((maximumWords & 2) !== 0 || (maximumWords & 1) !== 0 && Number.isNaN(height))) result.set(request.subarray(28, 32), 8);
1601
+ }
1602
+ return result;
1603
+ }
1604
+
1605
+ /** Width-aware sizing over stable widget-kind codes and native paragraph,
1606
+ * theme and row/bubble measurements. Operation 0 plans widths; 1 composes
1607
+ * measured heights; 2 measures the accordion's hidden content independently
1608
+ * of its own height, padding and depth guard. Results own their bytes.
1609
+ */
1610
+ function nscvWrappedLayout(request: Uint8Array): Uint8Array {
1611
+ if (request.length < 80 || request[0] !== 7) throw new Error("invalid wrapped layout request");
1612
+ const op = request[1]!, kind = request[2]!, flags = request[3]!;
1613
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength), count = wire.getUint32(4, true);
1614
+ if (op > 2 || kind > 62 || flags > 31 || request.length !== 80 + count * 16 || op === 2 && kind !== 14)
1615
+ throw new Error("invalid wrapped layout operation, kind, flags or length");
1616
+ const f = Math.fround, max = nscvSurfaceMax;
1617
+ const v = (at: number): number => wire.getFloat32(at, true);
1618
+ let mode = 0;
1619
+ if ((kind === 26 || kind === 44) && (flags & 1) !== 0) mode = 1;
1620
+ else if (kind === 2 || kind === 7 || kind === 4 || kind === 5 || kind === 24 || kind === 25) mode = (flags & 2) !== 0 ? 0 : 2;
1621
+ else if (kind === 0 || kind === 22 || kind === 18 || kind === 15 || kind === 16 || kind === 23) mode = 3;
1622
+ else if (kind === 17) mode = 4;
1623
+ else if (kind === 14) mode = 5;
1624
+ else if (kind === 1 || kind === 43 || kind === 8 || kind === 9 || kind === 10 || kind === 11 || kind === 12 || kind === 13 || kind === 44 && count > 0 || kind === 42 && (flags & 16) !== 0) mode = 6;
1625
+ if (op === 2) mode = 7;
1626
+ const stopped = wire.getUint32(8, true) >= wire.getUint32(12, true);
1627
+ const action = op === 2 ? 3 : stopped ? 0 : v(20) > 0 ? 1 : mode === 0 ? 0 : mode === 1 ? 2 : mode === 5 && (flags & 8) === 0 ? 4 : 3;
1628
+ const inner = op === 2 ? v(16) : max(0, f(f(v(16) - v(32)) - v(36)));
1629
+ const result = new Uint8Array(20 + count * 8), out = new DataView(result.buffer);
1630
+ out.setUint32(0, count, true); out.setUint32(4, action, true); out.setFloat32(8, inner, true); out.setUint32(16, mode, true);
1631
+ let content = 0, flows = 0;
1632
+ for (let i = 0; i < count; i++) {
1633
+ const at = 80 + i * 16, childFlags = wire.getUint32(at, true);
1634
+ if (childFlags > 7) throw new Error("invalid wrapped child flags");
1635
+ if ((childFlags & 1) === 0 || action !== 3) continue;
1636
+ flows++;
1637
+ let width = v(at + 4) > 0 ? v(at + 4) : mode === 4 && (flags & 4) !== 0 ? max(0, f(inner - v(56))) : inner;
1638
+ let query = 0;
1639
+ if (mode === 6) { query = (childFlags & 4) !== 0 ? 0 : 1; width = v(at + 8); }
1640
+ else if (mode === 2 && (childFlags & 2) !== 0 && !(v(at + 4) > 0)) {
1641
+ query = (childFlags & 4) !== 0 ? 0 : 2; width = v(at + 8);
1642
+ }
1643
+ out.setFloat32(20 + i * 8, width, true); out.setUint32(24 + i * 8, query, true);
1644
+ content = mode === 2 ? f(content + v(at + 12)) : max(content, v(at + 12));
1645
+ }
1646
+ let height = action === 0 ? v(68) : action === 1 ? v(20) : action === 2 ? v(64) : action === 4 ? v(52) : content;
1647
+ if (action === 3 && mode === 2 && flows > 1) height = f(height + f(max(0, v(48)) * f(flows - 1)));
1648
+ if (action === 3 && mode === 4) {
1649
+ if ((flags & 4) !== 0) height = f(v(52) + (height > 0 ? f(v(76) + height) : 0));
1650
+ const floor = max(v(60), f(v(52) + f(v(72) * 2)));
1651
+ height = max(height, f(f(floor - v(40)) - v(44)));
1652
+ }
1653
+ if (action === 3 && mode === 5) height = f(f(v(52) + (height > 0 ? max(0, v(48)) : 0)) + height);
1654
+ if (op !== 2 && action !== 0) {
1655
+ if (action !== 1) height = f(f(height + v(40)) + v(44));
1656
+ height = nscvSurfaceBound(height, v(24), v(28));
1657
+ }
1658
+ out.setFloat32(12, height, true); return result;
1659
+ }
1660
+
1661
+
1662
+ type NscFlowInteger = { low: number; high: number };
1663
+ function nscvFlowInteger(wire: DataView, at: number): NscFlowInteger { return { low: wire.getUint32(at, true), high: wire.getUint32(at + 4, true) }; }
1664
+ function nscvFlowCompare(a: NscFlowInteger, b: NscFlowInteger): number { return a.high !== b.high ? a.high - b.high : a.low - b.low; }
1665
+ function nscvFlowSmall(n: number): NscFlowInteger { return { low: n % 4294967296, high: Math.floor(n / 4294967296) }; }
1666
+ function nscvFlowAdd(a: NscFlowInteger, b: NscFlowInteger, checked: boolean): NscFlowInteger {
1667
+ const low = a.low + b.low, high = a.high + b.high + Math.floor(low / 4294967296);
1668
+ if (checked && high > 4294967295) throw new Error("virtual flow index overflow");
1669
+ return { low: low % 4294967296, high: high % 4294967296 };
1670
+ }
1671
+ function nscvFlowSubtract(a: NscFlowInteger, b: NscFlowInteger): NscFlowInteger {
1672
+ if (nscvFlowCompare(a, b) <= 0) return { low: 0, high: 0 };
1673
+ return { low: a.low >= b.low ? a.low - b.low : a.low + 4294967296 - b.low, high: a.high - b.high - (a.low < b.low ? 1 : 0) };
1674
+ }
1675
+ function nscvFlowMin(a: NscFlowInteger, b: NscFlowInteger): NscFlowInteger { return nscvFlowCompare(a, b) < 0 ? a : b; }
1676
+ function nscvFlowMax(a: NscFlowInteger, b: NscFlowInteger): NscFlowInteger { return nscvFlowCompare(a, b) > 0 ? a : b; }
1677
+ function nscvFlowZero(a: NscFlowInteger): boolean { return a.low === 0 && a.high === 0; }
1678
+ function nscvFlowIndex(value: number, ceil: boolean, checked: boolean): NscFlowInteger {
1679
+ if (!Number.isFinite(value) || value <= 0) return { low: 0, high: 0 };
1680
+ const integer = ceil ? Math.ceil(value) : Math.floor(value);
1681
+ if (integer >= 18446744073709551616) {
1682
+ if (checked) throw new Error("virtual flow floating index overflow");
1683
+ return { low: 4294967295, high: 4294967295 };
1684
+ }
1685
+ return nscvFlowSmall(integer);
1686
+ }
1687
+ function nscvFlowSemantic(value: NscFlowInteger): number { return value.high > 0 ? 4294967295 : value.low; }
1688
+ function nscvFlowWrite(out: DataView, at: number, value: NscFlowInteger): void { out.setUint32(at, value.low, true); out.setUint32(at + 4, value.high, true); }
1689
+
1690
+ type NscFlowRange = { start: NscFlowInteger; end: NscFlowInteger; extent: number; gap: number; offset: number; total: number };
1691
+ /** Shared uniform-window arithmetic over exact integer lanes and native
1692
+ * integer-to-f32 conversion facts. Native owns measurement and traversal. */
1693
+ function nscvFlowRange(count: NscFlowInteger, countF: number, authored: number, gapValue: number, viewportValue: number, scroll: number, overscan: NscFlowInteger, flags: number): NscFlowRange {
1694
+ const zero = { low: 0, high: 0 }, f = Math.fround, max = nscvSurfaceMax;
1695
+ if (nscvFlowZero(count) || authored <= 0 || viewportValue <= 0) return { start: zero, end: zero, extent: 0, gap: 0, offset: 0, total: 0 };
1696
+ const extent = max(0, authored), gap = max(0, gapValue), stride = f(extent + gap), viewport = max(0, viewportValue);
1697
+ const total = f(f(countF * extent) + f(max(0, f(countF - 1)) * gap));
1698
+ const maximum = max(0, f(total - viewport)), raw = Number.isFinite(scroll) ? scroll : 0;
1699
+ const offset = nscvSurfaceClamp(max(0, raw), 0, maximum, (flags & 1) !== 0);
1700
+ const layout = nscvSurfaceClamp(raw, -viewport, f(maximum + viewport), (flags & 1) !== 0);
1701
+ const first = nscvFlowMin(nscvFlowSubtract(count, nscvFlowSmall(1)), nscvFlowIndex(f(offset / stride), false, (flags & 2) !== 0));
1702
+ const visibleEnd = nscvFlowMin(count, nscvFlowIndex(f(f(f(offset + viewport) + gap) / stride), true, (flags & 2) !== 0));
1703
+ return { start: nscvFlowSubtract(first, overscan), end: nscvFlowMin(count, nscvFlowAdd(visibleEnd, overscan, (flags & 2) !== 0)), extent, gap, offset: layout, total };
1704
+ }
1705
+
1706
+ /** Virtual row placement, scroll displacement and content extents over
1707
+ * explicit native measurement facts. Requests/results have copied ownership;
1708
+ * index lanes retain every usize bit independently of JS number precision. */
1709
+ function nscvVirtualFlow(request: Uint8Array): Uint8Array {
1710
+ if (request.length < 128 || request[0] !== 8) throw new Error("invalid virtual flow request");
1711
+ const op = request[1]!, flags = request[2]!, axes = request[3]!;
1712
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength), count = wire.getUint32(4, true);
1713
+ if (op > 2 || flags > 3 || axes > 7 || request.length !== 128 + count * 64 || wire.getUint32(120, true) !== 0 || wire.getUint32(124, true) !== 0) throw new Error("invalid virtual flow operation, flags or length");
1714
+ const first = nscvFlowInteger(wire, 8), declared = nscvFlowInteger(wire, 16), anchor = nscvFlowInteger(wire, 24), overscan = nscvFlowInteger(wire, 32);
1715
+ const semantic = nscvFlowInteger(wire, 40), gridRows = nscvFlowInteger(wire, 48), f = Math.fround, max = nscvSurfaceMax;
1716
+ const v = (at: number): number => wire.getFloat32(at, true);
1717
+ let flows = 0;
1718
+ for (let i = 0; i < count; i++) { const lane = wire.getUint32(128 + i * 64, true); if (lane > 1) throw new Error("invalid virtual flow child flags"); if (lane === 1) flows++; }
1719
+ const checked = (flags & 2) !== 0, windowed = !nscvFlowZero(declared), variable = windowed && v(116) > 0;
1720
+ const builtEnd = op === 1 && variable ? declared : op !== 2 && windowed ? nscvFlowAdd(first, nscvFlowSmall(flows), checked) : nscvFlowSmall(flows);
1721
+ let items = windowed ? nscvFlowMax(declared, builtEnd) : op === 1 && (axes & 4) !== 0 && flows > 0 ? gridRows : flows > 0 ? nscvFlowSmall(flows) : semantic;
1722
+ let itemsF = windowed ? nscvFlowCompare(declared, builtEnd) >= 0 ? v(64) : v(60) : op === 1 && (axes & 4) !== 0 && flows > 0 ? v(68) : flows > 0 ? v(56) : v(72);
1723
+ if (op === 0 && flows === 0) { items = nscvFlowSmall(0); itemsF = 0; }
1724
+ const x = v(76), y = v(80), width = v(84), viewport = v(88), gap = max(0, v(92));
1725
+ const extent = v(96) > 0 ? v(96) : v(100), scroll = v(108);
1726
+ const range = variable || op === 2 ? { start: nscvFlowSmall(0), end: items, extent: 0, gap, offset: 0, total: v(116) }
1727
+ : nscvFlowRange(items, itemsF, extent, v(92), viewport, scroll, op === 1 ? nscvFlowSmall(0) : overscan, flags);
1728
+ const result = new Uint8Array(48 + count * 32), out = new DataView(result.buffer);
1729
+ out.setUint32(0, count, true); out.setUint32(4, op === 2 ? 4 : op === 1 ? variable ? 2 : 3 : variable ? 1 : 0, true);
1730
+ out.setUint32(8, nscvFlowSemantic(items), true); out.setFloat32(12, range.extent, true);
1731
+ out.setFloat32(16, op === 1 && variable ? v(116) : range.total, true); out.setFloat32(20, range.offset, true); nscvFlowWrite(out, 40, items);
1732
+ const translatedX = op === 2 ? f(x - ((axes & 1) !== 0 ? v(104) : 0)) : x;
1733
+ const translatedY = op === 2 ? f(y - ((axes & 2) !== 0 ? scroll : 0)) : y;
1734
+ for (const [at, value] of [[24, translatedX], [28, translatedY], [32, width], [36, viewport]]) out.setFloat32(at!, value!, true);
1735
+ let anchorChild = 0, leading = 0;
1736
+ if (op === 0 && variable && flows > 0) {
1737
+ const boundedAnchor = nscvFlowMin(nscvFlowSubtract(anchor, first), nscvFlowSmall(flows - 1)); anchorChild = boundedAnchor.low;
1738
+ const total = max(0, v(116)), maximum = max(0, f(total - viewport)), raw = Number.isFinite(scroll) ? scroll : 0;
1739
+ const offset = nscvSurfaceClamp(raw, -viewport, f(maximum + viewport), (flags & 1) !== 0);
1740
+ leading = f(f(y + max(0, v(112))) - offset);out.setFloat32(20, offset, true);
1741
+ let before = 0;
1742
+ for (let i = 0; i < count && before < anchorChild; i++) {
1743
+ const at = 128 + i * 64;if (wire.getUint32(at, true) === 0) continue;
1744
+ const height = nscvSurfaceBound(v(at + 12) > 0 ? v(at + 12) : v(at + 40), v(at + 24), v(at + 28));
1745
+ leading = f(leading - f(height + gap)); before++;
1746
+ }
1747
+ }
1748
+ let index = 0;
1749
+ for (let i = 0; i < count; i++) {
1750
+ const at = 128 + i * 64, target = 48 + i * 32;
1751
+ if (wire.getUint32(at, true) === 0 || op === 1) continue;
1752
+ const absolute = op === 2 ? nscvFlowSmall(0) : nscvFlowAdd(first, nscvFlowSmall(index), checked); index++;
1753
+ if (op === 0 && !variable && (nscvFlowCompare(absolute, range.start) < 0 || nscvFlowCompare(absolute, range.end) >= 0)) continue;
1754
+ const measureHorizontal = op === 2 && (axes & 1) !== 0 && v(at + 8) <= 0;
1755
+ out.setUint32(target, measureHorizontal ? 3 : 1, true);out.setUint32(target + 4, nscvFlowSemantic(absolute), true);nscvFlowWrite(out, target + 24, absolute);
1756
+ let childX: number, childY: number, childWidth: number, childHeight: number;
1757
+ if (op === 2) {
1758
+ childX = v(at + 48);childY = v(at + 52);childWidth = measureHorizontal ? max(v(at + 56), v(at + 44)) : v(at + 56);childHeight = v(at + 60);
1759
+ } else {
1760
+ childX = f(x + v(at + 32));childWidth = nscvSurfaceBound(v(at + 8) > 0 ? v(at + 8) : width, v(at + 16), v(at + 20));
1761
+ childHeight = nscvSurfaceBound(v(at + 12) > 0 ? v(at + 12) : variable ? v(at + 40) : range.extent, v(at + 24), v(at + 28));
1762
+ childY = variable ? f(leading + v(at + 36)) : f(f(f(y + f(v(at + 4) * f(range.extent + range.gap))) - range.offset) + v(at + 36));
1763
+ if (variable) leading = f(leading + f(childHeight + gap));
1764
+ }
1765
+ for (const [offset, value] of [[8, childX], [12, childY], [16, childWidth], [20, childHeight]]) out.setFloat32(target + offset!, value!, true);
1766
+ }
1767
+ return result;
1768
+ }
1769
+
1770
+ const nscvSemanticRoles = [1,1,1,1,14,14,1,11,1,1,1,19,1,1,1,1,1,1,1,8,8,8,1,8,9,9,2,4,4,4,2,5,5,5,5,6,6,6,6,6,7,10,12,13,15,2,16,17,18,20,5,21,22,0,0,22,23,1,26,24,1,4,6];
1771
+ type NscSemanticMetric = { present: boolean; offset: number; viewport: number; content: number };
1772
+ type NscSemanticScroll = { vertical: NscSemanticMetric; horizontal: NscSemanticMetric; primary: NscSemanticMetric; value: number; scrollable: boolean };
1773
+
1774
+ /** Exact unsigned division for authored grid columns and child counts. No
1775
+ * pointer, usize, or declared index crosses through a floating JS number. */
1776
+ function nscvSemanticDivide(value: NscFlowInteger, divisor: NscFlowInteger): { quotient: NscFlowInteger; remainder: NscFlowInteger } {
1777
+ if (nscvFlowZero(divisor)) throw new Error("zero semantic grid divisor");
1778
+ let low = 0, high = 0, quotientLow = 0, quotientHigh = 0;
1779
+ for (let bit = 63; bit >= 0; bit--) {
1780
+ const carry = high >= 2147483648;
1781
+ high = (high * 2 + Math.floor(low / 2147483648)) % 4294967296;
1782
+ low = (low * 2 + ((bit >= 32 ? value.high >>> (bit - 32) : value.low >>> bit) & 1)) % 4294967296;
1783
+ if (carry || nscvFlowCompare({ low, high }, divisor) >= 0) {
1784
+ const borrow = low < divisor.low ? 1 : 0;
1785
+ low = (low - divisor.low + 4294967296) % 4294967296;
1786
+ high = (high - divisor.high - borrow + 4294967296) % 4294967296;
1787
+ if (bit >= 32) quotientHigh += 2 ** (bit - 32); else quotientLow += 2 ** bit;
1788
+ }
1789
+ }
1790
+ return { quotient: { low: quotientLow, high: quotientHigh }, remainder: { low, high } };
1791
+ }
1792
+
1793
+ /** Complete semantic reduction over measured native tree facts. String and
1794
+ * text-range storage stays native-owned; selectors choose those borrowed
1795
+ * fields. The established semantic-action policy supplies action facts. */
1796
+ function nscvSemanticTree(request: Uint8Array): Uint8Array {
1797
+ if (request.length < 16 || request[0] !== 9 || request[1]! > 1 || request[2]! > 1 || request[3] !== 0) throw new Error("invalid semantic tree header");
1798
+ const wire = new DataView(request.buffer, request.byteOffset, request.byteLength);
1799
+ const count = wire.getUint32(4, true), target = wire.getUint32(8, true), capacity = wire.getUint32(12, true), query = request[1] === 1;
1800
+ if (request.length !== 16 + count * 128 || (query ? target >= count : target !== 0)) throw new Error("invalid semantic tree length or target");
1801
+ const word = (i: number, at: number): number => wire.getUint32(16 + i * 128 + at, true);
1802
+ const value = (i: number, at: number): number => wire.getFloat32(16 + i * 128 + at, true);
1803
+ const integer = (i: number, at: number): NscFlowInteger => nscvFlowInteger(wire, 16 + i * 128 + at);
1804
+ for (let i = 0; i < count; i++) {
1805
+ if (word(i, 0) > 62 || word(i, 4) > 26 || word(i, 16) > 32767 || word(i, 20) > 1023 || word(i, 24) > 2047 ||
1806
+ (word(i, 12) !== 4294967295 && word(i, 12) >= count)) throw new Error("invalid semantic node facts");
1807
+ for (let at = 104; at < 128; at += 4) if (word(i, at) !== 0) throw new Error("invalid semantic node reserved bytes");
1808
+ }
1809
+ const result = new Uint8Array(16 + (query ? 1 : count) * 144), out = new DataView(result.buffer), f = Math.fround, max = nscvSurfaceMax;
1810
+ const missing = 4294967295, flag = (i: number, bit: number): boolean => (word(i, 16) & bit) !== 0;
1811
+ const kind = (i: number): number => word(i, 0), parent = (i: number): number => word(i, 12), depth = (i: number): number => word(i, 8);
1812
+ const modal = (i: number): boolean => kind(i) >= 19 && kind(i) <= 21;
1813
+ const skip = (i: number): number => { let next = i + 1; while (next < count && depth(next) > depth(i)) next++; return next; };
1814
+ const childCount = (p: number, k: number): number => { let total = 0; for (let i = 0; i < count; i++) if (parent(i) === p && (k < 0 || kind(i) === k)) total++; return total; };
1815
+ const ordinal = (p: number, child: number, k: number): number => { let at = 0; for (let i = 0; i < count; i++) if (parent(i) === p && (k < 0 || kind(i) === k)) { if (i === child) return at; at++; } return missing; };
1816
+ const columns = (i: number): NscFlowInteger => { const children = integer(i, 44), authored = integer(i, 36); return nscvFlowZero(children) ? children : nscvFlowZero(authored) ? children : authored; };
1817
+ const rows = (i: number, cols: NscFlowInteger): NscFlowInteger => {
1818
+ if (flag(i, 4096)) return nscvFlowSmall(word(i, 28));
1819
+ const children = integer(i, 44);
1820
+ return nscvFlowZero(children) || nscvFlowZero(cols) ? nscvFlowSmall(0) : nscvFlowAdd(nscvFlowSmall(1), nscvSemanticDivide(nscvFlowSubtract(children, nscvFlowSmall(1)), cols).quotient, true);
1821
+ };
1822
+ const table = (i: number): boolean => kind(i) === 4 || kind(i) === 5;
1823
+ const tableRows = (i: number): number => flag(i, 4096) ? word(i, 28) : childCount(i, 43);
1824
+ const scroll = (i: number): NscSemanticScroll => {
1825
+ const vx = value(i, 68), vy = value(i, 72), vw = value(i, 76), vh = value(i, 80), virtual = flag(i, 4);
1826
+ const empty = { present: false, offset: 0, viewport: 0, content: 0 };
1827
+ let vertical: NscSemanticMetric = empty, horizontal: NscSemanticMetric = empty;
1828
+ for (let axis = 0; axis < 2; axis++) {
1829
+ if (axis === 0 ? kind(i) === 6 && !virtual && !flag(i, 64) : kind(i) !== 6 || virtual || !flag(i, 32)) continue;
1830
+ const extent = axis === 0 ? vh : vw, origin = axis === 0 ? vy : vx, raw = value(i, axis === 0 ? 84 : 88);
1831
+ let reach = f(origin + extent), content: number;
1832
+ if (axis === 0 && virtual) content = max(extent, value(i, 100));
1833
+ else {
1834
+ let child = i + 1;
1835
+ while (child < count && depth(child) > depth(i)) {
1836
+ if (axis === 0 ? modal(child) || flag(child, 8) && parent(child) === i : modal(child) || flag(child, 8)) { child = skip(child); continue; }
1837
+ reach = max(reach, f(f(value(child, axis === 0 ? 56 : 52) + value(child, axis === 0 ? 64 : 60)) + raw));
1838
+ if (axis === 0 ? kind(child) === 14 : kind(child) === 6 || flag(child, 16) || flag(child, 4) || kind(child) === 14 && !flag(child, 128)) child = skip(child); else child++;
1839
+ }
1840
+ content = max(0, f(reach - origin));
1841
+ }
1842
+ const maximum = max(0, f(content - extent));
1843
+ const metric = { present: true, offset: nscvSurfaceClamp(raw < 0 ? 0 : raw, 0, maximum, request[2] === 1), viewport: extent, content };
1844
+ if (axis === 0) vertical = metric; else horizontal = metric;
1845
+ }
1846
+ const verticalRange = vertical.present && vertical.content > vertical.viewport, horizontalRange = horizontal.present && horizontal.content > horizontal.viewport;
1847
+ let primary = verticalRange || vertical.present && !horizontalRange ? vertical : horizontal.present ? horizontal : vertical;
1848
+ const exposes = kind(i) === 6 || virtual && (kind(i) === 3 || kind(i) === 7 || table(i));
1849
+ if (!exposes || vw <= 0 || vh <= 0) primary = empty;
1850
+ const maximum = max(0, f(primary.content - primary.viewport));
1851
+ return { vertical, horizontal, primary, value: maximum > 0 ? f(primary.offset / maximum) : 0, scrollable: primary.present && maximum > 0 };
1852
+ };
1853
+ let emitted = 0, hidden = missing, concealed = missing;
1854
+ const stack: number[] = []; for (let d = 0; d < 32; d++) stack.push(missing);
1855
+ for (let i = query ? target : 0; i < (query ? target + 1 : count); i++) {
1856
+ const d = depth(i), k = kind(i), state = word(i, 20), disabled = (state & 8) !== 0;
1857
+ const role = word(i, 4) || nscvSemanticRoles[k]!;
1858
+ if (!query) {
1859
+ if (d >= 32) { out.setUint32(4, 1, true); break; }
1860
+ if (hidden !== missing) { if (d > hidden) continue; hidden = missing; }
1861
+ if (concealed !== missing) { if (d > concealed) continue; concealed = missing; }
1862
+ for (let level = d + 1; level < 32; level++) stack[level] = missing;
1863
+ if (flag(i, 1)) { hidden = d; continue; }
1864
+ if (k === 14 && !flag(i, 128)) concealed = d;
1865
+ if (role === 0 || flag(i, 2)) continue;
1866
+ if (emitted >= capacity) { out.setUint32(4, 2, true); break; }
1867
+ }
1868
+ const at = 16 + emitted * 144, s = scroll(i);
1869
+ out.setUint32(at, i, true);
1870
+ let ancestor = missing; if (!query) for (let level = d - 1; level >= 0; level--) if (stack[level] !== missing) { ancestor = stack[level]!; break; }
1871
+ out.setUint32(at + 4, ancestor, true); out.setUint32(at + 8, role, true);
1872
+ let actions = word(i, 24); if (s.scrollable && !disabled) actions |= 1 | 8 | 16;
1873
+ const selected = (state & 16) !== 0 || value(i, 84) >= 0.5;
1874
+ let composedState = state;
1875
+ if ((state & 256) === 0) {
1876
+ if (k === 14) composedState |= 256 | (selected ? 512 : 0);
1877
+ else if (k === 34 || k === 38) composedState |= 256;
1878
+ else if (k === 23 || k === 24 || k === 25) composedState |= 256 | 512;
1879
+ }
1880
+ let hasValue = flag(i, 512), semanticValue = value(i, 92);
1881
+ if (!hasValue) {
1882
+ if (k === 48 || k === 42 || k === 41 || k === 44 || k === 46 || k === 14 || k === 47 || k === 49 || k === 50 || k === 32) { hasValue = true; semanticValue = selected ? 1 : 0; }
1883
+ else if (k === 51 || k === 52 || k === 58) { hasValue = true; semanticValue = nscvSurfaceClamp(value(i, 84), 0, 1, request[2] === 1); }
1884
+ else if (k === 56 && flag(i, 1024)) { hasValue = true; semanticValue = value(i, 96); }
1885
+ }
1886
+ if (s.primary.present) { hasValue = true; semanticValue = s.value; }
1887
+ const focusable = !disabled && !flag(i, 1) && !flag(i, 2) && (flag(i, 8192) || flag(i, 16384) || (actions & 1) !== 0);
1888
+ const text = k >= 35 && k <= 39 || k === 62, placeholder = k >= 34 && k <= 39;
1889
+ out.setUint32(at + 12, (flag(i, 256) ? 1 : 0) | (text ? 2 : 0) | (placeholder ? 4 : 0) | (focusable ? 8 : 0) | (hasValue ? 16 : 0), true);
1890
+ out.setUint32(at + 16, composedState, true); out.setUint32(at + 20, actions, true); out.setFloat32(at + 24, semanticValue, true);
1891
+ const p = parent(i);
1892
+ if (p !== missing && kind(p) === 7) {
1893
+ let listCount = 0, listIndex = missing;
1894
+ if (flag(i, 2048) && flag(i, 4096)) { listCount = word(i, 28); listIndex = word(i, 32); }
1895
+ else if (k === 42) { listCount = childCount(p, 42); if (listCount > 0) listIndex = ordinal(p, i, 42); }
1896
+ if (listIndex !== missing || flag(i, 2048) && flag(i, 4096)) {
1897
+ out.setUint32(at + 28, 1, true); out.setUint32(at + 32, listIndex, true); out.setUint32(at + 36, listCount, true);
1898
+ }
1899
+ }
1900
+ let gridMask = 0;
1901
+ const gridValue = (bit: number, offset: number, value: NscFlowInteger): void => { gridMask |= bit; nscvFlowWrite(out, at + offset, value); };
1902
+ let gridParent = p;
1903
+ if (k === 3) {
1904
+ if (word(i, 4) === 14) { const cols = columns(i); gridValue(4, 60, rows(i, cols)); gridValue(8, 68, cols); }
1905
+ } else if (table(i)) {
1906
+ let maximum = 0; for (let child = 0; child < count; child++) if (parent(child) === i && kind(child) === 43) maximum = Math.max(maximum, childCount(child, 44));
1907
+ gridValue(4, 60, nscvFlowSmall(tableRows(i))); gridValue(8, 68, nscvFlowSmall(maximum));
1908
+ } else {
1909
+ if (gridParent !== missing && kind(gridParent) === 3 && word(gridParent, 4) === 14) {
1910
+ const cols = columns(gridParent), index = flag(i, 2048) ? word(i, 32) : ordinal(gridParent, i, -1);
1911
+ if (!nscvFlowZero(cols) && (index !== missing || flag(i, 2048))) { const divided = nscvSemanticDivide(nscvFlowSmall(index), cols); gridValue(1, 44, divided.quotient); gridValue(2, 52, divided.remainder); gridValue(4, 60, rows(gridParent, cols)); gridValue(8, 68, cols); }
1912
+ } else if (k === 43 || k === 44) {
1913
+ const row = k === 43 ? i : p;
1914
+ if (row !== missing && kind(row) === 43) {
1915
+ gridParent = parent(row);
1916
+ if (gridParent !== missing && table(gridParent)) {
1917
+ const index = flag(row, 2048) ? word(row, 32) : ordinal(gridParent, row, 43);
1918
+ if (index !== missing || flag(row, 2048)) gridValue(1, 44, nscvFlowSmall(index));
1919
+ if (k === 44) { const cell = ordinal(row, i, 44); if (cell !== missing) gridValue(2, 52, nscvFlowSmall(cell)); }
1920
+ gridValue(4, 60, nscvFlowSmall(tableRows(gridParent))); gridValue(8, 68, nscvFlowSmall(childCount(row, 44)));
1921
+ }
1922
+ }
1923
+ }
1924
+ }
1925
+ out.setUint32(at + 40, gridMask, true);
1926
+ for (let axis = 0; axis < 3; axis++) {
1927
+ const metric = axis === 0 ? s.primary : axis === 1 ? s.vertical : s.horizontal;
1928
+ const offset = axis === 0 ? 76 : axis === 1 ? 100 : 116;
1929
+ out.setUint32(at + offset, metric.present ? 1 : 0, true); out.setFloat32(at + offset + 4, metric.offset, true); out.setFloat32(at + offset + 8, metric.viewport, true); out.setFloat32(at + offset + 12, metric.content, true);
1930
+ }
1931
+ out.setFloat32(at + 92, s.value, true); out.setUint32(at + 96, s.scrollable ? 1 : 0, true);
1932
+ if (!query) stack[d] = emitted;
1933
+ emitted++;
1934
+ }
1935
+ out.setUint32(0, emitted, true); return result;
1936
+ }
1937
+
1938
+ /** Retained variable-window transitions. Estimate arithmetic and search decisions use bounded copied facts; sparse corrections cross once per measured
1939
+ * batch and hot window coordination uses small scalar records. No retained
1940
+ * native address or borrowed model bytes escape this copied boundary. */
1941
+ function nscvExtentPolicy(request: Uint8Array): Uint8Array {
1942
+ if (request.length < 4 || request[0] !== 10 || request[2]! > 1) throw new Error("invalid extent policy header");
1943
+ const op = request[1]!, w = new DataView(request.buffer, request.byteOffset, request.byteLength);
1944
+ const f = Math.fround, max = nscvSurfaceMax, integer = (at: number): NscFlowInteger => nscvFlowInteger(w, at);
1945
+ const v = (at: number): number => w.getFloat32(at, true);
1946
+ const fixed = (length: number): void => { if (request.length !== length) throw new Error("invalid extent policy length"); };
1947
+ if (op === 0) {
1948
+ fixed(72); if (request[3] !== 0) throw new Error("invalid extent sync flags");
1949
+ const oldId = integer(8), id = integer(16), oldCount = integer(24), count = integer(32), oldBase = integer(40), base = integer(48);
1950
+ if (nscvFlowZero(id) || w.getUint32(4,true) !== 0 || w.getUint32(64,true) !== 0 || w.getUint32(68,true) !== 0) throw new Error("invalid extent sync identity");
1951
+ const fresh = nscvFlowZero(oldId) || nscvFlowCompare(oldId,id) !== 0;
1952
+ const mode = fresh ? 1 : nscvFlowCompare(base,oldBase) < 0 ? 2 : nscvFlowCompare(base,oldBase) > 0 ? 3 : nscvFlowCompare(count,oldCount) > 0 ? 4 : nscvFlowCompare(count,oldCount) < 0 ? 5 : 0;
1953
+ const chunkSource = mode === 4 ? oldCount : mode === 5 ? count : nscvFlowSmall(0);
1954
+ const firstChunk = { low: Math.floor(chunkSource.low / 64) + (chunkSource.high % 64) * 67108864, high: Math.floor(chunkSource.high / 64) };
1955
+ const shift = mode === 2 ? nscvFlowMin(nscvFlowSubtract(oldBase,base),count) : mode === 3 ? nscvFlowMin(nscvFlowSubtract(base,oldBase),oldCount) : nscvFlowSmall(0);
1956
+ const result = new Uint8Array(40), out = new DataView(result.buffer);
1957
+ result[0] = mode; result[1] = mode === 1 ? 1 : mode === 4 ? 2 : mode === 2 ? 4 : 0;
1958
+ out.setFloat32(4,nscvExtentClean(v(56)),true); out.setFloat32(8,fresh ? 0 : v(60),true);
1959
+ nscvFlowWrite(out,16,firstChunk); nscvFlowWrite(out,24,shift); return result;
1960
+ }
1961
+ if (op === 1) return nscvExtentCorrections(request);
1962
+ if (op === 2) {
1963
+ fixed(32); if (request[3]! > 7) throw new Error("invalid extent window flags");
1964
+ const flags = request[3]!, retained = (flags & 4) !== 0, trailing = (flags & 1) !== 0, mounted = (flags & 2) !== 0;
1965
+ let offset = retained ? f(v(4) + v(8)) : v(4);
1966
+ if (trailing && (!mounted || (retained && v(20) >= 0 && v(4) >= f(max(0,f(v(20)-v(24))) - 1)))) offset = max(0,f(v(12)-v(16)));
1967
+ const result = new Uint8Array(4); new DataView(result.buffer).setFloat32(0,offset,true); return result;
1968
+ }
1969
+ if (op === 3) {
1970
+ fixed(32); if (request[3] !== 0 || w.getUint32(4,true) !== 0 || w.getUint32(28,true) !== 0) throw new Error("invalid extent range bounds");
1971
+ const result = new Uint8Array(16), out = new DataView(result.buffer);
1972
+ if (nscvFlowZero(integer(8)) || v(20) <= 0) return result;
1973
+ const maximum = max(0,f(v(16)-v(20))), raw = Number.isFinite(v(24)) ? v(24) : 0;
1974
+ const offset = nscvSurfaceClamp(max(0,raw),0,maximum,request[2] === 1);
1975
+ out.setUint32(0,1,true); out.setFloat32(4,offset,true); out.setFloat32(8,nscvSurfaceClamp(raw,-v(20),f(maximum+v(20)),request[2] === 1),true);
1976
+ out.setFloat32(12,f(offset+v(20)),true); return result;
1977
+ }
1978
+ if (op === 4 || op === 7) {
1979
+ fixed(op === 4 ? 48 : 64); if (request[3] !== 0 || w.getUint32(4,true) !== 0 || w.getUint32(40,true) !== 0 && op === 4 || w.getUint32(44,true) !== 0 && op === 4) throw new Error("invalid extent index facts");
1980
+ const count = integer(8), overscan = integer(32), first = nscvFlowMin(nscvFlowSubtract(count,nscvFlowSmall(1)),integer(16));
1981
+ let end = nscvFlowMin(count,nscvFlowAdd(integer(24),nscvFlowSmall(1),true));
1982
+ if (op === 4 && nscvFlowCompare(end,first) <= 0) end = nscvFlowAdd(first,nscvFlowSmall(1),true);
1983
+ const start = nscvFlowSubtract(first,overscan), last = nscvFlowSubtract(end,nscvFlowSmall(1));
1984
+ end = nscvFlowMin(count,nscvFlowAdd(end,overscan,true));
1985
+ if (op === 7) {
1986
+ if (w.getUint32(56,true) !== 0 || w.getUint32(60,true) !== 0) throw new Error("invalid extent coverage padding");
1987
+ const result = new Uint8Array(1); result[0] = nscvFlowCompare(start,integer(40)) < 0 || nscvFlowCompare(end,integer(48)) > 0 ? 1 : 0; return result;
1988
+ }
1989
+ const result = new Uint8Array(32), out = new DataView(result.buffer);
1990
+ nscvFlowWrite(out,0,start); nscvFlowWrite(out,8,end); nscvFlowWrite(out,16,first); nscvFlowWrite(out,24,last); return result;
1991
+ }
1992
+ if (op === 5) {
1993
+ fixed(32); if (request[3] !== 0 || w.getUint32(28,true) !== 0) throw new Error("invalid extent range finish");
1994
+ const result = new Uint8Array(24), out = new DataView(result.buffer);
1995
+ for (let i=0;i<6;i++) out.setFloat32(i*4,i === 0 ? v(20) : i === 1 ? v(24) : i === 2 ? v(4) : i === 3 ? v(12) : i === 4 ? max(0,f(v(4)-v(8))) : v(16),true);
1996
+ return result;
1997
+ }
1998
+ if (op === 6) {
1999
+ if (request.length < 24 || request[3] !== 0 || w.getUint32(12,true) !== 0) throw new Error("invalid extent slot header");
2000
+ const count=w.getUint32(4,true), declared=w.getUint32(8,true), id=integer(16);
2001
+ if (count > 254 || declared > 254 || request.length !== 24 + (count+declared)*8) throw new Error("invalid extent slot table");
2002
+ const result=new Uint8Array(2); result[1]=255; if(nscvFlowZero(id))return result;
2003
+ for(let i=0;i<count;i++)if(nscvFlowCompare(integer(24+i*8),id) === 0){result[1]=i;return result;}
2004
+ for(let i=0;i<count;i++)if(nscvFlowZero(integer(24+i*8))){result[1]=i;return result;}
2005
+ for(let i=0;i<count;i++){
2006
+ let keep=false;for(let j=0;j<declared;j++)if(nscvFlowCompare(integer(24+i*8),integer(24+(count+j)*8)) === 0)keep=true;
2007
+ if(!keep){result[0]=1;result[1]=i;return result;}
2008
+ }
2009
+ return result;
2010
+ }
2011
+ if (op === 8) {
2012
+ fixed(16);if(request[3]! > 1 || w.getUint32(12,true) !== 0)throw new Error("invalid extent pending shift");
2013
+ const result=new Uint8Array(4);new DataView(result.buffer).setFloat32(0,request[3] === 1 ? f(v(4)-v(8)) : f(v(4)+v(8)),true);return result;
2014
+ }
2015
+ if (op === 9 || op === 10) {
2016
+ if (request.length < 32 || request[3] !== 0) throw new Error("invalid extent estimate header");
2017
+ const count=w.getUint32(4,true);
2018
+ if (count > (op === 9 ? 1024 : 63) || request.length !== 32+count*4 || w.getUint32(28,true)!==0) throw new Error("invalid extent estimate batch");
2019
+ if (op === 9) {
2020
+ const result=new Uint8Array(4*Math.ceil(count/64)),out=new DataView(result.buffer);let prefix=v(8);
2021
+ for(let chunk=0;chunk<Math.ceil(count/64);chunk++){
2022
+ let sum=0;for(let i=chunk*64;i<Math.min(count,(chunk+1)*64);i++)sum=f(sum+v(32+i*4));
2023
+ prefix=f(prefix+sum);out.setFloat32(chunk*4,prefix,true);
2024
+ }
2025
+ return result;
2026
+ }
2027
+ let prefix=v(8);for(let i=0;i<count;i++)prefix=f(prefix+v(32+i*4));
2028
+ if(v(16)>0)prefix=f(prefix+f(v(16)*f(v(12)/v(20))));
2029
+ const result=new Uint8Array(4);new DataView(result.buffer).setFloat32(0,prefix,true);return result;
2030
+ }
2031
+ if (op === 11) {
2032
+ fixed(24);if(request[3]!>1 || w.getUint32(20,true)!==0)throw new Error("invalid extent scalar query");
2033
+ const result=new Uint8Array(4),out=new DataView(result.buffer);
2034
+ out.setFloat32(0,request[3]===1?max(0,f(v(4)+v(8))):f(f(v(4)+v(8))+f(v(12)*v(16))),true);return result;
2035
+ }
2036
+ if (op === 12) {
2037
+ fixed(40);if(request[3]!>3 || w.getUint32(4,true)!==0)throw new Error("invalid extent search continuation");
2038
+ const checked=(request[3]!&1)!==0,continued=(request[3]!&2)!==0,count=integer(8),target=max(0,v(32));
2039
+ let low=continued?integer(16):nscvFlowSmall(0),high=continued?integer(24):nscvFlowSubtract(count,nscvFlowSmall(1));
2040
+ const midpoint=(a:NscFlowInteger,b:NscFlowInteger):NscFlowInteger=>{
2041
+ const sum=nscvFlowAdd(nscvFlowAdd(a,b,checked),nscvFlowSmall(1),checked);
2042
+ return {low:Math.floor(sum.low/2)+(sum.high%2)*2147483648,high:Math.floor(sum.high/2)};
2043
+ };
2044
+ if(nscvFlowCompare(low,high)>0 || (!nscvFlowZero(count)&&nscvFlowCompare(high,count)>=0) || (continued&&nscvFlowCompare(low,high)>=0))throw new Error("invalid extent search bounds");
2045
+ if(continued){const mid=midpoint(low,high);if(v(36)<=target)low=mid;else high=nscvFlowSubtract(mid,nscvFlowSmall(1));}
2046
+ const active=nscvFlowCompare(low,high)<0,result=new Uint8Array(32),out=new DataView(result.buffer);
2047
+ nscvFlowWrite(out,0,low);nscvFlowWrite(out,8,high);nscvFlowWrite(out,16,active?midpoint(low,high):low);out.setUint32(24,active?1:0,true);out.setFloat32(28,target,true);return result;
2048
+ }
2049
+ if (op === 13) {
2050
+ fixed(48);if(request[3]!>6 || (request[3]!&3)>2 || w.getUint32(4,true)!==0)throw new Error("invalid extent query plan");
2051
+ const mode=request[3]!&3,count=integer(8),index=mode===2?count:nscvFlowMin(integer(16),count),covered=integer(32),chunks=integer(40);
2052
+ if(nscvFlowCompare(covered,nscvFlowSmall(262144))>0 || nscvFlowCompare(covered,count)>0 || chunks.high!==0 || chunks.low!==Math.ceil(covered.low/64))throw new Error("invalid extent cache shape");
2053
+ const tail=nscvFlowCompare(index,covered)>0;
2054
+ const chunk=tail?chunks.low:Math.floor(index.low/64),start=tail?covered:nscvFlowSmall(chunk*64),samples=tail?0:nscvFlowSubtract(index,start).low;
2055
+ const extra=tail?nscvFlowSubtract(index,covered):nscvFlowSmall(0),gapCount=mode===2?nscvFlowSubtract(count,nscvFlowSmall(1)):index;
2056
+ const logical=mode===1?nscvFlowAdd(integer(24),index,(request[3]!&4)!==0):nscvFlowSmall(0);
2057
+ const result=new Uint8Array(64),out=new DataView(result.buffer);
2058
+ nscvFlowWrite(out,0,index);nscvFlowWrite(out,8,logical);nscvFlowWrite(out,16,start);nscvFlowWrite(out,24,extra);nscvFlowWrite(out,32,gapCount);
2059
+ out.setUint32(40,chunk,true);out.setUint32(44,samples,true);out.setUint32(48,tail?1:0,true);out.setUint32(52,mode===2&&nscvFlowZero(count)?1:0,true);return result;
2060
+ }
2061
+ if (op === 14) {
2062
+ fixed(24);if(request[3]!==0 || w.getUint32(4,true)!==0)throw new Error("invalid extent rebuild plan");
2063
+ const covered=nscvFlowMin(integer(8),nscvFlowSmall(262144)),chunks=Math.ceil(covered.low/64),first=nscvFlowMin(integer(16),nscvFlowSmall(chunks)).low,end=Math.min(first+16,chunks);
2064
+ const result=new Uint8Array(40),out=new DataView(result.buffer);
2065
+ out.setUint32(0,covered.low,true);out.setUint32(4,chunks,true);out.setUint32(8,first,true);out.setUint32(12,end,true);
2066
+ out.setUint32(16,Math.min(covered.low,first*64),true);out.setUint32(20,Math.min(covered.low,end*64),true);out.setUint32(24,first<chunks?1:0,true);return result;
2067
+ }
2068
+ if (op === 15) {
2069
+ if(request.length<40 || request[3]!>3)throw new Error("invalid extent composed query");
2070
+ const count=w.getUint32(4,true);if(count>63 || request.length!==40+count*4 || w.getUint32(36,true)!==0)throw new Error("invalid extent composed facts");
2071
+ const tail=(request[3]!&1)!==0,empty=(request[3]!&2)!==0;
2072
+ if((tail&&count!==0) || (tail&&!(v(20)>0)))throw new Error("invalid extent tail facts");
2073
+ let prefix=v(8);for(let i=0;i<count;i++)prefix=f(prefix+v(40+i*4));
2074
+ if(tail)prefix=f(prefix+f(v(16)*f(v(12)/v(20))));
2075
+ const gap=f(v(28)*v(32)),result=new Uint8Array(12),out=new DataView(result.buffer);
2076
+ out.setFloat32(0,prefix,true);out.setFloat32(4,gap,true);out.setFloat32(8,empty?0:f(f(prefix+v(24))+gap),true);return result;
2077
+ }
2078
+ throw new Error("unknown extent policy operation");
2079
+ }
2080
+ function nscvExtentClean(value:number):number{return !Number.isFinite(value) || value < 0 ? 0 : value;}
2081
+ type NscExtentMeasured={index:NscFlowInteger;delta:number;prefix:number};
2082
+ function nscvExtentDistance(a:NscFlowInteger,b:NscFlowInteger):NscFlowInteger{return nscvFlowCompare(a,b)>0?nscvFlowSubtract(a,b):nscvFlowSubtract(b,a);}
2083
+ function nscvExtentCorrections(request:Uint8Array):Uint8Array{
2084
+ if(request.length<64 || request[3]!>5)throw new Error("invalid extent correction header");
2085
+ const w=new DataView(request.buffer,request.byteOffset,request.byteLength), mode=request[3]!, count=w.getUint32(4,true), rows=w.getUint32(8,true), f=Math.fround;
2086
+ if(count>2048 || w.getUint32(12,true)>1 || request.length!==64+count*16+rows*16 || w.getUint32(60,true)!==0 || (mode!==1 && mode!==3 && rows!==0))throw new Error("invalid extent correction table");
2087
+ const base=nscvFlowInteger(w,16), items=nscvFlowInteger(w,24);
2088
+ const anchor=mode===0 || mode===3?nscvFlowMin(nscvFlowInteger(w,32),items):nscvFlowInteger(w,32), logicalAnchor=mode===4 || mode===5?base:nscvFlowAdd(base,anchor,true);
2089
+ const measured:NscExtentMeasured[]=[];
2090
+ for(let i=0;i<count;i++){
2091
+ const at=64+i*16,index=nscvFlowInteger(w,at);
2092
+ if(i>0 && nscvFlowCompare(measured[i-1]!.index,index)>=0)throw new Error("invalid extent measurement ordering");
2093
+ measured.push({index,delta:w.getFloat32(at+8,true),prefix:w.getFloat32(at+12,true)});
2094
+ }
2095
+ let dirty=w.getUint32(12,true)===1,total=w.getFloat32(48,true),pending=w.getFloat32(44,true),before=w.getFloat32(40,true);
2096
+ const deltaBefore=():number=>{
2097
+ if(dirty)throw new Error("dirty extent query");
2098
+ for(const entry of measured)if(nscvFlowCompare(entry.index,logicalAnchor)>=0)return entry.prefix;
2099
+ return total;
2100
+ };
2101
+ if(mode===0 || mode===3){
2102
+ if(dirty)throw new Error("dirty extent correction begin");
2103
+ if(request[2]===0)before=f(f(w.getFloat32(52,true)+deltaBefore())+w.getFloat32(56,true));
2104
+ }
2105
+ if(mode===4){
2106
+ const end=nscvFlowAdd(base,items,true);
2107
+ // Both end truncation and head compaction mark the prefix dirty, even
2108
+ // when no entry drops. Preserve that intermediate state until finish.
2109
+ for(let i=measured.length-1;i>=0;i--)if(nscvFlowCompare(measured[i]!.index,base)<0 || nscvFlowCompare(measured[i]!.index,end)>=0)measured.splice(i,1);
2110
+ dirty=true;
2111
+ }
2112
+ for(let i=0;i<rows;i++){
2113
+ const at=64+count*16+i*16,physical=nscvFlowInteger(w,at);
2114
+ if(nscvFlowCompare(physical,items)>=0)continue;
2115
+ const index=nscvFlowAdd(base,physical,true),delta=f(nscvExtentClean(w.getFloat32(at+12,true))-nscvExtentClean(w.getFloat32(at+8,true)));
2116
+ let slot=0;while(slot<measured.length && nscvFlowCompare(measured[slot]!.index,index)<0)slot++;
2117
+ if(slot<measured.length && nscvFlowCompare(measured[slot]!.index,index)===0){
2118
+ if(Math.abs(f(measured[slot]!.delta-delta))<=0.25)continue;
2119
+ measured[slot]!.delta=delta;dirty=true;continue;
2120
+ }
2121
+ if(Math.abs(delta)<=0.25)continue;
2122
+ if(measured.length>=2048){
2123
+ const first=nscvExtentDistance(measured[0]!.index,logicalAnchor),last=nscvExtentDistance(measured[measured.length-1]!.index,logicalAnchor),incoming=nscvExtentDistance(index,logicalAnchor);
2124
+ const evictLast=nscvFlowCompare(last,first)>=0,far=evictLast?last:first;
2125
+ if(nscvFlowCompare(incoming,far)>=0)continue;
2126
+ measured.splice(evictLast?measured.length-1:0,1);dirty=true;
2127
+ slot=0;while(slot<measured.length && nscvFlowCompare(measured[slot]!.index,index)<0)slot++;
2128
+ }
2129
+ measured.splice(slot,0,{index,delta,prefix:0});dirty=true;
2130
+ }
2131
+ if(mode===2 || mode===3 || mode===5){
2132
+ if(dirty){total=0;for(const entry of measured){entry.prefix=total;total=f(total+entry.delta);}dirty=false;}
2133
+ if(mode!==5)pending=f(pending+f(f(f(w.getFloat32(52,true)+deltaBefore())+w.getFloat32(56,true))-before));
2134
+ }
2135
+ const result=new Uint8Array(32+measured.length*16),out=new DataView(result.buffer);
2136
+ nscvFlowWrite(out,0,anchor);out.setFloat32(8,before,true);out.setFloat32(12,pending,true);out.setFloat32(16,total,true);out.setUint32(20,dirty?1:0,true);out.setUint32(24,measured.length,true);
2137
+ for(let i=0;i<measured.length;i++){const at=32+i*16,e=measured[i]!;nscvFlowWrite(out,at,e.index);out.setFloat32(at+8,e.delta,true);out.setFloat32(at+12,e.prefix,true);}
2138
+ return result;
2139
+ }
2140
+
2141
+ /** Ordered text-layout and glyph-cache reconciliation over copied key facts.
2142
+ * Native supplies hash buckets and stores resources; equality, admission,
2143
+ * retention and eviction belong here. No pointers or arena reset cross this call.
2144
+ */
2145
+ function nscvGlyphAtlasHash(wire: DataView, at: number): number {
2146
+ let hash = 2166136261;
2147
+ // Equality folds signed zero, but retains all 64 font bits. A NaN key
2148
+ // never compares equal, regardless of which bucket holds its bits.
2149
+ const sizeBits = wire.getFloat32(at, true) === 0 ? 0 : wire.getUint32(at, true);
2150
+ hash = Math.imul(hash ^ sizeBits, 16777619) >>> 0;
2151
+ for (let i = 4; i < 24; i += 4) hash = Math.imul(hash ^ wire.getUint32(at + i, true), 16777619) >>> 0;
2152
+ return hash;
2153
+ }
2154
+ function nscvTextCachePolicy(request: Uint8Array): Uint8Array {
2155
+ if (request.length < 48 || request[1]! > 1 || request[2] !== 0 || request[3] !== 0) throw new Error("invalid text cache request");
2156
+ const w = new DataView(request.buffer, request.byteOffset, request.byteLength);
2157
+ const current = w.getUint32(4,true), previous = w.getUint32(8,true), capacity = w.getUint32(12,true), actionCapacity = w.getUint32(16,true), total = current + previous;
2158
+ if (total > 4294967295 || request.length !== 48 + total * 80 || w.getUint32(20,true)!==0 || w.getUint32(40,true)!==0 || w.getUint32(44,true)!==0) throw new Error("invalid text cache shape");
2159
+ const glyph = request[1] === 1, slots = glyph ? 32768 : 8192, indexed = (current >= 64 || previous >= 64) && total <= slots / 2;
2160
+ const bucketFor = (source: number): number => (glyph ? nscvGlyphAtlasHash(w, 48 + source * 80) : w.getUint32(48 + source * 80 + 72, true)) & (slots - 1);
2161
+ const equal = (a:number,b:number):boolean => {
2162
+ const x=48+a*80,y=48+b*80;
2163
+ const floats = glyph ? 1 : 6;
2164
+ for(let i=0;i<floats;i++) if(w.getFloat32(x+i*4,true)!==w.getFloat32(y+i*4,true))return false;
2165
+ const start=glyph?4:24,end=glyph?24:64;
2166
+ for(let i=start;i<end;i++)if(request[x+i]!==request[y+i])return false;
2167
+ return true;
2168
+ };
2169
+ const entries:number[]=[],actions:number[]=[];
2170
+ const prevHeads=new Uint32Array(indexed?slots:0),entryHeads=new Uint32Array(indexed?slots:0),prevNext=new Uint32Array(indexed?previous:0),entryNext=new Uint32Array(indexed?Math.min(capacity,total):0);
2171
+ if(indexed) {
2172
+ // Reverse insertion retains the lowest original index at each chain head.
2173
+ for(let i=previous-1;i>=0;i--){const source=current+i,bucket=bucketFor(source);prevNext[i]=prevHeads[bucket]!;prevHeads[bucket]=i+1;}
2174
+ }
2175
+ const lookup = (source:number,old:boolean):number => {
2176
+ if(indexed){const heads=old?prevHeads:entryHeads,next=old?prevNext:entryNext,bucket=bucketFor(source);let match=-1;
2177
+ for(let stored=heads[bucket]!;stored>0;stored=next[stored-1]!){const i=stored-1;if(equal(source,old?current+i:entries[i]!) && (match<0 || i<match))match=i;}
2178
+ return match;
2179
+ }
2180
+ const count=old?previous:entries.length;
2181
+ for(let i=0;i<count;i++)if(equal(source,old?current+i:entries[i]!))return i;
2182
+ return -1;
2183
+ };
2184
+ let failed=false;
2185
+ const appendEntry=(source:number):boolean=>{if(entries.length>=capacity)return false;const index=entries.length;entries.push(source);if(indexed){const bucket=bucketFor(source);entryNext[index]=entryHeads[bucket]!;entryHeads[bucket]=index+1;}return true;};
2186
+ const appendAction=(kind:number,source:number,cache:number):boolean=>{if(actions.length/3>=actionCapacity)return false;actions.push(kind,source,cache);return true;};
2187
+ for(let i=0;i<current;i++){
2188
+ if(lookup(i,false)>=0)continue;
2189
+ const old=lookup(i,true);
2190
+ if(!appendEntry(i) || !appendAction(old<0?0:1,i,old)){failed=true;break;}
2191
+ }
2192
+ if(!failed)for(let i=0;i<previous;i++){
2193
+ const source=current+i;if(lookup(source,false)>=0)continue;
2194
+ const last={low:w.getUint32(48+source*80+64,true),high:w.getUint32(48+source*80+68,true)},frame={low:w.getUint32(24,true),high:w.getUint32(28,true)},retention={low:w.getUint32(32,true),high:w.getUint32(36,true)};
2195
+ const warm=!nscvFlowZero(retention) && (nscvFlowCompare(frame,last)<=0 || nscvFlowCompare(nscvFlowSubtract(frame,last),retention)<=0);
2196
+ if(warm && entries.length<capacity){if(!appendEntry(source) || !appendAction(1,source,i)){failed=true;break;}}
2197
+ else if(!appendAction(2,source,i)){failed=true;break;}
2198
+ }
2199
+ const result=new Uint8Array(16+entries.length*4+actions.length*4),out=new DataView(result.buffer);
2200
+ out.setUint32(0,entries.length,true);out.setUint32(4,actions.length/3,true);out.setUint32(8,failed?1:0,true);
2201
+ for(let i=0;i<entries.length;i++)out.setUint32(16+i*4,entries[i]!,true);
2202
+ for(let i=0;i<actions.length;i++)out.setUint32(16+entries.length*4+i*4,actions[i]!<0?4294967295:actions[i]!,true);
2203
+ return result;
2204
+ }
2205
+
2206
+ /** Copied render-cache keys. Native retains fingerprints, resources and GPU objects. */
2207
+ function nscvRenderCachePolicy(request: Uint8Array): Uint8Array {
2208
+ if (request.length < 24 || request[1]! > 5 || request[2] !== 0 || request[3] !== 0) throw new Error("invalid render cache request");
2209
+ const input = new DataView(request.buffer, request.byteOffset, request.byteLength);
2210
+ const current = input.getUint32(4, true), previous = input.getUint32(8, true);
2211
+ const capacity = input.getUint32(12, true), actionCapacity = input.getUint32(16, true), total = current + previous;
2212
+ if (total > 4294967295 || request.length !== 24 + total * 56 || input.getUint32(20, true) !== 0) throw new Error("invalid render cache shape");
2213
+ for (let i = 0; i < total; i++) if (input.getUint32(24 + i * 56 + 52, true) !== 0) throw new Error("invalid render cache fact");
2214
+ const indexed = request[1] === 4 && (current >= 64 || previous >= 64) && current <= 2048 && previous <= 2048;
2215
+ const entries = new Uint32Array(Math.min(capacity, current));
2216
+ const actions = new Uint32Array(Math.min(actionCapacity, total) * 3);
2217
+ const previousHeads = new Uint32Array(indexed ? 4096 : 0), entryHeads = new Uint32Array(indexed ? 4096 : 0);
2218
+ const previousNext = new Uint32Array(indexed ? previous : 0), entryNext = new Uint32Array(indexed ? Math.min(capacity, current) : 0);
2219
+ if (indexed) for (let i = previous - 1; i >= 0; i--) {
2220
+ const bucket = input.getUint32(24 + (current + i) * 56 + 48, true) & 4095;
2221
+ previousNext[i] = previousHeads[bucket]!; previousHeads[bucket] = i + 1;
2222
+ }
2223
+ const equal = (a: number, b: number): boolean => {
2224
+ const x = 24 + a * 56, y = 24 + b * 56;
2225
+ for (let i = 0; i < 48; i++) if (request[x + i] !== request[y + i]) return false;
2226
+ return true;
2227
+ };
2228
+ let entryCount = 0, actionCount = 0, failed = false;
2229
+ const lookup = (source: number, old: boolean): number => {
2230
+ if (indexed) {
2231
+ const heads = old ? previousHeads : entryHeads, next = old ? previousNext : entryNext;
2232
+ const bucket = input.getUint32(24 + source * 56 + 48, true) & 4095;
2233
+ let match = -1;
2234
+ for (let stored = heads[bucket]!; stored > 0; stored = next[stored - 1]!) {
2235
+ const i = stored - 1;
2236
+ if (equal(source, old ? current + i : entries[i]!) && (match < 0 || i < match)) match = i;
2237
+ }
2238
+ return match;
2239
+ }
2240
+ for (let i = 0; i < (old ? previous : entryCount); i++) if (equal(source, old ? current + i : entries[i]!)) return i;
2241
+ return -1;
2242
+ };
2243
+ for (let i = 0; i < current; i++) {
2244
+ if (lookup(i, false) >= 0) continue;
2245
+ const old = lookup(i, true);
2246
+ if (actionCount >= actionCapacity) { failed = true; break; }
2247
+ actions[actionCount * 3] = old < 0 ? 0 : 1;
2248
+ actions[actionCount * 3 + 1] = i; actions[actionCount * 3 + 2] = old < 0 ? 4294967295 : old; actionCount++;
2249
+ // Native writes the action first, including when entry capacity then fails.
2250
+ if (entryCount >= capacity) { failed = true; break; }
2251
+ entries[entryCount] = i;
2252
+ if (indexed) {
2253
+ const bucket = input.getUint32(24 + i * 56 + 48, true) & 4095;
2254
+ entryNext[entryCount] = entryHeads[bucket]!; entryHeads[bucket] = entryCount + 1;
2255
+ }
2256
+ entryCount++;
2257
+ }
2258
+ if (!failed) for (let i = 0; i < previous; i++) {
2259
+ const source = current + i;
2260
+ if (lookup(source, false) >= 0) continue;
2261
+ if (actionCount >= actionCapacity) { failed = true; break; }
2262
+ actions[actionCount * 3] = 2; actions[actionCount * 3 + 1] = source; actions[actionCount * 3 + 2] = i; actionCount++;
2263
+ }
2264
+ const result = new Uint8Array(16 + entryCount * 4 + actionCount * 12), output = new DataView(result.buffer);
2265
+ output.setUint32(0, entryCount, true); output.setUint32(4, actionCount, true); output.setUint32(8, failed ? 1 : 0, true);
2266
+ for (let i = 0; i < entryCount; i++) output.setUint32(16 + i * 4, entries[i]!, true);
2267
+ for (let i = 0; i < actionCount * 3; i++) output.setUint32(16 + entryCount * 4 + i * 4, actions[i]!, true);
2268
+ return result;
2269
+ }
2270
+
2271
+ /** Ordered render-state and adjacent-batch coordination. Native supplies local
2272
+ * drawing bounds and primitive tags; commands, identities and resources stay
2273
+ * borrowed natively. Opcode 13 uses copied buffers and never collects an arena.
2274
+ * State replies include every written stack slot and complete partial commands.
2275
+ * Every arithmetic intermediate rounds in the native f32 evaluation order.
2276
+ */
2277
+ interface NscRenderAffine { readonly a: number; readonly b: number; readonly c: number; readonly d: number; readonly tx: number; readonly ty: number; }
2278
+ /** Override coordination copies exact ID words and numerical command facts.
2279
+ * Native retains payloads, geometry providers, animation clocks and resources.
2280
+ * Merging preserves every accepted/replaced prefix on capacity failure.
2281
+ */
2282
+ function nscvRenderOverridePolicy(request: Uint8Array): Uint8Array {
2283
+ if (request.length < 32 || request[1]! > 1 || request[2]! > 15 || request[3] !== 0) throw new Error("invalid render override header");
2284
+ const w = new DataView(request.buffer, request.byteOffset, request.byteLength), mode = request[1]!, flags = request[2]!;
2285
+ const first = w.getUint32(4, true), second = w.getUint32(8, true), commands = w.getUint32(12, true), entries = w.getUint32(16, true), capacity = w.getUint32(20, true);
2286
+ const commandAt = 32 + (first + second) * 40, entryAt = commandAt + commands * 92;
2287
+ if (request.length !== entryAt + entries * 28 || w.getUint32(24, true) !== 0 || w.getUint32(28, true) !== 0 || (mode === 0 && (commands !== 0 || entries !== 0)) || (mode === 1 && capacity !== 0)) throw new Error("invalid render override shape");
2288
+ const idEqual = (a: number, b: number): boolean => w.getUint32(a, true) === w.getUint32(b, true) && w.getUint32(a + 4, true) === w.getUint32(b + 4, true);
2289
+ for (let i = 0; i < first + second; i++) if (w.getUint32(32 + i * 40 + 8, true) > 3) throw new Error("invalid render override flags");
2290
+ for (let i = 0; i < commands; i++) if (w.getUint32(commandAt + i * 92 + 8, true) > 1 || w.getUint32(commandAt + i * 92 + 72, true) > 1) throw new Error("invalid render command flags");
2291
+ for (let i = 0; i < entries; i++) if (w.getUint32(entryAt + i * 28 + 8, true) > 1) throw new Error("invalid render damage flags");
2292
+ if (mode === 0) {
2293
+ const sources = new Uint32Array(Math.min(first + second, capacity));
2294
+ let count = 0, failed = false;
2295
+ for (let i = 0; i < first; i++) {
2296
+ if (count >= capacity) { failed = true; break; }
2297
+ sources[count++] = i;
2298
+ }
2299
+ if (!failed) for (let i = first; i < first + second; i++) {
2300
+ let found = -1;
2301
+ for (let j = 0; j < count; j++) if (idEqual(32 + sources[j]! * 40, 32 + i * 40)) { found = j; break; }
2302
+ if (found >= 0) { sources[found] = i; continue; }
2303
+ if (count >= capacity) { failed = true; break; }
2304
+ sources[count++] = i;
2305
+ }
2306
+ const result = new Uint8Array(16 + count * 4), out = new DataView(result.buffer);
2307
+ out.setUint32(0, count, true); out.setUint32(4, failed ? 1 : 0, true);
2308
+ for (let i = 0; i < count; i++) out.setUint32(16 + i * 4, sources[i]!, true);
2309
+ return result;
2310
+ }
2311
+ const find = (id: number, start: number, count: number): number => {
2312
+ for (let i = 0; i < count; i++) { const at = 32 + (start + i) * 40; if (idEqual(id, at)) return at; }
2313
+ return -1;
2314
+ };
2315
+ const equal = (a: number, b: number): boolean => {
2316
+ if (a < 0 || b < 0) return a === b;
2317
+ const mask = w.getUint32(a + 8, true);
2318
+ if (mask !== w.getUint32(b + 8, true) || !idEqual(a, b)) return false;
2319
+ if ((mask & 1) !== 0 && w.getFloat32(a + 12, true) !== w.getFloat32(b + 12, true)) return false;
2320
+ if ((mask & 2) !== 0) for (let i = 0; i < 6; i++) if (w.getFloat32(a + 16 + i * 4, true) !== w.getFloat32(b + 16 + i * 4, true)) return false;
2321
+ return true;
2322
+ };
2323
+ const union = (a: NscSurfaceRect | null, b: NscSurfaceRect | null): NscSurfaceRect | null => a === null ? b : b === null ? a : nscvRenderUnion(a, b, flags);
2324
+ const transformed = (at: number, override: number): NscSurfaceRect | null => {
2325
+ let transform = nscvRenderAffine(w, at + 16);
2326
+ if (override >= 0 && (w.getUint32(override + 8, true) & 2) !== 0) transform = nscvRenderMultiply(transform, nscvRenderAffine(w, override + 16));
2327
+ let bounds = nscvRenderTransform(transform, nscvRenderRect(w, at + 40), flags);
2328
+ const clip = nscvRenderOptional(w, at + 72);
2329
+ if (clip !== null) bounds = nscvRenderIntersection(bounds, clip, flags);
2330
+ bounds = nscvSurfaceNormalize(bounds);
2331
+ return nscvRenderEmpty(bounds) ? null : bounds;
2332
+ };
2333
+ let dirty: NscSurfaceRect | null = null, bounds: NscSurfaceRect | null = null, animationDirty: NscSurfaceRect | null = null;
2334
+ const result = new Uint8Array(64 + commands * 44), out = new DataView(result.buffer);
2335
+ out.setUint32(0, commands, true);
2336
+ // Damage observes original command transforms, before any override applies.
2337
+ for (let i = 0; i < commands; i++) {
2338
+ const at = commandAt + i * 92, hasId = w.getUint32(at + 8, true) === 1;
2339
+ const old = hasId ? find(at, 0, first) : -1, next = hasId ? find(at, first, second) : -1;
2340
+ if (!equal(old, next)) { dirty = union(dirty, transformed(at, old)); dirty = union(dirty, transformed(at, next)); }
2341
+ let opacity = w.getFloat32(at + 12, true), transform = nscvRenderAffine(w, at + 16), rect = nscvRenderRect(w, at + 56);
2342
+ if (next >= 0) {
2343
+ const mask = w.getUint32(next + 8, true);
2344
+ if ((mask & 1) !== 0) opacity = Math.fround(opacity * nscvRenderExtreme(0, nscvRenderExtreme(w.getFloat32(next + 12, true), 1, flags, false), flags, true));
2345
+ if ((mask & 2) !== 0) { transform = nscvRenderMultiply(transform, nscvRenderAffine(w, next + 16)); rect = transformed(at, next) ?? { x: 0, y: 0, width: 0, height: 0 }; }
2346
+ }
2347
+ const target = 64 + i * 44;
2348
+ out.setFloat32(target, opacity, true); nscvRenderPutAffine(out, target + 4, transform); nscvRenderPutRect(out, target + 28, rect);
2349
+ bounds = union(bounds, rect);
2350
+ }
2351
+ for (let i = 0; i < entries; i++) {
2352
+ const at = entryAt + i * 28;
2353
+ if (find(at, 0, first) < 0 && find(at, first, second) < 0) continue;
2354
+ const rect = nscvRenderOptional(w, at + 8);
2355
+ if (rect === null) { if (animationDirty !== null) animationDirty = nscvSurfaceNormalize(animationDirty); }
2356
+ else animationDirty = animationDirty === null ? nscvSurfaceNormalize(rect) : nscvRenderUnion(animationDirty, rect, flags);
2357
+ }
2358
+ nscvRenderPutOptional(out, 4, bounds); nscvRenderPutOptional(out, 24, dirty); nscvRenderPutOptional(out, 44, animationDirty);
2359
+ return result;
2360
+ }
2361
+ function nscvRenderExtreme(a: number, b: number, flags: number, maximum: boolean): number {
2362
+ if (a === 0 && b === 0) {
2363
+ const an = 1 / a < 0, bn = 1 / b < 0;
2364
+ if (an === bn) return a;
2365
+ return (flags & (1 << ((maximum ? 2 : 0) + (an ? 0 : 1)))) !== 0 ? -0 : 0;
2366
+ }
2367
+ return maximum ? nscvSurfaceMax(a, b) : nscvSurfaceMin(a, b);
2368
+ }
2369
+ function nscvRenderRect(w: DataView, at: number): NscSurfaceRect {
2370
+ return { x: w.getFloat32(at, true), y: w.getFloat32(at + 4, true), width: w.getFloat32(at + 8, true), height: w.getFloat32(at + 12, true) };
2371
+ }
2372
+ function nscvRenderPutRect(w: DataView, at: number, r: NscSurfaceRect): void {
2373
+ w.setFloat32(at, r.x, true); w.setFloat32(at + 4, r.y, true); w.setFloat32(at + 8, r.width, true); w.setFloat32(at + 12, r.height, true);
2374
+ }
2375
+ function nscvRenderOptional(w: DataView, at: number): NscSurfaceRect | null { return w.getUint32(at, true) === 0 ? null : nscvRenderRect(w, at + 4); }
2376
+ function nscvRenderPutOptional(w: DataView, at: number, r: NscSurfaceRect | null): void {
2377
+ w.setUint32(at, r === null ? 0 : 1, true);
2378
+ nscvRenderPutRect(w, at + 4, r === null ? { x: 0, y: 0, width: 0, height: 0 } : r);
2379
+ }
2380
+ function nscvRenderAffine(w: DataView, at: number): NscRenderAffine {
2381
+ return { a: w.getFloat32(at, true), b: w.getFloat32(at + 4, true), c: w.getFloat32(at + 8, true), d: w.getFloat32(at + 12, true), tx: w.getFloat32(at + 16, true), ty: w.getFloat32(at + 20, true) };
2382
+ }
2383
+ function nscvRenderPutAffine(w: DataView, at: number, t: NscRenderAffine): void {
2384
+ w.setFloat32(at, t.a, true); w.setFloat32(at + 4, t.b, true); w.setFloat32(at + 8, t.c, true); w.setFloat32(at + 12, t.d, true); w.setFloat32(at + 16, t.tx, true); w.setFloat32(at + 20, t.ty, true);
2385
+ }
2386
+ function nscvRenderMultiply(t: NscRenderAffine, u: NscRenderAffine): NscRenderAffine {
2387
+ const f = Math.fround;
2388
+ return { a: f(f(t.a * u.a) + f(t.c * u.b)), b: f(f(t.b * u.a) + f(t.d * u.b)), c: f(f(t.a * u.c) + f(t.c * u.d)), d: f(f(t.b * u.c) + f(t.d * u.d)),
2389
+ tx: f(f(f(t.a * u.tx) + f(t.c * u.ty)) + t.tx), ty: f(f(f(t.b * u.tx) + f(t.d * u.ty)) + t.ty) };
2390
+ }
2391
+ function nscvRenderTransform(t: NscRenderAffine, rect: NscSurfaceRect, flags: number): NscSurfaceRect {
2392
+ const r = nscvSurfaceNormalize(rect), f = Math.fround;
2393
+ let minX = f(f(f(t.a * r.x) + f(t.c * r.y)) + t.tx), minY = f(f(f(t.b * r.x) + f(t.d * r.y)) + t.ty), maxX = minX, maxY = minY;
2394
+ for (let i = 1; i < 4; i++) {
2395
+ const x = (i & 1) !== 0 ? nscvSurfaceRight(r) : r.x, y = i >= 2 ? nscvSurfaceBottom(r) : r.y;
2396
+ const px = f(f(f(t.a * x) + f(t.c * y)) + t.tx), py = f(f(f(t.b * x) + f(t.d * y)) + t.ty);
2397
+ minX = nscvRenderExtreme(minX, px, flags, false); minY = nscvRenderExtreme(minY, py, flags, false);
2398
+ maxX = nscvRenderExtreme(maxX, px, flags, true); maxY = nscvRenderExtreme(maxY, py, flags, true);
2399
+ }
2400
+ return { x: minX, y: minY, width: f(maxX - minX), height: f(maxY - minY) };
2401
+ }
2402
+ function nscvRenderEmpty(r: NscSurfaceRect): boolean { return r.width <= 0 || r.height <= 0; }
2403
+ function nscvRenderIntersection(a: NscSurfaceRect, b: NscSurfaceRect, flags: number): NscSurfaceRect {
2404
+ const x = nscvRenderExtreme(a.x, b.x, flags, true), y = nscvRenderExtreme(a.y, b.y, flags, true), right = nscvRenderExtreme(nscvSurfaceRight(a), nscvSurfaceRight(b), flags, false), bottom = nscvRenderExtreme(nscvSurfaceBottom(a), nscvSurfaceBottom(b), flags, false);
2405
+ return { x, y, width: right <= x || bottom <= y ? 0 : Math.fround(right - x), height: right <= x || bottom <= y ? 0 : Math.fround(bottom - y) };
2406
+ }
2407
+ function nscvRenderUnion(left: NscSurfaceRect, right: NscSurfaceRect, flags: number): NscSurfaceRect {
2408
+ const a = nscvSurfaceNormalize(left), b = nscvSurfaceNormalize(right);
2409
+ if (nscvRenderEmpty(a) && nscvRenderEmpty(b)) return { x: 0, y: 0, width: 0, height: 0 };
2410
+ if (nscvRenderEmpty(a)) return b;
2411
+ if (nscvRenderEmpty(b)) return a;
2412
+ const x = nscvRenderExtreme(a.x, b.x, flags, false), y = nscvRenderExtreme(a.y, b.y, flags, false);
2413
+ return { x, y, width: Math.fround(nscvRenderExtreme(nscvSurfaceRight(a), nscvSurfaceRight(b), flags, true) - x), height: Math.fround(nscvRenderExtreme(nscvSurfaceBottom(a), nscvSurfaceBottom(b), flags, true) - y) };
2414
+ }
2415
+ function nscvRenderRectEqual(a: NscSurfaceRect | null, b: NscSurfaceRect | null): boolean {
2416
+ return a === null ? b === null : b !== null && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
2417
+ }
2418
+ function nscvRenderPlanPolicy(request: Uint8Array): Uint8Array {
2419
+ if (request.length < 16 || request[1]! > 1 || request[2]! > 15 || request[3] !== 0) throw new Error("invalid render planning header");
2420
+ const w = new DataView(request.buffer, request.byteOffset, request.byteLength), mode = request[1]!, flags = request[2]!, count = w.getUint32(4, true), capacity = w.getUint32(8, true), header = mode === 0 ? 16 : 32;
2421
+ if (request.length !== header + count * 48 + (mode === 0 ? w.getUint32(12, true) : 0) || (mode === 1 && w.getUint32(12, true) > 1)) throw new Error("invalid render planning shape");
2422
+ for (let i = 0; i < count; i++) {
2423
+ const at = header + i * 48, kind = w.getUint32(at, true);
2424
+ if (kind > 14 || w.getUint32(at + 4, true) > (mode === 0 && kind === 12 ? 2 : 1) || (mode === 1 && w.getUint32(at + 12, true) > 1)) throw new Error("invalid render planning fact");
2425
+ }
2426
+ if (mode === 1) return nscvRenderBatches(w, count, capacity, flags);
2427
+ const result = new Uint8Array(864 + Math.min(count, capacity) * 68), out = new DataView(result.buffer), f = Math.fround, resume = w.getUint32(12, true);
2428
+ let start = 0;
2429
+ if (resume !== 0) {
2430
+ const at = 16 + count * 48;
2431
+ if (resume < 864 || resume > result.length || w.getUint32(at + 4, true) !== 4 || resume !== 864 + w.getUint32(at, true) * 68 || w.getUint32(at + 16, true) > 32 || w.getUint32(at + 20, true) > 32 || w.getUint32(at + 8, true) > w.getUint32(at + 16, true) || w.getUint32(at + 12, true) > w.getUint32(at + 20, true)) throw new Error("invalid render continuation state");
2432
+ result.set(request.subarray(at, at + resume)); start = out.getUint32(860, true);
2433
+ if (start >= count || w.getUint32(16 + start * 48 + 4, true) === 2) throw new Error("unresolved render continuation fact");
2434
+ }
2435
+ let opacity = resume === 0 ? 1 : out.getFloat32(24, true), transform: NscRenderAffine = resume === 0 ? { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 } : nscvRenderAffine(out, 48), clip: NscSurfaceRect | null = resume === 0 ? null : nscvRenderOptional(out, 28), bounds: NscSurfaceRect | null = resume === 0 ? null : nscvRenderOptional(out, 72);
2436
+ let clips = resume === 0 ? 0 : out.getUint32(8, true), opacities = resume === 0 ? 0 : out.getUint32(12, true), clipWritten = resume === 0 ? 0 : out.getUint32(16, true), opacityWritten = resume === 0 ? 0 : out.getUint32(20, true), emitted = resume === 0 ? 0 : out.getUint32(0, true), failed = 0, pending = 0;
2437
+ for (let i = start; i < count; i++) {
2438
+ const at = 16 + i * 48, kind = w.getUint32(at, true);
2439
+ if (kind === 0) {
2440
+ if (clips === 32) { failed = 1; break; }
2441
+ nscvRenderPutOptional(out, 92 + clips * 20, clip); clips++; clipWritten = Math.max(clipWritten, clips);
2442
+ const next = nscvRenderTransform(transform, nscvRenderRect(w, at + 8), flags);
2443
+ clip = clip === null ? next : nscvRenderIntersection(clip, next, flags);
2444
+ } else if (kind === 1) {
2445
+ if (clips === 0) { failed = 2; break; }
2446
+ clips--; clip = nscvRenderOptional(out, 92 + clips * 20);
2447
+ } else if (kind === 2) {
2448
+ if (opacities === 32) { failed = 1; break; }
2449
+ out.setFloat32(732 + opacities * 4, opacity, true); opacities++; opacityWritten = Math.max(opacityWritten, opacities);
2450
+ opacity = f(opacity * nscvRenderExtreme(0, nscvRenderExtreme(w.getFloat32(at + 8, true), 1, flags, false), flags, true));
2451
+ } else if (kind === 3) {
2452
+ if (opacities === 0) { failed = 2; break; }
2453
+ opacities--; opacity = out.getFloat32(732 + opacities * 4, true);
2454
+ } else if (kind === 4) transform = nscvRenderMultiply(transform, nscvRenderAffine(w, at + 24));
2455
+ else if (!(opacity <= 0) && w.getUint32(at + 4, true) !== 0) {
2456
+ if (w.getUint32(at + 4, true) === 2) { failed = 4; pending = i; break; }
2457
+ const local = nscvRenderRect(w, at + 8), transformed = nscvRenderTransform(transform, local, flags), visible = clip === null ? transformed : nscvRenderIntersection(clip, transformed, flags);
2458
+ if (nscvRenderEmpty(visible)) continue;
2459
+ if (emitted === capacity) { failed = 3; break; }
2460
+ const target = 864 + emitted * 68;
2461
+ out.setUint32(target, i, true); out.setFloat32(target + 4, opacity, true); nscvRenderPutOptional(out, target + 8, clip); nscvRenderPutAffine(out, target + 28, transform); nscvRenderPutRect(out, target + 52, visible);
2462
+ emitted++; bounds = bounds === null ? visible : nscvRenderUnion(bounds, visible, flags);
2463
+ }
2464
+ }
2465
+ out.setUint32(0, emitted, true); out.setUint32(4, failed, true); out.setUint32(8, clips, true); out.setUint32(12, opacities, true); out.setUint32(16, clipWritten, true); out.setUint32(20, opacityWritten, true);
2466
+ out.setFloat32(24, opacity, true); nscvRenderPutOptional(out, 28, clip); nscvRenderPutAffine(out, 48, transform); nscvRenderPutOptional(out, 72, bounds);
2467
+ out.setUint32(860, pending, true);
2468
+ return result.subarray(0, 864 + emitted * 68);
2469
+ }
2470
+ function nscvRenderBatches(w: DataView, count: number, capacity: number, flags: number): Uint8Array {
2471
+ const result = new Uint8Array(32 + Math.min(count, capacity) * 52), out = new DataView(result.buffer);
2472
+ nscvRenderPutOptional(out, 8, nscvRenderOptional(w, 12));
2473
+ let emitted = 0, failed = 0;
2474
+ for (let i = 0; i < count; i++) {
2475
+ const at = 32 + i * 48, kind = w.getUint32(at, true), fill = w.getUint32(at + 4, true), opacity = w.getFloat32(at + 8, true), clip = nscvRenderOptional(w, at + 12), bounds = nscvRenderRect(w, at + 32);
2476
+ const pipeline = kind <= 4 ? 0 : kind <= 8 ? fill : kind <= 10 ? 4 : kind === 11 ? 2 : kind === 12 ? 3 : kind === 13 ? 5 : 6;
2477
+ const previous = 32 + (emitted - 1) * 52;
2478
+ if (emitted > 0 && out.getUint32(previous, true) === pipeline && out.getUint32(previous + 4, true) + out.getUint32(previous + 8, true) === i && out.getFloat32(previous + 12, true) === opacity && nscvRenderRectEqual(nscvRenderOptional(out, previous + 16), clip)) {
2479
+ out.setUint32(previous + 8, out.getUint32(previous + 8, true) + 1, true); nscvRenderPutRect(out, previous + 36, nscvRenderUnion(nscvRenderRect(out, previous + 36), bounds, flags));
2480
+ } else {
2481
+ if (emitted === capacity) { failed = 4; break; }
2482
+ const target = 32 + emitted * 52;
2483
+ out.setUint32(target, pipeline, true); out.setUint32(target + 4, i, true); out.setUint32(target + 8, 1, true); out.setFloat32(target + 12, opacity, true); nscvRenderPutOptional(out, target + 16, clip); nscvRenderPutRect(out, target + 36, bounds); emitted++;
2484
+ }
2485
+ }
2486
+ out.setUint32(0, emitted, true); out.setUint32(4, failed, true);
2487
+ return result.subarray(0, 32 + emitted * 52);
2488
+ }
2489
+
2490
+ /** Final damage coordination uses copied numeric and exact-key facts. Native
2491
+ * owns drawing payloads, fingerprints, platform sampling support and storage.
2492
+ * Modes: diagnostic, presentation, effective-scale widening, retained edits.
2493
+ * Device clipping precedes f32 encoding; edge walks compare exact f64 products.
2494
+ */
2495
+ function nscvRenderDamagePolicy(request: Uint8Array): Uint8Array {
2496
+ if (request.length < 128 || request[1]! > 3 || request[2]! > 15 || request[3]! > 3) throw new Error("invalid render damage header");
2497
+ const w = new DataView(request.buffer, request.byteOffset, request.byteLength), mode = request[1]!, flags = request[2]!;
2498
+ const changes = w.getUint32(104, true), rectCount = w.getUint32(108, true), blurs = w.getUint32(112, true), baseline = w.getUint32(116, true), current = w.getUint32(120, true), capacity = w.getUint32(124, true);
2499
+ const rectAt = 128 + changes * 20, blurAt = rectAt + rectCount * 16, baselineAt = blurAt + blurs * 68, currentAt = baselineAt + baseline * 32;
2500
+ if (request.length !== currentAt + current * 32 || capacity < 1 || capacity > 8 || rectCount > capacity || (mode !== 3 && (baseline !== 0 || current !== 0)) || (mode === 3 && (changes !== 0 || rectCount !== 0 || blurs !== 0))) throw new Error("invalid render damage shape");
2501
+ for (let i = 0; i < 4; i++) if (w.getUint32(16 + i * 20, true) > 1) throw new Error("invalid render damage bounds");
2502
+ for (let i = 0; i < changes; i++) if (w.getUint32(128 + i * 20, true) > 1) throw new Error("invalid render damage change");
2503
+ for (let i = 0; i < blurs; i++) if (w.getUint32(blurAt + i * 68 + 40, true) > 1) throw new Error("invalid render damage clip");
2504
+ const f = Math.fround, extreme = (a: number, b: number, maximum: boolean): number => nscvRenderExtreme(a, b, flags, maximum);
2505
+ const union = (a: NscSurfaceRect | null, b: NscSurfaceRect | null): NscSurfaceRect | null => a === null ? b === null ? null : nscvSurfaceNormalize(b) : b === null ? nscvSurfaceNormalize(a) : nscvRenderUnion(a, b, flags);
2506
+ const intersects = (a: NscSurfaceRect, b: NscSurfaceRect): boolean => !nscvRenderEmpty(nscvRenderIntersection(a, b, flags));
2507
+ const clusters: NscSurfaceRect[] = [];
2508
+ let bounds: NscSurfaceRect | null = null;
2509
+ const add = (rect: NscSurfaceRect): void => {
2510
+ const normalized = nscvSurfaceNormalize(rect);
2511
+ if (nscvRenderEmpty(normalized)) return;
2512
+ bounds = union(bounds, normalized);
2513
+ for (let i = 0; i < clusters.length; i++) if (intersects(clusters[i]!, normalized)) { clusters[i] = nscvRenderUnion(clusters[i]!, normalized, flags); return; }
2514
+ if (clusters.length < capacity) { clusters.push(normalized); return; }
2515
+ let best = 0, cost = 3.4028234663852886e38;
2516
+ for (let i = 0; i < clusters.length; i++) {
2517
+ const cluster = clusters[i]!, merged = nscvRenderUnion(cluster, normalized, flags), delta = f(f(merged.width * merged.height) - f(cluster.width * cluster.height));
2518
+ if (delta < cost) { best = i; cost = delta; }
2519
+ }
2520
+ clusters[best] = nscvRenderUnion(clusters[best]!, normalized, flags);
2521
+ };
2522
+ const matched = new Uint8Array(baseline), stable = new Uint8Array(baseline), upsert = new Uint8Array(current);
2523
+ let valid = true;
2524
+ if (mode === 3) {
2525
+ // Open addressing changes lookup cost, never first-match or draw order.
2526
+ let slots = 64;
2527
+ while (slots < baseline * 2) slots *= 2;
2528
+ const table = new Uint32Array(slots);
2529
+ const equalKey = (a: number, b: number): boolean => w.getUint32(a, true) === w.getUint32(b, true) && w.getUint32(a + 4, true) === w.getUint32(b + 4, true);
2530
+ const hash = (at: number): number => (w.getUint32(at, true) ^ w.getUint32(at + 4, true)) >>> 0;
2531
+ for (let i = 0; i < baseline; i++) {
2532
+ const at = baselineAt + i * 32;
2533
+ let slot = hash(at) % slots;
2534
+ while (table[slot]! !== 0 && !equalKey(at, baselineAt + (table[slot]! - 1) * 32)) slot = (slot + 1) % slots;
2535
+ if (table[slot]! === 0) table[slot] = i + 1;
2536
+ }
2537
+ for (let i = 0; i < current; i++) {
2538
+ const at = currentAt + i * 32;
2539
+ let slot = hash(at) % slots;
2540
+ while (table[slot]! !== 0 && !equalKey(at, baselineAt + (table[slot]! - 1) * 32)) slot = (slot + 1) % slots;
2541
+ upsert[i] = 1;
2542
+ if (table[slot]! !== 0) {
2543
+ const index = table[slot]! - 1, old = baselineAt + index * 32;
2544
+ matched[index] = 1;
2545
+ if (w.getUint32(at + 8, true) === w.getUint32(old + 8, true) && w.getUint32(at + 12, true) === w.getUint32(old + 12, true)) { stable[index] = 1; upsert[i] = 0; continue; }
2546
+ add(nscvRenderRect(w, old + 16));
2547
+ }
2548
+ add(nscvRenderRect(w, at + 16));
2549
+ }
2550
+ for (let i = 0; i < baseline; i++) if (matched[i] === 0) add(nscvRenderRect(w, baselineAt + i * 32 + 16));
2551
+ let walk = 0;
2552
+ for (let i = 0; i < current; i++) {
2553
+ if (upsert[i] !== 0) continue;
2554
+ while (walk < baseline && stable[walk] === 0) walk++;
2555
+ if (walk >= baseline || !equalKey(baselineAt + walk * 32, currentAt + i * 32)) { valid = false; break; }
2556
+ walk++;
2557
+ }
2558
+ }
2559
+ const scale = w.getFloat32(12, true), surface = nscvSurfaceNormalize({ x: 0, y: 0, width: w.getFloat32(4, true), height: w.getFloat32(8, true) });
2560
+ const render = nscvRenderOptional(w, 16), fullBounds = nscvRenderEmpty(surface) ? render : surface;
2561
+ let full = (request[3]! & 1) !== 0, count = clusters.length;
2562
+ const written: NscSurfaceRect[] = [];
2563
+ if (mode === 3) for (const cluster of clusters) written.push(cluster);
2564
+ else if (mode === 2) {
2565
+ bounds = render;
2566
+ if (full || scale === w.getFloat32(100, true)) {
2567
+ for (let i = 0; i < rectCount; i++) written.push(nscvRenderRect(w, rectAt + i * 16));
2568
+ count = rectCount;
2569
+ } else {
2570
+ bounds = nscvDamageSnap(bounds, scale, w.getFloat32(4, true), w.getFloat32(8, true), flags);
2571
+ for (let i = 0; i < rectCount; i++) { const rect = nscvDamageSnap(nscvRenderRect(w, rectAt + i * 16), scale, w.getFloat32(4, true), w.getFloat32(8, true), flags); if (rect !== null) written.push(rect); }
2572
+ count = written.length < 2 ? 0 : written.length;
2573
+ }
2574
+ } else if (full) bounds = fullBounds;
2575
+ else {
2576
+ const overrides = mode === 0 ? nscvRenderOptional(w, 36) : union(nscvRenderOptional(w, 36), nscvRenderOptional(w, 56));
2577
+ if (mode === 1 && (request[3]! & 2) !== 0) {
2578
+ bounds = nscvRenderOptional(w, 76);
2579
+ for (let i = 0; i < rectCount; i++) clusters.push(nscvRenderRect(w, rectAt + i * 16));
2580
+ if (overrides !== null) add(overrides);
2581
+ bounds = nscvDamageSnap(bounds, scale, w.getFloat32(4, true), w.getFloat32(8, true), flags);
2582
+ if (bounds !== null && clusters.length > 1) for (const cluster of clusters) { const aligned = nscvDamageSnap(cluster, scale, w.getFloat32(4, true), w.getFloat32(8, true), flags); if (aligned !== null) written.push(aligned); }
2583
+ } else {
2584
+ for (let i = 0; i < changes; i++) bounds = union(bounds, nscvRenderOptional(w, 128 + i * 20));
2585
+ bounds = nscvDamageSnap(union(bounds, overrides), scale, w.getFloat32(4, true), w.getFloat32(8, true), flags);
2586
+ }
2587
+ count = written.length < 2 ? 0 : written.length;
2588
+ const requested = w.getFloat32(96, true), multiplier = Number.isFinite(requested) ? extreme(1, requested, true) : 1;
2589
+ for (let i = 0; i < blurs; i++) {
2590
+ const at = blurAt + i * 68, radius = w.getFloat32(at + 64, true), opacity = w.getFloat32(at + 60, true);
2591
+ if (!(radius > 0) || !(opacity > 0)) continue;
2592
+ const rect = nscvSurfaceNormalize(nscvRenderRect(w, at)), transform = nscvRenderAffine(w, at + 16), clip = nscvRenderOptional(w, at + 40);
2593
+ let output = nscvRenderTransform(transform, rect, flags);
2594
+ if (clip !== null) output = nscvRenderIntersection(output, nscvSurfaceNormalize(clip), flags);
2595
+ if (nscvRenderEmpty(output)) continue;
2596
+ let footprint: NscSurfaceRect;
2597
+ if (multiplier === 1) footprint = nscvSurfaceNormalize(nscvRenderTransform(transform, nscvDamageInflate(rect, extreme(0, radius, true)), flags));
2598
+ else {
2599
+ const x = f(Math.sqrt(f(f(transform.a * transform.a) + f(transform.b * transform.b)))), y = f(Math.sqrt(f(f(transform.c * transform.c) + f(transform.d * transform.d))));
2600
+ const extent = f(f(extreme(0, radius, true) * extreme(f(0.0001), extreme(x, y, true), true)) * multiplier);
2601
+ footprint = nscvDamageInflate(nscvSurfaceNormalize(output), extent);
2602
+ }
2603
+ if (count === 0 ? bounds !== null && intersects(footprint, nscvSurfaceNormalize(bounds)) : written.some((dirty) => intersects(footprint, nscvSurfaceNormalize(dirty)))) { full = true; bounds = fullBounds; count = 0; break; }
2604
+ }
2605
+ }
2606
+ const result = new Uint8Array(64 + written.length * 16 + baseline * 2 + current), out = new DataView(result.buffer);
2607
+ out.setUint32(0, full ? 1 : 0, true); out.setUint32(4, count, true); out.setUint32(8, written.length, true); out.setUint32(12, valid ? 1 : 0, true);
2608
+ nscvRenderPutOptional(out, 16, bounds);
2609
+ for (let i = 0; i < written.length; i++) nscvRenderPutRect(out, 64 + i * 16, written[i]!);
2610
+ let at = 64 + written.length * 16;
2611
+ for (let i = 0; i < baseline; i++) { result[at++] = matched[i]!; result[at++] = stable[i]!; }
2612
+ for (let i = 0; i < current; i++) result[at++] = upsert[i]!;
2613
+ return result;
2614
+ }
2615
+ function nscvDamageInflate(r: NscSurfaceRect, extent: number): NscSurfaceRect {
2616
+ const f = Math.fround;
2617
+ return { x: f(r.x - extent), y: f(r.y - extent), width: f(f(r.width + extent) + extent), height: f(f(r.height + extent) + extent) };
2618
+ }
2619
+ function nscvDamageSnap(bounds: NscSurfaceRect | null, scale: number, width: number, height: number, flags: number): NscSurfaceRect | null {
2620
+ if (bounds === null) return null;
2621
+ const f = Math.fround, r = nscvSurfaceNormalize(bounds), device = Number.isFinite(scale) && scale > 0 ? scale : 1;
2622
+ const bits = new DataView(new ArrayBuffer(4));
2623
+ const next = (value: number, up: boolean): number => {
2624
+ if (Number.isNaN(value) || value === (up ? Infinity : -Infinity)) return value;
2625
+ if (value === 0) { bits.setUint32(0, up ? 1 : 2147483649, true); return bits.getFloat32(0, true); }
2626
+ bits.setFloat32(0, value, true);
2627
+ const raw = bits.getUint32(0, true); bits.setUint32(0, raw + ((value > 0) === up ? 1 : -1), true);
2628
+ return bits.getFloat32(0, true);
2629
+ };
2630
+ const extreme = (a: number, b: number, maximum: boolean): number => nscvRenderExtreme(a, b, flags, maximum);
2631
+ const nudge = (value: number, up: boolean): number => {
2632
+ if (Number.isNaN(value)) return 0;
2633
+ const limit = 3.4028234663852886e38;
2634
+ let edge = extreme(-limit, extreme(value, limit, false), true);
2635
+ edge = next(next(edge, up), up);
2636
+ return extreme(-limit, extreme(edge, limit, false), true);
2637
+ };
2638
+ const axis = (low: number, high: number, extent: number): NscDamageAxis | null => {
2639
+ let min = f(Math.floor(f(low * device)) - 1), max = f(Math.ceil(f(high * device)) + 1);
2640
+ if (Number.isFinite(extent) && extent > 0) {
2641
+ const surface = Math.ceil(f(extent * device));
2642
+ if (Number.isFinite(surface)) {
2643
+ min = extreme(0, extreme(min, surface, false), true); max = extreme(0, extreme(max, surface, false), true);
2644
+ if (!(max > min)) return null;
2645
+ }
2646
+ }
2647
+ if (!(min >= -16777216 && min <= 16777216 && max >= -16777216 && max <= 16777216)) {
2648
+ const edge = nudge(f(min / device), false), end = nudge(f(max / device), true);
2649
+ let span = extreme(0, nudge(f(end - edge), true), true);
2650
+ while (span > 0 && !Number.isFinite(f(edge + span))) span = next(span, false);
2651
+ return { edge, span };
2652
+ }
2653
+ let edge = f(min / device);
2654
+ while (edge * device >= min) edge = next(edge, false);
2655
+ while (edge * device < min) edge = next(edge, true);
2656
+ if (edge === 0) edge = 0;
2657
+ let target = f(max / device);
2658
+ while (target * device <= max) target = next(target, true);
2659
+ while (target * device > max) target = next(target, false);
2660
+ if (target <= edge) return { edge, span: 0 };
2661
+ let span = f(target - edge);
2662
+ while (span > 0 && edge + span > target) { const smaller = next(span, false); if (smaller === span) return { edge, span: 0 }; span = smaller; }
2663
+ return { edge, span: span <= 0 ? 0 : span };
2664
+ };
2665
+ const x = axis(r.x, nscvSurfaceRight(r), width), y = axis(r.y, nscvSurfaceBottom(r), height);
2666
+ if (x === null || y === null || x.span <= 0 || y.span <= 0) return null;
2667
+ return { x: x.edge, y: y.edge, width: x.span, height: y.span };
2668
+ }
2669
+ interface NscDamageAxis { readonly edge: number; readonly span: number; }
2670
+
2671
+ /** Routed requests borrow all 36 native-owned slots: 16 host, 16 record-store,
2672
+ * four credentials. Admission preserves cross-pool cancellation before capacity
2673
+ * refusal. Completion returns owned routing data and copies opaque channel words.
2674
+ */
2675
+ function requestCoordinationPolicy(request: Uint8Array): Uint8Array {
2676
+ if (request.length < 16 || request[1]! > 3 || request[2]! > 2 || request[4]! > 1 || request[5]! > 1 || request[8]! > 1 || request[9]! > 1 || request[11]! > 1)
2677
+ throw new Error("invalid request coordination header");
2678
+ for (let i = 12; i < 16; i++) if (request[i] !== 0) throw new Error("reserved request coordination byte");
2679
+ const action = request[1]!, length = request[3]!;
2680
+ const positions = new DataView(new ArrayBuffer(36 * 4));
2681
+ let at = 16 + length, matching = -1, free = -1;
2682
+ const first = request[2] === 0 ? 0 : request[2] === 1 ? 16 : 32;
2683
+ const end = request[2] === 0 ? 16 : request[2] === 1 ? 32 : 36;
2684
+ for (let slot = 0; slot < 36; slot++) {
2685
+ if (at + 2 > request.length) throw new Error("truncated request coordination table");
2686
+ const size = request[at + 1]!, route = at + 2 + size;
2687
+ if (route + 13 > request.length || request[at]! > 1 || request[route + 2]! > 1 || request[route + 3]! > 1 || request[route + 4]! > 1)
2688
+ throw new Error("invalid request coordination slot");
2689
+ positions.setUint32(slot * 4, at, true);
2690
+ let equal = request[at] === 1 && size === length;
2691
+ for (let i = 0; i < size; i++) if (request[at + 2 + i] !== request[16 + i]) equal = false;
2692
+ if (equal && matching < 0) matching = slot;
2693
+ if (request[at] === 0 && slot >= first && slot < end && free < 0) free = slot;
2694
+ at = route + 13;
2695
+ }
2696
+ if (at !== request.length) throw new Error("trailing request coordination bytes");
2697
+ const result = new Uint8Array(16);
2698
+ result[0] = 255; result[1] = 255;
2699
+ if (action === 1) { result[0] = matching < 0 ? 255 : matching; return result; }
2700
+ if (action === 2) {
2701
+ const slot = request[10]!;
2702
+ if (slot >= 36) throw new Error("request result slot is out of bounds");
2703
+ const entry = positions.getUint32(slot * 4, true), route = entry + 2 + request[entry + 1]!;
2704
+ if (request[entry] !== 1) throw new Error("request result has no tracked owner");
2705
+ const ok = request[9] === 1;
2706
+ result[0] = slot; result[2] = request[route + (ok ? 0 : 1)]!;
2707
+ result[3] = ok && request[route + 3] === 1 ? 2 : ok && request[route + 2] === 1 ? 1 : 0;
2708
+ result[4] = 1; result[5] = request[route + 4]!;
2709
+ if (result[5] === 1) for (let i = 0; i < 8; i++) result[8 + i] = request[route + 5 + i]!;
2710
+ return result;
2711
+ }
2712
+ if (action === 3) {
2713
+ // Duplicate/collision refusal precedes capacity, which precedes channel
2714
+ // ownership refusal. The engine's actual channel admission follows this.
2715
+ result[3] = length > 0 && (matching >= 0 || request[4] === 1) ? 1 : free < 0 ? 2 : request[11] === 1 ? 3 : 0;
2716
+ result[0] = free < 0 ? 255 : free;
2717
+ return result;
2718
+ }
2719
+ result[2] = request[6]!; result[3] = request[7]!; result[4] = request[8]!;
2720
+ if (request[4] === 1 || length > 0 && matching >= 0 && request[5] === 1) return result;
2721
+ if (length > 0 && matching >= 0) {
2722
+ if (matching >= first && matching < end) { result[0] = matching; return result; }
2723
+ result[1] = matching; // Retire the old pool even if the destination is full.
2724
+ }
2725
+ result[0] = free < 0 ? 255 : free;
2726
+ return result;
2727
+ }
2728
+
2729
+ /** First-match cancellation over requests, named effects, clipboard writes,
2730
+ * subprocess streams, file streams, delays and DB commands. Declarative live
2731
+ * queries and synchronous exec terminals keep their owners and never cancel.
2732
+ */
2733
+ function cancellationPolicy(request: Uint8Array): Uint8Array {
2734
+ if (request.length < 2) throw new Error("invalid cancellation request");
2735
+ const length = request[1]!;
2736
+ let at = 2 + length;
2737
+ const counts = [36, 16, 16, 16, 4, 16, 16];
2738
+ const result = new Uint8Array(8); result[0] = 255; result[1] = 255;
2739
+ for (let family = 0; family < 7; family++) for (let slot = 0; slot < counts[family]!; slot++) {
2740
+ if (at + 3 > request.length) throw new Error("truncated cancellation table");
2741
+ const used = request[at]!, flags = request[at + 1]!, size = request[at + 2]!;
2742
+ if (used > 1 || flags > (family === 6 ? 3 : family === 0 || family === 1 || family === 4 ? 1 : 0) || at + 4 + size > request.length)
2743
+ throw new Error("invalid cancellation slot");
2744
+ let equal = length > 0 && used === 1 && size === length && (family !== 1 || flags === 0);
2745
+ for (let i = 0; i < size; i++) if (request[at + 3 + i] !== request[2 + i]) equal = false;
2746
+ if (equal && result[0] === 255) {
2747
+ result[0] = family; result[1] = slot; result[2] = family === 0 || family === 5 || family === 4 && flags === 0 || family === 6 && flags === 1 ? 1 : 0;
2748
+ result[3] = family !== 6 || flags === 1 ? 1 : 0;
2749
+ result[4] = family === 4 && flags === 1 ? 1 : 0;
2750
+ result[5] = family === 0 && flags === 1 ? 1 : 0;
2751
+ result[6] = request[at + 3 + size]!;
2752
+ result[7] = result[5]!;
2753
+ }
2754
+ at += 4 + size;
2755
+ }
2756
+ if (at !== request.length) throw new Error("trailing cancellation bytes");
2757
+ return result;
2758
+ }
2759
+
2760
+ /** Fallible credential request decoding returns offsets into the original
2761
+ * borrowed packet. Malformed authored payloads are normal rejections; no secret
2762
+ * or credential bytes are copied into the policy result or retained by it.
2763
+ */
2764
+ function credentialRecordPolicy(request: Uint8Array): Uint8Array {
2765
+ if (request.length < 2 || 2 + request[1]! > request.length) throw new Error("truncated credential policy header");
2766
+ const names = ["core.credentials.set", "core.credentials.get", "core.credentials.delete"];
2767
+ let operation = -1;
2768
+ for (let candidate = 0; candidate < 3; candidate++) {
2769
+ const name = names[candidate]!;
2770
+ let equal = name.length === request[1];
2771
+ if (equal) for (let i = 0; i < name.length; i++) if (name.charCodeAt(i) !== request[2 + i]) equal = false;
2772
+ if (equal) operation = candidate;
2773
+ }
2774
+ const result = new Uint8Array(20);
2775
+ if (operation < 0) return result;
2776
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength), out = new DataView(result.buffer);
2777
+ const start = 2 + request[1]!;
2778
+ let at = start;
2779
+ for (let field = 0; field < (operation === 0 ? 2 : 1); field++) {
2780
+ if (at + 4 > request.length) return new Uint8Array(20);
2781
+ const length = data.getUint32(at, true); at += 4;
2782
+ if (length > request.length - at) return new Uint8Array(20);
2783
+ out.setUint32(4 + field * 8, at - start, true); out.setUint32(8 + field * 8, length, true);
2784
+ at += length;
2785
+ }
2786
+ if (at !== request.length) return new Uint8Array(20);
2787
+ result[0] = 1; result[1] = operation;
2788
+ return result;
2789
+ }
2790
+
2791
+ /** Database command admission and complete page/done/exec result routing are
2792
+ * separate from live-query reconciliation. Replacement may reuse only a
2793
+ * one-shot query; an exec or live subscription keeps its original route.
2794
+ */
2795
+ function dbCommandPolicy(request: Uint8Array): Uint8Array {
2796
+ if (request.length < 12 || request[1]! > 1 || request[3]! > 1 || request[4]! > 1 || request[9]! > 2 || request[10]! > 1 || request[11] !== 0)
2797
+ throw new Error("invalid database command header");
2798
+ const positions = new DataView(new ArrayBuffer(64)), length = request[2]!;
2799
+ let at = 12 + length, matching = -1, free = -1;
2800
+ for (let slot = 0; slot < 16; slot++) {
2801
+ if (at + 7 > request.length) throw new Error("truncated database command table");
2802
+ const size = request[at + 6]!;
2803
+ if (request[at]! > 1 || request[at + 1]! > 1 || request[at + 2]! > 1 || at + 7 + size > request.length)
2804
+ throw new Error("invalid database command slot");
2805
+ positions.setUint32(slot * 4, at, true);
2806
+ let equal = length > 0 && request[at] === 1 && size === length;
2807
+ for (let i = 0; i < size; i++) if (request[at + 7 + i] !== request[12 + i]) equal = false;
2808
+ if (equal && matching < 0) matching = slot;
2809
+ if (request[at] === 0 && free < 0) free = slot;
2810
+ at += 7 + size;
2811
+ }
2812
+ if (at !== request.length) throw new Error("trailing database command bytes");
2813
+ const result = new Uint8Array(8); result[0] = 255;
2814
+ result[1] = request[5]!; result[2] = request[6]!; result[3] = request[7]!;
2815
+ if (request[1] === 0) {
2816
+ if (request[3] === 1) return result;
2817
+ if (matching >= 0) {
2818
+ const entry = positions.getUint32(matching * 4, true);
2819
+ if (request[4] !== 1 || request[entry + 1] !== 1 || request[entry + 2] === 1) return result;
2820
+ }
2821
+ result[0] = matching < 0 ? free < 0 ? 255 : free : matching;
2822
+ return result;
2823
+ }
2824
+ const slot = request[8]!;
2825
+ if (slot >= 16) throw new Error("database result slot is out of bounds");
2826
+ const entry = positions.getUint32(slot * 4, true);
2827
+ if (request[entry] !== 1) throw new Error("database result has no tracked owner");
2828
+ result[0] = slot;
2829
+ if (request[10] === 0) { result[4] = request[entry + 5]!; result[5] = 2; result[6] = request[entry + 2] === 1 ? 0 : 1; return result; }
2830
+ const kind = request[9]!;
2831
+ if (kind === 1 && request[entry + 1] !== 1 || kind === 2 && request[entry + 1] === 1) throw new Error("database terminal reached the wrong route");
2832
+ result[4] = request[entry + (kind === 0 ? 3 : 4)]!;
2833
+ result[5] = kind === 0 ? 0 : 1;
2834
+ result[6] = kind === 2 || kind === 1 && request[entry + 2] === 0 ? 1 : 0;
2835
+ return result;
2836
+ }
2837
+
2838
+ /** File-stream lifecycle (15). Header: action (lookup/read/open/chunk/close/
2839
+ * completion), key length, foreign-owner fact, result slot/op/event/outcome,
2840
+ * chunk/done/error tags, reserved. Four slots carry used/sink/busy/cancelling,
2841
+ * three routes, key length and exact key bytes. Native retains buffers and
2842
+ * engine identities. Owned result: slot, refusal, route, shape (void/bytes/
2843
+ * number/outcome), retirement, clear-busy, two reserved bytes.
2844
+ */
2845
+ function fileStreamPolicy(request: Uint8Array): Uint8Array {
2846
+ if (request.length < 12 || request[1]! > 5 || request[3]! > 1 || request[11] !== 0)
2847
+ throw new Error("invalid file stream header");
2848
+ const action = request[1]!, length = request[2]!;
2849
+ let at = 12 + length;
2850
+ if (at > request.length) throw new Error("truncated file stream key");
2851
+ const positions: number[] = [];
2852
+ let matching = -1, free = -1;
2853
+ for (let slot = 0; slot < 4; slot++) {
2854
+ if (at + 8 > request.length) throw new Error("truncated file stream slot");
2855
+ for (let i = 0; i < 4; i++) if (request[at + i]! > 1) throw new Error("invalid file stream fact");
2856
+ const size = request[at + 7]!;
2857
+ if (at + 8 + size > request.length) throw new Error("truncated file stream owner");
2858
+ positions.push(at);
2859
+ let equal = request[at] === 1 && size === length;
2860
+ if (equal) for (let i = 0; i < length; i++) if (request[at + 8 + i] !== request[12 + i]) equal = false;
2861
+ if (equal && matching < 0) matching = slot;
2862
+ if (request[at] === 0 && free < 0) free = slot;
2863
+ at += 8 + size;
2864
+ }
2865
+ if (at !== request.length) throw new Error("trailing file stream bytes");
2866
+ const result = new Uint8Array(8); result[0] = 255;
2867
+ if (action === 0) { result[0] = matching < 0 ? 255 : matching; return result; }
2868
+ result[2] = request[10]!;
2869
+ if (action === 1 || action === 2) {
2870
+ const replace = action === 1 && length > 0 && matching >= 0;
2871
+ const slot = replace ? matching : free;
2872
+ const refused = request[3] === 1 || action === 2 && (length === 0 || matching >= 0)
2873
+ || replace && request[positions[matching]! + 1] === 1 || slot < 0;
2874
+ if (refused) result[1] = 1;
2875
+ else { result[0] = slot; result[2] = request[9]!; }
2876
+ return result;
2877
+ }
2878
+ if (action === 3 || action === 4) {
2879
+ if (matching < 0 || request[positions[matching]! + 1] !== 1 || request[positions[matching]! + 3] === 1) result[1] = 2;
2880
+ else if (request[positions[matching]! + 2] === 1) result[1] = 3;
2881
+ else { result[0] = matching; result[2] = request[9]!; }
2882
+ return result;
2883
+ }
2884
+ const slot = request[4]!;
2885
+ if (slot >= 4 || request[positions[slot]!] !== 1 || request[5]! > 8 || request[6]! > 2 || request[7]! > 8)
2886
+ throw new Error("invalid file stream completion owner or enum");
2887
+ const owner = positions[slot]!, op = request[5]!, event = request[6]!, outcome = request[7]!;
2888
+ result[0] = slot; result[2] = request[owner + 6]!; result[3] = 3;
2889
+ if (request[owner + 3] === 1 && outcome === 5) result[4] = 1;
2890
+ else if (op === 4 && event === 1 && outcome === 0) { result[2] = request[owner + 4]!; result[3] = 1; }
2891
+ else if (op === 4 && event === 2 && outcome === 0) { result[2] = request[owner + 5]!; result[3] = 2; result[4] = 1; }
2892
+ else if (outcome === 0) { result[2] = request[owner + 5]!; result[3] = 0; result[4] = op === 7 ? 1 : 0; result[5] = 1; }
2893
+ else if (op === 6 && (outcome === 4 || outcome === 7)) result[5] = 1;
2894
+ else result[4] = 1;
2895
+ return result;
2896
+ }
2897
+
2898
+ /** Clipboard-write coordination (16). Header: lookup/admit/complete, key
2899
+ * length, collision fact, completion slot, authored route, two reserved bytes.
2900
+ * Sixteen slots carry used/route/key length/exact bytes. Empty names never
2901
+ * match but can occupy independent slots. Complete records borrow the native
2902
+ * owner key until dispatch; the policy owns slot, route and retirement only.
2903
+ */
2904
+ function clipboardWritePolicy(request: Uint8Array): Uint8Array {
2905
+ if (request.length < 8 || request[1]! > 2 || request[3]! > 1 || request[6] !== 0 || request[7] !== 0)
2906
+ throw new Error("invalid clipboard write header");
2907
+ const action = request[1]!, length = request[2]!;
2908
+ let at = 8 + length;
2909
+ if (at > request.length) throw new Error("truncated clipboard key");
2910
+ const positions: number[] = [];
2911
+ let matching = -1, free = -1;
2912
+ for (let slot = 0; slot < 16; slot++) {
2913
+ if (at + 3 > request.length || request[at]! > 1) throw new Error("invalid clipboard slot");
2914
+ const size = request[at + 2]!;
2915
+ if (at + 3 + size > request.length) throw new Error("truncated clipboard owner");
2916
+ positions.push(at);
2917
+ let equal = length > 0 && request[at] === 1 && size === length;
2918
+ if (equal) for (let i = 0; i < length; i++) if (request[at + 3 + i] !== request[8 + i]) equal = false;
2919
+ if (equal && matching < 0) matching = slot;
2920
+ if (request[at] === 0 && free < 0) free = slot;
2921
+ at += 3 + size;
2922
+ }
2923
+ if (at !== request.length) throw new Error("trailing clipboard bytes");
2924
+ const result = new Uint8Array(4); result[0] = 255; result[1] = request[5]!;
2925
+ if (action === 0) result[0] = matching < 0 ? 255 : matching;
2926
+ else if (action === 1) result[0] = request[3] === 1 || matching >= 0 || free < 0 ? 255 : free;
2927
+ else {
2928
+ const slot = request[4]!;
2929
+ if (slot >= 16 || request[positions[slot]!] !== 1) throw new Error("untracked clipboard completion");
2930
+ result[0] = slot; result[1] = request[positions[slot]! + 1]!; result[2] = 1;
2931
+ }
2932
+ return result;
2933
+ }
2934
+
2935
+ /** Operation 19: staged app dispatch plans. Facts are sampled only after the
2936
+ * preceding actions complete. Plans own their bytes; queues, causal boundaries,
2937
+ * typed messages and errors remain native-owned. Zero terminates each plan.
2938
+ * Actions: bind, sync, apply, audio, update-fx, update, relational-flush,
2939
+ * main, pending-query, capture/drain, video-query, secondary, hover, take-error.
2940
+ */
2941
+ function appDispatchPolicy(request: Uint8Array): Uint8Array {
2942
+ if (request.length !== 6 || request[1]! > 10 || request[5] !== 0)
2943
+ throw new Error("invalid app dispatch request");
2944
+ const stage = request[1]!, a = request[2]!, b = request[3]!, c = request[4]!;
2945
+ if (a > (stage === 9 ? 2 : 1) || b > 1 || c !== 0 ||
2946
+ (stage !== 5 && stage !== 8 && stage !== 9 && stage !== 10 && b !== 0))
2947
+ throw new Error("invalid app dispatch facts");
2948
+ const plan = new Uint8Array(16);
2949
+ if (stage === 0) { plan[0] = 1; plan[1] = 2; plan[2] = 3; plan[3] = 4; }
2950
+ else if (stage === 1) { plan[0] = a === 1 ? 5 : 6; plan[1] = 7; }
2951
+ else if (stage === 2 || stage === 6) { if (a === 1) plan[0] = 8; }
2952
+ else if (stage === 3) { if (a === 1) plan[0] = 9; }
2953
+ else if (stage === 4) { if (a === 1) { plan[0] = 1; plan[1] = 2; plan[2] = 10; plan[3] = 4; } }
2954
+ else if (stage === 5) { plan[0] = a === 1 ? 8 : b === 1 ? 11 : 0; }
2955
+ else if (stage === 7) { if (a === 0) plan[0] = 12; }
2956
+ else if (stage === 8) { if (a === 1 && b === 0) plan[0] = 13; }
2957
+ else if (stage === 9) { if (a === 0 || (a === 2 && b === 1)) plan[0] = 13; }
2958
+ else if (a === 0 && b === 1) plan[0] = 14;
2959
+ return plan;
2960
+ }
2961
+
2962
+ /** Operation 20: complete journal effect admission. Exact u64 facts stay as
2963
+ * word pairs. No record bytes, identities, blob storage, or frame reset cross
2964
+ * this boundary. All damage predicates precede regeneration in the consumer.
2965
+ */
2966
+ function sessionReplayPolicy(request: Uint8Array): Uint8Array {
2967
+ if (request.length !== 256 || request[1]! < 1 || request[1]! > 20 || request[2]! > 4 ||
2968
+ request[3]! > 8 || request[4]! > 2 || request[5]! > 9 || request[6]! > 14 ||
2969
+ request[7]! > 2 || request[8]! > 4 || request[9]! > 5 || request[10]! > 2 ||
2970
+ request[11]! > 6 || request[12]! > 2 || request[13]! > 6 || request[14]! > 6 || request[15]! > 3)
2971
+ throw new Error("invalid replay admission request");
2972
+ for (let at = 240; at < 247; at++) if (request[at]! > 1) throw new Error("invalid replay admission flag");
2973
+ if (request[247] !== 0 || request[248] === 0) throw new Error("invalid replay schema facts");
2974
+ for (let at = 249; at < 256; at++) if (request[at] !== 0) throw new Error("invalid replay reserved byte");
2975
+ const view = new DataView(request.buffer, request.byteOffset, request.byteLength);
2976
+ const kind = request[1]!, reason = request[2]!, fileOp = request[3]!, fileEvent = request[4]!, fileOutcome = request[5]!;
2977
+ const image = request[6]!, channel = request[7]!, video = request[8]!, pty = request[10]!;
2978
+ const code = view.getInt32(16, true), signal = view.getInt32(20, true);
2979
+ const nonzero = (field: number): boolean => view.getUint32(24 + field * 8, true) !== 0 || view.getUint32(28 + field * 8, true) !== 0;
2980
+ const exceeds = (a: number, b: number): boolean => {
2981
+ const ah = view.getUint32(28 + a * 8, true), bh = view.getUint32(28 + b * 8, true);
2982
+ return ah > bh || (ah === bh && view.getUint32(24 + a * 8, true) > view.getUint32(24 + b * 8, true));
2983
+ };
2984
+ const equal = (a: number, b: number): boolean => view.getUint32(24 + a * 8, true) === view.getUint32(24 + b * 8, true) && view.getUint32(28 + a * 8, true) === view.getUint32(28 + b * 8, true);
2985
+ const scalarDamaged = (field: number): boolean => view.getUint32(28 + field * 8, true) >= 2097152;
2986
+ const payload = nonzero(0), fileBlob = nonzero(1), imageBlob = nonzero(4), ptyBlob = nonzero(14), persistBlob = nonzero(16), dbBlob = nonzero(17);
2987
+ const fileRejected = request[240] === 1, playing = request[242] === 1, buffering = request[243] === 1;
2988
+ let damage = 0;
2989
+ let badFile = fileRejected && (fileOutcome !== 4 && ((fileOutcome !== 6 && fileOutcome !== 7) || (fileOp !== 6 && fileOp !== 7)));
2990
+ badFile = badFile || exceeds(1, 19);
2991
+ if (fileEvent === 1) badFile = badFile || fileOp !== 4 || fileOutcome !== 0 || payload || !fileBlob;
2992
+ else {
2993
+ badFile = badFile || fileBlob;
2994
+ if (fileEvent === 2) badFile = badFile || fileOp !== 4 || fileOutcome !== 0 || payload;
2995
+ else if (fileOp === 3 && fileOutcome === 0) badFile = badFile || payload;
2996
+ else badFile = badFile || nonzero(2) || nonzero(3) || request[241] === 1;
2997
+ }
2998
+ if (kind === 4 && badFile) damage |= 1;
2999
+ if (kind === 11 && image === 0 && !imageBlob) damage |= 2;
3000
+ if (kind === 12 && (exceeds(0, 20) || (channel !== 0 && payload))) damage |= 4;
3001
+ if (kind === 12 && (reason === 3 ? channel !== 2 : reason !== 0)) damage |= 8;
3002
+ let badImage = image !== 0 ? nonzero(5) || nonzero(6) : !nonzero(5) || !nonzero(6) || exceeds(5, 21) || exceeds(6, 21);
3003
+ if (image === 0 && !badImage) {
3004
+ // The schema dimension ceiling fits u32. Divide the byte ceiling before
3005
+ // multiplication so an oversized product never wraps or loses precision.
3006
+ const width = view.getUint32(64, true), height = view.getUint32(72, true);
3007
+ const ceiling = view.getUint32(200, true) + view.getUint32(204, true) * 4294967296;
3008
+ badImage = width > Math.floor(ceiling / 4 / height);
3009
+ }
3010
+ if (kind === 11 && badImage) damage |= 16;
3011
+ if (kind === 13 && (scalarDamaged(7) || scalarDamaged(8) || scalarDamaged(9) || scalarDamaged(10))) damage |= 32;
3012
+ if (kind === 8 && (scalarDamaged(12) || scalarDamaged(13))) damage |= 64;
3013
+ if (kind === 13 && (video === 4 ? nonzero(11) : !nonzero(11))) damage |= 128;
3014
+ if (kind === 13 && ((video === 3 || video === 4) ? playing || buffering || nonzero(9) || nonzero(10) : video === 2 && (playing || buffering || !equal(7, 8)))) damage |= 256;
3015
+ if (kind === 14 && video !== 0 && video !== 3) damage |= 512;
3016
+ let badPty = payload || exceeds(14, 23);
3017
+ if (pty === 0) badPty = badPty || !ptyBlob || code !== -1 || signal !== 0 || nonzero(15);
3018
+ else if (pty === 1) badPty = badPty || ptyBlob || (reason === 1) !== (signal !== 0) ||
3019
+ (reason !== 0 && code !== -1) || (reason === 0 && code !== -1 && (code < 0 || code > 255)) || (reason === 1 && (signal < 1 || signal > 127));
3020
+ else badPty = badPty || ptyBlob || (code !== 0 && code !== 1) || signal !== 0 || nonzero(15);
3021
+ if (kind === 15 && badPty) damage |= 1024;
3022
+ if (kind === 15 && ((pty !== 1 && reason !== 0) || (request[244] === 1 && (pty !== 1 || reason !== 3)))) damage |= 2048;
3023
+ if (kind === 16 && (payload || exceeds(16, 24) || (request[11] !== 0 && persistBlob))) damage |= 4096;
3024
+ const dbKind = code & 255, dbOutcome = (code >> 8) & 255;
3025
+ const badDb = dbKind > 2 || dbOutcome >= request[248]! || code !== (dbKind | (dbOutcome << 8)) ||
3026
+ (reason !== 0 && reason !== 3) || (reason === 3 && dbOutcome !== 6) || exceeds(17, 25) ||
3027
+ (dbKind === 0 ? dbOutcome !== 0 || payload === dbBlob || exceeds(0, 25) : payload || dbBlob);
3028
+ if (kind === 17 && badDb) damage |= 8192;
3029
+ const redacted = request[12] === 1 && request[13] === 0;
3030
+ if (kind === 18 && (payload || reason !== 0 || (redacted ? exceeds(18, 26) || request[245] === 1 || request[246] === 1 : nonzero(18) || request[245] === 0 || request[246] === 0))) damage |= 16384;
3031
+ const regenerate = kind === 6 || ((kind === 2 || kind === 9 || kind === 11 || kind === 12 || kind === 17) && reason === 3) ||
3032
+ (kind === 15 && pty === 1 && request[244] === 1) || (kind === 3 && request[14] === 1) ||
3033
+ (kind === 4 && fileRejected) || (kind === 5 && request[15] === 2) || (kind === 8 && request[9] === 4) || (kind === 13 && video === 4);
3034
+ const blob = kind === 15 && ptyBlob ? 1 : kind === 4 && fileBlob ? 2 : kind === 11 && imageBlob ? 3 : kind === 16 && persistBlob ? 4 : kind === 17 && dbBlob ? 5 : 0;
3035
+ const result = new Uint8Array(8);
3036
+ new DataView(result.buffer).setUint16(0, damage, true); result[2] = regenerate ? 1 : 0; result[3] = blob;
3037
+ return result;
3038
+ }
3039
+
3040
+ /** Operation 21: replay sequencing and refusal precedence. Native samples
3041
+ * OS/query/queue facts and executes the copied action after planning.
3042
+ */
3043
+ function replayCoordinationPolicy(request: Uint8Array): Uint8Array {
3044
+ if (request.length !== 8 || request[1]! > 6 || request[2]! > 2 || request[3]! > 1 || request[4]! > 1 || request[5] !== 0 || request[6] !== 0 || request[7] !== 0)
3045
+ throw new Error("invalid replay coordination request");
3046
+ const stage = request[1]!, a = request[2]!, b = request[3]!, c = request[4]!;
3047
+ if (stage !== 4 && a > 1) throw new Error("invalid replay coordination fact");
3048
+ const result = new Uint8Array(4);
3049
+ if (stage === 0) result[0] = a === 0 ? 1 : b === 1 && c === 0 ? 2 : 0;
3050
+ else if (stage === 1) result[0] = a === 1 || b === 1 ? 3 : 0;
3051
+ else if (stage === 2) result[0] = a === 0 ? 4 : 0;
3052
+ else if (stage === 3) result[0] = a === 1 || b === 1 ? 5 : 0;
3053
+ else if (stage === 4) result[0] = a === 0 ? b === 1 ? 6 : 7 : a === 1 ? 8 : 9;
3054
+ else if (stage === 5) result[0] = a === 1 ? 10 : 0;
3055
+ else result[0] = a === 1 ? 5 : 0;
3056
+ return result;
3057
+ }
3058
+
3059
+ /** Operation 22: menu admission, arena selection, recovery and view scheduling.
3060
+ * Identities are compared natively; counts cross as exact u64 word pairs.
3061
+ */
3062
+ function componentCoordinationPolicy(request: Uint8Array): Uint8Array {
3063
+ if (request.length !== 32 || request[1]! > 15 || request[2]! > 1 || request[3]! > 1 || request[4]! > 1)
3064
+ throw new Error("invalid component coordination request");
3065
+ for (let i = 5; i < 8; i++) if (request[i] !== 0) throw new Error("invalid component reserved byte");
3066
+ for (let i = 24; i < 32; i++) if (request[i] !== 0) throw new Error("invalid component reserved byte");
3067
+ const stage = request[1]!, a = request[2] === 1, b = request[3] === 1, c = request[4] === 1;
3068
+ const result = new Uint8Array(16), view = new DataView(request.buffer, request.byteOffset, request.byteLength);
3069
+ if (stage === 0) {
3070
+ const xl = view.getUint32(8, true), xh = view.getUint32(12, true), yl = view.getUint32(16, true), yh = view.getUint32(20, true);
3071
+ const at = xh < yh || (xh === yh && xl < yl) ? 8 : 16;
3072
+ result.set(request.subarray(at, at + 8), 8);
3073
+ } else if (stage === 1) result[0] = a ? 1 : b ? 2 : 0;
3074
+ else if (stage === 2 || stage === 3 || stage === 10 || stage === 11) result[0] = a && b && c ? 1 : 0;
3075
+ else if (stage === 4 || stage === 9) result[0] = a && b ? 1 : 0;
3076
+ else if (stage === 5) result[0] = a && (b || c) ? 1 : 0;
3077
+ else if (stage === 6) result[0] = (a ? 1 : 0) | (b && c ? 2 : 0);
3078
+ else if (stage === 7) result[0] = a && b ? 1 : 2;
3079
+ else if (stage === 8 || stage === 14) result[0] = a ? 1 : 0;
3080
+ else if (stage === 12) result[0] = a ? 1 : 2;
3081
+ else if (stage === 13) result[0] = a && !b ? 1 : 0;
3082
+ else result[0] = !a && b && c && (view.getUint32(8, true) !== 0 || view.getUint32(12, true) !== 0) ? 1 : 0;
3083
+ return result;
3084
+ }
3085
+
3086
+ /** Operation 23: axis selection and reach hysteresis with reference f32 order.
3087
+ * Latch capacity, exact widget identity and storage remain native capabilities.
3088
+ */
3089
+ function scrollReachPolicy(request: Uint8Array): Uint8Array {
3090
+ if (request.length !== 32 || request[1]! > 1 || request[2]! > 1 || request[3]! > 1 || request[4]! > 1 || request[5] !== 0 || request[6] !== 0 || request[7] !== 0)
3091
+ throw new Error("invalid scroll reach request");
3092
+ const view = new DataView(request.buffer, request.byteOffset, request.byteLength);
3093
+ const nonnegative = (value: number): number => Number.isNaN(value) || value <= 0 ? 0 : value;
3094
+ const vv = view.getFloat32(12, true), vc = view.getFloat32(16, true), hv = view.getFloat32(24, true), hc = view.getFloat32(28, true);
3095
+ const verticalRange = Math.fround(nonnegative(vc) - nonnegative(vv));
3096
+ const horizontalRange = Math.fround(nonnegative(hc) - nonnegative(hv));
3097
+ const horizontal = !(verticalRange > 0) && horizontalRange > 0;
3098
+ const result = new Uint8Array(8); result[0] = horizontal ? 1 : 0;
3099
+ const viewport = horizontal ? hv : vv, content = horizontal ? hc : vc, offset = view.getFloat32(horizontal ? 20 : 8, true);
3100
+ if (request[2] === 0 || viewport <= 0) return result;
3101
+ const remaining = request[1] === 1 ? offset : Math.fround(Math.fround(content - viewport) - offset);
3102
+ if (remaining > Math.fround(viewport * 1.5)) result[1] = 1;
3103
+ else if (!(remaining > Math.fround(viewport * 1.0)) && request[horizontal ? 4 : 3] === 0) result[1] = 2;
3104
+ return result;
3105
+ }
3106
+
3107
+ /** Portable recording coordination. Native owns event/record encoding, staged
3108
+ * bytes, hashing, sinks and blobs. Every identity, budget and counter remains
3109
+ * an exact pair of u32 words; no u64 crosses a JavaScript number boundary.
3110
+ * The response is copied before any encoding, sink or reentrant capability.
3111
+ */
3112
+ function sessionRecordingPolicy(request: Uint8Array): Uint8Array {
3113
+ if (request.length !== 64 || request[0] !== 24 || request[1]! > 12)
3114
+ throw new Error("invalid recording policy request");
3115
+ for (const at of [2, 3, 4, 7, 9, 10, 11, 12])
3116
+ if (request[at]! > 1) throw new Error("invalid recording flag");
3117
+ for (const at of [13, 14, 15, 28, 29, 30, 31])
3118
+ if (request[at] !== 0) throw new Error("invalid recording reserved byte");
3119
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
3120
+ const stage = request[1]!, depth = request[5]!, owner = request[6]!;
3121
+ const maxDepth = data.getUint32(20, true), maxChrome = data.getUint32(24, true);
3122
+ if (maxDepth === 0 || maxDepth > 254 || depth > maxDepth || owner !== 255 && owner >= depth)
3123
+ throw new Error("invalid recording stack");
3124
+ if (stage === 1 && request[8]! > 1 || stage === 7 && (request[8]! < 1 || request[8]! > 20))
3125
+ throw new Error("invalid recording category");
3126
+ const result = new Uint8Array(32), out = new DataView(result.buffer);
3127
+ result[1] = depth; result[2] = owner;
3128
+ const began = request[2] === 1, finished = request[3] === 1, failed = request[4] === 1;
3129
+ // begin intentionally ignores finished; write/count/fail intentionally ignore
3130
+ // both began and finished. The end record is written after finished is set.
3131
+ if (stage === 0 ? began || failed : stage >= 9 ? failed : !began || failed || finished)
3132
+ return result;
3133
+ result[0] = 1;
3134
+ if (stage === 1) {
3135
+ if (depth === maxDepth) { result[0] = 2; return result; }
3136
+ result[1] = depth + 1;
3137
+ if (owner !== 255) result[0] = 8;
3138
+ else if (request[8] === 1) result[2] = depth;
3139
+ } else if (stage === 2) {
3140
+ if (depth === 0) { result[0] = 0; return result; }
3141
+ result[1] = depth - 1;
3142
+ if (request[7] === 1) result[0] = 8;
3143
+ else if (owner === depth - 1) result[2] = 255;
3144
+ } else if (stage === 3) {
3145
+ if (request[12] === 1) result[0] = 3;
3146
+ else if (depth === 0) result[0] = 4;
3147
+ else if (data.getUint32(16, true) === maxChrome) result[0] = 5;
3148
+ else {
3149
+ result[1] = owner === 255 ? depth - 1 : owner;
3150
+ out.setUint32(16, data.getUint32(16, true) + 1, true);
3151
+ }
3152
+ } else if (stage === 4) {
3153
+ if (depth !== 0 || recordingWordsEqual(data, 32, 40)) result[0] = 0;
3154
+ } else if (stage === 7) {
3155
+ const kind = request[8]!, nonempty = !recordingWordsZero(data, 40);
3156
+ result[3] = kind === 18 ? request[10] === 1 && request[11] === 1 ? 7 : 6
3157
+ : kind === 4 && request[9] === 1 && nonempty ? 2
3158
+ : kind === 11 && nonempty ? 3 : kind === 15 && nonempty ? 1
3159
+ : kind === 16 && nonempty ? 4
3160
+ : kind === 17 && recordingWordsGreater(data, 40, 48) ? 5 : 0;
3161
+ } else if (stage === 9) {
3162
+ if (recordingWordsGreater(data, 40, 48)) { result[0] = 6; return result; }
3163
+ const low = data.getUint32(32, true) + data.getUint32(40, true) + 5;
3164
+ const high = data.getUint32(36, true) + data.getUint32(44, true) + Math.floor(low / 4294967296);
3165
+ if (high > 4294967295) { result[0] = 7; return result; }
3166
+ out.setUint32(8, low % 4294967296, true); out.setUint32(12, high, true);
3167
+ const limitLow = data.getUint32(56, true), limitHigh = data.getUint32(60, true);
3168
+ if (high > limitHigh || high === limitHigh && low % 4294967296 > limitLow) result[0] = 7;
3169
+ } else if (stage === 12) {
3170
+ const low = data.getUint32(32, true) + 1;
3171
+ const high = data.getUint32(36, true) + (low === 4294967296 ? 1 : 0);
3172
+ if (high > 4294967295) throw new Error("recording counter overflow");
3173
+ out.setUint32(8, low % 4294967296, true); out.setUint32(12, high, true);
3174
+ }
3175
+ return result;
3176
+ }
3177
+ function recordingWordsZero(data: DataView, at: number): boolean {
3178
+ return data.getUint32(at, true) === 0 && data.getUint32(at + 4, true) === 0;
3179
+ }
3180
+ function recordingWordsEqual(data: DataView, a: number, b: number): boolean {
3181
+ return data.getUint32(a, true) === data.getUint32(b, true) && data.getUint32(a + 4, true) === data.getUint32(b + 4, true);
3182
+ }
3183
+ function recordingWordsGreater(data: DataView, a: number, b: number): boolean {
3184
+ const highA = data.getUint32(a + 4, true), highB = data.getUint32(b + 4, true);
3185
+ return highA > highB || highA === highB && data.getUint32(a, true) > data.getUint32(b, true);
3186
+ }
3187
+
3188
+ /** Operation 25: replay progress, bounded mismatch retention, blob length
3189
+ * validation and first-match target selection. Native owns every capability
3190
+ * and applies these copied plans before reading, rendering or dispatching.
3191
+ * IDs, hashes and counters remain u32 word pairs; labels remain raw bytes.
3192
+ */
3193
+ function replayProgressPolicy(request: Uint8Array): Uint8Array {
3194
+ if (request.length < 96 || request[1]! > 6) throw new Error("invalid replay progress request");
3195
+ const stage = request[1]!, code = request[2]!, count = request[3]!;
3196
+ if (code > (stage === 2 ? 1 : stage === 4 ? 2 : 0) || count > (stage === 5 ? 16 : stage === 6 ? 32 : 0) || request.length !== 96 + count * 80)
3197
+ throw new Error("invalid replay progress facts");
3198
+ for (let at = 4; at < 8; at++) if (request[at] !== 0) throw new Error("invalid replay progress reserved byte");
3199
+ const data = new DataView(request.buffer, request.byteOffset, request.byteLength);
3200
+ const result = new Uint8Array(32), out = new DataView(result.buffer);
3201
+ result[2] = 255; out.setUint32(4, 4294967295, true);
3202
+ const reservedStart = stage === 6 ? 16 : stage === 5 ? 16 : 40;
3203
+ const reservedEnd = stage === 6 ? 32 : 96;
3204
+ for (let at = reservedStart; at < reservedEnd; at++) if (request[at] !== 0) throw new Error("invalid replay progress reserved byte");
3205
+ const labelLength = data.getUint32(8, true), labelHigh = data.getUint32(12, true);
3206
+ if (stage === 6 && labelHigh === 0 && labelLength < 64)
3207
+ for (let at = 32 + labelLength; at < 96; at++) if (request[at] !== 0) throw new Error("invalid replay label padding");
3208
+ for (let i = 0; i < count; i++) {
3209
+ const at = 96 + i * 80, length = request[at + 2]!;
3210
+ if (request[at]! > 1 || request[at + 1]! > 18 || length > 64 || stage === 5 && (request[at + 1] !== 0 || length !== 0))
3211
+ throw new Error("invalid replay target slot");
3212
+ for (let byte = at + 3; byte < at + 8; byte++) if (request[byte] !== 0) throw new Error("invalid replay slot reserved byte");
3213
+ for (let byte = at + 16 + length; byte < at + 80; byte++) if (request[byte] !== 0) throw new Error("invalid replay slot padding");
3214
+ }
3215
+ if (stage === 0 || stage === 1) {
3216
+ replayIncrement(data, 8, out, 8);
3217
+ if (stage === 1) {
3218
+ result.set(request.subarray(16, 24), 16);
3219
+ if (!recordingWordsEqual(data, 24, 32)) {
3220
+ result[1] = 1;
3221
+ if (data.getUint32(20, true) === 0 && data.getUint32(16, true) < 16) result[2] = data.getUint32(16, true);
3222
+ replayIncrement(data, 16, out, 16);
3223
+ }
3224
+ }
3225
+ } else if (stage === 2) result[0] = code === 0 ? 1 : recordingWordsGreater(data, 8, 16) ? 2 : 0;
3226
+ else if (stage === 3) result[0] = recordingWordsEqual(data, 8, 16) ? 0 : 3;
3227
+ else if (stage === 4) result[0] = code === 2 ? 4 : 0;
3228
+ else {
3229
+ for (let i = 0; i < count; i++) {
3230
+ const at = 96 + i * 80;
3231
+ if (request[at] !== 1) continue;
3232
+ let matches = stage === 5 ? recordingWordsEqual(data, 8, at + 8)
3233
+ : request[at + 1] === 17 && labelHigh === 0 && labelLength === request[at + 2];
3234
+ if (stage === 6 && matches) for (let byte = 0; byte < labelLength; byte++)
3235
+ if (request[32 + byte] !== request[at + 16 + byte]) matches = false;
3236
+ if (matches) { out.setUint32(4, i, true); break; }
3237
+ }
3238
+ }
3239
+ return result;
3240
+ }
3241
+ function replayIncrement(data: DataView, at: number, out: DataView, dest: number): void {
3242
+ const low = data.getUint32(at, true) + 1;
3243
+ const high = data.getUint32(at + 4, true) + (low === 4294967296 ? 1 : 0);
3244
+ if (high > 4294967295) throw new Error("replay counter overflow");
3245
+ out.setUint32(dest, low % 4294967296, true); out.setUint32(dest + 4, high, true);
3246
+ }
3247
+
3248
+ /** Operation 26 owns journal preambles, frame headers, reader admission,
3249
+ * sequencing, exact counters and end seals. Payload bytes never leave native
3250
+ * storage; complete copied facts retain refusal order and decode-failure state.
3251
+ */
3252
+ function sessionJournalPolicy(request: Uint8Array): Uint8Array {
3253
+ if (request.length !== 160 || request[1]! > 4 || request[2]! > 3 || request[3]! > 7)
3254
+ throw new Error("invalid journal policy request");
3255
+ for (let at = 4; at < 8; at++) if (request[at] !== 0) throw new Error("invalid journal reserved byte");
3256
+ for (let at = 136; at < 160; at++) if (request[at] !== 0) throw new Error("invalid journal reserved byte");
3257
+ const stage = request[1]!, data = new DataView(request.buffer, request.byteOffset, request.byteLength);
3258
+ const result = new Uint8Array(80), out = new DataView(result.buffer);
3259
+ result.set(request.subarray(16, 24), 8); result.set(request.subarray(32, 72), 16);
3260
+ if (stage === 0) {
3261
+ let magic = true;
3262
+ const expected = [78, 83, 68, 75, 83, 74, 78, 76];
3263
+ for (let i = 0; i < 8; i++) if (request[112 + i] !== expected[i]) magic = false;
3264
+ if (data.getUint32(12, true) === 0 && data.getUint32(8, true) < 16 || !magic) result[0] = 1;
3265
+ else if (!recordingWordsEqual(data, 24, 120)) result[0] = 2;
3266
+ else out.setUint32(8, 16, true);
3267
+ } else if (stage === 1) {
3268
+ // The format's u32 payload is bounded below 2^32 before addition.
3269
+ const length = data.getUint32(8, true), limit = data.getUint32(128, true);
3270
+ if (data.getUint32(132, true) !== 0 || limit > 4294967290) throw new Error("invalid journal record limit");
3271
+ if (data.getUint32(12, true) !== 0 || length > limit ||
3272
+ data.getUint32(20, true) === 0 && data.getUint32(16, true) < 5 + length) result[0] = 5;
3273
+ else { result[56] = request[3]!; out.setUint32(57, length, true); }
3274
+ } else if (stage === 2) {
3275
+ if ((request[2]! & 2) !== 0) {
3276
+ result[0] = recordingWordsEqual(data, 8, 16) ? 8 : 4;
3277
+ return result;
3278
+ }
3279
+ if (recordingWordsGreater(data, 16, 8)) throw new Error("invalid journal reader position");
3280
+ const low = data.getUint32(8, true) - data.getUint32(16, true);
3281
+ const high = data.getUint32(12, true) - data.getUint32(20, true) - (low < 0 ? 1 : 0);
3282
+ const remaining = low < 0 ? low + 4294967296 : low;
3283
+ if (high === 0 && remaining < 5) result[0] = 3;
3284
+ else {
3285
+ const kind = request[112]!, length = data.getUint32(113, true);
3286
+ if (kind < 1 || kind > 7) result[0] = 4;
3287
+ else if (data.getUint32(132, true) === 0 && length > data.getUint32(128, true)) result[0] = 5;
3288
+ else if (high === 0 && remaining - 5 < length) result[0] = 3;
3289
+ else {
3290
+ result[1] = kind; out.setUint32(4, length, true);
3291
+ const nextLow = data.getUint32(16, true) + 5 + length;
3292
+ out.setUint32(8, nextLow % 4294967296, true);
3293
+ out.setUint32(12, data.getUint32(20, true) + (nextLow >= 4294967296 ? 1 : 0), true);
3294
+ if ((request[2]! & 1) === 0 && kind !== 1) result[0] = 6;
3295
+ else if ((request[2]! & 1) !== 0 && kind === 1) result[0] = 4;
3296
+ else if (kind >= 2 && kind <= 5 || kind === 7) {
3297
+ const index = kind === 7 ? 4 : kind - 2;
3298
+ replayIncrement(data, 32 + index * 8, out, 16 + index * 8);
3299
+ }
3300
+ }
3301
+ }
3302
+ } else if (stage === 3) {
3303
+ for (let i = 0; i < 5; i++) if (!recordingWordsEqual(data, 32 + i * 8, 72 + i * 8)) result[0] = 7;
3304
+ } else {
3305
+ result.set(new Uint8Array([78, 83, 68, 75, 83, 74, 78, 76]), 64);
3306
+ result.set(request.subarray(24, 32), 72);
3307
+ }
3308
+ return result;
3309
+ }
3310
+
3311
+ /** Snapshot projections and profile statistics over copied facts. The host
3312
+ * retains borrowed labels, bounded storage, clocks and process/GPU queries.
3313
+ * Unsigned identities and counters travel as two exact 32-bit words.
3314
+ */
3315
+ export function snapshotCoordinationPolicy(request: Uint8Array): Uint8Array {
3316
+ if (request.length < 104 || request[0] !== 27 || request[1] !== 1 || request[2]! > 10 || request[3] !== 0)
3317
+ throw new Error("invalid snapshot coordination request");
3318
+ const mode = request[2]!, data = new DataView(request.buffer, request.byteOffset, request.byteLength);
3319
+ const flags = data.getUint32(4, true);
3320
+ const sampleCount = mode === 7 ? data.getUint32(8, true) : mode === 9 ? 12 : 0;
3321
+ if (sampleCount > 128 || request.length !== 104 + sampleCount * 4) throw new Error("invalid snapshot sample extent");
3322
+ const allowed = mode === 2 ? 1531 : mode === 1 ? 3 : mode === 5 ? 7 : mode === 0 || mode === 3 || mode === 6 ? 1 : 0;
3323
+ if ((flags & ~allowed) !== 0) throw new Error("invalid snapshot coordination flags");
3324
+ const result = new Uint8Array(104), out = new DataView(result.buffer);
3325
+ const at = (i: number): number => 8 + i * 8;
3326
+ const zero = (i: number): boolean => data.getUint32(at(i), true) === 0 && data.getUint32(at(i) + 4, true) === 0;
3327
+ const equal = (i: number, j: number): boolean => data.getUint32(at(i), true) === data.getUint32(at(j), true) && data.getUint32(at(i) + 4, true) === data.getUint32(at(j) + 4, true);
3328
+ const greater = (i: number, j: number): boolean => data.getUint32(at(i) + 4, true) > data.getUint32(at(j) + 4, true) ||
3329
+ data.getUint32(at(i) + 4, true) === data.getUint32(at(j) + 4, true) && data.getUint32(at(i), true) > data.getUint32(at(j), true);
3330
+ const copy = (i: number, j: number): void => { result.set(request.subarray(at(i), at(i) + 8), at(j)); };
3331
+ const small = (i: number, value: number): void => { out.setUint32(at(i), value, true); };
3332
+ const difference = (i: number, j: number, dest: number): void => {
3333
+ const low = data.getUint32(at(i), true) - data.getUint32(at(j), true);
3334
+ out.setUint32(at(dest), low, true);
3335
+ out.setUint32(at(dest) + 4, data.getUint32(at(i) + 4, true) - data.getUint32(at(j) + 4, true) - (low < 0 ? 1 : 0), true);
3336
+ };
3337
+ if (mode === 0) {
3338
+ // Active admission and aggregate-capacity projection (windows and menus).
3339
+ if (flags === 1) copy(greater(0, 1) ? 1 : 0, 0);
3340
+ if (zero(0) || zero(1) || flags === 0) result[0] = 1;
3341
+ } else if (mode === 1) {
3342
+ result[0] = flags === 3 && equal(0, 1) ? 1 : 0;
3343
+ } else if (mode === 2) {
3344
+ const has = (bit: number): boolean => (flags & bit) !== 0;
3345
+ const role = data.getUint32(56, true);
3346
+ if (data.getUint32(60, true) !== 0 || role > 26) throw new Error("invalid snapshot widget role");
3347
+ const selectable = role === 12 || role === 15 || role === 16 || role === 17 || role === 18 || role === 20;
3348
+ const selected = has(1) || has(2) && !(data.getFloat32(72, true) < 0.5) && selectable;
3349
+ let state = selected ? 1 : 0;
3350
+ if (has(8) || has(16) && has(32) && equal(0, 1)) state |= 2;
3351
+ if (!has(64)) state |= 4;
3352
+ if (has(128) || !zero(0) && equal(0, 2)) state |= 8;
3353
+ if (has(256) || !zero(0) && equal(0, 3)) state |= 16;
3354
+ if (has(1024) && greater(5, 4)) { state |= 32; copy(4, 0); }
3355
+ result[0] = state;
3356
+ const f = Math.fround;
3357
+ out.setFloat32(72, f(data.getFloat32(76, true) + data.getFloat32(92, true)), true);
3358
+ out.setFloat32(76, f(data.getFloat32(80, true) + data.getFloat32(96, true)), true);
3359
+ result.set(request.subarray(84, 92), 80);
3360
+ } else if (mode === 3) {
3361
+ if (flags === 1) {
3362
+ if (greater(0, 1)) throw new Error("invalid snapshot virtual range");
3363
+ result[0] = 1;
3364
+ for (let i = 0; i < 4; i++) small(i, data.getUint32(at(i) + 4, true) !== 0 ? 4294967295 : data.getUint32(at(i), true));
3365
+ difference(1, 0, 4);
3366
+ if (out.getUint32(at(4) + 4, true) !== 0) { small(4, 4294967295); out.setUint32(at(4) + 4, 0, true); }
3367
+ }
3368
+ } else if (mode === 4 || mode === 10) {
3369
+ if ((mode === 10 || !zero(0)) && !greater(0, 1)) difference(1, 0, 0);
3370
+ } else if (mode === 5) {
3371
+ result[0] = flags;
3372
+ } else if (mode === 6) {
3373
+ if (data.getUint32(20, true) !== 0 || data.getUint32(28, true) !== 0 || data.getUint32(16, true) > 128 || data.getUint32(24, true) >= 128)
3374
+ throw new Error("invalid frame profile ring");
3375
+ copy(1, 0); copy(2, 1); copy(3, 2);
3376
+ if (flags === 1) {
3377
+ result[0] = 1;
3378
+ const high = data.getUint32(12, true), low = data.getUint32(8, true);
3379
+ const ns = low + high * 4294967296;
3380
+ small(3, high > 999 || ns >= 4294967295000 ? 4294967295 : Math.floor(ns / 1000));
3381
+ small(0, Math.min(data.getUint32(16, true) + 1, 128));
3382
+ small(1, (data.getUint32(24, true) + 1) % 128);
3383
+ const nextLow = data.getUint32(32, true) + 1;
3384
+ small(2, nextLow); out.setUint32(28, data.getUint32(36, true) + (nextLow === 4294967296 ? 1 : 0), true);
3385
+ }
3386
+ } else if (mode === 7) {
3387
+ const length = data.getUint32(8, true);
3388
+ if (data.getUint32(12, true) !== 0 || length > 128) throw new Error("invalid frame profile window");
3389
+ copy(0, 0); copy(1, 1);
3390
+ const sorted: number[] = [];
3391
+ for (let i = 0; i < length; i++) {
3392
+ const sample = data.getUint32(104 + i * 4, true);
3393
+ let pos = sorted.length;
3394
+ sorted.push(sample);
3395
+ while (pos > 0 && sorted[pos - 1]! > sample) { sorted[pos] = sorted[pos - 1]!; pos--; }
3396
+ sorted[pos] = sample;
3397
+ }
3398
+ if (length > 0) {
3399
+ small(2, sorted[Math.max(Math.floor((length * 50 + 99) / 100), 1) - 1]!);
3400
+ small(3, sorted[Math.max(Math.floor((length * 90 + 99) / 100), 1) - 1]!);
3401
+ small(4, sorted[length - 1]!);
3402
+ }
3403
+ } else if (mode === 9) {
3404
+ for (let i = 0; i < 12; i++) if (data.getUint32(104 + i * 4, true) !== 0) result[0] = 1;
3405
+ }
3406
+ // Reset (mode 8) returns zero metadata, leaving enable state and samples owned by the host.
3407
+ return result;
3408
+ }
3409
+
3410
+ /** Copied blob-store decisions. File I/O, hashing, entropy, allocation and
3411
+ * borrowed payload storage remain explicit native capabilities. */
3412
+ export function sessionBlobPolicy(request: Uint8Array): Uint8Array {
3413
+ if (request.length < 64 || request[0] !== 28 || request[1] !== 1 || request[2]! > 12 || request[3]! > 3 ||
3414
+ (request[4] !== 0 || request[5] !== 0 || request[6] !== 0 || request[7] !== 0)) throw new Error("invalid session blob request");
3415
+ const mode = request[2]!, flags = request[3]!, data = new DataView(request.buffer, request.byteOffset, request.byteLength);
3416
+ const aLength = data.getUint32(56, true), bLength = data.getUint32(60, true);
3417
+ if (aLength > 4096 || bLength > 4096 || request.length !== 64 + aLength + bLength) throw new Error("invalid session blob extent");
3418
+ const a = request.subarray(64, 64 + aLength), b = request.subarray(64 + aLength);
3419
+ const equal = (x: Uint8Array, y: Uint8Array): boolean => {
3420
+ if (x.length !== y.length) return false;
3421
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return false;
3422
+ return true;
3423
+ };
3424
+ const at = (i: number): number => 8 + i * 8;
3425
+ const same = (i: number, j: number): boolean => data.getUint32(at(i), true) === data.getUint32(at(j), true) && data.getUint32(at(i) + 4, true) === data.getUint32(at(j) + 4, true);
3426
+ const greater = (i: number, j: number): boolean => data.getUint32(at(i) + 4, true) > data.getUint32(at(j) + 4, true) ||
3427
+ data.getUint32(at(i) + 4, true) === data.getUint32(at(j) + 4, true) && data.getUint32(at(i), true) > data.getUint32(at(j), true);
3428
+ const zero = (i: number): boolean => data.getUint32(at(i), true) === 0 && data.getUint32(at(i) + 4, true) === 0;
3429
+ const allowed = mode === 6 || mode === 8 ? 3 : mode === 0 || mode === 1 || mode === 5 || mode === 9 || mode === 12 ? 0 : 1;
3430
+ if ((flags & ~allowed) !== 0) throw new Error("invalid session blob flags");
3431
+ const textMode = mode === 11 || mode === 12;
3432
+ let text = new Uint8Array(0), action = 0;
3433
+ const result = new Uint8Array(32), out = new DataView(result.buffer);
3434
+ const copy = (i: number, dest: number): void => { result.set(request.subarray(at(i), at(i) + 8), at(dest)); };
3435
+ const increment = (i: number, dest: number, amount: number): void => {
3436
+ const low = data.getUint32(at(i), true) + amount;
3437
+ out.setUint32(at(dest), low, true); out.setUint32(at(dest) + 4, data.getUint32(at(i) + 4, true) + (low >= 4294967296 ? 1 : 0), true);
3438
+ };
3439
+ if (!textMode && mode !== 3 && mode !== 4 && mode !== 5 && mode !== 9 && (aLength !== 0 || bLength !== 0)) throw new Error("unexpected session blob bytes");
3440
+ if (mode === 0) action = zero(0) || greater(0, 1) ? 5 : 0;
3441
+ else if (mode === 1) action = greater(0, 1) ? 1 : 0;
3442
+ else if (mode === 2) action = flags === 1 ? 8 : 14;
3443
+ else if (mode === 3) {
3444
+ if (flags === 0) action = 7;
3445
+ else if (zero(2)) action = same(0, 1) ? 6 : 7;
3446
+ else {
3447
+ if (data.getUint32(28, true) !== 0 || data.getUint32(24, true) > 4096 || aLength !== data.getUint32(24, true)) throw new Error("invalid blob probe chunk");
3448
+ increment(1, 0, aLength);
3449
+ const nextLow = out.getUint32(8, true), nextHigh = out.getUint32(12, true);
3450
+ const beyond = nextHigh > data.getUint32(12, true) || nextHigh === data.getUint32(12, true) && nextLow > data.getUint32(8, true);
3451
+ if (beyond || !equal(a, b)) action = 7;
3452
+ else if (greater(3, 2)) action = nextLow === data.getUint32(8, true) && nextHigh === data.getUint32(12, true) ? 6 : 7;
3453
+ else action = 8;
3454
+ }
3455
+ } else if (mode === 4) {
3456
+ if (flags === 1) action = !same(0, 1) ? 7 : zero(0) ? 6 : 8;
3457
+ else {
3458
+ if (!equal(a, b)) action = 7;
3459
+ else {
3460
+ increment(0, 0, aLength);
3461
+ action = out.getUint32(8, true) === data.getUint32(16, true) && out.getUint32(12, true) === data.getUint32(20, true) ? 6 : 8;
3462
+ }
3463
+ }
3464
+ } else if (mode === 5) {
3465
+ if (aLength !== 16 || bLength !== 16 || !greater(1, 0)) throw new Error("invalid blob address probe");
3466
+ action = equal(a, b) ? 13 : 8; copy(0, 0);
3467
+ } else if (mode === 6) {
3468
+ if (greater(0, 1)) action = 1;
3469
+ else if ((flags & 1) !== 0) {
3470
+ action = (flags & 2) !== 0 ? 9 : 10;
3471
+ if (action === 9) increment(4, 1, 1);
3472
+ copy(2, 0);
3473
+ } else {
3474
+ action = same(2, 3) ? 2 : 11;
3475
+ if (action === 11) increment(2, 0, 1);
3476
+ }
3477
+ } else if (mode === 7) action = flags === 0 ? 3 : greater(0, 1) ? 1 : 0;
3478
+ else if (mode === 8) {
3479
+ if ((flags & 1) === 0) action = 2;
3480
+ else if ((flags & 2) === 0) action = same(0, 1) ? 12 : 0;
3481
+ else action = zero(2) ? 0 : 1;
3482
+ } else if (mode === 9) {
3483
+ if (aLength !== 16 || bLength !== 16) throw new Error("invalid blob hash extent");
3484
+ action = equal(a, b) ? 0 : 4;
3485
+ } else if (mode === 10) action = flags === 1 ? 0 : 2;
3486
+ else if (mode === 11) {
3487
+ const length = aLength + 1 + bLength + (flags === 1 ? 25 : 0);
3488
+ if (length > 1104 || data.getUint32(20, true) === 0 && length > data.getUint32(16, true)) action = 2;
3489
+ else {
3490
+ text = new Uint8Array(length);text.set(a);text[aLength] = 47;text.set(b, aLength + 1);
3491
+ if (flags === 1) {
3492
+ const start = aLength + 1 + bLength; text[start] = 46;
3493
+ for (let i = 0; i < 16; i++) {
3494
+ const word = data.getUint32(i < 8 ? 12 : 8, true), nibble = (word >>> ((7 - i % 8) * 4)) & 15;
3495
+ text[start + 1 + i] = nibble < 10 ? 48 + nibble : 87 + nibble;
3496
+ }
3497
+ text.set(new Uint8Array([46,112,97,114,116,105,97,108]), start + 17);
3498
+ }
3499
+ }
3500
+ } else {
3501
+ if (aLength !== 16 || bLength !== 0) throw new Error("invalid blob name hash");
3502
+ text = new Uint8Array(32);
3503
+ for (let i = 0; i < 16; i++) for (let j = 0; j < 2; j++) {
3504
+ const nibble = j === 0 ? a[i]! >>> 4 : a[i]! & 15;text[i * 2 + j] = nibble < 10 ? 48 + nibble : 87 + nibble;
3505
+ }
3506
+ }
3507
+ result[0] = action;
3508
+ if (!textMode) return result;
3509
+ const complete = new Uint8Array(32 + text.length);complete.set(result);complete.set(text, 32);new DataView(complete.buffer).setUint32(4, text.length, true);return complete;
3510
+ }
3511
+
3512
+ /** Complete automation text traversal and formatting. Programs reference
3513
+ * borrowed native slots; numeric spelling and writer I/O are explicit native
3514
+ * capabilities. Programs and escaped-byte chunks are bounded independently of
3515
+ * input label length and snapshot node count. */
3516
+ class NscSnapshotTextProgram implements nscContracts.Acyclic {
3517
+ flags: Uint8Array;
3518
+ bytes: number[] = [];
3519
+ constructor(flags: Uint8Array) { this.flags = flags; }
3520
+ flag(slot: number): boolean { return this.flags[8 + slot] === 1; }
3521
+ text(value: string): void {
3522
+ if (value.length === 0) return;
3523
+ this.bytes.push(0); this.word(value.length);
3524
+ for (let i = 0; i < value.length; i++) this.bytes.push(value.charCodeAt(i));
3525
+ }
3526
+ word(value: number): void { this.bytes.push(value & 255); this.bytes.push((value >>> 8) & 255); }
3527
+ slot(index: number, format: number): void { this.bytes.push(1); this.word(index); this.bytes.push(format); }
3528
+ children(collection: number): void { this.bytes.push(2); this.bytes.push(collection); }
3529
+ quoted(index: number): void { this.text("\""); this.slot(index, 4); this.text("\""); }
3530
+ result(): Uint8Array {
3531
+ if (this.bytes.length > 16384) throw new Error("snapshot program budget exceeded");
3532
+ const out = new Uint8Array(this.bytes.length);
3533
+ for (let i = 0; i < this.bytes.length; i++) out[i] = this.bytes[i]!;
3534
+ return out;
3535
+ }
3536
+ }
3537
+
3538
+ export function snapshotSerializationPolicy(request: Uint8Array): Uint8Array {
3539
+ if (request.length < 8 || request[0] !== 29 || request[1] !== 1 || request[3]! > 2)
3540
+ throw new Error("invalid snapshot serialization request");
3541
+ for (let i = 4; i < 8; i++) if (request[i] !== 0) throw new Error("invalid snapshot serialization reserved byte");
3542
+ const mode = request[2]!, variant = request[3]!;
3543
+ if (mode === 20 || mode === 21) {
3544
+ if (request.length > 264 || variant !== 0) throw new Error("invalid snapshot byte chunk");
3545
+ const bytes: number[] = [], hex = "0123456789abcdef";
3546
+ for (let i = 8; i < request.length; i++) {
3547
+ const byte = request[i]!;
3548
+ if (mode === 21) { bytes.push(hex.charCodeAt(byte >>> 4)); bytes.push(hex.charCodeAt(byte & 15)); }
3549
+ else if (byte === 34 || byte === 92) { bytes.push(92); bytes.push(byte); }
3550
+ else if (byte === 10 || byte === 13 || byte === 9) { bytes.push(92); bytes.push(byte === 10 ? 110 : byte === 13 ? 114 : 116); }
3551
+ else if (byte < 32 || byte === 127) {
3552
+ bytes.push(92); bytes.push(117); bytes.push(48); bytes.push(48); bytes.push(hex.charCodeAt(byte >>> 4)); bytes.push(hex.charCodeAt(byte & 15));
3553
+ } else bytes.push(byte);
3554
+ }
3555
+ const out = new Uint8Array(bytes.length);
3556
+ for (let i = 0; i < bytes.length; i++) out[i] = bytes[i]!;
3557
+ return out;
3558
+ }
3559
+ if (request.length !== 264 || mode > 19) throw new Error("invalid snapshot record");
3560
+ for (let i = 8; i < 264; i++) if (request[i]! > 1) throw new Error("invalid snapshot fact");
3561
+ const p = new NscSnapshotTextProgram(request);
3562
+ if (mode === 0) {
3563
+ if (variant === 0) {
3564
+ p.text("ready=true protocol=0x"); p.slot(0, 3);
3565
+ const names = [" frame=", " commands=", " runtime_uptime_ns=", " dispatch_errors=", " dropped_trace_records=", " publisher_pid="];
3566
+ for (let i = 0; i < names.length; i++) { p.text(names[i]!); p.slot(i + 1, 1); }
3567
+ p.text(" markup_watch="); p.text(p.flag(7) ? "armed\n" : "off\n");
3568
+ if (p.flag(8)) { p.text("frame_profile"); p.children(0); p.text("\n"); }
3569
+ } else if (variant === 1) { p.text("a11y root=@w1 nodes="); p.slot(9, 1); p.text("\n"); }
3570
+ p.children(1);
3571
+ if (variant !== 2) { p.children(2); p.children(3); }
3572
+ if (variant === 0) {
3573
+ p.children(4); p.children(5); p.children(6);
3574
+ if (p.flag(10)) p.children(7);
3575
+ if (p.flag(11)) p.children(8);
3576
+ p.children(9);
3577
+ if (p.flag(12)) p.children(10);
3578
+ }
3579
+ } else if (mode === 1) {
3580
+ const names = ["_p50_us=", "_p90_us=", "_max_us=", "_n="];
3581
+ for (let i = 0; i < names.length; i++) { p.text(" "); p.slot(0, 0); p.text(names[i]!); p.slot(i + 1, 1); }
3582
+ } else if (mode === 2) {
3583
+ p.text(variant === 1 ? "@w" : "window @w"); p.slot(0, 1);
3584
+ p.text(variant === 1 ? " role=window name=\"" : " \""); p.slot(1, 0); p.text("\"");
3585
+ if (variant !== 2) { p.text(" bounds=("); p.slot(2,1); p.text(","); p.slot(3,1); p.text(" "); p.slot(4,1); p.text("x"); p.slot(5,1); p.text(")"); }
3586
+ if (variant !== 1) { p.text(" focused="); p.text(p.flag(6) ? "true" : "false"); }
3587
+ if (variant === 0) { p.text(" frame="); p.slot(7,1); p.text(" commands="); p.slot(8,1); }
3588
+ p.text("\n");
3589
+ } else if (mode === 3) {
3590
+ if (variant === 1) {
3591
+ p.text("@w"); p.slot(0,1); p.text("/"); p.slot(1,0); p.text(" role="); p.slot(p.flag(3) ? 3 : 2,0);
3592
+ p.text(" name=\""); p.slot(p.flag(4) ? 4 : p.flag(5) ? 5 : 1,0); p.text("\" bounds=(");
3593
+ p.slot(6,1); p.text(","); p.slot(7,1); p.text(" "); p.slot(8,1); p.text("x"); p.slot(9,1); p.text(")\n");
3594
+ } else {
3595
+ p.text(" view @w");
3596
+ p.slot(0, 1);
3597
+ p.text("/");
3598
+ p.slot(1, 0);
3599
+ p.text(" kind=");
3600
+ p.slot(2, 0);
3601
+ p.text(" role=\"");
3602
+ p.slot(3, 0);
3603
+ p.text("\" accessibility_label=\"");
3604
+ p.slot(4, 0);
3605
+ p.text("\" text=\"");
3606
+ p.slot(5, 0);
3607
+ p.text("\" bounds=(");
3608
+ p.slot(6, 1);
3609
+ p.text(",");
3610
+ p.slot(7, 1);
3611
+ p.text(" ");
3612
+ p.slot(8, 1);
3613
+ p.text("x");
3614
+ p.slot(9, 1);
3615
+ p.text(") layer=");
3616
+ p.slot(10, 1);
3617
+ p.text(" visible=");
3618
+ p.text(p.flag(11) ? "true" : "false");
3619
+ p.text(" enabled=");
3620
+ p.text(p.flag(12) ? "true" : "false");
3621
+ p.text(" focused=");
3622
+ p.text(p.flag(13) ? "true" : "false");
3623
+ p.text(" open=");
3624
+ p.text(p.flag(14) ? "true" : "false");
3625
+ if (p.flag(250)) {
3626
+ p.text(" gpu_size=");
3627
+ p.slot(15, 1);
3628
+ p.text("x");
3629
+ p.slot(16, 1);
3630
+ p.text(" gpu_scale=");
3631
+ p.slot(17, 1);
3632
+ p.text(" gpu_backend=");
3633
+ p.slot(18, 0);
3634
+ p.text(" gpu_pixel_format=");
3635
+ p.slot(19, 0);
3636
+ p.text(" gpu_present_mode=");
3637
+ p.slot(20, 0);
3638
+ p.text(" gpu_alpha_mode=");
3639
+ p.slot(21, 0);
3640
+ p.text(" gpu_color_space=");
3641
+ p.slot(22, 0);
3642
+ p.text(" gpu_vsync=");
3643
+ p.text(p.flag(23) ? "true" : "false");
3644
+ p.text(" gpu_status=");
3645
+ p.slot(24, 0);
3646
+ p.text(" gpu_present_path=");
3647
+ p.slot(25, 0);
3648
+ p.text(" gpu_frame=");
3649
+ p.slot(26, 1);
3650
+ p.text(" gpu_timestamp_ns=");
3651
+ p.slot(27, 1);
3652
+ p.text(" gpu_frame_interval_ns=");
3653
+ p.slot(28, 1);
3654
+ p.text(" gpu_input_count=");
3655
+ p.slot(29, 1);
3656
+ p.text(" gpu_input_timestamp_ns=");
3657
+ p.slot(30, 1);
3658
+ p.text(" gpu_input_latency_ns=");
3659
+ p.slot(31, 1);
3660
+ p.text(" gpu_input_latency_budget_ns=");
3661
+ p.slot(32, 1);
3662
+ p.text(" gpu_input_latency_budget_exceeded=");
3663
+ p.slot(33, 1);
3664
+ p.text(" gpu_input_latency_budget_ok=");
3665
+ p.text(p.flag(34) ? "true" : "false");
3666
+ p.text(" gpu_first_frame_latency_ns=");
3667
+ p.slot(35, 1);
3668
+ p.text(" gpu_first_frame_latency_budget_ns=");
3669
+ p.slot(36, 1);
3670
+ p.text(" gpu_first_frame_latency_budget_exceeded=");
3671
+ p.slot(37, 1);
3672
+ p.text(" gpu_first_frame_latency_budget_ok=");
3673
+ p.text(p.flag(38) ? "true" : "false");
3674
+ p.text(" gpu_nonblank=");
3675
+ p.text(p.flag(39) ? "true" : "false");
3676
+ p.text(" gpu_occluded=");
3677
+ p.text(p.flag(40) ? "true" : "false");
3678
+ p.text(" gpu_sample=0x");
3679
+ p.slot(41, 2);
3680
+ p.text(" present_fallback=");
3681
+ p.slot(42, 0);
3682
+ p.text(" present_fallback_needed=");
3683
+ p.slot(43, 1);
3684
+ p.text(" present_fallback_limit=");
3685
+ p.slot(44, 1);
3686
+ p.text(" present_fallback_command=\"");
3687
+ p.slot(45, 0);
3688
+ p.text("\" present_fallback_frames=");
3689
+ p.slot(46, 1);
3690
+ p.text(" present_mode=");
3691
+ p.slot(47, 0);
3692
+ p.text(" present_patch_bytes=");
3693
+ p.slot(48, 1);
3694
+ p.text(" present_patch_upserts=");
3695
+ p.slot(49, 1);
3696
+ p.text(" present_patch_evicts=");
3697
+ p.slot(50, 1);
3698
+ p.text(" present_retained_commands=");
3699
+ p.slot(51, 1);
3700
+ p.text(" canvas_revision=");
3701
+ p.slot(52, 1);
3702
+ p.text(" canvas_commands=");
3703
+ p.slot(53, 1);
3704
+ p.text(" canvas_frame_requires_render=");
3705
+ p.text(p.flag(54) ? "true" : "false");
3706
+ p.text(" canvas_frame_full_repaint=");
3707
+ p.text(p.flag(55) ? "true" : "false");
3708
+ p.text(" canvas_frame_batches=");
3709
+ p.slot(56, 1);
3710
+ p.text(" canvas_frame_encoder_commands=");
3711
+ p.slot(57, 1);
3712
+ p.text(" canvas_frame_encoder_cache_actions=");
3713
+ p.slot(58, 1);
3714
+ p.text(" canvas_frame_encoder_pipeline_binds=");
3715
+ p.slot(59, 1);
3716
+ p.text(" canvas_frame_encoder_draws=");
3717
+ p.slot(60, 1);
3718
+ p.text(" canvas_frame_pipelines=");
3719
+ p.slot(61, 1);
3720
+ p.text(" canvas_frame_pipeline_uploads=");
3721
+ p.slot(62, 1);
3722
+ p.text(" canvas_frame_pipeline_retains=");
3723
+ p.slot(63, 1);
3724
+ p.text(" canvas_frame_pipeline_evicts=");
3725
+ p.slot(64, 1);
3726
+ p.text(" canvas_frame_path_geometries=");
3727
+ p.slot(65, 1);
3728
+ p.text(" canvas_frame_path_vertices=");
3729
+ p.slot(66, 1);
3730
+ p.text(" canvas_frame_path_indices=");
3731
+ p.slot(67, 1);
3732
+ p.text(" canvas_frame_path_uploads=");
3733
+ p.slot(68, 1);
3734
+ p.text(" canvas_frame_path_retains=");
3735
+ p.slot(69, 1);
3736
+ p.text(" canvas_frame_path_evicts=");
3737
+ p.slot(70, 1);
3738
+ p.text(" canvas_frame_images=");
3739
+ p.slot(71, 1);
3740
+ p.text(" canvas_frame_image_uploads=");
3741
+ p.slot(72, 1);
3742
+ p.text(" canvas_frame_image_retains=");
3743
+ p.slot(73, 1);
3744
+ p.text(" canvas_frame_image_evicts=");
3745
+ p.slot(74, 1);
3746
+ p.text(" canvas_frame_layers=");
3747
+ p.slot(75, 1);
3748
+ p.text(" canvas_frame_opacity_layers=");
3749
+ p.slot(76, 1);
3750
+ p.text(" canvas_frame_clip_layers=");
3751
+ p.slot(77, 1);
3752
+ p.text(" canvas_frame_transform_layers=");
3753
+ p.slot(78, 1);
3754
+ p.text(" canvas_frame_layer_uploads=");
3755
+ p.slot(79, 1);
3756
+ p.text(" canvas_frame_layer_retains=");
3757
+ p.slot(80, 1);
3758
+ p.text(" canvas_frame_layer_evicts=");
3759
+ p.slot(81, 1);
3760
+ p.text(" canvas_frame_resources=");
3761
+ p.slot(82, 1);
3762
+ p.text(" canvas_frame_uploads=");
3763
+ p.slot(83, 1);
3764
+ p.text(" canvas_frame_retains=");
3765
+ p.slot(84, 1);
3766
+ p.text(" canvas_frame_evicts=");
3767
+ p.slot(85, 1);
3768
+ p.text(" canvas_frame_effects=");
3769
+ p.slot(86, 1);
3770
+ p.text(" canvas_frame_shadows=");
3771
+ p.slot(87, 1);
3772
+ p.text(" canvas_frame_blurs=");
3773
+ p.slot(88, 1);
3774
+ p.text(" canvas_frame_effect_uploads=");
3775
+ p.slot(89, 1);
3776
+ p.text(" canvas_frame_effect_retains=");
3777
+ p.slot(90, 1);
3778
+ p.text(" canvas_frame_effect_evicts=");
3779
+ p.slot(91, 1);
3780
+ p.text(" canvas_frame_glyphs=");
3781
+ p.slot(92, 1);
3782
+ p.text(" canvas_frame_glyph_uploads=");
3783
+ p.slot(93, 1);
3784
+ p.text(" canvas_frame_glyph_retains=");
3785
+ p.slot(94, 1);
3786
+ p.text(" canvas_frame_glyph_evicts=");
3787
+ p.slot(95, 1);
3788
+ p.text(" canvas_frame_text_layouts=");
3789
+ p.slot(96, 1);
3790
+ p.text(" canvas_frame_text_lines=");
3791
+ p.slot(97, 1);
3792
+ p.text(" canvas_frame_text_uploads=");
3793
+ p.slot(98, 1);
3794
+ p.text(" canvas_frame_text_retains=");
3795
+ p.slot(99, 1);
3796
+ p.text(" canvas_frame_text_evicts=");
3797
+ p.slot(100, 1);
3798
+ p.text(" canvas_frame_gpu_packet_commands=");
3799
+ p.slot(101, 1);
3800
+ p.text(" canvas_frame_gpu_packet_cache_actions=");
3801
+ p.slot(102, 1);
3802
+ p.text(" canvas_frame_gpu_packet_cached_resources=");
3803
+ p.slot(103, 1);
3804
+ p.text(" canvas_frame_gpu_packet_unsupported=");
3805
+ p.slot(104, 1);
3806
+ p.text(" canvas_frame_gpu_packet_representable=");
3807
+ p.text(p.flag(105) ? "true" : "false");
3808
+ p.text(" canvas_frame_changes=");
3809
+ p.slot(106, 1);
3810
+ p.text(" canvas_frame_budget_exceeded=");
3811
+ p.slot(107, 1);
3812
+ p.text(" canvas_frame_budget_ok=");
3813
+ p.text(p.flag(108) ? "true" : "false");
3814
+ p.text(" widget_nodes=");
3815
+ p.slot(109, 1);
3816
+ p.text("/");
3817
+ p.slot(110, 1);
3818
+ p.text(" widget_semantics=");
3819
+ p.slot(111, 1);
3820
+ p.text("/");
3821
+ p.slot(112, 1);
3822
+ p.text(" context_menu_items=");
3823
+ p.slot(113, 1);
3824
+ p.text("/");
3825
+ p.slot(114, 1);
3826
+ p.text(" text_layout_plans=");
3827
+ p.slot(115, 1);
3828
+ p.text("/");
3829
+ p.slot(116, 1);
3830
+ p.text(" text_layout_lines=");
3831
+ p.slot(117, 1);
3832
+ p.text("/");
3833
+ p.slot(118, 1);
3834
+ if (p.flag(252)) {
3835
+ p.text(" canvas_frame_dirty=(");
3836
+ p.slot(119, 1);
3837
+ p.text(",");
3838
+ p.slot(120, 1);
3839
+ p.text(" ");
3840
+ p.slot(121, 1);
3841
+ p.text("x");
3842
+ p.slot(122, 1);
3843
+ p.text(")");
3844
+ } else p.text(" canvas_frame_dirty=null");
3845
+ p.text(" canvas_frame_profile_work_units=");
3846
+ p.slot(123, 1);
3847
+ p.text(" canvas_frame_profile_risk=");
3848
+ p.slot(124, 0);
3849
+ p.text(" canvas_frame_profile_surface_area=");
3850
+ p.slot(125, 1);
3851
+ p.text(" canvas_frame_profile_dirty_area=");
3852
+ p.slot(126, 1);
3853
+ p.text(" canvas_frame_profile_dirty_ratio=");
3854
+ p.slot(127, 1);
3855
+ p.text(" widget_revision=");
3856
+ p.slot(128, 1);
3857
+ p.text(" widget_nodes=");
3858
+ p.slot(129, 1);
3859
+ p.text(" widget_semantics=");
3860
+ p.slot(130, 1);
3861
+ p.text(" widget_cursor=");
3862
+ p.slot(131, 0);
3863
+ }
3864
+ if (p.flag(251)) {
3865
+ p.text(" url=\"");
3866
+ p.slot(132, 0);
3867
+ p.text("\"");
3868
+ }
3869
+ p.text("\n");
3870
+ }
3871
+ } else if (mode === 4) {
3872
+ p.text(variant === 0 ? " widget @w" : "@w"); p.slot(0,1); p.text("/"); p.slot(1,0); p.text("#"); p.slot(2,1);
3873
+ p.text(" role="); p.slot(3,0); p.text(" name=\""); p.slot(4,0); p.text("\" bounds=("); p.slot(5,1); p.text(","); p.slot(6,1); p.text(" "); p.slot(7,1); p.text("x"); p.slot(8,1); p.text(")");
3874
+ if (variant === 0) { p.text(" focused="); p.text(p.flag(9) ? "true" : "false"); p.text(" enabled="); p.text(p.flag(10) ? "true" : "false"); }
3875
+ if (p.flag(11)) { p.text(" parent=#"); p.slot(11,1); }
3876
+ if (p.flag(12)) { p.text(" value="); p.slot(12,1); }
3877
+ if (p.flag(13)) { p.text(" text=\""); p.slot(13,0); p.text("\""); }
3878
+ if (variant === 0 && p.flag(14)) { p.text(" placeholder=\""); p.slot(14,0); p.text("\""); }
3879
+ const grid = ["row_index", "column_index", "row_count", "column_count"];
3880
+ let wrote = false;
3881
+ for (let i = 0; i < 4; i++) if (p.flag(15+i)) { p.text(wrote ? "," : " grid=["); p.text(grid[i]!); p.text("="); p.slot(15+i,1); wrote = true; }
3882
+ if (wrote) p.text("]");
3883
+ if (p.flag(19)) { p.text(" list=[index="); p.slot(20,1); p.text(",count="); p.slot(21,1); p.text("]"); }
3884
+ if (p.flag(22)) { p.text(" scroll=[offset="); p.slot(23,1); p.text(",viewport="); p.slot(24,1); p.text(",content="); p.slot(25,1); p.text("]"); }
3885
+ if (p.flag(26)) { const names=["start", "end", "first", "last", "rendered"]; p.text(" virtual=["); for (let i=0;i<5;i++) { if(i>0)p.text(",");p.text(names[i]!);p.text("=");p.slot(27+i,1); }p.text("]"); }
3886
+ const states=["focused", "disabled", "hovered", "pressed", "selected", "expanded", "collapsed", "required", "read_only", "invalid"];
3887
+ wrote=false;
3888
+ for(let i=0;i<states.length;i++) if(p.flag(32+i)) {p.text(wrote ? "," : " state=[");p.text(states[i]!);wrote=true;} if(wrote)p.text("]");
3889
+ const actions=["focus", "press", "toggle", "increment", "decrement", "set_text", "set_selection", "select", "drag", "drop_files", "dismiss"];
3890
+ wrote=false;
3891
+ for(let i=0;i<actions.length;i++) if(p.flag(42+i)) {p.text(wrote ? "," : " actions=[");p.text(actions[i]!);wrote=true;} if(wrote)p.text("]");
3892
+ if(p.flag(53)){p.text(" selection=");p.slot(54,1);p.text("..");p.slot(55,1);}
3893
+ if(p.flag(56)){p.text(" composition=");p.slot(57,1);p.text("..");p.slot(58,1);}
3894
+ if(p.flag(59)){p.text(" context_menu=[");p.children(11);p.text("]");}
3895
+ p.text("\n");
3896
+ } else if (mode === 5) {
3897
+ if(p.flag(0))p.text(",");
3898
+ if(p.flag(1))p.text("separator");else{p.text("\"");p.slot(2,0);p.text("\"");if(!p.flag(3))p.text("(disabled)");}
3899
+ } else if (mode === 6) {
3900
+ p.text("command id=");p.quoted(0);p.text(" title=");p.quoted(1);p.text(" enabled=");p.text(p.flag(2)?"true":"false");p.text(" checked=");p.text(p.flag(3)?"true":"false");p.text("\n");
3901
+ } else if (mode === 7) {
3902
+ p.text("app-menu title=");p.quoted(0);p.text(" items=");p.slot(1,1);p.text("\n");p.children(12);
3903
+ } else if (mode === 8) {
3904
+ if(p.flag(0))p.text(" app-menu-item separator\n");else{
3905
+ p.text(" app-menu-item label=");p.quoted(1);p.text(" command=");p.quoted(2);p.text(" enabled=");p.text(p.flag(3)?"true":"false");p.text(" checked=");p.text(p.flag(4)?"true":"false");p.text(" key=");p.quoted(5);
3906
+ const names=["primary", "command", "control", "option", "shift"];p.text(" modifiers=(");for(let i=0;i<5;i++){if(i>0)p.text(",");p.text(names[i]!);p.text("=");p.text(p.flag(6+i)?"true":"false");}p.text(")\n");
3907
+ }
3908
+ } else if (mode === 9) {
3909
+ p.text("tray #");p.slot(0,1);p.text(" title=\"");p.slot(1,0);p.text("\" visible=");p.text(p.flag(2)?"true":"false");p.text(" items=");p.slot(3,1);p.text("\n");p.children(13);
3910
+ } else if (mode === 10) {
3911
+ if(p.flag(0))p.text(" tray-item separator\n");else{
3912
+ p.text(" tray-item #");p.slot(1,1);
3913
+ if(p.flag(2)){p.text(" role=segmented options=");p.slot(3,1);p.text("\n");p.children(14);}
3914
+ else if(p.flag(4)){p.text(" role=metric primary=");p.quoted(5);p.text(" secondary=");p.quoted(6);p.text(" accessibility=");p.quoted(7);p.text("\n");}
3915
+ else if(p.flag(8)){p.text(" role=chart caption=");p.quoted(9);p.text(" summary=");p.quoted(10);p.text(" accessibility=");p.quoted(11);p.text(" domain=(");p.slot(12,1);p.text(",");p.slot(13,1);p.text(") values=");p.children(15);p.text("\n");}
3916
+ else{p.text(" label=\"");p.slot(14,0);p.text("\" command=\"");p.slot(15,0);p.text("\" enabled=");p.text(p.flag(16)?"true":"false");p.text(" detail=\"");p.slot(17,0);p.text("\" role=");p.slot(18,0);p.text(" key=\"");p.slot(19,0);p.text("\" modifiers=(");const names=["primary", "command", "control", "option", "shift"];for(let i=0;i<5;i++){if(i>0)p.text(",");p.text(names[i]!);p.text("=");p.text(p.flag(20+i)?"true":"false");}p.text(")\n");}
3917
+ }
3918
+ } else if (mode === 11) {
3919
+ p.text(" tray-segment #");p.slot(0,1);p.text(" label=");p.quoted(1);p.text(" command=");p.quoted(2);p.text(" selected=");p.text(p.flag(3)?"true":"false");p.text(" enabled=");p.text(p.flag(4)?"true":"false");p.text("\n");
3920
+ } else if (mode === 12) { if(p.flag(0))p.text(",");p.slot(1,1);
3921
+ } else if (mode === 13) {
3922
+ p.text("audio key=");p.slot(0,1);p.text(" state=");p.text(p.flag(1)?"buffering":p.flag(2)?"playing":"paused");p.text(" source=");p.slot(3,0);p.text(" position_ms=");p.slot(4,1);p.text(" duration_ms=");p.slot(5,1);p.text(" spectrum_events=");p.slot(6,1);if(p.flag(6)){p.text(" spectrum_bands=");p.slot(7,5);}p.text("\n");
3923
+ } else if (mode === 14) {
3924
+ p.text("video key=");p.slot(0,1);p.text(" surface=");p.slot(1,1);p.text(" state=");p.text(p.flag(2)?"buffering":p.flag(3)?"playing":"paused");p.text(" source=");p.slot(4,0);p.text(" position_ms=");p.slot(5,1);p.text(" duration_ms=");p.slot(6,1);p.text(" dimensions=");p.slot(7,1);p.text("x");p.slot(8,1);p.text(" loop=");p.text(p.flag(9)?"true":"false");p.text(" muted=");p.text(p.flag(10)?"true":"false");p.text("\n");
3925
+ } else if (mode === 15) {
3926
+ p.text(" error event=");p.slot(0,0);p.text(" name=");p.slot(1,0);if(p.flag(2)){p.text(" detail=\"");p.slot(2,0);p.text("\"");}p.text(" timestamp_ns=");p.slot(3,1);p.text("\n");
3927
+ } else if (mode === 16) { p.text(" source kind=");p.slot(0,0);p.text(" bytes=");p.slot(1,1);p.text("\n");
3928
+ } else throw new Error("unknown snapshot serialization record");
3929
+ return p.result();
3930
+ }