Sky.Spa — the auto-split: Task-type tracing + the effects-via-Cmd dialect

Status: design (v2 target). This is the corrected, stronger mechanism for the compiler-derived client/server partition — the one the measurement in design.md §0.1 did not evaluate. That measurement falsified a weak mechanism (classify a branch by its returned Cmd); this document specifies the mechanism that survives it (trace Task in the branch body), the one obstacle it hits (inline effect interleaving), and the dialect that removes the obstacle. Grounded in real Sky surfaces (file:line).

Front door vs. mechanism. The user-facing entry is Std.App: write an App.app and build it with a client --target (web:app / mobile:* / tablet:*). The Spa.app / Spa.config / Spa.postJson / import Std.Spa names below are the low-level Std.Spa runtime and the generator internals that Std.App drives — how the split is computed and emitted, not surfaces user code writes.

1. Goal

Auto-derive the client/server split of a TEA app: pure UI transitions run on the client (zero round-trip), server effects become generated RPCs — no hand-written API routes. The property to earn: if it compiles, the split is sound. This is the "why do we need API routes — the AST already knows which update is effectful?" idea, made real.

2. Why the weak mechanism failed, and the right one

Sky's effect boundary is in the type system: every effect is Task Error a (sky-stdlib/Sky/Core/Task.sky), distinct from a pure a. So the information is there. The falsified mechanism looked in the wrong place:

Decidability. Pure-vs-effectful per branch is decidable in practice: it is a static call-graph walk over the typed HIR, and Task appears in the type wherever a task value flows. The one unsound corner — an effectful function stored in the Model and invoked dynamically — is conservatively rejected (a compile error), never guessed. Soundness direction is fixed: the analysis may over-approximate toward server (a needless RPC) but must never classify a server effect as client (which would leak the DB/secret to the browser).

3. Client vs server — classify by the producing kernel

"Any Task ⇒ backend" is one step too coarse: some Tasks run client-side. The refinement is a fixed table over the effect kernels:

Kernel familyTargetWhy
Db.*, Std.Db, File.*, Auth sign/verify (secret), server Http to own backendserverneeds the DB / secrets / server identity
Time.*, Random/Uuid, external Http, browser storage, navigationclientruns in the client runtime

A branch's effect target is the join of the kernels its body reaches. A branch reaching both a server and a client kernel is a mixed branch (§6).

4. The one real obstacle: interleaving (and the two ways out)

Detecting the effect is easy (§2). The obstacle is that today's apps execute the effect inline, weaving it into the pure model computation:

-- interleaved: effect sits in the MIDDLE of pure client work
SetSearch q ->
    ( { model | data = rank q (Task.run Products.listProducts) model.filters }
    , Cmd.none )

Detecting the Task.run here is trivial. Running this branch on a stateless client is not: the effect is bracketed by pure client work (rank … model.filters), so you'd have to split the branch at each run-site into [client-before] → [server RPC] → [client-after] — a continuation/CPS transform. That restructuring is the real work; "effects hide inline" precisely means "effects are interleaved with pure logic."

Two ways out:

5. The effects-via-Cmd dialect — the v2 contract

Two rules. Together they make the auto-split sound and cheap.

Rule 1 — Model = { ui, data }. ui = client-owned, ephemeral, no Std.Codec (never crosses the wire). data = a cached projection of server truth, has a Codec. "Has a codec ⇒ server-backed" is the boundary.

Rule 2 — effects only through Cmd/Task-return; never inline Task.run/force inside update or its transitive helpers.

Enforcement is a compile gate (very Sky — "if it compiles it works"). Both rules are decidable checks with clear errors:

A Spa app that violates either fails to compile with a message pointing at the inline effect or the mis-placed field — it never silently mis-partitions.

6. The partition, mechanically (once the dialect holds)

Per update branch, the compiler now knows: effect target (§2 + §3) and write-set at ui/data granularity (Rule 1). It derives:

The split-conflict / soundness check. A data field written by both a client-pure branch (optimistic) and a server branch is a conflict. The compiler either rejects it or requires a declared reconciliation policy (§8). This is the check that makes "if it compiles, the split is sound" literally true.

7. Security — untrusted client stays first-class

Auto-generation gives plumbing, never trust. The generated server endpoint:

Sky's typed secrets (Auth.signToken takes String, never any), Std.Auth, and the prod gate carry over unchanged.

8. The honest residuals (not detection — that's solved)

9. What is decidable vs what needs design (summary)

QuestionStatus
Is a branch effectful? (body Task-trace)✅ decidable (conservative reject of dynamic-effect-value)
Client vs server effect?✅ decidable (kernel table, §3)
Write-set at ui/data granularity?✅ decidable given Rule 1
Dialect enforcement (Rules 1 & 2)?✅ decidable compile gate
Generate the server-effect RPC + data delta?✅ mechanical given the dialect
Effect interleaving (inline Task.run)?⚠️ needs CPS transform — avoided by Rule 2
Reconcile concurrent/optimistic data writes?⚠️ needs per-field versioning design (§8)
Enforce untrusted-client authz?⚠️ author-declared + required compile gate (§7)

10. Staging — this is v2; v1 is forward-compatible

The auto-split is therefore not struck — it is reachable via body-level Task-type tracing once effects are mandated into Cmd. The measurement priced it (a dialect); this document is the mechanism that spends that price soundly.

11. Architecture-consult (2026-08-22): the design vs the real Rust compiler

A fresh-context consult mapped every §2–§9 claim onto the actual hir / ty / lower / project crates (file:line). The effect-detection half holds; the Rule 1 codec-boundary half does not; the codegen half hits a structural wall. Corrections, so a future session does not re-derive them:

Holds — effect detection is decidable against real structures:

Does NOT hold — Rule 1's "has a codec ⇒ server-backed" is not decidable:

Structural wall — the codegen half (§6) is not a small extension:

Where a Phase-1 gate lives: model on ty::check_modules's [E2008] precedent (ty/src/check.rs:459-522) — a post-inference, pre-lowering pass emitting typed Diagnostics; wire it whole-program between project/src/build.rs:319 (ty::check_modules) and :442 (lowering).

Opt-in: a new Spa.autoApp kernel sibling of Spa.app/config (Std/Spa.sky:129-137); the gate fires iff the entry calls it (same callee-DefId match as identifying update). This avoids wrongly gating existing v1 inline-Task.run apps.

Revised phasing (grounded):

  1. Phase 1 — opt-in dialect-conformance gate (Rules 1&2, no codegen). SMALL–MEDIUM, floor-free. Blocked only on settling the Rule 1 mechanism (above). Ships standalone value: "your app is auto-split-ready / here is the inline effect that isn't."
  2. Phase 2 — partition report (sky sub-command emitting the derived per-branch client/server/mixed split, still no codegen). Cheap given Phase 1; de-risks classification.
  3. Phase 3 — the RPC-generating auto-split (Candidate B). LARGE; needs explicit user authorization for (i) dual-target emission and (ii) the security-relevant §7 authz-required gate, and a dedicated doc-14 consult before touching emission.

Phase 1 + Phase 2 touch no runtime-narrowing floor (read-only analysis over typed HIR). Phase 3 does and must be re-consulted at that point.

12. Settled approach (2026-08-23): source-to-source + infer-first with effectful-origin taint

The user reframed the mechanism away from §6's in-compiler dual emission. It is simpler and does not touch the compiler IR at all, which dissolves the §11 "dual-target emission" and "endpoint-generation" walls:

Source-to-source into two ordinary Sky projects. The auto-split is a generator that reads one annotated/inferred project and emits two normal Sky source projects, each built by the existing compiler + targets:

examples/60-spa-todos (client + server + shared) IS the hand-written target shape — the generator's job is to produce that split from one project. Parse ↔ render already exists (sky fmt: syntax parses, fmt pretty-prints), so the generator is "parse the one project → rewrite update → emit two projects."

Inference (infer-first; annotation is the fallback). "Non-pure updates are server-side" is the rule. A branch is server iff it transitively:

  1. performs a server effect — a Db/File/Auth/server-Http kernel, or an inline Task.run / let _ = auto-force over one; or
  2. references an effectful-origin value — a top-level binding whose initialiser reaches an effect: a Task.run CAF (db = Task.run (Db.connect …)), an env/secret read (System.getenv…). These values are tainted; anything touching them is server, and they are excluded from the client build.

Both seeds propagate transitively over the call/reference graph; the analysis over-approximates to server on any ambiguity (e.g. Http whose target it cannot prove is external) — sound direction: a needless RPC, never a client leak. The compiler already detects effectful CAFs (the memoised-fresh-value warning) and has the Task-type + kernel machinery (§11), so both seeds are recoverable.

Fallback if inference proves ambiguous / bad DX (open question — the user is unsure it infers cleanly): mark server branches explicitly, via either a comment pragma or a Msg-constructor marker (Private T). Infer-with- annotation-override is the likely end state.

First build = the inference + an inspectable report, no codegen. For one project it prints each update branch as client / server with the taint reason (which effect or tainted value forced it), and flags a value used by both a client branch and a server-tainted path. This is read-only, floor-free, needs no authorization, and it directly answers "can it be inferred well?" before any generator or RPC exists. If the split it derives on a real app (todos, + a crafted effectful-CAF/env fixture) is correct and unambiguous, Infer wins; if not, we add the annotation fallback. Only then: the generator (source-to-source) + the runtime RPC glue.

13. Phase 1 DONE + verified (2026-08-23): sky spa-partition + the inference verdict

The inference + report shipped as sky spa-partition <entry> (rust/crates/project/src/spa_partition.rs, dispatched from crates/sky/src/main.rs; fixture + test in crates/sky/tests/). It walks the resolved + typed HIR only — no codegen, no IR change. Verified by running it on a crafted fixture, a direct-inline-effect app, and the real todos client, all classifications hand-checked.

Correction to §11 (found empirically — the consult was wrong here). §11 said "classify off Res::Kernel.module." That misses every server effect. With the full stdlib loaded, Http.post / System.getenv / Db.query / Auth.* / File.* resolve to Res::Def in their ordinary Sky-source modules (Sky.Core.Http, Std.Db, … are .sky whose bodies are Ffi.kernel "Http_post" etc.) — NOT Res::Kernel. The real effect origin is the Ffi.kernel "<Symbol>" string-literal prefix (Db_, Http_, System_, …). Keying off Res::Kernel.module alone silently classified the todos DB mutations as CLIENT — the exact leak the analysis must never produce. The shipped analyzer classifies by the FFI-symbol prefix + follows Res::Def callees into stdlib bodies to a taint fixpoint. (Types are read for the update body, but the server/client decision is symbol-identity + reference-graph, not type-based — an env read via pure-typed getenvOr proves types alone are insufficient.)

The FINAL rule (user, 2026-08-23) — dead simple, secure by default: pure → client, ANY effect → server; the client is 100% pure UI. We considered a client-capable-Http refinement (wasm can fetch) and a public-vs-secret env distinction, and the user rejected both as too much for an author to hold in their head — the model must fit 99% of cases with an exception only for the 1%. So every effect is server-side — not just the physically server-only families (Db/File/Auth/System/Server/Process/Io) but also the client-capable ones (Http/Time/Random/Uuid). An external Http call routes through the backend; a client-local uuid/timestamp is a documented later optimisation, not the v1 rule.

Why this is the right call: it is secure by default — an effectful value or function can never reach client code, because effects don't run on the client at all. No secret / DB handle / env value is ever in the bundle, auditable at a glance. And every operational worry dissolves: the client only calls its own backend (same-origin → no CORS, connect-src 'self' → trivial CSP), and all env/config lives in server code (no env semantics to learn). The only cost is an extra hop for external HTTP — accepted for v1.

Verified: the todos client reads 4 SERVER / 6 CLIENT — the four Spa.postJson mutations become RPCs (they reach Http), the six pure UI branches stay client — the correct auto-split shape; the effectful-CAF/env fixture reads 2 SERVER / 2 CLIENT.

Residual for the enforcing GATE — SHIPPED (2026-08-23): fail-closed guard. classify_kernel no longer defaults an unrecognised family to Neutral(client). It now classifies against two explicit, exhaustive lists in spa_partition — EFFECT_KERNELS (all → server, incl. Log/Live/Jobs/Cli/Tui/Webview/ Context/Ffi alongside the physically-server and client-capable families) and KNOWN_PURE_KERNELS (Basics/String/List/Dict/Set/Maybe/Result/ Task/Math/Regex/Encoding/Char/Path/Cmd/Sub/JsonEnc/ JsonDec/JsonDecP/Fmt/Qr) — and a family in neither falls through to a conservative SERVER verdict (never client). Since v0.27.0 a third list, MIXED_KERNELS, classifies a family per function: Crypto keeps only sha256/sha512/sha1/md5/constantTimeEqual/rsaSha256Verify on the client, Sign only verify and public-key import/export, Kx only public-key import/export; every other member (key derivation, keyed MACs, AEAD, random draws, signing, key agreement), and any member added later, is SERVER. Kdf, Noise and Cpace are SERVER as a whole, and so (v0.27.0) are Subprocess (the streaming Process.spawn family) and Watch (Std.Watch): a browser can neither spawn a process nor watch a file system. An app whose device must hold its own keys opts in with Spa.withClientCrypto / App.withClientCrypto: the key-holding members of Noise, Cpace, Kx, Sign and Kdf then run in the client, and the build refuses every flow that would move a key to the server (docs/skyspa/client-crypto.md). Two enforcement legs:

14. Generator — the e2e implementation plan (authorised 2026-08-23)

The user authorised the full e2e generator. Approach: source-to-source, two normal Sky projects, built by the existing compiler (§12). Phased, each phase verified before the next.

B0 — Msg-constant precision (in progress). update's own arms resolve update <LiteralMsg> to that arm; helpers stay conservative. Sound; removes false-server on pure composition.

B1 — read/write-set analysis (per server branch). Extend the partition with, for each SERVER branch: the read-set (Model fields + Msg args the branch reads → the RPC inputs) and the write-set (Model fields it writes → the RPC outputs). Field-precise for direct model.field access / { model | f = … }; over-approximate to "whole model" when a branch threads model into a helper (sound: bigger payload, never a wrong value — under-approximating reads is a correctness bug, so unknown ⇒ send more). This is what keeps payloads ∝ effect I/O, not Model size (§ the large-Model answer). A field read through a value DERIVED from the model counts as a read of the model's field: let m2 = { model | n = 0 } in if m2.flag …, let m2 = stamp model, (stamp model).flag each put flag in the request. A value that holds the model in a way the analysis cannot map back to fields (a destructured binder of a tuple that holds it, a case subject that holds it, the model in a list or a call argument) makes the request carry the whole model. Before v0.27.9 such a read was dropped: the backend rebuilt the field from init () and could take another branch than Sky.Live (spa_partition::collect_reads, fixture tests/fixtures/spa-readset-noneleaf). A field written on the allow path of a guard helper (requireFlag model (\_ -> ( { model | log = "busy" }, cmd ))) and kept on its reject path is not written on every path, so it rides the request too (collect_write_leaves walks the guard helper's own reject leaves). A whole-model RESPONSE goes with a narrow request only when every response leaf builds a fresh model (a record literal, { emptyModel | … }); when one leaf rebuilds the model and another keeps it ({ model | error = … } on a failed sign-in), the request carries the whole model, or the keeping leaf would answer with init's defaults (R3, BranchIo::fresh_response).

B2 — the RPC shape + runtime glue (prove on a minimal app first). One generic per-server-branch endpoint. Client → server: { msg args + read-set fields }; server runs the whole branch server-side (dodges interleaving) → returns { write-set fields }; client applies them. Reuse Spa.postJson (client) + Server.api (server) + Codec.auto for the I/O records. Trust boundary: the server treats client-sent fields as effect inputs only — anything authoritative is re-read from the DB / derived from the signed sky_spa, never trusted from the wire (§7). Hand-write the two projects for a counter-with-one-effect first, prove the round-trip, THEN generate.

B3 — the generator. sky spa-split <entry> [--out] emits two projects:

B4 — build both + e2e verify + fail-closed guard. Build backend (native) + frontend (wasm); run the round-trip (pure branch = zero network; server branch = RPC persists). Wire the fail-closed effect-family guard (§ residual). Then generalise to a real app.

Security is the spine: every phase preserves "an effectful value/function never reaches client code," and B4's guard makes it a build failure, not a hope.

15. B3/B4 DONE (2026-08-23): sky spa-split <entry> --out <dir>

The generator shipped as sky spa-split (rust/crates/project/src/spa_split.rs, dispatched from crates/sky/src/main.rs; fixture + acceptance test in crates/sky/tests/spa_split_flow.rs + tests/fixtures/spa-split/). It is source-to-source only — it reuses spa_partition's analysis (now split into analyze + analyze_loaded, plus a model_fields typed field-list on the report) and the syntax crate's CST for verbatim slicing. No compiler-IR change; the runtime-narrowing floor is untouched.

Running it — one command (2026-08-25). sky build src/Main.sky on a Spa.app entry AUTO-SPLITS (wasm frontend + native backend under .split/, --out to override) and builds both; sky run src/Main.sky does that and then runs the backend — which serves the wasm frontend + /_rpc same-origin, one binary. Detection keys on the entry's import Std.Spa (crates/sky/src/main.rs, is_spa_app_entry → spa_split_and_build).

--target and --embed COMPOSE with the split — they are not escape hatches. sky build --target ios src/Main.sky splits and builds the frontend for the iOS shell; sky build --embed src/Main.sky splits and bundles PostgreSQL into the backend; the two combine. sky run --embed runs the backend with its embedded cluster. Only three things skip the split: sky check (it type-checks the shared source directly), an explicit --wasm (a raw client build, advanced), and a project already generated by a prior split — the generator stamps [spa] generated = true into the frontend/backend sky.toml, and is_generated_split_project reads it so building the generated frontend (itself a Spa.app) never re-splits, whether the split's own --target sub-build or a user rebuilds it by hand.

The explicit form remains sky spa-split <entry> --out <dir> --build (+ --broker, --target, --embed) then cd <dir>/backend && ./sky-out/app — reach for it when you want the split artefacts kept at a specific path.

What it emits (matching the examples/60-spa-todos client+server+shared target shape):

Verified end-to-end on the counter-with-one-File-effect skeleton: sky spa-split → both projects build (sky build backend, sky build --target web frontend); POST /_rpc/Persist -d '{"n":7}' returns {"log":"saved: 7"}, count.txt is written with 7, GET / serves the wasm bootstrap and /main.wasm is 200.

Handled fully (generalised 2026-08-23 to a REAL one-project app — tests/fixtures/spa-split-todos, a todos app with Model { todos : List Todo, draft : String }, Msg = DraftChanged String | Add | Toggle Int | Remove Int, user-defined todoCodec/todoListCodec):

Refused, not mis-generated: a multi-module app (the entry importing sibling project modules) returns a clear Err rather than emitting a backend that references uncopied modules; a field whose codec cannot be resolved is an Err.

Fail-closed classification guard — SHIPPED (2026-08-23). The §13 residual is closed: spa_partition::classify_kernel classifies against exhaustive EFFECT_KERNELS / KNOWN_PURE_KERNELS lists with an unknown family falling through to a conservative SERVER verdict, spa_split::generate refuses to emit when the compiler knows an unclassified kernel, and the compile-time classification_is_exhaustive test (over the real hir::KERNEL_MODULES) makes "add a kernel without deciding its split side" a build failure. See §13.

16. Server→client PUSH (SSE) — Cmd.publish → Sub.subscribeTopic (2026-08-23)

B1–B4 (§14/§15) generate the client→server direction: an effectful branch becomes a POST /_rpc/<Msg> the client calls. This section adds the server→client direction, so a Sky.Spa app whose subscriptions subscribes to a topic is pushed messages when a server-effect branch publishes to it. It is the auto-split's counterpart of Sky.Live pub/sub, delivered over SSE (not WebSocket), and it reuses the existing runtime — the same in-process broker Sky.Live uses, the same Sky.Http.Server.Stream chunk-writer, the same Sub.subscribeTopic surface. No runtime-narrowing floor is touched (runtime Go

The wire path, end to end:

client A: Increment ─▶ POST /_rpc/Increment ─▶ backend runs update (real File
                                                effect) ─▶ returns (m2, Cmd.publish
                                                "count" n) ─▶ spaInterpretPublish
                                                fans it through the broker
                                                        │
broker.Publish("count", n) ─────────────────────────────┤
                                                        ▼
every client subscribed via GET /_sky/sub?topic=count receives an SSE
`data: <json>\n\n` frame ─▶ EventSource onmessage ─▶ JSON→Sky decode ─▶
sky_call(toMsg, payload) ─▶ GotCount n ─▶ update ─▶ re-render

What the generator emits (push mode). Push mode turns on when the app reaches Cmd.publish / Cmd.publishNoEcho or Sub.subscribeTopic (SpaPartitionReport.{publishes, subscribes_topics}, detected by walking the reachable defs for the kernel-alias symbols). Then sky spa-split adds to the backend:

The frontend keeps subscriptions verbatim; the client driver (runtime-go/rt/live_wasm.go) reconciles Sub.subscribeTopic leaves (identity = the topic string, same diff shape as Sub.every): an added topic opens new EventSource("/_sky/sub?topic=" + topic) whose onmessage JSON-decodes e.data to a Sky any and runs step(sky_call(toMsg, payload)); a removed topic closes the EventSource and releases its callback. The decode is structural (JSON.parse → Sky any, integral numbers → int), reconstructing the value's Sky shape rather than a .(T) assertion.

Security carries over unchanged. The client has no effects, so no secret / DB handle ever reaches it; the SSE endpoint only delivers what a server branch chose to publish. A publish payload is server-authored — never echoed from a client-sent field for anything authoritative (§7). The client only ever talks to its own backend (same-origin → no CORS). Since v0.27 the endpoint also streams a topic only to a visitor whose own subscriptions name it (§21).

Multi-replica — wired, and configurable in code. Spa_newBroker urlArg routes through maybeOverrideBroker(newTopicRegistry(0), effectiveBrokerUrl(url)): the default is in-process (single replica — a publish on A reaches only SSE connections on A). A broker URL upgrades it to the SAME cross-instance Redis broker Sky.Live uses (the Broker interface, live_redis_broker.go) — so a publish on replica A reaches an SSE subscriber on replica B — with no session store required (the broker is app-scoped, not store-scoped).

The URL comes from one of two places, reconciled by effectiveBrokerUrl (env wins):

An undialable URL degrades to in-process (logged); SKY_LIVE_BROKER=inprocess forces local. A multi-replica deploy still needs sticky routing so a client's /_sky/sub and /_rpc/* hit a coherent set. Verified end-to-end against a live Redis: two backend instances (no shared session store), a POST /_rpc/Increment on instance A delivers a data: frame to an SSE subscriber on instance B — driven by the baked --broker URL (no env), by the SKY_LIVE_BROKER_URL env (no bake), and the default (no URL) keeps single-instance in-process push.

Verified. tests/fixtures/spa-push-counter (a shared counter: Increment writes count+1 to disk inline and publishes "count"; GotCount n folds a pushed count; subscriptions = Sub.subscribeTopic "count" GotCount) generates, both projects build, and a live run proves push deterministically: an SSE reader on /_sky/sub?topic=count receives data: 1 then data: 2 as two POST /_rpc/Increment calls fire — no browser needed. rt unit tests (spa_push_test.go) cover the publish → broker leg; the generator wiring + build are asserted in spa_split_flow.rs (wires_server_to_client_push_when_the_app_uses_publish_and_subscribe_topic).

17. Multi-module apps (2026-08-23): pure modules → both trees, effectful modules → backend-only

§15 shipped the single-entry-module generator and refused any project whose src/ spanned more than the entry module. Real apps span modules — the Model/Msg loop in Main, the domain types + codecs in a Domain module, the effects in a Store module — so the generator now splits them. The mechanism is source-to-source still; no compiler IR, no runtime-narrowing floor is touched.

The routing rule (simpler + sound). Every project module other than the entry is classified by whether it contains a server-tainted def (the spa_partition taint analysis already tracks tainted top-level bindings across every module, not just the entry):

Shared still holds the generated <Msg>Req/<Msg>Resp records + codecs. When a wire field's codec or type is declared in a pure sibling module (e.g. todoListCodec / Todo in Domain), Shared imports that module rather than re-copying the def — the module is already present in both trees. Only codecs/types declared in the entry module are copied into Shared (as before, to avoid a duplicate definition, since the entry is transformed).

The mixed-module rule → a pure def that lives in a backend-only module. A module can be backend-only (it has ≥1 effect) yet also contain a pure helper. That pure helper is backend-only too (the whole module goes backend). This is sound as long as no frontend def needs it. The generator verifies exactly that: it walks every frontend-retained def (the entry's non-tainted defs — with update rewritten so its server branches no longer reference the module — plus every pure sibling module's defs) and, if any references a pure def in a backend-only module, refuses with a clear Err ("a pure client value cannot depend on a server-tainted module — move it into a pure module shared by both trees"). Fail-closed: a real error rather than a silent leak or a frontend that won't compile. A referenced codec that lives in a backend-only module is refused the same way.

What each tree gets:

Verified end-to-end on tests/fixtures/spa-split-multimodule — a todos app split across Main (Model/Msg/TEA loop), a pure Domain (the Todo type + todoCodec/todoListCodec) and an effectful Store (File load/save). sky spa-split routes Domain into both trees and Store into the backend only; the frontend leak-check is clean; both projects build (backend native, frontend wasm); and a live round-trip (POST /_rpc/Add, POST /_rpc/Toggle) persists to todos.json and returns the write-set. The generator wiring + build + routing are asserted in spa_split_flow.rs (splits_a_multi_module_app_routing_pure_and_effectful_modules).

18. Server-internal effect chaining (2026-09-10)

A server RPC branch that returns Cmd.perform serverTask ToMsg — where the result ToMsg feeds back through update and is dispatched only server-side — now runs the whole chain inside the triggering branch's RPC and answers with the final settled model diff. This mirrors Sky.Live, where the entire TEA loop is server-side.

The bug it fixes. The generated RPC handler used to bind ( m2, _ ) and discard the returned command (gen_backend), so a returned Cmd.perform ran nowhere and any field its result-Msg wrote was silently dropped. The canonical shape:

Reload ->
    ( model, Cmd.perform (File.readFile "data/note.txt") Reloaded )

Reloaded (Ok raw) ->
    ( { model | note = raw }, Cmd.none )

POST /_rpc/Reload used to answer with an empty note; now it settles the read server-side and returns note = the file contents.

Server-internal Msgs. A Msg is server-internal when it is the toMsg of a server arm's Cmd.perform/Cmd.batch, is constructed nowhere on the client (not in view, subscriptions, nor a client arm — an over-approximated, transitive scan), and is not itself a wire (/_rpc) branch. A server-internal Msg gets no /_rpc/<Msg> route, no Applied<Msg> variant, and its client update arm plus its Msg-union constructor are pruned from the frontend (spa_partition::compute_server_chaining → spa_split::union_text_without_variants + the frontend arm drop).

Write/read-set union (soundness). A chaining branch's RPC response write-set is the union over the triggering arm PLUS every server-internal continuation arm reachable through the perform edges. Reload's write-set gains note (written by Reloaded). Under-approximating (dropping a real write) is a correctness bug, so any shape the resolver cannot fully read widens to the whole model — never narrows.

Only server continuations chain (v0.27.0). A continuation whose own arm is CLIENT (reaches no server effect) does not join a chain: it must run in the client when the task's result arrives, on the model the client holds then, as Sky.Live runs it. Settled on the server it read the request's copy of the model and its write overwrote what the client did meanwhile. Such a branch is a client-result root (§19) or a follow-up branch (§20), whose result Msg runs in the client. Reload → Reloaded (Ok raw) -> { model | note = raw } above is therefore a client-result root today; a chain is Ship → Shipped where Shipped itself reaches a server effect (tests/fixtures/spa-server-chain). A chain root is a hold RPC (§20). The rule applies to a ROOT's own continuation only: once a chain passes through a server hop (Navigated → GotIndex, where GotIndex reads a file), the client-pure continuation of that hop (GotItems) settles in the same chain, because the root holds the client and nothing runs between the hops. The whole chain is then ONE round trip (tests/fixtures/spa-seeded-nav-chain, a_multi_hop_chain_settles_in_one_round_trip).

Fail-closed (G5). A branch is not chained when its transitive command chain contains a Std.Native client effect (which cannot run server-side), an ambiguous continuation (a toMsg that is also client- or wire-dispatched), or an opaque command shape the static resolver cannot read. The un-chained branch's continuations stay client arms, and the branch becomes a follow-up branch (§20): its command still RUNS. (There used to be a discard-and-warn floor here — the command ran nowhere. It is gone.)

Runtime. runtime-go/rt/spa_chain_notjs.go's Spa_settleServerChain (Ffi.kernel "Spa_settleServerChain", the spaChainSettle_ alias) folds every server-runnable perform leaf back through update to a fixpoint, bounded by a hard round cap (spaChainMaxRounds = 64) so a self-referential Msg cycle terminates rather than hangs. It returns ( settledModel, residualCmd ).

Verified. Classification + write-set union in crates/project/tests/spa_server_chain.rs (against tests/fixtures/spa-server-chain, which exercises both the chained Reload and the fail-closed SyncCopy that batches a Native client effect); the runtime fold + cycle termination in runtime-go/rt/spa_chain_notjs_test.go; and the end-to-end POST /_rpc/Reload → note in spa_split_flow.rs (server_internal_chain_e2e_post_reload_returns_file_note).

19. Client-result perform — pattern-2 (2026-09-10)

The complement of §18. Where server-internal chaining settles the whole chain server-side (the result Msg is server-only), a client-result perform runs the server task server-side but hands its result to the client, because the result Msg is a client arm.

The shape. A server branch returns Cmd.perform serverTask ResultMsg — directly or through a guard/HOF wrapper (requireAdmin model (\_ -> …)) — where serverTask reaches a real server effect and ResultMsg's own arm is client-pure (a model update over the task result):

Upload data ->
    guard model (\_ ->
        ( { model | busy = True }
        , Cmd.perform (saveBlob data) Saved
        ))

Saved (Ok url) ->
    ( { model | items = url :: model.items, busy = False }, Cmd.none )

The bug it fixes. Because the perform hides inside the guard thunk, §18's tail walk sees no command, so Upload fell to a plain wire branch whose handler bound ( m2, _ ) and discarded the command — saveBlob ran nowhere and Saved was never dispatched. The upload silently did nothing.

Behaviour. The Upload RPC runs saveBlob server-side and answers with the task result (Result Error String), carried in the branch's UploadResp record as a single result : List (Result Error String) field (Codec.list (Codec.result Codec.error <valCodec>)): one element when a server task ran, none when the branch took a Cmd.none path. The frontend's AppliedUpload (Ok resp) arm dispatches update (Saved spaResult_) model for [ spaResult_ ] and returns ( model, Cmd.none ) for [], as Sky.Live dispatches nothing on a Cmd.none path. It dispatches the result Msg with the whole Result value into the client update, so Saved's arm runs in the wasm client.

A Cmd.none leaf sends no request (v0.27.9). A root whose tail the client can read runs in the client as written, with each command that needs the server replaced by the RPC (the planned arm of §19a below, spa_partition::client_model_plan):

Gated ->
    let
        spaRpc_ =
            Spa.rpc gatedReqCodec gatedRespCodec "/_rpc/Gated" { flag = model.flag } AppliedGated
    in
    if model.flag then
        ( model, spaRpc_ )

    else
        ( model, Cmd.none )

So the request goes out only on the branch where Sky.Live runs the task. A root whose Cmd.none the client cannot see (a guard helper's reject path, a hold arm) sends the request on every branch, and the backend answers [] when no task ran. Before v0.27.9 it answered Err "… carried no server task to run", and the client dispatched Got (Err …), a failure the app never had. Saved stays a client arm — no /_rpc/Saved route, no SavedReq, no decomposition of the Result into Ok/Err binders (the record is missing field(s): url bug a Result-typed wire branch produces). The server task never crosses to the client; only its typed result does.

Why not the residual-Cmd channel. The alternative — return the Cmd.perform serverTask to the client to run — would hand a server effect to the wasm client, whose !js server-effect stub returns Err. Unsound. Only option (a), the typed result crossing the wire, is used.

Classification (spa_partition::compute_server_chaining, after the §18 pass). A branch pattern-1 did not already own (not a chaining root, not a server-internal continuation) is a pattern-2 root when its command — read through the guard-aware walk collect_guarded_tail_cmd_exprs — is a single Cmd.perform serverTask ResultMsg with a server task and a ResultMsg that is not server-classified (client-pure). Recorded as ServerChaining::client_result ((root, result_msg) pairs).

Fail-closed. The branch is not pattern-2 when ResultMsg's arm reaches a server effect (a deeper chain), the task is a Std.Native client effect, or the command is not a single clean server perform. It is then a follow-up branch (§20) — its command runs; nothing is discarded. Since v0.27.0 the direct-tuple shape (Reload → Reloaded of §18, with no wrapper) is pattern-2 too: a client-pure ResultMsg runs in the client whether or not the perform sits behind a wrapper. Only when ResultMsg's argument has no wire codec does it still settle server-side as a §18 chain (the build prints a note).

Runtime. runtime-go/rt/spa_perform_notjs.go's Spa_runServerPerform (Ffi.kernel "Spa_runServerPerform", the spaRunPerform_ alias) walks the branch's command, runs the single server perform leaf's task, and returns its Result raw, as a one-element list — without folding it back through update (§18's job). A command with no runnable perform (a Cmd.none path) returns the empty list: no task ran, nothing to dispatch.

Verified. Generation contracts (no server-effect leak; Saved is not a wire branch; the whole Result is carried; fail-closed Stored whose arm reaches a server effect), both-trees build, and the end-to-end POST /_rpc/Upload → Ok "blob.txt" in spa_split_flow.rs (client_result_perform_wires_task_result_to_client, client_result_both_trees_build, client_result_e2e_post_upload_returns_task_result, against tests/fixtures/spa-client-result); the Cmd.none leaf with no request and the [] answer in readset_through_derived_locals_and_none_leaf_sends_no_rpc and readset_noneleaf_backend_takes_the_live_branch_and_sends_no_false_err (tests/fixtures/spa-readset-noneleaf); the runtime run-and-return + no-fold + "no task ran" answer in runtime-go/rt/spa_perform_notjs_test.go.

19a. Async arms through case / if / let and helpers (v0.27.9)

Before v0.27.9 a server arm ran async (Spa.rpc) only when its body was a direct ( model, cmd ) tuple. Any other shape held later Msgs for the whole request (Spa.rpcHold), so a page froze while a slow call ran: in a support-desk app, Select (a helper), Redraft (a case) and Send (a case with an if) showed no selection and no "drafting" label until the model answered, and typed text applied late. Sky.Live shows them at once.

The plan (spa_partition::client_model_plan, per server arm). It walks the arm's tail positions:

One taint check. Everything the client copy evaluates (the whole arm body and every copied helper body, minus the Rpc command halves and the copied callee names, CollectCtx.skip) must reach no server effect and no server-tainted value, compose no other arm and force no effect. So every local in scope on the client is client data, a let that binds the task makes the arm hold, and every condition the client evaluates reads only the request model's fields: the read-set walk includes them (also a field read through a value derived from the model), so the backend takes the branch the client took.

The splice. The plan carries trimmed spans and the source text found there. The split (ArmRoutes::finalize_plans) checks each span against the module source, applies the splices in order (apply_plan_splices) and lays the arm out at its source column (moved right as a block when it sits at or left of column 8, the generated pattern column). The RPC is bound once at the arm's top, built from the model and Msg the arm runs on (a binder shadowed inside a branch does not change the request):

Select id ->
    let
        spaRpc_ =
            Spa.rpc selectReqCodec selectRespCodec "/_rpc/Select" { … } AppliedSelect
    in
    (selectTicketSpaClient_ spaRpc_) id model

A helper copy <f>SpaClient_ takes spaRpc_ before the helper's own parameters. Its annotation gains the helper's own command type (Cmd Msg ->, or Cmd msg -> for a helper polymorphic in its Msg) when the result is written as a ( model, Cmd … ) tuple, and is left out for an alias result. One copy per helper, however many arms call it. A helper in another module is copied into that module's client subset and added to its exposing list; it must be called qualified (Remote.pick model), and a module with no client subset holds the arm.

Fail closed. An arm holds, with a build note, when:

A constructor whose arms write the model is async only when every one of its server arms has a plan. A constructor that writes nothing stays async either way and uses a plan where one holds up (its Cmd.none branches then send nothing).

Build notes. Every server arm that holds gets one line: Sky.Spa: `Mixed Nothing` holds later Msgs while its request runs: <reason>. To run it async, as Sky.Live does: <change>.

Layout fixes found on the way. A server arm's pattern carried its leading trivia (the newline and the source indent) into the generated update, and a client arm of an update laid out with two-space indentation kept its body left of the generated pattern column. Such an update did not parse in the frontend. Both are fixed (arm_at_column_8, the trimmed pattern).

Verified. spa_split_flow.rs: async_leaves_run_their_model_write_in_the_client (tests/fixtures/spa-async-leaves: 17 async shapes, 9 hold shapes, each with its note), identity_arms_hold_and_a_guard_on_identity_holds_every_write (spa-async-identity), std_app_sibling_update_two_space_layout_runs_async_and_builds (spa-async-app, both trees built); spa_split::plan_tests (the oracle, a stale span, the annotation and layout helpers). The differential split fuzzer (xtask harness --only spa-diff-fuzz) builds each async arm's client leg with the split's own emitter (client_arm_body) and checks that the client sends exactly where the direct update's command is not Cmd.none and, for an arm that makes its own write in the client, that its model is the direct update's (falsifiers spa-diff-fuzz.async-arm-drops-write, spa-diff-fuzz.async-arm-sends-on-keep). The browser stage of scripts/spa-rpc-order-e2e.sh (scripts/spa-async-arms-verify.mjs, fixture spa-async-arms) holds the app's model call open and reads the page while the request is pending: the selection, the busy label and typed text show on web:app as on Sky.Live, a Cmd.none branch sends no request, and a hold arm (the negative control) shows its write only when its request answers.

20. RPC consistency, follow-ups, guard and persistence (2026-09-23)

The client must give the answer Sky.Live gives for the same Msg sequence. Live runs the whole TEA loop on the server, one Msg at a time, in dispatch order. Proven end to end by scripts/spa-rpc-consistency-e2e.sh (fixture rust/crates/sky/tests/fixtures/spa-rpc-consistency).

Each Msg once, in arrival order (v0.27.0). Every server-branch arm emits an RPC Cmd (runtime cmdT{kind: "rpc"}), and the client's Msg scheduler (runtime-go/rt/spa_rpcqueue.go) runs every Msg — a click, a timer tick, a perform result, an RPC result — through update exactly once, in arrival order, with its Cmds. The split gives each server constructor one of two kinds (spa_split::ArmRoutes):

This replaced the v0.26 design (one RPC at a time; Msgs applied during the RPC recorded and REPLAYED on top of the response, without their Cmds). A replay re-runs a client arm, which is not safe: an arm that spends a single-use state (Noise.encrypt on the model's transport) fails the second time, and an arm that decides on a field the response changed decides differently while its new Cmd is dropped (a timer that starts a call only when busy is False stalled for good). The differential property test TestSpaSched_MatchesLiveOnRandomInterleavings drives random Msg sequences with interleaved RPC completions through the scheduler and through a Sky.Live session model and requires the same update trace and the same model; scripts/spa-rpc-order-e2e.sh compares web:app with Sky.Live in Chromium and WebKit. The contract is documented for app authors in overview.md, "Msg order and server calls".

Retry without a second effect. Each request carries ?rid=<id>; a retry re-sends the same id. The backend answers a repeated id from the response it already produced (spa_rpc_dedupe.go: bounded cache, keyed by the session cookie + path

Follow-ups: a server branch's command runs. A server branch that is neither a chaining root (§18) nor a client-result root (§19) but returns Cmd.perform leaves is a follow-up branch (SpaPartitionReport::follow_up). Its handler runs every server perform leaf (Spa_collectFollowUps), encodes the resulting Msgs (one SpaFollow<Ctor>Req wire record per constructor, in Shared) into the response field spaFollow_, and the client decodes them and dispatches them in order through its own update (Spa.followUps), ahead of any Msg that waited behind the branch — a pure arm runs locally, a server arm sends its own RPC. The branch's own write-set applies FIRST: a follow-up that cannot be decoded is then routed to App.withRpcError, else reported on the console (Spa.reportError); it never takes the write with it, and it is never dropped. A known follow-up is never server-internal: a Msg a server chain also reaches (Save → Saved → Tracked, while Bump returns Tracked) keeps its client arm and its wire codec, and the chain still settles it on the server (v0.27.0: before, it was pruned, sent as an empty tag and Bump's whole write was dropped). The backend encoder has no empty-tag arm: a constructor the split proved is never a follow-up is dropped with the classified SpaFollowUpOutsideWire error, and the rest of the response still applies. The split reads the follow-up constructors from the command: a Cmd.perform _ Ctor leaf, through helpers, let names, let-bound local functions (refuse msg = ( { model | … }, Cmd.none ), or \msg -> …), if / case, and a Cmd.batch over a list, a list chosen by an if / case, xs ++ ys, c :: cs or List.map / List.indexedMap of a lambda or helper (each perform then runs once per element) (v0.27.10: the if-chosen list and the local functions). A follow-up constructor it reads whose argument has no wire codec fails the build, naming it. When a command cannot be read (for example Cmd.batch (List.filterMap …)), every Msg constructor may be its follow-up: those with a wire codec cross, and those without one are named in a build warning. If one of them occurs at run time, the backend drops it and logs the classified error SpaFollowUpOutsideWire (Spa_followUpOutsideWire); the rest of the response still applies (R1). The client decoder dispatches on the tag with one flat case, so it parses for a Msg of any size (v0.27.10: it was an else if chain, which passed the parser's nesting limit at a few hundred constructors). Every .sky file the split writes is parsed before it is written; one that does not parse stops the split with a message naming the file as a generator defect.

A Std.Native leaf (a client-only effect) cannot run on the server: the server skips it, and the client runs it when the Msg runs, on the model the request is built from (Cmd.batch [ <native leaves>, Spa.rpc … ]). A native leaf that uses a let-bound value of the arm or a server-tainted binding fails the build, naming it.

init's command runs on the server when it must (v0.27.9). init's command runs once when the client starts, unless the SSR page settled it. When that command reaches a server-only binding (a task that opens the database, a model slot, a qualified binding of a server module, through a helper or a let) and is not the GET-safe read the SSR settles, the client cannot hold it. The split then gives init the follow-up treatment of a server branch: the client init keeps its model and sends one RPC, POST /_rpc/SpaInit_; the backend handler runs init ()'s command (Spa_collectFollowUps) and answers the follow-up Msgs as JSON; the client dispatches them in order through update (AppliedSpaInit_), and a follow-up it cannot decode, or a failed RPC, goes to App.withRpcError, else the console. let bindings that only the command used become Cmd.none in the client copy, and a Std.Native or navigation leaf runs in the client when the RPC is sent. Shapes the split cannot rewrite fail the build, naming the binding: an init whose body is not a ( model, cmd ) tuple (through let … in), or a model that uses a server-only binding. spa_split::plan_init_rpc; tests init_command_reaching_server_bindings_runs_through_an_init_rpc and init_in_a_sibling_module_reaching_server_bindings_runs_through_an_init_rpc. Before, init was copied verbatim and the client failed with Undefined name (a database-backed app under --target web:app).

Guard. App.withGuard runs in the client before update for every Msg, exactly like Live (Spa.withGuard, spaGuardedUpdate); a rejected Msg keeps the model and runs no Cmd. The backend still runs the guard on every server branch (the trusted check), and the fields the guard reads ride every request (spa_partition::guard_readset), so the server guard sees the client's values. A guard that reaches a server effect cannot run in the client; the build warns.

Persistence. Every web:app build with a derivable init model persists the client model to localStorage and restores it on reload (Spa.withModelDecoder + Spa.withModelEncoder). The codec is Codec.auto of the model init () returns (spaModelBlank_), so the model may use let bindings, init's argument and private bindings of a sibling module that declares init (v0.29.9; before, a copy of the model's text named them in the client entry and the build failed with Undefined name). On a full page load the client restores the stored model and takes from the SSR seed ONLY the fields the server settled for THIS page (R2): the session fields, the fields the withRequest hook writes (it runs on every request, so they are a constant list, Spa.withPersistSeedFields), and the write-sets of the commands the page marks finished in data-sky-settled — init's command chain and the route's onNavigate Msg with its command chain. The page names these fields in data-sky-seed-fields on #app; the backend computes them per onNavigate constructor at build time (spaNavSeedFields_). Every other field keeps its stored value, even one only server branches write: the seed holds init's default for a field this page did not load, and a default never paints over data. An onNavigate Msg whose write-set cannot be read (a whole-model write, an unreadable command) is not marked finished, so the client runs it after the mount, as it did in v0.25.16. This is Sky.Live's rule: a Live reload keeps the session model and runs onNavigate over it, so a notice that onNavigate clears is cleared, and one it does not clear stays. A restore does not cancel init's own command.

Fields that are never stored (v0.29.0). A field the server owns (site settings, a feature flag, the server clock) should not come back from an earlier page. App.withPersistExclude [ "siteConfig", "serverNow" ] (or Spa.withPersistExcludeFields on a hand-written Spa.app) leaves the named fields out of every stored copy and, on a full load, always takes them from the SSR seed, so a stale copy cannot paint the first frame. A session field is never left out (the identity check below reads it). Without an SSR seed (a static deploy) the stored copy has no value for these fields, the model decoder refuses it, and the client boots from init. On Sky.Live the same builder makes a full page load of an existing session refresh the fields from init.

Persistence is per identity. The stored model restores only when the identity it was stored under equals the identity of the SSR seed. The identity is the value of the session fields (Spa.withPersistProtectedFields), canonically serialised (spa_persist.go spaIdentityOf). Any change of identity (one user to another, signed out to signed in, signed in to signed out) restores nothing, removes the stored copy, and boots from the seed (spaRestoreStored). Two tabs with two identities share one localStorage, so without this rule a full load of one tab restored the other identity's model under its own session. An update that clears the session removes the stored copy, and the page then writes no signed-out model (spaPersistWrite). See overview.md, "Client persistence and identity".

Seeded boot (SPA-10). When the page is server-rendered, the client boots from the #sky-model seed: the model the server rendered, with init's read and the route's onNavigate load already settled into it. The page carries data-sky-settled on #app, naming what the server FINISHED: init (init's command ran to the end, or was empty) and nav (the route's onNavigate command ran to the end). "To the end" means every leaf ran, no follow-up was left (the SSR settle runs one round) and no write was suppressed (a GET never mutates). The client skips exactly the named commands, so a settled deep link makes no RPC and onNavigate runs once per navigation, as on Sky.Live. A command the server did not finish (a chained read, a suppressed write, an init command that is not GET-safe) still runs once on the client; an init command that reaches server-only bindings runs through the init RPC (§20).

update without case msg of. A wholly pure update with no case runs in the client as written. One that reaches a server effect fails with a message naming the change (write update msg model = case msg of …).

21. RPC and push security

The split backend authenticates the browser with the signed sky_spa cookie (HttpOnly; SameSite=Lax, plus Secure on any request that arrived over TLS or through a proxy that sent X-Forwarded-Proto: https). The browser attaches that cookie by itself, so two endpoints need more than the cookie.

/_rpc/<Msg> and /_rpc/__spaSignOut are Server.rpc routes. Before v0.27 they were Server.api routes: exempt from CSRF and with no other check. A cross-origin page could send a CORS-simple text/plain POST, which a browser sends without a preflight and with the cookie, and the handler ran with the victim's session. SameSite=Lax limited this to same-site attackers (a sibling subdomain, another port on localhost) and to browsers without SameSite, but did not close it. The double-submit CSRF token cannot help: the CSRF cookie is HttpOnly and the wasm client cannot read it.

A Server.rpc route keeps the CSRF exemption and runs a guard before the handler (runtime-go/rt/rpc_guard.go):

RequestResult
Wrong method (for example GET /_rpc/Save)405
Body not Content-Type: application/json403
Sec-Fetch-Site: same-origin or nonepasses
Origin equal to the app's public originpasses
Origin: null, or any other Origin403
Sec-Fetch-Site other than same-origin with no Origin403
No Origin and no Sec-Fetch-Site (curl, a server)passes

The public origin is SKY_PUBLIC_URL when it is set (one URL or a comma-separated list), else the request's own scheme and Host. A proxy that keeps the Host header (Caddy's default) needs no setting. A proxy that rewrites Host, or a tunnel, needs SKY_PUBLIC_URL, and the 403 body says so. X-Forwarded-Host is not read. The native shells (mobile:*, desktop:*) load the backend's own http(s) URL, so their requests are same-origin. The wasm client already sends every RPC as a same-origin JSON POST, so an app needs no change.

GET /_sky/sub?topic=<t> is authorised against the app's own subscriptions. Before v0.27 it streamed any topic named in the query string, so a per-user topic reached anyone who asked for it. The handler now rebuilds the model the visitor's app would hold: init (), the withRequest seed when the app has one, and every session field from the verified sky_spa cookie (never from the query string). This is the same model the RPC handlers and the console gate build (verified_model_decl). It runs the app's subscriptions on that model and streams <t> only when the resulting Sub names it (Spa_subAllowsTopic, runtime-go/rt/spa_push.go). Anything else, and an empty topic, gets 403. No app change is needed.

The check is fail-closed:

SSR pages are CSRF-checked GETs (v0.29.1). The backend mounts each page with spaPageRoute_ "<pattern>" ssrHandler (the Spa_pageRoute kernel, runtime-go/rt/spa_ssr_notjs.go). Before v0.29.1 a page was a Server.api "GET <pattern>" route, which skips the CSRF middleware: the page set no CSRF cookie and its forms had no __sky_csrf field. A form submitted before hydration was then a native POST that ended on the CSRF 403 JSON page. Now the page GET takes the CSRF middleware, which sets the cookie on a first visit and passes the same token to the render, and each method="post" form of the page gets the hidden field. The runtime answers a native POST to a page (a form content type with no X-Sky-Csrf header) with 303 See Other to the same URL, Cache-Control: no-store, and does not read the body. It does so when the CSRF check fails as well, so a stale page or a lost cookie also lands on the page. The Location is always a path on the same origin (//host and /\host collapse to /host). A page leaves POST to another route on its path (App.api "POST /path", Server.any), and a page whose POST entry would conflict with another route at start is skipped with a log line, never a panic. The / catch-all (Server.staticNotFound) is a page for a request the router gives to it: a path under its prefix that no other route takes for that method. A hand-written Server.post or Server.any route next to it keeps its POST, so its handler runs and a failed check is the 403. Sky.Live answers a native POST to a page the same way.

A page with the field carries one visitor's token, and its response sets that visitor's CSRF cookie. Such a response gets Vary: Cookie and Cache-Control: private (an app Cache-Control keeps its other directives, less public and s-maxage), so a shared cache does not give one visitor's token to the next. Do not cache Sky pages in a shared cache.

Tests: runtime-go/rt/page_native_post_test.go (the page field, the 303, the App.api / /_rpc / JSON cases, the Location guard, Sky.Live), spa_split_flow.rs (spaPageRoute_ mounts, the App.api "POST /items" on a page path), and scripts/spa-early-submit-verify.mjs (the browser stage of scripts/spa-rpc-order-e2e.sh).

Tests: runtime-go/rt/spa_rpc_guard_test.go (the guard, method-keyed CSRF exemptions, Secure over TLS, the topic check) and spa_split_flow.rs (spa_rpc_origin_guard_and_sub_topic_authorisation, a live backend built from tests/fixtures/spa-sub-auth).

22. Server arms that match inside their Msg arguments (2026-09-28)

A server arm may match inside the arguments of its message. Every pattern shape splits: a nested constructor (Report (Ok line)), an Int or String literal (Pick 0, Named "admin"), a tuple (Pair ( 0, s )), a record (Take { id, label }), an as binding (Wrap ((Just n) as whole)) and a wildcard (Any _).

The rule: each arm keeps its side, and a server arm sends the whole message. The partition classifies each arm of update's case msg of (BranchVerdict::arm). The client update keeps every arm in its source order. A client arm is copied as written. A server arm sends the message to POST /_rpc/<Ctor>, and the backend runs the app's own update on it. The backend takes the same arm the client took: every arm before it failed to match on the client, Sky patterns are pure, and the arms keep their order, so those arms fail on the backend too. There is one route per constructor (spa_partition::server_routes). Its request and response are the union of the I/O of the constructor's server arms, because any of them can be the arm that runs. A client arm of a server constructor adds nothing to the route: a message it matches never leaves the client.

Positional arguments. A constructor sends its arguments positionally when one of its server arms matches inside an argument, or when it has more than one server arm (their binder names can differ). The client wraps each argument of each server arm in an as binding and sends the bound values:

Report (Ok line) ->            client:  Report ((Ok line) as spaArg0_) ->
                                            ( model, Spa.rpc … { spaArg0_ = spaArg0_ } … )
                               backend: update (Report p.spaArg0_) m

The argument types are the constructor's declared types (ArmShape::ctor_args), instantiated at the case subject's type, and each gets a wire codec from the resolver (§15). A constructor whose only server arm binds plain names (Report result ->) keeps the named form (update (Report p.result) m), so the output for such an app is unchanged. A tuple argument has a codec since this change: a JSON object keyed by position ({"0": …, "1": …}), built with Codec.object / Codec.field.

The wire diagram, the OpenAPI document and the differential fuzzer read the same routes. The fuzzer's harness writes the constructor's arms in order, diffs each server arm through the wire and answers Ok () for a client arm.

What is still refused, and why. A server arm cannot be split when the backend cannot rebuild its message from a request:

The generator also fails closed when the case it rewrites does not have the arms the partition classified (it never guesses which arm runs where).

Tests: project/tests/spa_server_arm_args.rs (every shape, the client arms kept, one route per constructor, the plain form unchanged); spa_diff_harness unit tests (a client arm keeps its place and is not diffed); spa_split_flow.rs server_arms_that_match_inside_their_msg_arguments_behave_as_the_live_app (the fixture tests/fixtures/spa-arm-patterns built as a Sky.Live app and as web:app, each message sent to both, the models compared); and fuzz_verb_flow.rs the_split_oracle_diffs_server_arms_that_match_inside_their_arguments.

23. Scope, types and shapes the split must carry (2026-09-29)

A downstream app found ten places where the split lost or misplaced part of a program that builds as Sky.Live. Each rule below replaces a text or bare-name heuristic with a fact from the resolver or the lexer.

Every kernel symbol family is decided. The partition reads the runtime symbol of Ffi.kernel "<Family>_<fn>" and of Ffi.callPure / Ffi.call. Families without a hir::KERNEL_MODULES pseudo-module used to fall to the fail-closed default (server), so a pure Bytes.slice became an RPC. Now:

SideFamilies
Client effectNative, WebSocket (the client holds its own socket, §20), Nav (§24)
Client (pure)Bytes, Decimal, Compression, DbDec (Std.Db.Decode decoders), Spa, the Std.Html render helpers
Client members of a mixed familyCsv parse / encode; Money formatting and allocation; Std.Config decoders; Std.Db.Table descriptions; Time formatting, parsing and calendar arithmetic (UTC or a named zone; the runtime embeds time/tzdata); Std.App view conversions
ServerSchema, Analytics, Cache, Email, PubSub, HttpStream, ServerStream, ServerWebSocket, Trace; Csv.parseStreamFromFile; Config.loadFromFile and the Sky.Config builders; the Table queries; Time.now / unixMillis / sleep / every; Std_App_livePort

spa_partition ffi_symbol_families_are_all_decided fails on a family that is in none of the lists, and on a listed member no stdlib module binds.

Exclusion is by definition, per module scope. A server-tainted binding is removed from the client by its DefId. The names a module writes bare that resolve to a tainted def are read from the resolver (ref_occs), so a server-only Net.send no longer removes the entry's own send. The report names the excluded binding with its module (Net.send).

A type the client names keeps its module in the client. A module with a server function used to be left out of the client whole unless the client reached one of its pure functions. Now any type or constructor a client module names (type_occs, constructor references) keeps a client copy of the module: its type declarations and pure defs, never a tainted def.

A client file keeps every import its code uses (v0.27.10). A server-only stdlib module (Std.Db, Sky.Core.File, …) stays imported in a client file (the entry, a module's client copy, Shared) while the finished file uses a name the import binds, and is dropped otherwise. The names are its alias, the names it spells, the constructors of each T(..) and every export of an exposing (..), read from the module's exports. A pure helper such as scope session id = Store.and_ [ Store.eq "id" (SqlString id) ] builds a value, not an effect, so it is copied, and its import Std.Db as Db exposing (SqlValue(..)) comes with it. Before, the gate saw only Db and SqlValue, and the entry and Shared dropped server-only imports without a gate, so the client failed with Undefined name: SqlString. The decision stays one of effects: a value of a server module's type is not server code, and a def that runs an effect is still never copied.

Shared brings the types its copied records name. A wire record copied into Shared can name a type of another module (at : Shape.Point). The references are read from type_occs inside the copied declarations; a stdlib type keeps its module's import line. (Until v0.30.0 a pure module was imported exposing (..) under the record's alias and a type of a server module was copied into Shared. §29 replaces both: the module is imported under a generated alias and the reference is qualified.)

A result Msg with captured arguments crosses whole. Cmd.perform task (Got url) is not a client-result RPC (§19), whose answer is the task result alone: it is a follow-up (§20), whose answer is the Msg Got url result. The stdlib Http.HttpResponse has a wire codec (Codec.auto over its three fields).

Patterns are read with the lexer. A constructor pattern's CST node can own the comment lines above the arm. The split reads the head and the arguments from non-trivia tokens, so a comment never changes how an arm is read.

init and update in any form. The generated backend and frontend call init () and update msg model by name. The synthesis defines them at top level whatever the App.app record held: an inline, let-bound or hoisted lambda becomes a function (its body kept, so the split reads its case and its model expression); a function under another name is copied under the canonical name; an eta-expanded update is update itself; anything else is eta-expanded. A module that already defines a different top-level update is an error naming both.

A model that is not a record crosses whole. The wire contract is per model field. A String, union or List model rides in one field, spaModel_, and every server branch reads and writes it whole. A wildcard or pattern model parameter (update msg _ =) is bound under an as in the regenerated update.

The user's source is checked first. A Std.App build for any target first type-checks the entry as written (App.run not rewritten), so an error in it is reported at the user's line, never at a rewritten App.runLive or in the synthesised or generated code. A record-literal argument whose field does not fit is reported at the field. The Std.App builders fix init's seed to (), so init : Page -> … is that one error, on every target.

Tests: the fixtures spa-client-crypto-aead, spa-pure-kernels, spa-tainted-name-scope, spa-server-module-types, spa-shared-foreign-type, spa-captured-result-msg, spa-arm-comment, spa-inline-init, spa-nonrecord-model and std-app-init-seed-error, each driven by a spa_split_flow.rs test that builds the backend and the wasm client; where a server branch runs, the test sends it to the split backend and to the Sky.Live build of the same source and compares the answers. Unit tests: spa_partition ffi_symbol_families_are_all_decided, client_crypto_opt_in_makes_the_keyed_crypto_primitives_placement_neutral, a_comment_above_an_arm_is_not_part_of_its_constructor; app_entry config_fields_get_their_canonical_top_level_name.

24. Dependency types, type identity and navigation (2026-09-29)

The split loads the dependencies the build loads. The analysis db (build::load_source_db, which the split, sky spa-partition, the diagrams and the fuzz harnesses read) loaded the fetched registry packages under .skydeps/ but not the local [dependencies] path packages. A record alias from a path package then named a missing module in the synthesised client entry, and the split failed with [update] type mismatch: Point vs record on a program sky check accepted. Both loaders now share build::load_registry_dependencies (registry packages, trusted) and build::load_path_dependency_sources (path packages, loaded as app modules: type-checked, and reported under their own path). The analysis db registers path modules as dependencies, not project modules, so the split treats them as the dependencies the generated projects declare.

Every type is resolved by its module, never its bare name. The codec resolver keyed the project's records and unions by bare name, and read a Msg payload's types from the syntax, which drops the qualifier. A payload of the stdlib's Cpace.Pending (device key material) was derived a codec as the app's own type alias Pending: the build failed, and the "a key never crosses a wire" rule was decided on the wrong type. Now:

A dependency's record crosses the wire. A record alias from a [dependencies] package (path or registry) is external: both generated projects carry the dependency, so Shared imports its module under a generated alias (import Geo.Shape as SpaTy_Geo_Shape_), names the type SpaTy_Geo_Shape_.Point, and derives its codec (autoGeo_Shape_PointCodec_). Two different project records with the same bare name on the wire were refused until v0.30.0 (the generated module named a project type by its bare name); since §29 each is named by its module and gets its own codec.

An error in derived code names the user's construct. The app's own source type-checks before the split runs, so a type or name error reported from the synthesised entry or a generated leg is a defect of the split. The build maps each one back (sky/src/split_diag.rs): a definition carried over unchanged is reported at the user's file and line; a rewritten one at the user's definition; a generated one (spaEncodeFollow_, spaModelBlank_, …) names the construct it came from (Msg, Model, init, the routes) and where it is. "The failure above is in the SYNTHESISED client entry" is gone.

Navigation (Std.Nav). Nav.pushUrl / Nav.replaceUrl / Nav.clearFragment are a client effect: an arm that only navigates stays in the client, and the wasm client applies the History API and routes like a link click (spaNavigate). A server arm that also navigates returns its navigation with the answer (v0.29.4): the server evaluates the command of the outcome it took (a case on a server read, a guard, a helper, a nested Cmd.batch), the runtime collects its Std.Nav leaves as data in batch order (Spa_collectScrolls, the returned-command wire version 2, beside the returned scrolls), and the client runs them after the answer renders, as Sky.Live runs them when the update returns. No navigation source is copied into the client, so its URL may use a value only the server has, and an Err branch or a refused guard navigates nowhere. Such an arm holds later Msgs (Spa.rpcScrollHold). A returned navigation is checked as a whole: a payload with an unknown field, a wrong type or an off-site URL is refused before any of its commands runs. A newer navigation cancels a returned one that has not run. An app whose navigations are all in client arms keeps its wire unchanged. A continuation arm that navigates is never settled on the server.

Tests: the fixtures spa-path-dep-record (with its lib/ package), spa-follow-bare-name and nav-cmds, driven by the spa_split_flow.rs tests a_record_alias_from_a_path_dependency_crosses_the_split, a_follow_up_payload_type_is_resolved_by_its_module_not_its_bare_name, a_device_key_on_a_continuation_is_still_refused, a_server_arm_navigation_returns_with_the_answer and a_server_arm_navigation_through_a_helper_returns_with_the_answer, the project tests spa_returned_navigation.rs; the unit tests spa_split::type_identity_tests and split_diag::tests; the browser e2e scripts/nav-e2e.sh (Sky.Live and web:app, Chrome and WebKit, strict CSP).

25. Sign-out ends the signed session (v0.27.0)

The split backend keeps no session object. It signs the session projection (the model fields of type Session / Maybe Session that a server branch writes) into the httpOnly sky_spa cookie (named sky_sid before v0.27.0, which it shared with Sky.Live; see "The cookie and old sessions" below), and verifies that cookie on every RPC, SSR render, console check and /_sky/sub request (§21). Before v0.27.0 the check was the signature and the 30-day exp only. A sign-out removed the cookie from the browser, but a copy of the cookie taken before sign-out (a stolen cookie, a second browser profile, a proxy log) still signed the user in until it expired. Sky.Live closed the same class in v0.27.0 by rotating the session id at sign-in and ending a revoked id in the shared store; the split backend now does the same with its signed token.

Each token carries a session id. Spa_signSession (runtime-go/rt/spa_session_revocation.go) stamps a random sid claim next to the projection claims. It keeps the id while a branch re-issues the same identity. When the identity changes (sign-in, a switch of account, a server branch that clears the session), it mints a new id and ends the old one, so the cookie from before the change stops working at once.

Sign-out ends the id. The wasm client calls POST /_rpc/__spaSignOut when the session field goes from Just to Nothing. The endpoint verifies the cookie, records its sid as ended for the rest of the token's lifetime, and clears the cookie. When the store cannot record the sign-out, the endpoint still clears the cookie but answers 503, so the failure is visible.

Verification refuses an ended id. Spa_verifySession is Auth.verifyToken plus two checks: the token has a sid, and the sid has not ended. A token without a sid (one signed before v0.27.0) is converted once (see below). When the store cannot answer, the cookie is refused and the failure is logged (spa.session-check.failed). The check never fails open.

Where the record lives. The record is an alias in the session store that Sky.Live uses for a retired session id (the sky_session_aliases table on sqlite and postgres, a sky:alias: key on redis), under the key prefix spa-sid:. It expires with the token it ends, and the store's own alias sweep removes it. The store is resolved as for Sky.Live: the operator's SKY_LIVE_STORE / SKY_LIVE_STORE_PATH, else the code (App.withConfig (WebConfig { store = … }), a top-level config with Sky.Config.withSessions), else a legacy sky.toml [live] store / storePath. The --target web:app synthesis carries App.withConfig and App.withBase into a spaServerConfig_ boot task (App.applyServerConfig), which the backend runs before it listens: the session store, its ttl and idleEvict, maxBodyBytes, csrf, and the base log, database and telemetry land in the builder layer, so an operator's variable still wins and a sky.toml default does not (v0.27.9; before, the synthesis dropped both builders and the backend saw only sky.toml and the environment). The boot line names the source: set by App.withConfig in the app's code. The backend's port is not taken from WebConfig: it listens on PORT (default 8951). A static-only backend (no server branch) runs no configuration task: it keeps no session, store or database for it to reach. The split also copies the runtime tables of a legacy sky.toml ([live] store / storePath, [database], [log], [analytics], [jobs], [env], [security]) into the backend manifest, for projects that still keep them; settings belong in code.

The boot log names the store, or says there is none. A backend with a signed session opens the store at boot and logs [sky.spa] session store (sign-out records): postgres (…). A backend with no signed session (no server branch writes a Session / Maybe Session model field) keeps no server-side session at all: the model lives in the browser. It opens no store and logs [sky.spa] session store: none. When a store is configured, the line names it and says which of three places set it:

A config binding writes SKY_LIVE_STORE inside the process, so the variable is not in /proc/<pid>/environ. --embed and [database] embedded = true never set a session store. The inline console keeps its own in-process memory store and logs it as [sky.live] sub-app /_sky/console session store: memory (…). That line is the console's, never the app's. (Before v0.27.4 the console printed the app's banner, [sky.live] session store: memory, and on a backend with no store it read as [live] store being ignored.)

StoreSign-out is refused on
none configuredthis host, across restarts (a sqlite file spa-sessions.db in the data dir, SKY_DATA_DIR else .skydata, beside the auto-minted signing secret)
memorythis process, until it restarts
sqlite at a shared pathevery process that opens the same file
postgres / redisevery replica

The cookie and old sessions. The cookie is sky_spa. A request that arrives with the old sky_sid is read only when that value is a Sky.Spa token (never a 32-hex Sky.Live id); the response sets sky_spa and expires the old one. A token signed before v0.27.0 has no sid. On its first request after the upgrade it is converted once and idempotently: the same claims and expiry, a fresh sid, and a record spa-legacy:<sha256(token)> in the sign-out store for the token's lifetime. A replay of the old token within 60 s gets the same new token; after that it is refused. A forged or expired token is never converted, and a store that is down converts nothing (fail closed). The conversion needs the same signing key as the old build: set SKY_SPA_SESSION_SECRET when the key file is not persisted.

The cookie's lifetime (v0.29.0). A sky_spa write that carries a token sets Max-Age to the session's lifetime, the same span as the token's exp, so the cookie and the token end together; before v0.29.0 the cookie had no Max-Age and a browser that clears session cookies on quit dropped a valid sign-in. The lifetime is 30 days. App.withSessionLifetime <seconds> sets it in code (the build carries it into the backend's boot task), and SKY_SPA_SESSION_LIFETIME (a Go duration such as 336h, or whole seconds) overrides both. The sign-out and legacy-clear writes keep Max-Age=0.

The signing key. A key minted in development is stored as .skydata/spa-session-secret.dev and is never read in production, so a development key copied into an image does not sign production sessions. A production process mints its own key; when it cannot persist it, it logs an ERROR and adds a line to the start-up report, because every restart would then sign everyone out. Set SKY_SPA_SESSION_SECRET (32 bytes or more) in production.

A deploy that changes the wire. Each build hashes its wire schema (the shared records and the route list) into <meta name="sky-wire">, and every /_rpc/ POST carries it in X-Sky-Wire. A backend that sees another hash answers 409 with X-Sky-Status: reload, before the handler runs. The client reloads once (guarded, so a mismatch cannot loop) and then says that the last action was not sent; a Msg is never replayed. A tab from before v0.27.0 sends no header, and the backend runs its server follow-ups inline, as v0.26.1 did.

A deployment with several replicas already sets SKY_SPA_SESSION_SECRET (every replica must verify with the same key). When that variable is set and no shared store is configured, the backend logs a warning when it first opens the store: a sign-out would then be refused only on the replica that served it. A store the operator configured that cannot be opened in production refuses every signed session (and logs why), rather than fall back to a per-process memory store. The backend tries to open it again every 30 seconds. In production with no store configured, a data dir where spa-sessions.db cannot be created is an error in the same way, and a backend with a session projection refuses to start (see docs/migration/v0.27.md#spa-sign-out-store); development keeps an in-memory fallback with a warning.

Cost. One store read per verified request (a primary-key lookup on sqlite or postgres, a GET on redis). A request with no session cookie reads nothing.

Tests: the Go unit tests in runtime-go/rt/spa_session_revocation_test.go (sign-out refuses the copied cookie, the id is kept for the same projection and rotated on a change, a token without a sid is refused, reserved claims, a forged cookie writes no record, fail closed when the store is down, the record outlives the store TTL and a reopen, expiry); the spa_split_flow.rs test spa_sign_out_revokes_the_signed_session_cookie on the fixture spa-session-revocation (two replicas sharing one sqlite store, both sign-out paths, a fresh sign-in, the default store across a restart); the unit tests spa_split::live_store_section_tests; and the browser e2e scripts/session-revocation-e2e.sh (Chrome / Chromium and WebKit, strict CSP: a copied live cookie works from a second browser, a copy taken before either sign-out does not).

26. Building the two legs: concurrency and the wasm-name handoff (v0.27.9)

sky build --target web:app (and every client target) builds the split as two child sky build processes: the native backend leg and the wasm frontend leg.

Concurrent or in order. The legs run at the same time when the machine's available memory holds both legs' sky process and Go peaks plus a 1 GB reserve (rust/crates/sky/src/leg_plan.rs), else one after the other. SKY_BUILD_PARALLEL=1 forces them together, SKY_BUILD_SERIAL=1 in order. When they run together, the parent sets each leg's go build -p from the memory they share (unless the user set SKY_GO_BUILD_JOBS / --go-jobs). A web bundle's .gz / .br are compressed by the parent, all assets at once, beside the backend leg when memory holds both.

The SSR wasm name. A backend that server-renders the first page names the frontend's main.<hash>.wasm in it, and the hash exists only once the frontend has built. The name is linked into the backend's generated skybuildinfo package (rt.SetSpaBuiltWasmName), a small package of its own, so the backend's main does not change with the frontend. In parallel the backend leg runs its Sky front end and a first go build (everything, main included) while the frontend builds; when the name arrives it rewrites the small package and builds again (one small compile and the link).

The handoff (rust/crates/project/src/spa_wasm_handoff.rs) is the backend child's standard input. The parent starts the backend with --spa-await-wasm-name-on-stdin and a piped stdin, and writes one line when the frontend leg ends: ok main.<hex>.wasm or failed, then closes the pipe. A delivery made before the backend started (the in-order path) is written as it starts.

The client's stamp is constant. The wasm client links a constant build stamp (build_stamp::client_stamp): nothing under GOOS=js reads it, and a per-commit value would change the wasm's bytes and its hashed name on every commit (a precompress cache miss, a new download for every browser, a new name for the backend to link). The backend keeps the real stamp at /_sky/buildinfo.

27. One Model wire for every whole-model branch (build speed)

A server branch that hands model to a helper reads the WHOLE model (§14 B1), and one whose result is a rebuilt model writes it whole. Before this change each such branch got its own MReq / MResp record and its own Codec.object … |> Codec.field … chain over every Model field, in Shared, which both legs compile. The generated source grew with branches × Model fields: a measured app with 100 whole-model branches and 200 Model fields generated 156k lines from 3.3k, and its backend leg spent 31 s in typecheck, 35 s in lowering and 4.75 GB of memory. The size is now linear in branches + fields:

Measured on a generated app (examples/62-app-notes grown to N groups of two Model fields and three arms; each SaveK hands model to an opaque helper), backend leg, before → after:

Ngenerated .sky linestypechecklower + emitmain.goleg wall
5049,310 → 18,1134.28 s → 0.29 s5.22 s → 0.69 s1.59 → 0.49 MB20.4 s → 7.9 s
100156,260 → 33,86330.9 s → 0.94 s35.2 s → 1.91 s5.20 → 0.88 MB85.7 s → 12.9 s
200550,160 → 65,363not run before → 3.33 snot run before → 6.54 s→ 1.69 MB→ 44.1 s

The generated source is now linear in N. Typecheck and lowering still grow faster than linearly, because every handler expression carries the full Model record type and the checker reads back one owned type per expression. That cost does not depend on how the wire is declared.

The spa_split_flow tests whole_model_branches_share_one_model_wire_codec (one Model field list, and the backend answers the flat JSON the previous client sent, byte for byte) and generated_wire_grows_linearly_with_whole_model_branches (Shared stays linear from N=25 to N=100) hold it; CodecConformanceTest pins that Codec.inline writes the same JSON as the flat record.

27.1 Every wire type is closed

The shared builder makes an open type in the Model wire fatal. spaModelWireFields_ is ONE annotated value (a CAF), so an any or a type variable in SpaModelWire_ is one fixed type for every whole-model request (the v0.27.0 value restriction), and the backend failed [E2012] ("the one type of a") at each Codec.inline .spaWholeModel_ spaModelWireFields_ use. The per-branch records before §27 hid the same gap, because each record's annotation filled its own any. Three shapes left a wire type open, and all are now named:

build_wire refuses any generated field type that still holds any or a type variable (open_type_word), so a future resolver gap fails the split with a clear message instead of [E2012] in generated code. The spa_split_flow test generated_wire_types_name_every_type_they_hold (fixture spa-wire-type-names) checks both legs of an app with all three shapes.

28. Generated code names nothing the app chose (v0.29.7)

The split writes code into the app's own modules (the backend and frontend Main, Shared, a sibling module that declares update). Before v0.29.7 that code named framework modules by the short names an app usually writes (Server.rpc, Codec.toJson, Cmd.none, Spa.rpc, Task.succeed) and added import Sky.Http.Server as Server (and Codec, System, Error, Ffi, Task, Maybe, Stream) only when the app did not import that module. Two faults had this one root:

Generated code now names each framework module only through an alias the split reserves (RESERVED_ALIASES in spa_split.rs): SpaServer_, SpaStream_, SpaCodec_, SpaSystem_, SpaError_, SpaFfi_, SpaTask_, SpaList_, SpaDict_, SpaMaybe_, SpaResult_, SpaString_, SpaSecret_, SpaCmd_, SpaSub_, SpaLib_ (Std.Spa), SpaApp_, plus the earlier SpaInitRpc_, SpaInitCodec_, SpaInitCmd_ and SpaMsgMod_. Generated type annotations qualify the framework types the same way (SpaServer_.Handler, SpaCodec_.Codec Item) and name builtin types (Task, Result, Error) bare, which no project can redefine. Every Sky file the split writes gets import <module> as <alias> for each reserved alias it uses (ensure_reserved_imports); a module may be imported twice, so the app's own imports stay exactly as written. An app whose module or import alias is one of the reserved names is refused with a message that names it. A value Shared copies from a sibling module (a codec of a module with a server effect) is app text: Shared imports each stdlib module that value names under the qualifier the sibling wrote (import Std.Codec as C), and each name it uses from an explicit exposing list. The sky fuzz harnesses use the same aliases. The Std.App to Spa.app synthesis that runs before the split (synthesize_spa_source in sky/src/main.rs) writes Spa., List., Task. and App. into the app's entry: it imports each under that exact name even when the entry already imports the module under another alias, and refuses an entry where a project module or another alias already takes the name. Test: project/tests/spa_split_reserved_aliases.rs (project modules Server, Codec and Error, import Sky.Core.Task as T, import Sky.Http.Server as Http, a sibling codec written with C.; both generated halves type-check).

29. Shared names every user type by its module (v0.30.0)

Three multi-module shapes passed sky check and failed in the split. Each came from Shared taking a user type into its own scope, by a copy or by an exposing (..) import:

The rule. Shared copies the declarations of a module only when it cannot import it: the entry, and every module whose import closure (as the user wrote it) reaches a module R whose generated copy imports Shared. R holds the module of update and of the Msg union (the regenerated update and the Applied<Msg> variants name the wire records), the module of an init whose command became an RPC, a server module whose client copy strips a copied declaration, and a module that names a union Shared owns (GAP-A). R grows with the copy set, so the two are computed to a fixpoint. A module that does not export a wire type or codec Shared must name is copied too. Every other module that declares a wire type or a referenced codec is imported once, qualified only, under a generated alias (import Store as SpaTy_Store_), as a dependency module already was (§24). A server module is imported too: since §23 its client copy keeps its type declarations and pure codecs, and the backend has the whole module. No module copy loses its own types, so an alias chain resolves in the user's own scope.

Every generated reference is qualified. ProjectShapes::type_ref, ctor_ref and each codec binding's reference name a type, constructor or codec of another module as SpaTy_<Mod>_.<Name>; an entry type stays bare (Shared declares it). The auto-derived codec names (auto<N>Codec_) are module-mangled when two declarations share a bare name (autoP1_RefusalCodec_). A copied declaration's type references and a copied codec's value references (read from type_occs and ref_occs) follow the same rule. Once the copy set is known, the qualifier of a copied module is removed, and every generated file gets one import <Mod> as SpaTy_<Mod>_ for each alias it uses (finish_type_refs).

The cycle invariant is checked. A module Shared names through its alias must not reach R; the split refuses such a module with the import path. After the trees are written, check_shared_acyclic refuses any import cycle through Shared in either generated tree and names it, so a shape the copy set missed is a split refusal, never a raw [E1010] from a generated file.

The GAP-A shape (a Msg module that also declares wire records and unions) is unchanged: the Msg module is in R, so its wire declarations are copied into Shared and its unions moved there, as before.

Tests: the fixtures spa-alias-chain, spa-alias-chain-msg, spa-shared-ctor-clash, spa-shared-cycle and spa-shared-cycle-chain (Wire -> Extra -> Inner -> Tags), driven by the spa_split_flow.rs tests a_record_alias_chain_through_server_modules_crosses_the_split, a_record_alias_chain_through_the_msg_module_crosses_the_split, generated_shared_code_names_user_types_and_constructors_qualified and shared_imports_no_module_that_imports_shared, each of which builds both legs and sends a server branch to the split backend; a_copied_wire_record_brings_the_types_it_names (rewritten for the qualified form); the project tests two_wire_records_with_one_name_split_with_one_codec_each and one_module_under_several_aliases_splits_through_generated_aliases.