Skip to main content

bynk_check/
wire.rs

1//! #855: the wire-contract IR — the shape a Bynk type takes crossing a
2//! context boundary, derived once from the AST + type table so both the
3//! emitter's codec generation and the editor's "wire contract" peek render
4//! the *same* derivation instead of two hand-synchronised ones.
5//!
6//! **The seam:** *`bynk-check` says what the boundary is. `bynk-emit` says
7//! how that reads as TypeScript.*
8//!
9//! This is the system model's boundary half. It lives here, not in
10//! `bynk-model`, because the checker's own boundary checks read it
11//! (crate-hygiene B4, #3012).
12//!
13//! Crossing this module boundary is legal for `BaseType`, `PredKind`,
14//! `TypeRef`, `Expr`, `TypeDecl` (all `bynk-syntax`) — the vocabulary a
15//! boundary type is built from. It is **not** legal for any TS-token string,
16//! `pred_condition_and_message` (`bynk-emit/src/emitter.rs`, stays put),
17//! `wire_default_node` (`bynk-emit/src/emitter/default_value.rs`, stays
18//! put — a default's *wire literal* is a rendering, not a boundary fact),
19//! or the `Qual` type-name→TS-namespace-prefix map (`bynk-emit`'s
20//! `serialisation.rs`; see the [`Provenance`] doc for why it cannot move
21//! here). `bynk-emit` renders this IR into TypeScript; it does not re-derive
22//! it.
23//!
24//! **Derived from AST + type table, not `checker::Ty`.** `Ty::Named { name,
25//! kind, args }` carries no refinement predicates, so a `Ty`-based
26//! derivation would still need this same type-table lookup for `PredKind`s —
27//! `Ty` would buy only generic substitution, which the moved walks below
28//! already implement directly over `TypeRef`. `contract.rs` (this crate)
29//! also derives straight from the AST + type table and must not depend on
30//! checker output being available; this module keeps the same shape of
31//! dependency.
32//!
33//! **This IR is *not* `contract.rs`'s canonical form**, and the two must
34//! never be unified — they disagree on purpose, on every axis that matters:
35//!
36//! | | `contract.rs` (hash) | `wire.rs` (this module) |
37//! |---|---|---|
38//! | predicates | sorted, deduped | **declaration order**, not deduped |
39//! | record fields | sorted by name | declaration order (emitted key order) |
40//! | sum variants | sorted by name | declaration order (`switch` arm order) |
41//! | opaque predicate | **elided** — unobservable to the consumer | **present** — the owner still re-validates |
42//!
43//! `contract.rs:248` documents the sorting as a *precondition* for hash
44//! correctness — hashing predicates in source order "would make two contexts
45//! that agree perfectly fail closed against each other." The hash is a
46//! **type identity** (order-insensitive by design); this module's shapes are
47//! an **emission order** (order-sensitive by necessity, since a JS `switch`
48//! and an inlined `if` chain both have a literal source order a reader can
49//! see). Merging them would create the exact spurious-409 failure the hash
50//! exists to prevent. What the two genuinely share — and what a cross-check
51//! test elsewhere asserts — is *boundary-type reachability*, not shape.
52
53use std::collections::{BTreeSet, HashMap};
54use std::sync::Arc;
55
56use bynk_syntax::ast::*;
57
58/// I4 (#1970): the declaration shapes this module's public API is
59/// parameterised by ([`collect_codec_closure`] walks `TypeRef` roots over a
60/// `TypeDecl` table, whose `body` is a `TypeBody`), re-exported so a renderer
61/// over that API (`bynk-emit`'s TypeScript client) names them from here — the
62/// P6.27 / P6.49 precedent `project_model`'s `TypeDecl` re-export follows.
63pub use bynk_syntax::ast::{TypeBody, TypeRef};
64
65// ---------------------------------------------------------------------
66// Core vocabulary
67// ---------------------------------------------------------------------
68
69/// The JSON value shape a [`BaseType`] occupies on the wire. Replaces
70/// `bynk-emit`'s `ts_base_for_serialisation` *classification* — the TS-token
71/// spelling of each kind (`"number"`, `"string"`, …) stays in `bynk-emit`,
72/// since a TS token is exactly what this seam excludes.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum JsonKind {
75    Number,
76    String,
77    Boolean,
78    Object,
79    Array,
80    Null,
81}
82
83/// The JSON kind a base type wires as. Same mapping as the `ts_base_for_serialisation`
84/// it replaces: `Int`/`Float`/`Duration`/`Instant` → `Number` (all four erase to a TS
85/// `number`), `String`/`Bytes` → `String` (a `Bytes` wires as a base64 string, ADR
86/// 0142 D5), `Bool` → `Boolean`.
87pub fn json_kind_of(b: BaseType) -> JsonKind {
88    match b {
89        BaseType::Int | BaseType::Float | BaseType::Duration | BaseType::Instant => {
90            JsonKind::Number
91        }
92        BaseType::String | BaseType::Bytes | BaseType::Decimal => JsonKind::String,
93        BaseType::Bool => JsonKind::Boolean,
94    }
95}
96
97/// An extra structural guard a base-typed wire value must pass beyond its
98/// `typeof`: an `Int`/`Instant` must be whole, a `Float` must be finite.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum BaseGuard {
101    Integral,
102    Finite,
103}
104
105/// What a structural-mismatch error reports as `expected` — the vocabulary a
106/// renderer needs to explain *why* a wire value was rejected, independent of
107/// the TS spelling of the check that rejected it.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum Expected {
110    Json(JsonKind),
111    Integer,
112    FiniteNumber,
113    Base64String,
114    SumVariantKind,
115}
116
117/// Where a boundary type's declaration lives relative to the module doing
118/// the crossing.
119///
120/// Carries the owner's *qualified unit name*, never a TS namespace prefix —
121/// the IR picks the re-validation *strategy* ([`Revalidation`]); `bynk-emit`
122/// alone knows how to spell that owner as an `import type * as <ns>` alias
123/// (`bynk-emit/src/emitter/serialisation.rs`'s `Qual`/`qual_prefix`, built
124/// per-emission from build-mode facts this crate does not have). Unifying
125/// the two would drag `BuildTarget` into the checker.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub enum Provenance {
128    /// The emitting module's own declaration: re-validation routes through
129    /// the type's own constructor.
130    Owned,
131    /// A type declared by another unit and reached through it — `owner_unit`
132    /// is that unit's qualified name (`commerce.payment`, never a TS
133    /// namespace spelling).
134    Consumed { owner_unit: String },
135}
136
137/// #661 Decisions C/D plus the owner path, stated once: how a boundary
138/// scalar's refinement is re-checked on the way in, given who declared it
139/// and where the check is happening.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum Revalidation {
142    /// Owner's own module: run the type's own `.of`.
143    ViaConstructor,
144    /// Consumed + transparent (Decision D): re-check each predicate inline,
145    /// since the consumer knows the shape by declaration even without an
146    /// importable constructor.
147    Inline,
148    /// Consumed + opaque (Decision C): the predicate is the owner's secret —
149    /// cast structurally after the base check; skew is caught by the
150    /// contract hash instead.
151    StructuralOnly,
152    /// `Bytes`: decoded, not cast — the one base type whose wire value is
153    /// not a direct cast of its erased representation. Applies regardless of
154    /// provenance, mirroring `emit_refined`'s early return to the dedicated
155    /// `Bytes` codec before the owned/consumed split is even considered.
156    Base64Decode,
157    /// `Decimal` (#2622): a canonical decimal string on the wire, parsed (never
158    /// cast) into the runtime's `{ coefficient, scale }` value. Like `Bytes`,
159    /// it takes a dedicated codec before the owned/consumed split.
160    DecimalParse,
161}
162
163/// A named boundary type's declared shape, refinement-independent of who is
164/// asking. `owner`-relative facts ([`Revalidation`]) live one level down, in
165/// [`WireScalar`] — the shape itself does not vary with provenance, only how
166/// hard the receiver re-checks it.
167#[derive(Debug, Clone)]
168pub struct WireType {
169    pub name: String,
170    /// The codec-name suffix this type resolves to (`Order`, or a
171    /// monomorphised generic's `Paginated_User`). Equal to `name` for every
172    /// non-generic declaration `wire_type` produces; kept as its own field
173    /// because a future generic-instantiation `WireType` (Phase 2+) needs
174    /// the two to diverge the same way `serialisation.rs`'s `fn_suffix` /
175    /// `ts_type` pair already does.
176    pub codec_suffix: String,
177    pub provenance: Provenance,
178    pub body: WireBody,
179}
180
181#[derive(Debug, Clone)]
182pub enum WireBody {
183    Scalar(WireScalar),
184    Record { fields: Vec<WireField> },
185    Sum(WireSum),
186}
187
188/// A refined- or opaque-base-type boundary scalar.
189#[derive(Debug, Clone)]
190pub struct WireScalar {
191    pub base: BaseType,
192    pub json: JsonKind,
193    /// `true` for `opaque BaseType`, `false` for a transparent refined type.
194    pub opaque: bool,
195    /// **Declaration order**, not sorted, not deduped — this is the
196    /// highest-risk drift trap between this IR and `contract.rs`'s canonical
197    /// form (see the module doc's comparison table). `Inline` revalidation
198    /// emits one check per predicate in exactly this order.
199    pub predicates: Vec<PredKind>,
200    /// The base-type guards this scalar's `Inline` revalidation applies,
201    /// *before* the declared predicates. Mirrors
202    /// `emit_inline_refinement_checks` exactly: `Int` guards `Integral`,
203    /// `Float` guards `Finite` — deliberately **not** `Instant`, which is
204    /// guarded at record-*field* position (`emit_field_deserialise`'s
205    /// `TypeRef::Base` arm) but not here. That asymmetry already exists in
206    /// the emitter this IR was extracted from; it is preserved verbatim
207    /// rather than "fixed" by this move, since fixing it would be a
208    /// behaviour change this phase must not make. (See `field_base_guards`
209    /// for the field-position set, which does include `Instant`.)
210    pub base_guards: Vec<BaseGuard>,
211    pub revalidation: Revalidation,
212}
213
214/// One field of a boundary record, in **declaration order** (the emitted
215/// JSON key order).
216#[derive(Debug, Clone)]
217pub struct WireField {
218    pub name: String,
219    pub shape: WireRef,
220    /// The JSON path segment this field contributes to a validation error's
221    /// `path` (`` `${path}.<segment>` ``) — equal to `name` today; kept
222    /// distinct because a future field-rename annotation would move the wire
223    /// key without moving the path segment a hover/error should still name.
224    pub path_segment: String,
225    /// The field's default initialiser, if any, carried as raw AST — its
226    /// *wire-JSON literal* rendering is `wire_default_node` (`bynk-emit`,
227    /// over `field_default_value`'s tree), which stays in `bynk-emit` per the
228    /// module doc: a default's lowered literal is a rendering, not a boundary
229    /// fact.
230    pub default: Option<(Expr, TypeRef)>,
231    /// #1969: the field's inline refinement (`qty: Int where Positive`), in
232    /// declaration order, checked on decode after the field's own codec. Empty
233    /// for an unrefined field and for every sum-variant payload field (the
234    /// grammar gives those no `where`).
235    pub predicates: Vec<PredKind>,
236}
237
238/// #1969: the JSON key a sum value's variant name travels under (`{"kind":
239/// "Circle", …}`). Part of the published wire format, version 1
240/// ([`crate::wire_format`]); the in-memory discriminant is `tag`.
241pub const WIRE_DISCRIMINANT: &str = "kind";
242
243/// A boundary sum type. The wire and in-memory discriminants are carried
244/// side by side because the codec's whole job is translating between them —
245/// `memory_discriminant` is the softest part of this seam (a host
246/// representation choice, not a wire fact); moving it back into `bynk-emit`
247/// alone is a one-field change if a reviewer objects.
248#[derive(Debug, Clone)]
249pub struct WireSum {
250    /// Always [`WIRE_DISCRIMINANT`].
251    pub wire_discriminant: &'static str,
252    pub memory_discriminant: &'static str,
253    pub variants: Vec<WireVariant>,
254}
255
256/// One variant of a [`WireSum`], in **declaration order** (the emitted
257/// `switch` arm order).
258#[derive(Debug, Clone)]
259pub struct WireVariant {
260    pub name: String,
261    pub payload: Vec<WireField>,
262}
263
264/// Why a [`WireRef`] carries no generated codec — the runtime-owned error
265/// family, which has no `TypeDecl` to derive a shape from.
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum UncheckedReason {
268    /// An `Effect[T]` reached in a field/element position (never a top-level
269    /// handler return, which strips it before it gets here).
270    Effect,
271    ValidationError,
272    DecodeError,
273    HttpResult,
274    QueueResult,
275    /// #1883, slice 1a: an `Asset` (rejected at boundaries by the checker).
276    Asset,
277}
278
279/// The resolved shape of one `TypeRef` occurrence — a field's type, a sum
280/// variant payload's type, a generic instantiation's argument. Mirrors the
281/// exhaustive dispatch `bynk-emit`'s `emit_field_deserialise` performs today,
282/// one level removed from any TS string.
283#[derive(Debug, Clone)]
284pub enum WireRef {
285    Base {
286        base: BaseType,
287        json: JsonKind,
288        guards: Vec<BaseGuard>,
289        expected: Expected,
290    },
291    /// `Bytes`: base64 string on the wire, decoded (never cast) into a
292    /// `Uint8Array`-shaped value.
293    Bytes,
294    /// `Decimal` (#2622): a canonical decimal string on the wire, parsed into
295    /// a `{ coefficient, scale }` value.
296    Decimal,
297    /// A named boundary type — resolve further via the model's own
298    /// `WireType` table.
299    Named { name: String },
300    /// A generic instantiation — `Result[A, B]`, `Option[A]`, `List[A]`,
301    /// `Map[K, V]`, or a generic record/sum application (`Paginated[User]`).
302    /// `key` is the same codec-suffix string in every case
303    /// (`Result_Int_String`, `Paginated_User`, …) — resolve further via the
304    /// model's `instantiations` list, keyed by [`WireInst::ts_name`].
305    Inst { key: String },
306    /// `()` — no wire content; the wire slot is `null`, the value `undefined`.
307    Unit,
308    /// The runtime-owned error family (plus a stray field-position `Effect`)
309    /// — cast through unchecked, since there is no `TypeDecl` to derive a
310    /// shape from. See [`UncheckedReason`].
311    Unchecked { reason: UncheckedReason },
312}
313
314/// The set of `TypeRef`s a boundary walk resolved and their re-derived
315/// structural shapes — the single source of truth both the emitter's codec
316/// generation and the wire-contract peek render from.
317#[derive(Debug, Clone)]
318pub struct WireModel {
319    pub types: Vec<WireType>,
320    pub instantiations: Vec<WireInst>,
321    /// The generic-record names (v0.174 #592) that are transitively
322    /// self-referential and therefore have no finite monomorphised codec set
323    /// — rejected at the boundary before emit, carried here as the same
324    /// membership set the codec walks use to short-circuit.
325    pub recursive: BTreeSet<String>,
326}
327
328// ---------------------------------------------------------------------
329// Moved verbatim from `bynk-emit/src/emitter/serialisation.rs` (pure,
330// AST-only walks — no TS string ever touches these). `pub(crate)` in the
331// original became `pub` here; everything else is unchanged apart from the
332// renames the plan calls for (`inner_ts_name` → `codec_suffix`, `app_ts_name`
333// → `inst_codec_suffix`).
334//
335// `GenericInst` moved as `WireInst` but **keeps its original variant names**
336// (`ResultInst`/`OptionInst`/…, not the plan's bare `Result`/`Option`/…):
337// `bynk-emit/src/emitter/serialisation.rs`'s `emit_generic_helpers_qualified`
338// — a codec-*emission* function, out of scope for this phase — pattern-matches
339// those variants directly, and this phase must not touch codec-emission call
340// sites.
341//
342// #855 (Phase 2 step 9, decided): the plan allowed renaming to the bare
343// spelling here since this step touches `emit_generic_helpers_qualified`
344// anyway — but the RecordInst/SumInst arms it touches already consume the
345// IR's `WireField`/`WireSum` shapes (steps 7/8's byte-identical rewrite of
346// `emit_record_codec`/`emit_sum_codec` covers them), and the other four arms
347// (`ResultInst`/`OptionInst`/`ListInst`/`MapInst`) build their TS inline —
348// they were never going to move to a `Result`/`Option`/`List`/`Map` spelling
349// of *this* enum either way. A pure rename would touch six match arms here
350// and this module's doc/tests for zero behavioural or architectural gain, so
351// the `*Inst`-suffixed names are kept. Revisit only if a future consumer
352// (e.g. the Phase 3+ peek) finds the bare spelling actually reads better at
353// its own call sites.
354// ---------------------------------------------------------------------
355
356/// Compute the set of type names (transitively reachable) that need
357/// serialise/deserialise helpers for this context: any type used in the
358/// argument or return position of a service handler exposed by this
359/// context, walked through record fields, sum payloads, and the generic
360/// type parameters of Result/Option/Effect.
361pub fn collect_boundary_types(
362    types: &HashMap<String, Arc<TypeDecl>>,
363    services: &HashMap<String, ServiceDecl>,
364    // v0.96 (ADR 0124): rehydration is a trust boundary — an agent's persisted
365    // `store`-field types are validated on load, so they need their deserialisers
366    // emitted. Register every store field's kind-argument types (the element /
367    // key / value types of `Cell`/`Map`/`Set`/`Cache`/`Log`).
368    agents: &HashMap<String, AgentDecl>,
369    // #1678: further boundary positions to root the walk at. On the `workers`
370    // target an agent call crosses a Durable Object `fetch`, so the emitter
371    // passes every agent handler's parameter and return types here.
372    extra_roots: &[TypeRef],
373) -> Vec<String> {
374    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
375    let mut out: Vec<String> = Vec::new();
376    let mut stack: Vec<String> = Vec::new();
377    let recursive_set = recursive_generic_names(types);
378    let recursive = &recursive_set;
379    for r in extra_roots {
380        collect_type_names(r, &mut stack, types, recursive);
381    }
382
383    let mut svc_names: Vec<&String> = services.keys().collect();
384    svc_names.sort();
385    for name in svc_names {
386        let service = &services[name];
387        for h in &service.handlers {
388            for p in &h.params {
389                collect_type_names(&p.type_ref, &mut stack, types, recursive);
390            }
391            collect_type_names(&h.return_type, &mut stack, types, recursive);
392        }
393    }
394
395    let mut agent_names: Vec<&String> = agents.keys().collect();
396    agent_names.sort();
397    for name in agent_names {
398        for f in &agents[name].store_fields {
399            for arg in &f.kind.args {
400                collect_type_names(arg, &mut stack, types, recursive);
401            }
402        }
403        // State-migrations S2 (#2224): a `migrate` step decodes stored bytes
404        // through its old record type, so that type needs a deserialiser too.
405        for m in &agents[name].migrations {
406            if let Some(old) = &m.old {
407                collect_type_names(&old.type_ref, &mut stack, types, recursive);
408            }
409        }
410    }
411
412    while let Some(name) = stack.pop() {
413        if !seen.insert(name.clone()) {
414            continue;
415        }
416        out.push(name.clone());
417        let Some(decl) = types.get(&name) else {
418            continue;
419        };
420        match &decl.body {
421            TypeBody::Record(r) => {
422                for f in &r.fields {
423                    collect_type_names(&f.type_ref, &mut stack, types, recursive);
424                }
425            }
426            TypeBody::Sum(s) => {
427                for v in &s.variants {
428                    for p in &v.payload {
429                        collect_type_names(&p.type_ref, &mut stack, types, recursive);
430                    }
431                }
432            }
433            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
434        }
435    }
436
437    out.sort();
438    out
439}
440
441/// v0.174 (#592): the set of generic-record names that are *recursive* — they
442/// transitively contain themselves, so they have no finite monomorphised codec
443/// (rejected at the boundary by the checker before emit). Precomputed once per
444/// collector so the per-`App` guard in the codec walks is an O(1) membership test
445/// rather than a fresh graph reachability walk at every occurrence.
446fn recursive_generic_names(
447    types: &HashMap<String, Arc<TypeDecl>>,
448) -> std::collections::HashSet<String> {
449    types
450        .iter()
451        .filter(|(_, d)| !d.type_params.is_empty())
452        .map(|(n, _)| n.clone())
453        .filter(|n| generic_record_is_recursive(n, types))
454        .collect()
455}
456
457fn collect_type_names(
458    t: &TypeRef,
459    stack: &mut Vec<String>,
460    types: &HashMap<String, Arc<TypeDecl>>,
461    recursive: &std::collections::HashSet<String>,
462) {
463    match t {
464        TypeRef::Named(id) => stack.push(id.name.clone()),
465        // Query/Stream/Connection types carry no boundary-collectable user
466        // types (non-boundary).
467        TypeRef::Query(..)
468        | TypeRef::Stream(..)
469        | TypeRef::Connection(..)
470        | TypeRef::History(..) => {}
471        // v0.174 (#592): a generic-record instantiation is boundary-serialisable
472        // through its monomorphised codec (`serialise_Paginated_User`). The
473        // *named* helpers that codec calls come from its concrete field types —
474        // the type arguments (`User`) and any non-parameter named field types
475        // (`Envelope[T] = { meta: Metadata, … }`) — so walk the substituted
476        // fields. A *recursive* generic record has no finite codec set and is
477        // rejected at the boundary before emit; the guard here is defence in
478        // depth so this walk can never fail to terminate.
479        TypeRef::App { name, args, .. } => {
480            if recursive.contains(&name.name) {
481                return;
482            }
483            // #593: a generic-sum instantiation's codec (`serialise_ApiResult_User`)
484            // likewise calls the named helpers of its *substituted variant
485            // payloads* (`serialise_User` for `Loaded(value: T)` at `T = User`),
486            // so walk those the same way records walk their fields.
487            if let Some(fields) = record_inst_fields(&name.name, args, types) {
488                for (_, ft) in &fields {
489                    collect_type_names(ft, stack, types, recursive);
490                }
491            } else if let Some(variants) = sum_inst_variants(&name.name, args, types) {
492                for (_, payload) in &variants {
493                    for (_, ft) in payload {
494                        collect_type_names(ft, stack, types, recursive);
495                    }
496                }
497            }
498        }
499        // v0.20a: function types carry no user-named types to collect and are
500        // rejected at boundaries anyway.
501        TypeRef::Fn(..) => {}
502        TypeRef::Result(a, b, _) => {
503            collect_type_names(a, stack, types, recursive);
504            collect_type_names(b, stack, types, recursive);
505        }
506        TypeRef::Option(a, _) => collect_type_names(a, stack, types, recursive),
507        TypeRef::Effect(a, _) => collect_type_names(a, stack, types, recursive),
508        TypeRef::HttpResult(a, _) => collect_type_names(a, stack, types, recursive),
509        // v0.20b: collections serialise element-/entry-wise; their inner
510        // named types need helpers.
511        TypeRef::List(a, _) | TypeRef::Set(a, _) => collect_type_names(a, stack, types, recursive),
512        TypeRef::Map(k, v, _) => {
513            collect_type_names(k, stack, types, recursive);
514            collect_type_names(v, stack, types, recursive);
515        }
516        TypeRef::Base(_, _)
517        | TypeRef::QueueResult(_)
518        | TypeRef::Asset(_)
519        | TypeRef::RequestHeaders(_)
520        | TypeRef::RequestQuery(_)
521        | TypeRef::RequestCookies(_)
522        | TypeRef::TokenClaims(_)
523        | TypeRef::BoundaryRejection(_)
524        | TypeRef::ValidationError(_)
525        | TypeRef::DecodeError(_)
526        | TypeRef::Unit(_) => {}
527    }
528}
529
530/// v0.174 (#592): substitute a generic record's declared field type — replacing
531/// each type-parameter name with the concrete argument type-ref — so a
532/// per-instantiation codec sees fully concrete field types.
533/// `Paginated[User]`'s `items: List[T]` becomes `items: List[User]`.
534fn subst_type_ref(t: &TypeRef, subst: &HashMap<String, TypeRef>) -> TypeRef {
535    match t {
536        TypeRef::Named(id) => match subst.get(&id.name) {
537            Some(replacement) => replacement.clone(),
538            None => t.clone(),
539        },
540        TypeRef::App { name, args, span } => TypeRef::App {
541            name: name.clone(),
542            args: args.iter().map(|a| subst_type_ref(a, subst)).collect(),
543            span: *span,
544        },
545        TypeRef::Result(a, b, s) => TypeRef::Result(
546            Box::new(subst_type_ref(a, subst)),
547            Box::new(subst_type_ref(b, subst)),
548            *s,
549        ),
550        TypeRef::Option(a, s) => TypeRef::Option(Box::new(subst_type_ref(a, subst)), *s),
551        TypeRef::Effect(a, s) => TypeRef::Effect(Box::new(subst_type_ref(a, subst)), *s),
552        TypeRef::HttpResult(a, s) => TypeRef::HttpResult(Box::new(subst_type_ref(a, subst)), *s),
553        TypeRef::List(a, s) => TypeRef::List(Box::new(subst_type_ref(a, subst)), *s),
554        TypeRef::Set(a, s) => TypeRef::Set(Box::new(subst_type_ref(a, subst)), *s),
555        TypeRef::Map(k, v, s) => TypeRef::Map(
556            Box::new(subst_type_ref(k, subst)),
557            Box::new(subst_type_ref(v, subst)),
558            *s,
559        ),
560        TypeRef::Query(a, s) => TypeRef::Query(Box::new(subst_type_ref(a, subst)), *s),
561        TypeRef::Stream(a, s) => TypeRef::Stream(Box::new(subst_type_ref(a, subst)), *s),
562        TypeRef::Connection(a, s) => TypeRef::Connection(Box::new(subst_type_ref(a, subst)), *s),
563        TypeRef::History(a, s) => TypeRef::History(Box::new(subst_type_ref(a, subst)), *s),
564        TypeRef::Fn(ps, r, s) => TypeRef::Fn(
565            ps.iter().map(|p| subst_type_ref(p, subst)).collect(),
566            Box::new(subst_type_ref(r, subst)),
567            *s,
568        ),
569        TypeRef::Base(..)
570        | TypeRef::QueueResult(_)
571        | TypeRef::Asset(_)
572        | TypeRef::RequestHeaders(_)
573        | TypeRef::RequestQuery(_)
574        | TypeRef::RequestCookies(_)
575        | TypeRef::TokenClaims(_)
576        | TypeRef::BoundaryRejection(_)
577        | TypeRef::ValidationError(_)
578        | TypeRef::DecodeError(_)
579        | TypeRef::Unit(_) => t.clone(),
580    }
581}
582
583/// #1846: `t` with each type `renames` names renamed, wherever it is named:
584/// a bare name, and the base of a generic application (`Envelope[Int]`),
585/// which `subst_type_ref` leaves alone because a type parameter is never
586/// applied. `bynk-emit` renames a consumed context's unexported types with it.
587pub fn rename_type_ref(t: &TypeRef, renames: &HashMap<String, String>) -> TypeRef {
588    match t {
589        TypeRef::Named(id) => match renames.get(&id.name) {
590            Some(to) => TypeRef::Named(Ident {
591                name: to.clone(),
592                span: id.span,
593            }),
594            None => t.clone(),
595        },
596        TypeRef::App { name, args, span } => TypeRef::App {
597            name: match renames.get(&name.name) {
598                Some(to) => Ident {
599                    name: to.clone(),
600                    span: name.span,
601                },
602                None => name.clone(),
603            },
604            args: args.iter().map(|a| rename_type_ref(a, renames)).collect(),
605            span: *span,
606        },
607        TypeRef::Result(a, b, s) => TypeRef::Result(
608            Box::new(rename_type_ref(a, renames)),
609            Box::new(rename_type_ref(b, renames)),
610            *s,
611        ),
612        TypeRef::Option(a, s) => TypeRef::Option(Box::new(rename_type_ref(a, renames)), *s),
613        TypeRef::Effect(a, s) => TypeRef::Effect(Box::new(rename_type_ref(a, renames)), *s),
614        TypeRef::HttpResult(a, s) => TypeRef::HttpResult(Box::new(rename_type_ref(a, renames)), *s),
615        TypeRef::List(a, s) => TypeRef::List(Box::new(rename_type_ref(a, renames)), *s),
616        TypeRef::Set(a, s) => TypeRef::Set(Box::new(rename_type_ref(a, renames)), *s),
617        TypeRef::Map(k, v, s) => TypeRef::Map(
618            Box::new(rename_type_ref(k, renames)),
619            Box::new(rename_type_ref(v, renames)),
620            *s,
621        ),
622        TypeRef::Query(a, s) => TypeRef::Query(Box::new(rename_type_ref(a, renames)), *s),
623        TypeRef::Stream(a, s) => TypeRef::Stream(Box::new(rename_type_ref(a, renames)), *s),
624        TypeRef::Connection(a, s) => TypeRef::Connection(Box::new(rename_type_ref(a, renames)), *s),
625        TypeRef::History(a, s) => TypeRef::History(Box::new(rename_type_ref(a, renames)), *s),
626        TypeRef::Fn(ps, r, s) => TypeRef::Fn(
627            ps.iter().map(|p| rename_type_ref(p, renames)).collect(),
628            Box::new(rename_type_ref(r, renames)),
629            *s,
630        ),
631        TypeRef::Base(..)
632        | TypeRef::QueueResult(_)
633        | TypeRef::Asset(_)
634        | TypeRef::RequestHeaders(_)
635        | TypeRef::RequestQuery(_)
636        | TypeRef::RequestCookies(_)
637        | TypeRef::TokenClaims(_)
638        | TypeRef::BoundaryRejection(_)
639        | TypeRef::ValidationError(_)
640        | TypeRef::DecodeError(_)
641        | TypeRef::Unit(_) => t.clone(),
642    }
643}
644
645/// v0.174 (#592): the concrete `(field-name, field-type)` list for a generic
646/// record instantiation `Name[args…]` — the declared fields with every type
647/// parameter substituted by the matching argument. Returns `None` if `name` is
648/// not a declared generic record or the arity does not match (both guaranteed
649/// impossible by the checker, so this is purely defensive).
650pub fn record_inst_fields(
651    name: &str,
652    args: &[TypeRef],
653    types: &HashMap<String, Arc<TypeDecl>>,
654) -> Option<Vec<(String, TypeRef)>> {
655    let decl = types.get(name)?;
656    let TypeBody::Record(r) = &decl.body else {
657        return None;
658    };
659    if decl.type_params.len() != args.len() {
660        return None;
661    }
662    let subst: HashMap<String, TypeRef> = decl
663        .type_params
664        .iter()
665        .map(|p| p.name.name.clone())
666        .zip(args.iter().cloned())
667        .collect();
668    Some(
669        r.fields
670            .iter()
671            .map(|f| (f.name.name.clone(), subst_type_ref(&f.type_ref, &subst)))
672            .collect(),
673    )
674}
675
676/// #593: the concrete `(variant-name, [(field-name, field-type)])` list for a
677/// generic sum instantiation `Name[args…]` — the declared variants with every
678/// type parameter substituted by the matching argument. The sum analogue of
679/// [`record_inst_fields`]; `None` (defensively) if `name` is not a declared
680/// generic sum or the arity does not match.
681#[allow(clippy::type_complexity)]
682pub fn sum_inst_variants(
683    name: &str,
684    args: &[TypeRef],
685    types: &HashMap<String, Arc<TypeDecl>>,
686) -> Option<Vec<(String, Vec<(String, TypeRef)>)>> {
687    let decl = types.get(name)?;
688    let TypeBody::Sum(s) = &decl.body else {
689        return None;
690    };
691    if decl.type_params.len() != args.len() {
692        return None;
693    }
694    let subst: HashMap<String, TypeRef> = decl
695        .type_params
696        .iter()
697        .map(|p| p.name.name.clone())
698        .zip(args.iter().cloned())
699        .collect();
700    Some(
701        s.variants
702            .iter()
703            .map(|v| {
704                (
705                    v.name.name.clone(),
706                    v.payload
707                        .iter()
708                        .map(|f| (f.name.name.clone(), subst_type_ref(&f.type_ref, &subst)))
709                        .collect(),
710                )
711            })
712            .collect(),
713    )
714}
715
716/// v0.174 (#592): the monomorphised codec suffix for a generic-record
717/// instantiation — `Paginated[User]` → `Paginated_User`,
718/// `Pair[User, String]` → `Pair_User_String`. #593: shared with generic sums.
719/// Renamed from `app_ts_name` in the move from `bynk-emit`.
720pub fn inst_codec_suffix(name: &str, args: &[TypeRef]) -> String {
721    let mut s = name.to_string();
722    for a in args {
723        s.push('_');
724        s.push_str(&codec_suffix(a));
725    }
726    s
727}
728
729/// The codec-name suffix a `TypeRef` resolves to — `Int`, `Order`,
730/// `Result_Int_String`, `Paginated_User`. Renamed from `inner_ts_name` in the
731/// move from `bynk-emit`; used both to key a [`WireInst`] and, unqualified,
732/// as the bare codec function suffix a same-module call reaches.
733pub fn codec_suffix(t: &TypeRef) -> String {
734    match t {
735        TypeRef::Base(b, _) => b.name().to_string(),
736        // v0.20a: function types are confined to non-boundary positions
737        // (`bynk.types.function_at_boundary`), so the serialisation machinery
738        // can never legally see one.
739        TypeRef::Fn(..)
740        | TypeRef::Query(..)
741        | TypeRef::Stream(..)
742        | TypeRef::Connection(..)
743        | TypeRef::History(..) => {
744            unreachable!("function/query/stream types are rejected at boundaries")
745        }
746        // v0.174 (#592): the codec suffix for a generic-record instantiation —
747        // `Paginated[User]` → `Paginated_User`.
748        TypeRef::App { name, args, .. } => inst_codec_suffix(&name.name, args),
749        TypeRef::Named(id) => id.name.clone(),
750        TypeRef::Result(a, b, _) => format!("Result_{}_{}", codec_suffix(a), codec_suffix(b)),
751        TypeRef::Option(a, _) => format!("Option_{}", codec_suffix(a)),
752        TypeRef::Effect(a, _) => format!("Effect_{}", codec_suffix(a)),
753        TypeRef::HttpResult(a, _) => format!("HttpResult_{}", codec_suffix(a)),
754        TypeRef::List(a, _) => format!("List_{}", codec_suffix(a)),
755        TypeRef::Set(a, _) => format!("Set_{}", codec_suffix(a)),
756        TypeRef::Map(k, v, _) => format!("Map_{}_{}", codec_suffix(k), codec_suffix(v)),
757        TypeRef::QueueResult(_) => "QueueResult".to_string(),
758        TypeRef::Asset(_) => "Asset".to_string(),
759        TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
760        TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
761        TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
762        TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
763        TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
764        TypeRef::ValidationError(_) => "ValidationError".to_string(),
765        TypeRef::DecodeError(_) => "DecodeError".to_string(),
766        TypeRef::Unit(_) => "Unit".to_string(),
767    }
768}
769
770/// #2656: the most levels of recursive-type nesting a boundary codec accepts.
771/// A value of a recursive type is one level; each value of a recursive type
772/// nested inside it, through any fields, variants or containers, is one more.
773/// A value of a non-recursive type is not counted and, as its codec carries no
774/// depth, the count starts again below it; such a type occurs a fixed number of
775/// times on any path, so the total stays bounded.
776/// Decoding a value nested deeper is a `StructuralMismatch` at the path where
777/// the bound is crossed; encoding one throws, as a non-finite `Float` does.
778///
779/// Measured on Node 22 against the emitted `workers` codecs before the bound
780/// existed (cold code, one fresh process per probe), the shallowest overflow of
781/// the four reference shapes was a record recursing through a `Map`, at 1,394
782/// levels when decoding. The bound is a quarter of that or less, because the
783/// Workers runtime's stack can be smaller than Node's, and no less than 256,
784/// so that legitimately deep data (a long linked list) still crosses. The
785/// measurements are recorded in the ADR for #2656, and the bound in the
786/// specification (§6.5); changing it changes which values cross a boundary.
787pub const MAX_RECURSIVE_NESTING: u32 = 256;
788
789/// #2656: the codec suffixes ([`codec_suffix`]) whose codecs can call
790/// themselves, directly or through other codecs: the named types that take
791/// part in a type cycle, and the container and generic-instantiation codecs
792/// the cycle passes through (`List_Dir` for `type Dir = { children:
793/// List[Dir] }`). Only these codecs carry a nesting depth, because only a
794/// recursive type can nest without a bound the program text sets. A codec
795/// that merely reaches a cycle without being on one (a non-recursive record
796/// with a `Dir` field) is not included: it adds a fixed number of frames.
797///
798/// The graph's nodes are codec suffixes, its edges the codec calls each codec
799/// makes; a node is recursive when it lies on a cycle (a strongly connected
800/// component with more than one node, or a self-call). Every non-generic
801/// declaration in `types` is a root, so the answer does not depend on which
802/// declarations a module happens to emit. A recursive *generic* declaration
803/// is never expanded: it has no finite codec set and is rejected at the
804/// boundary (§6.5).
805pub fn recursive_codec_suffixes(
806    types: &HashMap<String, Arc<TypeDecl>>,
807) -> std::collections::HashSet<String> {
808    let recursive_generics = recursive_generic_names(types);
809    // Adjacency by suffix, built by a worklist over the reachable codecs.
810    let mut edges: HashMap<String, Vec<String>> = HashMap::new();
811    let mut work: Vec<(String, Vec<TypeRef>)> = Vec::new();
812    let mut roots: Vec<&String> = types
813        .iter()
814        .filter(|(_, d)| d.type_params.is_empty())
815        .map(|(n, _)| n)
816        .collect();
817    roots.sort();
818    for name in roots {
819        work.push((name.clone(), named_codec_children(name, types)));
820    }
821    while let Some((suffix, children)) = work.pop() {
822        if edges.contains_key(&suffix) {
823            continue;
824        }
825        let mut out = Vec::new();
826        for c in children {
827            if !has_codec(&c) {
828                continue;
829            }
830            let s = codec_suffix(&c);
831            if !edges.contains_key(&s) {
832                work.push((
833                    s.clone(),
834                    ref_codec_children(&c, types, &recursive_generics),
835                ));
836            }
837            out.push(s);
838        }
839        edges.insert(suffix, out);
840    }
841    nodes_on_cycles(&edges)
842}
843
844/// The type references a named, non-generic declaration's codec delegates
845/// to: its record fields, or its sum variants' payload fields.
846fn named_codec_children(name: &str, types: &HashMap<String, Arc<TypeDecl>>) -> Vec<TypeRef> {
847    let Some(decl) = types.get(name) else {
848        return Vec::new();
849    };
850    if !decl.type_params.is_empty() {
851        return Vec::new();
852    }
853    match &decl.body {
854        TypeBody::Record(r) => r.fields.iter().map(|f| f.type_ref.clone()).collect(),
855        TypeBody::Sum(s) => s
856            .variants
857            .iter()
858            .flat_map(|v| v.payload.iter().map(|p| p.type_ref.clone()))
859            .collect(),
860        TypeBody::Refined { .. } | TypeBody::Opaque { .. } => Vec::new(),
861    }
862}
863
864/// The type references the codec for `t` delegates to.
865fn ref_codec_children(
866    t: &TypeRef,
867    types: &HashMap<String, Arc<TypeDecl>>,
868    recursive_generics: &std::collections::HashSet<String>,
869) -> Vec<TypeRef> {
870    match t {
871        TypeRef::Named(id) => named_codec_children(&id.name, types),
872        TypeRef::App { name, args, .. } => {
873            if recursive_generics.contains(&name.name) {
874                return Vec::new();
875            }
876            if let Some(fields) = record_inst_fields(&name.name, args, types) {
877                fields.into_iter().map(|(_, t)| t).collect()
878            } else if let Some(variants) = sum_inst_variants(&name.name, args, types) {
879                variants
880                    .into_iter()
881                    .flat_map(|(_, payload)| payload.into_iter().map(|(_, t)| t))
882                    .collect()
883            } else {
884                Vec::new()
885            }
886        }
887        TypeRef::Option(a, _) | TypeRef::List(a, _) | TypeRef::Set(a, _) => vec![(**a).clone()],
888        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => vec![(**a).clone(), (**b).clone()],
889        _ => Vec::new(),
890    }
891}
892
893/// Whether `t` has a generated codec of its own that another codec calls by
894/// name: a named type, a generic instantiation or a container, none of which
895/// holds a type with no wire form ([`codec_suffix`] refuses those). A type in
896/// a non-boundary declaration may hold one; it is never a codec.
897fn has_codec(t: &TypeRef) -> bool {
898    fn encodable(t: &TypeRef) -> bool {
899        match t {
900            TypeRef::Fn(..)
901            | TypeRef::Query(..)
902            | TypeRef::Stream(..)
903            | TypeRef::Connection(..)
904            | TypeRef::History(..) => false,
905            TypeRef::Option(a, _)
906            | TypeRef::List(a, _)
907            | TypeRef::Set(a, _)
908            | TypeRef::Effect(a, _)
909            | TypeRef::HttpResult(a, _) => encodable(a),
910            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => encodable(a) && encodable(b),
911            TypeRef::App { args, .. } => args.iter().all(encodable),
912            _ => true,
913        }
914    }
915    matches!(
916        t,
917        TypeRef::Named(_)
918            | TypeRef::App { .. }
919            | TypeRef::Option(..)
920            | TypeRef::List(..)
921            | TypeRef::Set(..)
922            | TypeRef::Result(..)
923            | TypeRef::Map(..)
924    ) && encodable(t)
925}
926
927/// The nodes of `edges` that lie on a cycle, by Tarjan's strongly connected
928/// components: a node is on a cycle when its component has more than one
929/// node, or when it has an edge to itself.
930fn nodes_on_cycles(edges: &HashMap<String, Vec<String>>) -> std::collections::HashSet<String> {
931    struct State<'a> {
932        edges: &'a HashMap<String, Vec<String>>,
933        index: HashMap<&'a str, usize>,
934        low: HashMap<&'a str, usize>,
935        stack: Vec<&'a str>,
936        on_stack: std::collections::HashSet<&'a str>,
937        next: usize,
938        out: std::collections::HashSet<String>,
939    }
940    fn connect<'a>(s: &mut State<'a>, v: &'a str) {
941        s.index.insert(v, s.next);
942        s.low.insert(v, s.next);
943        s.next += 1;
944        s.stack.push(v);
945        s.on_stack.insert(v);
946        let edges = s.edges;
947        for w in edges.get(v).map(Vec::as_slice).unwrap_or(&[]) {
948            let w = w.as_str();
949            if !s.index.contains_key(w) {
950                connect(s, w);
951                let lw = s.low[w];
952                let lv = s.low.get_mut(v).expect("visited");
953                *lv = (*lv).min(lw);
954            } else if s.on_stack.contains(w) {
955                let iw = s.index[w];
956                let lv = s.low.get_mut(v).expect("visited");
957                *lv = (*lv).min(iw);
958            }
959        }
960        if s.low[v] == s.index[v] {
961            let mut component = Vec::new();
962            loop {
963                let w = s.stack.pop().expect("component member");
964                s.on_stack.remove(w);
965                component.push(w);
966                if w == v {
967                    break;
968                }
969            }
970            let self_call = edges.get(v).is_some_and(|ws| ws.iter().any(|w| w == v));
971            if component.len() > 1 || self_call {
972                s.out.extend(component.into_iter().map(str::to_string));
973            }
974        }
975    }
976    let mut s = State {
977        edges,
978        index: HashMap::new(),
979        low: HashMap::new(),
980        stack: Vec::new(),
981        on_stack: std::collections::HashSet::new(),
982        next: 0,
983        out: std::collections::HashSet::new(),
984    };
985    let mut nodes: Vec<&String> = edges.keys().collect();
986    nodes.sort();
987    for v in nodes {
988        if !s.index.contains_key(v.as_str()) {
989            connect(&mut s, v);
990        }
991    }
992    s.out
993}
994
995/// v0.22b: the codec closure for a set of `Json.encode`/`Json.decode[T]`
996/// target type-refs — the named types needing per-type helpers (transitively
997/// through record fields and sum payloads) plus the generic instantiations
998/// needing specialised helpers. The same closure logic as the boundary
999/// collectors, rooted at expressions instead of service signatures.
1000pub fn collect_codec_closure(
1001    roots: &[TypeRef],
1002    types: &HashMap<String, Arc<TypeDecl>>,
1003) -> (Vec<String>, Vec<WireInst>) {
1004    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1005    let mut names: Vec<String> = Vec::new();
1006    let mut stack: Vec<String> = Vec::new();
1007    let recursive_set = recursive_generic_names(types);
1008    let recursive = &recursive_set;
1009    for r in roots {
1010        collect_type_names(r, &mut stack, types, recursive);
1011    }
1012    while let Some(name) = stack.pop() {
1013        if !seen.insert(name.clone()) {
1014            continue;
1015        }
1016        names.push(name.clone());
1017        let Some(decl) = types.get(&name) else {
1018            continue;
1019        };
1020        match &decl.body {
1021            TypeBody::Record(r) => {
1022                for f in &r.fields {
1023                    collect_type_names(&f.type_ref, &mut stack, types, recursive);
1024                }
1025            }
1026            TypeBody::Sum(s) => {
1027                for v in &s.variants {
1028                    for p in &v.payload {
1029                        collect_type_names(&p.type_ref, &mut stack, types, recursive);
1030                    }
1031                }
1032            }
1033            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
1034        }
1035    }
1036    names.sort();
1037
1038    let mut insts: Vec<WireInst> = Vec::new();
1039    let mut inst_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1040    for r in roots {
1041        walk_generic_inst(r, &mut insts, &mut inst_seen, types, recursive);
1042    }
1043    for name in &names {
1044        let Some(decl) = types.get(name) else {
1045            continue;
1046        };
1047        match &decl.body {
1048            TypeBody::Record(r) => {
1049                for f in &r.fields {
1050                    walk_generic_inst(&f.type_ref, &mut insts, &mut inst_seen, types, recursive);
1051                }
1052            }
1053            TypeBody::Sum(s) => {
1054                for v in &s.variants {
1055                    for p in &v.payload {
1056                        walk_generic_inst(
1057                            &p.type_ref,
1058                            &mut insts,
1059                            &mut inst_seen,
1060                            types,
1061                            recursive,
1062                        );
1063                    }
1064                }
1065            }
1066            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
1067        }
1068    }
1069    (names, insts)
1070}
1071
1072/// Collect the set of `Result<A, B>` / `Option<A>` instantiations used in
1073/// boundary positions so the emitter can synthesise the specialised
1074/// helpers. v0.18: an instantiation may also appear in the *fields* of a
1075/// boundary record or sum payload (e.g. the bynk surface's
1076/// `Request.contentType: Option[String]`) — the per-type serialisers
1077/// delegate to the specialised generic helpers, so walk those too.
1078pub fn collect_generic_instantiations(
1079    services: &HashMap<String, ServiceDecl>,
1080    // v0.96 (ADR 0124): an agent's `store`-field element types are validated on
1081    // rehydration, so a `Cell[Option[Int]]` / `Log[List[T]]` needs its specialised
1082    // generic helper emitted just like a boundary signature does.
1083    agents: &HashMap<String, AgentDecl>,
1084    boundary_type_names: &[String],
1085    types: &HashMap<String, Arc<TypeDecl>>,
1086    // #1678: further boundary positions, as for `collect_boundary_types`. Walked
1087    // after the services and agent stores, so existing emission order is kept.
1088    extra_roots: &[TypeRef],
1089) -> Vec<WireInst> {
1090    let mut out: Vec<WireInst> = Vec::new();
1091    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1092    let recursive_set = recursive_generic_names(types);
1093    let recursive = &recursive_set;
1094    // Iterate services in name order: `HashMap::values()` order varies per
1095    // process, and the *emission order* of the specialised helpers follows
1096    // first-encounter order here. Surfaced by the first fixture with
1097    // multiple same-file services carrying different instantiations (v0.23
1098    // #35 CI); latent since v0.8.
1099    let mut svc_names: Vec<&String> = services.keys().collect();
1100    svc_names.sort();
1101    for name in svc_names {
1102        let s = &services[name];
1103        for h in &s.handlers {
1104            for p in &h.params {
1105                walk_generic_inst(&p.type_ref, &mut out, &mut seen, types, recursive);
1106            }
1107            walk_generic_inst(&h.return_type, &mut out, &mut seen, types, recursive);
1108        }
1109    }
1110    let mut agent_names: Vec<&String> = agents.keys().collect();
1111    agent_names.sort();
1112    for name in agent_names {
1113        for f in &agents[name].store_fields {
1114            for arg in &f.kind.args {
1115                walk_generic_inst(arg, &mut out, &mut seen, types, recursive);
1116            }
1117        }
1118        for m in &agents[name].migrations {
1119            if let Some(old) = &m.old {
1120                walk_generic_inst(&old.type_ref, &mut out, &mut seen, types, recursive);
1121            }
1122        }
1123    }
1124    for r in extra_roots {
1125        walk_generic_inst(r, &mut out, &mut seen, types, recursive);
1126    }
1127    for name in boundary_type_names {
1128        let Some(decl) = types.get(name) else {
1129            continue;
1130        };
1131        // v0.174 (#592): never walk a *generic* declaration's own fields — they
1132        // are the declared, unsubstituted body (`Paginated[T] = { items: List[T]
1133        // }`), so walking `List[T]` would emit a bogus `serialise_List_T` over the
1134        // unbound type variable `T`. The instantiations a generic record needs
1135        // come from its *use* sites (`Paginated[User]`, a `TypeRef::App`), which
1136        // `walk_generic_inst` expands with concrete arguments. This mirrors the
1137        // `emit_helpers_for_owner` skip that keeps a bare `serialise_Paginated`
1138        // from being emitted.
1139        if !decl.type_params.is_empty() {
1140            continue;
1141        }
1142        match &decl.body {
1143            TypeBody::Record(r) => {
1144                for f in &r.fields {
1145                    walk_generic_inst(&f.type_ref, &mut out, &mut seen, types, recursive);
1146                }
1147            }
1148            TypeBody::Sum(s) => {
1149                for v in &s.variants {
1150                    for p in &v.payload {
1151                        walk_generic_inst(&p.type_ref, &mut out, &mut seen, types, recursive);
1152                    }
1153                }
1154            }
1155            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
1156        }
1157    }
1158    out
1159}
1160
1161/// A boundary occurrence of a generic instantiation needing its own
1162/// specialised codec — `Result<A, B>`, `Option<A>`, `List<A>`, `Map<K, V>`,
1163/// or a generic user record/sum applied to concrete arguments
1164/// (`Paginated[User]`, `ApiResult[User]`).
1165///
1166/// Moved from `bynk-emit/src/emitter/serialisation.rs`'s `GenericInst` as
1167/// part of the #855 IR extraction. Variant names are kept exactly as they
1168/// were (`ResultInst`, not the plan's bare `Result`, …): `bynk-emit`'s
1169/// `emit_generic_helpers_qualified` pattern-matches these variants directly.
1170/// Phase 2 step 9 ("Generic helpers") revisited the plan's bare
1171/// `Result`/`Option`/`List`/`Map`/`Record`/`Sum` spelling and **kept** the
1172/// `*Inst` suffix — see the "Moved verbatim" comment block above this
1173/// module's walk functions for the reasoning (a pure rename of six match
1174/// arms with no behavioural or architectural payoff).
1175#[derive(Debug, Clone)]
1176#[allow(clippy::enum_variant_names)]
1177pub enum WireInst {
1178    ResultInst {
1179        ok: TypeRef,
1180        err: TypeRef,
1181    },
1182    OptionInst {
1183        inner: TypeRef,
1184    },
1185    /// v0.20b: a `List[T]` boundary instantiation — element-wise wire format.
1186    ListInst {
1187        elem: TypeRef,
1188    },
1189    /// K6a (#2596): a `Set[T]` boundary instantiation — a JSON array in
1190    /// insertion order; a duplicate element fails the decode.
1191    SetInst {
1192        elem: TypeRef,
1193    },
1194    /// v0.20b: a `Map[K, V]` boundary instantiation — entries-array wire
1195    /// format (`[[k, v], …]`), insertion-ordered.
1196    MapInst {
1197        key: TypeRef,
1198        val: TypeRef,
1199    },
1200    /// v0.174 (#592): a generic user-record instantiation `Name[args…]` — a
1201    /// monomorphised per-instantiation record codec (`serialise_Paginated_User`)
1202    /// specialised to the concrete arguments (ADR 0183 Decision C's follow-on).
1203    RecordInst {
1204        name: String,
1205        args: Vec<TypeRef>,
1206    },
1207    /// #593: a generic user-sum instantiation `Name[args…]` — a monomorphised
1208    /// per-instantiation discriminated-union codec (`serialise_ApiResult_User`),
1209    /// the sum analogue of [`WireInst::RecordInst`].
1210    SumInst {
1211        name: String,
1212        args: Vec<TypeRef>,
1213    },
1214}
1215
1216impl WireInst {
1217    pub fn ts_name(&self) -> String {
1218        match self {
1219            WireInst::ResultInst { ok, err } => {
1220                format!("Result_{}_{}", codec_suffix(ok), codec_suffix(err))
1221            }
1222            WireInst::OptionInst { inner } => {
1223                format!("Option_{}", codec_suffix(inner))
1224            }
1225            WireInst::ListInst { elem } => format!("List_{}", codec_suffix(elem)),
1226            WireInst::SetInst { elem } => format!("Set_{}", codec_suffix(elem)),
1227            WireInst::MapInst { key, val } => {
1228                format!("Map_{}_{}", codec_suffix(key), codec_suffix(val))
1229            }
1230            WireInst::RecordInst { name, args } => inst_codec_suffix(name, args),
1231            WireInst::SumInst { name, args } => inst_codec_suffix(name, args),
1232        }
1233    }
1234}
1235
1236fn walk_generic_inst(
1237    t: &TypeRef,
1238    out: &mut Vec<WireInst>,
1239    seen: &mut std::collections::HashSet<String>,
1240    types: &HashMap<String, Arc<TypeDecl>>,
1241    recursive: &std::collections::HashSet<String>,
1242) {
1243    match t {
1244        // v0.174 (#592): a generic-record instantiation needs a monomorphised
1245        // codec, and so do the generic instantiations reachable through its
1246        // concrete field types (`Paginated[User]` → `List[User]` →
1247        // `serialise_List_User`, `Envelope[Box[User]]` → `Box[User]` →
1248        // `serialise_Box_User`). Substitute the fields and walk them. A recursive
1249        // generic record (no finite codec set) is rejected at the boundary before
1250        // emit; the guard here is defence in depth so this walk always terminates
1251        // (the `seen` dedup alone cannot bound *polymorphic* recursion, whose
1252        // instantiations each carry a distinct name).
1253        TypeRef::App { name, args, .. } => {
1254            if recursive.contains(&name.name) {
1255                return;
1256            }
1257            // #593: an `App` names a generic record OR a generic sum; dispatch on
1258            // the declaration's body so the right monomorphised codec is emitted,
1259            // and walk the reachable instantiations through its concrete member
1260            // types (a sum's variant payloads, a record's fields).
1261            let is_sum = matches!(
1262                types.get(&name.name).map(|d| &d.body),
1263                Some(TypeBody::Sum(_))
1264            );
1265            let inst = if is_sum {
1266                WireInst::SumInst {
1267                    name: name.name.clone(),
1268                    args: args.clone(),
1269                }
1270            } else {
1271                WireInst::RecordInst {
1272                    name: name.name.clone(),
1273                    args: args.clone(),
1274                }
1275            };
1276            let key = inst.ts_name();
1277            if !seen.insert(key) {
1278                return;
1279            }
1280            out.push(inst);
1281            for a in args {
1282                walk_generic_inst(a, out, seen, types, recursive);
1283            }
1284            if is_sum {
1285                if let Some(variants) = sum_inst_variants(&name.name, args, types) {
1286                    for (_, payload) in &variants {
1287                        for (_, ft) in payload {
1288                            walk_generic_inst(ft, out, seen, types, recursive);
1289                        }
1290                    }
1291                }
1292            } else if let Some(fields) = record_inst_fields(&name.name, args, types) {
1293                for (_, ft) in &fields {
1294                    walk_generic_inst(ft, out, seen, types, recursive);
1295                }
1296            }
1297        }
1298        TypeRef::Result(a, b, _) => {
1299            let inst = WireInst::ResultInst {
1300                ok: (**a).clone(),
1301                err: (**b).clone(),
1302            };
1303            let key = inst.ts_name();
1304            if seen.insert(key) {
1305                out.push(inst);
1306            }
1307            walk_generic_inst(a, out, seen, types, recursive);
1308            walk_generic_inst(b, out, seen, types, recursive);
1309        }
1310        TypeRef::Option(a, _) => {
1311            let inst = WireInst::OptionInst {
1312                inner: (**a).clone(),
1313            };
1314            let key = inst.ts_name();
1315            if seen.insert(key) {
1316                out.push(inst);
1317            }
1318            walk_generic_inst(a, out, seen, types, recursive);
1319        }
1320        TypeRef::Effect(a, _) => walk_generic_inst(a, out, seen, types, recursive),
1321        TypeRef::HttpResult(a, _) => walk_generic_inst(a, out, seen, types, recursive),
1322        TypeRef::List(a, _) => {
1323            let inst = WireInst::ListInst {
1324                elem: (**a).clone(),
1325            };
1326            let key = inst.ts_name();
1327            if seen.insert(key) {
1328                out.push(inst);
1329            }
1330            walk_generic_inst(a, out, seen, types, recursive);
1331        }
1332        TypeRef::Set(a, _) => {
1333            let inst = WireInst::SetInst {
1334                elem: (**a).clone(),
1335            };
1336            let key = inst.ts_name();
1337            if seen.insert(key) {
1338                out.push(inst);
1339            }
1340            walk_generic_inst(a, out, seen, types, recursive);
1341        }
1342        TypeRef::Map(k, v, _) => {
1343            let inst = WireInst::MapInst {
1344                key: (**k).clone(),
1345                val: (**v).clone(),
1346            };
1347            let key = inst.ts_name();
1348            if seen.insert(key) {
1349                out.push(inst);
1350            }
1351            walk_generic_inst(k, out, seen, types, recursive);
1352            walk_generic_inst(v, out, seen, types, recursive);
1353        }
1354        _ => {}
1355    }
1356}
1357
1358// ---------------------------------------------------------------------
1359// New: resolving a `TypeRef` / `TypeDecl` into the IR above. Not yet called
1360// by any codec path — `bynk-emit` still derives its own shape inline
1361// (Phase 2 switches it over). Exercised only by this module's own tests
1362// until then.
1363// ---------------------------------------------------------------------
1364
1365/// The base-type guards a bare **field-position** value (a record field, a
1366/// sum-variant payload field, a collection element) is checked against,
1367/// mirroring `emit_field_deserialise`'s `TypeRef::Base` arm: `Int`/`Duration`/
1368/// `Instant` must be whole, `Float` must be finite. #1969: `Duration` joined the
1369/// first group; a top-level `Duration` was already guarded, a field was not. Contrast [`WireScalar::base_guards`]
1370/// (a **named-type** consumed-inline revalidation), which guards `Int`/`Float`
1371/// only — the two positions are not the same check in the code this was
1372/// extracted from, and that asymmetry is preserved rather than merged.
1373pub fn field_base_guards(b: BaseType) -> Vec<BaseGuard> {
1374    match b {
1375        BaseType::Int | BaseType::Duration | BaseType::Instant => vec![BaseGuard::Integral],
1376        BaseType::Float => vec![BaseGuard::Finite],
1377        _ => Vec::new(),
1378    }
1379}
1380
1381/// The base-type guards a named type's `Inline` (consumed, transparent)
1382/// revalidation applies, mirroring `emit_inline_refinement_checks` exactly:
1383/// `Int` → `Integral`, `Float` → `Finite`. See [`WireScalar::base_guards`]'s
1384/// doc for why `Instant` is deliberately absent here despite being guarded
1385/// at field position.
1386fn scalar_base_guards(b: BaseType) -> Vec<BaseGuard> {
1387    match b {
1388        BaseType::Int => vec![BaseGuard::Integral],
1389        BaseType::Float => vec![BaseGuard::Finite],
1390        _ => Vec::new(),
1391    }
1392}
1393
1394/// Resolve one `TypeRef` occurrence (a field's type, a variant payload
1395/// field's type, a generic argument) into its [`WireRef`] shape — the same
1396/// dispatch `emit_field_deserialise` performs today, one level removed from
1397/// any TS string.
1398///
1399/// `types` is threaded through for signature symmetry with the walks above
1400/// and forward compatibility with a future disambiguation need; this
1401/// resolution is single-level (unlike `collect_type_names`'s transitive
1402/// walk) and does not currently consult it.
1403///
1404/// **This encodes the *deserialise*-side dispatch only** (mirroring
1405/// `emit_field_deserialise`'s arms one-for-one, including its `Effect` /
1406/// `HttpResult` arm, which it folds into the same unchecked cast as
1407/// `ValidationError`/`DecodeError`/`QueueResult`). The emitter does not
1408/// actually agree with itself on those two shapes across its other three
1409/// dispatches: `serialise_field_expr_via` *recurses* through `Effect` rather
1410/// than casting it unchecked, `deserialise_expr_via` also recurses through
1411/// `Effect`, and `codec_suffix` gives both `Effect` and `HttpResult` their
1412/// own composed names (`Effect_<inner>`, `HttpResult_<inner>`) rather than
1413/// treating them as opaque. A future serialise-side or codec-suffix-side
1414/// `WireRef` derivation must **not** assume this function's `Unchecked`
1415/// answer already covers it — that would silently change `Effect`-at-field-
1416/// position from "recurse into the inner type" to "cast unchecked" the
1417/// moment Phase 2 routes the serialise path through this same resolver.
1418/// Reconciling (or deliberately keeping two resolvers) is a Phase 2 decision,
1419/// not implied by this function's existence.
1420pub fn wire_ref(t: &TypeRef, _types: &HashMap<String, Arc<TypeDecl>>) -> WireRef {
1421    match t {
1422        // v0.20a: function types are confined to non-boundary positions
1423        // (`bynk.types.function_at_boundary`), so the serialisation machinery
1424        // can never legally see one — mirrors `emit_field_deserialise`'s
1425        // `unreachable!` on this same arm.
1426        TypeRef::Fn(..)
1427        | TypeRef::Query(..)
1428        | TypeRef::Stream(..)
1429        | TypeRef::Connection(..)
1430        | TypeRef::History(..) => {
1431            unreachable!(
1432                "function/query/stream/connection/history types are rejected at boundaries"
1433            )
1434        }
1435        // v0.110 (ADR 0142 D5): a bare `Bytes` field is a base64 JSON string,
1436        // decoded (not cast) into a `Uint8Array`.
1437        TypeRef::Base(BaseType::Bytes, _) => WireRef::Bytes,
1438        TypeRef::Base(BaseType::Decimal, _) => WireRef::Decimal,
1439        TypeRef::Base(b, _) => {
1440            let json = json_kind_of(*b);
1441            WireRef::Base {
1442                base: *b,
1443                json,
1444                guards: field_base_guards(*b),
1445                expected: Expected::Json(json),
1446            }
1447        }
1448        TypeRef::Named(id) => WireRef::Named {
1449            name: id.name.clone(),
1450        },
1451        // Every generic instantiation — App/Result/Option/List/Map — resolves
1452        // to the same codec-suffix key; `codec_suffix` already builds exactly
1453        // that string for each of these shapes.
1454        TypeRef::App { .. }
1455        | TypeRef::Result(..)
1456        | TypeRef::Option(..)
1457        | TypeRef::List(..)
1458        | TypeRef::Set(..)
1459        | TypeRef::Map(..) => WireRef::Inst {
1460            key: codec_suffix(t),
1461        },
1462        TypeRef::Effect(..) => WireRef::Unchecked {
1463            reason: UncheckedReason::Effect,
1464        },
1465        TypeRef::HttpResult(..) => WireRef::Unchecked {
1466            reason: UncheckedReason::HttpResult,
1467        },
1468        TypeRef::ValidationError(_) => WireRef::Unchecked {
1469            reason: UncheckedReason::ValidationError,
1470        },
1471        TypeRef::DecodeError(_) => WireRef::Unchecked {
1472            reason: UncheckedReason::DecodeError,
1473        },
1474        TypeRef::QueueResult(_) => WireRef::Unchecked {
1475            reason: UncheckedReason::QueueResult,
1476        },
1477        // #1883, slice 1a: never reached through a well-checked program — an
1478        // `Asset` at a boundary is `bynk.types.asset_at_boundary` — but the
1479        // model still needs a total answer.
1480        TypeRef::Asset(_)
1481        | TypeRef::RequestHeaders(_)
1482        | TypeRef::RequestQuery(_)
1483        | TypeRef::RequestCookies(_)
1484        | TypeRef::TokenClaims(_)
1485        | TypeRef::BoundaryRejection(_) => WireRef::Unchecked {
1486            reason: UncheckedReason::Asset,
1487        },
1488        TypeRef::Unit(_) => WireRef::Unit,
1489    }
1490}
1491
1492fn wire_fields(fields: &[RecordField], types: &HashMap<String, Arc<TypeDecl>>) -> Vec<WireField> {
1493    fields
1494        .iter()
1495        .map(|f| WireField {
1496            name: f.name.name.clone(),
1497            shape: wire_ref(&f.type_ref, types),
1498            path_segment: f.name.name.clone(),
1499            default: f.init.as_ref().map(|e| (e.clone(), f.type_ref.clone())),
1500            predicates: field_predicates(f),
1501        })
1502        .collect()
1503}
1504
1505/// #1969: a record field's inline refinement predicates, in declaration order
1506/// (`qty: Int where Positive` → `[Positive]`). The decoder checks them after
1507/// the field's own codec, so a refined field reads the same from the wire as a
1508/// field of a named refined type.
1509pub fn field_predicates(f: &RecordField) -> Vec<PredKind> {
1510    f.refinement
1511        .as_ref()
1512        .map(|r| r.predicates.iter().map(|p| p.kind.clone()).collect())
1513        .unwrap_or_default()
1514}
1515
1516fn wire_sum(body: &SumBody, types: &HashMap<String, Arc<TypeDecl>>) -> WireSum {
1517    WireSum {
1518        wire_discriminant: WIRE_DISCRIMINANT,
1519        memory_discriminant: "tag",
1520        variants: body
1521            .variants
1522            .iter()
1523            .map(|v| WireVariant {
1524                name: v.name.name.clone(),
1525                payload: v
1526                    .payload
1527                    .iter()
1528                    .map(|f| WireField {
1529                        name: f.name.name.clone(),
1530                        shape: wire_ref(&f.type_ref, types),
1531                        path_segment: f.name.name.clone(),
1532                        // Sum-variant payload fields carry no default in the
1533                        // surface grammar (`VariantField` has no `init`).
1534                        default: None,
1535                        predicates: Vec::new(),
1536                    })
1537                    .collect(),
1538            })
1539            .collect(),
1540    }
1541}
1542
1543/// Build one [`WireScalar`], choosing [`Revalidation`] per #661 Decisions
1544/// C/D plus the owner path: `Owned` → `ViaConstructor`; consumed + opaque →
1545/// `StructuralOnly`; consumed + transparent → `Inline`; a `Bytes` base →
1546/// `Base64Decode` regardless of provenance, mirroring `emit_refined`'s early
1547/// return to the dedicated `Bytes` codec before the owned/consumed split is
1548/// even considered.
1549fn wire_scalar(
1550    base: BaseType,
1551    opaque: bool,
1552    refinement: Option<&Refinement>,
1553    prov: &Provenance,
1554) -> WireScalar {
1555    let json = json_kind_of(base);
1556    let predicates: Vec<PredKind> = refinement
1557        .map(|r| r.predicates.iter().map(|p| p.kind.clone()).collect())
1558        .unwrap_or_default();
1559    let revalidation = if base == BaseType::Bytes {
1560        Revalidation::Base64Decode
1561    } else if base == BaseType::Decimal {
1562        Revalidation::DecimalParse
1563    } else {
1564        match prov {
1565            Provenance::Owned => Revalidation::ViaConstructor,
1566            Provenance::Consumed { .. } if opaque => Revalidation::StructuralOnly,
1567            Provenance::Consumed { .. } => Revalidation::Inline,
1568        }
1569    };
1570    WireScalar {
1571        base,
1572        json,
1573        opaque,
1574        predicates,
1575        base_guards: scalar_base_guards(base),
1576        revalidation,
1577    }
1578}
1579
1580/// Build a [`WireType`] from a `TypeDecl`, using the same base/predicate/
1581/// opaque logic currently inline in `bynk-emit`'s `emit_refined` and
1582/// `emit_bytes_named_codec` — without any TS string emission. Returns `None`
1583/// for a **generic** declaration (`decl.type_params` non-empty): a generic
1584/// record/sum has no single bare `WireType` of its own, only per-instantiation
1585/// shapes (`WireInst`), mirroring the skip in `emit_helpers_for_owner_qualified`.
1586pub fn wire_type(
1587    name: &str,
1588    decl: &TypeDecl,
1589    types: &HashMap<String, Arc<TypeDecl>>,
1590    prov: Provenance,
1591) -> Option<WireType> {
1592    if !decl.type_params.is_empty() {
1593        return None;
1594    }
1595    let body = match &decl.body {
1596        TypeBody::Refined {
1597            base, refinement, ..
1598        } => WireBody::Scalar(wire_scalar(*base, false, refinement.as_ref(), &prov)),
1599        TypeBody::Opaque {
1600            base, refinement, ..
1601        } => WireBody::Scalar(wire_scalar(*base, true, refinement.as_ref(), &prov)),
1602        TypeBody::Record(r) => WireBody::Record {
1603            fields: wire_fields(&r.fields, types),
1604        },
1605        TypeBody::Sum(s) => WireBody::Sum(wire_sum(s, types)),
1606    };
1607    Some(WireType {
1608        name: name.to_string(),
1609        codec_suffix: name.to_string(),
1610        provenance: prov,
1611        body,
1612    })
1613}
1614
1615/// Build the full [`WireModel`] for a boundary: every non-generic named type
1616/// in `type_names` resolved through `types`, plus the generic instantiations
1617/// the caller already collected (`collect_generic_instantiations` /
1618/// `collect_codec_closure`). `provenance` is supplied by the caller —
1619/// `bynk-emit` knows the build target and the consumed set; this crate must
1620/// not (see the [`Provenance`] doc).
1621pub fn boundary_model(
1622    type_names: &[String],
1623    types: &HashMap<String, Arc<TypeDecl>>,
1624    instantiations: Vec<WireInst>,
1625    provenance: impl Fn(&str) -> Provenance,
1626) -> WireModel {
1627    let recursive: BTreeSet<String> = recursive_generic_names(types).into_iter().collect();
1628    let mut wtypes = Vec::with_capacity(type_names.len());
1629    for name in type_names {
1630        let Some(decl) = types.get(name) else {
1631            continue;
1632        };
1633        if let Some(wt) = wire_type(name, decl, types, provenance(name)) {
1634            wtypes.push(wt);
1635        }
1636    }
1637    WireModel {
1638        types: wtypes,
1639        instantiations,
1640        recursive,
1641    }
1642}
1643
1644#[cfg(test)]
1645mod tests {
1646    use super::*;
1647
1648    fn types_of(src: &str) -> HashMap<String, Arc<TypeDecl>> {
1649        let tokens = bynk_syntax::lexer::tokenize(src).expect("lex");
1650        let commons = bynk_syntax::parser::parse(&tokens, src).expect("parse");
1651        commons
1652            .items
1653            .iter()
1654            .filter_map(|i| match i {
1655                CommonsItem::Type(t) => Some((t.name.name.clone(), Arc::new(t.clone()))),
1656                _ => None,
1657            })
1658            .collect()
1659    }
1660
1661    /// Parse a `context` unit and split it into its `types` and `services`
1662    /// tables, mirroring `bynk-emit`'s own boundary-collection call sites.
1663    fn context_of(src: &str) -> (HashMap<String, Arc<TypeDecl>>, HashMap<String, ServiceDecl>) {
1664        let tokens = bynk_syntax::lexer::tokenize(src).expect("lex");
1665        let unit = bynk_syntax::parser::parse_unit(&tokens, src).expect("parse");
1666        let SourceUnit::Context(ctx) = unit else {
1667            panic!("expected a context unit");
1668        };
1669        let mut types = HashMap::new();
1670        let mut services = HashMap::new();
1671        for item in &ctx.items {
1672            match item {
1673                CommonsItem::Type(t) => {
1674                    types.insert(t.name.name.clone(), Arc::new(t.clone()));
1675                }
1676                CommonsItem::Service(s) => {
1677                    services.insert(s.name.name.clone(), s.clone());
1678                }
1679                _ => {}
1680            }
1681        }
1682        (types, services)
1683    }
1684
1685    /// #2656: only the codecs on a type cycle carry a depth: the recursive
1686    /// types and the containers their cycles pass through, not a type that
1687    /// merely holds a recursive one, nor a container off the cycle.
1688    #[test]
1689    fn recursive_codec_suffixes_are_the_codecs_on_a_cycle() {
1690        let types = types_of(
1691            "commons x\n\n\
1692             type Tree =\n  | Leaf\n  | Node(left: Tree, right: Tree)\n\n\
1693             type Dir = { name: String, children: List[Dir], tags: List[String] }\n\n\
1694             type Chain = { value: Int, next: Option[Chain] }\n\n\
1695             type Index = { entries: Map[String, Index] }\n\n\
1696             type Expr =\n  | Lit(value: Int)\n  | Block(stmts: List[Stmt])\n\n\
1697             type Stmt =\n  | Eval(expr: Expr)\n\n\
1698             type Holder = { tree: Tree, dirs: List[Dir], maybe: Option[Tree] }\n\n\
1699             type Flat = { n: Int, names: List[String] }\n",
1700        );
1701        let mut got: Vec<String> = recursive_codec_suffixes(&types).into_iter().collect();
1702        got.sort();
1703        assert_eq!(
1704            got,
1705            [
1706                "Chain",
1707                "Dir",
1708                "Expr",
1709                "Index",
1710                "List_Dir",
1711                "List_Stmt",
1712                "Map_String_Index",
1713                "Option_Chain",
1714                "Stmt",
1715                "Tree",
1716            ]
1717        );
1718    }
1719
1720    #[test]
1721    fn json_kind_of_matches_the_ts_base_for_serialisation_mapping() {
1722        assert_eq!(json_kind_of(BaseType::Int), JsonKind::Number);
1723        assert_eq!(json_kind_of(BaseType::Float), JsonKind::Number);
1724        assert_eq!(json_kind_of(BaseType::Duration), JsonKind::Number);
1725        assert_eq!(json_kind_of(BaseType::Instant), JsonKind::Number);
1726        assert_eq!(json_kind_of(BaseType::String), JsonKind::String);
1727        // v0.110 (ADR 0142 D5): a `Bytes` wires as a base64 JSON string.
1728        assert_eq!(json_kind_of(BaseType::Bytes), JsonKind::String);
1729        assert_eq!(json_kind_of(BaseType::Bool), JsonKind::Boolean);
1730    }
1731
1732    #[test]
1733    fn collect_boundary_types_walks_params_return_and_record_fields() {
1734        let src = r#"
1735context test
1736
1737type ClientId = String where NonEmpty
1738type Rate = { count: Int, limit: Int }
1739
1740service Api {
1741  on call(client: ClientId) -> Effect[Rate] by Caller {
1742    client
1743  }
1744}
1745"#;
1746        let (types, services) = context_of(src);
1747        let agents: HashMap<String, AgentDecl> = HashMap::new();
1748        let names = collect_boundary_types(&types, &services, &agents, &[]);
1749        assert_eq!(names, vec!["ClientId".to_string(), "Rate".to_string()]);
1750    }
1751
1752    #[test]
1753    fn collect_boundary_types_ignores_types_unreachable_from_any_handler() {
1754        let src = r#"
1755context test
1756
1757type Used = String where NonEmpty
1758type Unused = { n: Int }
1759
1760service Api {
1761  on call(x: Used) -> Effect[Used] by Caller {
1762    x
1763  }
1764}
1765"#;
1766        let (types, services) = context_of(src);
1767        let agents: HashMap<String, AgentDecl> = HashMap::new();
1768        let names = collect_boundary_types(&types, &services, &agents, &[]);
1769        assert_eq!(names, vec!["Used".to_string()]);
1770    }
1771
1772    /// The highest-risk drift trap the plan flags: `contract.rs` sorts
1773    /// predicates (a precondition for hash correctness), but this IR must
1774    /// carry **declaration order** — `Inline` revalidation emits one `if`
1775    /// per predicate in source order. `NonEmpty` before `MaxLength` sorts
1776    /// (alphabetically, as `contract.rs`'s `canon_refinement` would — folding
1777    /// `NonEmpty` to `MinLength(1)` there does not change this: `MaxLength` <
1778    /// `MinLength` alphabetically, same relative order as `MaxLength` <
1779    /// `NonEmpty` before the fold) to `MaxLength` first, so this fixture's
1780    /// declaration order visibly differs from the sorted order — a positive
1781    /// assertion that the trap stays closed.
1782    #[test]
1783    fn wire_scalar_predicates_preserve_declaration_order_not_sorted() {
1784        let types = types_of("commons x\n\ntype Id = String where NonEmpty && MaxLength(20)\n");
1785        let decl = &types["Id"];
1786        let wt = wire_type("Id", decl, &types, Provenance::Owned).expect("scalar wire type");
1787        let WireBody::Scalar(scalar) = &wt.body else {
1788            panic!("expected a scalar body, got {:?}", wt.body);
1789        };
1790        assert_eq!(scalar.predicates.len(), 2);
1791        assert!(
1792            matches!(scalar.predicates[0], PredKind::NonEmpty),
1793            "predicates[0] must be the declared-first NonEmpty, got {:?}",
1794            scalar.predicates[0]
1795        );
1796        assert!(
1797            matches!(scalar.predicates[1], PredKind::MaxLength(20)),
1798            "predicates[1] must be the declared-second MaxLength(20), got {:?}",
1799            scalar.predicates[1]
1800        );
1801        // The sorted (contract.rs-style) order would put MaxLength first —
1802        // assert this IR does not match that order.
1803        assert!(
1804            !matches!(scalar.predicates[0], PredKind::MaxLength(_)),
1805            "predicates must be in declaration order, not sorted"
1806        );
1807    }
1808
1809    #[test]
1810    fn wire_type_selects_revalidation_by_provenance_and_opacity() {
1811        let types = types_of(
1812            "commons x\n\ntype Refined = String where NonEmpty\ntype Opaque = opaque String where NonEmpty\ntype Raw = Bytes\n",
1813        );
1814
1815        let refined = wire_type("Refined", &types["Refined"], &types, Provenance::Owned)
1816            .expect("owned scalar");
1817        let WireBody::Scalar(s) = &refined.body else {
1818            panic!("expected scalar")
1819        };
1820        assert_eq!(s.revalidation, Revalidation::ViaConstructor);
1821
1822        let consumed = Provenance::Consumed {
1823            owner_unit: "other".to_string(),
1824        };
1825        let refined_consumed =
1826            wire_type("Refined", &types["Refined"], &types, consumed.clone()).expect("consumed");
1827        let WireBody::Scalar(s) = &refined_consumed.body else {
1828            panic!("expected scalar")
1829        };
1830        assert_eq!(s.revalidation, Revalidation::Inline);
1831
1832        let opaque_consumed =
1833            wire_type("Opaque", &types["Opaque"], &types, consumed.clone()).expect("consumed");
1834        let WireBody::Scalar(s) = &opaque_consumed.body else {
1835            panic!("expected scalar")
1836        };
1837        assert_eq!(s.revalidation, Revalidation::StructuralOnly);
1838
1839        // Bytes: Base64Decode regardless of provenance.
1840        let raw_owned =
1841            wire_type("Raw", &types["Raw"], &types, Provenance::Owned).expect("owned bytes");
1842        let WireBody::Scalar(s) = &raw_owned.body else {
1843            panic!("expected scalar")
1844        };
1845        assert_eq!(s.revalidation, Revalidation::Base64Decode);
1846        let raw_consumed = wire_type("Raw", &types["Raw"], &types, consumed).expect("consumed");
1847        let WireBody::Scalar(s) = &raw_consumed.body else {
1848            panic!("expected scalar")
1849        };
1850        assert_eq!(s.revalidation, Revalidation::Base64Decode);
1851    }
1852
1853    #[test]
1854    fn wire_type_returns_none_for_a_generic_declaration() {
1855        let types = types_of("commons x\n\ntype Page[T] = { items: List[T] }\n");
1856        assert!(wire_type("Page", &types["Page"], &types, Provenance::Owned).is_none());
1857    }
1858
1859    /// Part 1.4's cross-check: for an `on call` handler, `wire.rs`'s codec
1860    /// walk (`collect_boundary_types`, restricted to that one handler) and
1861    /// `contract.rs`'s canonical hash form (`service_normal_form`, over the
1862    /// same handler projected as a `CrossContextService`) must reach the
1863    /// exact same *set* of named boundary types — even though the module
1864    /// doc's comparison table says the two disagree on purpose about
1865    /// *ordering* (declaration order vs sorted) and about whether an opaque
1866    /// predicate is shown. This test asserts REACHABILITY only: the set of
1867    /// type names each derivation's walk visits from the same root, not any
1868    /// string equality or order between the two renderings.
1869    ///
1870    /// The type names in the fixture are chosen so none is a substring of
1871    /// another (`ClientId`, `Address`, `Profile`, `Unrelated`) —
1872    /// `contract.rs`'s `canon_type`/`canon_named_in` are private to that
1873    /// module, so rather than duplicating their traversal here, this test
1874    /// recovers the set of types `service_normal_form`'s rendered string
1875    /// reaches by substring containment against every declared type name.
1876    /// With non-overlapping names that containment test is unambiguous.
1877    ///
1878    /// `Unrelated` is declared but reachable from no handler, so the
1879    /// equality assertion below is not vacuously true merely because this
1880    /// fixture happens to make every *other* declared type reachable — a
1881    /// regression that made `collect_boundary_types` return every declared
1882    /// name instead of the reachable closure would leak `Unrelated` into
1883    /// `boundary_names`, and this test would catch it.
1884    #[test]
1885    fn boundary_reachability_agrees_with_contract_normal_form() {
1886        let src = r#"
1887context test
1888
1889type ClientId = String where NonEmpty
1890type Address = { street: String, city: String }
1891type Profile = { id: ClientId, home: Address }
1892
1893// Declared, but reachable from no handler below (see the doc comment on
1894// this test for why).
1895type Unrelated = { n: Int }
1896
1897service Api {
1898  on call(client: ClientId) -> Effect[Profile] by Caller {
1899    Profile { id: client, home: Address { street: "x", city: "y" } }
1900  }
1901}
1902"#;
1903        let (types, services) = context_of(src);
1904        let service = &services["Api"];
1905        let handler = &service.handlers[0];
1906
1907        // Restrict `collect_boundary_types`'s walk to exactly this handler —
1908        // the same synthetic-single-handler-service narrowing
1909        // `bynk-ide`'s `wire_contract_for_service` performs, so a service
1910        // with more than one handler could not leak an unrelated handler's
1911        // types into either side of this comparison.
1912        let mut narrowed = service.clone();
1913        narrowed.handlers = vec![handler.clone()];
1914        let narrowed_services: HashMap<String, ServiceDecl> =
1915            HashMap::from([("Api".to_string(), narrowed)]);
1916        let agents: HashMap<String, AgentDecl> = HashMap::new();
1917        let boundary_names: std::collections::HashSet<String> =
1918            collect_boundary_types(&types, &narrowed_services, &agents, &[])
1919                .into_iter()
1920                .collect();
1921
1922        // The same handler, projected as a `CrossContextService` exactly as
1923        // `bynk-emit`'s `own_contract_hashes` / `bynk-ide`'s
1924        // `wire_contract::contract_form` project it, canonicalised through
1925        // the same type table.
1926        let svc = crate::resolver::CrossContextService {
1927            name: "Api".to_string(),
1928            params: handler
1929                .params
1930                .iter()
1931                .map(|p| (p.name.name.clone(), p.type_ref.clone()))
1932                .collect(),
1933            return_type: handler.return_type.clone(),
1934            span: handler.span,
1935            foreign_callers: Vec::new(),
1936        };
1937        let normal_form = crate::contract::service_normal_form(&svc, &types);
1938
1939        let contract_reachable: std::collections::HashSet<String> = types
1940            .keys()
1941            .filter(|name| normal_form.contains(name.as_str()))
1942            .cloned()
1943            .collect();
1944
1945        assert_eq!(
1946            boundary_names, contract_reachable,
1947            "wire::collect_boundary_types and contract::service_normal_form must \
1948             agree on *which* named types a handler's contract reaches, even though \
1949             they render/order that set completely differently (see this module's \
1950             doc comparison table):\n\
1951             wire.rs reached:     {boundary_names:?}\n\
1952             contract.rs reached: {contract_reachable:?}\n\
1953             normal form:         {normal_form:?}"
1954        );
1955        assert!(
1956            !boundary_names.contains("Unrelated") && !contract_reachable.contains("Unrelated"),
1957            "`Unrelated` is declared but reachable from no handler — both derivations \
1958             must exclude it, not merely agree on every declared type by coincidence:\n\
1959             wire.rs reached: {boundary_names:?}\n\
1960             contract.rs reached: {contract_reachable:?}"
1961        );
1962    }
1963
1964    /// `wire_ref` is the plan's flagged highest-risk function ("its two
1965    /// functions must stay in exact agreement about which `WireRef` arm a
1966    /// `TypeRef` resolves to"). Pin the arm each shape lands on before Phase 2
1967    /// starts consuming it.
1968    #[test]
1969    fn wire_ref_dispatches_every_type_ref_shape_to_the_expected_arm() {
1970        let types: HashMap<String, Arc<TypeDecl>> = HashMap::new();
1971        let sp = || bynk_syntax::span::Span::new(0, 0);
1972        let named = |n: &str| {
1973            TypeRef::Named(Ident {
1974                name: n.to_string(),
1975                span: sp(),
1976            })
1977        };
1978        let base = |b: BaseType| TypeRef::Base(b, sp());
1979
1980        assert!(matches!(
1981            wire_ref(&base(BaseType::Int), &types),
1982            WireRef::Base {
1983                base: BaseType::Int,
1984                json: JsonKind::Number,
1985                ..
1986            }
1987        ));
1988        assert!(matches!(
1989            wire_ref(&base(BaseType::Bytes), &types),
1990            WireRef::Bytes
1991        ));
1992        assert!(
1993            matches!(wire_ref(&named("ClientId"), &types), WireRef::Named { name } if name == "ClientId")
1994        );
1995        assert!(matches!(
1996            wire_ref(
1997                &TypeRef::Result(Box::new(base(BaseType::Int)), Box::new(base(BaseType::String)), sp()),
1998                &types
1999            ),
2000            WireRef::Inst { key } if key == "Result_Int_String"
2001        ));
2002        assert!(matches!(
2003            wire_ref(&TypeRef::Option(Box::new(base(BaseType::Int)), sp()), &types),
2004            WireRef::Inst { key } if key == "Option_Int"
2005        ));
2006        assert!(matches!(
2007            wire_ref(&TypeRef::List(Box::new(base(BaseType::Int)), sp()), &types),
2008            WireRef::Inst { key } if key == "List_Int"
2009        ));
2010        assert!(matches!(
2011            wire_ref(
2012                &TypeRef::Map(Box::new(base(BaseType::String)), Box::new(base(BaseType::Int)), sp()),
2013                &types
2014            ),
2015            WireRef::Inst { key } if key == "Map_String_Int"
2016        ));
2017        assert!(matches!(
2018            wire_ref(
2019                &TypeRef::App {
2020                    name: Ident { name: "Paginated".to_string(), span: sp() },
2021                    args: vec![named("User")],
2022                    span: sp(),
2023                },
2024                &types
2025            ),
2026            WireRef::Inst { key } if key == "Paginated_User"
2027        ));
2028        assert!(matches!(
2029            wire_ref(&TypeRef::Unit(sp()), &types),
2030            WireRef::Unit
2031        ));
2032        assert!(matches!(
2033            wire_ref(
2034                &TypeRef::Effect(Box::new(base(BaseType::Int)), sp()),
2035                &types
2036            ),
2037            WireRef::Unchecked {
2038                reason: UncheckedReason::Effect
2039            }
2040        ));
2041        assert!(matches!(
2042            wire_ref(
2043                &TypeRef::HttpResult(Box::new(base(BaseType::Int)), sp()),
2044                &types
2045            ),
2046            WireRef::Unchecked {
2047                reason: UncheckedReason::HttpResult
2048            }
2049        ));
2050        assert!(matches!(
2051            wire_ref(&TypeRef::ValidationError(sp()), &types),
2052            WireRef::Unchecked {
2053                reason: UncheckedReason::ValidationError
2054            }
2055        ));
2056        assert!(matches!(
2057            wire_ref(&TypeRef::DecodeError(sp()), &types),
2058            WireRef::Unchecked {
2059                reason: UncheckedReason::DecodeError
2060            }
2061        ));
2062        assert!(matches!(
2063            wire_ref(&TypeRef::QueueResult(sp()), &types),
2064            WireRef::Unchecked {
2065                reason: UncheckedReason::QueueResult
2066            }
2067        ));
2068    }
2069}