@native-sdk/cli 0.9.0 → 0.9.2

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 (181) hide show
  1. package/build/app.zig +357 -33
  2. package/build.zig +234 -11
  3. package/native-sdk.d.ts +8 -0
  4. package/package.json +10 -10
  5. package/packages/core/compile-surface/core.ts +70 -1
  6. package/packages/core/package-lock.json +11 -11
  7. package/packages/core/package.json +2 -2
  8. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  9. package/packages/core/scripts/run_external_core_compiler.mjs +52 -7
  10. package/packages/core/scripts/run_external_service_compiler.mjs +53 -13
  11. package/packages/core/scripts/stage_external_services.mjs +1 -1
  12. package/packages/core/sdk/core.d.ts +75 -0
  13. package/packages/core/sdk/core.ts +170 -13
  14. package/packages/core/sdk/events.d.ts +53 -0
  15. package/packages/core/sdk/events.ts +78 -7
  16. package/packages/core/src/checker.ts +470 -2
  17. package/packages/core/src/cli.ts +13 -0
  18. package/packages/core/src/contract.ts +3 -1
  19. package/packages/core/src/devhost.ts +30 -1
  20. package/packages/core/src/devhost_journal.mjs +10 -8
  21. package/packages/core/src/diagnostics.ts +99 -8
  22. package/packages/core/src/frontend.ts +6 -0
  23. package/packages/core/src/infer.ts +24 -0
  24. package/skill-data/automation/SKILL.md +1 -1
  25. package/skill-data/native-ui/SKILL.md +18 -12
  26. package/skill-data/ts-core/SKILL.md +54 -21
  27. package/skill-data/ts-services/SKILL.md +4 -4
  28. package/skill-data/ts-services/references/service-surface.md +2 -1
  29. package/skill-data/zig/SKILL.md +1 -1
  30. package/src/app_runner/root.zig +122 -6
  31. package/src/app_runner/ts_core_main.zig +9 -4
  32. package/src/app_runner/ts_core_mobile.zig +241 -0
  33. package/src/app_runner/window_placement.zig +63 -0
  34. package/src/automation/protocol.zig +5 -1
  35. package/src/automation/snapshot.zig +8 -6
  36. package/src/embed/app_exports.zig +3 -1
  37. package/src/embed/conversions.zig +1 -0
  38. package/src/embed/host.zig +10 -3
  39. package/src/embed/root.zig +2 -0
  40. package/src/embed/tests.zig +41 -1
  41. package/src/embed/types.zig +2 -0
  42. package/src/embed/ui_host.zig +94 -4
  43. package/src/platform/android/NativeSdkActivity.java +49 -4
  44. package/src/platform/android/android_host.c +3 -3
  45. package/src/platform/android/native_sdk_app.h +1 -1
  46. package/src/platform/ios/apple_image_fit.h +38 -0
  47. package/src/platform/ios/files.zig +1 -0
  48. package/src/platform/ios/native_sdk_app.h +1 -1
  49. package/src/platform/ios/uikit_host.m +28 -5
  50. package/src/platform/linux/cef_host.cpp +17 -3
  51. package/src/platform/linux/gtk_host.c +243 -15
  52. package/src/platform/linux/gtk_host.h +5 -4
  53. package/src/platform/linux/root.zig +91 -11
  54. package/src/platform/macos/appkit_host.h +18 -11
  55. package/src/platform/macos/appkit_host.m +402 -128
  56. package/src/platform/macos/cef_host.mm +342 -122
  57. package/src/platform/macos/image_fit_test.m +44 -0
  58. package/src/platform/macos/root.zig +231 -39
  59. package/src/platform/null_platform.zig +251 -54
  60. package/src/platform/null_platform_tests.zig +97 -4
  61. package/src/platform/root.zig +12 -0
  62. package/src/platform/types.zig +174 -35
  63. package/src/platform/windows/root.zig +42 -13
  64. package/src/platform/windows/webview2_host.cpp +72 -11
  65. package/src/primitives/app_manifest/root.zig +3 -0
  66. package/src/primitives/app_manifest/tests.zig +24 -0
  67. package/src/primitives/app_manifest/types.zig +13 -0
  68. package/src/primitives/app_manifest/validation.zig +24 -0
  69. package/src/primitives/canvas/a11y_audit.zig +9 -7
  70. package/src/primitives/canvas/a11y_audit_tests.zig +24 -0
  71. package/src/primitives/canvas/events.zig +50 -0
  72. package/src/primitives/canvas/layout_audit.zig +6 -6
  73. package/src/primitives/canvas/markdown.zig +4 -0
  74. package/src/primitives/canvas/markdown_tests.zig +1 -0
  75. package/src/primitives/canvas/png.zig +138 -0
  76. package/src/primitives/canvas/root.zig +13 -2
  77. package/src/primitives/canvas/text_span_tests.zig +5 -3
  78. package/src/primitives/canvas/text_spans.zig +2 -0
  79. package/src/primitives/canvas/text_tests.zig +20 -0
  80. package/src/primitives/canvas/ui.zig +55 -2
  81. package/src/primitives/canvas/ui_markup.zig +40 -13
  82. package/src/primitives/canvas/ui_markup_binary.zig +8 -6
  83. package/src/primitives/canvas/ui_markup_binary_tests.zig +14 -4
  84. package/src/primitives/canvas/ui_markup_compiled.zig +5 -1
  85. package/src/primitives/canvas/ui_markup_compiled_tests.zig +52 -0
  86. package/src/primitives/canvas/ui_markup_tests.zig +11 -2
  87. package/src/primitives/canvas/ui_markup_view.zig +8 -2
  88. package/src/primitives/canvas/ui_markup_view_tests.zig +49 -4
  89. package/src/primitives/canvas/ui_schema.zig +17 -13
  90. package/src/primitives/canvas/ui_tests.zig +47 -0
  91. package/src/primitives/canvas/widget_access.zig +3 -3
  92. package/src/primitives/canvas/widget_anchored_tests.zig +106 -0
  93. package/src/primitives/canvas/widget_builtin_tests.zig +580 -32
  94. package/src/primitives/canvas/widget_invalidation.zig +33 -6
  95. package/src/primitives/canvas/widget_layout.zig +333 -126
  96. package/src/primitives/canvas/widget_layout_tests.zig +169 -0
  97. package/src/primitives/canvas/widget_metrics.zig +7 -8
  98. package/src/primitives/canvas/widget_render.zig +76 -44
  99. package/src/primitives/canvas/widget_render_controls.zig +110 -32
  100. package/src/primitives/canvas/widget_render_style.zig +58 -18
  101. package/src/primitives/canvas/widget_render_surfaces.zig +45 -14
  102. package/src/primitives/canvas/widget_routing.zig +40 -34
  103. package/src/primitives/canvas/widget_runtime.zig +11 -2
  104. package/src/primitives/canvas/widget_runtime_tests.zig +10 -14
  105. package/src/primitives/canvas/widget_semantics.zig +8 -3
  106. package/src/primitives/canvas/widget_semantics_tests.zig +6 -2
  107. package/src/primitives/canvas/widget_tree.zig +99 -5
  108. package/src/primitives/canvas/widgets.zig +20 -7
  109. package/src/root.zig +10 -0
  110. package/src/runtime/api.zig +14 -0
  111. package/src/runtime/automation_commands.zig +35 -2
  112. package/src/runtime/automation_snapshot.zig +32 -24
  113. package/src/runtime/automation_widget_dispatch.zig +48 -6
  114. package/src/runtime/bridge_permission_tests.zig +35 -1
  115. package/src/runtime/bridge_responses.zig +1 -1
  116. package/src/runtime/builtin_bridge.zig +16 -3
  117. package/src/runtime/canvas_frame_packet_tests.zig +22 -13
  118. package/src/runtime/canvas_image_tests.zig +146 -2
  119. package/src/runtime/canvas_images.zig +35 -16
  120. package/src/runtime/canvas_limits.zig +13 -3
  121. package/src/runtime/canvas_widget_accessibility_tests.zig +279 -4
  122. package/src/runtime/canvas_widget_anchored_tests.zig +54 -0
  123. package/src/runtime/canvas_widget_control_tests.zig +31 -1
  124. package/src/runtime/canvas_widget_events.zig +151 -26
  125. package/src/runtime/canvas_widget_floating_tests.zig +48 -0
  126. package/src/runtime/canvas_widget_runtime.zig +322 -102
  127. package/src/runtime/canvas_widget_scroll_driver_tests.zig +34 -0
  128. package/src/runtime/canvas_widget_scroll_drivers.zig +12 -10
  129. package/src/runtime/canvas_widget_scroll_tests.zig +193 -2
  130. package/src/runtime/canvas_widget_semantics_tests.zig +337 -3
  131. package/src/runtime/canvas_widget_split_tree_tests.zig +55 -0
  132. package/src/runtime/canvas_widget_state.zig +33 -7
  133. package/src/runtime/core.zig +28 -6
  134. package/src/runtime/effects.zig +1337 -49
  135. package/src/runtime/effects_file_tests.zig +587 -0
  136. package/src/runtime/effects_image_tests.zig +91 -0
  137. package/src/runtime/effects_notification_tests.zig +11 -0
  138. package/src/runtime/file_access.zig +400 -0
  139. package/src/runtime/file_effect_crash_helper.zig +28 -0
  140. package/src/runtime/file_effect_crash_tests.zig +37 -0
  141. package/src/runtime/flow.zig +21 -9
  142. package/src/runtime/gpu_surface_events.zig +25 -2
  143. package/src/runtime/native_command_event_tests.zig +44 -2
  144. package/src/runtime/pty.zig +5 -2
  145. package/src/runtime/root.zig +7 -0
  146. package/src/runtime/session_blobs.zig +4 -1
  147. package/src/runtime/session_journal.zig +56 -5
  148. package/src/runtime/session_record.zig +38 -0
  149. package/src/runtime/session_replay.zig +110 -15
  150. package/src/runtime/session_tests.zig +192 -4
  151. package/src/runtime/shell_layout_tests.zig +12 -0
  152. package/src/runtime/state.zig +10 -0
  153. package/src/runtime/system_services.zig +129 -36
  154. package/src/runtime/ts_core_host.zig +281 -11
  155. package/src/runtime/ts_core_host_tests.zig +142 -1
  156. package/src/runtime/ts_ui_app.zig +461 -8
  157. package/src/runtime/ui_app.zig +330 -112
  158. package/src/runtime/ui_app_tests.zig +251 -25
  159. package/src/runtime/ui_app_window_tests.zig +74 -8
  160. package/src/runtime/validation.zig +20 -0
  161. package/src/runtime/view.zig +3 -0
  162. package/src/runtime/view_widget_control.zig +18 -0
  163. package/src/runtime/view_widget_scroll.zig +112 -18
  164. package/src/runtime/view_widget_tree.zig +110 -13
  165. package/src/runtime/widget_bridge.zig +2 -0
  166. package/src/runtime/window_command_bridge_tests.zig +86 -0
  167. package/src/runtime/window_storage.zig +16 -1
  168. package/src/runtime/window_views.zig +1 -0
  169. package/src/tooling/ios.zig +3 -0
  170. package/src/tooling/manifest.zig +90 -2
  171. package/src/tooling/package.zig +67 -2
  172. package/src/tooling/raw_manifest.zig +10 -0
  173. package/src/tooling/templates.zig +156 -18
  174. package/src/tooling/ts_core.zig +83 -0
  175. package/src/tooling/web_engine.zig +1 -1
  176. package/tools/corewire/emit.zig +3 -3
  177. package/tools/corewire/emit_facade.zig +65 -5
  178. package/tools/corewire/emit_profile.zig +2 -2
  179. package/tools/corewire/emit_service.zig +2 -2
  180. package/tools/corewire/service_contract.zig +4 -4
  181. package/tools/corewire/sidecar.zig +4 -4
@@ -49,6 +49,11 @@ export interface FrontendOptions {
49
49
  /// Generated @native-sdk/core surface carrying declared SQLite query
50
50
  /// constructors. Omitted for non-relational apps and direct checker tests.
51
51
  readonly sdkCorePath?: string;
52
+ /// Statically compiled secondary-window view labels discovered from direct
53
+ /// `src/windows/<label>.native` children. Undefined keeps core-only checker
54
+ /// use independent of an app tree; an empty set means app validation is
55
+ /// active and the app supplies no secondary-window roots.
56
+ readonly windowViews?: readonly string[];
52
57
  }
53
58
 
54
59
  export interface FrontendResult {
@@ -204,6 +209,7 @@ export function checkFile(entry: string, options: FrontendOptions = {}): Fronten
204
209
  options.permissions ?? [],
205
210
  options.persistRoutes,
206
211
  options.sdkCorePath,
212
+ options.windowViews,
207
213
  );
208
214
  const checkResult = checker.check();
209
215
  if (checkResult.diagnostics.length > 0) {
@@ -549,6 +549,30 @@ export class IntInference {
549
549
  }
550
550
  }
551
551
  }
552
+ // `windows(model)` returns host-consumed geometry. Those number slots
553
+ // are canvas points, so whole-valued descriptors must not accidentally
554
+ // specialize the canonical WindowDescriptor fields to i64 — another
555
+ // model may return fractional positions or dimensions through the same
556
+ // SDK record. Mark the descriptor's immediate number fields as boundary
557
+ // values, exactly like a host-constructed event record in reverse.
558
+ if (stmt.name?.text === "windows" && stmt.type) {
559
+ const returned = this.table.resolveTypeNode(stmt.type);
560
+ if (returned.k === "slice" && returned.elem.k === "struct") {
561
+ const descriptor = this.table.structs.get(returned.elem.name);
562
+ if (descriptor) {
563
+ for (const f of descriptor.fields) {
564
+ const numeric = f.type.k === "number" || (f.type.k === "optional" && f.type.inner.k === "number");
565
+ if (!numeric) continue;
566
+ const slot = this.slots.get(f.decl);
567
+ if (slot) {
568
+ slot.external = true;
569
+ slot.hostBoundary = true;
570
+ slot.proven = false;
571
+ }
572
+ }
573
+ }
574
+ }
575
+ }
552
576
  }
553
577
  }
554
578
 
@@ -117,7 +117,7 @@ Semantics:
117
117
  10. Use `native automate widget-key <view-label> <key> [text]` for focused retained widget keyboard input. The key accepts modifier chords — `cmd+a`, `cmd+c`, `cmd+v`, `cmd+x`, `ctrl+shift+arrowleft` (`cmd` sets the primary shortcut modifier on every platform) — so select-all/copy/cut/paste and shift-extended selection are drivable; after a copy, widget lines in the snapshot show the live selection as `selection=a..b`, and the copied text lands on the real system clipboard (`pbpaste` on macOS).
118
118
  11. Use `native automate widget-pinch <view-label> <scale> [x y]` for trackpad pinch gestures against a gpu-surface view: the runtime dispatches the real `pinch_begin`/`pinch_change`/`pinch_end` platform events, with one change carrying `scale - 1`. `<scale>` is the FINAL multiplicative zoom for the gesture — the cumulative gesture scale (the product of `1 + delta`) lands exactly on it — `1.5` zooms in 50%, `0.5` zooms out to half. The optional anchor point is view-local points, defaulting to the view center. Apps hear it through the pinch channel (`Options.on_pinch` / the TS core's `pinchMsg`).
119
119
  12. Use `native automate screenshot <view-label> [scale]` to capture the named `gpu_surface` view's canvas as `screenshot-<view-label>.png` (the CLI prints the artifact path and waits for the file).
120
- 13. Use `native automate tray-action <item-id>` to select a status-item dropdown row through the same platform event a real menu-bar click emits (command dispatch with source `.tray`). The live tray is visible in `snapshot.txt` as a `tray title="..." items=N` line followed by ` tray-item #id label="..." command="..." enabled=...` rows — the macOS menu bar is outside every window capture, so the snapshot is the only automation evidence the model-driven tray exists, and the `#id` there is what `tray-action` takes. Unknown ids degrade into the dispatch-error ring as `automation.tray_action`.
120
+ 13. Use `native automate tray-action <item-id>` for the primary status item, or `native automate tray-action <status-item-id> <item-id>` for an explicit item. Both select a dropdown row through the same platform event a real menu-bar click emits (command dispatch with source `.tray`). Live items appear in `snapshot.txt` as `tray #status-id title="..." visible=... items=N` followed by ` tray-item #item-id ...` rows — the menu bar is outside every window capture, so this is the automation evidence for every model-driven item. Unknown id pairs degrade into the dispatch-error ring as `automation.tray_action`.
121
121
  14. Use `native automate reload` to request a WebView reload.
122
122
  15. Use `native automate profile on` to enable per-stage frame timing: while on, `snapshot.txt` carries a `frame_profile` line with rolling p50/p90/max microseconds per pipeline stage (`rebuild`, `layout`, `reconcile`, `emit`, `a11y`, `plan`, `patch`, `encode`, `present`, `host_decode`, `host_draw`), each with a lifetime sample count (`<stage>_n=`). Drive some interactions, then `native automate snapshot | grep -o 'frame_profile.*'` to read where frame time goes; `profile off` stops recording and drops the line. Turning it on starts a fresh sample window.
123
123
 
@@ -153,7 +153,7 @@ Zero app code: on macOS every non-virtualized `scroll` region — and every wind
153
153
 
154
154
  Authors write ONE menu; the platform decides how it presents. The default is the real OS context menu at the pointer — `NSMenu` on macOS, `TrackPopupMenu` on Windows, `GtkPopoverMenu` on Linux — and the selection dispatches the item's typed `Msg`. On hosts without a native menu presenter (the mobile toolkit hosts and embed hosts today), the SAME declared items present automatically as an anchored canvas surface at the click point, with the standard anchored-surface behavior (Escape and outside-click dismiss, late z-pass, window clipping). Never two authored menus, never a canvas imitation where the OS menu exists.
155
155
 
156
- Markup declares the menu as a `<context-menu>` element — a DIRECT child of the pressable element whose right-click it answers (a hit target, or an element with a bound `on-press`/`on-hold`). It is metadata, not content: it renders nothing in the row's flow. Children are `menu-item`s (`on-press` required, `disabled` optional, the text content is the label) and bare `<separator/>`s, with `if`/`else`/`for` around them to swap or repeat items — a menu whose items all evaporate at runtime simply declares no menu (the All Notes row pattern). Conditional MENUS are spelled as conditional ITEMS: the `<context-menu>` itself takes no attributes and cannot sit behind a structure tag. No submenus: the platform channel carries flat items (label, enabled, separator) only.
156
+ Markup declares the menu as a `<context-menu>` element — a DIRECT child of the interactive element whose right-click it answers (a hit-target kind, or an element made interactive by `on-press`/`on-double-press`/`on-toggle`/`on-hold`/`on-drag`). It is metadata, not content: it renders nothing in the row's flow. Children are `menu-item`s (`on-press` required, `disabled` optional, the text content is the label) and bare `<separator/>`s, with `if`/`else`/`for` around them to swap or repeat items — a menu whose items all evaporate at runtime simply declares no menu (the All Notes row pattern). Conditional MENUS are spelled as conditional ITEMS: the `<context-menu>` itself takes no attributes and cannot sit behind a structure tag. No submenus: the platform channel carries flat items (label, enabled, separator) only.
157
157
 
158
158
  ```html
159
159
  <list-item on-press="open_note:{n.id}" label="{n.title}">
@@ -196,19 +196,19 @@ Automation drives the native path honestly: snapshots list every widget's declar
196
196
  | `stack`, `panel`, `card` | overlay containers | children stack on top of each other — `gap` can never space them and is a validation error (put a `column`/`row` inside for flow) |
197
197
  | `scroll` | scroll_view | wrap multiple children in a `column` inside it |
198
198
  | `list`, `grid` | list, grid | vertical stack / cell grid |
199
- | `tabs`, `toggle-group`, `button-group`, `radio-group`, `breadcrumb`, `pagination` | row containers | children flow horizontally (tab buttons, toggle-buttons, radios, ...) |
199
+ | `tabs`, `toggle-group`, `button-group`, `radio-group`, `breadcrumb`, `pagination` | row containers | children flow horizontally. Give every `radio-group` an accessible `label`; it is one logical `radiogroup`: descendant radios at any nesting depth share one Tab stop; arrows wrap while Home/End move to the edges, focus and selection move together, and selecting one clears the rest of the nearest group scope |
200
200
  | `table` > `table-row` > `table-cell` | table, data_row, data_cell | rows only inside a table, cells only inside a row (for/if wrappers are fine); cells are text leaves, dispatch with `on-press` |
201
201
  | `dropdown-menu` | dropdown_menu | vertical menu surface; children are `menu-item`s. `anchor="below\|above"` floats it against its PARENT's frame (see Pickers): late z-pass above the whole tree, window-clipped, auto-flipping at the window edges, zero flow space. Pair with `on-dismiss` |
202
202
  | `accordion` | accordion | header via `text` attr; children show while `selected`, dispatch `on-toggle` |
203
203
  | `alert`, `bubble` | surfaces | `alert` title via `text` attr; children stack inside. `bubble` hugs its message up to 80% of the thread (`ghost` exempt; explicit `width` wins) and takes one `<reactions>` child — the reaction pill straddling its bottom edge, one text run, dock via `text-alignment` (default `end`); `text=` on bubble itself is a teaching error (that channel belongs to the pill). Grouped runs are spacing, not vocabulary: 8 gap within a sender's run, 32 between turns |
204
- | `dialog`, `drawer`, `sheet` | modal surfaces | rendered in place — title via `text` attr, wrap in `<if>` to show conditionally |
204
+ | `dialog`, `drawer`, `sheet` | modal surfaces | root-relative and unaffected by ancestor scroll or clipping: dialogs center in the viewport, drawers span its width and dock to the bottom, and sheets span its height and dock to the right — title via `text` attr, wrap in `<if>` to show conditionally |
205
205
  | `resizable` | resizable | engine-managed drag handle; `width` sets the initial width |
206
206
  | `split` | split | two-pane horizontal splitter: exactly two element children (nest splits for more panes), the engine synthesizes the draggable divider between them. `value` binds the model-owned first-pane fraction (0 lays out at 0.5), `on-resize` names an f32 Msg variant dispatched with every applied fraction (echo it back through `value` — see Splitters), `min-width` on the panes bounds the drag, `gap` sets the divider band thickness. The divider is focusable: Left/Right (Shift for bigger steps) adjust, Home/End jump to the clamp edges |
207
207
  | `tree` | tree | disclosure-tree container (vertical flow): descendant rows carrying `role="treeitem"` — at ANY nesting depth — form one roving keyboard focus set with the ARIA tree keymap. Up/Down walk visible rows (selection follows focus through each row's `on-press`), Left collapses an expanded row or moves to the parent row, Right expands a collapsed row or moves to the first child row, Home/End jump to the edges, Enter/Space activate. Expandable rows bind `expanded` and `on-toggle`; the model owns selection and expansion (collapsed children are simply not rendered) |
208
208
  | `text`, `badge`, `tooltip` | text leaves | text content, `{}` interpolation allowed; `text` line policy via `wrap` (`"true"` word-wraps; `"false"`/unset paint one honest line, overflow eliding by default — `overflow="clip"` opts out), and `text` alone takes the typography rungs `size="heading"`/`size="display"` (themable token steps above title — section headings, hero stats, timer numerals). `tooltip` with `anchor="above\|below"` floats against its parent (the stack wrapping trigger + tooltip, the dropdown pattern) and the RUNTIME owns its visibility — hover intent on the trigger: shows after `tooltip-delay` ms (default 600; `"0"` = instant) and immediately on keyboard focus; hides on leave, focus departure, Escape, or a press of the trigger (a press also closes the warm window), and a shared 400ms warm window after a pointer-hovered tooltip hides on leave (the only hide that warms) shows the next trigger's tooltip instantly; the model never hears hover. These are shadcn/ui's defaults (Base UI). Without `anchor` it stays a static leaf that paints whenever the view renders it |
209
209
  | `text` > `span` | inline styled runs | mixed-style text in ONE wrapped paragraph: span children style runs with `weight="regular\|medium\|bold"`, `mono`, `italic`, `scale` (a positive multiplier on the paragraph's base size — inline headings, hero stats), `underline`, `foreground` (token name); `{bindings}` interpolate inside spans; whitespace between runs collapses to a single space (none = the runs abut); spans do not nest, take no events, and the paragraph announces as one text run — see "Rich text" |
210
210
  | `button`, `toggle-button`, `list-item`, `menu-item`, `toggle`, `switch`, `select`, `avatar` | text-bearing controls | label is the text content; `button`, `toggle-button`, `list-item`, and `menu-item` also take `icon="save"` — a vector icon drawn inline (buttons/toggle-buttons before the label, icon-only when the content is empty: add a `label`; list/menu items as a leading slot), ONE hit target whose icon follows the element's enabled/disabled tint (no overlay stacking, no duplicated `on-press`); tab strips are `toggle-button` children, so tabs get icons this way; `select` shows `placeholder` while empty and dispatches `on-press`; `avatar` renders initials, or a runtime image via `image="{binding}"` (see the Images section) |
211
- | `checkbox`, `radio`, `slider`, `progress` | value controls | `checked`, `value` (a 0..1 fraction on slider and progress; progress clamps out-of-range values at render, never an error); the checkbox/radio label rides `text="..."` — these are not text-bearing elements, so text content is a teaching error (`label=` alone names one for accessibility without a visible label); a slider's `value` follows the source when it MOVES (model-driven progress renders every rebuild) and keeps the user's drag while the source replays the same value — use `slider` for seek bars, `progress` for display-only; a markup slider's `on-change` dispatches a PLAIN Msg with no value payload — mirror the applied value into the model with `Options.sync` (the Zig builder's `on_value = Ui.valueMsg(.tag)` does deliver the applied f32) |
211
+ | `checkbox`, `radio`, `slider`, `progress` | value controls | `checked`, `value` (a 0..1 fraction on slider and progress; progress clamps out-of-range values at render, never an error); checkbox/radio visible labels are text content (`<checkbox>Done</checkbox>`), with `text="..."` as the equivalent binding-friendly form and `label=` alone naming one for accessibility without drawing a label; a radio selection TRANSITION (pointer, Space/Enter, grouped navigation, or accessibility selection) dispatches `on-change` when bound, then `on-toggle`, then `on-press` for compatibility — reactivating the already-checked radio has no new `on-change` edge, though a legacy fallback still receives the activation; a slider's `value` follows the source when it MOVES (model-driven progress renders every rebuild) and keeps the user's drag while the source replays the same value — use `slider` for seek bars, `progress` for display-only; a markup slider's `on-change` dispatches a PLAIN Msg with no value payload — mirror the applied value into the model with `Options.sync` (the Zig builder's `on_value = Ui.valueMsg(.tag)` does deliver the applied f32) |
212
212
  | `text-field`, `input`, `search-field`, `combobox`, `textarea` | text entry | `placeholder`; edits via `on-input`, enter via `on-submit` on single-line kinds; in a default `textarea`, Enter (and Shift+Enter) inserts a newline and `on-submit` dispatches on primary+Enter (cmd on macOS, ctrl elsewhere). A chat composer opts into `submit-on-enter="true"`: plain Enter submits, Shift+Enter remains a newline, and the primary chord still submits. `search-field` carries a built-in trailing clear affordance whenever it holds text (press the x, or Escape while focused — both clear through the text-edit path, so `on-input` hears it; no attribute, no external Clear button needed) |
213
213
  | `status-bar` | status bar | text leaf: content only, no children |
214
214
  | `separator`, `spacer` | separator, flexible space | `separator` is axis-aware: a horizontal rule in a `column`, a thin vertical divider in a `row`; give `spacer` a `grow` |
@@ -221,7 +221,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
221
221
  | `stepper` > `step` | composite stage track | `active="{index}"` (required) derives each step's completed/active/pending state; steps are text leaves (no attributes) joined by connectors; stepper also takes `key`, `global-key`, `label` |
222
222
  | `timeline` > `timeline-item` | composite ledger list | items only inside a timeline (for/if fine); items are leaves — `title` (required), `description`, `meta`, `indicator`, `variant`, `connector="false"` on the last item, `selected`; `on-press` makes the whole item pressable with a trailing chevron |
223
223
  | `chart` > `series` | composite data chart | series only inside a chart, and only series (the set is static — data varies through bindings); each series is a leaf — `values="{binding}"` (required) names a model `[]const f32` iterable, `kind` is `line`/`area`/`bar` (literal), `color` a token name, `label` the semantics name; chart takes `y-min`, `y-max`, `grid-lines`, `baseline`, `x-labels`, `y-labels`, `hover-details`, `stroke-width`, box options, `label` — see "Charts" |
224
- | `context-menu` | consumed by its parent | right-click menu on its DIRECT parent (a hit target or an element with `on-press`/`on-hold`); metadata, never a flow child. Children: `menu-item`s (`on-press` required, `disabled` optional, no `icon`) and bare `separator`s, with `if`/`else`/`for` around them. Attribute-less; presents natively where the host has a menu presenter, as an anchored surface elsewhere — see "Context menus" |
224
+ | `context-menu` | consumed by its parent | right-click menu on its DIRECT parent (a hit-target kind or an element with `on-press`/`on-double-press`/`on-toggle`/`on-hold`/`on-drag`); metadata, never a flow child. Children: `menu-item`s (`on-press` required, `disabled` optional, no `icon`) and bare `separator`s, with `if`/`else`/`for` around them. Attribute-less; presents natively where the host has a menu presenter, as an anchored surface elsewhere — see "Context menus" |
225
225
  | `input-group` > `textarea` + `input-group-actions` | composite grouped input | the composer shape: ONE bordered field wrapping exactly one `textarea` (first — document order is focus order) plus an optional `input-group-actions` row of controls inside the same border. The group wears the focus ring for its focused descendant and the textarea's own chrome dissolves automatically, so the whole group reads as one field; the textarea keeps its full behavior (`text`, `placeholder`, `on-input`, `on-submit`, `autofocus`, and optional `submit-on-enter`). Group takes `label`, `width`, `height`, `min-width`, `grow`, `key`, `global-key`; the actions row takes `gap` and holds ordinary elements (`if`/`else`/`for` work — swap send for stop while streaming) — put a `<spacer grow="1"/>` between leading and trailing controls (`Ui.inputGroup`/`Ui.inputGroupActions` are the Zig-view equivalents) |
226
226
 
227
227
  Not markup-expressible (deliberately — write these as Zig view functions with `canvas.Ui`): `icon_button` (`<button icon="...">` with empty content is the declarative icon button), `data_grid` (per-column cell templates), `popover`/`menu_surface` (anchored to runtime geometry), `segmented_control` (use `tabs`/`toggle-group`: `<button>` children of `<tabs>` lower to segmented triggers automatically, so the active tab lifts per the house treatment). Charts ARE expressible: `<chart>` with `<series values="{binding}">` children binding model f32 iterables — see the Charts section (`.band` series and dynamic series composition stay with `ui.chart`). Built-in vector icons ARE expressible: `<icon name="search"/>` (closed, compile-checked name set; `Ui.icon` is the Zig-view equivalent). App-authored icons: `canvas.svg_icon.parseComptime(@embedFile("icons/logo.svg"))` parses any SVG in the common 24x24 stroke-icon dialect at comptime; register the parsed table once at boot with `canvas.icons.registerAppIcons(&table)` and draw by name via `ui.appIcon(.{...}, "logo")` or `ElementOptions.icon` — registered names render exactly like built-ins on every draw path. Markup `<icon>`/`<button icon>` stay built-in-only (the compiled engine validates names at comptime, where runtime registrations cannot exist — engine parity). Runtime images ARE expressible: `<image image="{cover}" width="120" height="80" label="Cover art"/>` and `<avatar image="{user_image}">CT</avatar>` bind a `u64` ImageId model field/fn (the id is just model data; 0 draws nothing / keeps the initials fallback) — see the Images section; the `image` binding is required on the leaf (an unbound `<image>` is dead markup) and stays avatar+image scoped.
@@ -521,7 +521,7 @@ Scroll offsets follow the same mirror discipline as text: the Msg carries the of
521
521
 
522
522
  A handler or update error DEGRADES, it does not exit the app: dispatch catches it, records it in a bounded ring (`runtime.dispatchErrors()`, the `error event=... name=...` lines and `dispatch_errors=` count in automation snapshots, and a `dispatch.error` trace record at error level), and the app keeps running. Trace-sink capacity failures likewise never fail dispatch — dropped records are counted (`dropped_trace_records=`), not fatal. Design for it: an arm that can fail should still surface its own status in the model; the error ring is the safety net, not the UX.
523
523
 
524
- Presses follow ONE rule: a click lands on the nearest pressable widget under the pointer — plain text, icons, images, badges, and layout containers let it fall through to their closest pressable ancestor, and dragging still selects text. "Pressable" means an interactive kind (button, checkbox, list-item, ...) or ANY element with a bound `on-press`/`on-double-press`/`on-toggle` — the handler itself makes the element a hit target, so a pressable row is just `<panel on-press="open:{id}">` (or `<row on-press=...>`, `ui.row(.{ .on_press = ... })`) with plain text children: no empty-text overlays, no duplicating the handler onto every text leaf. Nested pressables resolve to the deepest one (a button inside a pressable row wins over the row); editable text fields, scroll containers, and modal surfaces (dialog, drawer, sheet, popover, menus) always claim their own presses, so a click in a field inside a pressable row places the caret instead of activating the row. The value/text handlers (`on-change`, `on-submit`, `on-input`) still only belong on controls — both engines and `markup check` reject them on layout/decoration elements with a teaching error.
524
+ Presses follow ONE rule: a click lands on the nearest press-claiming widget under the pointer — plain text, icons, images, badges, and layout containers let it fall through to their closest interactive ancestor, and dragging still selects text. An interactive element is a control kind (button, checkbox, list-item, ...) or ANY element with a bound `on-press`/`on-double-press`/`on-toggle`/`on-hold`/`on-drag`; these handlers make the element a hit target and press claimer. Thus a row can bind `on-press` for clicks or `on-drag` for spatial dragging, and child text still resolves to that row without overlays or duplicated handlers. Nested claimers resolve to the deepest one; editable text fields, scroll containers, and modal surfaces (dialog, drawer, sheet, popover, menus) always claim their own presses. The value/text handlers (`on-change`, `on-submit`, `on-input`) still only belong on controls — both engines and `markup check` reject them on layout/decoration elements with a teaching error.
525
525
 
526
526
  ### Keys: quiet list rows and the app-level fallback
527
527
 
@@ -681,7 +681,7 @@ Streaming responses (`.response = .stream`) frame the body into `on_line` Msgs a
681
681
 
682
682
  Stream rules: each body line is one `on_line` Msg (same payload type and copy rule as spawn lines; `max_line_bytes` mirrors the spawn override with the same 256 KiB ceiling); the terminal `on_response` Msg carries the real HTTP status with an empty body; `fx.cancel(key)` mid-stream stops the lines and delivers exactly one `.cancelled` terminal; the whole-exchange `timeout_ms` covers the stream's full lifetime, so raise it for long-running commands; lines dropped on a full queue that no later line reported ride the terminal's `response.dropped_before`. In the fake executor, `feedLine` feeds a stream fetch's lines and `feedResponse(key, status, "")` delivers its terminal.
683
683
 
684
- `fx.writeFile` / `fx.readFile` are TEA-friendly file persistence — session snapshots, app state — without smuggling an `Io` handle from `main` into `update`. Same discipline as spawn and fetch: bounded, key-based (shared key space and 16 slots), exactly one terminal Msg with an explicit outcome:
684
+ `fx.writeFile` / `fx.readFile` are TEA-friendly raw file effects for user-visible files, exports, and blobs — app state belongs in the engine-owned storage tiers. Same discipline as spawn and fetch: bounded, key-based, and explicit outcomes:
685
685
 
686
686
  ```zig
687
687
  pub const Msg = union(enum) {
@@ -708,8 +708,10 @@ pub const Msg = union(enum) {
708
708
 
709
709
  File rules:
710
710
 
711
- - `result.outcome` is explicit: `.ok` (a read's whole content in `result.bytes`; a write fully on disk), `.not_found` (reads only — writes create the path, parent directories included), `.io_failed` (permissions, path is a directory, disk), `.truncated` (the file exceeds the 1 MiB `max_effect_file_bytes`; `result.bytes` is the first bound bytes — its own outcome, not a flag, because a cut JSON snapshot must not parse as whole), `.rejected` (never ran: slots busy, duplicate key, empty/over-long path, write bytes over the bound — an over-bound WRITE is rejected outright since a partial write would corrupt the file), `.cancelled`.
711
+ - `result.outcome` is explicit: `.ok`, `.not_found`, `.io_failed`, `.truncated`, `.rejected`, `.cancelled`, `.sink_missing`, `.out_of_order`, or `.disk_full`.
712
712
  - Writes replace the file whole; `writeFile` bytes are copied at call time so the caller's buffer is immediately reusable. Reads deliver drain-scratch bytes — copy what the model keeps.
713
+ - `appendFile` appends one payload up to 1 MiB; `statFile` returns existence, size, and mtime; `deleteFile` deletes one file, returning `.not_found` when it is absent and unlinking a final symlink without deleting its target. `readFileStream` emits 256-KiB chunks then `.done(total)`. `writeFileStream` opens an atomic sink; acknowledge each `writeFileChunk` before sending the next, then `writeFileClose` syncs and atomically installs the destination. Streaming owns four slots separate from the general sixteen.
714
+ - Raw paths under this app's resolved data/config/cache/state/logs/temp roots need no grant. Every external path requires the `filesystem` permission. The runtime resolves existing parents and symlinks before checking, so an in-root symlink pointing out is external.
713
715
  - In the fake executor: `pendingFileAt(0)` records `key`/`op`/`path`/`bytes` for assertions; `feedFileResult(key, .ok, "{...}")` answers a read (over-bound content is cut and rewritten to `.truncated`, mirroring the real reader), `feedFileResult(key, .ok, "")` acknowledges a write; failure outcomes pass through as fed.
714
716
 
715
717
  `fx.credentialsSet` / `fx.credentialsGet` / `fx.credentialsDelete` are the only place authentication tokens, passwords, and similar app secrets belong. Declare both `.capabilities = .{ "credentials" }` and `.permissions = .{ "credentials" }` in `app.zon`; the stable app id is the OS keychain service namespace, while the supplied key is its account. Never copy a fetched secret into Model: consume the drain-scratch `result.bytes` immediately while constructing the next effect, so persistence, state fingerprints, and diagnostics cannot capture it.
@@ -872,9 +874,13 @@ The `.wake` platform event is how live platforms marshal worker completions onto
872
874
  >
873
875
  > After feeding, drain with `try harness.runtime.dispatchPlatformEvent(app, .wake);` — results become Msgs through the same path live platforms use.
874
876
 
875
- ## Secondary windows in Zig cores: model-declared (`windows_fn` + `window_view`)
877
+ ## Secondary windows
876
878
 
877
- Windows are model state, like an anchored surface's open flag. `Options.windows_fn` returns the descriptors that should exist RIGHT NOW (presence is visibility — no `visible` flag; the platform window channel has no hide); `Options.window_view` builds each declared window's whole canvas tree by window label. The runtime reconciles after every dispatch: create the newly declared, close the no-longer-declared, rebuild every open window's view from the same model.
879
+ In the default TypeScript path, export `windows(model): readonly WindowDescriptor[]` and put each possible window's Native markup at `src/windows/<label>.native`. Spell each constructor identity as a literal `label: asciiBytes("<label>")`; `native check` and every build reject dynamic labels and missing roots. Those roots may import shared components nested under `src/windows/`; the generated launcher compiles and hot-reloads the full closure. Use `windowDescriptor` from `@native-sdk/core`; its `closePolicy` field accepts `"quit"` or `"hide"`, and `titlebar` includes `"chromeless"`. A `"quit"` user close routes `onCloseCommand` through `commandMsg`; a `"hide"` close preserves the window and view and dispatches no close command. The `ts-core` skill has the complete descriptor and example.
880
+
881
+ ### Zig cores: `windows_fn` + `window_view`
882
+
883
+ Windows are model state, like an anchored surface's open flag. `Options.windows_fn` returns the descriptors that should exist RIGHT NOW (presence is liveness); `Options.window_view` builds each declared window's whole canvas tree by window label. The runtime reconciles after every dispatch: create the newly declared, close the no-longer-declared, rebuild every open window's view from the same model. There is no `visible` flag: transient visibility is host state changed through `hideWindow`/`showWindow` or a `.hide` close policy; stop declaring the window to really close it and release its retained views.
878
884
 
879
885
  ```zig
880
886
  fn windows(model: *const Model, scratch: *App.WindowsScratch) []const App.WindowDescriptor {
@@ -896,7 +902,7 @@ fn windowView(ui: *App.Ui, model: *const Model, window_label: []const u8) App.Ui
896
902
 
897
903
  Rules that matter:
898
904
  - **Every canvas label must be unique across the app** (main + declared windows); input routes back by it, and automation verbs (`widget-click <canvas-label> <id>`, `screenshot`) address any window's canvas the same way.
899
- - **A user close dispatches `on_close`** (the dismissal precedent): the window is already gone as the optimistic echo; clear the open flag in `update` — or keep declaring the window and the next rebuild brings it back (source wins). A close the model itself initiated never echoes a Msg.
905
+ - **Close policy**: `WindowDescriptor.close_policy` is `.quit` by default; a user close really closes and dispatches `on_close` (the dismissal precedent), so clear the open flag in `update` — or keep declaring the window and the next rebuild brings it back (source wins). `.hide` keeps the same window, slot, and views alive, dispatches no `on_close`, and `showWindow(label)` reveals it. A close the model itself initiated never echoes a Msg. Existing platform safeguards still apply: unsupported hosts refuse `.hide` rather than strand an unreachable window.
900
906
  - **Budget**: at most `UiApp.max_ui_windows` (4) declared windows; excess warns and is ignored. Every dispatched Msg rebuilds every open window's view.
901
907
  - **Present-before-show**: canvas windows (any `gpu_surface` view — startup, scene, and declared windows alike) are created ordered-out and become visible only after their first canvas frame presents, so opening one never flashes blank. Automatic (`WindowOptions.show = .on_first_present`, derived from the views); webview windows show immediately. The null platform records `window_show`, `window_visible`, and present/shown sequence numbers for ordering assertions; `NATIVE_SDK_WINDOW_TIMING=1` logs create→show latency on macOS.
902
908
  - **Markup binds ONE window's content** — there is no `window` element in the closed grammar. A markup-authored secondary window is a `canvas.CompiledMarkupView` whose `build` `window_view` calls for that label.
@@ -997,7 +1003,7 @@ Rules:
997
1003
 
998
1004
  - `fx.registerImage(id, w, h, rgba8)` takes already-decoded straight-alpha RGBA8 (exactly `w*h*4` bytes; the runtime copies — your buffer is free on return). `fx.registerImageBytes(id, bytes)` decodes first. `fx.unregisterImage(id)` frees the slot. Outside UiApp: `Runtime.registerCanvasImage` / `registerCanvasImageBytes` / `unregisterCanvasImage`.
999
1005
  - Re-registering an id replaces the pixels; every view repaints and GPU caches re-upload off the changed content fingerprint — no invalidation calls. For caches, mint fresh ids (effect-key style, monotonically increasing) and `unregisterImage` the evictee — never re-key different content onto a live id.
1000
- - Bounded and loud (`canvas_limits`): 16 slots (`max_registered_canvas_images`), 1 MiB per image (`max_registered_canvas_image_pixel_bytes`, 512×512 RGBA8 — avatar/icon scale). Errors: `error.ImageRegistryFull`, `error.ImageTooLarge`, `error.ImageDecodeFailed`, `error.InvalidImageId`/`InvalidImageDimensions`, `error.UnsupportedService` (codec-less platform).
1006
+ - Bounded and loud (`canvas_limits`): 16 slots, a 1 MiB decoded-pixel TARGET by default. Encoded images decode aspect-preservingly to fit, so real photos load and the reported dimensions are the registered geometry; raw-pixel `registerImage` remains strict. Image-centric apps may declare app.zon `.images = .{ .max_image_pixel_bytes = 8388608 }` (accepted range 1–8 MiB). Allocation is lazy per used slot, but 16 fully used 8 MiB slots are a declared 128 MiB high-water. Every encoded entry point, including direct `fx.registerImageBytes`, shares the separate flat 8 MiB source bound. Editors needing source-resolution pixels, 1:1 zoom, or tiles own that pipeline through a `gpu_surface` or media-surface producer, not this registry. Errors: `error.ImageRegistryFull`, `error.ImageTooLarge` (encoded source, raw pixels, or a codec-contract violation), `error.ImageDecodeFailed`, `error.InvalidImageId`/`InvalidImageDimensions`, `error.UnsupportedService`.
1001
1007
  - A draw referencing an unregistered id skips — a transient loading state can never fail presentation. `ui.avatar` clips a set image to the circle (`cover` fit) and renders the initials argument otherwise.
1002
1008
  - Registered images render in live presentation AND `renderCanvasScreenshot`/automation screenshots, so goldens can assert on them.
1003
1009
  - Deterministic tests: `harness.null_platform.image_decode = true` enables a strict decoder for the exact PNG subset `canvas.png.writeRgba8` emits — encode a raw RGBA fixture with the canvas PNG writer and drive the full decode→register→draw path with no bundled codec (`src/runtime/canvas_image_tests.zig` is the reference).
@@ -5,7 +5,7 @@ description: Authoring guide for the primary Native SDK app-logic path: TypeScri
5
5
 
6
6
  # Author app cores in the TypeScript subset
7
7
 
8
- TypeScript is the primary app-authoring language. An app core is the logic tier of a Native SDK app: `Model` (the app state), `Msg` (a discriminated union of everything that can happen), `update(model, msg)` (the one pure transition function), and the pure helpers they call. You write it as a TypeScript module rooted at `src/core.ts` - splitting into more modules under `src/` when it grows (see "Splitting a core into modules") - and the build checks the whole import graph with the `@native-sdk/core` frontend and compiles it to native code with the external core compiler. No JS engine ships in the binary — the program either passes the subset checker and compiles to native, or you get a teaching error naming the rule, the fix, and the reason. The same file is executable TypeScript: it typechecks with stock tsc and runs unmodified under node, so you can poke behavior with plain node scripts before the native build.
8
+ TypeScript is the primary app-authoring language. An app core is a Native SDK app's deterministic logic: `Model` (the app state), `Msg` (a discriminated union of everything that can happen), `update(model, msg)` (the one pure transition function), and the pure helpers they call. You write it as a TypeScript module rooted at `src/core.ts` - splitting into more modules under `src/` when it grows (see "Splitting a core into modules") - and the build checks the whole import graph with the `@native-sdk/core` frontend and compiles it to native code with the external core compiler. No JS engine ships in the binary — the program either passes the subset checker and compiles to native, or you get a teaching error naming the rule, the fix, and the reason. The same file is executable TypeScript: it typechecks with stock tsc and runs unmodified under node, so you can poke behavior with plain node scripts before the native build.
9
9
 
10
10
  A whole TS app starts as three files of truth and zero Zig: `src/core.ts` (this guide; plus core-class modules it imports under `src/`), `src/app.native` (the markup view over the core's model), and `app.zon` (windows, identity, permissions). Optional ordinary-TypeScript service modules live under `src/services/` and are never imported by the core; load `native skills get ts-services` for that boundary. `native init` scaffolds the three-file base; the build detects `src/core.ts` in the tree (never a flag or config — a tree with both `src/core.ts` and `src/main.zig` is a teaching error) and generates the wiring outside the app. The loop:
11
11
 
@@ -85,7 +85,7 @@ Logic:
85
85
  - **Local mutation — your own scratch is yours; shared data is immutable.** An array your function CREATES — an array literal (`const stack: number[] = []`, `const st = [1, 2, 3]`) or a fresh copy (`.slice()` / `.map()` / `.filter()` / `.concat()` / `.toSorted()`) — is locally owned, and the full mutating method set works on it with exact JS semantics: `push(...items)`, `pop()`, `shift()`, `unshift(...items)`, `splice(start, deleteCount?, ...items)` (negative/overshooting indices clamp the JS way; the value is the removed array, also yours), `reverse()`, `fill(v, start?, end?)`, in-place `sort(cmp)`, and indexed writes `xs[i] = v`. A parser stack, a work queue, a copy-then-sort — all legal, deterministic, and byte-identical to node. Ownership ends at the first ESCAPE: once the array is returned from a callback, stored into a record/array/model, aliased by a second binding (`const b = a`), or passed where the callee could keep or mutate it, mutating it afterwards is a taught NS1051 — finish mutating first, then let it escape (an early-exit `return` is fine: execution ends there, so mutations on the other path stay legal). Two loosenings keep real code flowing. BORROWING: passing an owned array into a `readonly T[]` parameter is NOT an escape when the callee only READS it (element/property access, iteration, spreads, further borrowing passes — no return of it, no store, no onward pass into a mutable position; recursion over borrowed slices included), so measure-mutate-measure loops work (`total(out); out.push(x); total(out)`). REASSIGNED-OWNING: a `let` binding whose EVERY assignment installs a fresh owning construction (a literal or a copy — `w = xs.filter(...)`, `acc = []`) stays owned through the reassignments; ONE mixed assignment (an alias, a parameter, a helper result) and the binding never owns (NS1001 names it). Never owned: parameters, model/msg data, module `const` tables, aliases, mixed reassigned bindings, and arrays produced by helper calls (copy with `.slice()` to own one). After the value escapes it is an ordinary immutable value; the commit walkers and sharing discipline are unaffected because ownership ended before the escape.
86
86
  - Local-mutation shape notes: `push`/`unshift` return the new length in JS, which has no mapping — mutate as a statement and read `.length` after; `sort`/`reverse`/`fill` return the same array — mutate as a statement, then use the array by name (`return copy.sort(cmp)` is a taught stop; the canonical form is `const copy = xs.slice(); copy.sort(cmp); return copy;`); `pop()`/`shift()` return `T | undefined` — the same one-empty the `.find` miss produces, so test `=== undefined` or fold with `??` (`stack.pop() ?? fallback`); spread arguments (`out.push(...xs)`) stay taught — one element per iteration; `xs[xs.length] = v` on an owned array IS a push (the one growth shape — compound forms like `xs[xs.length] += v` read the missing slot first and stay taught), and other out-of-bounds writes are JS sparse arrays with no mapping (they trap on the native bounds check in safe builds — keep writes inside `0..length-1`); changing the LENGTH of the array a `for...of` (or one of its own callbacks) is iterating is a taught stop (JS walks the live array; fixed-length writes during iteration are fine and identical to node); `copyWithin` stays out of v1 (splice/fill cover it).
87
87
  - `.toSorted(cmp)` sorts a copy in one expression; `.sort(cmp)` sorts in place on an array you own (on shared data it keeps the NS1022 teaching, which names the copy idiom). Both comparators follow the same rules: return a sign — `(a, b) => a - b` for ascending numbers, or explicit -1/0/1 branches; a boolean comparator is wrong in JS itself (false claims equality) and is rejected by the types plus a taught NS1023. The comparator-less arity sorts by string ToString order in JS (`[10, 9]` stays `[10, 9]`), which has no float-text mapping — pass a comparator. Both sorts are stable exactly like JS: comparator 0 (or NaN) keeps the original order of the pair. One honesty note: a comparator that is inconsistent over the actual data (e.g. `a - b` when elements can be `NaN`) is implementation-defined in JS itself, so node and native may then disagree — keep comparators consistent.
88
- - A `.find` miss is the tier's one empty value: JS spells it `undefined`, so test the result with `=== undefined` (never `=== null` — the checker teaches the difference) or fold it away with `??`: `tasks.find((t) => t.id === id) ?? fallback`.
88
+ - A `.find` miss is the core's one empty value: JS spells it `undefined`, so test the result with `=== undefined` (never `=== null` — the checker teaches the difference) or fold it away with `??`: `tasks.find((t) => t.id === id) ?? fallback`.
89
89
  - Optional chaining `?.` on property chains (`model.sel?.at ?? 0`), element hops (`m?.xs[0] ?? 0`, `xs?.[i] ?? d`), and method hops on supported receivers (`xs?.slice(0, 2)`, `xs?.includes(3) ?? false` — every mapped array/bytes method): each hop null-propagates exactly like JS, and the chain value is optional — end it in `??` or compare it against a real value. A `?.` chain compared against `null`/`undefined` is a taught error (NS1021), and `g?.()` on a function value stays taught.
90
90
  - Null-guard narrowing through `&&`/`||` chains, exactly the way TS narrows: `if (x !== null && x.items.length > 0)`, the flipped order (`null !== x`), the `||` dual (`x === null || x.items.length === 0`, including as an early-exit guard — the code after the exit stays narrowed), ternary conditions (`x !== null && x.at > 0 ? x.at : -1`), and `while (cur !== null && cur.n > 0)` loops (re-tested per iteration; assigning the guarded local drops the narrowing for what follows, like TS). Relational comparisons on guarded optionals (`cls !== null && cls < lim`) work too.
91
91
  - Nullish `??`, comparisons (including `===` on `string`-typed values — content equality, same as node; `==`/`!=` are taught NS1048 — coercion), `+ - * / % **` on numbers, unary `+`/`-`, and the bitwise family `& | ^ ~ << >> >>>` — all with JS number semantics (`/` is float division, `%` truncates, `**` is float pow with the exact JS corners — `1 ** NaN` is NaN, `(-1) ** Infinity` is NaN, right-associative `2 ** 3 ** 2` is 512; bitwise and shifts are ToInt32 with the shift count masked & 31, `>>>` yielding the unsigned 32-bit value; unary `+` is the identity on numbers). `**` and `/` results are float-classed; bitwise/shift operands are integer-required positions (a float operand is a taught NS1016).
@@ -98,7 +98,7 @@ Logic:
98
98
  - **Exceptions — `throw`/`try`/`catch`/`finally` as pure control flow.** Inside a core, exceptions are deterministic: `throw` carries a subset VALUE and unwinds to the nearest enclosing `catch` — across helper calls, out of array-method callbacks (a `throw` inside `.map`'s callback exits the whole loop, like JS), through nested `try`s, with `finally` running on every path (fall-through, `return`, `break`/`continue`, and throw alike). The discipline is two rules. First (NS1057): thrown values are kind-tagged subset shapes — throw kind-discriminated records (`throw { kind: "bad_digit", at: i } as ParseError`, where `ParseError` is an interface with a string-literal `kind` field or a `kind`-discriminated union; a single-shape core may also throw a number), and SEVERAL distinct shapes may throw: the checker collects every shape the core throws into its implicit thrown union. The catch binding IS that union — narrow it in place with kind tests, no `as` ceremony: `catch (e) { if (e.kind === "bad_digit") return -e.at; if (e.kind === "io") return e.code; return -1; }` (or `switch (e.kind)` — tsc cannot prove exhaustiveness over the implicit union, so give the switch a `default` or a trailing return). Bare rethrow (`throw e;`) re-raises the bound value — a narrowed arm included — and `catch { ... }` needs no binding; the single-`as` form (`const err = e as ParseError;`) stays legal in single-shape cores (and for a DECLARED union whose arms equal the thrown set — declare `type AppError = ... | ...` and `as AppError` works). What teaches: untagged values in a heterogeneous set, two shapes sharing one `kind` with different payloads, asserting one member shape of a multi-shape core, the binding escaping untyped into a call/store/return, and `throw new Error(...)` (engine error objects carry stack traces with no native layout). Second (NS1058): `finally` never redirects control flow — no `return`/`throw`/`break`-out inside it (JS's own no-unsafe-finally rule; loops fully inside the finally may break within themselves). An UNCAUGHT throw that reaches an exported function's boundary is a defined deterministic panic — exactly where node's process would crash. A throw mid-mutation of an owned array keeps the mutations applied so far, exactly like JS — the catch sees the array as node would.
99
99
  - **Local function values — const helpers hoist.** `const scale = (x: number): number => x * 3;` (arrow or `function` expression) hoists to an ordinary module-level fn when it is capture-free (module constants and other const helpers are fine to reference; enclosing locals/params are not — pass them as parameters), fully annotated (every parameter and the return type), and used only by direct calls (`scale(v)`, recursion included) or as an array-method callback (`xs.map(scale)`, comparators included). Everything else teaches NS1054: captures, missing annotations, `let` bindings, returning/storing the value, passing it to your own functions, calling through a record field. Capturing a locally-owned array also ENDS its ownership at the capture (a later mutation is the NS1051 teach) — the stored closure would retain the reference.
100
100
 
101
- Not yet in v1 — genuine roadmap deferrals, each stopping with a loud, tailored NS9001 naming the rewrite (never missing basic syntax; the banned-with-a-rule families live in "What the subset means" above): `.toSorted()`/`.sort()` without a comparator (JS ToString ordering; pass `(a, b) => a - b`), `.reduce` without an initial value (a taught NS1007 — JS throws on an empty array) or with an index parameter (use a classic loop), `.indexOf`/`.includes` on record arrays (match a field with `.find`/`.findIndex`), `.join` on number arrays (elements are float-valued; join byte values instead), float values (`/`, `**`, `Math.round`, `Math.sqrt`, float `Math.floor`-family results) where an integer is required such as an index (a taught NS1016 — those values can be fractional or NaN), Math methods beyond the batch above, `Number` methods beyond the three classifiers, float-valued template holes (JS float-to-string fidelity is a runtime v2 surface), arrays of unions (`readonly View[]`) or arrays of byte-strings (`readonly Uint8Array[]`) as model fields (wrap the element in a single-field interface), a collect spawn's stderr tail (v1 delivers the exit code and stdout; stderr is not surfaced — put diagnostics on stdout or check the code), per-line truncation flags (a stdout or response line over its configured bound arrives cut, without a flag), and non-timer subscriptions (`Sub.timer` is the one subscription; one-shot needs are `Cmd.delay`, and process/fetch/audio streams are Cmd-initiated, not subscribed).
101
+ Not yet in v1 — genuine roadmap deferrals, each stopping with a loud, tailored NS9001 naming the rewrite (never missing basic syntax; the banned-with-a-rule families live in "What the subset means" above). The rule-level deferrals carry `class: "deferred"` in the diagnostics catalogue — NS1011 (Map/Set), NS1019 (fixed arity), NS1040 (regexes), NS1042 (generators), NS1044 (BigInt/Symbol) — and their diagnostics say the capability is deliberately deferred, not impossible; the list below is the method-level remainder: `.toSorted()`/`.sort()` without a comparator (JS ToString ordering; pass `(a, b) => a - b`), `.reduce` without an initial value (a taught NS1007 — JS throws on an empty array) or with an index parameter (use a classic loop), `.indexOf`/`.includes` on record arrays (match a field with `.find`/`.findIndex`), `.join` on number arrays (elements are float-valued; join byte values instead), float values (`/`, `**`, `Math.round`, `Math.sqrt`, float `Math.floor`-family results) where an integer is required such as an index (a taught NS1016 — those values can be fractional or NaN), Math methods beyond the batch above, `Number` methods beyond the three classifiers, float-valued template holes (JS float-to-string fidelity is a runtime v2 surface), arrays of unions (`readonly View[]`) or arrays of byte-strings (`readonly Uint8Array[]`) as model fields (wrap the element in a single-field interface), a collect spawn's stderr tail (v1 delivers the exit code and stdout; stderr is not surfaced — put diagnostics on stdout or check the code), per-line truncation flags (a stdout or response line over its configured bound arrives cut, without a flag), and non-timer subscriptions (`Sub.timer` is the one subscription; one-shot needs are `Cmd.delay`, and process/fetch/audio streams are Cmd-initiated, not subscribed).
102
102
 
103
103
  ## Effects are Cmd data
104
104
 
@@ -121,7 +121,7 @@ export function update(model: Model, msg: Msg): Model | [Model, Cmd<Msg>] {
121
121
  }
122
122
  ```
123
123
 
124
- The command set (Cmd wire format v4):
124
+ The command set (Cmd wire format v7):
125
125
 
126
126
  - `Cmd.none` — no effects; returning a bare `Model` is sugar for `[model, Cmd.none]`.
127
127
  - `Cmd.persist()` — snapshot the just-committed Model through the engine-owned store. Requires `"persist"` in `app.zon` capabilities plus `.persist = .{ .version, .restore = .{ .ok, .none, .err } }`; the host owns canonical encoding, debounce/coalescing, atomic app-data placement, backup recovery, and replay.
@@ -129,7 +129,7 @@ The command set (Cmd wire format v4):
129
129
  - `Cmd.host(name, ...args)` — a fire-and-forget host command by literal name; the host decides what the name means. Args are numbers, OR exactly one bytes payload: a `Uint8Array` (`Cmd.host("clipboard.write", model.draft)`) or a flat inline record of number/boolean/`Uint8Array` fields (`Cmd.host("cfg.save", { gain: model.gain, on: model.muted, label: asciiBytes("main") })`) — the record lowers to one bytes payload from your types at build time, byte-identical under node and native. Anything else (a smuggled string, a nested record, a payload plus extra args) is a taught error (NS1020/NS1026).
130
130
  - `Cmd.request(name, payload, { key?, ok, err })` — a routed host command: the host performs `name` with the payload (same bytes/record rules) and dispatches exactly one result back to you as an ordinary Msg — the `ok` arm with the result bytes on success, or the `err` arm with the error bytes on failure. Both arms must carry exactly one `Uint8Array` field (`{ kind: "loaded", body: Uint8Array }`), checked by tsc and taught by NS1027. The routing is data — string-literal arm names, never callbacks — so the result decoder derives from your Msg types at build time. The optional `key` (a string literal) names the in-flight effect: issuing a request whose key is already in flight replaces it (the old result is dropped), which is the debounce/exactly-one-in-flight discipline.
131
131
  - Typed app services are the deliberate record-valued arm of this family: declare shared data shapes outside `src/services/`, import generated constructors from `@native-sdk/services`, and let those constructors encode requests and prove the typed success Msg arm. See `native skills get ts-services`. Raw `Cmd.request` remains bytes-oriented.
132
- - `Cmd.cancel(key)` — drop the in-flight keyed effect with that key, silently: a cancelled raw request, buffered named engine op (`readFile`/`writeFile`/`fetch`/`clipboardRead`), or armed delay dispatches NEITHER arm — its result is simply dropped. Live spawn, streaming-fetch, and streaming-service operations are the exceptions: cancel ends the stream and its `err` arm dispatches with `cancelled`, loud because an app may already have handled earlier stream messages.
132
+ - `Cmd.cancel(key)` — drop the in-flight keyed effect with that key, silently: a cancelled raw request, buffered named engine op (`readFile`/`writeFile`/`fetch`/`clipboardRead`), streamed file read, or armed delay dispatches NEITHER arm. Live spawn, streaming-fetch, streaming-service, and streamed write sinks are the exceptions: cancel ends them through `err: cancelled`; a half-written sink is observable and must never disappear silently.
133
133
  - `Cmd.batch([a, b])` — several commands from one dispatch, performed in order.
134
134
 
135
135
  ### The named engine ops
@@ -141,10 +141,11 @@ These map directly onto the host's effect engine — files, HTTP, the clipboard,
141
141
  - `Cmd.db.query(sql, params, { key?, page, done, err })` / `Cmd.db.exec(statements, { key?, ok, err })` — the permanent raw SQLite escape hatch. The engine owns `app.db`; parameters are `null | number | string | Uint8Array | dbText(bytes) | boolean`. A read delivers 256-row/256-KiB pages then `done`, with one result capped at 8,192 rows or 8 MiB; crossing either total bound rejects the whole result, so use `LIMIT` and keyset pagination for larger collections. An exec commits its 1–64 statements as ONE transaction. SQL remains pathless: `ATTACH`/`DETACH`/`VACUUM INTO`, TEMP schema objects, and engine lifecycle PRAGMAs are denied. Query keys replace/cancel silently; duplicate transaction keys reject loudly. Error bytes are `constraint`, `busy`, `io_failed`, `corrupt`, `misuse`, `rejected`, or `cancelled`. Every page/terminal journals and replay never opens SQLite. Prefer declared queries; NS1420 nudges raw query literals toward them.
142
142
  - `Cmd.readFile(path, { key?, ok, err })` — read a whole file. `ok` arm: one `Uint8Array` field with the content. `err` reasons: `not_found`, `io_failed`, `truncated` (the file exceeds the engine's 1 MiB read bound — a cut file never passes as whole), `rejected`. Paths are at most 1024 bytes.
143
143
  - `Cmd.writeFile(path, bytes, { key?, ok, err })` — write a whole file (parent directories created, an existing file replaced whole; at most 1 MiB). `ok` arm: NO payload fields (`{ kind: "wrote" }`) — a successful write has nothing to report. `err` reasons: `io_failed`, `rejected`.
144
+ - `Cmd.appendFile(path, bytes, route)` appends one bounded payload; `Cmd.statFile(path, route)` returns `{ exists, size, mtimeMs }`; `Cmd.deleteFile(path, route)` deletes one file with a payload-less `ok` arm and routes a missing path as `not_found` (a final symlink is unlinked without deleting its target). `Cmd.readFileStream(path, { key?, chunk, done, err })` delivers 256-KiB chunks then the total; reissuing or cancelling its key silently replaces/drops the read. Atomic exports open with `Cmd.writeFileStream(key, path, route)`, send one acknowledged `writeFileChunk` (≤1 MiB) at a time, then `writeFileClose`; a duplicate sink rejects, overlapping chunk/close routes `out_of_order`, and sink cancellation is loud. Stream chunks spill to the session blob store for byte-identical replay. Raw paths under this app's resolved data/config/cache/state/logs/temp roots need no grant; every external path requires the `filesystem` permission. The runtime resolves existing parents and symlinks before checking (an in-root symlink pointing out is external); NS1074 catches certainly-external literals.
144
145
  - `Cmd.fetch({ url, method?, headers?, body?, timeoutMs? }, { key?, ok, err })` — a buffered HTTP(S) exchange. `ok` arm: exactly two fields, one `number` and one `Uint8Array` (`{ kind: "fetched", status: number, body: Uint8Array }`) — matched by type, so the names are yours. The status is the real HTTP status: a 404 is still `ok` (an HTTP-level error is a delivered response). `err` reasons: `connect_failed`, `tls_failed`, `protocol_failed`, `timed_out`, `rejected`, and `truncated` (the body exceeded the engine's 256 KiB buffered bound — never delivered silently cut). The spec is an inline object: `url` bytes (≤ 2 KiB), `method` one of `"GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD"` (default GET), `headers` an inline flat record — names are compile-time ASCII, values are string literals OR runtime bytes (`{ authorization: bearerToken(model.apiKey), "content-type": "application/json" }` — how a launch-supplied key rides an `Authorization` header; ≤ 8 headers, ≤ 1 KiB total, NS1029/NS1030), `body` bytes (≤ 64 KiB), `timeoutMs` a positive integer literal (engine default when omitted).
145
146
  - `Cmd.clipboardWrite(bytes)` — put bytes on the system clipboard, fire-and-forget: there is no routing, and a refused or over-bound write is dropped by design.
146
147
  - `Cmd.clipboardRead({ key?, ok, err })` — read the clipboard. `ok` arm: one `Uint8Array` field with the text. `err` reasons: `failed` (no clipboard service, over-bound content, pasteboard error), `rejected`.
147
- - `Cmd.showNotification({ title, subtitle?, body? })` — request a desktop notification, fire-and-forget: `title` is required bytes (1–128), `subtitle` optional bytes (up to 128), and `body` optional bytes (up to 1024). The host validates all fields before entering the platform service; invalid or unavailable requests fail closed, and Focus / Do Not Disturb and user settings remain authoritative after acceptance. Fake execution and session replay never display one.
148
+ - `Cmd.showNotification({ id?, title, subtitle?, body?, actionLabel?, actionCommand? })` — request a desktop notification, fire-and-forget: `title` is required bytes (1–128), `subtitle`, `id`, `actionLabel`, and `actionCommand` are optional bytes (up to 128), and `body` is optional bytes (up to 1024). A nonempty `id` replaces the app's earlier notification with that id where the OS supports replacement. `actionLabel` and `actionCommand` must be supplied together; activation dispatches `actionCommand` through the ordinary app-command path while the process is running. The host validates every field and command name before entering the platform service; invalid or unavailable requests fail closed, and Focus / Do Not Disturb and user settings remain authoritative after acceptance. Fake execution and session replay never display one, while the null test platform can activate a recorded notification deterministically.
148
149
  - `Cmd.openExternalUrl(url)` — open an HTTP(S) URL in the system browser, fire-and-forget. `url` is bytes; the runtime validates it and enforces `security.navigation.external_links` before entering the platform service. Invalid, denied, or unavailable requests fail closed; fake execution and replay never open one.
149
150
  - `Cmd.revealPath(path)` — reveal a byte path in Finder, Files, or Explorer, fire-and-forget. Runtime path validation stays in force; invalid or unavailable requests fail closed, and fake execution/replay never reveal one.
150
151
  - `Cmd.credentials.set(key, secret, { key?, ok, err })` / `Cmd.credentials.get(key, route)` / `Cmd.credentials.delete(key, route)` — app-scoped Keychain on macOS/iOS, Secret Service/libsecret on Linux, Credential Manager on Windows, and AndroidKeyStore-wrapped authenticated ciphertext on Android. The authored credential key is a NUL-free string (UTF-8, ≤256 bytes); the manifest app id (≤128 bytes) supplies the service namespace, and secrets are `Uint8Array` values through 2,560 bytes (the cross-platform floor set by WinCred). Set/delete deliver empty bytes on `ok`; get delivers secret bytes; the closed err reasons are `miss`, `denied`, `locked`, `io_failed`, `over_bound`, and `rejected`. Declare BOTH `"credentials"` in `app.zon` capabilities and permissions; NS1071 warns when the capability is absent, NS1072 errors when permission is absent, and NS1073 reserves `core.credentials.*` for the typed factories. Never retain a returned secret in Model: consume its Msg immediately to construct the next effect. Recording stores only a successful get's length, per-session salt, and a placeholder digest independent of the secret (never the secret or a blob); replay delivers deterministic same-length placeholder bytes, and devhost keeps an in-memory map while printing only `<redacted, N bytes>`.
@@ -164,11 +165,11 @@ Four effect families deliver MANY results from one command — a keyed stream th
164
165
  - `Cmd.audioPlay(key, { path?, url?, cachePath?, expectedBytes? }, { event })` — open the audio event stream. One player is the whole surface, so a new `audioPlay` always REPLACES the current playback (the one key-reuse exception besides `Cmd.request`). The source cascade is the engine's: the local `path` is tried first, a missing file falls through to `url` (streamed progressively, cached at `cachePath` when given, integrity-gated by `expectedBytes` — omitted/0 means unknown size). At least one of `path`/`url` is required (NS1029); each is bytes, at most 1 KiB (NS1030). Prefer OMITTING `cachePath` for URL sources: when the app wiring configures a caches directory (`TsUiApp`'s `audio_cache_dir`), the host derives the conventional content-addressed cache path from the URL itself — your update never builds filesystem paths, and replay re-derives the same path by construction. Pass `cachePath` only to override that convention.
165
166
  - The `event` arm is the one SDK-fixed record shape, six fields matched by NAME: `state` (the `AudioState` string-literal union — import it from `@native-sdk/core/events`, or declare an alias with exactly the members `"loaded" | "position" | "completed" | "failed" | "rejected" | "spectrum"` in any order; the runtime matches members by name), `positionMs: number`, `durationMs: number` (milliseconds; the duration is the player's estimate), `playing: boolean`, `buffering: boolean` (true while a streamed url is stalled waiting for bytes), and `bands: Uint8Array` (the 32 spectrum band magnitudes, 0–255 each, all zeros outside `"spectrum"` events). Every playback event dispatches this arm — `"failed"` (unplayable source, decode/device failure) and `"rejected"` (an empty or over-long source) included, so failure is never silence — until `Cmd.audioStop` closes the stream. `"completed"` fires once at the natural end and does NOT close the stream: starting the next track from it is the idiom.
166
167
  - `Cmd.audioPause(key)` / `Cmd.audioResume(key)` / `Cmd.audioStop(key)` / `Cmd.audioSeek(key, ms)` / `Cmd.audioSetVolume(key, volume)` — fire-and-forget control verbs: no result of their own; their consequences arrive on the event stream (`audioResume` on a dead player reports one `"failed"` event, never silence). A verb whose key names no open stream is a no-op. `audioStop` is the audio stream's close — no events for the key after it (`Cmd.cancel` does not apply to audio). Volume is clamped 0..1 and remembered across tracks; a literal outside 0..1 (or a negative seek literal) stops the build (NS1030).
167
- - `Cmd.channelOpen(key, { event })` — open an EXTERNAL-SOURCE channel under the app's numeric key: the host stages a long-lived, thread-safe posting seam its NATIVE side feeds — embedders and platform-services extensions post bytes from their own threads (sockets, watchers, workers), and each accepted post dispatches the `event` arm as one `"data"` event. Posting is deliberately not a TS verb — compiled cores are single-threaded, so the TS tier opens, closes, and receives while the posting handle lives on the native side (`Effects.channelHandle(key)`). `key` may be any number expression, a positive integer below 2^53 (a certain-to-be-refused literal stops the build, NS1030). The `event` arm is a five-field record matched by NAME: `key` (the channel key echoed verbatim, so concurrent channels sharing one arm stay distinguishable; a key the wire cannot carry exactly echoes 0), `state` (the `ChannelState` union — import it from `@native-sdk/core` or declare an alias with exactly the three members `"data" | "closed" | "rejected"` in any order; checked BOTH directions, since a narrower union would silently drop states the host emits), `bytes` (`Uint8Array` — the post's payload on `"data"` events, empty otherwise), and `droppedPending`/`droppedTotal` (numbers — the honest back-pressure counters: posts the native handle refused since the previous delivered event, and over the channel's whole life; refused posts count, never silence). One channel per key at a time — a duplicate live key dispatches `"rejected"` — and the key shares the engine's effect-key space (a same-key fetch is blocked while the channel lives). No timer polling anywhere: the source wakes the loop itself. Channel events journal at the effect boundary, so recorded sessions replay the whole stream from the journal — the native posting side is never needed at replay (a native producer that consults `ChannelHandle.live()` before launching keeps replay fully offline; one that launches unconditionally is stopped at its first post, which answers `.closed`).
168
+ - `Cmd.channelOpen(key, { event })` — open an EXTERNAL-SOURCE channel under the app's numeric key: the host stages a long-lived, thread-safe posting seam its NATIVE side feeds — embedders and platform-services extensions post bytes from their own threads (sockets, watchers, workers), and each accepted post dispatches the `event` arm as one `"data"` event. Posting is deliberately not a TS verb — compiled cores are single-threaded, so the core opens, closes, and receives while the posting handle lives on the native side (`Effects.channelHandle(key)`). `key` may be any number expression, a positive integer below 2^53 (a certain-to-be-refused literal stops the build, NS1030). The `event` arm is a five-field record matched by NAME: `key` (the channel key echoed verbatim, so concurrent channels sharing one arm stay distinguishable; a key the wire cannot carry exactly echoes 0), `state` (the `ChannelState` union — import it from `@native-sdk/core` or declare an alias with exactly the three members `"data" | "closed" | "rejected"` in any order; checked BOTH directions, since a narrower union would silently drop states the host emits), `bytes` (`Uint8Array` — the post's payload on `"data"` events, empty otherwise), and `droppedPending`/`droppedTotal` (numbers — the honest back-pressure counters: posts the native handle refused since the previous delivered event, and over the channel's whole life; refused posts count, never silence). One channel per key at a time — a duplicate live key dispatches `"rejected"` — and the key shares the engine's effect-key space (a same-key fetch is blocked while the channel lives). No timer polling anywhere: the source wakes the loop itself. Channel events journal at the effect boundary, so recorded sessions replay the whole stream from the journal — the native posting side is never needed at replay (a native producer that consults `ChannelHandle.live()` before launching keeps replay fully offline; one that launches unconditionally is stopped at its first post, which answers `.closed`).
168
169
  - `Cmd.channelClose(key)` — close the open channel under the key, if any: staged posts flush, exactly one `"closed"` event (final drop totals aboard) dispatches the event arm, and the key frees. A key with no open channel no-ops.
169
170
  - `Cmd.audioCaptureStart(key, { source, sampleRate?, channels? }, { event })` — start a native `"microphone"` or `"system"` audio stream. The host converts into interleaved signed-16 little-endian PCM at 16/24/48 kHz and mono/stereo (default 48 kHz mono), in chunks no larger than 20 ms. The ten-field event arm is matched by NAME: `key`, `state` (exactly `"started" | "data" | "failed" | "stopped" | "rejected"`), `source` (exactly `"microphone" | "system"`), `sampleRate`, `channels`, `timestampMs`, `frames`, `pcm`, `droppedPending`, and `droppedTotal`. PCM is dispatch-lifetime bytes; the commit walker copies it when stored in the model. The bounded queue, wake behavior, drop accounting, journaling, and offline replay are the channel transport's. Microphone and system may run concurrently; a second start for one source replaces that source's prior key.
170
171
  - `Cmd.audioCaptureStop(key)` — synchronously quiesce native callbacks, flush already accepted chunks, deliver exactly one `"stopped"` terminal, and free the key. The key remains occupied until that terminal is delivered, so wait for `"stopped"` before reusing it; an earlier restart is rejected. A missing key no-ops. Declare `"microphone"` and/or `"system_audio"` in `app.zon` permissions so macOS dev executables and packaged apps carry the required usage descriptions.
171
- - `Cmd.imageLoad(id, { path?, url?, cachePath?, expectedBytes? }, { event })` — load an image at runtime under the model-owned NUMERIC ImageId your markup binds (`<image image="{cover}"/>`, `<avatar image="{avatar}"/>`); `id` may be any number expression (ids are model data), a positive integer below 2^53 (a certain-to-be-refused literal like 0 stops the build, NS1030). The source cascade is `audioPlay`'s exactly: local `path` first, a missing file falls through to `url` (fetched whole, installed at the cache path and integrity-gated by `expectedBytes`); at least one of `path`/`url` (NS1029), and prefer OMITTING `cachePath` — the wiring's caches directory (`TsUiApp`'s `image_cache_dir`) derives the content-addressed path from the URL. Exactly ONE `event` arm dispatches per load — a five-field record matched by NAME: `id` (the requested ImageId echoed verbatim, so concurrent loads sharing one arm stay distinguishable; an id the wire cannot carry exactly echoes 0), `state` (the `ImageState` union — exactly the fifteen members `"loaded" | "rejected" | "not_found" | "io_failed" | "connect_failed" | "tls_failed" | "protocol_failed" | "timed_out" | "http_status" | "cancelled" | "too_large" | "unsupported" | "decode_failed" | "registry_full" | "alloc_failed"`, any order; `"alloc_failed"` is resource exhaustion at registration — the host refused the memory, the bytes may be fine, retry when memory frees), `width`/`height` (the decoded dimensions on `"loaded"`, 0 otherwise), and `status` (the HTTP status for url loads that performed an exchange; 0 when none occurred — local paths, cache hits — so a cached `"loaded"` is distinguishable from a network one). On `"loaded"` the pixels are already registered under the id — store the id in the model then (the store-on-success discipline keeps a fallback rendering until the load lands). One load per id at a time: a duplicate live id dispatches `"rejected"` (the spawn discipline — a load in flight is never replaced implicitly), and image loads are not the string-keyed `Cmd.cancel`'s to end — `Cmd.imageCancel(id)` is their cancel, LOUD like spawn's: the one terminal still arrives as the event arm's `"cancelled"`, and the id frees for a fresh load once it lands (an id with no live load no-ops; the same NS1030 literal gate as `imageLoad`). Decode limits are the registered-image limits (16 slots, 1 MiB decoded pixels — avatar/cover scale, not photo scale); the encoded source bound is 1.25 MiB, and over-bound sources fail whole with `"too_large"`, never cut. `Cmd.imageUnregister(id)` releases a loaded image's registry slot — the gallery eviction move when the 17th distinct image would answer `"registry_full"`: views bound to the id fall back, and the slot accepts the next load. Unregister is synchronous registry surgery, NOT an effect — no result Msg, an unregistered id no-ops (the same NS1030 literal gate) — and it frees only the CURRENT registration: a load in flight under the id still registers at its terminal, so cancel the load first (`Cmd.imageCancel`) to keep the slot free.
172
+ - `Cmd.imageLoad(id, { path?, url?, cachePath?, expectedBytes? }, { event })` — load an image at runtime under the model-owned NUMERIC ImageId your markup binds (`<image image="{cover}"/>`, `<avatar image="{avatar}"/>`); `id` may be any number expression (ids are model data), a positive integer below 2^53 (a certain-to-be-refused literal like 0 stops the build, NS1030). The source cascade is `audioPlay`'s exactly: local `path` first, a missing file falls through to `url` (fetched whole, installed at the cache path and integrity-gated by `expectedBytes`); at least one of `path`/`url` (NS1029), and prefer OMITTING `cachePath` — the wiring's caches directory (`TsUiApp`'s `image_cache_dir`) derives the content-addressed path from the URL. Exactly ONE `event` arm dispatches per load — a five-field record matched by NAME: `id` (the requested ImageId echoed verbatim, so concurrent loads sharing one arm stay distinguishable; an id the wire cannot carry exactly echoes 0), `state` (the `ImageState` union — exactly the fifteen members `"loaded" | "rejected" | "not_found" | "io_failed" | "connect_failed" | "tls_failed" | "protocol_failed" | "timed_out" | "http_status" | "cancelled" | "too_large" | "unsupported" | "decode_failed" | "registry_full" | "alloc_failed"`, any order; `"alloc_failed"` is resource exhaustion at registration — the host refused the memory, the bytes may be fine, retry when memory frees), `width`/`height` (the actual registered dimensions on `"loaded"`, 0 otherwise), and `status` (the HTTP status for url loads that performed an exchange; 0 when none occurred — local paths, cache hits — so a cached `"loaded"` is distinguishable from a network one). On `"loaded"` the pixels are already registered under the id — store the id in the model then (the store-on-success discipline keeps a fallback rendering until the load lands). One load per id at a time: a duplicate live id dispatches `"rejected"` (the spawn discipline — a load in flight is never replaced implicitly), and image loads are not the string-keyed `Cmd.cancel`'s to end — `Cmd.imageCancel(id)` is their cancel, LOUD like spawn's: the one terminal still arrives as the event arm's `"cancelled"`, and the id frees for a fresh load once it lands (an id with no live load no-ops; the same NS1030 literal gate as `imageLoad`). The default registry has 16 slots and a 1 MiB decoded-pixel target per slot: platform codecs downscale photo-size sources at decode time, preserving aspect, instead of rejecting them. Image-centric apps may declare `.images = .{ .max_image_pixel_bytes = 8388608 }` in app.zon (1–8 MiB accepted); allocation stays lazy per used slot, but filling 16 ceiling-sized slots is a declared 128 MiB high-water. Encoded sources have their own flat 8 MiB bound; only over-bound source bytes report `"too_large"` in normal operation, never a cut decode. `Cmd.imageUnregister(id)` releases a loaded image's registry slot — the gallery eviction move when the 17th distinct image would answer `"registry_full"`: views bound to the id fall back, and the slot accepts the next load. Unregister is synchronous registry surgery, NOT an effect — no result Msg, an unregistered id no-ops (the same NS1030 literal gate) — and it frees only the CURRENT registration: a load in flight under the id still registers at its terminal, so cancel the load first (`Cmd.imageCancel`) to keep the slot free.
172
173
 
173
174
  ### The window verbs
174
175
 
@@ -183,7 +184,7 @@ Launch at Login uses keyed routed effects: `Cmd.launchAtLoginStatus({ key?, ok,
183
184
 
184
185
  ### Model-derived menu-bar status items
185
186
 
186
- Export `statusItem(model): StatusItemState` from `src/core.ts` to make the generated launcher install a native menu-bar status item and keep its presentation and menu synchronized with committed model state. Presentation and menu hash independently: changing title/width/tone/icon opacity/number style does not rebuild the rows, and neither change recreates the native item. `statusItem` is launcher-bound automatically, so do not repeat it in `viewUnbound`.
187
+ Export `statusItem(model): StatusItemState` from `src/core.ts` to make the generated launcher install a native menu-bar status item and keep its shell, presentation, and menu synchronized with committed model state. The three channels hash independently: changing icon/tooltip/activation hooks, title/width/tone/icon opacity/number style, or rows patches only that channel and never recreates the native item. `statusItem` is launcher-bound automatically, so do not repeat it in `viewUnbound`.
187
188
 
188
189
  ```ts
189
190
  import { asciiBytes, utf8Bytes } from "@native-sdk/core";
@@ -206,10 +207,41 @@ export function statusItem(model: Model): StatusItemState {
206
207
  }
207
208
  ```
208
209
 
209
- The canonical records live in `@native-sdk/core/events`. Install-time fields are `iconPath`, `tooltip`, `activationCommand`, `alternateActivationCommand`, and `openCommand`; all commands route through `commandMsg(name): Msg | null`. Presentation is exact: `title`, `width` (0 = host default), `tone` (`normal | warning | critical`), `iconOpacity` (0…1), and `monospaced`. Every row has id/label/command/separator/enabled plus byte `detail`, `role` (`command | info | header | hero | agent | context`), byte `key`, and the five explicit modifier booleans. Actionable rows need unique non-zero whole u32 ids and a non-empty label, separators conventionally use id 0, and the runtime cap is 32 rows. Row membership and every live presentation/menu field may derive from the model. Linux does not implement status items today.
210
+ The canonical records live in `@native-sdk/core/events`. Shell fields are `iconPath`, `tooltip`, `activationCommand`, `alternateActivationCommand`, and `openCommand`; all commands route through `commandMsg(name): Msg | null`. Presentation is exact: `title`, `width` (0 = host default), `tone` (`normal | warning | critical`), `iconOpacity` (0…1), and `monospaced`. Every row has id/label/command/separator/enabled plus byte `detail`, `role` (`command | info | header | hero | agent | context`), byte `key`, and the five explicit modifier booleans. Actionable rows need unique non-zero whole u32 ids and a non-empty label, separators conventionally use id 0, and the runtime cap is 32 rows per item. Row membership and every shell/presentation/menu field may derive from the model. Linux does not implement status items today.
211
+
212
+ For multiple items export `statusItems(model): readonly StatusItemDescriptor[]` instead (never both helpers). A descriptor has the singular fields plus stable non-zero `id` identity and live `visible`. Presence creates, absence removes, and changed icon/title/tooltip/visibility/activation/menu fields patch only that id; one menu update never recreates any native item. macOS supports eight simultaneous items. Row ids are scoped to one menu, so different status items may reuse them. This is the Vercel-shaped spend-indicator plus persistent-control-item surface.
210
213
 
211
214
  Commands are constructed inline in the return path and nowhere else (NS1017): never in the Model or a Msg, never in a local, never in a helper. This is what keeps effects inside the dispatch cycle and replay honest.
212
215
 
216
+ ### Model-declared secondary windows
217
+
218
+ Export `windows(model): readonly WindowDescriptor[]` to derive the secondary windows that should exist from committed model state. Import `WindowDescriptor` from `@native-sdk/core/events`, and construct entries with `windowDescriptor` from `@native-sdk/core` so omitted fields receive the canonical defaults. Presence is liveness: adding a descriptor creates the window, removing it closes the window and releases its retained view.
219
+
220
+ Each possible label has a statically compiled Native markup view at `src/windows/<label>.native`; for example descriptor label `settings` uses `src/windows/settings.native`. Spell that identity directly inside the canonical constructor as `label: asciiBytes("settings")`: window labels are static declarations, and `native check`/every build reject a dynamic label or one whose root file is missing. Window roots may import shared components nested under `src/windows/` with the ordinary `<import>` syntax; the generated launcher embeds and hot-reloads the full import closure. The descriptor's `canvasLabel` must be unique across the whole app. Both the main view and every open window view rebuild from the same model after a Msg.
221
+
222
+ ```ts
223
+ import { asciiBytes, windowDescriptor } from "@native-sdk/core";
224
+ import { type WindowDescriptor } from "@native-sdk/core/events";
225
+
226
+ export function windows(model: Model): readonly WindowDescriptor[] {
227
+ if (!model.settingsOpen) return [];
228
+ return [windowDescriptor({
229
+ label: asciiBytes("settings"),
230
+ canvasLabel: asciiBytes("settings-canvas"),
231
+ title: asciiBytes("Settings"),
232
+ width: 420,
233
+ height: 240,
234
+ resizable: false,
235
+ closePolicy: "quit",
236
+ onCloseCommand: asciiBytes("app.settings-closed"),
237
+ })];
238
+ }
239
+ ```
240
+
241
+ `closePolicy` is `"quit"` by default. Under `"quit"`, a user close really closes the window and routes `onCloseCommand` through `commandMsg`; map it to the Msg that clears the model's open flag. If the model keeps declaring the label, source wins and the next reconciliation recreates it. Under `"hide"`, the same native window and view stay alive, no close command fires, and `Cmd.showWindow("settings")` reveals it. Stopping the declaration always performs a real reconcile close. The platform safeguards for `hide` are the same as manifest windows. Model-declared secondary windows are desktop-only.
242
+
243
+ `titlebar` accepts `"standard"`, `"hidden_inset"`, `"hidden_inset_tall"`, and `"chromeless"`. The last removes all OS chrome and is required when a transparent model-declared window targets Windows; provide working app-drawn close/minimize controls for that fully skinned shape.
244
+
213
245
  ### The init command
214
246
 
215
247
  `initialModel` may return the same pair to run a boot effect once at install, before the first view build — loading a store is the canonical use:
@@ -359,7 +391,8 @@ export type Msg = /* ... */ | { readonly kind: "library_scrolled"; readonly scro
359
391
  The generated wiring detects each channel from an export (export exists → wired; a wrong shape is a taught NS1033). Event records are matched by field name, STRUCTURALLY: import them from `@native-sdk/core/events` (`FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`, `ChromeInsets`/`ChromeButtons`) or declare the same shapes in your core — both emit as your module's types and match identically. The `appearanceMsg`/`chromeMsg` arms themselves stay inline union members (`kind` plus the event's fields — the subset has no intersection arms); the SDK's `AppearanceEvent`/`ChromeEvent` records are those arms' canonical payload shapes, importable for helper signatures.
360
392
 
361
393
  - **`commandMsg(name: string): Msg | null`** — menus, shortcuts, and chrome tabs, by command id (string equality works on `string` values).
362
- - **`statusItem(model: Model): StatusItemState`** — the complete menu-bar item: install-time icon/tooltip/click hooks plus live presentation and dropdown. The generated launcher installs it and re-derives the live parts after committed updates; import the exact records from `@native-sdk/core/events`.
394
+ - **`statusItem(model: Model): StatusItemState` / `statusItems(model: Model): readonly StatusItemDescriptor[]`** — one complete menu-bar item, or a stable-id collection: live icon/tooltip/visibility/click hooks, presentation, and dropdown. The generated launcher reconciles after committed updates; import the exact records from `@native-sdk/core/events`.
395
+ - **`windows(model: Model): readonly WindowDescriptor[]`** — the model-declared secondary-window set. The launcher compiles `src/windows/<label>.native`, reconciles descriptor presence after committed updates, projects `closePolicy`, and routes a `.quit` `onCloseCommand` through `commandMsg`.
363
396
  - **`frameMsg(model: Model, frame: FrameEvent): Msg | null`** — presented frames. `FrameEvent` is exactly `{ width, height, timestampMs, intervalMs }` numbers (canvas points; fractional milliseconds). Return null for frames that change nothing — the idle law holds exactly when an idle app dispatches nothing (a frame arm that always returns a Msg would spin the loop at full frame rate). The installing frame is excluded; the first PRESENTED frame corrects any seeded value.
364
397
  - **`keyMsg(key: KeyEvent): Msg | null`** — the app-level key FALLBACK (a focused widget's own keys and editable text always win first). `KeyEvent` is exactly `{ key: string; shift: boolean; control: boolean; alt: boolean; super: boolean }`; the key NAME arrives lowercased (`key.key === "space"`).
365
398
  - **`pinchMsg(pinch: PinchEvent): Msg | null`** — the view-global trackpad pinch channel. `PinchEvent` carries `windowId`, `label`, begin/change/end `phase`, multiplicative `scale` delta, and the view-local `x`/`y` anchor.
@@ -371,19 +404,19 @@ The generated wiring detects each channel from an export (export exists → wire
371
404
 
372
405
  ## The rules the checker enforces
373
406
 
374
- Every diagnostic carries one of these IDs plus the fix and the why. Write to them up front:
407
+ Every diagnostic carries one of these IDs plus the fix and the why, and every rule carries a class: `guarantee` rules protect a core invariant (determinism and replay, fixed shapes, immutability of shared data, the one text representation) and are permanent; `deferred` rules (NS1011, NS1019, NS1040, NS1042, NS1044) wait on a deliberate easing decision and say so in their output. Write to them up front:
375
408
 
376
409
  - **NS1001 shared data is immutable; your own scratch is yours.** Never mutate `model`, `msg`, parameters, module tables, or anything reached from them — build the next value (`{ ...model, tasks: [...model.tasks, task] }`) or copy first (`const copy = xs.slice()`). Arrays this function creates itself mutate freely until they escape — appends via `xs[xs.length] = v`, all-owning reassigned bindings, and readonly-reader borrows included (see "Local mutation" above). The previous model stays live for rendering and undo; unchanged parts are shared, not copied.
377
- - **NS1002 updates are synchronous.** No `async`/`await`/Promises in a core. Work that takes time is command data; the runtime dispatches your `Msg` with the result.
410
+ - **NS1002 updates are synchronous.** No `async`/`await`/Promises in a core. Work that takes time is command data; the runtime dispatches your `Msg` with the result. Network and other ordinary async work runs in `src/services/` through the generated `@native-sdk/services` client.
378
411
  - **NS1003 models hold data, not functions.** No function-typed fields in the Model/Msg tree. Name the behavior as a message and handle it in `update`.
379
412
  - **NS1004 text is not indexable.** No `.length`/`s[i]`/`.charCodeAt` on `string`. Bytes: `Uint8Array`; display literals/templates use `utf8Bytes`, guaranteed-ASCII machine text uses `asciiBytes`.
380
- - **NS1005 update is deterministic.** No `Date.now()`, `Math.random()`, or ambient IO. Take time and randomness as message payloads.
413
+ - **NS1005 update is deterministic.** No `Date.now()`, `Math.random()`, or ambient IO. Take time and randomness as message payloads: time via `Cmd.now`, and a `src/services/` module may read the clock directly and return the value as a Msg.
381
414
  - **NS1006 classes are data classes, declared at module level.** `class` with annotated fields, one constructor, and plain methods compiles (see "Data classes" above); class expressions, `this` outside a member body, and `new` of anything but a data class (or `Uint8Array`) are taught.
382
415
  - **NS1007 implicit builtin throws stay out.** A JS builtin that throws mid-operation (`.reduce` with no initial value on a possibly-empty array) is taught toward its explicit form; your own `throw` of a subset value is supported control flow (see "Exceptions" above).
383
416
  - **NS1008 only erasable syntax.** No `enum`, `namespace`, decorators, parameter properties. String-literal unions are the enum.
384
417
  - **NS1009 no `for`/`in`.** Fixed shapes, no prototypes; model the data as an array and walk it with a classic loop.
385
418
  - **NS1010 module state lives in the Model.** Module-level `let` is banned (`const` is fine), and a class's MUTABLE `static` field is the same thing by another spelling — `static readonly` consts compile.
386
- - **NS1011 no Map/Set in v1.** Model the data as an id-keyed array of records and look up with a loop or `.filter`.
419
+ - **NS1011 no Map/Set in v1.** Model the data as an id-keyed array of records and look up with a loop or `.filter`; transform-heavy work may use `Map`/`Set` inside a `src/services/` module and return plain records.
387
420
  - **NS1012 object shapes are fixed.** No `delete`, getters/setters, sparse arrays, `Proxy`, `Symbol`. Optional data is `T | null`.
388
421
  - **NS1013 closed world.** No `eval`, `new Function`, dynamic `import()`.
389
422
  - **NS1014 the core's entry points live in core.ts.** `update`, `initialModel`, `subscriptions`, the wiring channel exports, and `viewUnbound` belong to the entry module; an entry export in an imported file would be silently ignored by the build, so it is taught instead. Move the export into `src/core.ts` and let the imported module hold what it calls.
@@ -408,7 +441,7 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
408
441
  - **NS1031 exported model helpers join the model's binding surface.** An exported single-Model-parameter helper becomes a Model declaration markup binds (`doneCount` → `{doneCount}`); two members with one binding name would be ambiguous — rename one.
409
442
  - **NS1032 viewUnbound names update-only model state.** `export const viewUnbound = [...] as const` entries must be string literals naming Model fields, exported model helpers, or Msg kinds — by their TypeScript spellings (`"nextId"`); anything else would silence nothing and hide a typo.
410
443
  - **NS1030 effect arguments respect the engine's limits.** A compile-time-knowable value outside an engine bound (a path literal over 1024 bytes, a URL literal over 2 KiB, more than 8 headers, a header block over 1 KiB, a delay literal outside 1ms..one year) stops the build instead of shipping a guaranteed runtime rejection. Dynamic values stay the engine's to validate — they surface through the `err` arm.
411
- - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg`/`pinchMsg`/`dropMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm; `themePack` and `statusItem` return their exact model-derived shell shapes. The generated wiring builds these host values structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
444
+ - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg`/`pinchMsg`/`dropMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm; `themePack`, `statusItem`, `statusItems`, and `windows` return their exact model-derived shell shapes. The generated wiring builds these host values structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
412
445
  - **NS1034 core imports stay inside src/.** `../` escapes and absolute paths are rejected: the entry module's directory is the core's whole world - the build ships exactly that tree.
413
446
  - **NS1035 npm packages do not run inside a core.** No JS engine ships in the binary; vendor the logic under `src/` or make the import type-only.
414
447
  - **NS1036 core modules do not import in a cycle.** Runtime cycles only work through JS live-binding indirection; hoist shared declarations, or make the back-edge `import type` (which is exempt and idiomatic).
@@ -416,8 +449,8 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
416
449
  - **NS1038 module-scope names are unique across a core's files.** Type names and exported value names share the compiled module's one namespace - declare the shared thing once and import it (private helper collisions are auto-prefixed instead). Same-file homonyms count too: a type and an exported value cannot share a name, and interfaces never merge.
417
450
  - **NS1039 a namespace import is a compile-time alias.** `import * as ns from "./util.ts"` works as dot-syntax (`ns.helper(x)`, `ns.Cfg`); `ns` itself is not a value (never stored or passed), and the intrinsic `@native-sdk/core` module is imported by name so the purity rules can see `Cmd`/`Sub`/`asciiBytes`/`utf8Bytes`.
418
451
  - **NS1064 `asciiBytes` is ASCII-only.** Use `utf8Bytes` for user-visible or Unicode text; reserve `asciiBytes` for values whose contract guarantees 7-bit ASCII.
419
- - **NS1040 no regular expressions.** A regex is a runtime engine the binary does not carry; scan bytes with loops or the SDK text helpers (`containsIgnoreCase`, `trimAsciiSpaces`).
420
- - **NS1041 types are static: no runtime type or shape tests.** `typeof` values, `in`, `instanceof`, and the `Object`/`Reflect`/`JSON`/`Array` statics read runtime tags fixed native layouts do not have; model alternatives as a discriminated union and switch on its `kind`.
452
+ - **NS1040 no regular expressions.** A regex is a runtime engine the binary does not carry; scan bytes with loops or the SDK text helpers (`containsIgnoreCase`, `trimAsciiSpaces`), or run the match in a `src/services/` module, where regexes are ordinary TypeScript.
453
+ - **NS1041 types are static: no runtime type or shape tests.** `typeof` values, `in`, `instanceof`, and the `Object`/`Reflect`/`JSON`/`Array` statics read runtime tags fixed native layouts do not have; model alternatives as a discriminated union and switch on its `kind`, and parse JSON in a `src/services/` module that returns a typed record.
421
454
  - **NS1042 no generators.** `function*`/`yield` is a resumable frame with hidden state; build the sequence as an array (push-builder or `.map`/`.filter`) and return it whole.
422
455
  - **NS1043 statements stay statements.** Comma sequences (outside a for-loop incrementor) and `void` squeeze statements into expression position (the subset's empty value is spelled `null`); a number `++`/`--`/assignment in value position is legal only where the split statement is order-exact (sole mention, unskippable — `arr[i++]`, `const n = ++count`), and the taught remainder names why.
423
456
  - **NS1044 no BigInt or Symbol.** A core's numbers are IEEE f64 slots (integer-classed slots emit i64); model identities as number ids.
@@ -514,7 +547,7 @@ export function update(model: Model, msg: Msg): Model {
514
547
 
515
548
  ## Running a core as an app
516
549
 
517
- A `native init` app needs NONE of this section: the build detects `src/core.ts` and stages the wiring itself (a core exporting `commandMsg(name: string): Msg | null` automatically receives menu/shortcut/status-item command events as Msgs). A core can also export `themePack(model: Model): ThemePack`, with `export type ThemePack = "house" | "geist"`, to select the built-in pack from live model state, and `statusItem(model): StatusItemState` to own the complete menu-bar item. The adapter wires these as `theme_fn` and `status_item_fn`; in hand Zig wiring, empty install-time fields from the callback inherit a custom static `status_item`. The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
550
+ A `native init` app needs NONE of this section: the build detects `src/core.ts` and stages the wiring itself (a core exporting `commandMsg(name: string): Msg | null` automatically receives menu/shortcut/status-item/window-close command events as Msgs). A core can also export `themePack(model: Model): ThemePack`, either status-item helper, and `windows(model): readonly WindowDescriptor[]`; the adapter wires the matching UiApp seams, while the generated launcher supplies secondary views from `src/windows/<label>.native`. The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
518
551
 
519
552
  The compiled core runs as a full desktop app through `native_sdk.TsUiApp(core)` — the committed TS model IS the app model, no shim, no glue:
520
553
 
@@ -534,7 +567,7 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
534
567
  });
535
568
  ```
536
569
 
537
- - `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically. It likewise wires `theme_fn` from `themePack(model)` and `status_item_fn` from `statusItem(model)`. A wiring that also sets one of those seams is a teaching panic. Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, a static `status_item` can supply icon/tooltip, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
570
+ - `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically. It likewise wires `theme_fn` from `themePack(model)` and the singular `status_item_fn` or collection `status_items_fn` from the matching helper. A wiring that also sets one of those seams is a teaching panic. Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
538
571
  - Markup binds your model's field names EXACTLY as you wrote them: `nextId` binds as `{nextId}` (the core's model keeps the TS spellings). Record arrays iterate with `<for each="tasks" as="t" key="id">` and items bind their fields (`{t.title}`); optional scalars gate with `<if test="{selected}">` (null is falsy); string-literal unions bind as their member name (`{filter}` renders `all` — compare against a quoted literal, `selected="{sortKey == 'cpu'}"`); exported single-model helpers bind as derived values (`{doneCount}`) and slice-returning ones drive `for each`. Markup `<chart>` series bind number arrays too — `<series kind="bar" values="{cpuSpark}" />` over a field or helper returning `readonly number[]` (f64, narrowed per sample into the chart pipeline); pad a filling window's leading gap with `NaN` samples, which draw nothing.
539
572
  - `Options.sync` does not exist for TS apps (a committed model cannot be mutated in place): keep continuous controls model-driven — bind the widget's value and echo `on-change`/`on-scroll` Msgs back into the model.
540
573
  - One live app per core module per process: two apps over the SAME core would share one committed root — and a process carries ONE compiled core (the archive owns a fixed-prefix C ABI symbol set).
@@ -542,7 +575,7 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
542
575
 
543
576
  ## Build targets
544
577
 
545
- Builds compile the whole app — the core archive, service executables or in-process archives, and the runner — for one stated target; the default is the build host, and `-Dtarget` selects a cross desktop target on the pinned compiler's matrix: Linux and Windows GNU targets from any macOS/Linux/Windows host, macOS targets from a macOS host. Windows MSVC builds natively on a matching Windows host (cross-Windows is GNU: Zig supplies that target's CRT and system libraries), and an explicitly spelled Linux `-gnu` target must state its glibc (`x86_64-linux-gnu.2.36` or later, or `-musl`) because the compiled runtime needs glibc 2.36+. Executable naming and packaging follow the target OS. TypeScript cores stay desktop-only: mobile targets keep Zig and markup cores and teach at configure time.
578
+ Builds compile the whole app — the core archive, service executables or in-process archives, and the runner — for one stated target; the default is the build host, and `-Dtarget` selects a cross desktop target on the pinned compiler's matrix: Linux and Windows GNU targets from any macOS/Linux/Windows host, macOS targets from a macOS host. Windows MSVC builds natively on a matching Windows host (cross-Windows is GNU: Zig supplies that target's CRT and system libraries), and an explicitly spelled Linux `-gnu` target must state its glibc (`x86_64-linux-gnu.2.36` or later, or `-musl`) because the compiled runtime needs glibc 2.36+. Executable naming and packaging follow the target OS. Mobile targets compile the core as a static archive merged into the mobile embed library (`native dev|package --target ios|android` link it like a Zig core's): aarch64 only — `aarch64-ios`/`aarch64-ios-simulator` from a macOS host (iOS 15.0 floor), `aarch64-linux-android` from any desktop host with an NDK (API 26 floor). Mobile services run on the in-process pool only (`auto` resolves to it; `"child"` is refused with a teaching); the vendored npm lane is unchanged. Persist, boot images, and URL media caching are not wired on mobile yet.
546
579
 
547
580
  ## Checking your work
548
581
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ts-services
3
- description: Authoring guide for Native SDK TypeScript services under src/services: ordinary scriptc static-tier TypeScript reached through generated typed Cmd clients, shared record shapes, hermetic vendored npm, streaming, deadlines, cancellation, devhost simulation, authority, replay, and the two desktop carriers (in-process thread pool, child subprocess). Use when adding or modifying src/services modules, moving Node/JSON/regex/Map/Date/class work out of a core, or fixing NS1065-NS1067.
3
+ description: Authoring guide for Native SDK TypeScript services under src/services: ordinary scriptc static-tier TypeScript reached through generated typed Cmd clients, shared record shapes, hermetic vendored npm, streaming, deadlines, cancellation, devhost simulation, authority, replay, and the two carriers (in-process thread pool, child subprocess). Use when adding or modifying src/services modules, moving Node/JSON/regex/Map/Date/class work out of a core, or fixing NS1065-NS1067.
4
4
  ---
5
5
 
6
6
  # Author TypeScript services behind the effect boundary
@@ -79,7 +79,7 @@ native vendor . escape-string-regexp@5.0.0
79
79
 
80
80
  The command installs with lifecycle scripts disabled in a temporary directory, copies the flattened package graph into `src/services/vendor/`, retains package/license files, computes canonical tree hashes, and rewrites app.zon's `service_packages` with exact names, `X.Y.Z` versions, and hashes. Check those bytes and manifest facts into source control.
81
81
 
82
- Builds never run npm or use the network. They verify package identity and every vendored byte, stage only declared packages, and invoke scriptc with `--npm-static <explicit-list>`. `auto`, dynamic-island fallback, and `--dynamic` are refused. Anything below 100% static coverage fails: `native check` preserves the coverage note verbatim and names the three options—choose another exact package, port/vendor a suitable implementation, or wait for compiler support. The checked-in scriptc 0.0.28 spike (`tests/ts-services/npm-static-spike.json`) passed three of five deliberately small candidates and refused `nanoid` and `micromark`; npm support is selective.
82
+ Builds never run npm or use the network. They verify package identity and every vendored byte, stage only declared packages, and invoke scriptc with `--npm-static <explicit-list>`. `auto`, dynamic-island fallback, and `--dynamic` are refused. Anything below 100% static coverage fails: `native check` preserves the coverage note verbatim and names the three options—choose another exact package, port/vendor a suitable implementation, or wait for compiler support. The checked-in package spike (`tests/ts-services/npm-static-spike.json`) passed three of five deliberately small candidates and refused `nanoid` and `micromark`; npm support is selective.
83
83
 
84
84
  ## Streaming, cancellation, and deadlines
85
85
 
@@ -113,13 +113,13 @@ Import `ServiceCancellation` as a type from `@native-sdk/core`; it is legal only
113
113
 
114
114
  `native dev --core` imports service modules in an isolated Node worker, verifies the same package hashes, decodes the same request contract, cooperatively interrupts cancellation/deadline work, maps errors through the same arms, and emits stream chunks through the same channel-event shape. Use `--script scenario.ndjson --watch` for repeatable logic iterations. The devhost reads `NATIVE_SDK_SESSION_RECORD`/`NATIVE_SDK_SESSION_REPLAY`, writes the native journal format, and starts no service worker during replay. Service-only recordings cross between it and the packaged runtime; packaged recordings containing other effect families must be replayed with `native automate replay`, and devhost rejects those records explicitly. `native dev` runs the compiled service executable beside the real app.
115
115
 
116
- Carrier selection is a build fact: `.service_carrier = "in_process" | "child"` in app.zon (or `-Dservice-carrier`). Unset/`"auto"` preserves the child carrier. The in-process archive is available for native Linux, cross-Linux x86_64/aarch64, native Windows x86_64, cross-Windows x86_64 GNU, and macOS targets built on macOS. `.service_pool_size` (or `-Dservice-pool-size`, 1–16) sets the in-process pool width; the default is min(4, cores).
116
+ Carrier selection is a build fact: `.service_carrier = "in_process" | "child"` in app.zon (or `-Dservice-carrier`). Unset/`"auto"` preserves the child carrier on desktop and resolves to the in-process pool on iOS/Android (mobile apps cannot spawn a sibling process; an explicit `"child"` there is refused with a teaching). The in-process archive is available for native Linux, cross-Linux x86_64/aarch64 (`aarch64-linux-android` included), native Windows x86_64, cross-Windows x86_64 GNU, and the Mach-O targets — macOS, `aarch64-ios`, `aarch64-ios-simulator` — built on macOS. `.service_pool_size` (or `-Dservice-pool-size`, 1–16) sets the in-process pool width; the default is min(4, cores).
117
117
 
118
118
  Authority differs by carrier. The child process runs with the app's privileges and app-data cwd, receives an explicit environment allowlist (path, user/home/temp, locale/time zone, certificate, and proxy variables; platform equivalents on Windows) with `NATIVE_SDK_*` internals stripped, and its stdout belongs to framed transport (diagnostics go to stderr). In-process services share the app process outright: the app's full environment and working directory, no transport-owned stdout — and a hardware fault (stack overflow) or `process.exit()` in service code takes the app with it, so the child carrier remains the fully isolated option. Each pool worker owns a separate service-module instance, so mutable module globals are worker-local and requests on different keys may observe different copies; keep shared durable state outside module globals. Either way this authority is why service work never runs synchronously inside `update`.
119
119
 
120
120
  Current limits:
121
121
 
122
- - desktop targets only: child executables use the broad compiler matrix (same-platform builds, Linux/Windows GNU cross-targets from desktop hosts, and macOS targets from macOS), while in-process archives require native Linux, cross-Linux x86_64/aarch64, native Windows x86_64, cross-Windows x86_64 GNU, or macOS built on macOS; Windows MSVC builds natively on a matching Windows host, while cross-Windows uses GNU because Zig supplies that target's CRT and system libraries; any explicitly spelled Linux `-gnu` target — even one matching the build host — must also spell its glibc (`x86_64-linux-gnu.2.36` or later, or `-musl`) because Zig otherwise selects the runtime's too-old default floor;
122
+ - child executables are desktop-only and use the broad compiler matrix (same-platform builds, Linux/Windows GNU cross-targets from desktop hosts, and macOS targets from macOS), while in-process archives follow the localization matrix above (mobile targets are archive-only: iOS from a macOS host at the 15.0 floor, Android from any desktop host with an NDK at the API 26 floor); Windows MSVC builds natively on a matching Windows host, while cross-Windows uses GNU because Zig supplies that target's CRT and system libraries; any explicitly spelled Linux `-gnu` target — even one matching the build host — must also spell its glibc (`x86_64-linux-gnu.2.36` or later, or `-musl`) because Zig otherwise selects the runtime's too-old default floor;
123
123
  - synchronous static-tier operations only—async services wait for the next compiler/runtime phase;
124
124
  - no JavaScript engine or dynamic npm fallback;
125
125
  - storage remains engine-owned effects, not a service-layer database shortcut;