Skip to main content

bynk_ide/
wire_contract.rs

1//! #855: the wire-contract peek — the model behind "hover a service handler"
2//! and "Show Wire Contract". Renders `bynk_check::wire::WireModel` (the
3//! same IR `bynk-emit`'s codec generation consumes) narrowed to *one*
4//! handler, plus the facts the IR does not carry: the request envelope
5//! shape, the cross-context contract form + hash (`on call` only), and the
6//! HTTP response set a route can actually answer with.
7//!
8//! **Handler resolution** mirrors `bynk-lsp/src/sequence_request.rs`'s
9//! `sequence_model_at`: re-parse the committed snapshot with
10//! `parse_unit_with_recovery`, find the `Handler` whose span contains the
11//! cursor. The re-parsed `Handler` supplies spans/body; the **retained**
12//! [`ContextBoundaryInfo`] supplies the type table — a single-file re-parse
13//! cannot see a `uses` target's types, which is the whole reason that table
14//! is retained project-wide (Phase 3).
15//!
16//! **Provenance.** [`bynk_check::wire::Provenance`] distinguishes a type this
17//! module owns from one reached through another unit. `ContextBoundaryInfo`'s
18//! `types` table is `contract_types_for(unit, …)` — *this* unit's own type
19//! namespace: own declarations, its `uses` targets', and (#2073) the types of
20//! the contexts it consumes, which its own signatures may name — the exact
21//! table `own_contract_hashes` (`bynk-driver/src/project.rs`) hashes a
22//! service's contract through. Every name resolvable through it is this
23//! unit's *own* view of its boundary, so the peek reports
24//! `Provenance::Owned` throughout, a borrowed consumed type included. A
25//! caller's view of another unit's boundary is out of scope for a peek that
26//! answers "what does this handler send and receive".
27//!
28//! **Scope.** Service handlers only. An agent's `on call` handler crosses a
29//! Durable-Object RPC boundary too, but the issue's worked examples (an HTTP
30//! route, a cross-context `on call`) are both service handlers, and
31//! `ContextBoundaryInfo` does not retain agents' own handler bodies in a form
32//! this module needs. Left for a later slice if an agent peek is wanted.
33
34use std::collections::HashMap;
35use std::path::PathBuf;
36
37use bynk_check::analysis::ContextBoundaryInfo;
38use bynk_check::checker::{Ty, TyId, Types};
39use bynk_check::contract;
40use bynk_check::resolver::CrossContextService;
41use bynk_check::wire::{self, WireModel, WireRef};
42use bynk_syntax::ast::*;
43use bynk_syntax::span::{FileId, Span};
44
45const HTTP_RESULT: &str = bynk_check::builtin_names::types::HTTP_RESULT;
46
47/// Which protocol hosts the hovered handler: the system model's own
48/// [`bynk_model::IrHandlerKind`], read through `bynk_model::lower_handler_kind_ir`.
49///
50/// This was an IDE-local mirror of `HandlerKind` until crate-hygiene B1 (#2939).
51/// It was kept separate "so a future field this peek needs is a local
52/// addition". The system-model ADR reverses that under M-1: a field the peek
53/// needs becomes a field of the model, where it gets a second reader for free.
54///
55/// The re-export keeps the old name, so `bynk-lsp` and `bynk openapi` name the
56/// model's type without a dependency edge of their own.
57pub use bynk_model::IrHandlerKind as BoundaryKind;
58/// [`BoundaryKind::Http`]'s method: the model's [`bynk_model::IrHttpMethod`].
59pub use bynk_model::IrHttpMethod;
60
61/// The request shape a handler's caller sends. **Three cases, not two** —
62/// `bynk-emit/src/emitter/workers_entry.rs`'s `h.params.len() == 1` branch is
63/// the *only* bare-value case; everything else, including **zero** params,
64/// takes the object branch. Rendering only `Bare`/`Keyed` would misstate a
65/// zero-arg service as accepting an (empty) object body it never inspects,
66/// when what actually happens is the body is not read at all.
67#[derive(Debug, Clone)]
68pub enum Envelope {
69    /// No params: the request body is not read.
70    Empty,
71    /// Exactly one param: the request body **is** the value of `param`,
72    /// with no wrapping object/key.
73    Bare { param: String, shape: WireRef },
74    /// Two or more params: an object keyed by parameter name, in
75    /// declaration order.
76    Keyed { params: Vec<(String, WireRef)> },
77    /// A `@raw(contentType:)` route: the request body is the octets of `param`
78    /// (a `Bytes`), sent under `content_type` (`"*/*"` for any) — not JSON, not
79    /// base64, and not wrapped in an object whatever the other params.
80    Raw { param: String, content_type: String },
81}
82
83/// The canonical form + hash of an `on call` handler's contract — the same
84/// projection `bynk-driver/src/project.rs`'s `own_contract_hashes` builds, so
85/// the hash this peek shows is provably the hash the emitted
86/// `X-Bynk-Contract` constant stamps.
87#[derive(Debug, Clone)]
88pub struct ContractForm {
89    pub normal_form: String,
90    pub hash: String,
91}
92
93/// Why a response was reachable — so a renderer can tell an author-declared
94/// outcome from one the boundary injects on their behalf without their
95/// having written a line for it.
96#[derive(Debug, Clone, PartialEq)]
97pub enum ResponseOrigin {
98    /// The handler's declared return type, `Effect[HttpResult[T]]` stripped
99    /// to its `Ok`/200 case.
100    DeclaredSuccess,
101    /// A variant literally constructed somewhere in the handler body, at
102    /// this span.
103    Constructed { span: Span },
104    /// A response the body never names — injected by the boundary itself.
105    BoundaryImplicit { why: &'static str },
106}
107
108/// One reachable HTTP outcome.
109#[derive(Debug, Clone, PartialEq)]
110pub struct HttpResponse {
111    pub status: u16,
112    /// The `HttpResult` variant name (`"Ok"`, `"TooManyRequests"`), or a
113    /// representative `BoundaryError` `kind` for a boundary-implicit
114    /// response with no variant of its own (`"StructuralMismatch"`).
115    pub variant: String,
116    pub origin: ResponseOrigin,
117}
118
119/// Why there is no cross-context contract to show for this handler.
120/// Rendered on the panel only — hover stays quiet about an absence (Part 4).
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum NoCrossContextReason {
123    /// Not an `on call` handler — HTTP/cron/message/websocket/event
124    /// handlers are never reached by another context's call.
125    NotACallHandler,
126    /// The project has only this one context/adapter — there is no *other*
127    /// context that could call in, so the question does not arise.
128    SingleContext,
129}
130
131/// The wire contract of one handler: its request envelope, its reachable
132/// response set (HTTP handlers only), its cross-context contract form + hash
133/// (`on call` only), and the boundary type shapes both reference.
134#[derive(Debug, Clone)]
135pub struct WireContractModel {
136    pub unit: String,
137    pub service: String,
138    pub kind: BoundaryKind,
139    pub handler_span: Span,
140    /// 1-indexed line of `handler_span`'s start, against the text this
141    /// model was built from.
142    pub handler_line: usize,
143    pub envelope: Envelope,
144    /// `on call` only; `None` whenever [`Self::no_cross_context`] is `Some`.
145    pub contract: Option<ContractForm>,
146    /// The boundary types this handler's envelope + responses reference,
147    /// resolved through the retained [`ContextBoundaryInfo`] — the same IR
148    /// `bynk-emit`'s codec generation renders.
149    pub boundary: WireModel,
150    /// Declaration span for every named type in `boundary.types`, keyed by
151    /// name — click-to-code for the panel's per-type blocks.
152    pub type_sites: HashMap<String, Span>,
153    /// Empty for a non-HTTP handler.
154    pub responses: Vec<HttpResponse>,
155    /// Whether the handler may answer `Ok`: its body constructs one, or yields
156    /// an `HttpResult` the walk cannot see into (a helper's result). The
157    /// declared success is always listed in [`Self::responses`] (as
158    /// [`ResponseOrigin::DeclaredSuccess`]) whether or not the body returns it,
159    /// so a consumer that wants only what the handler *can* answer — the
160    /// OpenAPI export (#856) — uses this to drop it when it provably cannot.
161    pub ok_reachable: bool,
162    /// #3609: the `T` of the handler's `HttpResult[T]`, resolved against
163    /// [`Self::boundary`] as the envelope's refs are. `None` for a non-HTTP
164    /// handler, a return that is not an `HttpResult`, and a `()` payload —
165    /// which is what a raw-response handler (`Raw(..)`) declares, so a client
166    /// knows there is no typed body to check paths against.
167    pub success: Option<WireRef>,
168    pub no_cross_context: Option<NoCrossContextReason>,
169}
170
171/// How many **real** contexts/adapters a project has — the input
172/// [`wire_contract_at`]/[`wire_contract_for_service`]'s `context_count`
173/// wants, deciding [`NoCrossContextReason::SingleContext`].
174///
175/// **Must** be computed this way, not as a bare `boundary_info.len()`:
176/// `boundary_info` (mirroring `sequence_info`, #846) retains an entry for
177/// every `UnitKind::Context | UnitKind::Adapter`, which includes the
178/// synthetic toolchain-injected `bynk` capability-surface unit — so a
179/// project with nothing but `consumes bynk { Clock }` would count *two*
180/// "contexts" and `SingleContext` would almost never fire. `unit_sources`
181/// (ADR 0095) already excludes synthetic units for exactly this reason
182/// (document links, consumed-context navigation); intersecting against it
183/// reuses that existing filter rather than a bespoke `name == "bynk"` check.
184///
185/// A free function (not buried in a caller's own helper) precisely so
186/// `bynk-lsp`'s `bynk/wireContract` handler calls this — the one place the
187/// filter is encoded — instead of re-deriving `boundary_info.len()` from
188/// the plan's literal parameter name and reintroducing the bug.
189pub fn real_context_count(
190    boundary_info: &HashMap<String, ContextBoundaryInfo>,
191    unit_sources: &HashMap<String, Vec<PathBuf>>,
192) -> usize {
193    boundary_info
194        .keys()
195        .filter(|k| unit_sources.contains_key(k.as_str()))
196        .count()
197}
198
199/// Locate the `Handler` enclosing `offset` in `text` and build its wire
200/// contract. Mirrors `sequence_request::sequence_model_at`'s re-parse
201/// convention. `info` is the owning unit's retained boundary table (Phase
202/// 3); `expr_types` is that same file's checked expression types (empty for
203/// a file with errors — the `Ok`-overload disambiguation then falls back to
204/// the declared return type, see `ResponseWalk::is_http_result_expr` below).
205///
206/// `context_count` is how many **real** contexts/adapters the project has —
207/// build it with [`real_context_count`], not a bare `boundary_info.len()`
208/// (see that function's doc for why the difference matters).
209///
210/// Scoped to service handlers (see the module doc); an agent handler at
211/// `offset` answers `None`.
212pub fn wire_contract_at(
213    unit: &str,
214    text: &str,
215    offset: usize,
216    info: &ContextBoundaryInfo,
217    expr_types: &[(Span, TyId)],
218    tys: &Types,
219    context_count: usize,
220) -> Option<WireContractModel> {
221    let tokens = bynk_syntax::lexer::tokenize(text).ok()?;
222    let (parsed, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
223    let items: &[CommonsItem] = match parsed.as_ref()? {
224        SourceUnit::Context(c) => &c.items,
225        SourceUnit::Adapter(a) => &a.items,
226        SourceUnit::Commons(_) | SourceUnit::Suite(_) => return None,
227    };
228    for item in items {
229        if let CommonsItem::Service(s) = item
230            && let Some(h) = handler_at(&s.handlers, offset)
231        {
232            return wire_contract_for_service(
233                unit,
234                text,
235                &s.name.name,
236                h,
237                info,
238                expr_types,
239                tys,
240                context_count,
241            );
242        }
243    }
244    None
245}
246
247fn handler_at(handlers: &[Handler], offset: usize) -> Option<&Handler> {
248    handlers
249        .iter()
250        .find(|h| h.span.start <= offset && offset < h.span.end)
251}
252
253/// Build the wire contract for one already-located handler. The pure half of
254/// [`wire_contract_at`] — the part that never touches the offset/re-parse
255/// machinery — split out the same way `sequence_model_at` delegates to
256/// `sequence::sequence_model`.
257///
258/// `service_name` must name an entry in `info.services` (the owning unit's
259/// retained service table) — the handler is spliced into a clone of that
260/// declaration (a synthetic single-handler service) so
261/// `bynk_check::wire::collect_boundary_types` narrows its walk to exactly
262/// this handler's params/return, not the whole service's. `None` if the
263/// service is not (yet) in the retained table — a live-buffer/committed-round
264/// mismatch (the same class of staleness `sequence_model_at` accepts for
265/// `sequence_info`).
266#[allow(clippy::too_many_arguments)]
267pub fn wire_contract_for_service(
268    unit: &str,
269    text: &str,
270    service_name: &str,
271    handler: &Handler,
272    info: &ContextBoundaryInfo,
273    expr_types: &[(Span, TyId)],
274    tys: &Types,
275    context_count: usize,
276) -> Option<WireContractModel> {
277    let real = info.services.get(service_name)?;
278    let mut synthetic = real.clone();
279    synthetic.handlers = vec![handler.clone()];
280    let services: HashMap<String, ServiceDecl> =
281        HashMap::from([(service_name.to_string(), synthetic)]);
282    let agents: HashMap<String, AgentDecl> = HashMap::new();
283
284    let boundary_names = wire::collect_boundary_types(&info.types, &services, &agents, &[]);
285    let insts =
286        wire::collect_generic_instantiations(&services, &agents, &boundary_names, &info.types, &[]);
287    // Every name reachable through `info.types` is this unit's own view of
288    // its boundary — see the module doc's Provenance note.
289    let boundary = wire::boundary_model(&boundary_names, &info.types, insts, |_| {
290        wire::Provenance::Owned
291    });
292
293    let type_sites: HashMap<String, Span> = boundary_names
294        .iter()
295        .filter_map(|n| info.types.get(n).map(|d| (n.clone(), d.span)))
296        .collect();
297
298    let envelope = envelope_for(handler, &info.types);
299    let kind = bynk_model::lower_handler_kind_ir(&handler.kind);
300
301    let no_cross_context = if context_count <= 1 {
302        Some(NoCrossContextReason::SingleContext)
303    } else if kind != bynk_model::IrHandlerKind::Call {
304        Some(NoCrossContextReason::NotACallHandler)
305    } else {
306        None
307    };
308    let contract = if no_cross_context.is_none() {
309        Some(contract_form(service_name, handler, &info.types))
310    } else {
311        None
312    };
313
314    let success = if matches!(kind, BoundaryKind::Http { .. }) {
315        http_result_inner(&handler.return_type)
316            .filter(|t| !matches!(t, TypeRef::Unit(_)))
317            .map(|t| wire::wire_ref(t, &info.types))
318    } else {
319        None
320    };
321    let (responses, ok_reachable) = if matches!(kind, BoundaryKind::Http { .. }) {
322        (
323            http_responses(handler, real.span.file, expr_types, tys),
324            ok_is_reachable(handler, real.span.file, expr_types, tys),
325        )
326    } else {
327        (Vec::new(), false)
328    };
329
330    Some(WireContractModel {
331        unit: unit.to_string(),
332        service: service_name.to_string(),
333        kind,
334        handler_span: handler.span,
335        handler_line: line_of(text, handler.span.start),
336        envelope,
337        contract,
338        boundary,
339        type_sites,
340        responses,
341        ok_reachable,
342        success,
343        no_cross_context,
344    })
345}
346
347/// 1-indexed line number of `offset` in `text`.
348fn line_of(text: &str, offset: usize) -> usize {
349    text.get(..offset).unwrap_or(text).matches('\n').count() + 1
350}
351
352fn envelope_for(handler: &Handler, types: &HashMap<String, std::sync::Arc<TypeDecl>>) -> Envelope {
353    if let Some(content_type) = handler.raw_content_type() {
354        return Envelope::Raw {
355            param: "body".to_string(),
356            content_type: content_type.to_string(),
357        };
358    }
359    match handler.params.as_slice() {
360        [] => Envelope::Empty,
361        [p] => Envelope::Bare {
362            param: p.name.name.clone(),
363            shape: wire::wire_ref(&p.type_ref, types),
364        },
365        params => Envelope::Keyed {
366            params: params
367                .iter()
368                .map(|p| (p.name.name.clone(), wire::wire_ref(&p.type_ref, types)))
369                .collect(),
370        },
371    }
372}
373
374/// The same `CrossContextService` projection `own_contract_hashes`
375/// (`bynk-driver/src/project.rs`) builds, canonicalised through the same
376/// `info.types` table — so the hash this peek shows is provably the hash
377/// the emitted `X-Bynk-Contract` constant stamps.
378fn contract_form(
379    service_name: &str,
380    handler: &Handler,
381    types: &HashMap<String, std::sync::Arc<TypeDecl>>,
382) -> ContractForm {
383    let svc = CrossContextService {
384        name: service_name.to_string(),
385        params: handler
386            .params
387            .iter()
388            .map(|p| (p.name.name.clone(), p.type_ref.clone()))
389            .collect(),
390        return_type: handler.return_type.clone(),
391        span: handler.span,
392        foreign_callers: Vec::new(),
393    };
394    let normal_form = contract::service_normal_form(&svc, types);
395    let hash = contract::contract_hash(&normal_form);
396    ContractForm { normal_form, hash }
397}
398
399/// The reachable HTTP response set: the declared success case, every
400/// variant literally constructed in the body, and the boundary-implicit
401/// cases the body never names (400 on any param, 404 on an `Option?`
402/// short-circuit — ADR 0177). 401 on a caller binding is deferred (plan
403/// risk 8; needs actor/`by` resolution this phase does not do).
404///
405/// `file` is the handler's own file — the retained service declaration's
406/// `FileId`, since a service lives in one file — which scopes the
407/// `expr_types` lookup (see `ResponseWalk::file`).
408fn http_responses(
409    handler: &Handler,
410    file: FileId,
411    expr_types: &[(Span, TyId)],
412    tys: &Types,
413) -> Vec<HttpResponse> {
414    let declared_is_http_result =
415        matches!(strip_effect(&handler.return_type), TypeRef::HttpResult(..));
416
417    let mut out = Vec::new();
418    if declared_is_http_result {
419        out.push(HttpResponse {
420            status: 200,
421            variant: "Ok".to_string(),
422            origin: ResponseOrigin::DeclaredSuccess,
423        });
424    }
425
426    let mut walk = ResponseWalk {
427        expr_types,
428        file,
429        tys,
430        declared_is_http_result,
431        seen: out.iter().map(response_key).collect(),
432        saw_option_question: false,
433        out: Vec::new(),
434    };
435    walk.walk_block(&handler.body);
436    out.extend(walk.out);
437
438    if !handler.params.is_empty() {
439        out.push(HttpResponse {
440            status: 400,
441            variant: "StructuralMismatch".to_string(),
442            origin: ResponseOrigin::BoundaryImplicit {
443                why: "every param is structurally re-validated on the way in; a malformed or \
444                      refinement-violating value fails closed with a 400 the handler body \
445                      never names",
446            },
447        });
448    }
449    if handler.raw_content_type().is_some() {
450        out.push(HttpResponse {
451            status: 413,
452            variant: "PayloadTooLarge".to_string(),
453            origin: ResponseOrigin::BoundaryImplicit {
454                why: "a raw body is counted as it is read and cut off at the route's cap",
455            },
456        });
457        out.push(HttpResponse {
458            status: 415,
459            variant: "UnsupportedMediaType".to_string(),
460            origin: ResponseOrigin::BoundaryImplicit {
461                why: "the request's Content-Type is not the media type `@raw` declares",
462            },
463        });
464    }
465    // #3276: a `@form` route answers `415` to any other `Content-Type`, and `413`
466    // to a body over its cap, before the handler runs.
467    let multipart = handler
468        .annotations
469        .iter()
470        .any(|a| a.name.name == "multipart");
471    if multipart {
472        out.push(HttpResponse {
473            status: 415,
474            variant: "UnsupportedMediaType".to_string(),
475            origin: ResponseOrigin::BoundaryImplicit {
476                why: "the request's Content-Type is not `multipart/form-data`",
477            },
478        });
479        out.push(HttpResponse {
480            status: 413,
481            variant: "PayloadTooLarge".to_string(),
482            origin: ResponseOrigin::BoundaryImplicit {
483                why: "the body, a file part or the part count is over the route's cap",
484            },
485        });
486    }
487    if handler.annotations.iter().any(|a| a.name.name == "form") {
488        out.push(HttpResponse {
489            status: 415,
490            variant: "UnsupportedMediaType".to_string(),
491            origin: ResponseOrigin::BoundaryImplicit {
492                why: "the request's Content-Type is not `application/x-www-form-urlencoded` (UTF-8)",
493            },
494        });
495        if handler.limit_max_body().is_some() {
496            out.push(HttpResponse {
497                status: 413,
498                variant: "PayloadTooLarge".to_string(),
499                origin: ResponseOrigin::BoundaryImplicit {
500                    why: "a capped body is counted as it is read and cut off at the route's cap",
501                },
502            });
503        }
504    }
505    if walk.saw_option_question {
506        out.push(HttpResponse {
507            status: 404,
508            variant: "NotFound".to_string(),
509            origin: ResponseOrigin::BoundaryImplicit {
510                why: "an `Option?` short-circuits to 404 on `None` (ADR 0177)",
511            },
512        });
513    }
514    out
515}
516
517/// Whether the handler may answer `Ok`: its body constructs one, or returns
518/// an `HttpResult` the walk cannot see into (a call to a helper, a bound
519/// local). [`http_responses`]' walk seeds `Ok` from the declared return type, so
520/// it cannot say; this is the sound reading, which drops the declared success
521/// only when every `HttpResult` the body yields is a variant it names.
522fn ok_is_reachable(
523    handler: &Handler,
524    file: FileId,
525    expr_types: &[(Span, TyId)],
526    tys: &Types,
527) -> bool {
528    let mut walk = ResponseWalk {
529        expr_types,
530        file,
531        tys,
532        declared_is_http_result: matches!(
533            strip_effect(&handler.return_type),
534            TypeRef::HttpResult(..)
535        ),
536        seen: Default::default(),
537        saw_option_question: false,
538        out: Vec::new(),
539    };
540    walk.walk_block(&handler.body);
541    if walk.out.iter().any(|r| r.variant == "Ok") {
542        return true;
543    }
544    let mut exprs = Vec::new();
545    for st in &handler.body.statements {
546        statement_exprs(st, &mut exprs);
547    }
548    exprs.push(&handler.body.tail);
549    exprs.into_iter().any(|e| walk.opaque_http_result(e))
550}
551
552/// `Effect[HttpResult[T]]` / `HttpResult[T]` → `T`; `None` when the declared
553/// return is not an `HttpResult`. The one place the payload type is read, shared
554/// with `bynk openapi` so the two cannot drift.
555pub fn http_result_inner(t: &TypeRef) -> Option<&TypeRef> {
556    match strip_effect(t) {
557        TypeRef::HttpResult(inner, _) => Some(inner.as_ref()),
558        _ => None,
559    }
560}
561
562/// The wire shape of the body one response carries (#3609), given the model's
563/// [`WireContractModel::success`]: `T` for a value variant, `None` for
564/// everything else. A message variant's body is `{ "error": String }` and a
565/// redirect's location travels in a header with no body (as `bynk openapi`
566/// describes them); neither is a ref into `types`, so they are left `None`
567/// here and described by [`response_body`] instead (#3632). Boundary-implicit
568/// responses are `None` too — the boundary shapes their bodies, not the handler.
569pub fn response_payload(resp: &HttpResponse, success: Option<&WireRef>) -> Option<WireRef> {
570    match response_body(resp, success)? {
571        ResponseBody::Value(r) => Some(r),
572        _ => None,
573    }
574}
575
576/// What a response's body is (#3632): the classification `bynk openapi`'s
577/// `responses_of` makes per `HttpVariantPayload`, as data a client can read.
578#[derive(Debug, Clone)]
579pub enum ResponseBody {
580    /// `T`, the handler's `HttpResult[T]` payload, JSON-encoded.
581    Value(WireRef),
582    /// `{ "error": String }`.
583    Message,
584    /// No body; the target is the `Location` header.
585    Redirect,
586    /// Author-owned bytes under an author-chosen media type, no codec.
587    Raw,
588    /// `text/event-stream`.
589    Stream,
590}
591
592/// The header a [`ResponseBody::Redirect`] carries its target in.
593pub const REDIRECT_HEADER: &str = "Location";
594
595/// The body of one response, or `None` when it has none to describe: a
596/// no-payload variant, a `()` value payload, or a boundary-implicit response
597/// (the boundary shapes those bodies, not the handler).
598pub fn response_body(resp: &HttpResponse, success: Option<&WireRef>) -> Option<ResponseBody> {
599    if matches!(resp.origin, ResponseOrigin::BoundaryImplicit { .. }) {
600        return None;
601    }
602    Some(match http_variant(&resp.variant)?.payload {
603        HttpVariantPayload::Value => ResponseBody::Value(success?.clone()),
604        HttpVariantPayload::Message => ResponseBody::Message,
605        HttpVariantPayload::Location => ResponseBody::Redirect,
606        HttpVariantPayload::Streamed => ResponseBody::Stream,
607        HttpVariantPayload::Raw
608        | HttpVariantPayload::RawTagged
609        | HttpVariantPayload::RawStreamed
610        | HttpVariantPayload::RawError => ResponseBody::Raw,
611        HttpVariantPayload::None => return None,
612    })
613}
614
615/// Strip `Effect[_]` to expose the inner type — mirrors
616/// `bynk-emit/src/emitter/workers_entry.rs`'s `http_result_inner`, one level
617/// short of unwrapping `HttpResult` itself (the caller checks that).
618fn strip_effect(t: &TypeRef) -> &TypeRef {
619    match t {
620        TypeRef::Effect(inner, _) => inner.as_ref(),
621        other => other,
622    }
623}
624
625/// The handler-body expression walk finding every literally-constructed
626/// `HttpResult` variant, plus whether an `Option?` short-circuit is present
627/// (the boundary-implicit 404). Structured after `bynk-ide/src/sequence.rs`'s
628/// `Builder` — a small piece of walk state threaded through recursive
629/// `walk_*` methods — but this walk is a *full* expression descent (via
630/// `bynk_syntax::ast::expr_children`), not `sequence.rs`'s statement-level
631/// control-flow-only walk: a response can be constructed anywhere in an
632/// expression tree (a call argument, a record field), not only in tail
633/// position.
634struct ResponseWalk<'a> {
635    expr_types: &'a [(Span, TyId)],
636    /// The handler's own file. A file's `expr_types` is not only its own
637    /// spans: `check_pipeline` merges a sibling file's methods on a type
638    /// declared here into this file's checked view, so their bodies' spans
639    /// (byte offsets into the *sibling's* text) land in this vector too.
640    /// Only entries stamped with this `FileId` are this file's.
641    file: FileId,
642    /// T3.6b (R4.1): the table `expr_types`' ids resolve against.
643    tys: &'a Types,
644    /// #855 risk 7 ("the `Ok` overload"): the declared-return-type fallback
645    /// used whenever `expr_types` has no entry for a span (an expression the
646    /// checker never typed — ADR 0094's partial types still miss those) —
647    /// mirrors `bynk-emit/src/emitter/lower.rs`'s own `Ok`/`HttpResult` overload
648    /// disambiguation, which has the identical ambiguity and the identical
649    /// (checker-backed, so never actually degraded there) resolution.
650    /// Applied to `Ok` and bare `Call` (see `is_http_result_expr` below) but
651    /// **not** a bare `Ident` (see `is_http_result_ident` below), which has
652    /// no concrete-shaped signal to fall back onto and would misreport an
653    /// ordinary local whose name collides with a variant name.
654    declared_is_http_result: bool,
655    seen: std::collections::HashSet<String>,
656    saw_option_question: bool,
657    out: Vec<HttpResponse>,
658}
659
660impl<'a> ResponseWalk<'a> {
661    /// The checker-recorded type at `span`: an entry in [`Self::file`] over
662    /// the same byte range. `span`'s own `FileId` is ignored — the handler
663    /// may come from [`wire_contract_at`]'s reparse, which stamps
664    /// `FileId::UNKNOWN`, while `expr_types` carries the analysis round's
665    /// real ids (T3.5, #1062), so `Span`'s derived `PartialEq` would never
666    /// match. A recorded `Ty::Error` is "no type", so it degrades to the
667    /// same fallback as a missing entry.
668    fn expr_ty(&self, span: Span) -> Option<std::sync::Arc<Ty>> {
669        self.expr_types
670            .iter()
671            .find(|(s, _)| s.file == self.file && s.start == span.start && s.end == span.end)
672            .map(|(_, t)| self.tys.get(*t))
673            .filter(|t| !matches!(**t, Ty::Error))
674    }
675
676    /// Whether `span`'s expression checked as `HttpResult[_]` — the same
677    /// disambiguation `lower.rs:720-731` performs for the `Ok` overload,
678    /// degrading to the declared-return heuristic when the checker recorded
679    /// nothing (see `declared_is_http_result`'s doc). Used for `Ok` and
680    /// `Call`: a bare `Call { name, .. }` already carries a concrete
681    /// variant-shaped name (`TooManyRequests(...)`), so the same fallback
682    /// is low-risk there. **Not** used for a bare `Ident` — see
683    /// `is_http_result_ident` below.
684    fn is_http_result_expr(&self, span: Span) -> bool {
685        match self.expr_ty(span).as_deref() {
686            Some(Ty::HttpResult(_)) => true,
687            Some(_) => false,
688            None => self.declared_is_http_result,
689        }
690    }
691
692    /// The stricter check for a bare `Ident` — never falls back to the
693    /// declared-return heuristic. `HTTP_VARIANTS` includes names an author
694    /// can plausibly bind as an ordinary local (`Found`, `Gone`, `Conflict`,
695    /// `Accepted`, `Created`, `Raw`, `Streaming`): with the same fallback as
696    /// `is_http_result_expr`, a file with errors and a `let found = …;
697    /// found` tail on an `HttpResult`-returning handler would misreport a
698    /// 302 that was never constructed. `Ok`/`Call` need the fallback because
699    /// degrading them means answering nothing at all for the *one*
700    /// expression the plan's risk 7 is about; a bare identifier read has no
701    /// such asymmetry — unknown stays unknown.
702    fn is_http_result_ident(&self, span: Span) -> bool {
703        matches!(self.expr_ty(span).as_deref(), Some(Ty::HttpResult(_)))
704    }
705
706    fn push(&mut self, variant: HttpVariant, span: Span) {
707        self.push_status(variant, variant.status, span);
708    }
709
710    /// #2341 (L4): a `RawError` answers the status its first argument names,
711    /// so each distinct status is its own response.
712    fn push_raw_error(&mut self, variant: HttpVariant, args: &[Expr], span: Span) {
713        if let Some(status) = args.first().and_then(raw_error_status) {
714            self.push_status(variant, status, span);
715        }
716    }
717
718    fn push_status(&mut self, variant: HttpVariant, status: u16, span: Span) {
719        if self.seen.insert(variant_key(variant.name, status)) {
720            self.out.push(HttpResponse {
721                status,
722                variant: variant.name.to_string(),
723                origin: ResponseOrigin::Constructed { span },
724            });
725        }
726    }
727
728    fn walk_block(&mut self, b: &Block) {
729        for s in &b.statements {
730            let mut exprs = Vec::new();
731            statement_exprs(s, &mut exprs);
732            for e in exprs {
733                self.walk_expr(e);
734            }
735        }
736        self.walk_expr(&b.tail);
737    }
738
739    fn walk_expr(&mut self, e: &Expr) {
740        self.classify(e);
741        for child in expr_children(e) {
742            self.walk_expr(child);
743        }
744    }
745
746    /// The four recognition shapes `lower.rs` renders through
747    /// (`HttpResult.Variant(args)`/`HttpResult.Variant` qualified forms at
748    /// `:1417`/`:4149`, the bare `Ident`/`Call` forms disambiguated by
749    /// checker type at `:3781`/`:3834`), plus the `Ok` overload
750    /// (`:720-731`) and the `?`-on-`Option` boundary-implicit 404
751    /// (`:764-768`, ADR 0177).
752    /// Whether `e` (or anything under it) is an `HttpResult` value that is not a
753    /// variant construction the walk recognises — a helper's call, a local.
754    fn opaque_http_result(&self, e: &Expr) -> bool {
755        let named_variant = |n: &str| http_variant(n).is_some();
756        let leaf_opaque = match &e.kind {
757            ExprKind::Call { name, .. } => !named_variant(&name.name),
758            ExprKind::MethodCall { receiver, .. } => {
759                !matches!(&receiver.kind, ExprKind::Ident(id) if id.name == HTTP_RESULT)
760            }
761            ExprKind::Ident(id) => !named_variant(&id.name),
762            ExprKind::FieldAccess { receiver, .. } => {
763                !matches!(&receiver.kind, ExprKind::Ident(id) if id.name == HTTP_RESULT)
764            }
765            _ => false,
766        };
767        (leaf_opaque && matches!(self.expr_ty(e.span).as_deref(), Some(Ty::HttpResult(_))))
768            || expr_children(e)
769                .into_iter()
770                .any(|c| self.opaque_http_result(c))
771    }
772
773    fn classify(&mut self, e: &Expr) {
774        match &e.kind {
775            ExprKind::MethodCall {
776                receiver,
777                method,
778                args,
779                ..
780            } => {
781                if let ExprKind::Ident(id) = &receiver.kind
782                    && id.name == HTTP_RESULT
783                    && let Some(v) = http_variant(&method.name)
784                {
785                    if v.status == AUTHOR_CHOSEN_STATUS {
786                        self.push_raw_error(v, args, e.span);
787                    } else {
788                        self.push(v, e.span);
789                    }
790                }
791            }
792            ExprKind::FieldAccess { receiver, field } => {
793                if let ExprKind::Ident(id) = &receiver.kind
794                    && id.name == HTTP_RESULT
795                    && let Some(v) = http_variant(&field.name)
796                {
797                    self.push(v, e.span);
798                }
799            }
800            ExprKind::Ident(id) => {
801                if self.is_http_result_ident(e.span)
802                    && let Some(v) = http_variant(&id.name)
803                {
804                    self.push(v, e.span);
805                }
806            }
807            ExprKind::Call { name, args, .. } => {
808                if self.is_http_result_expr(e.span)
809                    && let Some(v) = http_variant(&name.name)
810                {
811                    if v.status == AUTHOR_CHOSEN_STATUS {
812                        self.push_raw_error(v, args, e.span);
813                    } else {
814                        self.push(v, e.span);
815                    }
816                }
817            }
818            ExprKind::Ok(_) => {
819                if self.is_http_result_expr(e.span)
820                    && let Some(v) = http_variant("Ok")
821                {
822                    self.push(v, e.span);
823                }
824            }
825            ExprKind::Question(inner) => {
826                if matches!(self.expr_ty(inner.span).as_deref(), Some(Ty::Option(_))) {
827                    self.saw_option_question = true;
828                }
829            }
830            _ => {}
831        }
832    }
833}
834
835/// The dedupe key of a response: its variant, plus the status for a variant
836/// whose status is chosen per construction (`RawError`, #2341).
837fn variant_key(variant: &str, status: u16) -> String {
838    match http_variant(variant) {
839        Some(v) if v.status == AUTHOR_CHOSEN_STATUS => format!("{variant} {status}"),
840        _ => variant.to_string(),
841    }
842}
843
844fn response_key(r: &HttpResponse) -> String {
845    variant_key(&r.variant, r.status)
846}
847
848#[cfg(test)]
849mod tests {
850    use super::*;
851    use std::path::PathBuf;
852
853    /// Same convention as `sequence.rs`/`architecture.rs`'s `setup_project`:
854    /// a temp dir unique to the test name, self-contained fixtures only
855    /// (never `examples/` — `bynk-ide` is published standalone).
856    fn setup_project(test_name: &str, files: &[(&str, &str)]) -> PathBuf {
857        let root = std::env::temp_dir().join(format!(
858            "bynk-ide-wire-contract-test-{test_name}-{}",
859            std::process::id()
860        ));
861        let _ = std::fs::remove_dir_all(&root);
862        std::fs::create_dir_all(&root).expect("create test root");
863        for (rel, contents) in files {
864            let p = root.join(rel);
865            if let Some(parent) = p.parent() {
866                std::fs::create_dir_all(parent).expect("create parent");
867            }
868            std::fs::write(&p, contents).expect("write file");
869        }
870        root
871    }
872
873    // -- Fixture: examples/rate-limiter's `GET /check/:client`, reproduced
874    // -- self-contained (not read from `examples/` — see `setup_project`)
875    // -- and simplified to a single file (no `uses window` — irrelevant to
876    // -- what this module resolves).
877    const RATELIMIT_SRC: &str = r#"context ratelimit
878
879consumes bynk { Clock }
880
881type ClientId = String where NonEmpty
882
883type RateView = {
884  allowed:   Bool,
885  remaining: Int,
886  resetAt:   Int,
887}
888
889agent Limiter {
890  key client: ClientId
891
892  store count: Cell[Int]
893
894  on call hit(now: Int) -> Effect[RateView] {
895    let _ <- count.update((c) => c + 1)
896    RateView { allowed: count < 10, remaining: 10 - count, resetAt: now }
897  }
898}
899
900service api from http {
901  on GET("/check/:client") (client: ClientId) -> Effect[HttpResult[RateView]] by Visitor given Clock {
902    let now  <- Clock.now()
903    let view <- Limiter(client).hit(now.toEpochMillis())
904    if view.allowed {
905      Ok(view)
906    } else {
907      TooManyRequests("rate limit exceeded")
908    }
909  }
910}
911"#;
912
913    fn find_offset(text: &str, needle: &str) -> usize {
914        text.find(needle)
915            .unwrap_or_else(|| panic!("`{needle}` not found in fixture"))
916    }
917
918    /// Thin wrapper over the module's own [`real_context_count`] — exercises
919    /// the exact function `bynk-lsp`'s `bynk/wireContract` handler must call
920    /// (Phase 5), rather than a test-local re-derivation that could drift
921    /// from it.
922    fn real_context_count(diag: &crate::ProjectDiagnostics) -> usize {
923        super::real_context_count(&diag.boundary_info, &diag.unit_sources)
924    }
925
926    const RAW_SRC: &str = r#"context uploads
927
928service api from http {
929  limits { maxBody: 1000 }
930
931  @raw(contentType: "image/png")
932  on PUT("/avatars/:user") (user: String, body: Bytes) -> Effect[HttpResult[String]] by Visitor {
933    Ok(user)
934  }
935}
936"#;
937
938    #[test]
939    fn a_raw_route_is_a_raw_envelope_whatever_its_other_params_with_413_and_415() {
940        let root = setup_project("uploads", &[("uploads.bynk", RAW_SRC)]);
941        let diag = crate::testkit::diagnose_project(&root);
942        let info = diag
943            .boundary_info
944            .get("uploads")
945            .expect("boundary_info entry for uploads");
946        let offset = find_offset(RAW_SRC, "PUT(\"/avatars/:user\")");
947        let model = wire_contract_at(
948            "uploads",
949            RAW_SRC,
950            offset,
951            info,
952            &[],
953            &diag.ty_intern,
954            real_context_count(&diag),
955        )
956        .expect("a wire contract at the PUT handler's header");
957
958        match &model.envelope {
959            Envelope::Raw {
960                param,
961                content_type,
962            } => {
963                assert_eq!(param, "body");
964                assert_eq!(content_type, "image/png");
965            }
966            other => panic!("expected Envelope::Raw, got {other:?}"),
967        }
968        let statuses: Vec<u16> = model.responses.iter().map(|r| r.status).collect();
969        assert!(statuses.contains(&413), "{statuses:?}");
970        assert!(statuses.contains(&415), "{statuses:?}");
971    }
972
973    #[test]
974    fn rate_limiter_get_check_client_is_a_bare_envelope_with_a_revalidated_client_id() {
975        let root = setup_project("ratelimit", &[("ratelimit.bynk", RATELIMIT_SRC)]);
976        let diag = crate::testkit::diagnose_project(&root);
977        let info = diag
978            .boundary_info
979            .get("ratelimit")
980            .expect("boundary_info entry for ratelimit");
981
982        let offset = find_offset(RATELIMIT_SRC, "GET(\"/check/:client\")");
983        let model = wire_contract_at(
984            "ratelimit",
985            RATELIMIT_SRC,
986            offset,
987            info,
988            &[],
989            &diag.ty_intern,
990            real_context_count(&diag),
991        )
992        .expect("a wire contract at the GET handler's header");
993
994        assert_eq!(model.unit, "ratelimit");
995        assert_eq!(model.service, "api");
996        assert_eq!(
997            model.kind,
998            BoundaryKind::Http {
999                method: IrHttpMethod::Get,
1000                path: "/check/:client".to_string(),
1001            }
1002        );
1003
1004        // One param (`client`) sends the bare value — not wrapped in an
1005        // object, and not the two-case envelope the issue text describes.
1006        let (param, shape) = match &model.envelope {
1007            Envelope::Bare { param, shape } => (param, shape),
1008            other => panic!("expected Envelope::Bare, got {other:?}"),
1009        };
1010        assert_eq!(param, "client");
1011        assert!(
1012            matches!(shape, WireRef::Named { name } if name == "ClientId"),
1013            "the bare param's shape should resolve to the named ClientId type: {shape:?}"
1014        );
1015
1016        // `ClientId` is in the boundary type set, owned (declared in this
1017        // same context), refined `NonEmpty`, revalidated via its own
1018        // constructor.
1019        let client_id = model
1020            .boundary
1021            .types
1022            .iter()
1023            .find(|t| t.name == "ClientId")
1024            .expect("ClientId is a boundary type");
1025        assert_eq!(client_id.provenance, bynk_check::wire::Provenance::Owned);
1026        let bynk_check::wire::WireBody::Scalar(scalar) = &client_id.body else {
1027            panic!("ClientId should be a scalar, got {:?}", client_id.body);
1028        };
1029        assert!(
1030            scalar
1031                .predicates
1032                .iter()
1033                .any(|p| matches!(p, PredKind::NonEmpty)),
1034            "ClientId's predicates should include NonEmpty: {:?}",
1035            scalar.predicates
1036        );
1037        assert_eq!(
1038            scalar.revalidation,
1039            bynk_check::wire::Revalidation::ViaConstructor
1040        );
1041        assert!(model.type_sites.contains_key("ClientId"));
1042
1043        // A single-context project: even though `api`'s handler is `Http`
1044        // (never `NotACallHandler` would even get a chance to fire), the
1045        // more fundamental "there is no other context" reason wins.
1046        assert_eq!(
1047            model.no_cross_context,
1048            Some(NoCrossContextReason::SingleContext)
1049        );
1050        assert!(model.contract.is_none());
1051    }
1052
1053    /// [`ResponseWalk::expr_ty`]'s answer for every expression in the
1054    /// handler at `offset`, keyed by its source text — reparsed the same way
1055    /// [`wire_contract_at`] reparses, so the probe of whether the walk's
1056    /// primary, checker-typed path is actually taken rather than the
1057    /// declared-return fallback.
1058    fn walk_expr_tys(
1059        text: &str,
1060        offset: usize,
1061        file: FileId,
1062        expr_types: &[(Span, TyId)],
1063        tys: &Types,
1064    ) -> Vec<(String, Option<std::sync::Arc<Ty>>)> {
1065        fn collect<'e>(e: &'e Expr, out: &mut Vec<&'e Expr>) {
1066            out.push(e);
1067            for c in expr_children(e) {
1068                collect(c, out);
1069            }
1070        }
1071        let tokens = bynk_syntax::lexer::tokenize(text).expect("lexes");
1072        let (parsed, _) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
1073        let Some(SourceUnit::Context(c)) = parsed else {
1074            panic!("fixture is a context");
1075        };
1076        let handler = c
1077            .items
1078            .iter()
1079            .find_map(|i| match i {
1080                CommonsItem::Service(s) => handler_at(&s.handlers, offset),
1081                _ => None,
1082            })
1083            .expect("a handler at offset");
1084        let mut exprs = Vec::new();
1085        for s in &handler.body.statements {
1086            statement_exprs(s, &mut exprs);
1087        }
1088        exprs.push(&handler.body.tail);
1089        let mut all = Vec::new();
1090        for e in exprs {
1091            collect(e, &mut all);
1092        }
1093        let walk = ResponseWalk {
1094            expr_types,
1095            file,
1096            tys,
1097            declared_is_http_result: true,
1098            seen: Default::default(),
1099            saw_option_question: false,
1100            out: Vec::new(),
1101        };
1102        all.iter()
1103            .map(|e| {
1104                (
1105                    text[e.span.start..e.span.end].to_string(),
1106                    walk.expr_ty(e.span),
1107                )
1108            })
1109            .collect()
1110    }
1111
1112    #[test]
1113    fn rate_limiter_response_set_has_declared_constructed_and_boundary_implicit() {
1114        let root = setup_project("ratelimit-responses", &[("ratelimit.bynk", RATELIMIT_SRC)]);
1115        let diag = crate::testkit::diagnose_project(&root);
1116        let info = diag.boundary_info.get("ratelimit").expect("entry");
1117
1118        // Drive with the round's own retained `expr_types` for this file —
1119        // the primary path (not the degraded fallback).
1120        let rel = diag
1121            .files
1122            .iter()
1123            .find(|f| {
1124                f.source_path
1125                    .file_name()
1126                    .is_some_and(|n| n == "ratelimit.bynk")
1127            })
1128            .map(|f| f.source_path.clone())
1129            .expect("ratelimit.bynk in the round's files");
1130        let expr_types: &[(Span, TyId)] = diag
1131            .expr_types
1132            .get(&rel)
1133            .map(|v| v.as_slice())
1134            .unwrap_or(&[]);
1135
1136        assert!(
1137            !expr_types.is_empty(),
1138            "the clean fixture recorded no expr types"
1139        );
1140        let offset = find_offset(RATELIMIT_SRC, "GET(\"/check/:client\")");
1141        // The constructed responses themselves resolve to `HttpResult`, not
1142        // just some incidental sub-expression — otherwise the walk took the
1143        // degraded fallback for exactly the expressions it classifies.
1144        let walked = walk_expr_tys(
1145            RATELIMIT_SRC,
1146            offset,
1147            info.services["api"].span.file,
1148            expr_types,
1149            &diag.ty_intern,
1150        );
1151        for src in ["Ok(view)", "TooManyRequests(\"rate limit exceeded\")"] {
1152            let ty = walked
1153                .iter()
1154                .find(|(t, _)| t == src)
1155                .unwrap_or_else(|| panic!("`{src}` not walked: {walked:?}"))
1156                .1
1157                .as_deref();
1158            assert!(
1159                matches!(ty, Some(Ty::HttpResult(_))),
1160                "`{src}` should resolve to a recorded HttpResult, got {ty:?}"
1161            );
1162        }
1163        let model = wire_contract_at(
1164            "ratelimit",
1165            RATELIMIT_SRC,
1166            offset,
1167            info,
1168            expr_types,
1169            &diag.ty_intern,
1170            real_context_count(&diag),
1171        )
1172        .expect("a wire contract at the GET handler's header");
1173
1174        let statuses: Vec<(u16, &str)> = model
1175            .responses
1176            .iter()
1177            .map(|r| (r.status, r.variant.as_str()))
1178            .collect();
1179        assert!(
1180            statuses.contains(&(200, "Ok")),
1181            "declared success missing: {statuses:?}"
1182        );
1183        assert!(
1184            statuses.contains(&(429, "TooManyRequests")),
1185            "constructed TooManyRequests missing: {statuses:?}"
1186        );
1187        assert!(
1188            statuses.iter().any(|&(s, _)| s == 400),
1189            "boundary-implicit 400 (the handler has a param) missing: {statuses:?}"
1190        );
1191        assert!(
1192            model
1193                .responses
1194                .iter()
1195                .find(|r| r.status == 200)
1196                .is_some_and(|r| r.origin == ResponseOrigin::DeclaredSuccess)
1197        );
1198        assert!(
1199            model.responses.iter().any(|r| matches!(
1200                r.origin,
1201                ResponseOrigin::BoundaryImplicit { .. }
1202            ) && r.status == 400)
1203        );
1204    }
1205
1206    // -- Fixture 2: a two-context project with a real `on call` boundary —
1207    // -- the contract form + hash + Envelope::Keyed path (multi-param).
1208    const PROVIDER_SRC: &str = r#"context billing
1209
1210type Quote = { amount: Int, currency: String }
1211
1212service Pricing {
1213  on call(sku: String, qty: Int) -> Effect[Quote] by Caller {
1214    Quote { amount: qty * 100, currency: "USD" }
1215  }
1216}
1217"#;
1218    const CONSUMER_SRC: &str = r#"context storefront
1219
1220consumes billing
1221
1222service checkout {
1223  on call(sku: String, qty: Int) -> Effect[Int] by Caller {
1224    let q <- billing.Pricing(sku, qty)
1225    q.amount
1226  }
1227}
1228"#;
1229
1230    #[test]
1231    fn two_context_call_handler_has_a_keyed_envelope_and_a_contract_hash() {
1232        let root = setup_project(
1233            "two-context",
1234            &[
1235                ("billing.bynk", PROVIDER_SRC),
1236                ("storefront.bynk", CONSUMER_SRC),
1237            ],
1238        );
1239        let diag = crate::testkit::diagnose_project(&root);
1240        let info = diag
1241            .boundary_info
1242            .get("billing")
1243            .expect("boundary_info entry for billing");
1244
1245        let offset = find_offset(PROVIDER_SRC, "on call(");
1246        let model = wire_contract_at(
1247            "billing",
1248            PROVIDER_SRC,
1249            offset,
1250            info,
1251            &[],
1252            &diag.ty_intern,
1253            real_context_count(&diag),
1254        )
1255        .expect("a wire contract at the `price` handler");
1256
1257        assert_eq!(model.kind, BoundaryKind::Call);
1258        let params = match &model.envelope {
1259            Envelope::Keyed { params } => params,
1260            other => panic!("expected Envelope::Keyed for a two-param call, got {other:?}"),
1261        };
1262        assert_eq!(
1263            params.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(),
1264            vec!["sku", "qty"],
1265            "keyed params stay in declaration order"
1266        );
1267
1268        assert!(model.no_cross_context.is_none(), "two contexts + on call");
1269        let contract = model.contract.expect("on call gets a contract form");
1270        assert_eq!(
1271            contract.hash,
1272            bynk_check::contract::contract_hash(&contract.normal_form)
1273        );
1274
1275        // Independent re-derivation via the exact projection
1276        // `own_contract_hashes` uses, against the same retained table — the
1277        // hovered hash must equal what the emitter would stamp.
1278        let svc = CrossContextService {
1279            name: "Pricing".to_string(),
1280            params: vec![
1281                (
1282                    "sku".to_string(),
1283                    TypeRef::Base(BaseType::String, Span::new(0, 0)),
1284                ),
1285                (
1286                    "qty".to_string(),
1287                    TypeRef::Base(BaseType::Int, Span::new(0, 0)),
1288                ),
1289            ],
1290            return_type: TypeRef::Named(Ident {
1291                name: "Quote".to_string(),
1292                span: Span::new(0, 0),
1293            }),
1294            span: Span::new(0, 0),
1295            foreign_callers: Vec::new(),
1296        };
1297        let independent_form = contract::service_normal_form(&svc, &info.types);
1298        assert_eq!(contract.normal_form, independent_form);
1299        assert_eq!(contract.hash, contract::contract_hash(&independent_form));
1300    }
1301
1302    #[test]
1303    fn zero_param_call_handler_is_the_empty_envelope() {
1304        let src = r#"context solo
1305
1306service Ping {
1307  on call() -> Effect[Int] by Caller {
1308    1
1309  }
1310}
1311"#;
1312        let root = setup_project("zero-param", &[("solo.bynk", src)]);
1313        let diag = crate::testkit::diagnose_project(&root);
1314        let info = diag.boundary_info.get("solo").expect("entry");
1315
1316        let offset = find_offset(src, "on call()");
1317        let model = wire_contract_at(
1318            "solo",
1319            src,
1320            offset,
1321            info,
1322            &[],
1323            &diag.ty_intern,
1324            real_context_count(&diag),
1325        )
1326        .expect("a wire contract at the `Ping` handler");
1327
1328        assert!(
1329            matches!(model.envelope, Envelope::Empty),
1330            "zero params: the request body is not read, not an empty keyed object"
1331        );
1332        // Single-context project: `on call` still answers SingleContext, not
1333        // a real contract.
1334        assert_eq!(
1335            model.no_cross_context,
1336            Some(NoCrossContextReason::SingleContext)
1337        );
1338    }
1339
1340    // -- Regression: the `Ok`-overload `expr_types` fallback (plan risk 7)
1341    // -- must not extend to a bare `Ident`. `HTTP_VARIANTS` includes names
1342    // -- an author can plausibly bind as an ordinary local (`Found`, `Gone`,
1343    // -- `Conflict`, …) — without a recorded expr type, a bare `Found` read
1344    // -- must stay unknown, not get misreported as a constructed 302.
1345    #[test]
1346    fn bare_ident_collision_with_a_variant_name_is_not_misreported_without_expr_types() {
1347        const SRC: &str = r#"context oddnames
1348
1349service api from http {
1350  on GET("/x") () -> Effect[HttpResult[Int]] by Visitor {
1351    let Found = 1
1352    Found
1353  }
1354}
1355"#;
1356        let root = setup_project("ident-collision", &[("oddnames.bynk", SRC)]);
1357        let diag = crate::testkit::diagnose_project(&root);
1358        let info = diag
1359            .boundary_info
1360            .get("oddnames")
1361            .expect("boundary_info entry for oddnames");
1362
1363        let offset = find_offset(SRC, "GET(\"/x\")");
1364        // Deliberately pass an empty `expr_types` — the degraded path (an
1365        // expression the checker never typed, see `expr_types` above) this
1366        // fixture is standing in for, even though it type-checks cleanly on
1367        // its own.
1368        let model = wire_contract_at(
1369            "oddnames",
1370            SRC,
1371            offset,
1372            info,
1373            &[],
1374            &diag.ty_intern,
1375            real_context_count(&diag),
1376        )
1377        .expect("a wire contract at the GET handler");
1378
1379        assert!(
1380            model.responses.iter().all(|r| r.variant != "Found"),
1381            "a bare `Found` local must not be misreported as HttpResult.Found \
1382             without a recorded expr type: {:?}",
1383            model.responses
1384        );
1385    }
1386
1387    // -- A bare-`Ident` variant never falls back to the declared-return
1388    // -- heuristic, so it is reported only when `expr_ty` finds the
1389    // -- checker's recorded type. That lookup used to compare whole `Span`s,
1390    // -- `FileId` included: the round's spans carry a real `FileId` (T3.5,
1391    // -- #1062), the reparse's carry `FileId::UNKNOWN`, so it never matched
1392    // -- and a tail `NoContent` silently dropped out of the response set.
1393    #[test]
1394    fn bare_ident_variant_is_reported_from_real_expr_types() {
1395        const SRC: &str = r#"context flags
1396
1397service api from http {
1398  on DELETE("/flags/:name") (name: String) -> Effect[HttpResult[String]] by Visitor {
1399    NoContent
1400  }
1401}
1402"#;
1403        let root = setup_project("bare-ident-variant", &[("flags.bynk", SRC)]);
1404        let diag = crate::testkit::diagnose_project(&root);
1405        let info = diag.boundary_info.get("flags").expect("entry");
1406        let expr_types: &[(Span, TyId)] = diag
1407            .files
1408            .iter()
1409            .find(|f| f.source_path.file_name().is_some_and(|n| n == "flags.bynk"))
1410            .and_then(|f| diag.expr_types.get(&f.source_path))
1411            .map(|v| v.as_slice())
1412            .expect("flags.bynk's recorded expr types");
1413        assert!(
1414            expr_types.iter().all(|(s, _)| s.file != FileId::UNKNOWN),
1415            "the premise: analysis spans carry a real FileId"
1416        );
1417
1418        let offset = find_offset(SRC, "DELETE(");
1419        let model = wire_contract_at(
1420            "flags",
1421            SRC,
1422            offset,
1423            info,
1424            expr_types,
1425            &diag.ty_intern,
1426            real_context_count(&diag),
1427        )
1428        .expect("a wire contract at the DELETE handler");
1429
1430        assert!(
1431            model
1432                .responses
1433                .iter()
1434                .any(|r| r.status == 204 && r.variant == "NoContent"),
1435            "a tail `NoContent` must be reported as constructed: {:?}",
1436            model.responses
1437        );
1438    }
1439
1440    /// A recorded `Ty::Error` is "no type": it must degrade to the
1441    /// declared-return fallback exactly like a missing entry, not count as a
1442    /// definite non-`HttpResult` answer.
1443    #[test]
1444    fn expr_ty_matches_by_range_and_treats_error_as_no_type() {
1445        let tys = Types::new();
1446        let file = FileId(0);
1447        let error = tys.intern(Ty::Error);
1448        let http = tys.intern(Ty::HttpResult(error));
1449        let expr_types = [
1450            (Span::new_in(file, 10, 20), http),
1451            (Span::new_in(file, 30, 40), error),
1452            (Span::new_in(FileId(1), 50, 60), http),
1453        ];
1454        let walk = ResponseWalk {
1455            expr_types: &expr_types,
1456            file,
1457            tys: &tys,
1458            declared_is_http_result: true,
1459            seen: Default::default(),
1460            saw_option_question: false,
1461            out: Vec::new(),
1462        };
1463
1464        // A reparsed span (`FileId::UNKNOWN`) over the same range matches.
1465        assert!(matches!(
1466            walk.expr_ty(Span::new(10, 20)).as_deref(),
1467            Some(Ty::HttpResult(_))
1468        ));
1469        assert!(walk.is_http_result_ident(Span::new(10, 20)));
1470
1471        // `Ty::Error` is no type: the ident check stays unknown, the expr
1472        // check takes the declared-return fallback.
1473        assert!(walk.expr_ty(Span::new(30, 40)).is_none());
1474        assert!(!walk.is_http_result_ident(Span::new(30, 40)));
1475        assert!(walk.is_http_result_expr(Span::new(30, 40)));
1476
1477        // Another file's entry over the same range is not this file's type.
1478        assert!(walk.expr_ty(Span::new(50, 60)).is_none());
1479    }
1480
1481    /// `name`'s recorded expr types from a round that must be error-free —
1482    /// so a fixture that stops type-checking fails loudly here rather than
1483    /// silently degrading the walk to its fallback.
1484    fn clean_expr_types<'d>(diag: &'d crate::ProjectDiagnostics, name: &str) -> &'d [(Span, TyId)] {
1485        for f in &diag.files {
1486            assert!(
1487                f.diagnostics.is_empty(),
1488                "{:?} has diagnostics: {:?}",
1489                f.source_path,
1490                f.diagnostics
1491            );
1492        }
1493        diag.files
1494            .iter()
1495            .find(|f| f.source_path.file_name().is_some_and(|n| n == name))
1496            .and_then(|f| diag.expr_types.get(&f.source_path))
1497            .map(|v| v.as_slice())
1498            .unwrap_or_else(|| panic!("{name}'s recorded expr types"))
1499    }
1500
1501    // -- The primary-path twin of the degraded-path collision test above:
1502    // -- with the real `expr_types` (so the fixture must check cleanly,
1503    // -- hence `Ok(Found)`), `Found` is recorded as `Int`, and that recorded
1504    // -- type is what keeps it out of the response set.
1505    #[test]
1506    fn bare_ident_collision_with_a_variant_name_is_rejected_by_its_recorded_type() {
1507        const SRC: &str = r#"context oddnames
1508
1509service api from http {
1510  on GET("/x") () -> Effect[HttpResult[Int]] by Visitor {
1511    let Found = 1
1512    Ok(Found)
1513  }
1514}
1515"#;
1516        let root = setup_project("ident-collision-typed", &[("oddnames.bynk", SRC)]);
1517        let diag = crate::testkit::diagnose_project(&root);
1518        let info = diag.boundary_info.get("oddnames").expect("entry");
1519        let expr_types = clean_expr_types(&diag, "oddnames.bynk");
1520
1521        let offset = find_offset(SRC, "GET(\"/x\")");
1522        let walked = walk_expr_tys(
1523            SRC,
1524            offset,
1525            info.services["api"].span.file,
1526            expr_types,
1527            &diag.ty_intern,
1528        );
1529        assert!(
1530            walked.iter().any(|(t, ty)| t == "Found"
1531                && ty
1532                    .as_deref()
1533                    .is_some_and(|ty| !matches!(ty, Ty::HttpResult(_)))),
1534            "the tail `Found` should resolve to its recorded non-HttpResult type: {walked:?}"
1535        );
1536
1537        let model = wire_contract_at(
1538            "oddnames",
1539            SRC,
1540            offset,
1541            info,
1542            expr_types,
1543            &diag.ty_intern,
1544            real_context_count(&diag),
1545        )
1546        .expect("a wire contract at the GET handler");
1547        assert!(
1548            model.responses.iter().all(|r| r.variant != "Found"),
1549            "a bare `Found` local must not be reported as HttpResult.Found: {:?}",
1550            model.responses
1551        );
1552    }
1553
1554    // -- `classify`'s `Option?` arm has no fallback, so — like the bare
1555    // -- `Ident` arm — the boundary-implicit 404 (ADR 0177) was unreachable
1556    // -- while `expr_ty` never matched.
1557    #[test]
1558    fn option_question_in_a_handler_adds_the_boundary_implicit_404() {
1559        const SRC: &str = r#"context lookup
1560
1561fn find(n: String) -> Option[Int] {
1562  Some(1)
1563}
1564
1565service api from http {
1566  on GET("/x/:n") (n: String) -> Effect[HttpResult[Int]] by Visitor {
1567    let v = find(n)?
1568    Ok(v)
1569  }
1570}
1571"#;
1572        let root = setup_project("option-question", &[("lookup.bynk", SRC)]);
1573        let diag = crate::testkit::diagnose_project(&root);
1574        let info = diag.boundary_info.get("lookup").expect("entry");
1575        let expr_types = clean_expr_types(&diag, "lookup.bynk");
1576
1577        let model = wire_contract_at(
1578            "lookup",
1579            SRC,
1580            find_offset(SRC, "GET("),
1581            info,
1582            expr_types,
1583            &diag.ty_intern,
1584            real_context_count(&diag),
1585        )
1586        .expect("a wire contract at the GET handler");
1587        assert!(
1588            model.responses.iter().any(|r| r.status == 404
1589                && r.variant == "NotFound"
1590                && matches!(r.origin, ResponseOrigin::BoundaryImplicit { .. })),
1591            "an `Option?` short-circuit must add the boundary-implicit 404: {:?}",
1592            model.responses
1593        );
1594    }
1595
1596    // -- A file's `expr_types` also carries a sibling file's spans: the
1597    // -- checker merges `b.bynk`'s methods on a type declared in `a.bynk`
1598    // -- into `a.bynk`'s checked view. `b.bynk` is padded so its `Ok(1)`
1599    // -- (an `HttpResult`) sits at exactly the byte range of `a.bynk`'s
1600    // -- `Found` local; a range-only match would mint a 302 the handler never
1601    // -- constructs.
1602    #[test]
1603    fn a_sibling_files_span_at_the_same_range_is_not_this_files_type() {
1604        const A: &str = r#"context shop
1605
1606type Q = { n: Int }
1607
1608service api from http {
1609  on GET("/x") () -> Effect[HttpResult[Int]] by Visitor {
1610    let Found = 1
1611    Ok(Found)
1612  }
1613}
1614"#;
1615        let target = find_offset(A, "Ok(Found)") + "Ok(".len();
1616        let head = "context shop\n\nfn Q.r(self) -> HttpResult[Int] {\n";
1617        let pad = target
1618            .checked_sub(head.len())
1619            .expect("a.bynk's `Found` sits past b.bynk's header");
1620        let b = format!("{head}{}Ok(1)\n}}\n", " ".repeat(pad));
1621        assert_eq!(
1622            b.find("Ok(1)"),
1623            Some(target),
1624            "the padding lines the spans up"
1625        );
1626
1627        let root = setup_project("sibling-span", &[("shop/a.bynk", A), ("shop/b.bynk", &b)]);
1628        let diag = crate::testkit::diagnose_project(&root);
1629        let info = diag.boundary_info.get("shop").expect("entry");
1630        let expr_types = clean_expr_types(&diag, "a.bynk");
1631        let file = info.services["api"].span.file;
1632        assert!(
1633            expr_types.iter().any(|(s, t)| s.file != file
1634                && (s.start, s.end) == (target, target + 5)
1635                && matches!(*diag.ty_intern.get(*t), Ty::HttpResult(_))),
1636            "the premise: a.bynk's expr types hold b.bynk's `Ok(1)` at the same range"
1637        );
1638
1639        let model = wire_contract_at(
1640            "shop",
1641            A,
1642            find_offset(A, "GET("),
1643            info,
1644            expr_types,
1645            &diag.ty_intern,
1646            real_context_count(&diag),
1647        )
1648        .expect("a wire contract at the GET handler");
1649        assert!(
1650            model.responses.iter().all(|r| r.variant != "Found"),
1651            "b.bynk's `Ok(1)` must not type a.bynk's `Found`: {:?}",
1652            model.responses
1653        );
1654    }
1655
1656    // -- #3631: a user sum variant named like an `HttpResult` variant is that
1657    // -- sum's constructor, not the HTTP response. The checker records the
1658    // -- constructor call's own (sum) type, so the walk never reaches the
1659    // -- declared-return fallback for it.
1660    #[test]
1661    fn user_sum_variant_named_like_an_http_variant_is_not_a_response() {
1662        const SRC: &str = r#"context catalogue
1663
1664type Item = { id: Int, name: String }
1665type Outcome = | Found(item: Item) | Absent
1666
1667service api from http {
1668  on GET("/outcome/:id") (id: String) -> Effect[HttpResult[Outcome]] by Visitor {
1669    Ok(Found(Item { id: 1, name: id }))
1670  }
1671}
1672"#;
1673        let root = setup_project("sum-variant-found", &[("catalogue.bynk", SRC)]);
1674        let diag = crate::testkit::diagnose_project(&root);
1675        let info = diag.boundary_info.get("catalogue").expect("entry");
1676        let expr_types = clean_expr_types(&diag, "catalogue.bynk");
1677        let model = wire_contract_at(
1678            "catalogue",
1679            SRC,
1680            find_offset(SRC, "GET("),
1681            info,
1682            expr_types,
1683            &diag.ty_intern,
1684            real_context_count(&diag),
1685        )
1686        .expect("a wire contract at the GET handler");
1687        let variants: Vec<&str> = model.responses.iter().map(|r| r.variant.as_str()).collect();
1688        assert_eq!(variants, ["Ok", "StructuralMismatch"], "{variants:?}");
1689    }
1690
1691    /// The responses `src`'s `GET /x` handler constructs, by variant name.
1692    fn constructed_variants(test: &str, ctx_name: &str, src: &str) -> Vec<String> {
1693        let file = format!("{ctx_name}.bynk");
1694        let root = setup_project(test, &[(file.as_str(), src)]);
1695        let diag = crate::testkit::diagnose_project(&root);
1696        let info = diag.boundary_info.get(ctx_name).expect("entry");
1697        let expr_types = clean_expr_types(&diag, &file);
1698        wire_contract_at(
1699            ctx_name,
1700            src,
1701            find_offset(src, "GET("),
1702            info,
1703            expr_types,
1704            &diag.ty_intern,
1705            real_context_count(&diag),
1706        )
1707        .expect("a wire contract at the GET handler")
1708        .responses
1709        .into_iter()
1710        .map(|r| r.variant)
1711        .collect()
1712    }
1713
1714    // -- #3631: every `HttpResult` variant name, used as a user sum variant
1715    // -- (bare call, and bare nullary), is the user's constructor.
1716    #[test]
1717    fn every_http_variant_name_as_a_user_sum_variant_is_not_a_response() {
1718        const SRC: &str = r#"context names
1719
1720type Msg = { text: String }
1721type Shape =
1722  | Created(msg: Msg)
1723  | Accepted(msg: Msg)
1724  | NotFound(msg: Msg)
1725  | Conflict(msg: Msg)
1726  | Gone(msg: Msg)
1727  | Redirect(msg: Msg)
1728  | Found(msg: Msg)
1729  | NoContent
1730
1731service api from http {
1732  on GET("/x") () -> Effect[HttpResult[List[Shape]]] by Visitor {
1733    let m = Msg { text: "t" }
1734    Ok([Created(m), Accepted(m), NotFound(m), Conflict(m), Gone(m), Redirect(m), Found(m), NoContent])
1735  }
1736}
1737"#;
1738        let variants = constructed_variants("all-http-names", "names", SRC);
1739        assert_eq!(variants, ["Ok"], "only the declared `Ok`: {variants:?}");
1740    }
1741
1742    // -- #3631: the wire contract still reports a genuine `HttpResult.Found`,
1743    // -- bare and qualified, alongside a same-named user variant elsewhere.
1744    #[test]
1745    fn genuine_http_found_is_still_a_response() {
1746        const SRC: &str = r#"context moved
1747
1748type Item = { id: Int }
1749type Outcome = | Found(item: Item) | Absent
1750
1751fn lookup() -> Outcome {
1752  Found(Item { id: 1 })
1753}
1754
1755service api from http {
1756  on GET("/x") () -> Effect[HttpResult[Outcome]] by Visitor {
1757    match lookup() {
1758      Found(item) => Found("/elsewhere")
1759      Absent => HttpResult.NotFound
1760    }
1761  }
1762}
1763"#;
1764        let variants = constructed_variants("genuine-found", "moved", SRC);
1765        assert!(
1766            variants.iter().any(|v| v == "Found"),
1767            "a genuine `Found(\"/elsewhere\")` is the 302: {variants:?}"
1768        );
1769        assert!(variants.iter().any(|v| v == "NotFound"), "{variants:?}");
1770    }
1771}