> Documentation version: main. [HTML page](https://lukewilliamboswell.github.io/roc-native-windows/contributing.html)

<a id="contribute-to-the-platform"></a>

# Contribute to the platform

<a id="verify-native-windows"></a>

## Run the examples on Windows

Use this path to work on Win32 behaviour and test the app examples. To
write your own app, start at [Create and package a starter app](apps.md#get-started).

Install the x64 Windows builds of
[Blueprint 0.13.0](https://github.com/lukewilliamboswell/roc-blueprint/releases/tag/0.13.0)
and [Roc](https://github.com/roc-lang/nightlies/releases). Put
` blueprint.exe ` and ` roc.exe ` on your PowerShell path. Use a platform bundle
built from this checkout. In a scratch directory, run ` roc unbundle ` on
its raw ` HASH.tar.zst ` archive and copy the extracted ` targets/ ` folder
into ` platform/ ` in your checkout.

Run the suite from the repository root on Windows x64.

``` powershell
blueprint run test-native -- --target x64mingw
```

On Windows on Arm, run the x64 Blueprint and Roc binaries under Windows
emulation and pass ` --target arm64mingw ` to test native ARM64 executables.
The task runs Roc expects and the app’s specs where present.

For host changes on Windows, install Rustup and Zig 0.17.1. Run
` blueprint run build ` to rebuild the local link inputs and cross-build the
examples with the Roc dev backend.

Run ` blueprint run check ` before opening or updating a pull request. It
checks formatting, runs Clippy with warnings denied and the Cargo tests
with your native Rust toolchain, and checks every app and its expects with
Roc warnings treated as errors. It builds no hosts or app executables, so
it finishes in a few minutes. Install the linker for your toolchain if
Cargo needs it.
Run ` blueprint run bundle ` from a checkout with spaces in its path as part
of the first native contributor verification.

To develop one example interactively, open PowerShell at the repository root.

``` powershell
Set-Location examples/starter
roc ../../cli/windows.roc -- dev --target x64mingw
```

When verifying a release, use the same staged bundle on each architecture
and bootstrap a fresh project with an empty Roc package cache. Use an
interactive Windows desktop for capture. Check focus, DPI, Narrator,
file dialogs, networking and workers. Install, start, upgrade and uninstall
the MSI on a clean machine. Cross-builds and Wine compatibility checks
provide separate evidence from native Windows runs. Hosted CI builds both
hosts and the platform bundle once on Linux. Every later job builds and
tests the apps against that bundle, served on loopback, so they all use
the hosts a release would ship. CI runs the source checks on macOS,
cross-builds every app with the Roc dev backend on Linux, and checks the
Win32 behavior scenarios on Windows x64. Run the interactive desktop
checks below for Narrator, input focus, and display settings.
The workflow’s manual options run the external UI Automation probe and
native ARM64 scenarios. The macOS runner stages ARM64 apps and scenario
plans so the ARM64 runners can execute them directly. The ` standalone `
option stages a local release preview on macOS and verifies a Reading List
project generated from that preview on Windows x64 with a fresh Roc cache.

Run [the accessibility probe and desktop
walkthroughs](accessibility.md#verify-uia) before recording accessibility verification for a release.

<a id="windows-handoff"></a>

## Windows handoff checks

Use an interactive Windows desktop and record the OS build and the app
architecture with each result. Run the following with the bundled
targets from this checkout. Use ` arm64mingw ` for the native app tests on
Windows on Arm.

``` powershell
blueprint run test-native -- --target x64mingw
blueprint run test-accessibility -- -FreshStarter
```

Run the keyboard probes in ` tests/native-keyboard/ ` and repeat the
Reading List accessibility check on a project created by the standalone
release launcher. In ` windows.roc dev `, press Ctrl+R after a valid edit
and then after a syntax error. Verify that a valid edit starts a fresh
app instance and a failed build reopens the last successful executable.
Record cross-build, Wine, and native Windows results separately.

TODO: Native ARM64 verification needs a contributor with a Windows on Arm
machine. Until then, hosted CI runs the ARM64 scenarios, ARM64
accessibility, and standalone jobs only on manual dispatch, and a release
only installs and launches the ARM64 MSI. If you can help, run the commands
above with ` --target arm64mingw ` and report the results with the OS build.

Track the remaining accessibility work in
[Native control accessibility](https://github.com/lukewilliamboswell/roc-native-windows/issues/1)
and [Windows desktop accessibility baseline](https://github.com/lukewilliamboswell/roc-native-windows/issues/2).

| Development tasks | Implemented in the examples or host | Windows verification remaining |
| --- | --- | --- |
| 01–09, 11–15 | List and grid, native choices, edit, button, static labels, tabs, tree, toolbar, and progress and status bars. | Verify keyboard and IME interaction, native names, long labels and read-only text, overflow, and focus at high DPI. Check task-specific behavior against the existing specs and UI Automation probe. |
| 10, 21–22 | Localized date and time edits, date chooser, independent windows, and owned Notes dialog. | Verify two locales, a 24-hour time format, Narrator, Escape during IME, opener focus, and window activation across monitors. |
| 16–18 | App and command icons, HTTP taskbar progress, Start shortcut, and Explorer drop handling. | Install two apps with the same display name. Check Explorer and Start icons, ordinary upgrade and rollback after a failed upgrade, and uninstall. Check taskbar progress across an Explorer restart and drag a real file from Explorer into Files. |
| 19–20 | Clipboard text, file and folder pickers, and scoped file results. | Check copy into a second app, native picker cancellation, Unicode names, and Save As on Windows. Task 36 covers the authority checks. |
| 23–27 | Packaged and rendered rasters, Direct3D shader views, custom input, and native styling. | Compare hardware and WARP output and test device loss. Check real mouse capture, zoom and mixed DPI, contrast themes, and recording on desktop. |
| 28–32 | Control and grid semantics, keyboard focus, an external UI Automation probe, accessible graphics and slider, and polite status feedback. | Establish the desktop baseline for all seven examples. Inspect civil field label and validation relationships, the focused grid EDIT and its native text interface, decorative graphic visibility, and announcements during completion and cancellation. Check Narrator, Text size, contrast themes, and mixed-DPI focus. The previous hosted x64 probe failed in Workers with ` Expecting object to be local `. Use the updated probe’s operation and exception details to trace the failure if it recurs. |
| 33–34 | Private packaged fonts and app-owned themes. Standalone init carries the Reading List theme, its Crimson Text title font and its assets. | Verify the selected faces, glyph fallback, Text size and DPI across multiple windows. Check a generated app and an installed app with clean OS font settings. |
| 35 | Wall and monotonic clocks, time-zone and regional facts, and secure randomness with deterministic spec fixtures. | Check OS time-zone transitions, locale overrides, and CNG on both Windows architectures. |
| 36 | Retained file and directory handles at picker confirmation, exclusive Save As creation, rooted assets and settings, native Copy, dedicated scenario executables, and an exact HTTP origin allowlist. | Verify picker behavior, replacement, cancellation, and installed capabilities on both Windows architectures. HTTP uses a generic network failure for denial pending a dedicated result in Signals. |

Before publication, validate one exact set of versioned release assets.
Collect the native Windows run results, dependency license texts, SBOMs,
and provenance alongside the installer and bootstrap checks.

<a id="work-budgets"></a>

## Budget native work

The host counts the native work it does, so tests and specs can check
cost as well as behaviour. ` host/src/work.rs ` holds per-thread counters,
one per ` Op `, and ` host/src/native.rs ` wraps each costly Win32 call.
The wrappers count moves, invalidation and redraws, window text,
` EnableWindow ` (` enable-window `, for controls and single radios), the
` SendMessageW ` calls that repaint (` native::send_repaint `,
` native::set_font `), GDI brushes, fonts and deletions, DWM attributes,
theme changes, window properties, the scrollbar and text measurement.
The host’s window procedures count ` WM_PAINT `, ` WM_ERASEBKGND ` and
` WM_NCPAINT `. ` sync_node `, ` style_node `, ` layout ` and ` arrange ` count
their visits. Counting stays on in release builds because specs run the
app’s release host. Each count is one thread-local add. Only tests and
spec runs turn on tracing, which records each call’s window and the
shadow state that marks redundant writes.

` host/clippy.toml ` forbids the raw calls everywhere except ` native.rs `,
so ` blueprint run check ` fails on a new direct call. To cover another
call, add a wrapper to ` native.rs `, add a line to the ` ops! ` list in
` work.rs ` if it needs a new counter, and add the raw function to
` disallowed-methods `. Every ` Op ` name works in ` (expect-work ...) `
without a CLI change. Send a repaint-causing message through
` native::send_repaint `. Plain queries keep using ` SendMessageW `.

The collection controls send every message through ` native::send `,
which counts it as the ` Op ` the caller names. Each control’s own ` send `
helper picks the counter from the message:

| Counter | Counts |
| --- | --- |
| ` collection-scan ` | Nodes a list view, data grid, tree view, option list or tab strip visits or compares to find which of its items a change to its child lists replaced. A change that only edits items scans nothing. |
| ` list-read ` | Headings and cells a report projection reads from the wire tree. |
| ` list-insert `, ` list-delete `, ` list-set-text ` | ` LVM_INSERTITEMW `, ` LVM_DELETEITEM ` or ` LVM_DELETEALLITEMS `, and ` LVM_SETITEMTEXTW ` sent to a list view or data grid. |
| ` list-message ` | Any other list view or header message, such as a query, a state or column width change, a sort arrow (` HDM_GETITEMW ` and ` HDM_SETITEMW ` on the header), or a scroll. |
| ` choice-read ` | Options a combo box, list box, radio group or tab strip reads. A label or ` enabled ` change reads only that option or radio. |
| ` choice-insert `, ` choice-delete `, ` choice-set ` | Option and tab inserts, deletes and clears, and ` TCM_SETITEMW ` relabels. |
| ` choice-message ` | Any other option list or tab strip message, such as a selection query. |
| ` tree-read ` | Tree nodes a tree view reads from the wire tree. |
| ` tree-query `, ` tree-edit ` | ` TVM_GET* ` queries, and every other tree view message: inserts, deletes, renames, expansion and selection. |
| ` uia-snapshot ` | Cells copied into a new version of a data grid’s UI Automation table. |
| ` uia-lookup ` | Row lookups, hit-test probes and announcement cell comparisons in the data grid’s UI Automation provider. |
| ` uia-event ` | UI Automation events the data grid raises. |
| ` invalidate-rect ` | Partial invalidations through ` native::invalidate_rect `. While tracing, tests read the rectangles back with ` native::take_invalidated `. |

Budget tests live in ` host/src/test_host.rs `. ` TestHost::mount ` builds
a tree with ` wire_builder::Commands ` and mounts it in a hidden native
window. ` apply ` runs one batch and its incremental sync
(` SurfaceRegistry::sync_changed `) the way ` App::apply ` does and returns
its ` Work `. ` TestHost::reference ` mounts a host that syncs every batch
with the full reference walk instead, to measure what a change cost
before incremental sync. Assert the work with ` work.at_most(&[(Op::SetWindowPos, 0)]) `,
or check which windows the batch touched with ` touched(Op::Invalidate) `.
Set ` ROC_HOST_WORK_REPORT=1 ` to print each batch’s work.

``` rust
let mut host = TestHost::mount(LIGHT, |c| column(c, 30));
host.resync();
let work = host.apply(|c| {
    c.attr(14, "checked", Some("true"));
});
work.at_most(&[(Op::RepaintMessage, 1), (Op::SetWindowPos, 0)]);
```

A passing budget test is a tight budget. An ` #[ignore] `d budget test is an
open audit finding. Its reason names the finding, such as
` #[ignore = "reconcile-1: ..."] `, and its comment records the work measured
today. A fix removes the ` #[ignore] `, and the test then guards it. Run the
open findings with
` cargo test --manifest-path host/Cargo.toml -- --ignored test_host `.

Some counters measure host work beyond Win32 calls:

| Counter | Counts |
| --- | --- |
| ` surface-sync ` | native syncs after one or more turns, incremental or full |
| ` pump-tick ` | pump polls; an idle app makes none |
| ` font-verify ` | full-file checks of a packaged font against the selected face |
| ` icon-decode ` | ` .ico ` asset reads and decodes for buttons and toolbars |
| ` class-name ` | window class names read by the paint and notify paths |
| ` system-query ` | reads of high contrast, the DWM colour, the locale layout and dark mode |
| ` roc-turn ` | Roc turns: the mount and each delivered event |
| ` command-bytes ` | bytes of view commands the turns returned |
| ` raster-queued `, ` raster-dropped ` | image jobs queued for the image worker, and pending jobs a newer input for the same image replaced |
| ` raster-backlog ` | image jobs queued while 64 jobs or 64 MiB were already pending |

Native tests that need an app use ` window::turn_tests `. They build an
` App ` whose script answers each turn in place of Roc, so they can queue
effect answers and measure one pump tick.

In a spec, ` (expect-work ...) ` asserts the previous step’s work. See
[Assert native work](spec-runner.md#expect-work). Choose budgets
that hold now and would fail on the regression they guard. Check that
by reverting the fix locally. With ` ROC_HOST_WORK_REPORT=1 `, each
` expect-work ` step also appends a JSON line to ` work.txt ` in the spec’s
artifacts directory, since the CLI keeps a passing spec’s output to
itself. The line names the step and holds every counter, the span
times, the GDI and USER handle counts before and after the step and the
peak working set. See [Read the work report](spec-runner.md#work-report)
for the fields. Set ` ROC_WINDOWS_FULL_SYNC=1 ` as well to measure the
same steps with the full reference walk.

Sync work is bounded by the change, not the window, so a budget can
name visits. ` sync-visit ` and ` style-visit ` count the nodes a sync
visited and restyled, and ` layout-visit ` the nodes layout measured or
placed. An unchanged batch visits nothing. A one-leaf change visits one
node, and lays the window out only when the leaf’s size can change.
` one_leaf_change_does_constant_work ` checks that with ` assert_scales ` at
100, 200 and 400 controls. Only a new palette restyles every control.

<a id="time-the-host"></a>

### Time the host’s phases

` work.rs ` also times the host’s phases with ` QueryPerformanceCounter `.
Hold a guard for the phase, ` let _span = work::span(Span::Sync); `, and
its elapsed ticks and one entry are added to a per-thread total when it
drops. The spans are:

| Span | Times |
| --- | --- |
| ` turn ` | the Roc engine’s mount and each event, in ` App::start ` and ` App::deliver ` |
| ` apply ` | ` App::apply `, which reads the turn’s commands and, unless the turn is coalesced, syncs |
| ` sync ` | ` App::flush `, one native sync of one or more turns |
| ` layout ` | ` Layout::place_root ` and ` measure_root ` (not yet guarded, so 0 until ` layout.rs ` holds the span) |
| ` arrange ` | ` Surface::place `, which lays a window out and moves its controls (not yet guarded, so 0 until ` view.rs ` holds the span) |
| ` paint ` | dispatching a ` WM_PAINT `, in the message loop and the spec runner |
| ` pump ` | ` App::poll `, one pump tick |

Spans nest and each total is inclusive: ` pump ` holds the tick’s turns,
applies and syncs, ` sync ` holds layout and arrange, and ` arrange ` holds
its layout. A span that re-enters itself is timed once. Like the
counters, the totals are thread-local, allocate nothing and stay on in
release builds. ` QueryPerformanceCounter ` reads the invariant TSC in user
mode, so a span is two reads and a few adds: ` spans_cost_little `
measures about 30 ns a span in a release test build, against a step’s
handful of spans and the microseconds each Win32 call costs. Spec runs
report span times in ` work.txt `. They are machine-dependent, so the
benchmark reports them and never gates on them.

<a id="budget-sentry"></a>

### Watch a running app’s budget

The budget sentry watches every native sync of a running app and logs
any whose work is out of proportion to its change. It is on in dev
builds (` windows.roc dev `, whose executable carries the development
marker). A shipped app never runs it, and spec runs leave it off
because specs assert their own budgets. Set ` ROC_HOST_BUDGET_SENTRY=0 `
to silence it, or ` =1 ` to turn it on for any build. Off, it costs one
branch per sync. On, it copies the counters before and after each sync.

It uses the sync’s change set from ` Tree::take_changes `, the nodes
created or changed and the parents whose children changed, and names a
sync when one of these holds:

- A counter of native or tree work exceeds 16 per changed node and 256
  in all (` work::sentry::PER_NODE ` and ` FLOOR `). Polls, system queries,
  paints, Roc turns and command bytes are not judged.

- ` RedrawWindow ` with ` RDW_ALLCHILDREN ` (` redraw-all `) ran on a sync that
  changed no window’s ` appearance ` and opened or closed no window.

- The sync took longer than a 60 Hz frame, 16 ms.


The mount is never judged. The log goes to standard error, at most one
line a second. The next line says how many it held back. A line names
the turns and command bytes since the last sync, the findings, up to six
changed nodes by tag and child-index path, the time in the sync and in
its layout, arrange and paint, and the sync’s work:

```
roc-native-windows: budget: a sync after 1 turn (10 command bytes) changed 1 node and took 42.3 ms: set-window-pos=420 (420 per changed node), plan-visit=842 (842 per changed node), sync took 42.3 ms (frame budget 16 ms); changed: ui-vstack [0, 0, 0]; timing: turns 0.0 ms, sync 42.3 ms (layout 0.0 ms, arrange 0.0 ms, paint 0.0 ms); work: set-window-pos=420 sync-visit=1 layout-visit=2 arrange=1 surface-sync=1 plan-visit=842
```

That line comes from ` budget_sentry_names_a_disproportionate_turn_only `
in ` window.rs `, which moves one text to the front of a 420-row column.
The test also checks that a one-text change logs nothing. A line is a
lead, not a failure. Reproduce the turn in a spec or a ` test_host `
budget test, and fix the host or record the budget there.

<a id="property-tests"></a>

## Check layout against its reference model

` host/src/layout.rs ` lays out a window without one. ` Source ` describes
each node (a stack, panel, tabs, drop target or leaf control) and
` Measure ` answers text and control metrics, so tests run the real layout
with a fixed-pitch fake measurer on any OS. ` view.rs ` implements both
over the wire tree, the mounted controls and an HDC. Layout memoises each
node’s measurement for the whole arrange, and ` TextCache ` keeps text
measurements across arranges, keyed by node, text, font and width. After
an incremental sync, ` layout::Memo ` keeps node measurements and placements
across arranges too, less those of the changed nodes and their ancestors,
and ` Layout::place_changes ` lists only the placements that changed, each
with the placement before it in tab order.

` host/src/layout/reference.rs ` keeps the original naive algorithm as the
specification. The property test in ` host/src/layout/tests.rs ` builds
random trees of rows, columns, panels, tabs, drop targets, texts and
controls, with random captions, labels, padding, spacing, ` stack-below `
widths, maximum widths and DPIs. It checks that:

- the optimised layout produces exactly the reference’s ` Placement `
  vector and size, and measuring alone gives the same size;

- a cached measurer gives the same result, and measures nothing when warm;


- row and column children are spaced by exactly the stack’s spacing;


- every child sits inside its container’s content box, which fits the
  container’s maximum width;

- a row narrower than its ` stack-below ` width stacks as a column.


The containment check skips trees where some container is given less
width than its padding. The original algorithm never clamps padding, so
such a container overflows its parent; the test reports how many trees
it checked.

Run it, and the linear-scaling tests next to it, with
` cargo test --manifest-path host/Cargo.toml layout `. The in-tree
generator in ` host/src/oracle/rng.rs ` is SplitMix64 seeded from
` ROC_HOST_SEED ` (decimal or ` 0x ` hex) or a fixed default, so every run
checks the same 2,000 trees. Set ` ROC_HOST_ITERS ` to check more, and
` ROC_HOST_WORK_REPORT=1 ` with ` -- --nocapture ` to print the coverage:

``` powershell
$env:ROC_HOST_SEED = "0x1234"; $env:ROC_HOST_ITERS = "200000"
cargo test --manifest-path host/Cargo.toml --release layout::tests -- --nocapture
```

A failure shrinks the tree with ` ddmin ` (` host/src/oracle/shrink.rs `) and
prints the run’s seed, the failing case’s own seed, the width and DPI and
the shrunk tree. Set ` ROC_HOST_SEED ` to the printed run seed to replay it.
To keep a failure as a regression test, copy the shrunk specs into a
` #[test] ` next to ` nested_rows_layout_is_linear `.

Scrolling keeps the layout and moves every child with one
` ScrollWindowEx `. A control whose top lies beyond the 16-bit range
` SetWindowPos ` accepts is parked at the clamp, and a scroll that brings it
within reach moves it to its place;
` content_taller_than_the_native_limit_stays_in_place ` checks that at about
100,000 pixels. ` scrolled_pixels_match_a_full_repaint ` in
` host/src/test_host.rs ` compares the scrolled screen pixels with a full
repaint. It needs a visible, unobscured window on an interactive
desktop, so it is ignored by default; run it with
` cargo test scrolled_pixels_match_a_full_repaint -- --ignored `.

A change to layout must keep the reference model unchanged and pass the
property test. A deliberate change to layout behaviour changes the
reference in the same commit, and the example specs and recordings show
the change.

<a id="host-oracles"></a>

## Check the host against oracles

The host’s pure code is checked against simpler references, so a fix or
an optimisation cannot quietly change behaviour. The oracles live in
` host/src/oracle/ ` and run with ` cargo test `. They need no extra crates, and
share the generator and shrinker described in
[Check layout against its reference model](#property-tests).

- **The wire tree model**: ` oracle/model.rs ` holds ` ModelTree `, a naive reference for ` wire::Tree `.
  It keeps nodes in a ` Vec `, finds ids by scanning, clones itself to make
  each command atomic and finds what changed by comparing before and after.
  The property test ` tree_matches_the_reference_model ` generates random
  edit sequences with ` wire_builder::Commands `. They cover templates and
  instantiation, elements, text and comments, attributes, properties,
  listeners, row holes, moves, removal and clearing. About one edit in ten is
  invalid and must be refused. After every edit the test checks four things.
  The tree and the model must agree on whether the edit applied. The tree
  must pass ` Tree::check_invariants `. The two ` canonical() ` forms must be
  equal. The recorded ` Tree::changes ` must match the model’s. A failure is
  shrunk with ddmin and printed with its seed.

- **Tree invariants**: ` Tree::check_invariants ` asserts the following:

  - Parent and child links agree, and each child is listed once.


  - Every node is reachable from the root exactly once, so there are no
    cycles and no orphaned keys.

  - Wire ids and the nodes that carry them form a bijection.


  - Every ref targets a live node, and that node’s reverse index lists the
    ref.

  - Each row hole names either a removed node or a node inside its row.


  - The tag and listener indices are exact.


  - Recorded changes name only live nodes.

    A command that fails leaves the tree exactly as it was.

- **Change recording**: ` Tree::changes ` (taken with ` take_changes `) records the nodes created or
  changed in value, and the parents whose children changed. Setting a value
  to what it already is records nothing. ` Tree::revision ` and
  ` structure_revision ` let callers cache what they read, and
  ` Node::subtree_revision ` lets a collection skip an unchanged subtree.
  The host takes the changes once per sync, so coalesced turns sync with
  their union.

  ` Surface::sync_changed ` groups the changes by the list view, data grid,
  tree view or option list that reads them and hands each its share as a
  ` list_view::Delta `. The collection reads again only the rows, cells,
  nodes or options the delta names. When one of its child lists changed,
  it compares its mounted items with the new ones from both ends and reads
  only the range between, then plans that range with the same minimal
  reorder plans as a full read. A data grid patches its UI Automation table
  with only the cells whose value, feedback or editability changed, and
  announces only those. The full walk, ` Surface::sync `, gives a collection
  no delta, so it reads everything, which is what the incremental path must
  match.

- **Incremental sync**: ` Surface::sync_changed ` syncs only what ` Tree::changes ` names, and
  ` Surface::sync ` is the full walk it must match (see
  [Incremental sync](architecture.md#incremental-sync)).
  ` host/src/sync_differential.rs ` checks them against each other. It
  mounts the same random UI in two hidden windows, one synced
  incrementally and one with the full walk, and applies random batches of
  edits to both: inserted subtrees of stacks, panels, tab pages, texts,
  buttons, checkboxes, switches, sliders, fields, progress bars, option
  lists and list views; removals and moves; attributes that change
  content, size, enabled state and colour; texts; and appearance changes.
  After every batch the two windows' ` NativeSnapshot `s and the placements
  of their last arrange must be equal. A batch that fails must fail in
  both, which ends the case as it would end the app. A failure shrinks
  with ddmin and prints its seed and case. ` ROC_HOST_ITERS ` sets the
  number of batches (default 300). ` ROC_WINDOWS_FULL_SYNC=1 ` makes a real
  app use the full walk, to tell an incremental sync bug from an app bug.

  When you change what a control reads during sync, keep the two in step:
  anything ` Nodes::item ` or ` flex ` reads is part of a node’s layout
  fingerprint, and state that changes outside a sync must drop that
  node’s fingerprint, as ` refresh_grid ` and the civil field commit do.
  ` resumed_memo_matches_a_fresh_layout ` in ` host/src/layout/tests.rs `
  checks that a layout memo kept across arranges, with the changed node
  and its ancestors invalidated, places exactly as a fresh layout, and that
  its changes, applied in order to the controls the last layout left, give
  the fresh layout’s order and places. The differential test also mounts
  content up to about 120,000 pixels tall and scrolls it, past the 16-bit
  child window coordinates.

- **Fuzz smoke**: ` oracle/smoke.rs ` feeds real, generated and mutated command streams
  through ` Reader ` and ` Tree::command `. The mutations are bit flips,
  overwrites, inserts, deletes, corrupt length words, truncation and
  splices. A command must apply or return an error. It must never panic or
  read past its input. The tree must pass its invariants after every
  command. The seeds are in ` host/fuzz/corpus/wire_commands/ `. To refresh
  them, run the example specs with ` ROC_HOST_WIRE_CORPUS ` set to an absolute
  directory. The host then writes every view command it applies to
  ` wire-<pid>.bin ` there. Copy the small files into the corpus.
  ` recorded_streams_apply_in_full ` checks that each one still applies
  without error.

- **Scaling**: ` oracle/scale.rs ` provides ` assert_scales(what, n, max_exponent, work) `.
  It counts operations at n, 2n and 4n, never time, and fails when the
  log-log slope exceeds the limit: ` LINEAR ` (1.15) or ` CONSTANT ` (0.1). The
  wire tree counts ` tree-scan ` (child lookups and ref sweeps) and
  ` tree-shift ` (siblings moved to make or close a gap). A node’s children
  are a linked list, so a child lookup is one step and inserting, moving
  and removing a child moves no siblings: ` tree-shift ` stays 0.
  ` WindowPlan::visit ` counts ` plan-visit `, and the raster bridge counts
  ` bridge-visit `. Write a scaling test before a complexity fix, watch it
  fail, then fix.

- **Seeds and iterations**: Every random test prints ` ROC_HOST_SEED=0x... ` and the case number when it
  fails. Replay a failure with that seed, for example
  ` ROC_HOST_SEED=0x1234 cargo test --manifest-path host/Cargo.toml tree_matches `, with the printed seed in place of ` 0x1234 `.
  ` ROC_HOST_ITERS ` sets the number of cases. The defaults are 300 model and
  plan cases and 2,000 fuzz inputs. Before a change to ` wire.rs `, ` windows.rs `
  or the sync in ` view.rs `, run once with ` ROC_HOST_ITERS=20000 `. Set
  ` ROC_HOST_WORK_REPORT=1 ` to print the scaling points and the generators'
  statistics.

<a id="verify-specs-against-a-fresh-mount"></a>

### Verify specs against a fresh mount

With ` ROC_WINDOWS_SPEC_VERIFY=fresh `, the spec runner checks every step
against a fresh mount. After each step and its pump, it mounts the app’s
current tree fresh in hidden twin windows. The twins get the same client
size and the same decoded images. The runner then compares a
` NativeSnapshot ` of each synced window with its twin
(` host/src/native_snapshot.rs `). Per view, the snapshot holds the class,
text, rect in the parent’s client area, visibility, enabled state, button
check state, slider position and the colours the view was styled with. Per parent, it holds the z-order of the
mounted children. Views are keyed by tree key. The verify work is left out
of ` expect-work ` counts, and the twin leaves the synced window’s text
measurement cache intact, so a step after it measures what it would have.

``` powershell
$env:ROC_WINDOWS_SPEC_VERIFY = "fresh"
roc ../../cli/windows.roc -- test --target x64mingw
```

` blueprint run test-native-verify ` (` scripts/build.roc -- test-native-verify `)
runs every example’s specs this way, and CI runs it after the native
scenarios.

A mismatch fails the step and lists every difference, with both windows'
client size and scroll state. It is a real bug unless it comes from state
the tree does not hold. The snapshot leaves that state out:

- The vertical scroll offset is added back to top-level rects.


- Hidden controls have no rect.


- An edit’s text counts only while the tree controls it (` value `), it
  does not have focus, and it is not a civil date or time field holding
  the user’s draft.

- Selection, dropdown, expansion and focus state are not recorded.


If a difference is state like this, add it to that list in
` native_snapshot.rs `. Otherwise fix the incremental path.

<a id="benchmark-the-host"></a>

## Benchmark the host

` blueprint run bench ` measures how the host’s work grows as an app gets
bigger. It runs real apps through the spec runner and counts work, so its
results do not depend on the machine. It needs a Windows desktop session
and the x64 host in ` platform/targets/x64mingw `.

``` powershell
blueprint run bench
blueprint run bench -- --large --no-examples
blueprint run bench -- --only list --sizes 1000,2000,4000
```

The quick default runs every scenario at three small sizes, three times
each, and then samples the examples. It takes under two minutes. ` --large `
runs once at sizes up to 100,000 list rows and takes much longer.
` --repeat N ` sets the repeats, ` --no-examples ` skips the examples and
` --examples-only ` skips the sweep.

` examples/bench ` is one app with a scenario per dimension. Its boot
storage picks the scenario and the size, and shared buttons change one
row, a tenth of the rows or every row, reorder, filter, unmount and
remount, switch the appearance and advance a shader. Each
` tests/specs/*.scm ` file is a scenario at a small size and passes as an
ordinary spec. The harness rewrites the spec’s ` bench-size ` setup and
drops its assertions. It adds an ` (expect-work (sync-visit >= 0)) ` probe
after every step and runs the plan with ` ROC_HOST_WORK_REPORT=1 `, so each
probe appends a JSON line for that step to ` work.txt `
([Read the work report](spec-runner.md#work-report)). Each line
names the step it measured by line, column and command, so the harness
matches a line to its step by that identity, not by its position, and a
missing line cannot shift the rest onto the wrong steps. A step followed
by ` await-work ` shares its probe with the wait. ` mount ` is the work from
startup to the first step. The harness still reads the counter-only
lines of an older host by position.

The harness writes three reports to ` build/bench/ `:

- **` results.json `**: every counter of every step at every size, each step’s
  span times (` spans_us `), GDI and USER handles before and after (` gdi `,
  ` user `) and peak working set, the run times, the fits and the example
  samples.

- **` summary.md `**: regressions and handle leaks, flagged growth, run times,
  the time per span and the handle deltas at each scenario’s largest size,
  and every fit.

- **` examples.md `**: each example spec step ranked by its total work, and the
  three most expensive steps for each counter.

Each fit is the least-squares slope of log(count + 1) against log(size)
for one scenario, step and counter. A slope near 0 is constant work and
near 1 is linear work. Above 1.15 is flagged ` superlinear `. A step whose
change has a fixed size, such as ` click Change one `, is flagged
` nonconstant ` above 0.15. Pump ticks count timed polls and are never
flagged or gated. Wall time and span times are advisory: they keep the
fastest of the repeats and never gate.

Handle leaks gate at every size, quick or large, without a baseline. A
round trip in ` round_trips `, such as ` click Toggle ` then ` click Toggle #2 `
in churn, must end with the GDI and USER handle counts it started with.
A steady step in ` steady_steps `, one that changes only text and values
such as ` click Change one `, must end with the counts it began with. Both
allow 2 handles plus 1% for a caret or a tooltip. Add a pair to
` round_trips ` when a scenario gains a step that undoes another.

To add a scenario, add a case to ` Bench.Scenario ` and its view in
` examples/bench/src/main.roc `, and add ` tests/specs/NAME.scm ` with
` (setup (local-storage "bench-scenario" "NAME") (local-storage "bench-size" "N")) `.
Add its quick and large sizes to ` sizes_for ` in ` scripts/bench.roc `, and
add a step to ` constant_steps ` if its change has a fixed size. Keep a
process under 10,000 USER handles: every control is its own window.

` bench/baseline.json ` holds the fits of a quick run. Each run gates on
it. A count that rises more than 10% plus two at any size fails, and so
does a whole growth order that rises. Work on a step that had none also
fails. A run reports the least count of its repeats, and the baseline
keeps the greatest it saw, so worker timing does not fail the gate. A
fall in growth order prints ` IMPROVED `. Flags in the baseline record
known-bad growth.

Change the baseline only on purpose, in the commit that changes the work.
Run ` blueprint run bench -- --update-baseline `, which repeats each
scenario six times, and review the diff. One fit is one line. A counter
the baseline has never recorded, such as a newly added ` Op `, prints
` NEW COUNTER ` and is not gated until an update records it, so a new
counter needs no baseline change in the commit that adds it. The
baseline format is unchanged by the JSON report.

The benchmark runs locally only. CI does not run it, and long fuzz
or oracle campaigns such as ` ROC_HOST_ITERS=20000 ` are local too.

` test --stage-native ` also writes demo plans to ` demo-plans/ ` beside
` plans/ `, so the harness can sample demos. Demos run without their ` wait `
steps.

<a id="windows-diagnostics"></a>

## Diagnose a local Windows build

Use the example’s ` build/x64mingw/ ` or ` build/arm64mingw/ ` executable from
the commit under test. Save traces and local tools under the ignored
repository-root ` build/windows-diagnostics/ ` directory.

- For a UI Automation failure, open the example and use Live Inspect in
  [Accessibility Insights for Windows](https://accessibilityinsights.io/downloads/).
  Inspect the control’s name, relationships, patterns, and events around the
  failing action. Compare them with the out-of-process probe and the
  [keyboard and Narrator walkthrough](accessibility.md#verify-uia).

- For an automated accessibility scan, extract the portable CLI ZIP from
  the [Axe.Windows
  release](https://github.com/microsoft/axe-windows/releases/tag/v2.4.2). Open the example on the interactive desktop at the same privilege
  level as the scanner. From the repository root, run the following with the
  extracted CLI on ` PATH ` or use its full path. Replace ` 1234 ` with the app’s PID.

  ``` powershell
  New-Item -ItemType Directory -Force build/windows-diagnostics/axe-windows
  AxeWindowsCLI.exe --processid 1234 --outputdirectory build/windows-diagnostics/axe-windows --alwayssavetestfile
  ```

  Each scan checks the app’s current UI Automation tree. Use the native probe and
  desktop walkthrough for workflow transitions, keyboard focus, and Narrator
  feedback. Open the ` .a11ytest ` report in Accessibility Insights for Windows
  to inspect individual findings.

- For a slow or unresponsive app, use ` wpr -profiles ` to find a recording
  profile. From an elevated PowerShell, check ` wpr -status `, then start a CPU
  recording with ` wpr -start CPU -filemode `. Reproduce the action once and
  use ` wpr -stop build/windows-diagnostics/workers.etl `. Open the trace in
  WPA and filter to the app’s process. WPA is available through the
  [Windows Performance Toolkit](https://learn.microsoft.com/en-us/windows-hardware/test/wpt/).

- For suspected Win32 heap, handle, or lock misuse, use the Windows SDK’s
  [Application Verifier](https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/application-verifier-testing-applications).
  Give a copy of the app a unique executable name, enable its Basics tests,
  and launch it under a debugger. Delete the settings for that name when
  finished with ` appverif -delete settings -for workers-verifier.exe `.

- For image metadata and hashes, extract
  [Sigcheck](https://learn.microsoft.com/sysinternals/downloads/sigcheck).
  From the repository root, run ` sigcheck64 -a -h -r examples/workers/build/x64mingw/workers.exe `
  with the tool on ` PATH `, or use its extracted path. Use ` sigcheck64a ` on
  Windows on Arm. Compare the SHA-256 with the executable being debugged.

- For file, registry, and DLL activity, extract
  [Process Monitor](https://learn.microsoft.com/sysinternals/downloads/procmon).
  Stop capture while setting an include filter on the executable’s process
  name. Start capture, reproduce the operation, then stop and save the events
  as a ` .PML ` file. Check the filtered trace before sharing it because paths
  and process details can contain local information.

<a id="review-host-authority"></a>

## Review each feature’s security model

Include a security discussion in every feature design or change
description. Use [the authority
contract](architecture.md#capability-boundary) and describe the feature’s hazards, the controls that address
them, and what remains outside those controls. For work that leaves the
security boundary as it is, a brief explanation is enough.

- Name the user workflow, what the app author makes available, and
  what the user authorizes. Identify sensitive data and operations,
  who can supply their inputs, and what could go wrong. Consider
  untrusted data, dependencies, resource replacement, and exhaustion
  where relevant.

- Show the usual call with its safe defaults. For an unattended grant,
  explain why user designation and app-scoped facilities do not cover
  the workflow. State the target, allowed operations, who can receive
  the authority, its limits and lifetime, and when it is released.
  For a retained grant, describe revocation and what can reopen it.

- List the typed outcomes the caller can act on and explain any
  structured payload. Show how the caller handles denial or refusal
  without interpreting diagnostic text.

- Trace the controls through the actual host paths, including raw
  requests, simulation, redirects or file replacements, and
  cancellation where applicable. Verify that denial leaves the
  target untouched and consumes no in-flight slot. Check that
  read-only access stays read-only across the ABI and in workers.

- Exercise the ordinary path with its defaults and the failure paths
  that establish the controls. Verify desktop interactions on native
  Windows. Use specs for repeatable policy and result behavior.

Put lasting explanations of hazards, controls, and security limits
in the relevant manual chapter. Keep API doc comments focused on the
contract callers need at the call site, including authority, defaults,
and result tags. Link to the manual for the rationale and examples.

<a id="record-example-gallery"></a>

## Refresh the README recordings

From an example’s directory, record its gallery scenario on a Windows desktop.

``` powershell
roc ../../cli/windows.roc -- record tests/specs/demo.scm --format gif
```

The command prints its output directory under ` build/specs/ `. Copy the
resulting ` demo.gif ` to ` docs/images/<example>.gif ` at the repository root.
Keep the example’s scenario under ` tests/specs/ ` so the recording can be
repeated.

The HTTP demo uses a local response. Run this from ` examples/http ` in a
separate terminal while recording that example.

``` powershell
roc ../../scripts/serve.roc -- tests/fixtures --port 48393
```

<a id="build-the-platform"></a>

## Cross-build the platform from source

For the maintainer build on Apple Silicon macOS, install Blueprint 0.13.0,
Roc as ` roc `, Zig 0.17.1, and Rustup.
` Blueprint.roc ` names the tooling compiler and ` Blueprint.lock ` carries
the fetched digests. ` rust-toolchain.toml ` selects the Rust version and
Windows targets. Use the Roc nightly validated by this checkout when
testing the current compiler and platform together.

``` sh
blueprint run check
blueprint run build
blueprint run bundle
blueprint run docs
```

` check ` runs Rust format, lint, and portable tests, checks generated ABI
bindings using the vendored ` host/glue/RustGlue.roc `, runs Roc expects and
spec validation, and cross-builds the examples. ` build ` writes the example executables under
` examples/<name>/build/<target>/ `. ` bundle ` writes the Windows platform
bundle to ` dist/platform/ `. ` docs ` renders the manual website, Markdown,
and PDF under ` .docs-out/ ` on macOS or Linux using the locked ` roc-docs `
utility from roc-automation. The Documentation workflow builds the same
manual for pull requests and publishes the main branch to
[GitHub Pages](https://lukewilliamboswell.github.io/roc-native-windows/).

The platform examples depend on the local platform through relative
paths. Keep compiler pins in ` scripts/ `, keep generated ABI changes
reviewable, and keep build products out of source control. An example
with specs adds ` .scm ` files under ` tests/specs/ ` and data under
` tests/fixtures/ `.

To exercise packaging directly from the checkout, build the local MSI
packager and run the CLI from the example directory.

``` sh
blueprint run packager
export ROC_WINDOWS_MSI="$PWD/packaging/target/release/roc-windows-msi"
cd examples/counter
roc ../../cli/windows.roc -- package --target x64mingw
```

<a id="publish-a-packager-release"></a>

## Publish an MSI packager release

The MSI packager, ` roc-windows-msi `, has its own version in
` packaging/Cargo.toml ` and its own GitHub release tagged ` msi-<version> `.
It changes rarely, so several platform releases can share one packager
release.

To release a new packager, raise the version in ` packaging/Cargo.toml `
and merge that change to ` main `. Then run the Release MSI packager
workflow on ` main ` with the same version and ` publish ` enabled. It
cross-builds the six packagers on macOS, records their SBOMs, license
notices and ` SHA256SUMS `, attests the files and publishes them. The
release is not marked as the latest, so the newest platform release keeps
that place. Pull requests that change the packager or the release
scripts run the same staging as a dry run.

To stage the files locally on Apple Silicon macOS, add the Intel macOS
and Linux musl Rust targets.

``` sh
rustup target add x86_64-apple-darwin x86_64-unknown-linux-musl aarch64-unknown-linux-musl
blueprint run release -- packager 0.1.0 dist/msi
```

<a id="stage-a-release"></a>

## Stage a release

Record user-visible changes in ` docs/releases/unreleased.adoc ` as they land
on the integration branch. Fold those entries into the versioned notes
when preparing the next release.

Copy the [release notes template](https://github.com/lukewilliamboswell/roc-native-windows/blob/main/docs/releases/template.adoc)
to ` docs/releases/<version>.adoc `. Replace the title’s version, write a
short summary for app authors, and remove the template comments. Keep
` {roc-version} `, ` {platform-url} ` and ` {cli-url} ` for the workflow to fill
from the tested compiler and staged assets. Use HTTPS links and keep the
release notes self-contained for GitHub.

The Release Windows platform workflow stages the public assets and a loopback
preview, then uses the preview to bootstrap Reading List and test MSI
installation, upgrade, launch, and removal on Windows x64 and ARM64. Run it
on ` main ` with ` publish ` enabled to attest the staged files, verify the GitHub
draft assets, and publish. The final job bootstraps from the public URLs.
Pull requests render the newest authored version’s notes during the dry run.
A manual run uses the version supplied to the workflow.

A platform release does not build the MSI packagers. It links to the
packager release pinned in ` packaging/msi-release.sha256 `, which lists the
SHA-256 of each of the six ` roc-windows-msi-<version>-<system> ` files. The
staged ` windows.roc ` embeds their ` msi-<version> ` download URLs and
checksums, and ` windows.roc -- package ` downloads the one for the build
machine and checks it. Releases that pin the same packager share its files.

To move the platform to a new packager release, replace the pin with the
packager lines from that release’s ` SHA256SUMS `.

``` sh
gh release download msi-0.1.0 --pattern SHA256SUMS --output - \
  | grep -E '  roc-windows-msi-[^ ]+$' | grep -v '\.spdx\.json$' > packaging/msi-release.sha256
```

Download the pinned packagers and check them. Build the platform bundle
and pass its generated path, the release version, the public asset base
URL and the packager directory. The base URL must end with the release
version, because the packager URLs point to ` msi-<version> ` beside it.

``` sh
gh release download msi-0.1.0 --dir dist/msi --pattern 'roc-windows-msi-*'
(cd dist/msi && sha256sum --check ../../packaging/msi-release.sha256)
blueprint run bundle
blueprint run release -- --packagers dist/msi 0.1.1 dist/platform/HASH.tar.zst "$RELEASE_BASE_URL" dist/release
```

The output directory must be new. Every attachment includes the version.
The CLI and platform bundle use underscores in the version so Roc can
read URLs containing a dotted release tag. The standalone launcher and
the two license files use the dotted version. The scaffold writes the
fetched launcher as ` windows.roc `.

Stage and serve the files to test a local HTTP URL. A preview copies the
pinned packagers beside the platform and links to those copies. Without
` --packagers `, a preview on macOS builds the packagers from source instead,
which is how CI tests packager changes before their release.

``` sh
blueprint run release -- --local --packagers dist/msi 0.1.1 dist/platform/HASH.tar.zst dist/release-preview
blueprint run serve -- dist/release-preview
```

The preview server uses Basic CLI’s TCP support and binds to
` 127.0.0.1:8000 `. If you choose a different port with ` serve --port `,
pass the matching loopback URL to the release task when staging the files.

In another terminal, set ` TOOL_BUNDLE ` to the generated
` windows-0_1_1-HASH.tar.zst ` filename and use a fresh directory and cache
to check the first-user path.

``` sh
roc "http://127.0.0.1:8000/$TOOL_BUNDLE" -- init /tmp/windows-release-preview
cd /tmp/windows-release-preview
roc windows.roc -- test --check
roc windows.roc -- package --target x64mingw
roc windows.roc -- package --target arm64mingw
```

Before a public release, verify the exact bytes to be published, include
license and provenance evidence, and produce validated SBOM sidecars.
Use the [roc-automation platform guide](https://github.com/lukewilliamboswell/roc-automation/blob/main/docs/platforms.adoc)
for the release matrix and the
[SBOM contract](https://github.com/lukewilliamboswell/roc-automation/blob/main/docs/software-bill-of-materials.adoc)
for release evidence.

