@native-sdk/cli 0.8.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1847 -16
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +82 -16
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. package/tools/corewire/sidecar.zig +26 -15
@@ -1,13 +1,13 @@
1
1
  ---
2
2
  name: ts-core
3
- description: Authoring guide for the primary Native SDK app-logic path: TypeScript app cores - Model, Msg, update, and the pure functions they call, written in the closed app-core subset, checked by the @native-sdk/core frontend, and compiled ahead-of-time to native code by the external core compiler. Use for new apps unless the user explicitly chose Zig, when writing or modifying a src/core.ts app core, fixing subset checker errors (NS1001-NS1060), or deciding how to express state, messages, text (bytes and the byte-text string methods), text input, continuous controls (sliders, scroll), effects (Cmd), subscriptions (Sub), the host-event wiring channels (frameMsg, keyMsg, pinchMsg, dropMsg, appearanceMsg, chromeMsg, envMsgs, app.zon assets), derived values, the view_unbound lint opt-out, local mutation of owned arrays, or how to split a core into modules under src/ (relative imports, namespace imports, @native-sdk/core/text, @native-sdk/core/events).
3
+ description: Authoring guide for the primary Native SDK app-logic path: TypeScript app cores - Model, Msg, update, and the pure functions they call, written in the closed app-core subset, checked by the @native-sdk/core frontend, and compiled ahead-of-time to native code by the external core compiler. Use for new apps unless the user explicitly chose Zig, when writing or modifying a src/core.ts app core, fixing subset checker errors (NS1001-NS1069), or deciding how to express state, messages, text (bytes and the byte-text string methods), text input, continuous controls (sliders, scroll), effects (Cmd), subscriptions (Sub), the host-event wiring channels (frameMsg, keyMsg, pinchMsg, dropMsg, appearanceMsg, chromeMsg, envMsgs, app.zon assets), derived values, the view_unbound lint opt-out, local mutation of owned arrays, or how to split a core into modules under src/ (relative imports, namespace imports, @native-sdk/core/text, @native-sdk/core/events). Use ts-services alongside this guide for src/services work.
4
4
  ---
5
5
 
6
6
  # Author app cores in the TypeScript subset
7
7
 
8
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.
9
9
 
10
- A whole TS app is three files of truth and zero Zig: `src/core.ts` (this guide; plus any modules it imports under `src/`), `src/app.native` (the markup view over the core's model), and `app.zon` (windows, identity, permissions). `native init` scaffolds exactly that; 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:
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
 
12
12
  ```sh
13
13
  native dev --core # the fastest loop: run the core under node's virtual host —
@@ -79,7 +79,7 @@ Logic:
79
79
 
80
80
  - `switch` on any union's `kind` tag — `msg.kind` (the Msg dispatch) and model-field unions (`switch (model.view.kind)`) alike — with member case labels, label stacking (`case "a": case "b": body`), `break`, and a trailing `default` covering the unnamed arms (without a `default` the switch must be exhaustive — NS1015; with every arm named the `default` is JS dead code and emits nothing) — and `switch` on a string-literal-union or numeric-literal-union *value* (`switch (model.filter)`) — an uncovered member skips the switch exactly like JS (a `default` anywhere but last is a taught stop in both forms) — and `switch` on a plain `number` or `string` value, lowered to an if/else chain with exact JS semantics: strict equality per case (NaN matches nothing, `-0` matches `0`, strings compare contents), cases tested in source order, `default` matching only after every case misses wherever it sits (an empty `default:` stacking onto the next body included); `if`/`else`; classic `for (let i = 0; ...)` including countdowns (`i--`, `i -= k`), multi-counter inits (`let lo = 0, hi = n`), and comma incrementors (`lo++, hi--` — the for-header is the one home for comma sequences); `do { ... } while (cond)` (the body runs before the first test; `continue` jumps to the test, exactly node); `for (const x of xs)` over arrays and `Uint8Array`, with `break`/`continue`, plus the indexed pair form `for (const [i, x] of xs.entries())` (exactly the `[index, element]` two-identifier binding — the index is the loop index, integer-classed; other tuple shapes stay taught); `while`; labeled statements on loops and blocks with labeled `break`/`continue` (`outer: for (...) { ... continue outer; }` — a labeled `continue` in a classic for still runs the incrementor, like JS); `let` locals with reassignment (and `let x: number;` declared-then-assigned); ternaries; `&&`/`||`/`!`; the empty statement `;`.
81
81
  - `const { total, done: doneCount } = stats;` — record-field destructuring into const locals (a compile-time alias per field, renames included). Array patterns, parameter patterns, defaults, rest, and nesting are taught (NS1045 — positions can be silently absent in JS; fields cannot).
82
- - `import * as util from "./util.ts"` — a namespace import over your own modules is pure dot-syntax: `util.helper(x)`, `util.CONST`, and `util.Cfg` in type positions all resolve to the target module's flat names. The alias is not a value (storing or passing `util` itself is taught), and the intrinsic `@native-sdk/core` module is always imported by name (NS1039 — the purity rules recognize `Cmd`/`Sub`/`asciiBytes` by their imported names).
82
+ - `import * as util from "./util.ts"` — a namespace import over your own modules is pure dot-syntax: `util.helper(x)`, `util.CONST`, and `util.Cfg` in type positions all resolve to the target module's flat names. The alias is not a value (storing or passing `util` itself is taught), and the intrinsic `@native-sdk/core` module is always imported by name (NS1039 — the purity rules recognize `Cmd`/`Sub`/`asciiBytes`/`utf8Bytes` by their imported names).
83
83
  - Object spread `{ ...model, field: v }`, array spreads in any shape — append `[...xs, x]`, prepend `[x, ...xs]`, multi-spread `[...a, x, ...b]` (each compiles to one exact-size copy) — `.length`, indexing `xs[i]`.
84
84
  - Array methods, lowered to inlined loops and exact-size arena copies: `.map` / `.filter` / `.find` / `.findIndex` / `.some` / `.every` / `.reduce` / `.toSorted` / `.slice` / `.concat` / `.indexOf` / `.includes`. `.map` is type-changing — `tasks.map((t) => t.id)` produces a number array, `t => t.title` a bytes array, and a callback that can return `null` produces an optional-element array. Callbacks on map/filter/find/findIndex/some/every may take the `(element, index)` pair — the index is the loop index, integer-classed (`.reduce` stays `(acc, x)`: its index parameter is not in v1, and no callback takes the third JS parameter, the array itself — reference the array by name). Array-method calls may sit directly in `if`/`else if` and ternary conditions (`if (xs.some((x) => x > 3))`) — the scan lowers to a loop just before the branch; a `while` condition cannot (it re-evaluates per iteration — hoist into the loop body or restructure). Callbacks are arrows (expression or block body), inline `function` expressions, or a BARE REFERENCE to a module-level function or const helper (`xs.map(encodeTurn)`, `xs.toSorted(byAscending)` — the referenced body inlines exactly like the arrow spelled at the site); in a block body every code path must end in an explicit `return` (falling off the end would be JS `undefined`, which has no mapping — a taught stop). JS semantics hold exactly: `.slice` resolves negative and out-of-range indices the JS way, `.indexOf` never matches `NaN` while `.includes` does, `.some`/`.every` keep their vacuous defaults on empty arrays, and `.reduce` needs its initial value (the no-initial form throws on an empty array in JS, so it is a taught NS1007 — pass the starting accumulator). `.indexOf`/`.includes` work on scalar elements (numbers, tags, booleans); on record arrays JS compares references, which has no native mapping — match a field with `.find`/`.findIndex` instead.
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.
@@ -91,14 +91,14 @@ Logic:
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).
92
92
  - Every compound assignment as a statement: `+= -= *= /= %= **= &= |= ^= <<= >>= >>>=`, each exactly `x = x op v`, plus the guarded forms `&&=`/`||=` (boolean targets; the right side evaluates only when assigned, like JS) and `??=` (optional targets; assigns only when null). A number `++`/`--`/assignment may sit in a VALUE position when the split statement is provably order-exact — the variable's only mention in the statement, in a position JS cannot skip (`arr[i++]`, `const n = ++count`, `const z = (y = 5)`; postfix yields the pre-step value, everything else the post-step value, exactly JS); every other value-position form is taught (NS1043 — ternary branches, short-circuit right operands, loop conditions, or a second mention of the variable).
93
93
  - The Math batch, every corner pinned to node: `Math.min` / `Math.max` (any arity — `Math.min()` is Infinity, `Math.max()` is -Infinity, NaN propagates, -0 orders below +0), `Math.round` (half toward +Infinity), `Math.floor` / `Math.ceil` / `Math.trunc` (NaN/Infinity propagate; the -0 results keep their sign, so `Math.ceil(-0.5)` is -0), `Math.abs` (clears the zero sign), `Math.sign` (NaN stays NaN, a zero keeps its sign), `Math.sqrt` (negative input is NaN, `sqrt(-0)` is -0). `Number.isInteger` / `Number.isFinite` / `Number.isNaN` classify like node, and the `NaN` / `Infinity` globals are ordinary number values. Math calls over compile-time constants fold to their exact JS value — `const HALF = Math.floor(5 / 2)` is the integer 2, `5 % 0` is NaN, `-5 % 5` is -0. A bare `-0` literal (and constant arithmetic folding to -0, like `0 * -1`) is a float value — only f64 carries the signed zero — so it cannot flow into an index or another integer-required slot. The integer rule: floor/ceil/trunc/abs/sign of an integer-classed value stays integer-classed, but of a float value stays float (floor of NaN is NaN), so `bytes[Math.floor(x / 2)]` over a float `x` is still a taught NS1016 — keep index flows integer end to end.
94
- - Template literals with integer holes (`` `${n} of ${total}` ``) feeding `asciiBytes` (below). Float-valued holes are not in v1 (JS float-to-string fidelity is a runtime v2 surface).
95
- - Module-level `const` numbers and strings fold to comptime constants, and const tables emit as rodata (no arena, shared for free at commit): arrays of numbers / booleans / strings / literal-union members (`const WEEKDAYS = [3, 5, 2]`, `const ORDER: readonly Filter[] = ["done", "all"]`), records annotated with an interface (`const LIMITS: Limits = { lo: 1, hi: 9 }`), and arrays of records (`const SEEDS: readonly Task[] = [...]`, names as `asciiBytes` literals). Element access, `.length`, `for...of`, and the array methods all work over tables. Everything inside must fold at compile time — no spreads, no calls except `asciiBytes` on a literal — and a record table needs its interface annotation (an unannotated `{ ... }` is a taught stop naming the fix). Helper functions; recursion.
94
+ - Template literals with integer holes (`` `${n} of ${total}` ``) feeding `utf8Bytes` or `asciiBytes` (below). Float-valued holes are not in v1 (JS float-to-string fidelity is a runtime v2 surface).
95
+ - Module-level `const` numbers and strings fold to comptime constants, and const tables emit as rodata (no arena, shared for free at commit): arrays of numbers / booleans / strings / literal-union members (`const WEEKDAYS = [3, 5, 2]`, `const ORDER: readonly Filter[] = ["done", "all"]`), records annotated with an interface (`const LIMITS: Limits = { lo: 1, hi: 9 }`), and arrays of records (`const SEEDS: readonly Task[] = [...]`, names as `utf8Bytes` literals). Element access, `.length`, `for...of`, and the array methods all work over tables. Everything inside must fold at compile time — no spreads, no calls except `asciiBytes` or `utf8Bytes` on a literal — and a record table needs its interface annotation (an unannotated `{ ... }` is a taught stop naming the fix). Helper functions; recursion.
96
96
  - **Generics — module-level, monomorphized per call site.** A generic `function`, `interface`, or `type` declares type parameters and instantiates from tsc's RESOLVED type arguments (explicit or inferred): `export function pick<T>(xs: readonly T[], i: number): T { return xs[i]; }` called with tasks emits `pick__Task`, with numbers `pick__f64` (a bare `number` type argument is always f64 — the JS-exact class), one readable Zig fn per distinct instantiation, deduped. Generics over records, unions, arrays, optionals, and bytes all work; generic interfaces/aliases instantiate structurally (`Box<Task>` emits `Box__Task`; `type Opt<T> = T | null` resolves straight through); generics may recurse and call other generics (the inner call resolves at the outer's instantiation). `typeof CONST` type-query aliases resolve through tsc too (`const LIMIT = 9; type Limit = typeof LIMIT`). The boundaries teach: a call site whose type argument stays abstract (`pick([])` infers `never`; `any`/`unknown`, unnamed literal unions) is NS1053 — annotate the call or name the alias; generic function VALUES and generic entry points are NS1050.
97
97
  - **Data classes — fields, one constructor, plain methods, statics; no inheritance.** `class Task { title: Uint8Array; done: boolean = false; constructor(title: Uint8Array) { this.title = title; } toggle(): void { this.done = !this.done; } isDone(): boolean { return this.done; } }` emits as a plain struct plus module-level functions; `new Task(...)` constructs a record-shaped value (field initializers run in declaration order, then the constructor body). `static` members are per-class module declarations: a `static` method lowers to a receiver-less module fn under the class's mangled name (`Task.fromRow(...)` resolves to `Task__fromRow`), and a `static readonly` field with an initializer is a module const (`Task.LIMIT` — the module-const value rules apply: numbers/strings fold, tables need their annotation); a MUTABLE static is module state and teaches NS1010, and inside a static member reach other statics by the class name, never `this` (NS1056). `private`/`protected` keywords are accepted and ERASED — tsc enforces them at the type level, which is their whole meaning (`#`-fields stay taught: runtime privacy brands). `this` reaches instance fields and methods (`this.count`, `this.step()`) — anything that lets `this` escape as a value (returning it, storing it, passing it) is taught (NS1056), so fluent chaining is out. Mutation follows exactly the array ownership rule: an instance your function creates with `new` mutates freely — direct field writes (`t.count = 1`, `t.count += 2`) and methods that write `this` — until it ESCAPES (returned, passed, stored, aliased — then NS1051), and parameters/model data never mutate (NS1001); methods that only read are callable on anything. Fields require type annotations; instances flow between functions, sit in arrays, and compare/narrow like records. The class TAIL teaches by name: `extends`/`super`/`abstract` (NS1055 — compose, or model variants as a `kind`-union), getters/setters/`#`-privates/`accessor`/class expressions (NS1056), mutable statics (NS1010), generic classes (NS1053), parameter properties (NS1008), `instanceof` (NS1041 — a `kind` field is the tag that exists). Class instances stay LOCAL values in v1: storing one in the Model tree is taught (NS1056) — keep records (interfaces) in the Model and construct the class where behavior is needed.
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), record payloads on `Cmd.request` results (results and errors arrive as one bytes payload; the record-shaped results are `Cmd.fetch`'s buffered `{ status, body }` arm, `Cmd.spawn`'s collect `{ code, output }` arm, and the fixed audio event arm), 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): `.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,29 +121,37 @@ export function update(model: Model, msg: Msg): Model | [Model, Cmd<Msg>] {
121
121
  }
122
122
  ```
123
123
 
124
- The command set (Cmd wire format v3):
124
+ The command set (Cmd wire format v4):
125
125
 
126
126
  - `Cmd.none` — no effects; returning a bare `Model` is sugar for `[model, Cmd.none]`.
127
- - `Cmd.persist()` — ask the host to persist the committed model.
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.
128
128
  - `Cmd.now("tick")` — request a timestamp; the runtime dispatches the named Msg arm with the time (ms) as its payload. The target arm must carry exactly one number field (`{ kind: "tick", at: number }`), and tsc checks that for you.
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
- - `Cmd.cancel(key)` — drop the in-flight keyed effect with that key, silently: a cancelled request, buffered named engine op (`readFile`/`writeFile`/`fetch`/`clipboardRead`), or armed delay dispatches NEITHER arm — its result is simply dropped. Live spawn and streaming-fetch 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.
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
133
  - `Cmd.batch([a, b])` — several commands from one dispatch, performed in order.
133
134
 
134
135
  ### The named engine ops
135
136
 
136
137
  These map directly onto the host's effect engine — files, HTTP, the clipboard, notifications, one-shot timers. Routed operations follow the `Cmd.request` rules (inline `{ key?, ok, err }`, string-literal arm names, arm shapes checked by tsc and taught by NS1027), with one difference from `request`: each op's `ok` arm has the op's OWN result shape. Keys follow the one keyed-effect rule everywhere: issuing a keyed op whose key is already in flight REPLACES the old one (the superseded op's result is dropped — no message), and `Cmd.cancel(key)` drops it silently. Every `err` arm carries exactly one `Uint8Array` field and receives a machine-readable reason; fire-and-forget writes and notifications have no routing arms. Paths, URLs, and bodies are bytes (`asciiBytes` for literals); dynamic values the engine refuses at runtime surface through the `err` arm, while compile-time-knowable bounds for routed operations stop the build (NS1030). Fire-and-forget operations fail closed under the host's validation instead.
137
138
 
139
+ - `Cmd.store.set(key, bytes, { key?, ok, err })` / `get` / `delete` / `scan` / `setMany` — capability-gated, engine-owned per-record storage. Declare `"store"` in `app.zon`; keys are UTF-8 strings up to 512 bytes and values are bytes up to 1 MiB. `setMany` applies 1–64 entries atomically. `get`'s ok bytes are `[1][value...]` for a hit and `[0]` for a miss, keeping an empty value distinct from absence. `scan(prefix, { limit?, after? }, route)` returns a little-endian length-prefixed page of key/value pairs plus an opaque next-key cursor; pass those next-key bytes back as `after` (a known literal cursor may be a string). The limit defaults to 100 and is capped at 256. Writes run off-loop in issue order, a synchronous read waits for earlier writes in the same command walk, every result journals, and failures route one of `io_failed`, `over_bound`, `bad_key`, `rejected`, or `busy`. The SQLite backing and app-data path are never part of the app-facing API.
140
+ - **Checked relational SQLite:** declare `"sqlite"` in `app.zon`. Add append-only, contiguous `src/schema/NNNN_name.sql` migrations (`STRICT` ordinary tables), commit the generated `src/schema/migrations.lock.json`, and add named statements in `src/queries.sql`: `-- name: notesInFolder`, `-- name: moveNote :exec`, or `-- name: notesInFolder :live`. `native check` applies the migrations and prepares every query with real SQLite, then generates flat `Cmd.q<Name>(params, route)` query constructors, typed `Cmd.q<Name>(params)` exec members composed only through `Cmd.qTx([...], route)`, `Sub.q<Name>(key, params, route)` for `:live`, row/param interfaces, and `decode<Name>Page`. TEXT/BLOB rows are `Uint8Array`; parameters inferred from TEXT columns wrap bytes automatically; raw or uninferred dynamic TEXT (for example an FTS `MATCH` term) uses `dbText(bytes)`. INTEGER is an exact `number` and generated decoders reject values outside ±(2^53−1). Live queries rerun after committed writes to their generated table dependency set, coalesced once per command frame. `native db new-migration <name>`, `status`, and `reset --yes` own development migration operations. Do not edit or reuse a shipped migration number.
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.
138
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.
139
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`.
140
144
  - `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).
141
145
  - `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.
142
146
  - `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`.
143
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.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
+ - `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
+ - `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>`.
151
+ - `Cmd.formatLocalTime(timestampMs, "date" | "time" | "datetime", { key?, ok, err })` — format epoch milliseconds (the same unit `Cmd.now` produces) through the host's current locale and local time zone; `ok` carries localized UTF-8 bytes. This is deliberately an effect rather than a pure helper: locale/timezone are ambient state, so the observed bytes journal and replay without consulting the replay machine. Err reasons are `invalid_request`, `unsupported`, and `failed`.
144
152
  - `Cmd.delay(key, ms, "fired")` — a keyed ONE-SHOT timer: dispatches the named arm once, `ms` from now, with the fire time (ms) as its single number payload (the same arm shape `Cmd.now` and `Sub.timer` target). Re-issuing a live delay key re-arms it from now — that is the debounce discipline (`Cmd.delay("autosave", 800, "save_now")` on every keystroke, one fire after the pause). `Cmd.cancel(key)` drops it silently. The interval is 1ms to one year; a literal outside that stops the build (NS1030).
145
153
 
146
- One honesty note on `Cmd.persist()`: it compiles and encodes, but no shipping host implements the persist verb yet, so the checker teaches NS1028 as a WARNING (never failing the build). Persist real state with `Cmd.writeFile` and load it back with `Cmd.readFile` from `initialModel`'s boot command — the pattern every real app uses.
154
+ Model persistence is capability-gated. Without `"persist"`, NS1028 warns that `Cmd.persist()` has no linked host binding; declaring the capability without issuing the command produces the inverse warning. Configure a monotonic schema version and three boot routes in `app.zon`: `.persist = .{ .version = 1, .restore = .{ .ok = "restored", .none = "fresh_boot", .err = "restore_failed" } }`. The ok/none routes name void Msg arms; err names a one-`Uint8Array`-field arm receiving `corrupt`, `version_unknown`, `migrate_failed`, `io_failed`, or `rejected` from boot restore or a later write. `native check` validates those route names and payloads, and `native dev --core` runs the same fence before starting its virtual host. Check stores the last accepted version/model-fingerprint pair under `.native/cache` and warns with NS1068 until a changed Model advances the version; runtime fingerprint checks remain the hard gate on cold checkouts. An older binary also refuses writes with `version_unknown` while a newer-schema snapshot is installed, preserving that snapshot across a rollback. A pure optional `migrate(snapshot: Uint8Array, fromVersion: number): Model` hook handles older versions (throw to fail). Version 1 snapshots the whole Model in a tagged, length-delimited engine format, so never put credentials in it. `Cmd.readFile`/`writeFile` are for user-visible files, exports, and blobs, not routine model storage.
147
155
 
148
156
  ### The streaming ops: fetch, spawn, audio, and channels
149
157
 
@@ -164,11 +172,42 @@ Four effect families deliver MANY results from one command — a keyed stream th
164
172
 
165
173
  ### The window verbs
166
174
 
167
- The menu-bar lifecycle pair — fire-and-forget, no routing and no result Msg (the window's own frame event carries the resulting state):
175
+ The menu-bar lifecycle verbs are fire-and-forget, with no result Msg (the window's own frame event carries visibility state):
168
176
 
169
177
  - `Cmd.showWindow(label)` — un-hide + activate the window with the declared label (a string literal — window labels are declarations, in `app.zon` or a `windows_fn` descriptor): the counterpart to a `close_policy = "hide"` close and the tray "Open" consequence; also restores a minimized window. An unknown label is a no-op.
178
+ - `Cmd.hideWindow(label)` — order a live window out without closing it; native identity and views remain, and `showWindow` is the inverse.
179
+ - `Cmd.setDockPresence(visible)` — on macOS, switch between a regular Dock/app-switcher app and accessory/headless behavior; unsupported hosts ignore it.
170
180
  - `Cmd.quitApp()` — the graceful terminate, and the tray "Quit" consequence: the host quits through the SAME shutdown path a last-window close takes, so the stop hook runs exactly once and a recording session seals its journal.
171
181
 
182
+ Launch at Login uses keyed routed effects: `Cmd.launchAtLoginStatus({ key?, ok, err })` queries `SMAppService.mainApp`, and `Cmd.setLaunchAtLogin(enabled, { key?, ok, err })` registers/unregisters it. The ok arm has one `Uint8Array` field containing UTF-8 `enabled`, `disabled`, `requires_approval`, or `not_found`; err carries `unsupported`, `failed`, or `invalid_request`. The result journals and replays exactly like `Cmd.request`. In `app.zon`, set `initially_hidden = true` on the startup window to prevent any launch flash, and `allows_fullscreen = false` on settings windows to retain resizing while disabling macOS native fullscreen.
183
+
184
+ ### Model-derived menu-bar status items
185
+
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
+
188
+ ```ts
189
+ import { asciiBytes, utf8Bytes } from "@native-sdk/core";
190
+ import { type StatusItemState } from "@native-sdk/core/events";
191
+
192
+ export function statusItem(model: Model): StatusItemState {
193
+ return {
194
+ iconPath: asciiBytes("assets/menu-bar.svg"),
195
+ tooltip: utf8Bytes("Player status"),
196
+ activationCommand: asciiBytes("app.refresh"),
197
+ alternateActivationCommand: asciiBytes("player.toggle"),
198
+ openCommand: asciiBytes("app.refresh"),
199
+ presentation: { title: model.playing ? utf8Bytes("MB PLAY") : utf8Bytes("MB"), width: 62, tone: "normal", iconOpacity: 1, monospaced: true },
200
+ items: [
201
+ { id: 1, label: utf8Bytes("Open"), command: asciiBytes("app.open"), separator: false, enabled: true, detail: asciiBytes(""), role: "command", key: asciiBytes(""), modifiers: { primary: false, command: false, control: false, option: false, shift: false } },
202
+ { id: 0, label: asciiBytes(""), command: asciiBytes(""), separator: true, enabled: false, detail: asciiBytes(""), role: "command", key: asciiBytes(""), modifiers: { primary: false, command: false, control: false, option: false, shift: false } },
203
+ { id: 2, label: model.playing ? utf8Bytes("Pause") : utf8Bytes("Play"), command: asciiBytes("player.toggle"), separator: false, enabled: true, detail: utf8Bytes("configured ✓"), role: "agent", key: asciiBytes(""), modifiers: { primary: false, command: false, control: false, option: false, shift: false } },
204
+ ],
205
+ };
206
+ }
207
+ ```
208
+
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
+
172
211
  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.
173
212
 
174
213
  ### The init command
@@ -210,17 +249,17 @@ Sub values follow the Cmd purity rule with their own home (NS1025): built inline
210
249
 
211
250
  Keep the Sub-vs-stream line straight: a Sub is DECLARATIVE — derived from the model, started and stopped by reconciliation, and the app never opens or closes one. The multi-result streams (`Cmd.fetch`'s response lines, `Cmd.spawn`'s stdout lines, `Cmd.audioPlay`'s events, `Cmd.channelOpen`'s posts, and audio capture chunks) are Cmd-INITIATED — imperative opens with a keyed lifecycle the app drives (`Cmd.cancel` for fetch/spawn, `Cmd.audioStop` for playback, `Cmd.channelClose` for external channels, and `Cmd.audioCaptureStop` for capture). If the effect should exist exactly while some model state holds, it wants a Sub shape; if the app decides when it starts and ends, it is a stream.
212
251
 
213
- One caveat for node-side pokes: the build resolves the `@native-sdk/core*` specifiers for you, but plain `node` does not know them, so quick behavioral checks under node work directly on cores with no SDK import, and on cores importing `Cmd`, `Sub`, `asciiBytes`, or the text engine only with a module mapping (or by copying the SDK module files next to the core and rewriting the specifiers). `native dev --core` already maps them.
252
+ One caveat for node-side pokes: the build resolves the `@native-sdk/core*` specifiers for you, but plain `node` does not know them, so quick behavioral checks under node work directly on cores with no SDK import, and on cores importing `Cmd`, `Sub`, `asciiBytes`, `utf8Bytes`, or the text engine only with a module mapping (or by copying the SDK module files next to the core and rewriting the specifiers). `native dev --core` already maps them.
214
253
 
215
254
  ## Splitting a core into modules
216
255
 
217
- `src/core.ts` is the ENTRY module; a core that outgrows it splits into more `.ts` files under `src/` (subdirectories included). The whole import graph still compiles as ONE native module - one flat namespace - and runs unchanged under node.
256
+ `src/core.ts` is the ENTRY module; a core that outgrows it splits into more `.ts` files under `src/` except `src/services/` (subdirectories included). The whole core import graph still compiles as ONE native module - one flat namespace - and runs unchanged under node. `src/services/` is a separate module class: importing it from the core, including with `import type`, is NS1065.
218
257
 
219
258
  - **Spell relative imports with the real filename**: `import { parsePs } from "./parsers.ts"` (node's loader resolves real files, not bare stems - a missing extension or a missing file is a taught NS1037).
220
- - **`src/` is the boundary**: `../` escapes and absolute paths are taught (NS1034); bare npm specifiers are taught (NS1035 - vendor the code under `src/` or make the import `import type`). Only `@native-sdk/core` (the intrinsic Cmd/Sub/asciiBytes surface) and the SDK library modules below carry runtime meaning from outside.
259
+ - **`src/` is the boundary**: `../` escapes and absolute paths are taught (NS1034); bare npm specifiers are taught (NS1035 - vendor the code under `src/` or make the import `import type`). Only `@native-sdk/core` (the intrinsic Cmd/Sub/asciiBytes/utf8Bytes surface) and the SDK library modules below carry runtime meaning from outside.
221
260
  - **Everything module-level is importable**: interfaces, literal-union aliases, discriminated unions, module `const` numbers and tables, and helper functions all cross files (renamed imports and `import * as ns` namespace aliases both work — the alias is dot-syntax over the same flat namespace, never a value of its own). Export lists and value re-exports work too: `export { helper, doneCount as remaining }` binds names over existing declarations, and `export { parsePs } from "./parsers.ts"` forwards another module's export by name (a renamed binding emits as a flat-namespace alias). Type names and EXPORTED value names must be unique across the core's files (NS1038 - declare once, import where used; renamed exports claim their new names in the same namespace); colliding PRIVATE helpers are fine (the compile uniques them per module).
222
261
  - **No runtime import cycles** (NS1036). `import type` back-edges are legal and idiomatic: a helper module type-imports `Model` from `./core.ts` while `core.ts` runtime-imports the helpers - that is the expected shape, not a smell.
223
- - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
262
+ - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), the model-derived launcher helpers (`themePack`/`statusItem`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
224
263
  - **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`, `AudioCaptureState`/`AudioCaptureSource`/`AudioCaptureEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
225
264
 
226
265
  The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor-ts` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/chatbot` (core.ts + api.ts — the JSON-over-bytes wire-format reference: request encoding and a targeted parse walk that returns `null` on anything malformed) in the SDK repo.
@@ -229,17 +268,18 @@ The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player
229
268
 
230
269
  `string` in a core is for literals, string-literal-union tags, and `===` comparisons — content equality, on tags and plain `string` values alike (`name === "app.add"` in a command mapper works and behaves identically under node and native). Dynamic, user-visible text lives in the Model as `Uint8Array` — indexing yields byte values, `.length` is byte length, `subarray` is a view and `slice` is a copy, and both resolve their bounds the JS way (negatives count from the end, out-of-range clamps, a crossed range is empty), identical under node and native. Observing a `string`'s code units (`.length`, `s[i]`, `.charCodeAt`) is banned (NS1004) because UTF-16 and UTF-8 would disagree, and `+` concatenation is banned (NS1018) because runtime string building needs a JS string heap the binary does not carry — build text with template literals into bytes instead.
231
270
 
232
- Turn literals and templates into bytes with the `asciiBytes` intrinsic from the SDK. The compiler recognizes the import by identity and folds every call at compile time — a literal argument becomes rodata, a template becomes per-dispatch arena bytes — and under node the same import runs as a plain function with the same result:
271
+ Turn user-visible literals and templates into UTF-8 bytes with `utf8Bytes`. Use `asciiBytes` only where ASCII is part of the value's contract: command names, keys, paths, URLs, protocol tokens, and empty fields. The compiler recognizes both imports by identity and folds every call at compile time — a literal argument becomes rodata, a template becomes per-dispatch arena bytes — and under node the same imports run as plain functions with the same result:
233
272
 
234
273
  ```ts
235
- import { asciiBytes } from "@native-sdk/core";
274
+ import { asciiBytes, utf8Bytes } from "@native-sdk/core";
236
275
  export type Bytes = Uint8Array;
237
276
 
238
- const label = asciiBytes(`${done} of ${total} done`); // arena bytes
239
- const seed = asciiBytes("Stretch"); // rodata, free to commit
277
+ const label = utf8Bytes(`${done} of ${total} done`); // arena UTF-8 bytes
278
+ const seed = utf8Bytes("Café…"); // UTF-8 rodata
279
+ const command = asciiBytes("app.refresh"); // guaranteed ASCII
240
280
  ```
241
281
 
242
- Arguments must be string literals or templates (the fold happens at compile time); dynamic text is already bytes, so there is nothing to bridge. Hand-rolling the old bridge shape (`function asciiBytes(s: string): Bytes { ... }`) no longer gets special treatment — its body observes code units and teaches NS1004.
282
+ Arguments must be string literals or templates (the fold happens at compile time); dynamic text is already bytes, so there is nothing to bridge. `utf8Bytes` matches `TextEncoder`, including U+FFFD for lone surrogates. A non-ASCII literal/template passed to `asciiBytes` is NS1064, and the node implementation throws `RangeError` for a dynamic misuse. Hand-rolling either bridge gets no special treatment — its body observes code units and teaches NS1004.
243
283
 
244
284
  ### The byte-text string methods
245
285
 
@@ -319,6 +359,7 @@ export type Msg = /* ... */ | { readonly kind: "library_scrolled"; readonly scro
319
359
  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.
320
360
 
321
361
  - **`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`.
322
363
  - **`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.
323
364
  - **`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"`).
324
365
  - **`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.
@@ -335,7 +376,7 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
335
376
  - **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.
336
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.
337
378
  - **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`.
338
- - **NS1004 text is not indexable.** No `.length`/`s[i]`/`.charCodeAt` on `string`. Bytes: `Uint8Array`; literals and templates become bytes through the `asciiBytes` intrinsic.
379
+ - **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`.
339
380
  - **NS1005 update is deterministic.** No `Date.now()`, `Math.random()`, or ambient IO. Take time and randomness as message payloads.
340
381
  - **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.
341
382
  - **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).
@@ -349,28 +390,32 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
349
390
  - **NS1015 exhaustive switch on message unions.** Cover every `kind`; no `default`.
350
391
  - **NS1016 integer and fractional numbers never share a slot.** A `number` that indexes memory (or otherwise must be an integer) cannot also receive fractional values; split the field or keep the whole flow integer. In practice this splits a core's numbers into two domains that never meet in one expression: integer values (indexes, ids, counts, anything compared against integer literals or formatted into template holes) and float values (division results, fractional literals). Deriving a float from an integer domain is done by parallel accumulation, not conversion — count in the integer domain and accumulate the float alongside (`pct += 1` next to `fraction += 0.01`); there is no float-to-integer conversion in v1 (`|0` demands an already-integer operand, and `Math.floor` of a float stays float), so integer division is spelled as a bounded whole-unit loop (`while (rest >= 1000) { rest -= 1000; seconds += 1; }`) — and when the dividend is unbounded (wall-clock milliseconds, byte totals), as binary long division, still integer end to end: `function intDiv(n, d) { let q = 0; let r = n; while (r >= d) { let step = d; let count = 1; while (step + step <= r) { step += step; count += count; } r -= step; q += count; } return q; }` (~2·log2(n/d) iterations; `%` of two integer-classed values stays integer, so `dayMs = at % 86400000` needs no loop at all). Primitive-array elements (`readonly number[]`) are always float-classed — wrap ids in single-field records when they must stay integers. One channel corollary: a shared helper parameter is ONE slot, so a helper that receives fractional values in one call cannot receive a proven-integer value in another (push the integer through its own inline site instead — the system-monitor port's process-count history does exactly this beside its fractional cpu/mem pushes).
351
392
  - **NS1017 commands are issued in update's return, not stored.** Build `Cmd` values inline in the returned `[model, cmd]` tuple; a command in the model, a message, a local, or a helper escapes the dispatch cycle.
352
- - **NS1018 no string concatenation.** `+` (or `+=`) with a string operand builds text at runtime; build bytes with `asciiBytes` on a template literal, or stitch `Uint8Array` buffers with `.set`.
393
+ - **NS1018 no string concatenation.** `+` (or `+=`) with a string operand builds text at runtime; build display bytes with `utf8Bytes` on a template literal, or stitch `Uint8Array` buffers with `.set`.
353
394
  - **NS1019 functions have fixed arity.** No parameter defaults (`= value`), rest parameters (`...xs`), `arguments`, or call spreads (`f(...xs)`); pass every argument explicitly (take and pass an array instead of a spread).
354
395
  - **NS1020 host command args are numbers or one bytes payload.** `Cmd.host` encodes f64 scalars or one bytes/record payload; a string smuggled through `as` has no encoding.
355
396
  - **NS1021 optional chains end in `??` or a value use.** `x?.y === null` would have to distinguish JS `undefined` (the chain short-circuited) from `null` (the field's value); normalize with `??` or guard the base first.
356
397
  - **NS1022 shared arrays sort by copy, not in place.** `.sort()` on a parameter or model array would mutate data that stays live for rendering and undo; sort a copy you own — `const copy = xs.slice(); copy.sort((a, b) => a - b);` — or inline with `.toSorted((a, b) => a - b)`.
357
398
  - **NS1023 sort comparators return a sign, not a boolean.** JS reads the comparator numerically: `true` coerces to 1 but `false` to 0, which claims equality and leaves pairs unsorted under node too. Return `a - b`, or explicit -1/0/1 branches.
358
- - **NS1024 model text is bytes.** A `string`-typed field anywhere in the Model tree has no commit representation (it would need a JS string heap). Type it `Uint8Array` and build values with `asciiBytes`, or use a string-literal union when the field holds one of a closed set of tags. Reported at the field's declaration.
399
+ - **NS1024 model text is bytes.** A `string`-typed field anywhere in the Model tree has no commit representation (it would need a JS string heap). Type it `Uint8Array` and build display values with `utf8Bytes`, or use a string-literal union when the field holds one of a closed set of tags. Reported at the field's declaration.
359
400
  - **NS1025 subscriptions are declared in subscriptions' return, not stored.** `Sub` values are inert descriptors the host reconciles after every commit; build them inline in `subscriptions(model)`'s return path — a Sub in the model, a message, a local, or another function escapes reconciliation.
360
401
  - **NS1026 host payloads are bytes or a flat scalar record.** `Cmd.host`/`Cmd.request` carry exactly one payload: a `Uint8Array`, or an inline record of number/boolean/`Uint8Array` fields. Nested records, other field types, or a payload mixed with extra arguments have no wire encoding.
361
402
  - **NS1027 effect results route to Msg arms by name.** Routing (`{ key?, ok, err }`) and timer targets are string-literal arm names with the payload shape the effect produces — one `Uint8Array` field for host results/errors, one number field for timer and delay fires, no fields for `writeFile`'s ok, one number plus one `Uint8Array` field for `fetch`'s ok. Callbacks and computed names cannot work: the runtime builds the result Msg from the arm's declared shape at build time.
362
- - **NS1028 Cmd.persist is not yet host-backed (warning).** The op compiles and stays on the wire, but no shipping host performs it — persist with `Cmd.writeFile` and boot-load with `Cmd.readFile` instead. The only non-fatal notice in the set.
403
+ - **NS1028 Cmd.persist and capability disagree (warning).** `Cmd.persist()` requires `"persist"` in `app.zon`; declaring the capability without issuing the command produces the inverse warning. The operation stays on the wire so the warning remains non-fatal, but only capability-enabled builds link the snapshot store.
404
+ - **NS1069 Cmd.store and capability disagree (warning).** Any `Cmd.store.*` operation requires `"store"` in `app.zon`; declaring the capability without issuing a store command produces the inverse warning. The SQLite engine is linked only for `"store"` or the relational `"sqlite"` capability, while the record-store host binding is installed only for `"store"`.
405
+ - **NS1070 relational SQLite and capability disagree (warning).** Raw `Cmd.db.*`, generated `Cmd.q<Name>`, and generated `Sub.q<Name>` require `"sqlite"`; declaring the capability without using any of them produces the inverse warning.
406
+ - **NS14xx SQL diagnostics come from the real schema.** Fix the migration or named statement at the reported `.sql` line. Migration versions are append-only and contiguous; ordinary generated-query tables are `STRICT`; raw query literals receive the non-fatal NS1420 escape-hatch nudge; identifier-like INTEGER fields receive NS1422's exact-number warning.
363
407
  - **NS1029 effect op arguments have a fixed shape.** Paths/URLs/bodies are bytes, `Cmd.fetch`'s spec is an inline object with a closed verb literal, a number-literal timeout, and an inline flat record of headers whose NAMES are compile-time ASCII and whose VALUES are string literals or runtime bytes (`Uint8Array`). The record's shape encodes at build time; a runtime header value rides its length-prefixed wire field at dispatch time exactly like `url`/`body` — but a smuggled string (a ternary of literals, a template) has no encoding: make it bytes.
364
408
  - **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.
365
409
  - **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.
366
410
  - **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.
367
- - **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. The generated wiring builds these host events structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
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.
368
412
  - **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.
369
413
  - **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.
370
414
  - **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).
371
415
  - **NS1037 an import names a real module file.** Spell relative specifiers with the `.ts` extension and point them at existing files; `@native-sdk/...` specifiers must name a shipped SDK module.
372
416
  - **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.
373
- - **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`.
417
+ - **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
+ - **NS1064 `asciiBytes` is ASCII-only.** Use `utf8Bytes` for user-visible or Unicode text; reserve `asciiBytes` for values whose contract guarantees 7-bit ASCII.
374
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`).
375
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`.
376
421
  - **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.
@@ -398,7 +443,7 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
398
443
  A complete core in the idiom — readonly interfaces, a tagged Msg, spread updates, map/filter, the bytes intrinsic, derived exports:
399
444
 
400
445
  ```ts
401
- import { asciiBytes } from "@native-sdk/core";
446
+ import { utf8Bytes } from "@native-sdk/core";
402
447
 
403
448
  export type Bytes = Uint8Array;
404
449
  export type Filter = "all" | "active" | "done";
@@ -424,7 +469,7 @@ export type Msg =
424
469
 
425
470
  export function initialModel(): Model {
426
471
  return {
427
- tasks: [{ id: 1, title: asciiBytes("Ship the core"), done: false }],
472
+ tasks: [{ id: 1, title: utf8Bytes("Ship the core"), done: false }],
428
473
  nextId: 2,
429
474
  filter: "all",
430
475
  draft: new Uint8Array(0),
@@ -469,7 +514,7 @@ export function update(model: Model, msg: Msg): Model {
469
514
 
470
515
  ## Running a core as an app
471
516
 
472
- 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 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; the adapter wires it as the stock theme's pack axis while system scheme/contrast/motion, manifest accent, and surface scale remain runtime-owned. The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
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.
473
518
 
474
519
  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:
475
520
 
@@ -489,12 +534,16 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
489
534
  });
490
535
  ```
491
536
 
492
- - `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 an exported `themePack(model)` 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`).
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`).
493
538
  - 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.
494
539
  - `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.
495
540
  - 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).
496
541
  - Record/replay, the automation verbs, and screenshot fingerprints work unchanged — the adapter rides the standard UiApp dispatch path.
497
542
 
543
+ ## Build targets
544
+
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.
546
+
498
547
  ## Checking your work
499
548
 
500
549
  Scaffolded apps carry an editor surface (`package.json`, `tsconfig.json`, and a CLI-managed `node_modules/@native-sdk/core` copy, npm-managed after the package is published): it exists so stock tsc/editors resolve `@native-sdk/core`, it is NEVER build truth (every `native` verb works with node_modules deleted; check/dev/build re-materialize it), and it is not a language marker — tree detection still keys on `src/core.ts` alone. Do not hand-edit or vendor files under `node_modules/`.
@@ -508,4 +557,4 @@ native check # inside an app
508
557
  node <sdk-repo>/packages/core/src/cli.ts src/core.ts
509
558
  ```
510
559
 
511
- Exit 0 means the module typechecked (real tsc semantics) and passed every subset rule — the exact pass every build runs before the external core compiler takes the graph. Because the subset is erasable TypeScript, `node` can import your core directly for quick behavioral checks (`node --input-type=module -e "..."` or a small `node --test` file) — the native build has the same semantics. If the core imports `@native-sdk/core` (for `Cmd` or `asciiBytes`), map that one specifier for node first: copy the SDK module file next to the core and rewrite the import, or run through a loader that resolves it.
560
+ Exit 0 means the module typechecked (real tsc semantics) and passed every subset rule — the exact pass every build runs before the external core compiler takes the graph. Because the subset is erasable TypeScript, `node` can import your core directly for quick behavioral checks (`node --input-type=module -e "..."` or a small `node --test` file) — the native build has the same semantics. If the core imports `@native-sdk/core` (for `Cmd`, `asciiBytes`, or `utf8Bytes`), map that one specifier for node first: copy the SDK module file next to the core and rewrite the import, or run through a loader that resolves it.
@@ -0,0 +1,126 @@
1
+ ---
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.
4
+ ---
5
+
6
+ # Author TypeScript services behind the effect boundary
7
+
8
+ Use `src/services/**/*.ts` for imperative work that needs ordinary TypeScript beyond the deterministic core subset: `fs`, `path`, `process`, `os`, `child_process`, `fetch`, regexes, JSON, `Map`/`Set`, `Date`, and classes supported by the pinned scriptc static tier. Both classes compile with the exact scriptc version in `packages/core/package.json`; neither enables `--dynamic` or ships a JavaScript engine. The exact verdict for every surface the compiler currently projects — with each status and refusal code, plus the manifest's explicit coverage limits — is `references/service-surface.md`, generated from the pinned compiler's own manifest; consult it rather than guessing compiler capability.
9
+
10
+ The class line is hard:
11
+
12
+ - `src/core.ts` and its imports outside `src/services/` retain NS1001–NS1064 and `deterministic: true`.
13
+ - The core never imports a service file, even type-only (NS1065). It imports generated command constructors from `@native-sdk/services`.
14
+ - A service may import shared, subset-legal declarations from the core class. Put every boundary record, enum, or union there so one declaration is authoritative on both sides.
15
+ - A service may import compiler-supported Node built-ins and exact packages declared by app.zon. Undeclared bare imports teach NS1066.
16
+
17
+ ## Typed operation surface
18
+
19
+ Every directly exported, non-default named function is an operation named `<module-basename>.<export>`. It must be synchronous, have a body, take zero or one explicitly annotated request, and explicitly return a contract-encodable result. Boundary data may use booleans, numbers, integer-class numbers, bytes, optionals, readonly slices, and named records/enums/kind-unions. Functions and behavior-bearing classes do not cross.
20
+
21
+ ```ts
22
+ // src/shared.ts — core-class file, imported by both classes
23
+ export type ParseRequest = {
24
+ readonly source: Uint8Array;
25
+ readonly caseSensitive: boolean;
26
+ };
27
+
28
+ export type ParseResult = {
29
+ readonly bytes: Uint8Array;
30
+ readonly matched: boolean;
31
+ };
32
+
33
+ // src/services/feeds.ts
34
+ import type { ParseRequest, ParseResult } from "../shared.ts";
35
+
36
+ export function parse(request: ParseRequest): ParseResult {
37
+ const text = new TextDecoder().decode(request.source);
38
+ const matched = request.caseSensitive ? /feed/.test(text) : /feed/i.test(text);
39
+ return { bytes: new TextEncoder().encode(JSON.stringify({ matched })), matched };
40
+ }
41
+ ```
42
+
43
+ `services.contract.json` carries the complete type table, operation names, exact compiler pin, source hashes, package facts, deadlines, streaming declarations, and `deterministic: false`. Generated host codecs, the Zig registry/result decoders, and the typed client consume that sidecar; none re-read source to infer a second truth.
44
+
45
+ Explicit boundary throws must be exactly inline `{ kind, message }` shapes with a string-valued message and must escape the operation. They arrive as UTF-8 JSON bytes on the error arm. Do not throw `new Error(...)` from the exported surface.
46
+
47
+ ## Call through the generated client
48
+
49
+ Import from `@native-sdk/services`; `native check` derives this virtual module, and build/dev stage the same projection without writing `src/services.gen.ts` into the author tree. The editor copy lives under ignored `node_modules/@native-sdk/services`.
50
+
51
+ ```ts
52
+ import { feedsParse } from "@native-sdk/services";
53
+ import type { ParseRequest, ParseResult } from "./shared.ts";
54
+
55
+ export type Msg =
56
+ | { readonly kind: "parse"; readonly request: ParseRequest }
57
+ | { readonly kind: "parsed"; readonly result: ParseResult }
58
+ | { readonly kind: "parse_failed"; readonly error: Uint8Array };
59
+
60
+ case "parse":
61
+ return [model, feedsParse(msg.request, {
62
+ key: "feed-parse",
63
+ ok: "parsed",
64
+ err: "parse_failed",
65
+ })];
66
+ ```
67
+
68
+ The generated route type proves that `ok` names the one Msg arm carrying exactly the declared result and `err` names a one-bytes-field arm. Raw `Cmd.request(name, bytes, route)` remains available as the low-level byte seam.
69
+
70
+ Keys share the engine effect-key space. A duplicate live service key rejects with `rejected` through `err`. Same-key requests run strictly FIFO on both carriers; the in-process carrier runs different keys in parallel across its pool instances. Terminal results and stream events are journaled; replay feeds the recorded events without starting a child process or a pool thread.
71
+
72
+ ## Hermetic npm
73
+
74
+ Resolve packages only with an explicit author action:
75
+
76
+ ```bash
77
+ native vendor . escape-string-regexp@5.0.0
78
+ ```
79
+
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
+
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.
83
+
84
+ ## Streaming, cancellation, and deadlines
85
+
86
+ A last `emit` capability declares a stream. Each typed chunk becomes canonical bytes on the existing external channel; the operation still returns one typed terminal result.
87
+
88
+ ```ts
89
+ import type { ServiceCancellation } from "@native-sdk/core";
90
+
91
+ export type ParseChunk = { readonly bytes: Uint8Array; readonly index: number };
92
+
93
+ /**
94
+ * @deadlineMs 5000
95
+ * @streamBuffer 8
96
+ */
97
+ export function parseLarge(
98
+ request: ParseRequest,
99
+ emit: (chunk: ParseChunk) => void,
100
+ cancellation: ServiceCancellation,
101
+ ): ParseResult {
102
+ for (let index = 0; index < request.source.length; index += 4096) {
103
+ cancellation.throwIfCancelled();
104
+ emit({ bytes: request.source.slice(index, index + 4096), index });
105
+ }
106
+ return parse(request);
107
+ }
108
+ ```
109
+
110
+ Import `ServiceCancellation` as a type from `@native-sdk/core`; it is legal only as the final capability parameter. The generated client route additionally requires `channelKey` and a channel-event Msg arm. `@streamBuffer` is a 1–64 in-flight contract cap (default 8); `@deadlineMs` is a 1–86400000 operation deadline. A terminal result closes the channel after its interim frames. `Cmd.cancel(key)` flips the token, closes a streaming channel, sends `cancelled` through `err`, and drops every later chunk. Deadline expiry flips the same token and sends JSON with `kind: "timeout"`. Poll `cancelled()` or call `throwIfCancelled()` at bounded intervals; a short cooperative grace period follows the token, and an operation that unwinds inside it keeps its instance (child process or pool instance) warm. Ignoring the token has a per-carrier hard edge: the child is killed and the next request starts a clean host; the in-process carrier abandons that instance's thread, routes the failure, and adds a fresh instance to the pool. The abandoned dispatch keeps its key reserved until it physically stops, so a same-key replacement cannot overlap its side effects. A detected runtime trap routes `kind: "service_trap"` and poisons only the instance it fired in.
111
+
112
+ ## Dev loop, authority, and current limits
113
+
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
+
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).
117
+
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
+
120
+ Current limits:
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;
123
+ - synchronous static-tier operations only—async services wait for the next compiler/runtime phase;
124
+ - no JavaScript engine or dynamic npm fallback;
125
+ - storage remains engine-owned effects, not a service-layer database shortcut;
126
+ - custom widgets, renderers, platform integration, and new engine capabilities remain Zig toolkit extensions.