Skip to main content

bynk_check/
context_checks.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3
4use crate::builtin_names::methods::{OF, UNSAFE};
5use crate::checker::{
6    self, CapabilityInfo, CapabilityOpInfo, Ty, TyId, TypedExpr, Types, statement_at_boundary,
7};
8use crate::hints::HintSink;
9use crate::index::{RefSink, SymbolKind};
10use crate::kernel_op::{FormStatic, JsonStatic, StaticOp, YamlStatic};
11use crate::locals::LocalsSink;
12use crate::requirements::RequirementSink;
13use crate::resolver::{self, ResolvedCommons};
14use crate::symbols::{ConsumedType, UnitTable, record_provides_clause_ref, resolve_given_cap_ref};
15use bynk_project::detect_provider_dependency_cycles;
16use bynk_syntax::ast::*;
17use bynk_syntax::error::{Applicability, CompileError};
18use bynk_syntax::span::Span;
19
20/// The base a derived capability (`capability Stock = D1`) was made from, as
21/// `(unit, base)`. One definition for handlers and test/property bodies, so
22/// the #2865 typed-read recognition cannot drift between them (#2995).
23pub(crate) fn derived_from(
24    decl: &CapabilityDecl,
25    flattened_caps: &HashMap<String, String>,
26) -> Option<(String, String)> {
27    decl.derived.as_ref().and_then(|d| {
28        flattened_caps
29            .get(&d.base.name)
30            .map(|unit| (unit.clone(), d.base.name.clone()))
31    })
32}
33
34/// #926: build a checker-facing [`CapabilityOpInfo`] from a capability op's
35/// AST, with the op's own type parameters (if any) resolved as [`Ty::Var`]
36/// rather than ground types — a call site substitutes a concrete `Ty` for
37/// each before checking. Shared by every site that reconstructs
38/// `CapabilityInfo` from a `CapabilityDecl` (local capabilities, test/property
39/// bodies targeting a context) so the vars-in-scope treatment can't drift.
40pub fn build_capability_op_info(
41    op: &CapabilityOp,
42    types: &HashMap<String, Arc<TypeDecl>>,
43    tys: &Arc<Types>,
44) -> CapabilityOpInfo {
45    let vars: HashSet<String> = op.type_params.iter().map(|p| p.name.name.clone()).collect();
46    CapabilityOpInfo {
47        name: op.name.name.clone(),
48        type_params: op.type_params.iter().map(|p| p.name.name.clone()).collect(),
49        params: op
50            .params
51            .iter()
52            .map(|p| checker::resolve_type_ref_in(&p.type_ref, types, &vars, tys))
53            .map(|t| t.unwrap_or_else(|| tys.intern(Ty::Unit)))
54            .collect(),
55        param_names: op.params.iter().map(|p| p.name.name.clone()).collect(),
56        return_ty: checker::resolve_type_ref_in(&op.return_type, types, &vars, tys)
57            .unwrap_or_else(|| tys.intern(Ty::Unit)),
58        codable_params: checker::codable::codable_op_params(op),
59        reply_policy: checker::codable::op_reply_policy(op),
60        boundary_conflict: None,
61    }
62}
63
64/// Enforce v0.4 construction rules: types owned by a consumed context can be
65/// referenced (held, passed, read for transparent exports) but cannot be
66/// constructed. This catches `OtherType { ... }`, `OtherType.of(...)`,
67/// `OtherType.unsafe(...)`, and `OtherType.Variant(...)` expressions where
68/// `OtherType` is from a consumed context.
69pub fn check_context_constraints(
70    typed: &checker::TypedCommons,
71    consumed_types: &HashMap<String, ConsumedType>,
72    local_type_names: &HashSet<String>,
73    tys: &Arc<Types>,
74) -> Vec<CompileError> {
75    let mut errors = Vec::new();
76    for item in &typed.commons.items {
77        // #2868: a `given` function is typed with the context's declarations,
78        // after this pass; `check_handler_constraints` walks it.
79        if let CommonsItem::Fn(f) = item
80            && f.given.is_empty()
81        {
82            walk_block_for_constraints(
83                &f.body,
84                typed,
85                consumed_types,
86                local_type_names,
87                &mut errors,
88                tys,
89            );
90            // #1700: a contract predicate is an expression like any other.
91            for c in f.requires.iter().chain(&f.ensures) {
92                walk_expr_for_constraints(
93                    &c.predicate,
94                    typed,
95                    consumed_types,
96                    local_type_names,
97                    &mut errors,
98                    tys,
99                );
100            }
101        }
102    }
103    errors
104}
105
106/// #1700: the same cross-context constraints as [`check_context_constraints`],
107/// over the bodies it cannot reach — service and agent handlers, agent
108/// invariants and transitions, and provider operations. These are typed by [`check_context_declarations`], after
109/// [`check_context_constraints`] runs, so this pass runs after that one: the
110/// opaque-`match` rule reads the discriminant's checked type.
111pub fn check_handler_constraints(
112    typed: &checker::TypedCommons,
113    consumed_types: &HashMap<String, ConsumedType>,
114    local_type_names: &HashSet<String>,
115    tys: &Arc<Types>,
116) -> Vec<CompileError> {
117    let mut errors = Vec::new();
118    for item in &typed.commons.items {
119        let (bodies, predicates): (Vec<&Block>, Vec<&Expr>) = match item {
120            CommonsItem::Service(s) => {
121                check_handler_inputs_not_external_opaque(s, typed, consumed_types, &mut errors);
122                (s.handlers.iter().map(|h| &h.body).collect(), Vec::new())
123            }
124            // An agent's invariants and transitions are typed alongside its
125            // handlers, and are expressions that can name a consumed type.
126            CommonsItem::Agent(a) => (
127                a.handlers.iter().map(|h| &h.body).collect(),
128                a.invariants
129                    .iter()
130                    .map(|i| &i.predicate)
131                    .chain(a.transitions.iter().map(|t| &t.predicate))
132                    .collect(),
133            ),
134            CommonsItem::Provider(p) => (p.ops.iter().map(|op| &op.body).collect(), Vec::new()),
135            // #2868: a `given` function, typed with the context's declarations.
136            // #2882: a function `given_fn_refusal` rejected was not typed
137            // (`check_given_fns`), so its body is not walked either. This pass
138            // runs on contexts only.
139            CommonsItem::Fn(f)
140                if !f.given.is_empty() && checker::given_fn_refusal(f, true).is_none() =>
141            {
142                (
143                    vec![&f.body],
144                    f.requires
145                        .iter()
146                        .chain(&f.ensures)
147                        .map(|c| &c.predicate)
148                        .collect(),
149                )
150            }
151            _ => continue,
152        };
153        for body in bodies {
154            walk_block_for_constraints(
155                body,
156                typed,
157                consumed_types,
158                local_type_names,
159                &mut errors,
160                tys,
161            );
162        }
163        for e in predicates {
164            walk_expr_for_constraints(e, typed, consumed_types, local_type_names, &mut errors, tys);
165        }
166    }
167    errors
168}
169
170/// The types an expression decodes from JSON: the target of `Json.decode` /
171/// `Json.decodeSql`, and each type that fills a `Codable` witness of a callee
172/// (its decode half runs inside the callee). Encoding is not a decode.
173fn decode_targets(e: &Expr, typed: &checker::TypedCommons) -> Vec<TyId> {
174    use checker::Callee;
175    use checker::codable::{WitnessKind, witness_list};
176    match typed.callees.get(&e.id) {
177        Some(Callee::Intrinsic {
178            op:
179                StaticOp::Json(JsonStatic::Decode | JsonStatic::DecodeSql)
180                | StaticOp::Yaml(YamlStatic::Decode)
181                | StaticOp::Form(FormStatic::Decode),
182            ..
183        }) => match typed.expr_ty(e.id).as_deref() {
184            Some(Ty::Result(t, _)) => vec![*t],
185            _ => Vec::new(),
186        },
187        // #2865: a typed `D1` read decodes its row.
188        Some(Callee::D1Select { row, .. }) => vec![*row],
189        Some(
190            Callee::Fn(decl, ws)
191            | Callee::FnValue(decl, ws)
192            | Callee::Method(decl, ws)
193            | Callee::Static(decl, ws),
194        ) => witness_list(decl, &typed.types)
195            .iter()
196            .zip(ws)
197            .filter(|(w, _)| w.kind == WitnessKind::Codec)
198            .map(|(_, t)| *t)
199            .collect(),
200        _ => Vec::new(),
201    }
202}
203
204/// The first externally-owned opaque type that decoding `t` would create: a
205/// consumed type its owner exports opaque, or one declared `opaque`, found
206/// through named types' fields and payloads as well as through the type
207/// itself. Such a value can only be made by the owning context (#2794).
208fn external_opaque_in(
209    t: TyId,
210    typed: &checker::TypedCommons,
211    consumed: &HashMap<String, ConsumedType>,
212    tys: &Arc<Types>,
213) -> Option<(String, String)> {
214    fn names(t: TyId, tys: &Arc<Types>, out: &mut Vec<String>) {
215        match &*tys.get(t) {
216            Ty::Named { name, args, .. } => {
217                out.push(name.clone());
218                args.iter().for_each(|a| names(*a, tys, out));
219            }
220            Ty::Option(a) | Ty::List(a) | Ty::Set(a) => names(*a, tys, out),
221            Ty::Result(a, b) | Ty::Map(a, b) => {
222                names(*a, tys, out);
223                names(*b, tys, out);
224            }
225            _ => {}
226        }
227    }
228    let mut stack = Vec::new();
229    names(t, tys, &mut stack);
230    external_opaque_reaching(stack, typed, consumed)
231}
232
233/// As [`external_opaque_in`], from the type names a position mentions.
234fn external_opaque_reaching(
235    mut stack: Vec<String>,
236    typed: &checker::TypedCommons,
237    consumed: &HashMap<String, ConsumedType>,
238) -> Option<(String, String)> {
239    let mut seen: HashSet<String> = HashSet::new();
240    while let Some(n) = stack.pop() {
241        if !seen.insert(n.clone()) {
242            continue;
243        }
244        let decl = typed.types.get(&n);
245        if let Some(ct) = consumed.get(&n)
246            && (ct.visibility == Visibility::Opaque
247                || decl.is_some_and(|d| matches!(d.body, TypeBody::Opaque { .. })))
248        {
249            return Some((n, ct.owning_context.clone()));
250        }
251        let Some(decl) = decl else {
252            continue;
253        };
254        let vars: HashSet<&str> = decl
255            .type_params
256            .iter()
257            .map(|p| p.name.name.as_str())
258            .collect();
259        let mut found = Vec::new();
260        match &decl.body {
261            TypeBody::Record(r) => r
262                .fields
263                .iter()
264                .for_each(|f| crate::project_model::type_ref_names(&f.type_ref, &vars, &mut found)),
265            TypeBody::Sum(sum) => sum.variants.iter().for_each(|v| {
266                v.payload.iter().for_each(|p| {
267                    crate::project_model::type_ref_names(&p.type_ref, &vars, &mut found)
268                })
269            }),
270            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
271        }
272        stack.extend(found);
273    }
274    None
275}
276
277/// #2794: decoding creates a value, so a context cannot decode a type another
278/// context owns and exports opaque, through `Json.decode`, `Json.decodeSql` or a
279/// `Codable` witness: its codec would check no more than the base type, because
280/// the owner's predicate is the owner's secret. A reply from the owner's own
281/// service is not this: that decode is generated, and a skewed owner is caught
282/// by the contract hash.
283fn check_decode_of_external_opaque(
284    e: &Expr,
285    typed: &checker::TypedCommons,
286    consumed: &HashMap<String, ConsumedType>,
287    errors: &mut Vec<CompileError>,
288    tys: &Arc<Types>,
289) {
290    if consumed.is_empty() {
291        return;
292    }
293    for t in decode_targets(e, typed) {
294        if let Some((name, owner)) = external_opaque_in(t, typed, consumed, tys) {
295            errors.push(
296                CompileError::new(
297                    "bynk.context.external_decode",
298                    e.span,
299                    format!(
300                        "cannot decode `{}` here — `{name}` is owned by context `{owner}`",
301                        tys.display(t),
302                    ),
303                )
304                .with_note(
305                    "decoding creates a value, and values of an externally-owned opaque type can only be created inside the owning context; take the value from a service of `{owner}` instead".replace("{owner}", &owner),
306                ),
307            );
308            return;
309        }
310    }
311}
312
313/// #2794: an HTTP or queue handler decodes its parameters from bytes the
314/// context did not produce, so a parameter that reaches a type another context
315/// owns and exports opaque would create one of its values from the base type
316/// alone. A `call` handler's arguments come from a Bynk caller that holds such
317/// a value, so it is not an input in this sense. A `from Events(E)` subscriber is
318/// one: its event arrives as the publisher's payload, decoded here, so a
319/// payload field of such a type is refused (the event's declaration is walked
320/// like any record's).
321fn check_handler_inputs_not_external_opaque(
322    s: &ServiceDecl,
323    typed: &checker::TypedCommons,
324    consumed: &HashMap<String, ConsumedType>,
325    errors: &mut Vec<CompileError>,
326) {
327    if consumed.is_empty() || matches!(s.protocol, ServiceProtocol::Call | ServiceProtocol::Cron) {
328        return;
329    }
330    // A held WebSocket decodes every inbound frame as `in_type`, whichever
331    // handler the frame reaches.
332    if let ServiceProtocol::WebSocket { in_type, .. } = &s.protocol {
333        let mut names = Vec::new();
334        crate::project_model::type_ref_names(in_type, &HashSet::new(), &mut names);
335        if let Some((name, owner)) = external_opaque_reaching(names, typed, consumed) {
336            errors.push(
337                CompileError::new(
338                    "bynk.context.external_decode",
339                    in_type.span(),
340                    format!(
341                        "cannot take inbound frames of this type here — `{name}` is owned by context `{owner}`"
342                    ),
343                )
344                .with_note(
345                    "a frame is decoded from bytes this context did not produce, which creates a value; values of an externally-owned opaque type can only be created inside the owning context",
346                ),
347            );
348            return;
349        }
350    }
351    for h in &s.handlers {
352        for p in &h.params {
353            let mut names = Vec::new();
354            crate::project_model::type_ref_names(&p.type_ref, &HashSet::new(), &mut names);
355            if let Some((name, owner)) = external_opaque_reaching(names, typed, consumed) {
356                errors.push(
357                    CompileError::new(
358                        "bynk.context.external_decode",
359                        p.type_ref.span(),
360                        format!(
361                            "cannot take `{}` as an input here — `{name}` is owned by context `{owner}`",
362                            p.name.name,
363                        ),
364                    )
365                    .with_note(
366                        "an input is decoded from bytes this context did not produce, which creates a value; values of an externally-owned opaque type can only be created inside the owning context",
367                    ),
368                );
369            }
370        }
371    }
372}
373
374fn walk_block_for_constraints(
375    block: &Block,
376    typed: &checker::TypedCommons,
377    consumed: &HashMap<String, ConsumedType>,
378    local: &HashSet<String>,
379    errors: &mut Vec<CompileError>,
380    tys: &Arc<Types>,
381) {
382    let mut exprs = Vec::new();
383    for stmt in &block.statements {
384        statement_exprs(stmt, &mut exprs);
385    }
386    exprs.push(&block.tail);
387    for e in exprs {
388        walk_expr_for_constraints(e, typed, consumed, local, errors, tys);
389    }
390}
391
392/// Recurse an expression for the cross-context construction/inspection
393/// constraints, checking each node's own shape then descending through
394/// `ast::expr_children` — the exhaustive total child iterator — rather than a
395/// hand-matched recursion. A `_ => {}` below only opts a variant out of *this
396/// function's own* business-rule check; the recursion beneath it is
397/// unconditional and can't be silently skipped by a future `ExprKind` variant
398/// the way the equivalent hand-rolled match could.
399///
400/// `local` threads through unread — pre-existing (`check_context_constraints`'s
401/// `local_type_names` is part of the broader `ResolvedCommons`/local-type-name
402/// handling the review flags separately at #57), not introduced by this pass.
403/// Collapsing the old mutual block/expr recursion into one self-recursive
404/// function made clippy's `only_used_in_recursion` newly able to see it.
405#[allow(clippy::only_used_in_recursion)]
406fn walk_expr_for_constraints(
407    e: &Expr,
408    typed: &checker::TypedCommons,
409    consumed: &HashMap<String, ConsumedType>,
410    local: &HashSet<String>,
411    errors: &mut Vec<CompileError>,
412    tys: &Arc<Types>,
413) {
414    check_decode_of_external_opaque(e, typed, consumed, errors, tys);
415    match &e.kind {
416        // A transparent export shares its structure with consumers, including
417        // field-level construction (type-system §6.5); only an opaque one's
418        // record form is the owner's alone. #1700: this used to reject any
419        // consumed type, which free functions rarely hit but handlers do —
420        // building `bynk`'s `Request`, or an adapter's boundary record, is how
421        // those capabilities are called.
422        ExprKind::RecordConstruction { type_name, .. } => {
423            if let Some(ct) = consumed.get(&type_name.name)
424                && ct.visibility == Visibility::Opaque
425            {
426                errors.push(
427                    CompileError::new(
428                        "bynk.context.external_construction",
429                        type_name.span,
430                        format!(
431                            "cannot construct `{}` here — it is owned by context `{}`",
432                            type_name.name, ct.owning_context,
433                        ),
434                    )
435                    .with_note(
436                        "values of an externally-owned type can only be created inside the owning context",
437                    ),
438                );
439            }
440        }
441        // `T.method(...)` written as MethodCall with receiver Ident(T).
442        ExprKind::MethodCall {
443            receiver, method, ..
444        } => {
445            if let ExprKind::Ident(id) = &receiver.kind
446                && let Some(ct) = consumed.get(&id.name)
447            {
448                let is_construct = method.name == OF
449                    || method.name == UNSAFE
450                    || matches!(
451                        typed.types.get(&id.name).map(|d| &d.body),
452                        Some(TypeBody::Sum(s)) if s.variants.iter().any(|v| v.name.name == method.name),
453                    );
454                if is_construct {
455                    errors.push(
456                        CompileError::new(
457                            "bynk.context.external_construction",
458                            id.span.merge(method.span),
459                            format!(
460                                "cannot construct `{}.{}` here — `{}` is owned by context `{}`",
461                                id.name, method.name, id.name, ct.owning_context,
462                            ),
463                        )
464                        .with_note(
465                            "values of an externally-owned type can only be created inside the owning context",
466                        ),
467                    );
468                }
469            }
470        }
471        // `T.X` on an opaquely-exported sum's type name names a variant, and
472        // a field read on a value of an opaquely-exported type reads its
473        // fields: both inspect the shape the export hides (#1948).
474        ExprKind::FieldAccess { receiver, field } => {
475            if let ExprKind::Ident(id) = &receiver.kind
476                && let Some(ct) = consumed.get(&id.name)
477                && ct.visibility == Visibility::Opaque
478                && typed
479                    .types
480                    .get(&id.name)
481                    .map(|d| matches!(d.body, TypeBody::Sum(_)))
482                    .unwrap_or(false)
483            {
484                errors.push(
485                    CompileError::new(
486                        "bynk.context.opaque_inspection",
487                        id.span.merge(field.span),
488                        format!(
489                            "cannot inspect opaquely-exported type `{}` from outside context `{}`",
490                            id.name, ct.owning_context,
491                        ),
492                    )
493                    .with_note(
494                        "opaque exports hide the type's shape; the owning context did not expose variants or fields",
495                    ),
496                );
497            } else if let Some((name, ct)) = opaque_export_of(receiver, typed, consumed) {
498                errors.push(
499                    CompileError::new(
500                        "bynk.context.opaque_inspection",
501                        field.span,
502                        format!(
503                            "cannot read field `{}` of opaquely-exported type `{name}` from outside context `{}`",
504                            field.name, ct.owning_context,
505                        ),
506                    )
507                    .with_note(
508                        "opaque exports hide the type's shape; a consumer can hold and pass the value, and call its methods, but not read its fields",
509                    ),
510                );
511            }
512        }
513        // If the discriminant is typed as an opaquely-exported consumed
514        // type, the match is forbidden because we can't reveal the variants.
515        ExprKind::Match { discriminant, arms } => {
516            let mut discriminant_reported = false;
517            // #2712: a `let`/lambda-parameter record pattern is a `match` on a
518            // hidden binder the author never wrote, so its opaque type is
519            // reported where they wrote it — at the pattern, below.
520            let hidden_record = matches!(&discriminant.kind, ExprKind::Ident(i) if bynk_syntax::ast::is_generated_binding(&i.name))
521                && matches!(
522                    arms.first().map(|a| &a.pattern),
523                    Some(Pattern::Record { .. })
524                );
525            if !hidden_record && let Some(ty) = typed.expr_ty(discriminant.id).as_deref() {
526                let display = ty.display(tys);
527                if let Some(ct) = consumed.get(&display)
528                    && ct.visibility == Visibility::Opaque
529                {
530                    discriminant_reported = true;
531                    errors.push(
532                        CompileError::new(
533                            "bynk.context.opaque_inspection",
534                            discriminant.span,
535                            format!(
536                                "cannot `match` on opaquely-exported type `{}` from outside context `{}`",
537                                display, ct.owning_context,
538                            ),
539                        )
540                        .with_note(
541                            "opaque exports hide the type's shape; the owning context did not expose variants",
542                        ),
543                    );
544                }
545            }
546            // #2641: a record pattern reads fields exactly as `.field` does.
547            // The discriminant report above already covers a `match` on the
548            // opaque value itself.
549            for arm in arms {
550                opaque_record_patterns(&arm.pattern, consumed, !discriminant_reported, errors);
551            }
552        }
553        ExprKind::Is { pattern, .. } => opaque_record_patterns(pattern, consumed, true, errors),
554        _ => {}
555    }
556    for child in expr_children(e) {
557        walk_expr_for_constraints(child, typed, consumed, local, errors, tys);
558    }
559}
560
561/// #2641: every record pattern in `pattern` that names an opaquely-exported
562/// consumed type reads the fields the export hides, as a field read does.
563/// `top` is false when the pattern's own scrutinee was already reported.
564fn opaque_record_patterns(
565    pattern: &Pattern,
566    consumed: &HashMap<String, ConsumedType>,
567    top: bool,
568    errors: &mut Vec<CompileError>,
569) {
570    match pattern {
571        Pattern::Record {
572            type_name, fields, ..
573        } => {
574            if top
575                && let Some(ct) = consumed.get(&type_name.name)
576                && ct.visibility == Visibility::Opaque
577            {
578                errors.push(
579                    CompileError::new(
580                        "bynk.context.opaque_inspection",
581                        pattern.span(),
582                        format!(
583                            "cannot match fields of opaquely-exported type `{}` from outside context `{}`",
584                            type_name.name, ct.owning_context,
585                        ),
586                    )
587                    .with_note(
588                        "opaque exports hide the type's shape; a consumer can hold and pass the value, and call its methods, but not read its fields",
589                    ),
590                );
591            }
592            for (_, sub) in fields {
593                if let Some(sub) = sub {
594                    opaque_record_patterns(sub, consumed, true, errors);
595                }
596            }
597        }
598        Pattern::List { elems, .. } => {
599            for e in elems {
600                opaque_record_patterns(e, consumed, true, errors);
601            }
602        }
603        Pattern::Variant { bindings, .. } => {
604            for b in bindings {
605                opaque_record_patterns(b.pattern(), consumed, true, errors);
606            }
607        }
608        Pattern::Or(alts, _) => {
609            for a in alts {
610                opaque_record_patterns(a, consumed, top, errors);
611            }
612        }
613        Pattern::Refined { inner, .. } => opaque_record_patterns(inner, consumed, top, errors),
614        Pattern::Wildcard(_)
615        | Pattern::Binding(_)
616        | Pattern::Literal { .. }
617        | Pattern::Range(_) => {}
618    }
619}
620
621/// #1948: the opaquely-exported consumed type `e` is a value of, if any,
622/// with its export's metadata. Reads the type `e` was checked at, so a
623/// value bound from a call or a parameter is caught however it is spelled.
624fn opaque_export_of<'c>(
625    e: &Expr,
626    typed: &checker::TypedCommons,
627    consumed: &'c HashMap<String, ConsumedType>,
628) -> Option<(String, &'c ConsumedType)> {
629    let ty = typed.expr_ty(e.id)?;
630    let Ty::Named { name, .. } = &*ty else {
631        return None;
632    };
633    let ct = consumed.get(name)?;
634    (ct.visibility == Visibility::Opaque).then(|| (name.clone(), ct))
635}
636
637/// Check capability/provider/service/agent declaration bodies for a context (or
638/// adapter) unit. Mutates `typed` to extend the expr_types map with bindings
639/// observed in the new bodies.
640///
641/// The parent builds the shared state read by every per-kind validator — a
642/// `resolved` commons snapshot and the `capability_info_map` (local capability
643/// signatures, extended with the cross-context flattened caps) — then runs the
644/// per-declaration-kind validators in a fixed order. The order is load-bearing:
645/// multi-error fixtures assert the diagnostic sequence
646/// (capabilities → providers → services → agents).
647#[allow(clippy::too_many_arguments)]
648pub fn check_context_declarations(
649    typed: &mut checker::TypedCommons,
650    table: &UnitTable,
651    cross_context: &resolver::CrossContextInfo,
652    is_context: bool,
653    uses_commons_type_names: &HashSet<String>,
654    // Events slice 3a (#972): this unit's own local + direct-`uses` types —
655    // deliberately narrower than `typed.types` (local + uses + *consumes*).
656    // A field default is validated against this table because it's the same
657    // one a **subscriber** regenerating this event's codec cross-context
658    // will see (`emit_consumed_context_helpers`'s `combined_types_for`,
659    // #973) — a default reachable only through this unit's own `consumes`
660    // would pass here-with-the-wider-table and then silently fail to
661    // construct in a subscriber's module, with no diagnostic at emit time.
662    subscriber_visible_types: &HashMap<String, Arc<TypeDecl>>,
663    refs: &mut RefSink,
664    hints: &mut HintSink,
665    locals: &mut LocalsSink,
666    requirements: &mut RequirementSink,
667    tys: &Arc<Types>,
668) -> Vec<CompileError> {
669    let mut errors = Vec::new();
670    let no_vars: HashSet<String> = HashSet::new();
671
672    // Build a resolved-commons snapshot for the per-handler checker.
673    // We synthesise a ResolvedCommons by reusing typed.types / typed.fns /
674    // typed.methods; the resolver wouldn't add anything new. `ResolvedCommons::new`
675    // derives `local_type_names`/`event_type_names` from `table` — the
676    // *pre-merge* local table — rather than `typed.types` (already
677    // local+uses+consumes merged); see its doc comment for why that
678    // distinction matters (owner-only emission, spine #936).
679    let resolved = ResolvedCommons::new(
680        typed.commons.clone(),
681        typed.types.clone(),
682        &table.types,
683        typed.fns.clone(),
684        typed.methods.clone(),
685        table.agents.clone(),
686        &table.events,
687        cross_context.clone(),
688        HashMap::new(),
689        is_context,
690        uses_commons_type_names.clone(),
691    )
692    .with_local_fns(&table.fns)
693    // #1883, slice 1a: a handler body sees the unit's assets too.
694    .with_assets(typed.assets.clone())
695    .with_embeds(typed.embeds.clone())
696    .with_consts(typed.consts.clone())
697    .with_shadowed_imports(typed.shadowed_imports.clone())
698    .with_scope_facts_of(typed)
699    .with_stability(typed.stability.clone());
700
701    // v0.25: capability operation signatures reference types.
702    check_capability_decls(table, &typed.types, &no_vars, refs);
703    // S4a (#1966): a derived capability's base (`capability Sessions = Kv`)
704    // is a reference to the base, in the unit that declares it, recorded as a
705    // bare `given Kv` is.
706    for item in &typed.commons.items {
707        if let CommonsItem::Capability(c) = item
708            && let Some(d) = &c.derived
709        {
710            crate::symbols::record_capability_clause_ref(&d.base, cross_context, refs);
711        }
712    }
713
714    // Capability info from the table.
715    let mut capability_info_map: HashMap<String, CapabilityInfo> = table
716        .capabilities
717        .iter()
718        .map(|(name, decl)| {
719            let ops = decl
720                .ops
721                .iter()
722                .map(|op| build_capability_op_info(op, &typed.types, tys))
723                .collect();
724            (
725                name.clone(),
726                CapabilityInfo {
727                    name: name.clone(),
728                    ops,
729                    derived_from: derived_from(decl, &cross_context.flattened_caps),
730                },
731            )
732        })
733        .collect();
734    // v0.17: flattened capabilities (`consumes U { Cap }`) enter the local map
735    // under their bare names, resolved from the consumed unit's exported
736    // capability so bare `given Cap` / `Cap.op(…)` type-check as if local.
737    let mut receiving_cache: Option<checker::Projection> = None;
738    for (cap, unit) in &cross_context.flattened_caps {
739        let Some(xcap) = cross_context
740            .consumed_capabilities
741            .get(unit)
742            .and_then(|m| m.get(cap))
743        else {
744            continue;
745        };
746        // #2634: an operation may name a type the unit declares but does not
747        // export (an adapter's `Token`), or one the consumer also declares.
748        // As the qualified `U.Cap.op` call does, resolve the signature against
749        // the unit's own table; a name the consumer binds to a structurally
750        // different type is refused (`bynk.boundary.structural_mismatch`)
751        // rather than read as the consumer's. The refusal is per op, at its call.
752        let unit_types = cross_context
753            .consumed_types
754            .get(unit)
755            .unwrap_or(&typed.types);
756        let (receiving, _) = receiving_cache.get_or_insert_with(|| {
757            checker::projected_types(&typed.types, &cross_context.consumed_types, tys)
758        });
759        let ops = xcap
760            .ops
761            .iter()
762            .map(|op| {
763                let vars: HashSet<String> = op.type_params.iter().cloned().collect();
764                let mut conflict: Option<(String, String, bool)> = None;
765                let mut resolve = |tr: &TypeRef, in_param: bool| {
766                    let ty = checker::resolve_type_ref_in(tr, unit_types, &vars, tys)
767                        .unwrap_or_else(|| tys.intern(Ty::Unit));
768                    if conflict.is_none()
769                        && let Some(name) =
770                            checker::rebrand_conflict(ty, unit_types, &typed.types, receiving, tys)
771                    {
772                        conflict = Some((unit.clone(), name, in_param));
773                    }
774                    checker::rebrand_return_type(ty, &typed.types, tys)
775                };
776                let params = op.params.iter().map(|(_, tr)| resolve(tr, true)).collect();
777                let return_ty = resolve(&op.return_type, false);
778                CapabilityOpInfo {
779                    name: op.name.clone(),
780                    type_params: op.type_params.clone(),
781                    params,
782                    param_names: op.params.iter().map(|(n, _)| n.clone()).collect(),
783                    return_ty,
784                    codable_params: op.codable_params.clone(),
785                    reply_policy: op.reply_policy,
786                    boundary_conflict: conflict,
787                }
788            })
789            .collect();
790        capability_info_map.insert(
791            cap.clone(),
792            CapabilityInfo {
793                name: cap.clone(),
794                ops,
795                derived_from: None,
796            },
797        );
798    }
799
800    check_provider_decls(
801        typed,
802        table,
803        cross_context,
804        &resolved,
805        &capability_info_map,
806        refs,
807        hints,
808        locals,
809        requirements,
810        &mut errors,
811        tys,
812    );
813    check_service_decls(
814        typed,
815        table,
816        cross_context,
817        &resolved,
818        &capability_info_map,
819        refs,
820        hints,
821        locals,
822        requirements,
823        &mut errors,
824        tys,
825    );
826    check_given_fns(
827        typed,
828        cross_context,
829        &resolved,
830        &capability_info_map,
831        refs,
832        hints,
833        locals,
834        requirements,
835        &mut errors,
836        tys,
837    );
838    check_agent_decls(
839        typed,
840        table,
841        cross_context,
842        is_context,
843        uses_commons_type_names,
844        &capability_info_map,
845        &no_vars,
846        refs,
847        hints,
848        locals,
849        requirements,
850        &mut errors,
851        tys,
852    );
853    // After the agent bodies, so their own agent calls are classified too.
854    check_provider_agent_calls(table, &typed.callees, &mut errors);
855    // #2469: every body's requirements and agent calls are now classified, so
856    // the capability paths can be drawn from the same facts.
857    let paths = crate::capability_paths::CapabilityGraph::build(
858        table,
859        &typed.callees,
860        requirements.current(),
861        typed.commons.span.file,
862    );
863    requirements.record_paths(paths);
864
865    check_event_field_defaults(
866        table,
867        &resolved,
868        subscriber_visible_types,
869        &mut typed.expr_types,
870        &mut typed.callees,
871        refs,
872        hints,
873        locals,
874        &mut errors,
875        tys,
876    );
877
878    check_event_annotations(table, &mut errors);
879
880    // State-migrations S3 (#2248): `replaces` / `removed agent` on their own
881    // terms; what needs the schema lock is the reconcile's.
882    check_class_declarations(table, &mut errors);
883
884    errors
885}
886
887/// State-migrations S3 (#2248, Decision B): the source-only rules for agent
888/// class renames and removals. The old name of a `replaces` or `removed agent`
889/// must not still be declared as an agent, and each old name has one fate — a
890/// single rename, or a removal.
891fn check_class_declarations(table: &UnitTable, errors: &mut Vec<CompileError>) {
892    let mut fates: HashMap<&str, Span> = HashMap::new();
893    let mut agents: Vec<&AgentDecl> = table.agents.values().map(|a| &**a).collect();
894    agents.sort_by_key(|a| a.span.start);
895    for a in agents {
896        let Some(old) = &a.replaces else { continue };
897        if table.agents.contains_key(&old.name) {
898            errors.push(
899                CompileError::new(
900                    "bynk.agent.replaces_live",
901                    old.span,
902                    format!(
903                        "agent `{}` replaces `{}`, but `{}` is still declared",
904                        a.name.name, old.name, old.name
905                    ),
906                )
907                .with_note("a rename moves the old class's data to the new one; remove the old declaration"),
908            );
909        }
910        if let Some(prev) = fates.insert(&old.name, old.span) {
911            errors.push(
912                CompileError::new(
913                    "bynk.agent.class_conflict",
914                    old.span,
915                    format!("agent class `{}` is renamed more than once", old.name),
916                )
917                .with_label(prev, "first renamed here"),
918            );
919        }
920    }
921    for r in &table.removed_agents {
922        if table.agents.contains_key(&r.name.name) {
923            errors.push(
924                CompileError::new(
925                    "bynk.agent.removed_live",
926                    r.name.span,
927                    format!(
928                        "`removed agent {}` names a class that is still declared",
929                        r.name.name
930                    ),
931                )
932                .with_note(
933                    "removing a class deletes its stored data; remove the declaration first",
934                ),
935            );
936        }
937        if let Some(prev) = fates.insert(&r.name.name, r.name.span) {
938            errors.push(
939                CompileError::new(
940                    "bynk.agent.class_conflict",
941                    r.name.span,
942                    format!(
943                        "agent class `{}` is both renamed and removed, or removed twice",
944                        r.name.name
945                    ),
946                )
947                .with_label(prev, "its other fate is declared here"),
948            );
949        }
950    }
951}
952
953/// Events slice 3a (#972): validate every `event`'s field default (`field: T
954/// = expr`), if it has one. Two gates, both required before emission ever
955/// sees it:
956///
957/// 1. **Static/pure/typed** — `checker::check_event_field_default`, the same
958///    empty-pure-scope discipline agent `store` field defaults already have
959///    (`bynk.agents.bad_state_initialiser`'s sibling), pushing
960///    `bynk.types.bad_field_default` on failure.
961/// 2. **Constructible** — `crate::wire_default::lower_field_default_wire`
962///    against `subscriber_visible_types`, the *narrower* table a subscriber
963///    regenerating this event's codec cross-context will actually see. This
964///    is what keeps emission's own `.ok()` fallback (`emit_record`)
965///    unreachable in practice: anything this same function can't build is
966///    rejected here, with a diagnostic, before it ever reaches emission.
967///
968/// Only gate 2 runs when gate 1 already found a problem — a value that
969/// isn't even a valid static value of the right type has nothing useful to
970/// say about wire-constructibility, and would just be a confusing second
971/// error for the same field.
972#[allow(clippy::too_many_arguments)]
973fn check_event_field_defaults(
974    table: &UnitTable,
975    resolved: &ResolvedCommons,
976    subscriber_visible_types: &HashMap<String, Arc<TypeDecl>>,
977    expr_types: &mut HashMap<ExprId, TypedExpr>,
978    callees: &mut HashMap<ExprId, checker::Callee>,
979    refs: &mut RefSink,
980    hints: &mut HintSink,
981    locals: &mut LocalsSink,
982    errors: &mut Vec<CompileError>,
983    tys: &Arc<Types>,
984) {
985    for event in table.events.values() {
986        for field in &event.body.fields {
987            let Some(init) = &field.init else {
988                continue;
989            };
990            let before = errors.len();
991            checker::check_event_field_default(
992                init,
993                &field.type_ref,
994                "event field default",
995                resolved,
996                tys,
997                expr_types,
998                callees,
999                errors,
1000                refs,
1001                hints,
1002                locals,
1003            );
1004            if errors.len() > before {
1005                continue;
1006            }
1007            if let Err(reason) = crate::wire_default::lower_event_field_default_wire(
1008                init,
1009                &field.type_ref,
1010                subscriber_visible_types,
1011            ) {
1012                errors.push(
1013                    CompileError::new(
1014                        "bynk.types.bad_field_default",
1015                        init.span,
1016                        format!(
1017                            "event field `{}`'s default cannot be represented on the wire: {reason}",
1018                            field.name.name
1019                        ),
1020                    )
1021                    .with_note(
1022                        "a default is spliced into the same codec a real wire value passes \
1023                         through, so it must be buildable with no reference to any type's \
1024                         generated value namespace — only literals, sum-variant tags, and record \
1025                         literals qualify",
1026                    ),
1027                );
1028            }
1029        }
1030    }
1031}
1032
1033/// Events slice 3b (#978): validate every event's `@`-annotations against
1034/// the closed one-name registry. `@schema` is the only legal name; its sole
1035/// argument must be a positive `Int` literal, positional (not labelled), and
1036/// it may appear at most once per event. `EventDecl::schema_version` reads
1037/// the same annotations permissively (falling back to `1` on anything that
1038/// doesn't fit) — this is what keeps that fallback unreachable for anything
1039/// but an already-reported error.
1040fn check_event_annotations(table: &UnitTable, errors: &mut Vec<CompileError>) {
1041    for event in table.events.values() {
1042        let mut schema_count = 0usize;
1043        for ann in &event.annotations {
1044            if ann.name.name != "schema" {
1045                errors.push(
1046                    CompileError::new(
1047                        "bynk.event.unknown_annotation",
1048                        ann.name.span,
1049                        format!(
1050                            "unknown event annotation `@{}` — expected `@schema`",
1051                            ann.name.name
1052                        ),
1053                    )
1054                    .with_note("event annotations are a closed set"),
1055                );
1056                continue;
1057            }
1058            schema_count += 1;
1059            if schema_count > 1 {
1060                errors.push(
1061                    CompileError::new(
1062                        "bynk.event.bad_schema_version",
1063                        ann.span,
1064                        "`@schema` may appear at most once on an event",
1065                    )
1066                    .with_note("the event's schema version is a single value, not a set"),
1067                );
1068                continue;
1069            }
1070            match ann.args.as_slice() {
1071                [arg] if arg.label.is_none() => {
1072                    if !matches!(&arg.value.kind, ExprKind::IntLit { value, .. } if *value > 0) {
1073                        errors.push(crate::annotation_consts::with_const_origin(
1074                            CompileError::new(
1075                                "bynk.event.bad_schema_version",
1076                                arg.span,
1077                                "`@schema`'s argument must be a positive `Int` literal, or an `Int` constant bound to one",
1078                            ),
1079                            arg,
1080                        ));
1081                    }
1082                }
1083                [arg] => {
1084                    errors.push(CompileError::new(
1085                        "bynk.event.bad_schema_version",
1086                        arg.span,
1087                        "`@schema` takes one positional argument, not a labelled one",
1088                    ));
1089                }
1090                [] => {
1091                    errors.push(
1092                        CompileError::new(
1093                            "bynk.event.bad_schema_version",
1094                            ann.span,
1095                            "`@schema` requires one argument — the schema version",
1096                        )
1097                        .with_note("write `@schema(2)`, for example"),
1098                    );
1099                }
1100                _ => {
1101                    errors.push(CompileError::new(
1102                        "bynk.event.bad_schema_version",
1103                        ann.span,
1104                        "`@schema` takes exactly one argument",
1105                    ));
1106                }
1107            }
1108        }
1109    }
1110}
1111
1112/// v0.25: capability operation signatures reference types; record them under
1113/// the capability as owner (the table is unit-level — the owner re-attributes
1114/// spans to the declaring file at assembly).
1115fn check_capability_decls(
1116    table: &UnitTable,
1117    types: &HashMap<String, Arc<TypeDecl>>,
1118    no_vars: &HashSet<String>,
1119    refs: &mut RefSink,
1120) {
1121    for (name, decl) in &table.capabilities {
1122        refs.set_owner(name);
1123        for op in &decl.ops {
1124            // #926: an op's own type parameters shadow a same-named real type
1125            // (mirroring every other `skip`-set use here) — a bare `T` should
1126            // never index-reference an unrelated declared type `T`.
1127            let vars: HashSet<String> = if op.type_params.is_empty() {
1128                no_vars.clone()
1129            } else {
1130                op.type_params.iter().map(|p| p.name.name.clone()).collect()
1131            };
1132            for p in &op.params {
1133                checker::record_type_refs(&p.type_ref, types, &vars, refs);
1134            }
1135            checker::record_type_refs(&op.return_type, types, &vars, refs);
1136        }
1137    }
1138    refs.clear_owner();
1139}
1140
1141/// Check provider bodies. v0.12: a provider may declare `given` and use
1142/// those capabilities in its bodies (provider composition). Bodies are
1143/// effectful if the operation returns Effect[T]; no `self`. Also detects
1144/// provider dependency cycles over capabilities.
1145#[allow(clippy::too_many_arguments)]
1146fn check_provider_decls(
1147    typed: &mut checker::TypedCommons,
1148    table: &UnitTable,
1149    cross_context: &resolver::CrossContextInfo,
1150    resolved: &ResolvedCommons,
1151    capability_info_map: &HashMap<String, CapabilityInfo>,
1152    refs: &mut RefSink,
1153    hints: &mut HintSink,
1154    locals: &mut LocalsSink,
1155    requirements: &mut RequirementSink,
1156    errors: &mut Vec<CompileError>,
1157    tys: &Arc<Types>,
1158) {
1159    for provider in table.providers.values() {
1160        refs.set_owner(&provider.provider_name.name);
1161        // v0.25: `provides Cap = …` references the capability.
1162        // v0.35 (ADR 0068): and records a capability→provider implementation edge.
1163        if table.capabilities.contains_key(&provider.capability.name)
1164            || cross_context
1165                .flattened_caps
1166                .contains_key(&provider.capability.name)
1167        {
1168            record_provides_clause_ref(&provider.capability, cross_context, refs);
1169        }
1170        // Build the provider's capability scope from its `given`, validating
1171        // each name is a declared capability.
1172        let mut provider_caps: HashMap<String, CapabilityInfo> = HashMap::new();
1173        for cap_ref in &provider.given {
1174            if let Some(info) =
1175                resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
1176            {
1177                provider_caps.insert(cap_ref.key().to_string(), info);
1178            }
1179        }
1180        for op in &provider.ops {
1181            // The provider's `given` keys are in scope (so cross-context
1182            // capability calls resolve), but unused-`given` is not reported
1183            // per-op: a capability may be used in one op but not another.
1184            // No `given_anchor`: the clause lives on the `provides` line,
1185            // not at the op's return type, so an absent clause is not
1186            // synthesised here (v0.26).
1187            checker::check_handler_body(
1188                resolved,
1189                checker::HandlerBodyCheck {
1190                    capabilities: provider_caps.clone(),
1191                    declared_capabilities: capability_info_map.clone(),
1192                    ..checker::HandlerBodyCheck::new(
1193                        &op.body,
1194                        &op.return_type,
1195                        &op.params,
1196                        &provider.given,
1197                    )
1198                },
1199                checker::CheckSinks {
1200                    tys,
1201                    expr_types: &mut typed.expr_types,
1202                    errors,
1203                    refs,
1204                    hints,
1205                    locals,
1206                    requirements,
1207                    callees: &mut typed.callees,
1208                },
1209            );
1210        }
1211    }
1212
1213    // v0.12: providers form a dependency graph over capabilities (a provider's
1214    // `given` are the capabilities its provided capability depends on). Reject
1215    // a cycle — the composition root cannot instantiate one in dependency
1216    // order. Self-provision (`provides X = … given X`) is the trivial cycle.
1217    detect_provider_dependency_cycles(&table.providers, errors);
1218}
1219
1220/// #2868: type-check this file's context functions that declare `given`. They
1221/// wait for the context's capability table, which a plain function's check
1222/// (`check_record_in`) does not have. A function the declaration rules refuse
1223/// (`given_fn_refusal`) was reported there and is not checked again.
1224#[allow(clippy::too_many_arguments)]
1225fn check_given_fns(
1226    typed: &mut checker::TypedCommons,
1227    cross_context: &resolver::CrossContextInfo,
1228    resolved: &ResolvedCommons,
1229    capability_info_map: &HashMap<String, CapabilityInfo>,
1230    refs: &mut RefSink,
1231    hints: &mut HintSink,
1232    locals: &mut LocalsSink,
1233    requirements: &mut RequirementSink,
1234    errors: &mut Vec<CompileError>,
1235    tys: &Arc<Types>,
1236) {
1237    let fns: Vec<Arc<FnDecl>> = typed
1238        .commons
1239        .items
1240        .iter()
1241        .filter_map(|i| match i {
1242            CommonsItem::Fn(f) if !f.given.is_empty() => Some(Arc::new(f.clone())),
1243            _ => None,
1244        })
1245        .collect();
1246    for f in fns {
1247        if checker::given_fn_refusal(&f, resolved.is_context).is_some() {
1248            continue;
1249        }
1250        refs.set_owner(f.name.display());
1251        let mut capabilities: HashMap<String, CapabilityInfo> = HashMap::new();
1252        for cap_ref in &f.given {
1253            if let Some(info) =
1254                resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
1255            {
1256                capabilities.insert(cap_ref.key().to_string(), info);
1257            }
1258        }
1259        checker::check_context_fn(
1260            &f,
1261            checker::FnCaps {
1262                capabilities,
1263                declared_capabilities: capability_info_map.clone(),
1264            },
1265            resolved,
1266            &mut typed.expr_types,
1267            &mut typed.callees,
1268            errors,
1269            refs,
1270            hints,
1271            locals,
1272            requirements,
1273            tys,
1274        );
1275        refs.clear_owner();
1276    }
1277}
1278
1279/// The agent handlers `body` calls, as `(agent, handler)` — read from the
1280/// checker's `Callee::Agent` classification, so an inline `Agent(key).m()` and
1281/// a let-bound `a.m()` count alike.
1282pub(crate) fn agent_calls_in(
1283    body: &Block,
1284    callees: &HashMap<ExprId, checker::Callee>,
1285) -> Vec<(String, String, Span)> {
1286    fn walk(
1287        e: &Expr,
1288        callees: &HashMap<ExprId, checker::Callee>,
1289        out: &mut Vec<(String, String, Span)>,
1290    ) {
1291        if let ExprKind::MethodCall { method, .. } = &e.kind
1292            && let Some(checker::Callee::Agent { agent, handler }) = callees.get(&e.id)
1293        {
1294            out.push((agent.clone(), handler.clone(), method.span));
1295        }
1296        for c in expr_children(e) {
1297            walk(c, callees, out);
1298        }
1299    }
1300    let mut top = Vec::new();
1301    for s in &body.statements {
1302        statement_exprs(s, &mut top);
1303    }
1304    top.push(&body.tail);
1305    let mut out = Vec::new();
1306    for e in top {
1307        walk(e, callees, &mut out);
1308    }
1309    out
1310}
1311
1312/// A capability an agent call needs: the `given` entry that asks for it, and
1313/// the agent handler whose `given` it is.
1314struct AgentNeed<'t> {
1315    cap: &'t CapRef,
1316    agent: String,
1317    handler: String,
1318}
1319
1320/// Every capability calling `agent.handler` needs: the handler's own `given`,
1321/// and — since a handler's deps are widened to cover the agent handlers it
1322/// calls (#527) — theirs, transitively. The first handler to ask for a key
1323/// is the one recorded.
1324fn agent_handler_needs<'t>(
1325    table: &'t UnitTable,
1326    callees: &HashMap<ExprId, checker::Callee>,
1327    agent: &str,
1328    handler: &str,
1329    seen: &mut HashSet<(String, String)>,
1330    out: &mut Vec<AgentNeed<'t>>,
1331) {
1332    if !seen.insert((agent.to_string(), handler.to_string())) {
1333        return;
1334    }
1335    let Some(h) = table.agents.get(agent).and_then(|a| {
1336        a.handlers
1337            .iter()
1338            .find(|h| h.method_name.as_ref().is_some_and(|n| n.name == handler))
1339    }) else {
1340        return;
1341    };
1342    for c in &h.given {
1343        if !out.iter().any(|n| n.cap.key() == c.key()) {
1344            out.push(AgentNeed {
1345                cap: c,
1346                agent: agent.to_string(),
1347                handler: handler.to_string(),
1348            });
1349        }
1350    }
1351    for (a, m, _) in agent_calls_in(&h.body, callees) {
1352        agent_handler_needs(table, callees, &a, &m, seen, out);
1353    }
1354}
1355
1356/// A provider op that calls an agent handler hands it the provider's own deps,
1357/// and a provider is constructed with exactly its declared `given` — unlike a
1358/// service or agent handler, whose deps are widened to cover the agent
1359/// handlers it calls (#527). So every capability the agent handler needs must
1360/// be in the provider's `given`; otherwise the emitted call fails `tsc`.
1361fn check_provider_agent_calls(
1362    table: &UnitTable,
1363    callees: &HashMap<ExprId, checker::Callee>,
1364    errors: &mut Vec<CompileError>,
1365) {
1366    for provider in table.providers.values() {
1367        let entries: Vec<(String, Span)> = provider
1368            .given
1369            .iter()
1370            .map(|c| (c.key().to_string(), c.span))
1371            .collect();
1372        for op in &provider.ops {
1373            for (agent, handler, span) in agent_calls_in(&op.body, callees) {
1374                let mut needs = Vec::new();
1375                agent_handler_needs(
1376                    table,
1377                    callees,
1378                    &agent,
1379                    &handler,
1380                    &mut HashSet::new(),
1381                    &mut needs,
1382                );
1383                for need in needs {
1384                    let key = need.cap.key();
1385                    if entries.iter().any(|(k, _)| k == key) {
1386                        continue;
1387                    }
1388                    // As the agent handler's `given` spells it: a cross-context
1389                    // entry keeps its prefix.
1390                    let written = match need.cap.prefix() {
1391                        Some(prefix) => format!("{prefix}.{key}"),
1392                        None => key.to_string(),
1393                    };
1394                    let mut err = CompileError::new(
1395                        "bynk.provider.agent_call_undeclared_capability",
1396                        span,
1397                        format!(
1398                            "agent handler `{agent}.{handler}` needs `{written}`, but provider `{}` does not list it in `given`",
1399                            provider.provider_name.name
1400                        ),
1401                    );
1402                    if (need.agent.as_str(), need.handler.as_str())
1403                        != (agent.as_str(), handler.as_str())
1404                    {
1405                        err = err.with_note(format!(
1406                            "`{agent}.{handler}` calls `{}.{}`, which is `given {written}`",
1407                            need.agent, need.handler
1408                        ));
1409                    }
1410                    err = err.with_note(format!(
1411                        "a provider hands an agent handler only the capabilities in its own `given`; add `{written}` to the provider's `given` clause"
1412                    ));
1413                    // The clause lives on the `provides` line, so the fix is
1414                    // offered only when it already has entries (v0.26). Not for
1415                    // a cross-context entry: its prefix may be an alias that only
1416                    // the agent's own file declares.
1417                    if let Some((_, last)) = entries.last()
1418                        && !need.cap.is_cross_context()
1419                    {
1420                        err = err.with_suggestion(
1421                            format!("add `{written}` to the `given` clause"),
1422                            vec![(Span::new(last.end, last.end), format!(", {written}"))],
1423                            Applicability::MachineApplicable,
1424                        );
1425                    }
1426                    errors.push(err);
1427                }
1428            }
1429        }
1430    }
1431}
1432
1433/// #3766: an `on call` service has exactly one `on call` handler. Both were
1434/// emitted as members of one object literal, so the last silently shadowed
1435/// the first and its body was dead code. Reported on each handler past the
1436/// first (services name-sorted for a deterministic order), in the shape of
1437/// `bynk.event.duplicate_handler` and `bynk.email.duplicate_handler`.
1438pub(crate) fn check_one_call_handler(table: &UnitTable, errors: &mut Vec<CompileError>) {
1439    let mut services: Vec<&ServiceDecl> = table
1440        .services
1441        .values()
1442        .filter(|s| matches!(s.protocol, ServiceProtocol::Call))
1443        .collect();
1444    services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
1445    for service in services {
1446        let calls: Vec<_> = service
1447            .handlers
1448            .iter()
1449            .filter(|h| h.kind == HandlerKind::Call)
1450            .collect();
1451        for extra in calls.iter().skip(1) {
1452            errors.push(
1453                CompileError::new(
1454                    "bynk.service.duplicate_call_handler",
1455                    extra.span,
1456                    format!(
1457                        "the service `{}` has more than one `on call` handler — it needs exactly one",
1458                        service.name.name
1459                    ),
1460                )
1461                .with_label(calls[0].span, "the service's `on call` handler")
1462                .with_note(
1463                    "a service is called by its name, so it has one entry; to offer a second operation, declare a second service",
1464                ),
1465            );
1466        }
1467    }
1468}
1469
1470/// Check service handlers across all services in this context: HTTP/cron/queue
1471/// handler shape and per-kind duplicate detection (route/schedule/consumer),
1472/// then each handler's `given` clause and body. The duplicate-detection passes
1473/// run before the body pass so the `bynk.<kind>.duplicate_*` diagnostics
1474/// precede the body diagnostics in multi-error fixtures.
1475/// v0.44: a service is one protocol adapter — every handler's form must match
1476/// the `from <protocol>` header. A `from`-less service (`Call`) admits only
1477/// `on call`; mismatches are `bynk.service.{missing_from,mixed_protocols}`.
1478/// `visible_types` is the merged type map (this unit's declarations plus its
1479/// `uses`/`consumes` targets, `typed.types`); `table.types` holds only this
1480/// unit's own, so a check that fails closed on an unknown name must use the
1481/// former, as the HTTP path-param rule does.
1482pub(crate) fn check_service_protocols(
1483    table: &UnitTable,
1484    visible_types: &HashMap<String, Arc<TypeDecl>>,
1485    errors: &mut Vec<CompileError>,
1486    tys: &Arc<Types>,
1487) {
1488    // v0.104 (slice 3b, D5): at v1 the Workers upgrade routes by the `Upgrade:
1489    // websocket` header alone (no path/query discriminator), so a context may hold
1490    // at most one `from websocket` service. Report every WS service past the first
1491    // (name-sorted for a deterministic diagnostic).
1492    let mut ws_services: Vec<&ServiceDecl> = table
1493        .services
1494        .values()
1495        .filter(|s| matches!(s.protocol, ServiceProtocol::WebSocket { .. }))
1496        .collect();
1497    ws_services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
1498    for extra in ws_services.iter().skip(1) {
1499        errors.push(
1500            CompileError::new(
1501                "bynk.service.websocket_multiple",
1502                extra.name.span,
1503                format!(
1504                    "this context holds more than one `from websocket` service (`{}`) — at v1 the upgrade routes by the `Upgrade: websocket` header alone, so a context may host only one",
1505                    extra.name.name
1506                ),
1507            )
1508            .with_note("split the WebSocket services into separate contexts; per-path routing of multiple WebSocket endpoints is a named follow-on"),
1509        );
1510    }
1511    for service in table.services.values() {
1512        // v0.103: a `from websocket` service holds exactly one `on open` handler
1513        // (the edge upgrade); inbound frames are the agent's typed messages, not
1514        // service handlers.
1515        if matches!(service.protocol, ServiceProtocol::WebSocket { .. }) {
1516            let opens: Vec<&Handler> = service
1517                .handlers
1518                .iter()
1519                .filter(|h| matches!(h.kind, HandlerKind::Open))
1520                .collect();
1521            if opens.is_empty() {
1522                errors.push(
1523                    CompileError::new(
1524                        "bynk.service.websocket_open_arity",
1525                        service.name.span,
1526                        format!(
1527                            "the `from websocket` service `{}` has no `on open` handler — it needs exactly one (the edge upgrade)",
1528                            service.name.name
1529                        ),
1530                    )
1531                    .with_note("a `from websocket` service holds exactly one `on open`, and optionally one `on message` (inbound) and one `on close`"),
1532                );
1533            } else if opens.len() > 1 {
1534                errors.push(CompileError::new(
1535                    "bynk.service.websocket_open_arity",
1536                    opens[1].span,
1537                    format!(
1538                        "the `from websocket` service `{}` has more than one `on open` handler — it needs exactly one",
1539                        service.name.name
1540                    ),
1541                ));
1542            }
1543            // #1657 (runtime-semantics track §3.4): an `on open` parameter
1544            // arrives as a query-string value (`url.searchParams.get`), which the
1545            // upgrade passes on unparsed. A `room: Int` was a string cast `as
1546            // number`, so `room + 1` gave `"51"` and `?room=05` reached a
1547            // different agent than `Room(5)`. Like an HTTP path parameter
1548            // (`bynk.http.path_param_not_stringy`), it must be constructible from
1549            // `String`. `on message`/`on close` route values are a prefix of
1550            // these, so they inherit the rule.
1551            for open in &opens {
1552                for p in &open.params {
1553                    // The merged map: an opaque `String` imported through `uses`
1554                    // is constructible too (review of #1693).
1555                    if !is_string_constructible(&p.type_ref, visible_types) {
1556                        errors.push(
1557                            CompileError::new(
1558                                "bynk.service.websocket_param_not_stringy",
1559                                p.type_ref.span(),
1560                                format!(
1561                                    "the `on open` parameter `{}` must have a type constructible from `String` (got `{}`)",
1562                                    p.name.name,
1563                                    ts_type_ref_display(&p.type_ref),
1564                                ),
1565                            )
1566                            .with_note(
1567                                "it arrives as a query-string value; use `String`, a refined `String`, or an opaque type whose base is `String`, and parse an `Int` with `Int.parse` in the body",
1568                            ),
1569                        );
1570                    }
1571                }
1572            }
1573            // v0.106 (slice 3b-iii): the inbound `on message` and `on close` are
1574            // optional but at most one each; an `on message` carries the decoded
1575            // inbound frame as the single param typed as the service's `in` type.
1576            let ServiceProtocol::WebSocket { in_type, .. } = &service.protocol else {
1577                unreachable!("guarded by the enclosing match");
1578            };
1579            // Resolved-`Ty` equality, not surface-syntax comparison — the
1580            // param/route matching below must not silently treat two
1581            // differently-spelled-but-equal types as a mismatch, nor two
1582            // distinct types `type_refs_match`'s `_ => false` fallback
1583            // couldn't classify (List/Map/Query/…) as matching.
1584            let resolve_ty = |t: &TypeRef| {
1585                checker::resolve_type_ref_in(t, &table.types, &HashSet::new(), tys)
1586                    .unwrap_or(tys.intern(Ty::Unit))
1587            };
1588            let messages: Vec<&Handler> = service
1589                .handlers
1590                .iter()
1591                .filter(|h| matches!(h.kind, HandlerKind::Message))
1592                .collect();
1593            let closes: Vec<&Handler> = service
1594                .handlers
1595                .iter()
1596                .filter(|h| matches!(h.kind, HandlerKind::Close))
1597                .collect();
1598            if messages.len() > 1 {
1599                errors.push(CompileError::new(
1600                    "bynk.service.websocket_open_arity",
1601                    messages[1].span,
1602                    format!(
1603                        "the `from websocket` service `{}` has more than one `on message` handler — it needs at most one",
1604                        service.name.name
1605                    ),
1606                ));
1607            }
1608            if closes.len() > 1 {
1609                errors.push(CompileError::new(
1610                    "bynk.service.websocket_open_arity",
1611                    closes[1].span,
1612                    format!(
1613                        "the `from websocket` service `{}` has more than one `on close` handler — it needs at most one",
1614                        service.name.name
1615                    ),
1616                ));
1617            }
1618            for message in &messages {
1619                let frame_params = message
1620                    .params
1621                    .iter()
1622                    .filter(|p| resolve_ty(&p.type_ref) == resolve_ty(in_type))
1623                    .count();
1624                if frame_params != 1 {
1625                    errors.push(
1626                        CompileError::new(
1627                            "bynk.ws.message_frame_param",
1628                            message.span,
1629                            format!(
1630                                "a WebSocket `on message` handler must have exactly one parameter of the service's inbound frame type `{}` (the decoded frame), but found {frame_params}",
1631                                ts_type_ref_display(in_type)
1632                            ),
1633                        )
1634                        .with_note(
1635                            "declare the frame as a parameter, e.g. `on message by user: Actor (frame: ClientFrame)`; any other parameters are route values recovered from the connection",
1636                        ),
1637                    );
1638                }
1639            }
1640            // v0.106 (slice 3b-iii): an `on message`/`on close` recovers its
1641            // non-frame (route) parameters **positionally** from the socket
1642            // attachment the `on open` accept wrote — so they must be a
1643            // type-compatible prefix of the `on open` parameters. A mismatch would
1644            // silently `as`-cast one route value to another's type at the dispatch.
1645            if let [open] = opens.as_slice() {
1646                let op = &open.params;
1647                let route_mismatch = |p: &Param, errors: &mut Vec<CompileError>| {
1648                    errors.push(
1649                        CompileError::new(
1650                            "bynk.ws.route_param_mismatch",
1651                            p.span,
1652                            format!(
1653                                "the route parameter `{}: {}` does not match the `on open` parameter at this position — `on message`/`on close` route values are recovered positionally from the connection, so they must be a type-compatible prefix of the `on open` parameters",
1654                                p.name.name,
1655                                ts_type_ref_display(&p.type_ref)
1656                            ),
1657                        )
1658                        .with_note(
1659                            "give the inbound/close handler the same leading parameters (name aside) as `on open`, in the same order",
1660                        ),
1661                    );
1662                };
1663                if let [message] = messages.as_slice() {
1664                    let mut idx = 0usize;
1665                    for p in &message.params {
1666                        if resolve_ty(&p.type_ref) == resolve_ty(in_type) {
1667                            continue; // the decoded frame, not a route value
1668                        }
1669                        if op
1670                            .get(idx)
1671                            .is_none_or(|o| resolve_ty(&p.type_ref) != resolve_ty(&o.type_ref))
1672                        {
1673                            route_mismatch(p, errors);
1674                        }
1675                        idx += 1;
1676                    }
1677                }
1678                if let [close] = closes.as_slice() {
1679                    for (i, p) in close.params.iter().enumerate() {
1680                        if op
1681                            .get(i)
1682                            .is_none_or(|o| resolve_ty(&p.type_ref) != resolve_ty(&o.type_ref))
1683                        {
1684                            route_mismatch(p, errors);
1685                        }
1686                    }
1687                }
1688            }
1689            // #3046: the principal is established once, by `on open`'s `by`, and
1690            // carried for the connection's life (the Workers socket attachment).
1691            // `on message`/`on close` read it rather than re-verifying per frame, so
1692            // their `by` must name the same kind of principal: the same single actor
1693            // or the same actor-sum members. Binder names may differ, and a sum's
1694            // member order is irrelevant (the order only matters to open's
1695            // first-wins resolution). A checker rule, not a Workers-only one: the
1696            // contract is the language's, whatever a target does with the principal.
1697            if let [open] = opens.as_slice() {
1698                let actors_of = |h: &Handler| -> Option<std::collections::BTreeSet<String>> {
1699                    h.by_clause
1700                        .as_ref()
1701                        .map(|by| by.actors.iter().map(|a| a.name.clone()).collect())
1702                };
1703                let render = |h: &Handler| -> String {
1704                    match &h.by_clause {
1705                        Some(by) => by
1706                            .actors
1707                            .iter()
1708                            .map(|a| a.name.as_str())
1709                            .collect::<Vec<_>>()
1710                            .join(" | "),
1711                        None => "no `by` clause".to_string(),
1712                    }
1713                };
1714                let open_actors = actors_of(open);
1715                for h in messages.iter().chain(closes.iter()) {
1716                    if actors_of(h) != open_actors {
1717                        let which = if matches!(h.kind, HandlerKind::Message) {
1718                            "on message"
1719                        } else {
1720                            "on close"
1721                        };
1722                        errors.push(
1723                            CompileError::new(
1724                                "bynk.ws.lifecycle_by_mismatch",
1725                                h.by_clause.as_ref().map_or(h.span, |by| by.span),
1726                                format!(
1727                                    "the `{which}` handler of `{}` is `by` {}, but `on open` is `by` {} — a connection's principal is established once, at `on open`, so the lifecycle handlers must name the same actor(s)",
1728                                    service.name.name,
1729                                    render(h),
1730                                    render(open),
1731                                ),
1732                            )
1733                            .with_note(
1734                                "give `on message`/`on close` the same `by` actor (or the same actor-sum members) as `on open`; the binder name may differ. The principal is carried from `on open` for the connection's life, never re-verified per frame",
1735                            ),
1736                        );
1737                    }
1738                }
1739            }
1740            // v0.104 (D2): on Workers the upgrade is routed to the Durable Object
1741            // that hosts the connection — the agent the `on open` transfers it to.
1742            // That target must be statically resolvable: exactly one top-level
1743            // transfer (`Agent(key).method(…, connection)`).
1744            let local_agents: std::collections::HashSet<String> =
1745                table.agents.keys().cloned().collect();
1746            for open in &opens {
1747                // v0.104 (slice 3b): an `on open` cannot `given` capabilities — on
1748                // Workers it runs inside the connection-hosting Durable Object, which
1749                // has no composition root to supply them (the capabilities belong on
1750                // the agent handler the connection transfers to).
1751                if !open.given.is_empty() {
1752                    errors.push(
1753                        CompileError::new(
1754                            "bynk.ws.open_given_unsupported",
1755                            open.span,
1756                            "a WebSocket `on open` handler cannot declare `given` capabilities — on Workers it runs inside the connection-hosting Durable Object, which has no composition root to supply them",
1757                        )
1758                        .with_note(
1759                            "move capability use into the agent handler the connection transfers to (it carries its own `given`)",
1760                        ),
1761                    );
1762                }
1763                use crate::websocket::{WsOpenShape, analyse_open_shape};
1764                match analyse_open_shape(&open.body, &local_agents) {
1765                    WsOpenShape::One(_) => {}
1766                    WsOpenShape::None => errors.push(
1767                        CompileError::new(
1768                            "bynk.ws.open_transfer_shape",
1769                            open.span,
1770                            "a WebSocket `on open` handler must transfer its `connection` into exactly one agent — e.g. `Room(roomId).join(…, connection)` — so the upgrade can be routed to the hosting Durable Object",
1771                        )
1772                        .with_note(
1773                            "transfer the connection to an agent unconditionally (not inside an `if`/`match`); key it by a handler parameter, a `const` or a literal so the upgrade can be routed",
1774                        ),
1775                    ),
1776                    WsOpenShape::Multiple => errors.push(CompileError::new(
1777                        "bynk.ws.open_transfer_shape",
1778                        open.span,
1779                        "a WebSocket `on open` handler transfers its `connection` into more than one agent — the upgrade has no single Durable Object to route to",
1780                    )),
1781                }
1782            }
1783        }
1784        // #1781: a `from Events` service has exactly one `on event` handler.
1785        // Two were emitted as one object with a duplicate `event` key, which
1786        // `tsc --strict` rejects and which ran only the last in the bundle.
1787        if matches!(service.protocol, ServiceProtocol::Events { .. }) {
1788            let mut events = service
1789                .handlers
1790                .iter()
1791                .filter(|h| h.kind == HandlerKind::Event);
1792            if let (Some(first), Some(second)) = (events.next(), events.next()) {
1793                errors.push(
1794                    CompileError::new(
1795                        "bynk.event.duplicate_handler",
1796                        second.span,
1797                        format!(
1798                            "the `from Events` service `{}` has more than one `on event` handler — it needs exactly one",
1799                            service.name.name
1800                        ),
1801                    )
1802                    .with_label(first.span, "the service's `on event` handler")
1803                    .with_note(
1804                        "to react to one event in two ways, declare two services: each subscriber is delivered to independently",
1805                    ),
1806                );
1807            }
1808        }
1809        for handler in &service.handlers {
1810            let matches_protocol = matches!(
1811                (&service.protocol, &handler.kind),
1812                (ServiceProtocol::Call, HandlerKind::Call)
1813                    | (ServiceProtocol::Http, HandlerKind::Http { .. })
1814                    | (ServiceProtocol::Http, HandlerKind::Rejected)
1815                    | (ServiceProtocol::Cron, HandlerKind::Cron { .. })
1816                    | (ServiceProtocol::Queue { .. }, HandlerKind::Message)
1817                    | (ServiceProtocol::Email { .. }, HandlerKind::Message)
1818                    // v0.103/v0.106: a `from websocket` admits `on open` (the
1819                    // upgrade), and the inbound/close lifecycle `on message`/`on
1820                    // close` (slice 3b-iii).
1821                    | (
1822                        ServiceProtocol::WebSocket { .. },
1823                        HandlerKind::Open | HandlerKind::Message | HandlerKind::Close
1824                    )
1825                    // Events (#936): `from Events(E)` admits exactly `on event(e: E)`.
1826                    | (ServiceProtocol::Events { .. }, HandlerKind::Event)
1827            );
1828            if matches_protocol {
1829                // Events track, slice 1 (spine #936): a latent slice-0 gap —
1830                // nothing previously checked that `on event(e: E)`'s declared
1831                // parameter type agrees with the header's `from Events(E)`.
1832                // Harmless while no code depended on it; load-bearing now
1833                // that a subscription pattern (checked against the header's
1834                // `E`) assumes the body sees `e` at that same type. Runs
1835                // whether or not a pattern is present.
1836                if let ServiceProtocol::Events { event_type, .. } = &service.protocol
1837                    && handler.kind == HandlerKind::Event
1838                {
1839                    // #1781: emission is fire-and-forget, so a subscriber's
1840                    // result has nowhere to go; it returns `Effect[()]`. A
1841                    // non-`Effect` return is `bynk.service.return_not_effect`'s.
1842                    if let TypeRef::Effect(inner, _) = &handler.return_type
1843                        && !matches!(inner.as_ref(), TypeRef::Unit(_))
1844                    {
1845                        errors.push(
1846                            CompileError::new(
1847                                "bynk.event.return_not_effect_unit",
1848                                handler.return_type.span(),
1849                                format!(
1850                                    "an `on event` handler must return `Effect[()]`, but got `{}`",
1851                                    ts_type_ref_display(&handler.return_type)
1852                                ),
1853                            )
1854                            .with_note(
1855                                "emission is fire-and-forget: nothing receives a subscriber's result",
1856                            ),
1857                        );
1858                    }
1859                    if let Some(param) = handler.params.first() {
1860                        let header_name = type_ref_named(event_type);
1861                        let param_name = type_ref_named(&param.type_ref);
1862                        if header_name.is_none() || header_name != param_name {
1863                            errors.push(
1864                                CompileError::new(
1865                                    "bynk.event.handler_param_type_mismatch",
1866                                    param.type_ref.span(),
1867                                    format!(
1868                                        "this handler's parameter type does not match the header's event type `{}`",
1869                                        type_ref_to_display(event_type)
1870                                    ),
1871                                )
1872                                .with_note(
1873                                    "an `on event(e: E)` handler's parameter must be the same event type its `from Events(E)` header names",
1874                                ),
1875                            );
1876                        }
1877                    }
1878                    // Events track, slice 2 (spine #936): the arity/type
1879                    // check for the optional `env: EventEnvelope` second
1880                    // parameter — a latent gap independent of whether this
1881                    // slice's envelope machinery is ever used. Before this,
1882                    // `on event(e: E, extra: Whatever)` parsed and passed
1883                    // every existing check (the type-mismatch check above
1884                    // only ever inspected `params.first()`), then failed as
1885                    // a raw `tsc` argument-count error at the generated
1886                    // call site rather than a bynk diagnostic. A malformed
1887                    // *first* parameter is caught above already
1888                    // (`handler_param_type_mismatch` fires when position 0
1889                    // isn't the header's event type, including when it's
1890                    // `EventEnvelope` written in the wrong slot) — this
1891                    // check only adds the arity bound and the second
1892                    // parameter's required type.
1893                    match handler.params.len() {
1894                        0 => errors.push(
1895                            CompileError::new(
1896                                "bynk.event.bad_params",
1897                                handler.span,
1898                                "`on event` handlers take at least one parameter (the event payload)",
1899                            )
1900                            .with_note("add the payload parameter — e.g. `on event(e: E)`"),
1901                        ),
1902                        1 => {}
1903                        2 => {
1904                            let env_param = &handler.params[1];
1905                            if type_ref_named(&env_param.type_ref) != Some("EventEnvelope") {
1906                                errors.push(
1907                                    CompileError::new(
1908                                        "bynk.event.bad_params",
1909                                        env_param.type_ref.span(),
1910                                        "an `on event` handler's second parameter must be `EventEnvelope`",
1911                                    )
1912                                    .with_note(
1913                                        "the payload comes first; `EventEnvelope` carries runtime metadata about the emission (eventId, publisherId, emittedAt, schemaVersion)",
1914                                    ),
1915                                );
1916                            }
1917                        }
1918                        n => errors.push(CompileError::new(
1919                            "bynk.event.bad_params",
1920                            handler.params[2].span,
1921                            format!(
1922                                "`on event` handlers take at most two parameters (the event payload and, optionally, `EventEnvelope`), got {n}"
1923                            ),
1924                        )),
1925                    }
1926                }
1927                continue;
1928            }
1929            match &service.protocol {
1930                ServiceProtocol::Call => {
1931                    let suggested = match &handler.kind {
1932                        HandlerKind::Http { .. } | HandlerKind::Rejected => "from http",
1933                        HandlerKind::Cron { .. } => "from cron",
1934                        HandlerKind::Message => "from queue(\"…\")",
1935                        HandlerKind::Open | HandlerKind::Close => "from websocket(in: …, out: …)",
1936                        HandlerKind::Event => "from Events(EventType)",
1937                        HandlerKind::Call => continue,
1938                    };
1939                    errors.push(
1940                        CompileError::new(
1941                            "bynk.service.missing_from",
1942                            handler.span,
1943                            format!(
1944                                "this handler needs a protocol on the service header — add `{suggested}` to `service {}`",
1945                                service.name.name,
1946                            ),
1947                        )
1948                        .with_note("a service with no `from` clause admits only `on call` handlers"),
1949                    );
1950                }
1951                wire => {
1952                    errors.push(
1953                        CompileError::new(
1954                            "bynk.service.mixed_protocols",
1955                            handler.span,
1956                            format!(
1957                                "a `{}` service admits only its own handler form; this handler does not match",
1958                                protocol_label(wire),
1959                            ),
1960                        )
1961                        .with_note(
1962                            "a service is one protocol adapter — split differing handlers into separate services",
1963                        ),
1964                    );
1965                }
1966            }
1967        }
1968    }
1969}
1970
1971fn protocol_label(p: &ServiceProtocol) -> &'static str {
1972    match p {
1973        ServiceProtocol::Call => "call",
1974        ServiceProtocol::Http => "from http",
1975        ServiceProtocol::Cron => "from cron",
1976        ServiceProtocol::Queue { .. } => "from queue",
1977        ServiceProtocol::WebSocket { .. } => "from websocket",
1978        ServiceProtocol::Events { .. } => "from Events",
1979        ServiceProtocol::Email { .. } => "from email",
1980    }
1981}
1982
1983/// The bare name of a `TypeRef::Named` reference, or `None` for anything
1984/// else — an event type is always a plain named record, so this is enough
1985/// to compare a `from Events(E)` header against an `on event(e: T)`
1986/// handler's declared parameter type (Events track slice 1, spine #936).
1987fn type_ref_named(t: &TypeRef) -> Option<&str> {
1988    match t {
1989        TypeRef::Named(id) => Some(id.name.as_str()),
1990        _ => None,
1991    }
1992}
1993
1994/// Render a type-ref in the same form the user wrote it, for diagnostics.
1995///
1996/// P4.1 (#1115): moved here from `bynk-emit/src/project/tests_emit.rs` — a
1997/// pure `TypeRef` renderer with no emission dependency, shared by this
1998/// module's own checks (`check_by_clause_contracts`, `check_service_decls`,
1999/// …) and by `bynk-emit`'s `tests_emit`/`project.rs`, which now call
2000/// `bynk_check::context_checks::ts_type_ref_display` instead of a local copy.
2001pub fn ts_type_ref_display(r: &TypeRef) -> String {
2002    match r {
2003        TypeRef::Base(b, _) => b.name().to_string(),
2004        TypeRef::Named(id) => crate::symbols::display_type_name(&id.name).to_string(),
2005        TypeRef::Result(t, e, _) => format!(
2006            "Result[{}, {}]",
2007            ts_type_ref_display(t),
2008            ts_type_ref_display(e)
2009        ),
2010        TypeRef::Option(t, _) => format!("Option[{}]", ts_type_ref_display(t)),
2011        TypeRef::Effect(t, _) => format!("Effect[{}]", ts_type_ref_display(t)),
2012        TypeRef::HttpResult(t, _) => format!("HttpResult[{}]", ts_type_ref_display(t)),
2013        TypeRef::QueueResult(_) => "QueueResult".to_string(),
2014        TypeRef::Asset(_) => "Asset".to_string(),
2015        TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
2016        TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
2017        TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
2018        TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
2019        TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
2020        TypeRef::List(t, _) => format!("List[{}]", ts_type_ref_display(t)),
2021        TypeRef::Set(t, _) => format!("Set[{}]", ts_type_ref_display(t)),
2022        TypeRef::Query(t, _) => format!("Query[{}]", ts_type_ref_display(t)),
2023        TypeRef::Stream(t, _) => format!("Stream[{}]", ts_type_ref_display(t)),
2024        TypeRef::Connection(t, _) => format!("Connection[{}]", ts_type_ref_display(t)),
2025        TypeRef::History(t, _) => format!("History[{}]", ts_type_ref_display(t)),
2026        TypeRef::Map(k, v, _) => format!(
2027            "Map[{}, {}]",
2028            ts_type_ref_display(k),
2029            ts_type_ref_display(v)
2030        ),
2031        TypeRef::ValidationError(_) => "ValidationError".to_string(),
2032        TypeRef::DecodeError(_) => "DecodeError".to_string(),
2033        TypeRef::Unit(_) => "()".to_string(),
2034        // v0.157 (ADR 0183): render a generic-type application as written.
2035        TypeRef::App { name, args, .. } => format!(
2036            "{}[{}]",
2037            name.name,
2038            args.iter()
2039                .map(ts_type_ref_display)
2040                .collect::<Vec<_>>()
2041                .join(", ")
2042        ),
2043        TypeRef::Fn(params, ret, _) => {
2044            let lhs = match params.len() {
2045                0 => "()".to_string(),
2046                1 if !matches!(params[0], TypeRef::Fn(..)) => ts_type_ref_display(&params[0]),
2047                _ => format!(
2048                    "({})",
2049                    params
2050                        .iter()
2051                        .map(ts_type_ref_display)
2052                        .collect::<Vec<_>>()
2053                        .join(", ")
2054                ),
2055            };
2056            format!("{lhs} -> {}", ts_type_ref_display(ret))
2057        }
2058    }
2059}
2060
2061/// A short bynk-source-level rendering of a type reference for a diagnostic
2062/// message — not the TS-facing `ts_type_ref` family, which renders the
2063/// erased/emitted shape rather than what the author wrote.
2064pub fn type_ref_to_display(t: &TypeRef) -> String {
2065    match t {
2066        TypeRef::Named(id) => crate::symbols::display_type_name(&id.name).to_string(),
2067        TypeRef::Base(b, _) => b.name().to_string(),
2068        other => format!("{other:?}"),
2069    }
2070}
2071
2072/// v0.45: actor-contract well-formedness and the handler `by`-clause checks.
2073///
2074/// Two passes: (1) each `actor` declaration is well-formed — the refinement
2075/// form's predicate is restricted to the closed actor-claim catalogue over a
2076/// `Bearer` base, the scheme is admitted, and a declared identity is a
2077/// context-ownable (sealed) type; (2) each service handler either
2078/// names an admissible actor on `by` or inherits the protocol default — and
2079/// HTTP requires an explicit `by`.
2080/// Validate one `by` clause's actor contracts against a protocol (v0.155,
2081/// factored so both a handler's own clause and a service-level default are
2082/// checked by the same logic). `params` is the enclosing handler's parameters —
2083/// `Some` for a real handler, `None` for a service-level default validated in
2084/// isolation (a default has no handler body, so the two body-shaped checks —
2085/// binder/parameter collision and `Signature`-requires-`body` — are skipped for
2086/// it and re-run per handler when the default is inherited).
2087fn check_by_clause_contracts(
2088    by: &bynk_syntax::ast::ByClause,
2089    params: Option<&[bynk_syntax::ast::Param]>,
2090    protocol: &ServiceProtocol,
2091    table: &UnitTable,
2092    refs: &mut RefSink,
2093    errors: &mut Vec<CompileError>,
2094) {
2095    use crate::actors::{self, Scheme};
2096
2097    // A named binder introduces a new binding; it must not collide with a handler
2098    // parameter of the same name (which it would otherwise silently shadow in the
2099    // body scope). The binder-less form captures nothing, so it can't collide.
2100    // Only meaningful for a real handler (a default is validated without params).
2101    if let (Some(params), Some(binder)) = (params, &by.binder)
2102        && params.iter().any(|p| p.name.name == binder.name)
2103    {
2104        errors.push(
2105            CompileError::new(
2106                "bynk.actor.binder_shadows_param",
2107                binder.span,
2108                format!(
2109                    "the actor binder `{}` collides with a handler parameter of the same name",
2110                    binder.name,
2111                ),
2112            )
2113            .with_note("rename the `by` binder or the parameter"),
2114        );
2115    }
2116    // v0.52: a multi-actor sum (`by who: A | B`) must bind the resolved actor —
2117    // the body learns *which* peer verified by matching on the binder.
2118    if by.is_sum() && by.binder.is_none() {
2119        errors.push(
2120            CompileError::new(
2121                "bynk.actor.sum_requires_binder",
2122                by.span,
2123                "a multi-actor `by` clause must bind the resolved actor",
2124            )
2125            .with_note("write `by who: A | B (…)` and `match who { … }` in the body"),
2126        );
2127    }
2128    // Resolve each member to its contract: a local declaration *or* a prelude
2129    // actor. A local declaration that exists but is malformed (its scheme already
2130    // errored at the decl) does NOT fall through to a prelude actor of the same
2131    // name — only an unresolved name is. `members` keeps the resolved peers in
2132    // declared order for the reachability check below.
2133    let mut members: Vec<(&bynk_syntax::ast::Ident, actors::Contract)> = Vec::new();
2134    for actor_ref in &by.actors {
2135        let local = table.actors.get(&actor_ref.name);
2136        // A refinement actor (`actor A = B where …`) is never a peer: every `A`
2137        // is a `B`, so the arm is dead (Q3/Q4).
2138        if by.is_sum()
2139            && local.is_some_and(|a| a.refinement.is_some() && !is_caller_refinement(a, table))
2140        {
2141            errors.push(
2142                CompileError::new(
2143                    "bynk.actor.refinement_in_sum",
2144                    actor_ref.span,
2145                    format!(
2146                        "the refinement actor `{}` cannot be a peer in a multi-actor sum",
2147                        actor_ref.name
2148                    ),
2149                )
2150                .with_note(
2151                    "a refinement narrows a base actor — match it inside the \
2152                     resolved arm, not as a sum member",
2153                ),
2154            );
2155            continue;
2156        }
2157        let contract = if let Some(a) = local {
2158            refs.record(actor_ref.span, SymbolKind::Actor, &actor_ref.name);
2159            // v0.53: a refinement actor's contract is its base's scheme
2160            // (refinement elimination — an `Admin` is-a `User`); the invariant
2161            // rides the seam, not the scheme. A malformed refinement already
2162            // errored at its decl (pass 1).
2163            let scheme_actor = match &a.refinement {
2164                Some(r) => table.actors.get(&r.base.name),
2165                None => Some(a),
2166            };
2167            if is_caller_refinement(a, table) {
2168                // #3890: a refinement over `Caller` inherits its scheme and identity.
2169                actors::prelude_actor("Caller")
2170            } else {
2171                scheme_actor
2172                    .and_then(|sa| sa.auth.as_ref())
2173                    .and_then(|au| Scheme::from_name(&au.name))
2174                    .filter(|s| s.admitted())
2175                    .map(|scheme| actors::Contract {
2176                        scheme,
2177                        identity: actors::Identity::Unit,
2178                    })
2179            }
2180        } else {
2181            actors::prelude_actor(&actor_ref.name)
2182        };
2183        let Some(contract) = contract else {
2184            if local.is_none() {
2185                errors.push(
2186                    CompileError::new(
2187                        "bynk.actor.unknown_actor",
2188                        actor_ref.span,
2189                        format!("unknown actor `{}`", actor_ref.name),
2190                    )
2191                    .with_note(
2192                        "name a declared `actor` or a prelude actor \
2193                         (`Visitor`, `Scheduler`, `Producer`, `Sender`, `Caller`)",
2194                    ),
2195                );
2196            }
2197            continue;
2198        };
2199        if !actors::scheme_admissible(protocol, contract.scheme) {
2200            errors.push(
2201                CompileError::new(
2202                    "bynk.actor.scheme_not_admissible",
2203                    by.span,
2204                    format!(
2205                        "a `{}` actor is not admissible on a `{}` handler",
2206                        contract.scheme.as_str(),
2207                        protocol_label(protocol),
2208                    ),
2209                )
2210                .with_note(match protocol {
2211                    // I3 (#1971): a foreign caller calls a service, and only
2212                    // by `call`.
2213                    _ if contract.scheme == Scheme::Foreign => {
2214                        "a `Foreign` actor is admitted only on an `on call` handler"
2215                    }
2216                    ServiceProtocol::Http => {
2217                        "public HTTP routes take an anonymous actor — write `by v: Visitor`"
2218                    }
2219                    _ => "internal protocols (call/cron/queue) take an `Internal` actor",
2220                }),
2221            );
2222        }
2223        // v0.54: the `Caller` prelude actor yields a `CallerId` (the calling
2224        // context's name), a cross-context `on call` concept — it is admissible
2225        // only on the `Call` protocol, even though its `Internal` scheme is
2226        // otherwise valid on cron/queue (those take `Scheduler`/`Producer`).
2227        let is_caller = (!table.actors.contains_key(&actor_ref.name)
2228            && actors::prelude_actor(&actor_ref.name).map(|c| c.identity)
2229                == Some(actors::Identity::CallerId))
2230            || local.is_some_and(|a| is_caller_refinement(a, table));
2231        if is_caller && !matches!(protocol, ServiceProtocol::Call) {
2232            errors.push(
2233                CompileError::new(
2234                    "bynk.actor.scheme_not_admissible",
2235                    by.span,
2236                    format!(
2237                        "the `Caller` actor is not admissible on a `{}` handler",
2238                        protocol_label(protocol),
2239                    ),
2240                )
2241                .with_note(
2242                    "`Caller` carries the calling context's identity — it is only \
2243                     admissible on `on call`; cron takes `Scheduler`, queue takes `Producer`",
2244                ),
2245            );
2246        }
2247        // v0.151: `Oidc` is single-actor only this slice — a multi-actor sum owns
2248        // the whole boundary and reads the body once, a shape the OIDC seam (JWKS
2249        // fetch + async key import) does not yet fit. Reject it as a peer.
2250        if by.is_sum() && contract.scheme == actors::Scheme::Oidc {
2251            errors.push(
2252                CompileError::new(
2253                    "bynk.actor.oidc_not_in_sum",
2254                    actor_ref.span,
2255                    format!(
2256                        "the `Oidc` actor `{}` cannot be a peer in a multi-actor sum",
2257                        actor_ref.name
2258                    ),
2259                )
2260                .with_note(
2261                    "OIDC is single-actor this slice — give the route a single \
2262                     `by user: <OidcActor>` clause",
2263                ),
2264            );
2265        }
2266        // #3386: `SignedCookie` is single-actor only in its first slice, as
2267        // `Oidc` was: the per-arm CSRF rule is the part that gets harder in a
2268        // sum, so a route guarded by one takes a single `by u: <Actor>`.
2269        if by.is_sum() && contract.scheme == actors::Scheme::SignedCookie {
2270            errors.push(
2271                CompileError::new(
2272                    "bynk.actor.signed_cookie_not_in_sum",
2273                    actor_ref.span,
2274                    format!(
2275                        "the `SignedCookie` actor `{}` cannot be a peer in a multi-actor sum",
2276                        actor_ref.name
2277                    ),
2278                )
2279                .with_note(
2280                    "a signed cookie is single-actor in this slice — give the route a single \
2281                     `by user: <SignedCookieActor>` clause",
2282                ),
2283            );
2284        }
2285        members.push((actor_ref, contract));
2286    }
2287    // v0.51: a Signature member verifies an HMAC over the body, so the handler
2288    // MUST take a `body` parameter (single or sum). Skipped for a service-level
2289    // default (no handler body); re-checked per handler when inherited.
2290    if let Some(params) = params
2291        && members
2292            .iter()
2293            .any(|(_, c)| c.scheme == actors::Scheme::Signature)
2294        && !params.iter().any(|p| p.name.name == "body")
2295    {
2296        errors.push(
2297            CompileError::new(
2298                "bynk.actor.signature_requires_body",
2299                by.span,
2300                "a `Signature` handler must take a `body` parameter (the signature is over the body)",
2301            )
2302            .with_note("add a `(body: T)` parameter to the handler"),
2303        );
2304    }
2305    // #3380: a `Signature` actor computes its HMAC over the whole body before the
2306    // handler runs, so the body cannot be a stream the handler reads afterwards.
2307    if let Some(params) = params
2308        && members
2309            .iter()
2310            .any(|(_, c)| c.scheme == actors::Scheme::Signature)
2311        && let Some(body) = params
2312            .iter()
2313            .find(|p| p.name.name == "body" && is_byte_stream(&p.type_ref))
2314    {
2315        errors.push(
2316            CompileError::new(
2317                "bynk.http.stream_body_signature",
2318                body.type_ref.span(),
2319                "a `Signature` route cannot take a streamed `body`",
2320            )
2321            .with_note(
2322                "the signature is an HMAC over the whole body, verified before the handler runs; take `body: Bytes` for a signed webhook, or sign the head (a header or the path) and verify the content out of band",
2323            ),
2324        );
2325    }
2326    // v0.52: sum reachability — a decidable, scheme-level check. No two peers
2327    // share a scheme (the second is unreachable); a `None` catch-all (`Visitor`)
2328    // accepts everyone, so it must come last. The compiler does not reason about
2329    // predicate-level disjointness — that is what keeps this decidable (Q4).
2330    if by.is_sum() {
2331        let mut seen: Vec<actors::Scheme> = Vec::new();
2332        let mut seen_catch_all = false;
2333        for (actor_ref, contract) in &members {
2334            if seen_catch_all {
2335                errors.push(
2336                    CompileError::new(
2337                        "bynk.actor.unreachable_sum_arm",
2338                        actor_ref.span,
2339                        format!(
2340                            "actor `{}` is unreachable — an earlier `None` peer accepts every caller",
2341                            actor_ref.name
2342                        ),
2343                    )
2344                    .with_note("a catch-all (`None`, e.g. `Visitor`) peer must come last"),
2345                );
2346                continue;
2347            }
2348            if contract.scheme == actors::Scheme::None {
2349                seen_catch_all = true;
2350            } else if contract.scheme == actors::Scheme::Foreign {
2351                // I3 (#1971): foreign peers are told apart by name, each
2352                // verified under its own secret, so several can share a sum.
2353                // That every foreign secret is the context's only use of its
2354                // name is checked once per context (`check_actor_contracts`).
2355            } else if seen.contains(&contract.scheme) {
2356                errors.push(
2357                    CompileError::new(
2358                        "bynk.actor.duplicate_sum_scheme",
2359                        actor_ref.span,
2360                        format!(
2361                            "actor `{}` repeats the `{}` scheme of an earlier peer",
2362                            actor_ref.name,
2363                            contract.scheme.as_str()
2364                        ),
2365                    )
2366                    .with_note(
2367                        "peers in a sum are distinguished by scheme — two same-scheme \
2368                         peers can't both be reached",
2369                    ),
2370                );
2371            } else {
2372                seen.push(contract.scheme);
2373            }
2374        }
2375    }
2376}
2377
2378/// #3386: the config value kinds a scheme admits. The config grammar also reads a duration
2379/// (`12.hours`) and a bare identifier (`Lax`), but only `SignedCookie` takes either; for every other
2380/// scheme they are refused here, because their seams read a string or an integer and would otherwise
2381/// drop the value quietly (a `Signature` `tolerance = 5.minutes` reads as no tolerance at all, which
2382/// would turn the replay window off). A repeated `SignedCookie` key is refused too, since the first
2383/// would win quietly in a scheme that guards a session.
2384fn check_scheme_arg_kinds(actor: &ActorDecl, errors: &mut Vec<CompileError>) {
2385    use crate::actors::Scheme;
2386    let signed_cookie =
2387        actor.auth.as_ref().and_then(|a| Scheme::from_name(&a.name)) == Some(Scheme::SignedCookie);
2388    let mut seen: HashSet<&str> = HashSet::new();
2389    for arg in &actor.auth_config {
2390        if signed_cookie && !seen.insert(arg.key.name.as_str()) {
2391            errors.push(
2392                CompileError::new(
2393                    "bynk.actor.signed_cookie_duplicate_key",
2394                    arg.key.span,
2395                    format!(
2396                        "the scheme config key `{}` is given more than once",
2397                        arg.key.name
2398                    ),
2399                )
2400                .with_note(
2401                    "only the first value would be read, so the second is refused: keep one",
2402                ),
2403            );
2404        }
2405        if !signed_cookie
2406            && matches!(
2407                arg.value,
2408                bynk_syntax::ast::SchemeArgValue::Duration { .. }
2409                    | bynk_syntax::ast::SchemeArgValue::Ident(_)
2410            )
2411        {
2412            errors.push(
2413                CompileError::new(
2414                    "bynk.actor.scheme_arg_kind",
2415                    arg.span,
2416                    format!(
2417                        "the scheme config value for `{}` must be a string or an integer",
2418                        arg.key.name
2419                    ),
2420                )
2421                .with_note(
2422                    "a duration or a bare name is accepted only by `SignedCookie`; give a whole number (a `Signature` `tolerance` is in seconds: `tolerance = 300`) or a quoted string",
2423                ),
2424            );
2425        }
2426    }
2427}
2428
2429/// The keys a `SignedCookie` actor's config admits (#3386).
2430const SIGNED_COOKIE_KEYS: &[&str] = &["cookie", "secret", "previous", "ttl", "sameSite"];
2431
2432/// A `ttl` above this many seconds draws `signed_cookie_ttl_long` (30 days).
2433const SIGNED_COOKIE_LONG_TTL_SECS: i64 = 30 * 24 * 60 * 60;
2434
2435/// Whether `name` is an RFC 6265 `token` (a legal cookie name).
2436fn is_cookie_token(name: &str) -> bool {
2437    !name.is_empty()
2438        && name
2439            .bytes()
2440            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
2441}
2442
2443/// #3386: validate one `SignedCookie` actor declaration: the closed key set, a
2444/// `secret` and a `ttl`, a legal and preferably `__Host-` cookie name, a
2445/// distinct secret, and a string-constructible identity minted from `sub`.
2446fn check_signed_cookie_actor(
2447    actor: &ActorDecl,
2448    auth: &Ident,
2449    table: &UnitTable,
2450    types: &HashMap<String, Arc<TypeDecl>>,
2451    errors: &mut Vec<CompileError>,
2452) {
2453    let bad_arg = |span: Span, key: &str, want: &str, errors: &mut Vec<CompileError>| {
2454        errors.push(
2455            CompileError::new(
2456                "bynk.actor.signed_cookie_bad_arg",
2457                span,
2458                format!("a `SignedCookie` actor's `{key}` must be {want}"),
2459            )
2460            .with_note(
2461                "write `auth = SignedCookie(secret = \"<ENV_NAME>\", ttl = 12.hours)`; the optional keys are `cookie`, `previous` and `sameSite`",
2462            ),
2463        );
2464    };
2465    for arg in &actor.auth_config {
2466        if !SIGNED_COOKIE_KEYS.contains(&arg.key.name.as_str()) {
2467            errors.push(
2468                CompileError::new(
2469                    "bynk.actor.signed_cookie_unknown_key",
2470                    arg.key.span,
2471                    format!("unknown `SignedCookie` config key `{}`", arg.key.name),
2472                )
2473                .with_note("the keys are `secret`, `ttl`, `cookie`, `previous` and `sameSite`"),
2474            );
2475        }
2476    }
2477    // The signing key: named, a string, and not another actor's secret.
2478    match actor.scheme_arg("secret") {
2479        None => errors.push(
2480            CompileError::new(
2481                "bynk.actor.signed_cookie_missing_secret",
2482                auth.span,
2483                "a `SignedCookie` actor must name its signing secret",
2484            )
2485            .with_note(
2486                "write `auth = SignedCookie(secret = \"<ENV_NAME>\", ttl = 12.hours)` — the env var holding the signing key (`bynk deploy` mints it when unset)",
2487            ),
2488        ),
2489        Some(arg) if arg.value.as_str().is_none() => {
2490            bad_arg(arg.span, "secret", "an env binding name, as a string", errors);
2491        }
2492        Some(_) => {}
2493    }
2494    let previous = actor.scheme_arg("previous");
2495    if let Some(arg) = previous
2496        && arg.value.as_str().is_none()
2497    {
2498        bad_arg(
2499            arg.span,
2500            "previous",
2501            "an env binding name, as a string",
2502            errors,
2503        );
2504    }
2505    // Distinct keys: this actor's `secret` and `previous` may not be another
2506    // actor's secret (or previous), nor each other, or one scheme's credential
2507    // could be replayed against another.
2508    let mine: Vec<(&str, &str, Span)> = ["secret", "previous"]
2509        .iter()
2510        .filter_map(|k| {
2511            let a = actor.scheme_arg(k)?;
2512            Some((*k, a.value.as_str()?, a.span))
2513        })
2514        .collect();
2515    if let [(_, a, _), (_, b, span)] = mine.as_slice()
2516        && a == b
2517    {
2518        errors.push(
2519            CompileError::new(
2520                "bynk.actor.signed_cookie_secret_shared",
2521                *span,
2522                "a `SignedCookie` actor's `previous` key is the same variable as its `secret`",
2523            )
2524            .with_note("`previous` is the key being rotated out — give it its own variable"),
2525        );
2526    }
2527    for other in table.actors.values() {
2528        if other.name.name == actor.name.name {
2529            continue;
2530        }
2531        let other_names: Vec<&str> = ["secret", "previous"]
2532            .iter()
2533            .filter_map(|k| other.scheme_arg(k)?.value.as_str())
2534            .collect();
2535        for (key, value, span) in &mine {
2536            if other_names.contains(value) {
2537                errors.push(
2538                    CompileError::new(
2539                        "bynk.actor.signed_cookie_secret_shared",
2540                        *span,
2541                        format!(
2542                            "the `{key}` `{value}` of `SignedCookie` actor `{}` is also used by actor `{}`",
2543                            actor.name.name, other.name.name
2544                        ),
2545                    )
2546                    .with_note(
2547                        "a session key signs one actor's cookies only — sharing it would let a credential for one actor be replayed against another; give each its own variable",
2548                    ),
2549                );
2550            }
2551        }
2552    }
2553    // Expiry: required, a positive whole number of seconds, bounded by a warning.
2554    match actor.scheme_arg("ttl") {
2555        None => {
2556            let mut err = CompileError::new(
2557                "bynk.actor.signed_cookie_missing_ttl",
2558                auth.span,
2559                "a `SignedCookie` actor must declare a `ttl`",
2560            )
2561            .with_note(
2562                "an immortal session cookie is the failure to avoid — write `ttl = 12.hours`; a stateless cookie cannot be revoked before it expires, so keep it short",
2563            );
2564            // #3431: insert `ttl = 12.hours` after the last config entry. Adding
2565            // a key touches nothing else, but the lifetime is the author's
2566            // choice, so it is offered (`MaybeIncorrect`), never taken by
2567            // fix-all. No entry to anchor on (no config at all) ⇒ note only.
2568            if let Some(last) = actor.auth_config.last() {
2569                let at = Span::new_in(last.span.file, last.span.end, last.span.end);
2570                err = err.with_suggestion(
2571                    "add `ttl = 12.hours` (a stateless cookie cannot be revoked before it expires, so keep it short)",
2572                    vec![(at, ", ttl = 12.hours".to_string())],
2573                    Applicability::MaybeIncorrect,
2574                );
2575            }
2576            errors.push(err);
2577        }
2578        Some(arg) => match arg.value.as_duration_millis() {
2579            Some(ms) if ms > 0 && ms % 1000 == 0 => {
2580                if ms / 1000 > SIGNED_COOKIE_LONG_TTL_SECS {
2581                    errors.push(
2582                        CompileError::new(
2583                            "bynk.actor.signed_cookie_ttl_long",
2584                            arg.span,
2585                            "this `SignedCookie` `ttl` is longer than 30 days",
2586                        )
2587                        .with_note(
2588                            "a stateless signed cookie cannot be revoked before it expires: a copy a user already took keeps working for the whole `ttl`. Shorten it, or use a server-side session (see `examples/sessions`) if you need to log out everywhere",
2589                        ),
2590                    );
2591                }
2592            }
2593            _ => errors.push(
2594                CompileError::new(
2595                    "bynk.actor.signed_cookie_bad_ttl",
2596                    arg.span,
2597                    "a `SignedCookie` `ttl` must be a positive whole number of seconds",
2598                )
2599                .with_note(
2600                    "write a `Duration` literal such as `ttl = 12.hours` or `ttl = 30.minutes`",
2601                ),
2602            ),
2603        },
2604    }
2605    // The cookie's name: a token, and `__Host-` unless the author chose otherwise.
2606    if let Some(arg) = actor.scheme_arg("cookie") {
2607        match arg.value.as_str() {
2608            None => bad_arg(arg.span, "cookie", "a cookie name, as a string", errors),
2609            Some(name) if !is_cookie_token(name) => errors.push(
2610                CompileError::new(
2611                    "bynk.actor.signed_cookie_bad_name",
2612                    arg.span,
2613                    format!("`{name}` is not a legal cookie name"),
2614                )
2615                .with_note(
2616                    "a cookie name is an RFC 6265 token: letters, digits and ``!#$%&'*+-.^_`|~``, no spaces, `=`, `;`, `,` or quotes",
2617                ),
2618            ),
2619            Some(name) if !name.to_ascii_lowercase().starts_with("__host-") => errors.push(
2620                CompileError::new(
2621                    "bynk.actor.signed_cookie_unprefixed",
2622                    arg.span,
2623                    format!("the session cookie `{name}` is not a `__Host-` cookie"),
2624                )
2625                .with_note(
2626                    "a `__Host-` name stops a sibling subdomain setting or overwriting the cookie; the default is `__Host-session`",
2627                ),
2628            ),
2629            Some(_) => {}
2630        }
2631    }
2632    if let Some(arg) = actor.scheme_arg("sameSite")
2633        && !matches!(
2634            arg.value.as_ident(),
2635            Some("Lax" | "Strict" | "Unrestricted")
2636        )
2637    {
2638        bad_arg(
2639            arg.span,
2640            "sameSite",
2641            "`Lax`, `Strict` or `Unrestricted`",
2642            errors,
2643        );
2644    }
2645    match &actor.identity {
2646        None => errors.push(
2647            CompileError::new(
2648                "bynk.actor.signed_cookie_identity_not_string_constructible",
2649                auth.span,
2650                "a `SignedCookie` actor must declare a string-constructible `identity`",
2651            )
2652            .with_note(
2653                "the verified identity is minted from the cookie's `sub` claim — declare `identity = T` where `T` is a refined or opaque `String`",
2654            ),
2655        ),
2656        Some(id) if !is_string_constructible(id, types) => errors.push(
2657            CompileError::new(
2658                "bynk.actor.signed_cookie_identity_not_string_constructible",
2659                id.span(),
2660                "a `SignedCookie` actor's identity must be string-constructible",
2661            )
2662            .with_note(
2663                "the identity is minted from the cookie's `sub` claim (a string) — use a refined or opaque `String` type",
2664            ),
2665        ),
2666        Some(_) => {}
2667    }
2668}
2669
2670/// #3386: route-level refusals for a handler guarded by a `SignedCookie` actor.
2671/// The signed value is consumed at the seam and never reaches handler code, so a
2672/// typed `cookies` record may not read the session cookie by name; and a shared
2673/// cache would serve one user's answer to another.
2674fn check_signed_cookie_route(
2675    handler: &Handler,
2676    table: &UnitTable,
2677    types: &HashMap<String, Arc<TypeDecl>>,
2678    errors: &mut Vec<CompileError>,
2679) {
2680    let Some(seam) = crate::actors::signed_cookie_seam_for(handler, &table.actors) else {
2681        return;
2682    };
2683    // A typed `cookies` field whose wire name (its own, or `@name`) is the session cookie.
2684    if let Some(p) = handler.params.iter().find(|p| p.name.name == "cookies")
2685        && let TypeRef::Named(rec) = &p.type_ref
2686        && let Some(TypeBody::Record(r)) = types.get(&rec.name).map(|d| &d.body)
2687    {
2688        for f in &r.fields {
2689            let wire = f.wire_name().unwrap_or_else(|| f.name.name.clone());
2690            if wire == seam.cookie {
2691                errors.push(
2692                    CompileError::new(
2693                        "bynk.actor.signed_cookie_read_directly",
2694                        f.span,
2695                        format!(
2696                            "the field `{}` reads the session cookie `{}` that the `SignedCookie` actor `{}` consumes",
2697                            f.name.name, seam.cookie, seam.actor
2698                        ),
2699                    )
2700                    .with_note(
2701                        "the signed value is verified at the boundary and never reaches the handler — read the identity from the `by` binder; the router also hides this cookie from a raw `RequestCookies` view",
2702                    ),
2703                );
2704            }
2705        }
2706    }
2707    for ann in handler
2708        .annotations
2709        .iter()
2710        .filter(|a| a.name.name == "cache")
2711    {
2712        let public = ann.args.iter().any(|a| {
2713            a.label.as_ref().is_some_and(|n| n.name == "scope")
2714                && matches!(&a.value.kind, ExprKind::Ident(id) if id.name == "public")
2715        });
2716        if public {
2717            errors.push(
2718                CompileError::new(
2719                    "bynk.actor.signed_cookie_public_cache",
2720                    ann.span,
2721                    "a `@cache(scope: public)` route is guarded by a `SignedCookie` actor, so a shared cache could replay one user's response to another",
2722                )
2723                .with_note("use `scope: private`, or drop `@cache`"),
2724            );
2725        }
2726    }
2727}
2728
2729/// #3890: whether an actor declaration refines the prelude `Caller` (no local
2730/// actor named `Caller` shadows it).
2731pub(crate) fn is_caller_refinement(actor: &bynk_syntax::ast::ActorDecl, table: &UnitTable) -> bool {
2732    actor
2733        .refinement
2734        .as_ref()
2735        .is_some_and(|r| r.base.name == "Caller" && !table.actors.contains_key("Caller"))
2736}
2737
2738/// A handler with no `by` clause: edge protocols (HTTP, WebSocket) have no safe
2739/// default actor; the internal protocols inherit one.
2740fn check_missing_by(handler: &Handler, protocol: &ServiceProtocol, errors: &mut Vec<CompileError>) {
2741    if crate::actors::default_actor(protocol).is_some() {
2742        return;
2743    }
2744    if matches!(protocol, ServiceProtocol::Call) {
2745        // Only a real `on call` handler: a stray kind in a call service has its own error.
2746        if handler.kind == HandlerKind::Call {
2747            errors.push(missing_by_on_call(handler));
2748        }
2749        return;
2750    }
2751    // v0.103 (D-A): a WebSocket upgrade authenticates at the edge before the
2752    // connection is accepted — `on open` must name its actor, no anonymous upgrade.
2753    let (msg, note) = match protocol {
2754        ServiceProtocol::WebSocket { .. } => (
2755            "a WebSocket `on open` handler must declare its actor with a `by` clause",
2756            "the upgrade authenticates at the edge before accepting the connection — name the actor (`by user: Participant`), there is no anonymous upgrade",
2757        ),
2758        _ => (
2759            "an HTTP handler must declare its actor with a `by` clause",
2760            "HTTP has no safe default actor — a public route writes `by v: Visitor`; an authenticated route names its actor",
2761        ),
2762    };
2763    errors.push(
2764        CompileError::new("bynk.actor.missing_by_on_http", handler.span, msg).with_note(note),
2765    );
2766}
2767
2768/// Where a handler's `given` clause sits: after its return type, and after its
2769/// own `by` clause when it writes one (`-> T by A given C`). A `by` inherited
2770/// from a service header lies before the handler and does not move the anchor.
2771fn given_anchor_after_by(handler: &Handler) -> Span {
2772    let ret = handler.return_type.span();
2773    match &handler.by_clause {
2774        Some(by) if by.span.start >= ret.end => by.span,
2775        _ => ret,
2776    }
2777}
2778
2779/// #3891: an `on call` handler states its actor, as an HTTP route does. The
2780/// fix-it inserts `by Caller` (the former silent default: any consuming
2781/// context) after the return type.
2782fn missing_by_on_call(handler: &Handler) -> CompileError {
2783    let at = handler.return_type.span().end;
2784    CompileError::new(
2785        "bynk.actor.missing_by_on_call",
2786        handler.span,
2787        "an `on call` handler must declare its actor with a `by` clause",
2788    )
2789    .with_note(
2790        "`by Caller` admits any context that consumes this one; a refinement or a `Foreign` actor narrows it. \
2791         Migrate a project with `bynk check --fix=bynk.actor.missing_by_on_call`",
2792    )
2793    .with_suggestion(
2794        "add `by Caller`",
2795        vec![(Span::new_in(handler.span.file, at, at), " by Caller".to_string())],
2796        Applicability::MachineApplicable,
2797    )
2798}
2799
2800/// Once per context, after every actor declaration is read: the checks on foreign callers' secrets.
2801fn check_foreign_secret_dupes(table: &UnitTable, errors: &mut Vec<CompileError>) {
2802    use crate::actors::Scheme;
2803    // I3 (#1971): a foreign caller's secret is the context's only use of that
2804    // name. The Worker's table of foreign callers maps every one of them to
2805    // its secret, and a caller is checked under the secret its claimed name
2806    // selects, so two foreign actors on one secret could each pass for the
2807    // other wherever either is admitted; and `bynk deploy` mints a foreign
2808    // secret, which would overwrite another actor's. In declaration order, so
2809    // the later one is reported.
2810    let mut by_position: Vec<&ActorDecl> = table.actors.values().collect();
2811    by_position.sort_by_key(|a| a.name.span.start);
2812    let mut secret_owner: HashMap<&str, (&str, bool)> = HashMap::new();
2813    for actor in by_position {
2814        let Some(arg) = actor.scheme_arg("secret") else {
2815            continue;
2816        };
2817        let Some(secret) = arg.value.as_str() else {
2818            continue;
2819        };
2820        let foreign = actor
2821            .auth
2822            .as_ref()
2823            .is_some_and(|au| Scheme::from_name(&au.name) == Some(Scheme::Foreign));
2824        match secret_owner.get(secret) {
2825            Some((other, other_foreign)) if foreign || *other_foreign => {
2826                errors.push(
2827                    CompileError::new(
2828                        "bynk.actor.foreign_duplicate_secret",
2829                        arg.span,
2830                        format!(
2831                            "actor `{}` uses the secret `{secret}` already named by actor `{other}`, and one of them is a foreign caller",
2832                            actor.name.name
2833                        ),
2834                    )
2835                    .with_note(
2836                        "a foreign caller is told apart by the secret its calls verify under, and \
2837                         `bynk deploy` mints it — give it a name no other actor uses",
2838                    ),
2839                );
2840            }
2841            Some(_) => {}
2842            None => {
2843                secret_owner.insert(secret, (&actor.name.name, foreign));
2844            }
2845        }
2846    }
2847}
2848
2849/// A refinement actor's declaration (`actor Admin = <Base> where <pred>`): over
2850/// the prelude `Caller` (#3890) the predicate is `IsContext(…)`; over a declared
2851/// `Bearer` actor (v0.53) it is the closed claim-predicate set.
2852fn check_refinement_actor(
2853    actor: &bynk_syntax::ast::ActorDecl,
2854    table: &UnitTable,
2855    refs: &mut RefSink,
2856    errors: &mut Vec<CompileError>,
2857) {
2858    use crate::actors::{self, Scheme};
2859    // v0.53: a refinement actor (`actor Admin = User where <pred>`) carries
2860    // an authorisation invariant. Its base MUST be a declared `Bearer` actor
2861    // (only Bearer carries claims to authorise against), and its `where`
2862    // predicate MUST be in the closed claim-predicate set.
2863    if let Some(r) = &actor.refinement
2864        && is_caller_refinement(actor, table)
2865    {
2866        // #3890: a refinement over the prelude `Caller` narrows which
2867        // contexts may call, by the closed `IsContext(…)` vocabulary.
2868        if let Err(span) = actors::parse_caller_predicate(&r.predicate) {
2869            errors.push(
2870                    CompileError::new(
2871                        "bynk.actor.refinement_predicate_unsupported",
2872                        span,
2873                        "a refinement over `Caller` must be `IsContext(<context>, …)`, composed with `&&`, `||`, `!`",
2874                    )
2875                    .with_note(
2876                        "the calling context is the only thing a `Caller` carries; claims such as \
2877                         `hasClaim` belong to a `Bearer` actor",
2878                    ),
2879                );
2880        }
2881        return;
2882    }
2883    if let Some(r) = &actor.refinement {
2884        let base = table.actors.get(&r.base.name);
2885        let base_is_bearer = base.is_some_and(|b| {
2886            b.refinement.is_none()
2887                && b.auth.as_ref().and_then(|a| Scheme::from_name(&a.name)) == Some(Scheme::Bearer)
2888        });
2889        if base_is_bearer {
2890            refs.record(r.base.span, SymbolKind::Actor, &r.base.name);
2891        } else {
2892            errors.push(
2893                CompileError::new(
2894                    "bynk.actor.refinement_base_unsupported",
2895                    r.base.span,
2896                    format!(
2897                        "the base actor `{}` of refinement `{}` must be a declared `Bearer` actor",
2898                        r.base.name, actor.name.name,
2899                    ),
2900                )
2901                .with_note(
2902                    "authorisation invariants test JWT claims, which only a `Bearer` actor \
2903                         carries — refine a `Bearer` actor, not `None`/`Internal`/`Signature`",
2904                ),
2905            );
2906        }
2907        if let Err(span) = actors::parse_claim_predicate(&r.predicate) {
2908            errors.push(
2909                    CompileError::new(
2910                        "bynk.actor.refinement_predicate_unsupported",
2911                        span,
2912                        "a refinement predicate must be `hasClaim(\"…\")` or `claimEquals(\"…\", \"…\")`, composed with `&&`, `||`, `!`",
2913                    )
2914                    .with_note(
2915                        "claims are untyped JSON, so the predicate vocabulary is a closed set this \
2916                         slice; a general typed-claims surface is a later slice (`IsContext(…)` \
2917                         belongs to a refinement over `Caller`)",
2918                    ),
2919                );
2920        }
2921    }
2922}
2923
2924fn check_actor_contracts(
2925    table: &UnitTable,
2926    resolved: &ResolvedCommons,
2927    refs: &mut RefSink,
2928    errors: &mut Vec<CompileError>,
2929) {
2930    use crate::actors::Scheme;
2931
2932    // Pass 1 — actor declaration well-formedness.
2933    for actor in table.actors.values() {
2934        refs.set_owner(&actor.name.name);
2935        if actor.refinement.is_some() {
2936            check_refinement_actor(actor, table, refs, errors);
2937            continue;
2938        }
2939        let Some(auth) = &actor.auth else {
2940            continue;
2941        };
2942        check_scheme_arg_kinds(actor, errors);
2943        match Scheme::from_name(&auth.name) {
2944            None => errors.push(
2945                CompileError::new(
2946                    "bynk.actor.unknown_scheme",
2947                    auth.span,
2948                    format!("unknown authentication scheme `{}`", auth.name),
2949                )
2950                .with_note(
2951                    "the authentication schemes are `None`, `Internal`, `Bearer`, `Signature`, `Oidc`, `Foreign`, and `SignedCookie`",
2952                ),
2953            ),
2954            // I3 (#1971): a foreign caller names the secret its calls verify
2955            // under; it carries no identity beyond the actor itself, and its
2956            // name must never read as a Bynk context's, which is what keeps
2957            // it apart from every `Caller` on the wire.
2958            Some(Scheme::Foreign) => {
2959                match actor.scheme_arg("secret") {
2960                    None => errors.push(
2961                        CompileError::new(
2962                            "bynk.actor.foreign_missing_secret",
2963                            auth.span,
2964                            "a `Foreign` actor must name the secret its calls are signed with",
2965                        )
2966                        .with_note("write `auth = Foreign(secret = \"<ENV_NAME>\")`"),
2967                    ),
2968                    Some(arg) if arg.value.as_str().is_none() => errors.push(
2969                        CompileError::new(
2970                            "bynk.actor.foreign_secret_not_string",
2971                            arg.span,
2972                            "a `Foreign` actor's secret must name an env binding, as a string",
2973                        )
2974                        .with_note("write `auth = Foreign(secret = \"<ENV_NAME>\")`"),
2975                    ),
2976                    Some(arg) => {
2977                        if arg.value.as_str().is_some_and(|v| {
2978                            v.starts_with(crate::wire_format::EDGE_FROM_PREFIX)
2979                                || v.starts_with(crate::wire_format::EDGE_TO_PREFIX)
2980                        }) {
2981                            errors.push(
2982                                CompileError::new(
2983                                    "bynk.actor.foreign_reserved_secret",
2984                                    arg.span,
2985                                    "a `Foreign` actor's secret may not use a `BYNK_CALL_` edge key's name",
2986                                )
2987                                .with_note(
2988                                    "those names are the keys `bynk deploy` mints between contexts — \
2989                                     pick another, such as `LEGACY_CALL_KEY`",
2990                                ),
2991                            );
2992                        }
2993                    }
2994                }
2995                if crate::wire_format::is_edge_name(&actor.name.name) {
2996                    errors.push(
2997                        CompileError::new(
2998                            "bynk.actor.foreign_name_is_context_name",
2999                            actor.name.span,
3000                            format!(
3001                                "foreign actor `{}` is named like a context",
3002                                actor.name.name
3003                            ),
3004                        )
3005                        .with_note(
3006                            "a foreign caller sends its actor's name as its caller, so it must \
3007                             not read as a context's name: start it with a capital letter",
3008                        ),
3009                    );
3010                }
3011                // I4 (#1970): a foreign caller signs under the key its Worker
3012                // holds as `BYNK_CALL_TO_<CONTEXT>`, named from this context's
3013                // name, so the name must be one a key can be derived from (the
3014                // domain `bynk deploy` refuses outside of, at a deploy rather
3015                // than here, for Bynk-to-Bynk edges).
3016                let context = resolved.commons.name.joined();
3017                if !crate::wire_format::is_edge_name(&context) {
3018                    errors.push(
3019                        CompileError::new(
3020                            "bynk.actor.foreign_context_name_unkeyable",
3021                            auth.span,
3022                            format!(
3023                                "context `{context}` cannot admit foreign caller `{}`: no call key can be named from the context's name",
3024                                actor.name.name
3025                            ),
3026                        )
3027                        .with_note(
3028                            "an edge key is named from the context's name, which must be lowercase \
3029                             letters and digits in dot-separated segments, each starting with a \
3030                             letter, with single underscores between runs (no `__`, no trailing `_`)",
3031                        ),
3032                    );
3033                }
3034                if let Some(id) = &actor.identity {
3035                    errors.push(
3036                        CompileError::new(
3037                            "bynk.actor.foreign_identity_unsupported",
3038                            id.span(),
3039                            "a `Foreign` actor does not support a declared `identity`",
3040                        )
3041                        .with_note(
3042                            "the actor is the identity: a handler tells foreign callers apart by \
3043                             `match`ing its `by` sum",
3044                        ),
3045                    );
3046                }
3047            }
3048            // v0.47: a Bearer actor must name its signing secret and yield a
3049            // string-constructible identity (minted from the JWT `sub` claim).
3050            Some(Scheme::Bearer) => {
3051                if actor.scheme_arg("secret").is_none() {
3052                    errors.push(
3053                        CompileError::new(
3054                            "bynk.actor.bearer_missing_secret",
3055                            auth.span,
3056                            "a `Bearer` actor must name its signing secret",
3057                        )
3058                        .with_note(
3059                            "write `auth = Bearer(secret = \"<ENV_NAME>\")` — the env var the \
3060                             `Secrets` capability resolves to the JWT signing key",
3061                        ),
3062                    );
3063                }
3064                match &actor.identity {
3065                    None => errors.push(
3066                        CompileError::new(
3067                            "bynk.actor.bearer_identity_not_string_constructible",
3068                            auth.span,
3069                            "a `Bearer` actor must declare a string-constructible `identity`",
3070                        )
3071                        .with_note(
3072                            "the verified identity is minted from the token's `sub` claim — \
3073                             declare `identity = T` where `T` is a refined or opaque `String`",
3074                        ),
3075                    ),
3076                    Some(id) if !is_string_constructible(id, &resolved.types) => errors.push(
3077                        CompileError::new(
3078                            "bynk.actor.bearer_identity_not_string_constructible",
3079                            id.span(),
3080                            "a `Bearer` actor's identity must be string-constructible",
3081                        )
3082                        .with_note(
3083                            "the identity is minted from the token's `sub` claim (a string) — \
3084                             use a refined or opaque `String` type",
3085                        ),
3086                    ),
3087                    Some(_) => {}
3088                }
3089            }
3090            // v0.51: a Signature actor must name its secret and signature header;
3091            // a `tolerance` requires a `timestamp`; identity is `()` (a declared
3092            // identity is not yet supported).
3093            Some(Scheme::Signature) => {
3094                if actor.scheme_arg("secret").is_none() {
3095                    errors.push(
3096                        CompileError::new(
3097                            "bynk.actor.signature_missing_secret",
3098                            auth.span,
3099                            "a `Signature` actor must name its signing secret",
3100                        )
3101                        .with_note(
3102                            "write `auth = Signature(secret = \"<ENV_NAME>\", header = \"<Header>\")`",
3103                        ),
3104                    );
3105                }
3106                if actor.scheme_arg("header").is_none() {
3107                    errors.push(
3108                        CompileError::new(
3109                            "bynk.actor.signature_missing_header",
3110                            auth.span,
3111                            "a `Signature` actor must name the signature header",
3112                        )
3113                        .with_note(
3114                            "write `header = \"<Header-Name>\"` — the request header carrying the HMAC",
3115                        ),
3116                    );
3117                }
3118                if let Some(tol) = actor.scheme_arg("tolerance")
3119                    && actor.scheme_arg("timestamp").is_none()
3120                {
3121                    errors.push(
3122                        CompileError::new(
3123                            "bynk.actor.signature_tolerance_without_timestamp",
3124                            tol.span,
3125                            "`tolerance` requires a `timestamp` header to check against",
3126                        )
3127                        .with_note("add `timestamp = \"<Header>\"`, or drop `tolerance`"),
3128                    );
3129                }
3130                if let Some(id) = &actor.identity {
3131                    errors.push(
3132                        CompileError::new(
3133                            "bynk.actor.signature_identity_unsupported",
3134                            id.span(),
3135                            "a `Signature` actor does not yet support a declared `identity`",
3136                        )
3137                        .with_note(
3138                            "a signature attests authenticity, not a principal — the event is the \
3139                             body param; use `by Webhook ()`",
3140                        ),
3141                    );
3142                }
3143            }
3144            // v0.151: an `Oidc` actor names its provider's public trust
3145            // parameters — `issuer` (checked against `iss`), `audience` (checked
3146            // against `aud`), and the `jwks` endpoint URL — and yields a
3147            // string-constructible identity minted from the verified `sub`
3148            // claim. It names **no secret**: the trust root is the provider's
3149            // published public key set, not a shared signing key.
3150            Some(Scheme::Oidc) => {
3151                if actor.scheme_arg("issuer").is_none() {
3152                    errors.push(
3153                        CompileError::new(
3154                            "bynk.actor.oidc_missing_issuer",
3155                            auth.span,
3156                            "an `Oidc` actor must name its `issuer`",
3157                        )
3158                        .with_note(
3159                            "write `auth = Oidc(issuer = \"https://issuer.example\", audience = \"<aud>\", jwks = \"<jwks-url>\")` — \
3160                             the `iss` the verified token must carry",
3161                        ),
3162                    );
3163                }
3164                if actor.scheme_arg("audience").is_none() {
3165                    errors.push(
3166                        CompileError::new(
3167                            "bynk.actor.oidc_missing_audience",
3168                            auth.span,
3169                            "an `Oidc` actor must name its `audience`",
3170                        )
3171                        .with_note(
3172                            "add `audience = \"<aud>\"` — the `aud` claim the token must be issued for (this API)",
3173                        ),
3174                    );
3175                }
3176                if actor.scheme_arg("jwks").is_none() {
3177                    errors.push(
3178                        CompileError::new(
3179                            "bynk.actor.oidc_missing_jwks",
3180                            auth.span,
3181                            "an `Oidc` actor must name its `jwks` endpoint",
3182                        )
3183                        .with_note(
3184                            "add `jwks = \"https://issuer.example/.well-known/jwks.json\"` — the public key set the verifier fetches",
3185                        ),
3186                    );
3187                }
3188                // #2380 (L5): `trustFrom` names an environment variable whose JSON
3189                // overrides the declared trust roots at run time (tests, staging).
3190                if let Some(arg) = actor.scheme_arg("trustFrom") {
3191                    match arg.value.as_str() {
3192                        None => errors.push(
3193                            CompileError::new(
3194                                "bynk.actor.oidc_trust_from_not_string",
3195                                arg.span,
3196                                "`trustFrom` names an environment variable, as a string",
3197                            )
3198                            .with_note(
3199                                "write `trustFrom = \"MY_OIDC_TRUST\"`; when it is set, its JSON `{\"issuer\", \"jwks\", \"audience\"?}` replaces the declared trust roots",
3200                            ),
3201                        ),
3202                        Some(name) => {
3203                            let clashes = table.actors.values().any(|other| {
3204                                other
3205                                    .scheme_arg("secret")
3206                                    .and_then(|a| a.value.as_str())
3207                                    == Some(name)
3208                            });
3209                            if clashes {
3210                                errors.push(
3211                                    CompileError::new(
3212                                        "bynk.actor.oidc_trust_from_is_secret",
3213                                        arg.span,
3214                                        format!(
3215                                            "`trustFrom` names `{name}`, which an actor uses as its `secret`"
3216                                        ),
3217                                    )
3218                                    .with_note(
3219                                        "give the trust override its own environment variable: a secret is a key, not trust roots",
3220                                    ),
3221                                );
3222                            }
3223                        }
3224                    }
3225                }
3226                match &actor.identity {
3227                    None => errors.push(
3228                        CompileError::new(
3229                            "bynk.actor.oidc_identity_not_string_constructible",
3230                            auth.span,
3231                            "an `Oidc` actor must declare a string-constructible `identity`",
3232                        )
3233                        .with_note(
3234                            "the verified identity is minted from the token's `sub` claim — \
3235                             declare `identity = T` where `T` is a refined or opaque `String`",
3236                        ),
3237                    ),
3238                    Some(id) if !is_string_constructible(id, &resolved.types) => errors.push(
3239                        CompileError::new(
3240                            "bynk.actor.oidc_identity_not_string_constructible",
3241                            id.span(),
3242                            "an `Oidc` actor's identity must be string-constructible",
3243                        )
3244                        .with_note(
3245                            "the identity is minted from the token's `sub` claim (a string) — \
3246                             use a refined or opaque `String` type",
3247                        ),
3248                    ),
3249                    Some(_) => {}
3250                }
3251            }
3252            // #3386: a signed session cookie.
3253            Some(Scheme::SignedCookie) => {
3254                check_signed_cookie_actor(actor, auth, table, &resolved.types, errors);
3255            }
3256            Some(_) => {}
3257        }
3258        // A declared identity must be a context-ownable (sealed) type — either
3259        // declared directly in this context, or a `uses`-imported commons type
3260        // this context's own emission rebrands (`uses_commons_type_names`,
3261        // `emit_context_rebrands`'s exact predicate) — either way, unforgeable
3262        // from outside the context. A `consumes`-surfaced cross-context type is
3263        // neither: it is not rebranded, so it stays excluded.
3264        //
3265        // Events track, slice 0 (spine #936) narrowed `local_type_names` itself
3266        // to "declared directly here" only (owner-only emission and `.raw`/
3267        // `.unsafe()` need exactly that, excluding `uses`-rebrands too) — this
3268        // check predates that narrowing and needs the broader "context-owned"
3269        // union back, so it reads `uses_commons_type_names` alongside it
3270        // instead of relying on the now-narrower `local_type_names` alone.
3271        // (Signature and Foreign handle their own identity rule above.)
3272        if !matches!(
3273            Scheme::from_name(actor.auth.as_ref().map(|a| a.name.as_str()).unwrap_or("")),
3274            Some(Scheme::Signature | Scheme::Foreign)
3275        ) && let Some(id) = &actor.identity
3276        {
3277            let ownable = matches!(id, TypeRef::Named(n) if
3278                resolved.is_local_type(&n.name) || resolved.is_uses_commons_type(&n.name));
3279            if !ownable {
3280                errors.push(
3281                    CompileError::new(
3282                        "bynk.actor.identity_not_sealed",
3283                        id.span(),
3284                        "an actor identity must be a context-ownable value type",
3285                    )
3286                    .with_note(
3287                        "declare the identity as a type in this context so it is sealed — \
3288                         minted only inside the context and unforgeable downstream",
3289                    ),
3290                );
3291            }
3292        }
3293    }
3294
3295    check_foreign_secret_dupes(table, errors);
3296
3297    // Pass 2 — handler `by`-clause contracts.
3298    for service in table.services.values() {
3299        refs.set_owner(&service.name.name);
3300        for handler in &service.handlers {
3301            match &handler.by_clause {
3302                Some(by) => {
3303                    check_by_clause_contracts(
3304                        by,
3305                        Some(&handler.params),
3306                        &service.protocol,
3307                        table,
3308                        refs,
3309                        errors,
3310                    );
3311                    check_signed_cookie_route(handler, table, &resolved.types, errors);
3312                }
3313                // #2341 (decision C): `on rejected` has no actor; its own
3314                // checks (`check_rejected_handlers`) refuse a `by`.
3315                _ if handler.kind == HandlerKind::Rejected => {}
3316                None => check_missing_by(handler, &service.protocol, errors),
3317            }
3318        }
3319        // v0.155: a service-level `by` default is validated *indirectly* — the
3320        // normalization pass injects it into the handlers that omit their own
3321        // clause, and the loop above checks those copies. So when the default is
3322        // inherited by **no** handler (every handler overrides it, or the service
3323        // has no handlers), it is injected into nothing and would go unchecked —
3324        // a typo'd/unknown default actor could pass silently, then surface later
3325        // at the header the moment an override is removed. Validate it directly
3326        // here in exactly that case, against the header span, so the diagnostic
3327        // is neither missed nor duplicated with the inherited-handler path.
3328        if let Some(default_by) = &service.default_by {
3329            let inherited = service.handlers.iter().any(|h| {
3330                h.by_clause
3331                    .as_ref()
3332                    .is_some_and(|b| b.span == default_by.span)
3333            });
3334            if !inherited {
3335                check_by_clause_contracts(default_by, None, &service.protocol, table, refs, errors);
3336            }
3337        }
3338    }
3339}
3340
3341#[allow(clippy::too_many_arguments)]
3342fn check_service_decls(
3343    typed: &mut checker::TypedCommons,
3344    table: &UnitTable,
3345    cross_context: &resolver::CrossContextInfo,
3346    resolved: &ResolvedCommons,
3347    capability_info_map: &HashMap<String, CapabilityInfo>,
3348    refs: &mut RefSink,
3349    hints: &mut HintSink,
3350    locals: &mut LocalsSink,
3351    requirements: &mut RequirementSink,
3352    errors: &mut Vec<CompileError>,
3353    tys: &Arc<Types>,
3354) {
3355    // v0.44: a service is one protocol adapter — every handler's form must
3356    // match the service's `from <protocol>` header.
3357    crate::email::check_service_protocols_and_email(table, &typed.types, errors, tys);
3358
3359    // v0.45: actor-contract well-formedness and the handler `by`-clause checks.
3360    check_actor_contracts(table, resolved, refs, errors);
3361
3362    // #2341 (decision C): the shape of each service's `on rejected`.
3363    check_rejected_handlers(table, errors);
3364
3365    // #3343: `@name("…")` on the fields of a request record.
3366    validate_field_names(table, &typed.types, &typed.consts, errors);
3367
3368    let cf_is_std = cf_type_is_std(cross_context, table);
3369    // v0.9: validate HTTP handler shape and check for duplicate routes
3370    // across all services in this context.
3371    let mut route_first_span: HashMap<(HttpMethod, String), Span> = HashMap::new();
3372    for service in table.services.values() {
3373        for handler in &service.handlers {
3374            let HandlerKind::Http { method, path } = &handler.kind else {
3375                continue;
3376            };
3377            validate_http_handler(handler, *method, path, &typed.types, cf_is_std, errors);
3378            let key = (*method, path.clone());
3379            if let Some(prev) = route_first_span.get(&key).copied() {
3380                errors.push(
3381                    CompileError::new(
3382                        "bynk.http.duplicate_route",
3383                        handler.span,
3384                        format!(
3385                            "duplicate HTTP route: another handler already declares `{} {}`",
3386                            method.as_str(),
3387                            path,
3388                        ),
3389                    )
3390                    .with_label(prev, "previously declared here"),
3391                );
3392            } else {
3393                route_first_span.insert(key, handler.span);
3394            }
3395        }
3396    }
3397
3398    // v0.140 (ADR 0163): validate handler-position annotations (`@cache`) across
3399    // every handler — services and agents — so a misplaced annotation is caught
3400    // wherever it is written, not only on well-formed HTTP routes.
3401    for service in table.services.values() {
3402        let service_cap = service.limits.as_ref().and_then(|p| p.max_body());
3403        for handler in &service.handlers {
3404            validate_handler_annotations(handler, service_cap, errors);
3405        }
3406    }
3407    for agent in table.agents.values() {
3408        for handler in &agent.handlers {
3409            validate_handler_annotations(handler, None, errors);
3410        }
3411    }
3412
3413    // v0.131 (ADR 0159): validate each service's `cors { }` policy.
3414    for service in table.services.values() {
3415        validate_service_cors(service, errors);
3416    }
3417
3418    // v0.141 (ADR 0164): validate each service's `security { }` policy. (Absence
3419    // is legal and still stamps the safe defaults — only a *declared* block is
3420    // validated here.)
3421    for service in table.services.values() {
3422        if let Some(policy) = &service.security {
3423            validate_security_policy(service, policy, errors);
3424        }
3425    }
3426
3427    // v0.142 (ADR 0165): validate each service's `limits { }` policy. (Absence is
3428    // legal — a service with no cap is unchanged; only a *declared* block is
3429    // validated here.)
3430    for service in table.services.values() {
3431        if let Some(policy) = &service.limits {
3432            validate_limits_policy(service, policy, errors);
3433        }
3434    }
3435
3436    // #2858: validate each service's `json { }` policy, then refuse the one
3437    // ambiguous shape (`Option[Option[T]]`) in any plain-mode route's response.
3438    for service in table.services.values() {
3439        if let Some(policy) = &service.json {
3440            validate_json_policy(service, policy, errors);
3441        }
3442        if !matches!(service.protocol, ServiceProtocol::Http) {
3443            continue;
3444        }
3445        for handler in &service.handlers {
3446            if !matches!(handler.kind, HandlerKind::Http { .. })
3447                || effective_json_options(service.json.as_ref(), handler) != JsonOptions::Plain
3448            {
3449                continue;
3450            }
3451            let TypeRef::Effect(inner, _) = &handler.return_type else {
3452                continue;
3453            };
3454            let TypeRef::HttpResult(body, _) = inner.as_ref() else {
3455                continue;
3456            };
3457            if let Some(payload) = null_payload_option(body, &resolved.types, &mut HashSet::new()) {
3458                errors.push(
3459                    CompileError::new(
3460                        "bynk.json.nested_option_plain",
3461                        body.span(),
3462                        format!(
3463                            "`Option[{payload}]`: `Some({some})` and `None` would both write `null` in plain JSON",
3464                            some = if payload == "()" { "()" } else { "…" },
3465                        ),
3466                    )
3467                    .with_note(
3468                        "an `Option` payload that can itself be `null` (`Option[T]` or `()`) is ambiguous; model it as a sum type, or keep this route tagged with `@json(options: tagged)`",
3469                    ),
3470                );
3471            }
3472        }
3473    }
3474
3475    // v0.10a: validate `on cron` handler shape and check for duplicate
3476    // schedules across all services in this context (the generated
3477    // `scheduled` dispatcher routes on `event.cron`, so duplicates are
3478    // ambiguous).
3479    let mut schedule_first_span: HashMap<String, Span> = HashMap::new();
3480    for service in table.services.values() {
3481        for handler in &service.handlers {
3482            let HandlerKind::Cron { expr } = &handler.kind else {
3483                continue;
3484            };
3485            validate_cron_handler(handler, expr, errors);
3486            if let Some(prev) = schedule_first_span.get(expr).copied() {
3487                errors.push(
3488                    CompileError::new(
3489                        "bynk.cron.duplicate_schedule",
3490                        handler.span,
3491                        format!(
3492                            "duplicate cron schedule: another handler already declares `{expr}`",
3493                        ),
3494                    )
3495                    .with_label(prev, "previously declared here"),
3496                );
3497            } else {
3498                schedule_first_span.insert(expr.clone(), handler.span);
3499            }
3500        }
3501    }
3502
3503    // v0.10b: validate `on queue` handler shape and check for duplicate
3504    // consumers across all services in this context (the generated `queue`
3505    // dispatcher routes on `batch.queue`, so two consumers of the same queue
3506    // are ambiguous).
3507    let mut consumer_first_span: HashMap<String, Span> = HashMap::new();
3508    for service in table.services.values() {
3509        let ServiceProtocol::Queue { name } = &service.protocol else {
3510            continue;
3511        };
3512        for handler in &service.handlers {
3513            if !matches!(handler.kind, HandlerKind::Message) {
3514                continue;
3515            }
3516            validate_queue_handler(handler, name, errors);
3517            if let Some(prev) = consumer_first_span.get(name).copied() {
3518                errors.push(
3519                    CompileError::new(
3520                        "bynk.queue.duplicate_consumer",
3521                        handler.span,
3522                        format!(
3523                            "duplicate queue consumer: another handler already consumes `{name}`",
3524                        ),
3525                    )
3526                    .with_label(prev, "previously declared here"),
3527                );
3528            } else {
3529                consumer_first_span.insert(name.clone(), handler.span);
3530            }
3531        }
3532    }
3533
3534    // Check service handlers.
3535    for service in table.services.values() {
3536        refs.set_owner(&service.name.name);
3537        for handler in &service.handlers {
3538            // The given clause must reference only declared (local) or
3539            // exported (cross-context) capabilities.
3540            let mut handler_caps: HashMap<String, CapabilityInfo> = HashMap::new();
3541            for cap_ref in &handler.given {
3542                if let Some(info) =
3543                    resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
3544                {
3545                    handler_caps.insert(cap_ref.key().to_string(), info);
3546                }
3547            }
3548            // The handler return type must be Effect[T].
3549            if !matches!(handler.return_type, TypeRef::Effect(_, _)) {
3550                errors.push(CompileError::new(
3551                    "bynk.service.return_not_effect",
3552                    handler.return_type.span(),
3553                    format!(
3554                        "service handler must return `Effect[T]`, but got `{}`",
3555                        ts_type_ref_display(&handler.return_type)
3556                    ),
3557                ));
3558            }
3559            // v0.45: the `by`-bound actor identity, in scope for the body.
3560            let actor_binding =
3561                handler_actor_binding(handler, &service.protocol, table, resolved, tys);
3562            // #1170: persist it, keyed by this handler's own span — the
3563            // "no arena identity" substitute `TypedCommons::actor_bindings`'s
3564            // own doc comment names — so a post-`certify` consumer
3565            // (`bynk-emit::ir::lower`) can read it back once one exists.
3566            if let Some((binder, ty)) = &actor_binding {
3567                typed
3568                    .actor_bindings
3569                    .insert(handler.span, (binder.clone(), *ty));
3570            }
3571            // v0.103 (real-time track slice 3): an `on open` handler receives a
3572            // fresh owned `Connection[out]` named `connection`. Inject it as a
3573            // synthetic first parameter so the body type-checks against it and
3574            // the linearity pass seeds it as an owned held binding the handler
3575            // must dispose (transfer to an agent).
3576            // v0.103/v0.106: a `from websocket` lifecycle handler receives the
3577            // `connection` as a synthetic first param — the fresh owned socket for
3578            // `on open` (which must be disposed/transferred), or the **borrowed**
3579            // firing socket for `on message`/`on close` (used non-consumingly, never
3580            // disposed by the handler). The body type-checks against it either way;
3581            // the linearity pass treats the borrowed cases via `borrowed_held`.
3582            let is_ws_lifecycle = matches!(
3583                (&handler.kind, &service.protocol),
3584                (
3585                    HandlerKind::Open | HandlerKind::Message | HandlerKind::Close,
3586                    ServiceProtocol::WebSocket { .. }
3587                )
3588            );
3589            let params_for_check: Vec<Param> = match (&handler.kind, &service.protocol) {
3590                (
3591                    HandlerKind::Open | HandlerKind::Message | HandlerKind::Close,
3592                    ServiceProtocol::WebSocket { out_type, .. },
3593                ) => {
3594                    let mut ps = vec![open_connection_param(out_type, handler.span)];
3595                    ps.extend(handler.params.iter().cloned());
3596                    ps
3597                }
3598                _ => handler.params.clone(),
3599            };
3600            // The firing `connection` of `on message`/`on close` is borrowed, not
3601            // owned — no disposal obligation (contrast `on open`, owned).
3602            let borrowed_held: std::collections::HashSet<String> = if is_ws_lifecycle
3603                && matches!(handler.kind, HandlerKind::Message | HandlerKind::Close)
3604            {
3605                std::iter::once("connection".to_string()).collect()
3606            } else {
3607                std::collections::HashSet::new()
3608            };
3609            checker::check_handler_body(
3610                resolved,
3611                checker::HandlerBodyCheck {
3612                    capabilities: handler_caps,
3613                    declared_capabilities: capability_info_map.clone(),
3614                    given_anchor: Some(given_anchor_after_by(handler)),
3615                    report_unused: true,
3616                    actor_binding,
3617                    borrowed_held,
3618                    oidc_binder: crate::actors::oidc_seam_for(handler, &table.actors)
3619                        .and_then(|seam| seam.binder),
3620                    // #2683: a WebSocket handler runs in the connection-hosting
3621                    // Durable Object, whose `deps` carry no execution context.
3622                    service_handler: !is_ws_lifecycle,
3623                    ..checker::HandlerBodyCheck::new(
3624                        &handler.body,
3625                        &handler.return_type,
3626                        &params_for_check,
3627                        &handler.given,
3628                    )
3629                },
3630                checker::CheckSinks {
3631                    tys,
3632                    expr_types: &mut typed.expr_types,
3633                    errors,
3634                    refs,
3635                    hints,
3636                    locals,
3637                    requirements,
3638                    callees: &mut typed.callees,
3639                },
3640            );
3641        }
3642        // v0.155: like the `by` default (see check_actor_contracts), a service-
3643        // level `given` default is validated only through the handlers that
3644        // inherit it — the normalization pass injects it into handlers that
3645        // declare no `given` of their own. When it is inherited by no handler
3646        // (every handler declares its own `given`), resolve the default's
3647        // capabilities directly here so an unknown/typo'd default capability is
3648        // still reported, at the header. (A service always has ≥1 handler, so the
3649        // zero-handler case cannot arise; only full shadowing.)
3650        if let Some(first) = service.default_given.first() {
3651            let inherited = service
3652                .handlers
3653                .iter()
3654                .any(|h| h.given.first().is_some_and(|g| g.span == first.span));
3655            if !inherited {
3656                for cap_ref in &service.default_given {
3657                    let _ = resolve_given_cap_ref(
3658                        cap_ref,
3659                        capability_info_map,
3660                        cross_context,
3661                        errors,
3662                        refs,
3663                    );
3664                }
3665            }
3666        }
3667    }
3668}
3669
3670/// v0.103: the synthetic `connection: Connection[out]` parameter an `on open`
3671/// handler receives — a fresh, owned held binding the framework supplies and the
3672/// handler must dispose (§2.9.4).
3673fn open_connection_param(out_type: &TypeRef, span: Span) -> Param {
3674    Param {
3675        name: Ident {
3676            name: "connection".to_string(),
3677            span,
3678        },
3679        type_ref: TypeRef::Connection(Box::new(out_type.clone()), span),
3680        span,
3681    }
3682}
3683
3684/// v0.45: the actor binding a service handler exposes to its body, if it has a
3685/// `by <binder>: <Actor>` clause. Returns `(binder, identity_ty)`. Default-actor
3686/// handlers (no `by`) carry no named binding. The identity type is the actor's
3687/// declared `identity = T` (a context-ownable type), or the scheme default:
3688/// `()` for trivial actors, the calling-context id (`String`) for the prelude
3689/// `Caller` (Q7).
3690fn handler_actor_binding(
3691    handler: &Handler,
3692    _protocol: &ServiceProtocol,
3693    table: &UnitTable,
3694    resolved: &ResolvedCommons,
3695    tys: &Arc<Types>,
3696) -> Option<(String, checker::TyId)> {
3697    let by = handler.by_clause.as_ref()?;
3698    // No binder (binder-less `by <Actor>`) ⇒ no identity binding in scope.
3699    let binder = by.binder.as_ref()?;
3700    // A binder that collides with a parameter is diagnosed
3701    // (`bynk.actor.binder_shadows_param`); suppress the binding so the body
3702    // scope keeps the real parameter rather than the clobbering actor binding.
3703    if handler.params.iter().any(|p| p.name.name == binder.name) {
3704        return None;
3705    }
3706    // v0.52: a sum (`by who: A | B`) binds an `ActorSum` the body matches; a
3707    // single actor binds an `Actor` exposing `.identity`.
3708    let binder_ty = if by.is_sum() {
3709        tys.intern(checker::Ty::ActorSum(
3710            by.actors
3711                .iter()
3712                .map(|a| {
3713                    (
3714                        a.name.clone(),
3715                        actor_identity_ty(&a.name, table, resolved, tys),
3716                    )
3717                })
3718                .collect(),
3719        ))
3720    } else {
3721        tys.intern(checker::Ty::Actor(actor_identity_ty(
3722            &by.primary().name,
3723            table,
3724            resolved,
3725            tys,
3726        )))
3727    };
3728    Some((binder.name.clone(), binder_ty))
3729}
3730
3731/// The identity `Ty` a named actor yields (a local declaration or a prelude
3732/// actor).
3733fn actor_identity_ty(
3734    actor_name: &str,
3735    table: &UnitTable,
3736    resolved: &ResolvedCommons,
3737    tys: &Arc<Types>,
3738) -> checker::TyId {
3739    actor_identity_ty_guarded(actor_name, table, resolved, &mut Vec::new(), tys)
3740}
3741
3742/// Inner worker carrying a `seen` chain so a malformed **refinement cycle**
3743/// (`actor A = A`, or `A = B` / `B = A`) terminates with the unit identity
3744/// instead of overflowing the stack. A valid refinement's base is a direct
3745/// `Bearer` actor (the checker rejects refinement chains/cycles with
3746/// `refinement_base_unsupported`), so this guard only ever fires on input that
3747/// is already a compile error — it keeps the checker from crashing before that
3748/// diagnostic is reported.
3749fn actor_identity_ty_guarded<'a>(
3750    actor_name: &'a str,
3751    table: &'a UnitTable,
3752    resolved: &ResolvedCommons,
3753    seen: &mut Vec<&'a str>,
3754    tys: &Arc<Types>,
3755) -> checker::TyId {
3756    use crate::actors::{Identity, prelude_actor};
3757    if let Some(local) = table.actors.get(actor_name) {
3758        // v0.53: a refinement actor (`actor Admin = User where …`) yields its
3759        // base's identity — refinement elimination, an `Admin` is-a `User`.
3760        if let Some(r) = &local.refinement {
3761            if seen.contains(&actor_name) {
3762                return tys.intern(checker::Ty::Unit);
3763            }
3764            seen.push(actor_name);
3765            // Resolve against the declaration's own key so the cycle guard sees
3766            // the same name on a self-reference.
3767            if let Some((key, _)) = table.actors.get_key_value(&r.base.name) {
3768                return actor_identity_ty_guarded(key.as_str(), table, resolved, seen, tys);
3769            }
3770            // #3890: a refinement over the prelude `Caller` yields a `CallerId`.
3771            if is_caller_refinement(local, table) {
3772                return tys.intern(checker::Ty::Base(bynk_syntax::ast::BaseType::String));
3773            }
3774            return tys.intern(checker::Ty::Unit);
3775        }
3776        return match &local.identity {
3777            Some(id) => checker::resolve_type_ref(id, &resolved.types, tys)
3778                .unwrap_or_else(|| tys.intern(checker::Ty::Unit)),
3779            None => tys.intern(checker::Ty::Unit),
3780        };
3781    }
3782    match prelude_actor(actor_name).map(|c| c.identity) {
3783        Some(Identity::CallerId) => {
3784            tys.intern(checker::Ty::Base(bynk_syntax::ast::BaseType::String))
3785        }
3786        // #3328: `Sender`'s `SenderIdentity` is minted by the Workers `email()`
3787        // entry. It is the first-party record from `bynk.cloudflare`, so it types
3788        // as that record when the context imports it (`consumes bynk.cloudflare
3789        // { SenderIdentity, … }`) and as the unit value when it does not, as the
3790        // other platform-tag actors read.
3791        Some(Identity::Declared(name)) => checker::resolve_type_ref(
3792            &bynk_syntax::ast::TypeRef::Named(bynk_syntax::ast::Ident {
3793                name,
3794                span: bynk_syntax::span::Span::default(),
3795            }),
3796            &resolved.types,
3797            tys,
3798        )
3799        .unwrap_or_else(|| tys.intern(checker::Ty::Unit)),
3800        _ => tys.intern(checker::Ty::Unit),
3801    }
3802}
3803
3804/// The closed storage-kind catalogue (design notes §10). Every kind is functional
3805/// but `Queue`, which parses and validates as a known kind and is refused
3806/// (`bynk.store.kind_unsupported`).
3807const STORAGE_KINDS: &[&str] = &["Cell", "Map", "Set", "Log", "Queue", "Cache"];
3808
3809/// The closed storage-annotation registry (ADR 0111 D2/D3): each `@name` with the
3810/// storage kind(s) it attaches to. `functional` is whether anything acts on the
3811/// annotation: it is `true` for `@ttl`, `@retain` and `@indexed`, and `false`
3812/// only for `@bounded`, which is recognised and refused
3813/// (`bynk.store.annotation_unsupported`) until it has a meaning.
3814struct AnnotationSpec {
3815    name: &'static str,
3816    kinds: &'static [&'static str],
3817    functional: bool,
3818}
3819
3820const ANNOTATIONS: &[AnnotationSpec] = &[
3821    AnnotationSpec {
3822        name: "ttl",
3823        kinds: &["Cache"],
3824        functional: true,
3825    },
3826    AnnotationSpec {
3827        name: "retain",
3828        kinds: &["Log"],
3829        functional: true,
3830    },
3831    AnnotationSpec {
3832        name: "indexed",
3833        kinds: &["Map"],
3834        functional: true,
3835    },
3836    AnnotationSpec {
3837        name: "bounded",
3838        kinds: &["Queue", "Log"],
3839        functional: false,
3840    },
3841];
3842
3843/// Validate a `store` field's annotations against the closed registry (ADR 0111):
3844/// an unknown name is `bynk.store.unknown_annotation`; a known name on the wrong
3845/// kind is `bynk.store.annotation_kind_mismatch`; a known name on the right kind
3846/// that nothing acts on yet is `bynk.store.annotation_unsupported`. `head` is
3847/// the (already known-valid) storage kind of the field.
3848fn validate_store_annotations(
3849    f: &StoreField,
3850    head: &str,
3851    types: &HashMap<String, Arc<TypeDecl>>,
3852    errors: &mut Vec<CompileError>,
3853) {
3854    for ann in &f.annotations {
3855        let name = ann.name.name.as_str();
3856        let Some(spec) = ANNOTATIONS.iter().find(|s| s.name == name) else {
3857            errors.push(
3858                CompileError::new(
3859                    "bynk.store.unknown_annotation",
3860                    ann.name.span,
3861                    format!(
3862                        "unknown storage annotation `@{name}` — expected one of {}",
3863                        ANNOTATIONS
3864                            .iter()
3865                            .map(|s| format!("@{}", s.name))
3866                            .collect::<Vec<_>>()
3867                            .join(", ")
3868                    ),
3869                )
3870                .with_note("storage annotations are a closed set (ADR 0111)"),
3871            );
3872            continue;
3873        };
3874        if !spec.kinds.contains(&head) {
3875            errors.push(CompileError::new(
3876                "bynk.store.annotation_kind_mismatch",
3877                ann.span,
3878                format!(
3879                    "`@{name}` applies to {}, not `{head}`",
3880                    spec.kinds
3881                        .iter()
3882                        .map(|k| format!("`{k}`"))
3883                        .collect::<Vec<_>>()
3884                        .join("/")
3885                ),
3886            ));
3887            continue;
3888        }
3889        if !spec.functional {
3890            errors.push(
3891                CompileError::new(
3892                    "bynk.store.annotation_unsupported",
3893                    ann.span,
3894                    format!("`@{name}` is recognised but has no effect yet"),
3895                )
3896                .with_note(if head == "Log" {
3897                    "leave the annotation off; to limit a `Log`, use `@retain`, which drops \
3898                     entries older than a period"
3899                } else {
3900                    "leave the annotation off"
3901                }),
3902            );
3903            continue;
3904        }
3905        // v0.93 (ADR 0118): `@indexed(by: k, …)` — each `by:` names a
3906        // **value-keyable field of the map's value type** to maintain a secondary
3907        // index on. Validate the keys here, now the kind/value type are known.
3908        if name == "indexed" {
3909            validate_indexed_keys(f, types, ann, errors);
3910        }
3911    }
3912}
3913
3914/// v0.93 (ADR 0118): each `@indexed(by: k)` key must label a `by:` argument that
3915/// names a **value-keyable field** of the map's value type (a `Record`). A
3916/// non-`by:` argument, a key that is not a field, or a non-keyable field type is
3917/// a diagnostic.
3918fn validate_indexed_keys(
3919    f: &StoreField,
3920    types: &HashMap<String, Arc<TypeDecl>>,
3921    ann: &Annotation,
3922    errors: &mut Vec<CompileError>,
3923) {
3924    // The map's value type is the second kind argument (`Map[K, V]`).
3925    let value_fields: Option<&[RecordField]> = f
3926        .kind
3927        .args
3928        .get(1)
3929        .and_then(|v| match v {
3930            TypeRef::Named(id) => types.get(&id.name),
3931            _ => None,
3932        })
3933        .and_then(|decl| match &decl.body {
3934            TypeBody::Record(r) => Some(r.fields.as_slice()),
3935            _ => None,
3936        });
3937    for arg in &ann.args {
3938        // Only `by:` labels are admitted on `@indexed`.
3939        let Some(label) = &arg.label else {
3940            errors.push(CompileError::new(
3941                "bynk.index.bad_argument",
3942                arg.span,
3943                "`@indexed` arguments are `by: <field>` labels naming a field to index on",
3944            ));
3945            continue;
3946        };
3947        if label.name != "by" {
3948            errors.push(CompileError::new(
3949                "bynk.index.bad_argument",
3950                arg.span,
3951                format!("`@indexed` takes `by:` arguments, not `{}:`", label.name),
3952            ));
3953            continue;
3954        }
3955        let ExprKind::Ident(key) = &arg.value.kind else {
3956            errors.push(CompileError::new(
3957                "bynk.index.bad_argument",
3958                arg.value.span,
3959                "`@indexed(by: …)` names a field of the map's value type",
3960            ));
3961            continue;
3962        };
3963        // The value type must be a record whose field `key` exists and is keyable.
3964        match value_fields.and_then(|fs| fs.iter().find(|rf| rf.name.name == key.name)) {
3965            None => {
3966                errors.push(CompileError::new(
3967                    "bynk.index.unknown_key",
3968                    arg.value.span,
3969                    format!(
3970                        "`@indexed(by: {0})` — the map's value type has no field `{0}`",
3971                        key.name
3972                    ),
3973                ));
3974            }
3975            Some(field) if !type_ref_is_keyable(&field.type_ref, types) => {
3976                errors.push(
3977                    CompileError::new(
3978                        "bynk.index.unkeyable_key",
3979                        arg.value.span,
3980                        format!(
3981                            "`@indexed(by: {0})` — field `{0}` is not value-keyable; an index key must be `Int`, `String`, or a refined/opaque type over them",
3982                            key.name
3983                        ),
3984                    ),
3985                );
3986            }
3987            Some(_) => {}
3988        }
3989    }
3990}
3991
3992/// #1680 (runtime-semantics track S13): a store `Set`'s element and a store
3993/// `Map`'s or `Cache`'s key must be value-keyable, the rule value `Map` keys,
3994/// `distinct`/`groupBy` keys and `@indexed` fields already follow. A store
3995/// collection is a plain object keyed by its key's string form
3996/// (`rec[item] = true`), so a record key failed `tsc` (TS2538), and without
3997/// `tsc` every record would have keyed as `"[object Object]"`. A name that
3998/// doesn't resolve is reported by the resolver, so it is skipped here.
3999fn check_store_keyable(
4000    t: &TypeRef,
4001    what: &str,
4002    types: &HashMap<String, Arc<TypeDecl>>,
4003    errors: &mut Vec<CompileError>,
4004) {
4005    if let TypeRef::Named(id) = t
4006        && !types.contains_key(&id.name)
4007    {
4008        return;
4009    }
4010    if !type_ref_is_keyable(t, types) {
4011        errors.push(
4012            CompileError::new(
4013                "bynk.store.unkeyable_key",
4014                t.span(),
4015                format!(
4016                    "{what} must be value-keyable — `String`, `Int`, or a refined/opaque type over them"
4017                ),
4018            )
4019            .with_note(
4020                "only `String` and `Int` keys (or a refined or opaque type over them) are supported, matching value `Map` keys and `@indexed` fields; key a record by one of its id fields, and an enum by its name as a `String`",
4021            ),
4022        );
4023    }
4024}
4025
4026/// Whether a `TypeRef` is value-keyable (the Map-key / index-key rule, ADR 0110
4027/// D5): `Int`/`String`, including a refined/opaque named type over them.
4028fn type_ref_is_keyable(t: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
4029    match t {
4030        TypeRef::Base(BaseType::Int | BaseType::String, _) => true,
4031        TypeRef::Named(id) => matches!(
4032            types.get(&id.name).map(|d| &d.body),
4033            Some(TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. })
4034                if matches!(base, BaseType::Int | BaseType::String)
4035        ),
4036        _ => false,
4037    }
4038}
4039
4040/// v0.93 (ADR 0118 D4): index-hygiene **warnings** (non-failing, via ADR 0117).
4041/// Cross-references the agent's `@indexed(by: …)` declarations against the
4042/// equality `filter`s in its handlers:
4043///   - `bynk.index.missing` — an equality `filter` on a non-indexed keyable field
4044///     (the lookup scans; an index would route it);
4045///   - `bynk.index.unused` — a declared index no equality `filter` routes through
4046///     (it costs maintenance on every write).
4047///
4048/// These are perf hints, never compile gates (§11). The selectivity/ambiguity
4049/// tie-break (D5) and compound-predicate routing are a named follow-on, so a
4050/// single-equality predicate (the only shape routed today) is never ambiguous.
4051fn validate_index_hygiene(
4052    agent: &AgentDecl,
4053    types: &HashMap<String, Arc<TypeDecl>>,
4054    errors: &mut Vec<CompileError>,
4055) {
4056    let mut store_maps: HashSet<String> = HashSet::new();
4057    // map → declared (field, span-of-the-`by:`-argument)
4058    let mut declared: HashMap<String, Vec<(String, Span)>> = HashMap::new();
4059    // map → the value type's record fields (for the keyability check)
4060    let mut value_fields: HashMap<String, Vec<RecordField>> = HashMap::new();
4061    for f in &agent.store_fields {
4062        if f.kind.head.name != "Map" || f.kind.args.len() != 2 {
4063            continue;
4064        }
4065        store_maps.insert(f.name.name.clone());
4066        if let Some(TypeBody::Record(r)) = f
4067            .kind
4068            .args
4069            .get(1)
4070            .and_then(|v| match v {
4071                TypeRef::Named(id) => types.get(&id.name),
4072                _ => None,
4073            })
4074            .map(|d| &d.body)
4075        {
4076            value_fields.insert(f.name.name.clone(), r.fields.clone());
4077        }
4078        for an in f.annotations.iter().filter(|a| a.name.name == "indexed") {
4079            for arg in &an.args {
4080                if arg.label.as_ref().map(|l| l.name.as_str()) == Some("by")
4081                    && let ExprKind::Ident(k) = &arg.value.kind
4082                {
4083                    declared
4084                        .entry(f.name.name.clone())
4085                        .or_default()
4086                        .push((k.name.clone(), arg.value.span));
4087                }
4088            }
4089        }
4090    }
4091    if store_maps.is_empty() {
4092        return;
4093    }
4094    // Walk every handler body for equality filters in the routable position
4095    // (`<map>.filter((r) => r.f == …)`), recording the (map, field) pairs hit and
4096    // warning about a missing index the first time a field is filtered on.
4097    let mut used: HashSet<(String, String)> = HashSet::new();
4098    let mut missing_seen: HashSet<(String, String)> = HashSet::new();
4099    for h in &agent.handlers {
4100        walk_block_for_index_filters(&h.body, &store_maps, &mut |map, field, span| {
4101            used.insert((map.to_string(), field.to_string()));
4102            let is_declared = declared
4103                .get(map)
4104                .is_some_and(|v| v.iter().any(|(f, _)| f == field));
4105            if is_declared {
4106                return;
4107            }
4108            let keyable = value_fields.get(map).is_some_and(|fs| {
4109                fs.iter()
4110                    .any(|rf| rf.name.name == field && type_ref_is_keyable(&rf.type_ref, types))
4111            });
4112            if keyable && missing_seen.insert((map.to_string(), field.to_string())) {
4113                errors.push(
4114                    CompileError::new(
4115                        "bynk.index.missing",
4116                        span,
4117                        format!(
4118                            "a query filters `{map}` by equality on `{field}`, which is not indexed — add `@indexed(by: {field})` to route this lookup through an index instead of a scan"
4119                        ),
4120                    )
4121                    .with_note("a perf hint, not an error — the scan still compiles and runs"),
4122                );
4123            }
4124        });
4125    }
4126    // A declared index no equality filter routes through is dead maintenance.
4127    for (map, fields) in &declared {
4128        for (field, span) in fields {
4129            if !used.contains(&(map.clone(), field.clone())) {
4130                errors.push(
4131                    CompileError::new(
4132                        "bynk.index.unused",
4133                        *span,
4134                        format!(
4135                            "`@indexed(by: {field})` on `{map}` is never used — no query filters `{map}` by equality on `{field}`, yet the index is maintained on every write"
4136                        ),
4137                    )
4138                    .with_note("remove it, or add a query that filters by equality on this field"),
4139                );
4140            }
4141        }
4142    }
4143}
4144
4145/// `<map>.filter((r) => r.<field> == …)` with `map` a store map → `(map, field)`.
4146/// The routable equality-filter shape (the only one [`route_indexed_filter`]
4147/// lowers); deeper-in-a-chain filters cannot route, so they are not hygiene-relevant.
4148fn routable_eq_filter<'a>(
4149    store_maps: &HashSet<String>,
4150    e: &'a Expr,
4151) -> Option<(&'a str, &'a str, Span)> {
4152    let ExprKind::MethodCall {
4153        receiver,
4154        method,
4155        args,
4156        ..
4157    } = &e.kind
4158    else {
4159        return None;
4160    };
4161    if method.name != "filter" {
4162        return None;
4163    }
4164    let ExprKind::Ident(map) = &receiver.kind else {
4165        return None;
4166    };
4167    if !store_maps.contains(&map.name) {
4168        return None;
4169    }
4170    let [arg] = args.as_slice() else {
4171        return None;
4172    };
4173    let ExprKind::Lambda(lam) = &arg.kind else {
4174        return None;
4175    };
4176    let [param] = lam.params.as_slice() else {
4177        return None;
4178    };
4179    let pname = param.name.name.as_str();
4180    let ExprKind::BinOp(BinOp::Eq, lhs, rhs) = &lam.body.kind else {
4181        return None;
4182    };
4183    let field_of = |x: &'a Expr| -> Option<&'a str> {
4184        if let ExprKind::FieldAccess { receiver, field } = &x.kind
4185            && let ExprKind::Ident(r) = &receiver.kind
4186            && r.name == pname
4187        {
4188            Some(field.name.as_str())
4189        } else {
4190            None
4191        }
4192    };
4193    let field = field_of(lhs).or_else(|| field_of(rhs))?;
4194    Some((map.name.as_str(), field, e.span))
4195}
4196
4197/// Recurse a block, invoking `cb(map, field, span)` for each routable equality
4198/// filter found anywhere in it.
4199fn walk_block_for_index_filters(
4200    block: &Block,
4201    store_maps: &HashSet<String>,
4202    cb: &mut dyn FnMut(&str, &str, Span),
4203) {
4204    let mut exprs = Vec::new();
4205    for stmt in &block.statements {
4206        statement_exprs(stmt, &mut exprs);
4207    }
4208    exprs.push(&block.tail);
4209    for e in exprs {
4210        walk_expr_for_index_filters(e, store_maps, cb);
4211    }
4212}
4213
4214/// Recurse an expression, invoking `cb` for each routable equality filter.
4215/// Descends through `ast::expr_children` — the exhaustive total child
4216/// iterator — rather than a hand-matched recursion, so a future `ExprKind`
4217/// variant can't be silently skipped the way the old `_ => {}` here could.
4218fn walk_expr_for_index_filters(
4219    e: &Expr,
4220    store_maps: &HashSet<String>,
4221    cb: &mut dyn FnMut(&str, &str, Span),
4222) {
4223    if let Some((map, field, span)) = routable_eq_filter(store_maps, e) {
4224        cb(map, field, span);
4225    }
4226    for child in expr_children(e) {
4227        walk_expr_for_index_filters(child, store_maps, cb);
4228    }
4229}
4230
4231/// v0.81/v0.82 (storage track): validate an agent's `store`-field kinds and build
4232/// the per-kind scopes — `Cell` fields (name → element type; bare reads + `:=`)
4233/// and `Map` fields (name → (key, value) types; effectful entry ops, ADR 0110).
4234/// Unknown heads, bad arity, and not-yet-supported kinds are diagnosed.
4235#[allow(clippy::type_complexity)]
4236fn store_field_scopes(
4237    agent: &AgentDecl,
4238    types: &HashMap<String, Arc<TypeDecl>>,
4239    no_vars: &HashSet<String>,
4240    refs: &mut RefSink,
4241    errors: &mut Vec<CompileError>,
4242    tys: &Arc<Types>,
4243) -> (
4244    HashMap<String, TyId>,
4245    HashMap<String, (TyId, TyId)>,
4246    HashMap<String, TyId>,
4247    HashMap<String, (TyId, TyId, i64)>,
4248    HashMap<String, TyId>,
4249) {
4250    let mut cells: HashMap<String, TyId> = HashMap::new();
4251    let mut maps: HashMap<String, (TyId, TyId)> = HashMap::new();
4252    let mut sets: HashMap<String, TyId> = HashMap::new();
4253    let mut caches: HashMap<String, (TyId, TyId, i64)> = HashMap::new();
4254    let mut logs: HashMap<String, TyId> = HashMap::new();
4255    let arity_err = |f: &StoreField, kind: &str, want: usize, errors: &mut Vec<CompileError>| {
4256        errors.push(CompileError::new(
4257            "bynk.store.kind_arity",
4258            f.kind.span,
4259            format!(
4260                "`{kind}` takes exactly {want} type argument(s), found {}",
4261                f.kind.args.len()
4262            ),
4263        ));
4264    };
4265    for f in &agent.store_fields {
4266        let head = f.kind.head.name.as_str();
4267        if !STORAGE_KINDS.contains(&head) {
4268            errors.push(
4269                CompileError::new(
4270                    "bynk.store.unknown_kind",
4271                    f.kind.head.span,
4272                    format!(
4273                        "unknown storage kind `{head}` — expected one of {}",
4274                        STORAGE_KINDS.join(", ")
4275                    ),
4276                )
4277                .with_note("a `store` field's type is a storage kind, not an ordinary type"),
4278            );
4279            continue;
4280        }
4281        // v0.85 (ADR 0111): validate any `@…` annotations now the kind is known.
4282        validate_store_annotations(f, head, types, errors);
4283        match head {
4284            "Cell" => {
4285                if f.kind.args.len() != 1 {
4286                    arity_err(f, "Cell", 1, errors);
4287                    continue;
4288                }
4289                let elem = &f.kind.args[0];
4290                checker::record_type_refs(elem, types, no_vars, refs);
4291                if let Some(ty) = checker::resolve_type_ref(elem, types, tys) {
4292                    cells.insert(f.name.name.clone(), ty);
4293                }
4294            }
4295            "Map" => {
4296                if f.kind.args.len() != 2 {
4297                    arity_err(f, "Map", 2, errors);
4298                    continue;
4299                }
4300                checker::record_type_refs(&f.kind.args[0], types, no_vars, refs);
4301                checker::record_type_refs(&f.kind.args[1], types, no_vars, refs);
4302                check_store_keyable(&f.kind.args[0], "a `Map` key", types, errors);
4303                if let (Some(k), Some(v)) = (
4304                    checker::resolve_type_ref(&f.kind.args[0], types, tys),
4305                    checker::resolve_type_ref(&f.kind.args[1], types, tys),
4306                ) {
4307                    maps.insert(f.name.name.clone(), (k, v));
4308                }
4309            }
4310            "Set" => {
4311                if f.kind.args.len() != 1 {
4312                    arity_err(f, "Set", 1, errors);
4313                    continue;
4314                }
4315                let elem = &f.kind.args[0];
4316                checker::record_type_refs(elem, types, no_vars, refs);
4317                check_store_keyable(elem, "a `Set` element", types, errors);
4318                if let Some(ty) = checker::resolve_type_ref(elem, types, tys) {
4319                    sets.insert(f.name.name.clone(), ty);
4320                }
4321            }
4322            // v0.87 (ADR 0113): `Cache[K, V]` — a `Map` with per-entry TTL.
4323            "Cache" => {
4324                if f.kind.args.len() != 2 {
4325                    arity_err(f, "Cache", 2, errors);
4326                    continue;
4327                }
4328                checker::record_type_refs(&f.kind.args[0], types, no_vars, refs);
4329                checker::record_type_refs(&f.kind.args[1], types, no_vars, refs);
4330                check_store_keyable(&f.kind.args[0], "a `Cache` key", types, errors);
4331                // A `Cache` requires `@ttl(<Duration>)`; its millisecond value is
4332                // the entry lifetime. Absent → steer the author to a `Map`.
4333                let ttl = cache_ttl_millis(f, errors);
4334                if let (Some(k), Some(v), Some(ttl)) = (
4335                    checker::resolve_type_ref(&f.kind.args[0], types, tys),
4336                    checker::resolve_type_ref(&f.kind.args[1], types, tys),
4337                    ttl,
4338                ) {
4339                    caches.insert(f.name.name.clone(), (k, v, ttl));
4340                }
4341            }
4342            // v0.95 (ADR 0121): `Log[T]` — an append-only, time-indexed sequence.
4343            // The element type drives `append` and the lazy `Query[T]` read surface;
4344            // `@retain` (optional) is read by the emitter, not needed here.
4345            "Log" => {
4346                if f.kind.args.len() != 1 {
4347                    arity_err(f, "Log", 1, errors);
4348                    continue;
4349                }
4350                let elem = &f.kind.args[0];
4351                checker::record_type_refs(elem, types, no_vars, refs);
4352                if let Some(t) = checker::resolve_type_ref(elem, types, tys) {
4353                    logs.insert(f.name.name.clone(), t);
4354                }
4355            }
4356            other => {
4357                errors.push(
4358                    CompileError::new(
4359                        "bynk.store.kind_unsupported",
4360                        f.kind.head.span,
4361                        format!(
4362                            "storage kind `{other}` is not yet supported — use `Cell`, `Map`, \
4363                             `Set`, `Cache` or `Log`"
4364                        ),
4365                    )
4366                    .with_note("`Queue` is the one storage kind with no implementation yet"),
4367                );
4368            }
4369        }
4370    }
4371    (cells, maps, sets, caches, logs)
4372}
4373
4374/// v0.87 (ADR 0113 D2): a `Cache` field must carry `@ttl(<Duration literal>)`;
4375/// return its value in milliseconds. A missing `@ttl`, or one present whose
4376/// first argument isn't itself a `Duration` literal (`@ttl(5)`, or
4377/// `@ttl(-5.minutes)` — unary negation over a `DurationLit` is not one), is
4378/// `bynk.store.cache_ttl_required`. Grounded during P6.7's own review
4379/// (#1163): no annotation-argument checker validates `@ttl`'s shape anywhere
4380/// else — this doc comment previously claimed otherwise — so leaving the
4381/// malformed case undiagnosed would let a `Cache` field with no resolvable
4382/// TTL reach a certified program.
4383fn cache_ttl_millis(f: &StoreField, errors: &mut Vec<CompileError>) -> Option<i64> {
4384    let ttl = f.annotations.iter().find(|a| a.name.name == "ttl");
4385    let Some(ttl) = ttl else {
4386        errors.push(
4387            CompileError::new(
4388                "bynk.store.cache_ttl_required",
4389                f.kind.span,
4390                "a `Cache` field requires a `@ttl(<duration>)` annotation — its entry lifetime",
4391            )
4392            .with_note("a keyed store with no expiry is a `Map`, not a `Cache`"),
4393        );
4394        return None;
4395    };
4396    match ttl.args.first().map(|a| &a.value.kind) {
4397        Some(ExprKind::DurationLit { millis, .. }) => Some(*millis),
4398        _ => {
4399            let span = ttl.args.first().map_or(ttl.span, |a| a.span);
4400            errors.push(
4401                CompileError::new(
4402                    "bynk.store.cache_ttl_required",
4403                    span,
4404                    "`@ttl`'s argument must be a duration literal, e.g. `5.minutes`, or a `Duration` constant bound to one",
4405                )
4406                .with_note("a keyed store with no expiry is a `Map`, not a `Cache`"),
4407            );
4408            None
4409        }
4410    }
4411}
4412
4413#[allow(clippy::too_many_arguments)]
4414fn check_agent_decls(
4415    typed: &mut checker::TypedCommons,
4416    table: &UnitTable,
4417    cross_context: &resolver::CrossContextInfo,
4418    is_context: bool,
4419    uses_commons_type_names: &HashSet<String>,
4420    capability_info_map: &HashMap<String, CapabilityInfo>,
4421    no_vars: &HashSet<String>,
4422    refs: &mut RefSink,
4423    hints: &mut HintSink,
4424    locals: &mut LocalsSink,
4425    requirements: &mut RequirementSink,
4426    errors: &mut Vec<CompileError>,
4427    tys: &Arc<Types>,
4428) {
4429    for agent in table.agents.values() {
4430        refs.set_owner(&agent.name.name);
4431        // v0.81 (storage track, emission slice — ADR 0109): `store` `Cell` fields
4432        // are checked (kind validity, bare reads, the `:=` write form, invariant
4433        // resolution) *and* emitted — the cells form the agent's state record,
4434        // written through a staged working copy committed atomically at handler
4435        // end. `store_cells` maps each `Cell` field to its element type, for the
4436        // bare-read scope and the `:=`/invariant checks below.
4437        #[allow(clippy::type_complexity)]
4438        let (store_cells, store_maps, store_sets, store_caches, store_logs): (
4439            HashMap<String, TyId>,
4440            HashMap<String, (TyId, TyId)>,
4441            HashMap<String, TyId>,
4442            HashMap<String, (TyId, TyId, i64)>,
4443            HashMap<String, TyId>,
4444        ) = if agent.store_fields.is_empty() {
4445            (
4446                HashMap::new(),
4447                HashMap::new(),
4448                HashMap::new(),
4449                HashMap::new(),
4450                HashMap::new(),
4451            )
4452        } else {
4453            store_field_scopes(agent, &typed.types, no_vars, refs, errors, tys)
4454        };
4455        // v0.93 (ADR 0118 D4): index-hygiene warnings cross-reference `@indexed`
4456        // declarations against the equality filters in the handlers.
4457        validate_index_hygiene(agent, &typed.types, errors);
4458        // v0.25: the agent's key type and store field types reference types.
4459        checker::record_type_refs(&agent.key_type, &typed.types, no_vars, refs);
4460        for field in &agent.store_fields {
4461            for arg in &field.kind.args {
4462                checker::record_type_refs(arg, &typed.types, no_vars, refs);
4463            }
4464        }
4465        // The agent's `Cell` fields form its state record. Expose that record
4466        // under the name `<AgentName>State` in the type table so the body and
4467        // invariants can be checked against it.
4468        let agent_state_name = format!("{}State", agent.name.name);
4469        // #1697: the state record is a name the agent's handlers and invariants
4470        // can write, so a user type of the same name would be silently replaced
4471        // there by the record (and collide with its interface in the emitted
4472        // module). Reject it instead.
4473        if let Some(user) = table.types.get(&agent_state_name) {
4474            errors.push(
4475                CompileError::new(
4476                    "bynk.agent.state_name_conflict",
4477                    user.name.span,
4478                    format!(
4479                        "type `{agent_state_name}` has the name of agent `{}`'s state record",
4480                        agent.name.name
4481                    ),
4482                )
4483                .with_note(format!(
4484                    "inside `{}`'s handlers, `{agent_state_name}` is the record of its `Cell` fields, so this type would be replaced there; rename it",
4485                    agent.name.name
4486                )),
4487            );
4488        }
4489        let state_record_fields: Vec<RecordField> = agent
4490            .store_fields
4491            .iter()
4492            .filter(|f| f.kind.head.name == "Cell" && f.kind.args.len() == 1)
4493            .map(|f| RecordField {
4494                annotations: Vec::new(),
4495                documentation: None,
4496                trivia: Default::default(),
4497                name: f.name.clone(),
4498                type_ref: f.kind.args[0].clone(),
4499                refinement: None,
4500                init: f.init.clone(),
4501                span: f.span,
4502            })
4503            .collect();
4504        // Build a synthetic Record TypeDecl and stuff it into a *clone* of
4505        // the resolved types so handler bodies see it.
4506        let synthetic_state = TypeDecl {
4507            derives: Vec::new(),
4508            derives_kw: None,
4509            name: Ident {
4510                name: agent_state_name.clone(),
4511                span: agent.span,
4512            },
4513            type_params: Vec::new(),
4514            body: TypeBody::Record(RecordBody {
4515                trailing_comments: Default::default(),
4516                fields: state_record_fields,
4517                span: agent.span,
4518            }),
4519            documentation: None,
4520            span: agent.span,
4521            trivia: Trivia::default(),
4522            private: None,
4523        };
4524        let mut types_for_handler = typed.types.clone();
4525        types_for_handler.insert(agent_state_name.clone(), Arc::new(synthetic_state.clone()));
4526        // `local_type_names` is derived from `table.types` (the pre-merge
4527        // local table), NOT `types_for_handler` (local+uses+consumes, plus
4528        // the synthetic state record) — reusing the merged table here was
4529        // review finding #9: it silently over-widened `.raw`/`.unsafe()`/
4530        // owner-only-event-emission to any consumed/used type inside an
4531        // agent handler body, making all three gates unreachable there.
4532        let resolved_for_handler = ResolvedCommons::new(
4533            typed.commons.clone(),
4534            types_for_handler,
4535            &table.types,
4536            typed.fns.clone(),
4537            typed.methods.clone(),
4538            table.agents.clone(),
4539            &table.events,
4540            cross_context.clone(),
4541            HashMap::new(),
4542            is_context,
4543            uses_commons_type_names.clone(),
4544        )
4545        .with_local_fns(&table.fns)
4546        // #1883, slice 1a: a handler body sees the unit's assets too.
4547        .with_assets(typed.assets.clone())
4548        .with_embeds(typed.embeds.clone())
4549        .with_consts(typed.consts.clone())
4550        .with_shadowed_imports(typed.shadowed_imports.clone())
4551        .with_scope_facts_of(typed)
4552        .with_stability(typed.stability.clone());
4553        // v0.81: the fresh-key rule for `store Cell[T]` fields — an
4554        // initialiser is checked against the element type `T` (which also types
4555        // the init expression so the emitter can qualify variant constructors),
4556        // and a field with neither an initialiser nor an implicit zero is rejected.
4557        for field in &agent.store_fields {
4558            if field.kind.head.name != "Cell" || field.kind.args.len() != 1 {
4559                continue; // non-Cell / malformed kinds are diagnosed elsewhere
4560            }
4561            let elem = &field.kind.args[0];
4562            if let Some(init) = &field.init {
4563                checker::check_state_initialiser(
4564                    init,
4565                    elem,
4566                    &resolved_for_handler,
4567                    tys,
4568                    &mut typed.expr_types,
4569                    &mut typed.callees,
4570                    errors,
4571                    refs,
4572                    hints,
4573                    locals,
4574                );
4575            } else if !checker::is_zeroable(elem, None, &typed.types) {
4576                errors.push(
4577                    CompileError::new(
4578                        "bynk.agents.non_zeroable_state_field",
4579                        field.span,
4580                        format!(
4581                            "agent `{}` store cell `{}` has no defined zero value, so a fresh \
4582                             key cannot be initialised",
4583                            agent.name.name, field.name.name
4584                        ),
4585                    )
4586                    .with_note(
4587                        "add an initialiser (`store name: Cell[T] = value`), or use \
4588                         `Cell[Option[…]]` (None means \"never set\")",
4589                    ),
4590                );
4591            }
4592        }
4593        let state_ty = tys.intern(Ty::Named {
4594            name: agent_state_name.clone(),
4595            kind: checker::NamedKind::Record,
4596            args: Vec::new(),
4597        });
4598        let key_ty = checker::resolve_type_ref(&agent.key_type, &typed.types, tys)
4599            .unwrap_or_else(|| tys.intern(Ty::Unit));
4600        let mut self_scope: HashMap<String, TyId> = HashMap::new();
4601        // `self` is a synthetic record carrying the agent's key field, so that
4602        // `self.<key>` resolves. The parser treats `self.x` as FieldAccess on
4603        // Ident("self"), so `self` is given a one-off synthetic record type.
4604        let agent_self_name = format!("__{}Self", agent.name.name);
4605        let self_decl = TypeDecl {
4606            derives: Vec::new(),
4607            derives_kw: None,
4608            name: Ident {
4609                name: agent_self_name.clone(),
4610                span: agent.span,
4611            },
4612            type_params: Vec::new(),
4613            body: TypeBody::Record(RecordBody {
4614                trailing_comments: Default::default(),
4615                fields: vec![RecordField {
4616                    annotations: Vec::new(),
4617                    documentation: None,
4618                    trivia: Default::default(),
4619                    name: Ident {
4620                        name: agent.key_name.name.clone(),
4621                        span: agent.key_name.span,
4622                    },
4623                    type_ref: agent.key_type.clone(),
4624                    refinement: None,
4625                    init: None,
4626                    span: agent.key_name.span,
4627                }],
4628                span: agent.span,
4629            }),
4630            documentation: None,
4631            span: agent.span,
4632            trivia: Trivia::default(),
4633            private: None,
4634        };
4635        let mut types_for_handler = resolved_for_handler.types.clone();
4636        types_for_handler.insert(agent_self_name.clone(), Arc::new(self_decl.clone()));
4637        // Same fix as above: `local_type_names` comes from `table.types`
4638        // (pre-merge), not `types_for_handler` (merged, plus the synthetic
4639        // `self` record type).
4640        let resolved_for_handler = ResolvedCommons::new(
4641            typed.commons.clone(),
4642            types_for_handler,
4643            &table.types,
4644            typed.fns.clone(),
4645            typed.methods.clone(),
4646            table.agents.clone(),
4647            &table.events,
4648            cross_context.clone(),
4649            HashMap::new(),
4650            is_context,
4651            uses_commons_type_names.clone(),
4652        )
4653        .with_local_fns(&table.fns)
4654        // #1883, slice 1a: a handler body sees the unit's assets too.
4655        .with_assets(typed.assets.clone())
4656        .with_embeds(typed.embeds.clone())
4657        .with_consts(typed.consts.clone())
4658        .with_shadowed_imports(typed.shadowed_imports.clone())
4659        .with_scope_facts_of(typed)
4660        .with_stability(typed.stability.clone());
4661        self_scope.insert(
4662            "self".to_string(),
4663            tys.intern(Ty::Named {
4664                name: agent_self_name.clone(),
4665                kind: checker::NamedKind::Record,
4666                args: Vec::new(),
4667            }),
4668        );
4669        // v0.81: each `Cell` store field is a bare local of its element type
4670        // (implicit deref in read position); the `:=` write form is checked
4671        // separately against `store_cells`.
4672        for (name, ty) in &store_cells {
4673            self_scope.insert(name.clone(), *ty);
4674        }
4675        let _ = key_ty;
4676
4677        // Finding #36: `check_handler_body` takes the five kind-scopes as one
4678        // `HashMap<String, StoreField>` — a field name is only ever one kind,
4679        // so recombine them here rather than threading five parallel maps.
4680        let store_fields: HashMap<String, checker::StoreField> = store_cells
4681            .iter()
4682            .map(|(name, t)| (name.clone(), checker::StoreField::Cell(*t)))
4683            .chain(
4684                store_maps
4685                    .iter()
4686                    .map(|(name, (k, v))| (name.clone(), checker::StoreField::Map(*k, *v))),
4687            )
4688            .chain(
4689                store_sets
4690                    .iter()
4691                    .map(|(name, t)| (name.clone(), checker::StoreField::Set(*t))),
4692            )
4693            .chain(store_caches.iter().map(|(name, (k, v, ttl))| {
4694                (name.clone(), checker::StoreField::Cache(*k, *v, *ttl))
4695            }))
4696            .chain(
4697                store_logs
4698                    .iter()
4699                    .map(|(name, t)| (name.clone(), checker::StoreField::Log(*t))),
4700            )
4701            .collect();
4702
4703        // v0.80/v0.81: invariant well-formedness — predicates are pure `Bool`
4704        // expressions over the agent's `store` cells (§14, ADR 0108 D5).
4705        checker::check_invariants(
4706            &agent.invariants,
4707            &store_cells,
4708            &agent.name.name,
4709            &resolved_for_handler,
4710            tys,
4711            &mut typed.expr_types,
4712            errors,
4713            refs,
4714            hints,
4715            locals,
4716            requirements,
4717            &mut typed.callees,
4718        );
4719
4720        // v0.116 (testing track slice 4): step invariants — predicates over the
4721        // `old`/`new` state pair, checked against the synthetic state record.
4722        checker::check_transitions(
4723            &agent.transitions,
4724            state_ty,
4725            &agent.name.name,
4726            &resolved_for_handler,
4727            &mut typed.expr_types,
4728            errors,
4729            refs,
4730            hints,
4731            locals,
4732            requirements,
4733            &mut typed.callees,
4734            tys,
4735        );
4736
4737        // State-migrations S2 (#2224): an old type's field defaults stand in for
4738        // an initialiser that field had (Decision C). They are spliced into the
4739        // old type's own decoder, so they follow an event default's rules.
4740        for step in &agent.migrations {
4741            let Some(TypeRef::Named(id)) = step.old.as_ref().map(|o| &o.type_ref) else {
4742                continue;
4743            };
4744            let Some(decl) = resolved_for_handler.types.get(&id.name).cloned() else {
4745                continue;
4746            };
4747            let TypeBody::Record(r) = &decl.body else {
4748                continue;
4749            };
4750            for field in &r.fields {
4751                let Some(init) = &field.init else {
4752                    continue;
4753                };
4754                let before = errors.len();
4755                checker::check_event_field_default(
4756                    init,
4757                    &field.type_ref,
4758                    "old-state field default",
4759                    &resolved_for_handler,
4760                    tys,
4761                    &mut typed.expr_types,
4762                    &mut typed.callees,
4763                    errors,
4764                    refs,
4765                    hints,
4766                    locals,
4767                );
4768                if errors.len() > before {
4769                    continue;
4770                }
4771                if let Err(reason) = crate::wire_default::lower_event_field_default_wire(
4772                    init,
4773                    &field.type_ref,
4774                    &resolved_for_handler.types,
4775                ) {
4776                    errors.push(CompileError::new(
4777                        "bynk.types.bad_field_default",
4778                        init.span,
4779                        format!(
4780                            "old-state field `{}`'s default cannot be represented on the wire: \
4781                             {reason}",
4782                            field.name.name
4783                        ),
4784                    ));
4785                }
4786            }
4787        }
4788
4789        // State-migrations S2 (#2224): each `migrate` step's body, on its own
4790        // terms (purity, key-free, `:=` targets, record-literal semantics).
4791        // The lock-dependent checks run in the schema-registry reconcile.
4792        checker::check_migrations(
4793            agent,
4794            &store_cells,
4795            &resolved_for_handler.types,
4796            &resolved_for_handler,
4797            tys,
4798            &mut typed.expr_types,
4799            errors,
4800            refs,
4801            hints,
4802            locals,
4803            requirements,
4804            &mut typed.callees,
4805        );
4806        // #2221: a move a handler can make that a `transition` refuses at
4807        // commit, from the agent state model the editor's state view also
4808        // reads. The type table is the agent's own (local, `uses` and
4809        // `consumes`), so a state type declared elsewhere is still seen.
4810        errors.extend(crate::agent_state::may_violate_diagnostics(
4811            agent,
4812            &resolved_for_handler.types,
4813        ));
4814
4815        for handler in &agent.handlers {
4816            // v0.99 (DECISION H): `by` is a service-edge clause — it establishes
4817            // the actor (`identity`/`who`) from the inbound request. An agent
4818            // `on call` handler is reached across the agent boundary by the
4819            // factory (`__makeAgent`), never from an ingress, so it has no actor
4820            // and the parser-accepted `by` clause would silently be dropped.
4821            // Rejecting it turns the deps-split taxonomy's "actor auth never
4822            // crosses the agent boundary" guarantee into an enforced invariant.
4823            if let Some(by) = &handler.by_clause {
4824                errors.push(
4825                    CompileError::new(
4826                        "bynk.actor.by_on_agent",
4827                        by.span,
4828                        "`by` is a service-edge clause; an agent handler has no actor",
4829                    )
4830                    .with_note(
4831                        "an agent `on call` handler is invoked across the agent boundary, not \
4832                         from an ingress — remove the `by` clause",
4833                    ),
4834                );
4835            }
4836            let mut handler_caps: HashMap<String, CapabilityInfo> = HashMap::new();
4837            for cap_ref in &handler.given {
4838                if let Some(info) =
4839                    resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
4840                {
4841                    handler_caps.insert(cap_ref.key().to_string(), info);
4842                }
4843            }
4844            // The handler return type must be Effect[T].
4845            if !matches!(handler.return_type, TypeRef::Effect(_, _)) {
4846                errors.push(CompileError::new(
4847                    "bynk.agent.return_not_effect",
4848                    handler.return_type.span(),
4849                    format!(
4850                        "agent handler must return `Effect[T]`, but got `{}`",
4851                        ts_type_ref_display(&handler.return_type)
4852                    ),
4853                ));
4854            }
4855            checker::check_handler_body(
4856                &resolved_for_handler,
4857                checker::HandlerBodyCheck {
4858                    capabilities: handler_caps,
4859                    declared_capabilities: capability_info_map.clone(),
4860                    agent_state_ty: Some(state_ty),
4861                    agent_self_scope: Some(self_scope.clone()),
4862                    given_anchor: Some(handler.return_type.span()),
4863                    report_unused: true,
4864                    store_fields: store_fields.clone(),
4865                    ..checker::HandlerBodyCheck::new(
4866                        &handler.body,
4867                        &handler.return_type,
4868                        &handler.params,
4869                        &handler.given,
4870                    )
4871                },
4872                checker::CheckSinks {
4873                    tys,
4874                    expr_types: &mut typed.expr_types,
4875                    errors,
4876                    refs,
4877                    hints,
4878                    locals,
4879                    requirements,
4880                    callees: &mut typed.callees,
4881                },
4882            );
4883        }
4884    }
4885}
4886
4887/// A service's CORS checks: its `cors { }` policy (ADR 0159) and, #3329, the
4888/// cross-site cookie warning that depends on it.
4889fn validate_service_cors(service: &ServiceDecl, errors: &mut Vec<CompileError>) {
4890    if let Some(policy) = &service.cors {
4891        validate_cors_policy(service, policy, errors);
4892    }
4893    warn_cross_site_cookie_without_credentials(service, errors);
4894}
4895
4896/// #3329 (`bynk.http.cookie_cross_site_without_credentials`, a warning): a
4897/// `from http` service whose handlers attach a `Cookie { … sameSite:
4898/// SameSite.Unrestricted … }` (`withCookie`/`clearCookie`) but whose `cors`
4899/// policy lacks `credentials: true` (or that has none). The browser withholds
4900/// the cookie from credential-less cross-site requests, so it can never return.
4901fn warn_cross_site_cookie_without_credentials(
4902    service: &ServiceDecl,
4903    errors: &mut Vec<CompileError>,
4904) {
4905    if !matches!(service.protocol, ServiceProtocol::Http) {
4906        return;
4907    }
4908    if service.cors.as_ref().is_some_and(|c| c.credentials()) {
4909        return;
4910    }
4911    let mut hit: Option<Span> = None;
4912    for handler in &service.handlers {
4913        let mut exprs: Vec<&Expr> = Vec::new();
4914        for s in &handler.body.statements {
4915            bynk_syntax::ast::statement_exprs(s, &mut exprs);
4916        }
4917        exprs.push(&handler.body.tail);
4918        let mut visit = |e: &Expr| {
4919            if hit.is_some() {
4920                return;
4921            }
4922            let ExprKind::MethodCall { method, args, .. } = &e.kind else {
4923                return;
4924            };
4925            if method.name != "withCookie" && method.name != "clearCookie" {
4926                return;
4927            }
4928            let Some(arg) = args.first() else { return };
4929            let ExprKind::RecordConstruction {
4930                type_name, fields, ..
4931            } = &arg.kind
4932            else {
4933                return;
4934            };
4935            let unrestricted = type_name.name == "Cookie" && fields.iter().any(|f| {
4936                f.name.name == "sameSite"
4937                    && matches!(
4938                        f.value.as_ref().map(|v| &v.kind),
4939                        Some(ExprKind::FieldAccess { field, .. }) if field.name == "Unrestricted"
4940                    )
4941            });
4942            if unrestricted {
4943                hit = Some(arg.span);
4944            }
4945        };
4946        fn walk(e: &Expr, f: &mut dyn FnMut(&Expr)) {
4947            f(e);
4948            for c in bynk_syntax::ast::expr_children(e) {
4949                walk(c, f);
4950            }
4951        }
4952        for e in exprs {
4953            walk(e, &mut visit);
4954        }
4955        if hit.is_some() {
4956            break;
4957        }
4958    }
4959    let Some(span) = hit else { return };
4960    errors.push(
4961        CompileError::new(
4962            "bynk.http.cookie_cross_site_without_credentials",
4963            span,
4964            format!(
4965                "service `{}` sets a `SameSite.Unrestricted` cookie but does not declare `cors {{ credentials: true }}`, so a cross-origin `fetch` can never send it back",
4966                service.name.name
4967            ),
4968        )
4969        .with_note(
4970            "add `cors { origins: [...], credentials: true }` if a page on another origin must send it back; a cookie used only in cross-site navigations, embeds or SSO callbacks needs no `cors`, and `SameSite.Lax` suits one that need not cross sites",
4971        ),
4972    );
4973}
4974
4975/// Validate a service's `cors { }` policy (v0.131, ADR 0159). The grammar is
4976/// lenient — any `name: value` field parses — so the checker is where the closed
4977/// field set, the value shapes, and the spec-mandated wildcard/credentials
4978/// constraint (DECISION F) are enforced.
4979fn validate_cors_policy(
4980    service: &ServiceDecl,
4981    policy: &CorsPolicy,
4982    errors: &mut Vec<CompileError>,
4983) {
4984    // CORS is a browser-facing HTTP concern; it is meaningless on any other
4985    // protocol.
4986    if !matches!(service.protocol, ServiceProtocol::Http) {
4987        errors.push(
4988            CompileError::new(
4989                "bynk.http.cors_not_http",
4990                policy.span,
4991                "a `cors { }` policy is only valid on a `from http` service",
4992            )
4993            .with_note("CORS governs cross-origin browser access, which only the HTTP surface has"),
4994        );
4995        return;
4996    }
4997
4998    // Field names are a closed set; flag anything else (the parser accepts any
4999    // name, per the annotation precedent).
5000    for field in &policy.fields {
5001        if !matches!(
5002            field.name.name.as_str(),
5003            "origins" | "headers" | "credentials" | "maxAge"
5004        ) {
5005            errors.push(
5006                CompileError::new(
5007                    "bynk.http.cors_unknown_field",
5008                    field.name.span,
5009                    format!("unknown `cors` field `{}`", field.name.name),
5010                )
5011                .with_note("known fields are `origins`, `headers`, `credentials`, and `maxAge`"),
5012            );
5013        }
5014    }
5015
5016    // `origins` is required and must be a non-empty list of string literals.
5017    match policy.field("origins") {
5018        None => errors.push(CompileError::new(
5019            "bynk.http.cors_invalid_origins",
5020            policy.span,
5021            "a `cors { }` policy must declare `origins` — the allowed origins, or `[\"*\"]`",
5022        )),
5023        Some(expr) => match &expr.kind {
5024            ExprKind::ListLit(items, ..) if !items.is_empty() => {
5025                for item in items {
5026                    if !matches!(item.kind, ExprKind::StrLit(_)) {
5027                        errors.push(CompileError::new(
5028                            "bynk.http.cors_invalid_origins",
5029                            item.span,
5030                            "each `cors` origin must be a string literal (e.g. \"https://app.example.com\" or \"*\")",
5031                        ));
5032                    }
5033                }
5034            }
5035            _ => errors.push(CompileError::new(
5036                "bynk.http.cors_invalid_origins",
5037                expr.span,
5038                "`cors` `origins` must be a non-empty list of string literals",
5039            )),
5040        },
5041    }
5042
5043    // `headers`, when present, is a list of string literals.
5044    if let Some(expr) = policy.field("headers") {
5045        let ok = matches!(&expr.kind, ExprKind::ListLit(items, ..)
5046            if items.iter().all(|i| matches!(i.kind, ExprKind::StrLit(_))));
5047        if !ok {
5048            errors.push(CompileError::new(
5049                "bynk.http.cors_invalid_field",
5050                expr.span,
5051                "`cors` `headers` must be a list of string literals",
5052            ));
5053        }
5054    }
5055
5056    // `credentials`, when present, is a boolean literal.
5057    if let Some(expr) = policy.field("credentials")
5058        && !matches!(expr.kind, ExprKind::BoolLit(_))
5059    {
5060        errors.push(CompileError::new(
5061            "bynk.http.cors_invalid_field",
5062            expr.span,
5063            "`cors` `credentials` must be `true` or `false`",
5064        ));
5065    }
5066
5067    // `maxAge`, when present, is a `Duration` literal.
5068    if let Some(expr) = policy.field("maxAge")
5069        && !matches!(expr.kind, ExprKind::DurationLit { .. })
5070    {
5071        errors.push(CompileError::new(
5072            "bynk.http.cors_invalid_field",
5073            expr.span,
5074            "`cors` `maxAge` must be a `Duration` literal (e.g. `1.hour`)",
5075        ));
5076    }
5077
5078    // DECISION F: the Fetch spec forbids `Access-Control-Allow-Credentials: true`
5079    // with a wildcard origin — the browser rejects it at runtime, so catch it at
5080    // compile time.
5081    if policy.credentials() && policy.is_wildcard() {
5082        errors.push(
5083            CompileError::new(
5084                "bynk.http.cors_wildcard_credentials",
5085                policy.span,
5086                "`cors` cannot combine `credentials: true` with the wildcard origin `[\"*\"]`",
5087            )
5088            .with_note(
5089                "the Fetch spec forbids credentialed requests against a wildcard origin — \
5090                 list the exact origins instead",
5091            ),
5092        );
5093    }
5094}
5095
5096/// v0.141 (ADR 0164): validate a service's `security { }` policy. Security
5097/// response headers are wire behaviour of the browser-facing HTTP surface, so the
5098/// section is only legal on a `from http` service; the field vocabulary is the
5099/// closed set `hsts`/`nosniff`; `hsts` is a *positive* `Duration` (the same rule
5100/// `@cache maxAge` uses) and `nosniff` a `Bool`.
5101fn validate_security_policy(
5102    service: &ServiceDecl,
5103    policy: &SecurityPolicy,
5104    errors: &mut Vec<CompileError>,
5105) {
5106    // Security headers are a browser-facing HTTP concern; they are meaningless on
5107    // any other protocol (mirrors the `cors_not_http` gate).
5108    if !matches!(service.protocol, ServiceProtocol::Http) {
5109        errors.push(
5110            CompileError::new(
5111                "bynk.http.security_not_http",
5112                policy.span,
5113                "a `security { }` policy is only valid on a `from http` service",
5114            )
5115            .with_note(
5116                "security response headers govern the browser-facing HTTP surface, \
5117                 which only a `from http` service has",
5118            ),
5119        );
5120        return;
5121    }
5122
5123    // Field names are a closed set; flag anything else (the parser accepts any
5124    // name, per the CORS / annotation precedent).
5125    for field in &policy.fields {
5126        if !matches!(field.name.name.as_str(), "hsts" | "nosniff") {
5127            errors.push(
5128                CompileError::new(
5129                    "bynk.http.security_unknown_field",
5130                    field.name.span,
5131                    format!("unknown `security` field `{}`", field.name.name),
5132                )
5133                .with_note("known fields are `hsts` and `nosniff`"),
5134            );
5135        }
5136    }
5137
5138    // `hsts`, when present, is a *positive* `Duration` literal — HSTS with a
5139    // zero/negative `max-age` is nonsensical (0 would actively *clear* the pin).
5140    if let Some(expr) = policy.field("hsts")
5141        && !matches!(&expr.kind, ExprKind::DurationLit { millis, .. } if *millis > 0)
5142    {
5143        errors.push(CompileError::new(
5144            "bynk.http.security_invalid_field",
5145            expr.span,
5146            "`security` `hsts` must be a positive `Duration` literal (e.g. `180.days`)",
5147        ));
5148    }
5149
5150    // `nosniff`, when present, is a boolean literal.
5151    if let Some(expr) = policy.field("nosniff")
5152        && !matches!(expr.kind, ExprKind::BoolLit(_))
5153    {
5154        errors.push(CompileError::new(
5155            "bynk.http.security_invalid_field",
5156            expr.span,
5157            "`security` `nosniff` must be `true` or `false`",
5158        ));
5159    }
5160}
5161
5162/// v0.142 (ADR 0165): validate a service's `limits { }` policy. A request-body
5163/// ceiling is wire behaviour of the HTTP surface, so the section is only legal on
5164/// a `from http` service; the field vocabulary is the closed set `maxBody`; and
5165/// `maxBody` is a *positive* `Int` byte count (there is no `Size` literal yet — a
5166/// `1.mb`-style literal is a named follow-on, so v1 takes an `Int`).
5167fn validate_limits_policy(
5168    service: &ServiceDecl,
5169    policy: &LimitsPolicy,
5170    errors: &mut Vec<CompileError>,
5171) {
5172    // A request-body ceiling is an HTTP-surface concern; it is meaningless on any
5173    // other protocol (mirrors the `cors_not_http` / `security_not_http` gate).
5174    if !matches!(service.protocol, ServiceProtocol::Http) {
5175        errors.push(
5176            CompileError::new(
5177                "bynk.http.limits_not_http",
5178                policy.span,
5179                "a `limits { }` policy is only valid on a `from http` service",
5180            )
5181            .with_note(
5182                "a request-body size ceiling governs the HTTP surface, \
5183                 which only a `from http` service has",
5184            ),
5185        );
5186        return;
5187    }
5188
5189    // Field names are a closed set; flag anything else (the parser accepts any
5190    // name, per the CORS / security / annotation precedent).
5191    for field in &policy.fields {
5192        if !matches!(field.name.name.as_str(), "maxBody" | "maxFile" | "maxParts") {
5193            errors.push(
5194                CompileError::new(
5195                    "bynk.http.limits_unknown_field",
5196                    field.name.span,
5197                    format!("unknown `limits` field `{}`", field.name.name),
5198                )
5199                .with_note("the fields are `maxBody`, and (for `@multipart` routes) `maxFile` and `maxParts`"),
5200            );
5201        }
5202    }
5203    // #3276: `maxFile` and `maxParts` are positive `Int` counts too.
5204    for name in ["maxFile", "maxParts"] {
5205        if let Some(expr) = policy.field(name)
5206            && !matches!(&expr.kind, ExprKind::IntLit { value: n, .. } if *n > 0)
5207        {
5208            errors.push(CompileError::new(
5209                "bynk.http.limits_invalid_field",
5210                expr.span,
5211                format!("`limits` `{name}` must be a positive `Int` literal"),
5212            ));
5213        }
5214    }
5215
5216    // `maxBody`, when present, is a *positive* `Int` literal — a byte count. Zero
5217    // or a negative ceiling is nonsensical (it would reject every request). There
5218    // is no byte `Size` literal yet, so v1 takes a plain `Int` (ADR 0165
5219    // DECISION C).
5220    if let Some(expr) = policy.field("maxBody")
5221        && !matches!(&expr.kind, ExprKind::IntLit { value: n, .. } if *n > 0)
5222    {
5223        errors.push(CompileError::new(
5224            "bynk.http.limits_invalid_field",
5225            expr.span,
5226            "`limits` `maxBody` must be a positive `Int` literal — a byte count (e.g. `1_048_576`)",
5227        ));
5228    }
5229}
5230
5231/// #2858: validate a service's `json { }` policy. The response encoding is a
5232/// property of the HTTP surface, so the section is only legal on a `from http`
5233/// service; the closed field set is `options`, whose value is the bare
5234/// identifier `tagged` or `plain`.
5235fn validate_json_policy(
5236    service: &ServiceDecl,
5237    policy: &JsonPolicy,
5238    errors: &mut Vec<CompileError>,
5239) {
5240    if !matches!(service.protocol, ServiceProtocol::Http) {
5241        errors.push(
5242            CompileError::new(
5243                "bynk.http.json_not_http",
5244                policy.span,
5245                "a `json { }` policy is only valid on a `from http` service",
5246            )
5247            .with_note("the response JSON encoding governs the HTTP surface, which only a `from http` service has"),
5248        );
5249        return;
5250    }
5251    for field in &policy.fields {
5252        if field.name.name != "options" {
5253            errors.push(
5254                CompileError::new(
5255                    "bynk.http.json_unknown_field",
5256                    field.name.span,
5257                    format!("unknown `json` field `{}`", field.name.name),
5258                )
5259                .with_note("the only field is `options`"),
5260            );
5261        }
5262    }
5263    if let Some(expr) = policy.field("options")
5264        && JsonOptions::from_expr(expr).is_none()
5265    {
5266        errors.push(CompileError::new(
5267            "bynk.http.json_invalid_field",
5268            expr.span,
5269            "`json` `options` must be `tagged` or `plain`",
5270        ));
5271    }
5272}
5273
5274/// #2858: validate `@json(options: tagged | plain)` on an HTTP handler.
5275fn validate_json_args(ann: &Annotation, errors: &mut Vec<CompileError>) {
5276    let mut options: Option<&AnnotationArg> = None;
5277    for arg in &ann.args {
5278        match arg.label.as_ref().map(|l| l.name.as_str()) {
5279            Some("options") => options = Some(arg),
5280            _ => errors.push(
5281                CompileError::new(
5282                    "bynk.http.json_unknown_arg",
5283                    arg.span,
5284                    "`@json` accepts only the `options:` argument",
5285                )
5286                .with_note("write `@json(options: plain)`"),
5287            ),
5288        }
5289    }
5290    match options {
5291        None => errors.push(
5292            CompileError::new(
5293                "bynk.http.json_invalid_arg",
5294                ann.span,
5295                "`@json` needs an `options:` argument",
5296            )
5297            .with_note("write `@json(options: plain)`"),
5298        ),
5299        Some(arg) if JsonOptions::from_expr(&arg.value).is_none() => {
5300            errors.push(CompileError::new(
5301                "bynk.http.json_invalid_arg",
5302                arg.span,
5303                "`@json` `options` must be `tagged` or `plain`",
5304            ));
5305        }
5306        Some(_) => {}
5307    }
5308}
5309
5310/// #2858: the first `Option[U]` met writing `t` as plain JSON whose payload `U`
5311/// can itself encode as `null` (`Option[T]` or `()`), as `U` displayed. Plain
5312/// encoding would write `Some(null-payload)` and `None` identically. The walk
5313/// goes through containers, named records and sums, and generic instantiations
5314/// (with their type arguments substituted); `seen` guards a recursive type.
5315pub(crate) fn null_payload_option(
5316    t: &TypeRef,
5317    types: &HashMap<String, Arc<TypeDecl>>,
5318    seen: &mut HashSet<String>,
5319) -> Option<String> {
5320    match t {
5321        TypeRef::Option(inner, _) => {
5322            if matches!(inner.as_ref(), TypeRef::Option(..) | TypeRef::Unit(_)) {
5323                return Some(ts_type_ref_display(inner));
5324            }
5325            null_payload_option(inner, types, seen)
5326        }
5327        TypeRef::List(a, _)
5328        | TypeRef::Set(a, _)
5329        | TypeRef::Effect(a, _)
5330        | TypeRef::HttpResult(a, _) => null_payload_option(a, types, seen),
5331        TypeRef::Map(k, v, _) | TypeRef::Result(k, v, _) => {
5332            null_payload_option(k, types, seen).or_else(|| null_payload_option(v, types, seen))
5333        }
5334        TypeRef::Named(id) => {
5335            if !seen.insert(id.name.clone()) {
5336                return None;
5337            }
5338            match types.get(&id.name).map(|d| &d.body) {
5339                Some(TypeBody::Record(r)) => r
5340                    .fields
5341                    .iter()
5342                    .find_map(|f| null_payload_option(&f.type_ref, types, seen)),
5343                Some(TypeBody::Sum(s)) => s
5344                    .variants
5345                    .iter()
5346                    .flat_map(|v| &v.payload)
5347                    .find_map(|f| null_payload_option(&f.type_ref, types, seen)),
5348                _ => None,
5349            }
5350        }
5351        TypeRef::App { name, args, .. } => {
5352            if !seen.insert(bynk_check_wire_key(&name.name, args)) {
5353                return None;
5354            }
5355            let fields = crate::wire::record_inst_fields(&name.name, args, types)
5356                .map(|fs| fs.into_iter().map(|(_, t)| t).collect::<Vec<_>>())
5357                .or_else(|| {
5358                    crate::wire::sum_inst_variants(&name.name, args, types).map(|vs| {
5359                        vs.into_iter()
5360                            .flat_map(|(_, fs)| fs.into_iter().map(|(_, t)| t))
5361                            .collect()
5362                    })
5363                })
5364                .unwrap_or_default();
5365            args.iter()
5366                .find_map(|a| null_payload_option(a, types, seen))
5367                .or_else(|| {
5368                    fields
5369                        .iter()
5370                        .find_map(|f| null_payload_option(f, types, seen))
5371                })
5372        }
5373        _ => None,
5374    }
5375}
5376
5377/// The `seen` key of a generic instantiation.
5378fn bynk_check_wire_key(name: &str, args: &[TypeRef]) -> String {
5379    crate::wire::inst_codec_suffix(name, args)
5380}
5381
5382/// #2341 (decision C): `on rejected(why: BoundaryRejection) -> HttpResult[()]`
5383/// (or `Effect[HttpResult[()]]`) renders the router's own rejections. At most
5384/// one per service, one `BoundaryRejection` parameter, no `by` (it runs before
5385/// any actor is known) and no `given` (it renders a body, nothing more).
5386fn check_rejected_handlers(table: &UnitTable, errors: &mut Vec<CompileError>) {
5387    for service in table.services.values() {
5388        let mut first: Option<Span> = None;
5389        for handler in &service.handlers {
5390            if handler.kind != HandlerKind::Rejected {
5391                continue;
5392            }
5393            if let Some(prev) = first {
5394                errors.push(
5395                    CompileError::new(
5396                        "bynk.http.duplicate_rejected",
5397                        handler.span,
5398                        format!(
5399                            "service `{}` already declares `on rejected`",
5400                            service.name.name
5401                        ),
5402                    )
5403                    .with_label(prev, "first declared here"),
5404                );
5405                continue;
5406            }
5407            first = Some(handler.span);
5408            let signature = |span: Span, msg: &str| {
5409                CompileError::new("bynk.http.rejected_signature", span, msg.to_string()).with_note(
5410                    "write `on rejected(why: BoundaryRejection) -> Effect[HttpResult[()]] { … }`",
5411                )
5412            };
5413            match handler.params.as_slice() {
5414                [p] if matches!(p.type_ref, TypeRef::BoundaryRejection(_)) => {}
5415                [p] => errors.push(signature(
5416                    p.span,
5417                    "`on rejected` takes the rejection, typed `BoundaryRejection`",
5418                )),
5419                _ => errors.push(signature(
5420                    handler.span,
5421                    "`on rejected` takes exactly one parameter, the `BoundaryRejection`",
5422                )),
5423            }
5424            if let Some(by) = &handler.by_clause {
5425                errors.push(signature(
5426                    by.span,
5427                    "`on rejected` has no `by`: it runs before any actor is known",
5428                ));
5429            }
5430            if let Some(g) = handler.given.first() {
5431                errors.push(signature(
5432                    g.span,
5433                    "`on rejected` has no `given`: it renders a response body and uses no capability",
5434                ));
5435            }
5436            let inner = match &handler.return_type {
5437                TypeRef::Effect(inner, _) => inner.as_ref(),
5438                other => other,
5439            };
5440            let unit_result = matches!(inner, TypeRef::HttpResult(t, _) if matches!(t.as_ref(), TypeRef::Unit(_)));
5441            if !unit_result {
5442                errors.push(signature(
5443                    handler.return_type.span(),
5444                    "`on rejected` returns `HttpResult[()]` (or `Effect[HttpResult[()]]`)",
5445                ));
5446            }
5447        }
5448    }
5449}
5450
5451/// #3753: `*`, `{` and `}` are reserved in a route segment, literal or
5452/// `:name`, so a rest-segment form (#3752) can be added later without changing
5453/// what an existing route means. Reports the segment's first reserved
5454/// character, once, and returns whether it found one, so the caller skips the
5455/// segment rather than also reporting a parameter named `key*`.
5456fn reserved_route_char(
5457    seg: &str,
5458    path: &str,
5459    handler: &Handler,
5460    errors: &mut Vec<CompileError>,
5461) -> bool {
5462    let Some(ch) = seg.chars().find(|c| matches!(c, '*' | '{' | '}')) else {
5463        return false;
5464    };
5465    errors.push(
5466        CompileError::new(
5467            "bynk.http.reserved_route_syntax",
5468            handler.span,
5469            format!("`{ch}` in the route `{path}` is reserved for a future route form"),
5470        )
5471        .with_note(if seg.starts_with(':') {
5472            format!("drop `{ch}` from the parameter's name: a `:name` segment already takes any value, so check it in the handler")
5473        } else {
5474            format!("to match a literal `{ch}`, take the segment as a `:name` parameter and check it in the handler")
5475        }),
5476    );
5477    true
5478}
5479
5480/// Validate an `on http METHOD "path"` handler (v0.9 §4.1):
5481///
5482/// - Path must start with `/`, must not be `/_bynk/...` (reserved).
5483/// - Every `:name` segment binds to a handler parameter of the same name.
5484/// - Every parameter is either a path parameter or named `body`, `headers` or
5485///   `query`.
5486/// - Path parameter types are constructible from `String` (`String`, refined
5487///   `String`, or opaque `String`).
5488/// - GET / DELETE handlers may not have a `body` parameter.
5489/// - The handler return type must be `Effect[HttpResult[T]]`.
5490fn validate_http_handler(
5491    handler: &Handler,
5492    method: HttpMethod,
5493    path: &str,
5494    types: &HashMap<String, Arc<TypeDecl>>,
5495    cf_is_std: bool,
5496    errors: &mut Vec<CompileError>,
5497) {
5498    if !path.starts_with('/') {
5499        errors.push(CompileError::new(
5500            "bynk.http.invalid_path",
5501            handler.span,
5502            format!("HTTP path `{path}` must start with `/`"),
5503        ));
5504    }
5505    if path.starts_with("/_bynk/") || path == "/_bynk" {
5506        errors.push(
5507            CompileError::new(
5508                "bynk.http.reserved_prefix",
5509                handler.span,
5510                format!("HTTP path `{path}` uses the reserved `/_bynk/` prefix",),
5511            )
5512            .with_note("paths under `/_bynk/` are reserved for internal Bynk dispatch"),
5513        );
5514    }
5515    // #1883, slice 2: `/_assets/` is where content-hashed static assets are
5516    // served, before the Worker runs, so a handler there could be shadowed by
5517    // any asset; the prefix is reserved outright.
5518    let assets_dir = crate::assets::SERVED_PREFIX.trim_end_matches('/');
5519    if path == assets_dir || path.starts_with(crate::assets::SERVED_PREFIX) {
5520        errors.push(
5521            CompileError::new(
5522                "bynk.http.reserved_prefix",
5523                handler.span,
5524                format!("HTTP path `{path}` uses the reserved `{}` prefix", crate::assets::SERVED_PREFIX),
5525            )
5526            .with_note("paths under `/_assets/` are reserved for static assets, which the platform serves before the Worker runs"),
5527        );
5528    }
5529    // Parse segments and collect path-parameter names.
5530    let mut path_param_names: Vec<&str> = Vec::new();
5531    // #3753: a refused route has no reliable parameter list, so its handler
5532    // parameters are not also reported as unbound (`extra_param`).
5533    let mut refused = false;
5534    for seg in path.split('/').filter(|s| !s.is_empty()) {
5535        if reserved_route_char(seg, path, handler, errors) {
5536            refused = true;
5537            continue;
5538        }
5539        if let Some(rest) = seg.strip_prefix(':') {
5540            if rest.is_empty() {
5541                errors.push(CompileError::new(
5542                    "bynk.http.invalid_path",
5543                    handler.span,
5544                    format!("HTTP path `{path}` has an empty parameter segment `:`"),
5545                ));
5546            } else {
5547                path_param_names.push(rest);
5548            }
5549        }
5550    }
5551    // Every :name must have a matching handler parameter.
5552    for name in &path_param_names {
5553        if !handler.params.iter().any(|p| p.name.name == *name) {
5554            errors.push(CompileError::new(
5555                "bynk.http.unbound_path_param",
5556                handler.span,
5557                format!("path parameter `:{name}` has no matching handler parameter `{name}`",),
5558            ));
5559        }
5560    }
5561    // Every handler parameter must be a path param, `body` or `headers`.
5562    for p in &handler.params {
5563        let is_path = path_param_names.iter().any(|n| n == &p.name.name.as_str());
5564        let is_body = p.name.name == "body";
5565        // #2341 (decision A): `headers` is the request's headers, and must be
5566        // typed `RequestHeaders`.
5567        let is_headers = !is_path && p.name.name == "headers";
5568        if is_headers && !matches!(p.type_ref, TypeRef::RequestHeaders(_)) {
5569            errors.push(
5570                CompileError::new(
5571                    "bynk.http.headers_wrong_type",
5572                    p.type_ref.span(),
5573                    format!(
5574                        "an HTTP handler's `headers` parameter must be typed `RequestHeaders` (got `{}`)",
5575                        ts_type_ref_display(&p.type_ref),
5576                    ),
5577                )
5578                .with_note("`headers: RequestHeaders` gives the handler the request's headers"),
5579            );
5580        }
5581        // #2854: `query` is the request's query string, a record `T` the router
5582        // decodes and validates, or the raw `RequestQuery` view.
5583        let is_query = !is_path && p.name.name == "query";
5584        if is_query {
5585            validate_query_param(p, types, errors);
5586        }
5587        // #3277: `cookies` is the request's cookies, a record `T` the router decodes
5588        // and validates.
5589        let is_cookies = !is_path && p.name.name == "cookies";
5590        if is_cookies {
5591            validate_cookies_param(p, types, errors);
5592        }
5593        // #3513 C: `cf` is what Cloudflare derived about the connection, and must be
5594        // typed `RequestCf` (from `bynk.cloudflare`).
5595        let is_cf = !is_path && p.name.name == "cf";
5596        if is_cf
5597            && !(cf_is_std && matches!(&p.type_ref, TypeRef::Named(id) if id.name == "RequestCf"))
5598        {
5599            errors.push(
5600                CompileError::new(
5601                    "bynk.http.cf_wrong_type",
5602                    p.type_ref.span(),
5603                    format!(
5604                        "an HTTP handler's `cf` parameter must be typed `RequestCf` (got `{}`)",
5605                        ts_type_ref_display(&p.type_ref),
5606                    ),
5607                )
5608                .with_note(
5609                    "`cf: RequestCf` gives the handler what Cloudflare derived about the request; it is the `RequestCf` of `bynk.cloudflare` (`consumes bynk.cloudflare { RequestCf }`), not a type of your own",
5610                ),
5611            );
5612        }
5613        // #3276: the `body` of a `@form` handler is a record of form leaves.
5614        if is_body
5615            && let Some(kind) = handler
5616                .annotations
5617                .iter()
5618                .find(|a| matches!(a.name.name.as_str(), "form" | "multipart"))
5619                .map(|a| a.name.name.as_str())
5620        {
5621            validate_form_body(p, kind, types, errors);
5622            if let Some(by) = handler.by_clause.as_ref().filter(|b| b.is_sum()) {
5623                errors.push(
5624                    CompileError::new(
5625                        "bynk.http.form_on_sum_route",
5626                        by.span,
5627                        format!("a `@{kind}` route cannot take a sum of actors"),
5628                    )
5629                    .with_note(
5630                        "a multi-actor route reads and verifies the body as JSON itself; name one actor, or split the route",
5631                    ),
5632                );
5633            }
5634        }
5635        // #3380: a streamed `body`'s route cannot take a sum of actors either: its
5636        // wrapper reads and verifies the body itself.
5637        if is_body
5638            && is_byte_stream(&p.type_ref)
5639            && let Some(by) = handler.by_clause.as_ref().filter(|b| b.is_sum())
5640        {
5641            errors.push(
5642                CompileError::new(
5643                    "bynk.http.stream_body_on_sum_route",
5644                    by.span,
5645                    "a route with a streamed `body` cannot take a sum of actors",
5646                )
5647                .with_note(
5648                    "a multi-actor route reads and verifies the body itself before the handler runs; name one actor, or split the route",
5649                ),
5650            );
5651        }
5652        if !refused && !is_path && !is_body && !is_headers && !is_query && !is_cookies && !is_cf {
5653            errors.push(
5654                CompileError::new(
5655                    "bynk.http.extra_param",
5656                    p.span,
5657                    format!(
5658                        "handler parameter `{}` is not a path parameter and is not named `body`, `headers`, `query`, `cookies` or `cf`",
5659                        p.name.name
5660                    ),
5661                )
5662                .with_note(
5663                    "HTTP handler parameters must match a `:name` path segment, or be named `body`, `headers`, `query`, `cookies` or `cf`",
5664                ),
5665            );
5666        }
5667        // Path params must be constructible from String.
5668        if is_path && !is_string_constructible(&p.type_ref, types) {
5669            errors.push(
5670                CompileError::new(
5671                    "bynk.http.path_param_not_stringy",
5672                    p.type_ref.span(),
5673                    format!(
5674                        "path parameter `{}` must have a type constructible from `String` (got `{}`)",
5675                        p.name.name,
5676                        ts_type_ref_display(&p.type_ref),
5677                    ),
5678                )
5679                .with_note(
5680                    "use `String`, a refined `String`, or an opaque type whose base is `String`",
5681                ),
5682            );
5683        }
5684        if is_body && method.forbids_body() {
5685            errors.push(
5686                CompileError::new(
5687                    "bynk.http.body_on_get_or_delete",
5688                    p.span,
5689                    format!(
5690                        "`on http {}` handlers may not declare a `body` parameter",
5691                        method.as_str()
5692                    ),
5693                )
5694                .with_note("GET and DELETE requests conventionally carry no body"),
5695            );
5696        }
5697    }
5698    // Validate return type shape.
5699    let return_ok = match &handler.return_type {
5700        TypeRef::Effect(inner, _) => matches!(inner.as_ref(), TypeRef::HttpResult(_, _)),
5701        _ => false,
5702    };
5703    if !return_ok {
5704        errors.push(CompileError::new(
5705            "bynk.http.return_not_effect_http_result",
5706            handler.return_type.span(),
5707            format!(
5708                "`on http` handler must return `Effect[HttpResult[T]]`, but got `{}`",
5709                ts_type_ref_display(&handler.return_type),
5710            ),
5711        ));
5712    }
5713}
5714
5715/// #2854: whether `r` reads off a query string as one value: a `String`, `Int`,
5716/// `Bool` or `Decimal`, a refined or opaque type over one of those, or an enum
5717/// (a sum none of whose variants carries a payload).
5718fn is_query_leaf(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
5719    let stringy_base = |b: &BaseType| {
5720        matches!(
5721            b,
5722            BaseType::String | BaseType::Int | BaseType::Bool | BaseType::Decimal
5723        )
5724    };
5725    match r {
5726        TypeRef::Base(b, _) => stringy_base(b),
5727        TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
5728            Some(TypeBody::Refined { base, .. }) | Some(TypeBody::Opaque { base, .. }) => {
5729                stringy_base(base)
5730            }
5731            Some(TypeBody::Sum(s)) => s.variants.iter().all(|v| v.payload.is_empty()),
5732            _ => false,
5733        },
5734        _ => false,
5735    }
5736}
5737
5738/// #3513 C: whether this unit's `RequestCf` is the standard library's: consumed from
5739/// `bynk.cloudflare`, and not a type the unit declares itself. `cf` takes only that one,
5740/// so a look-alike cannot bypass the platform lock and the unstable gate, which are both
5741/// keyed to the import.
5742fn cf_type_is_std(cross_context: &resolver::CrossContextInfo, table: &UnitTable) -> bool {
5743    cross_context
5744        .consumed_types
5745        .get("bynk.cloudflare")
5746        .is_some_and(|t| t.contains_key("RequestCf"))
5747        && !table.types.contains_key("RequestCf")
5748}
5749
5750/// #2854: whether `r` is a legal field type of a typed `query` record: a leaf,
5751/// an `Option` of one, or a `List` of one (a key repeated).
5752pub(crate) fn is_query_field_type(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
5753    match r {
5754        TypeRef::Option(inner, _) | TypeRef::List(inner, _) => is_query_leaf(inner, types),
5755        other => is_query_leaf(other, types),
5756    }
5757}
5758
5759/// Where a record is read off an HTTP request: the surface decides what a wire
5760/// name must look like and whether two names that differ only in case clash.
5761#[derive(Clone, Copy, PartialEq, Eq)]
5762enum RequestSurface {
5763    Cookies,
5764    Query,
5765    Form,
5766}
5767
5768/// #3446: the records a handler of this unit decodes as its `cookies` parameter, in any file
5769/// of the unit. `Record.field.cookie(v)` is legal only on one of these: the decoder it must agree
5770/// with is then in the unit that writes the cookie.
5771pub(crate) fn cookie_records_of(table: &UnitTable) -> HashSet<String> {
5772    let mut out = HashSet::new();
5773    for service in table.services.values() {
5774        for h in &service.handlers {
5775            if !matches!(h.kind, HandlerKind::Http { .. }) {
5776                continue;
5777            }
5778            for p in &h.params {
5779                if p.name.name == "cookies"
5780                    && let TypeRef::Named(id) = &p.type_ref
5781                {
5782                    out.insert(id.name.clone());
5783                }
5784            }
5785        }
5786    }
5787    out
5788}
5789
5790/// RFC 9110 `token`: a cookie name is one.
5791fn is_http_token(s: &str) -> bool {
5792    !s.is_empty()
5793        && s.chars()
5794            .all(|c| c.is_ascii_graphic() && !"()<>@,;:\\\"/[]?={}".contains(c))
5795}
5796
5797/// #3343: `@name("…")` before a record field names the key it has on the wire,
5798/// where that is not an identifier (`__Host-sid`). It is legal only on a record
5799/// used as the `cookies`, `query` or `@form`/`@multipart` `body` parameter of an
5800/// `on http` handler (the readers that take names off a request); it takes one
5801/// string literal; and two fields may not share a wire name (nor, for cookies and
5802/// query, differ only in case).
5803pub(crate) fn validate_field_names(
5804    table: &UnitTable,
5805    types: &HashMap<String, Arc<TypeDecl>>,
5806    consts: &HashMap<String, ConstDecl>,
5807    errors: &mut Vec<CompileError>,
5808) {
5809    let mut uses: HashMap<String, Vec<RequestSurface>> = HashMap::new();
5810    for service in table.services.values() {
5811        for h in &service.handlers {
5812            if !matches!(h.kind, HandlerKind::Http { .. }) {
5813                continue;
5814            }
5815            for p in &h.params {
5816                let surface = match p.name.name.as_str() {
5817                    "cookies" => Some(RequestSurface::Cookies),
5818                    "query" => Some(RequestSurface::Query),
5819                    "body"
5820                        if h.annotations
5821                            .iter()
5822                            .any(|a| matches!(a.name.name.as_str(), "form" | "multipart")) =>
5823                    {
5824                        Some(RequestSurface::Form)
5825                    }
5826                    _ => None,
5827                };
5828                if let (Some(s), TypeRef::Named(id)) = (surface, &p.type_ref) {
5829                    uses.entry(id.name.clone()).or_default().push(s);
5830                }
5831            }
5832        }
5833    }
5834    let mut names: Vec<&String> = types.keys().collect();
5835    names.sort();
5836    for name in names {
5837        let TypeBody::Record(rec) = &types[name].body else {
5838            continue;
5839        };
5840        if rec.fields.iter().all(|f| f.annotations.is_empty()) {
5841            continue;
5842        }
5843        let surfaces = uses.get(name).cloned().unwrap_or_default();
5844        let mut wire: Vec<(String, Span)> = Vec::new();
5845        let mut reported_not_request = false;
5846        for f in &rec.fields {
5847            let mut external: Option<(String, Span)> = None;
5848            for ann in &f.annotations {
5849                if ann.name.name != "name" {
5850                    errors.push(
5851                        CompileError::new(
5852                            "bynk.types.field_annotation_unknown",
5853                            ann.span,
5854                            format!("unknown field annotation `@{}`", ann.name.name),
5855                        )
5856                        .with_note("the only field annotation is `@name(\"…\")`"),
5857                    );
5858                    continue;
5859                }
5860                let arg = match ann.args.as_slice() {
5861                    [a] if a.label.is_none() => Some(a),
5862                    _ => None,
5863                };
5864                let literal = arg.and_then(|a| match &a.value.kind {
5865                    ExprKind::StrLit(s) => Some(s.clone()),
5866                    _ => None,
5867                });
5868                let Some(literal) = literal else {
5869                    let mut err = CompileError::new(
5870                        "bynk.types.field_name_bad_arg",
5871                        ann.span,
5872                        "`@name` takes exactly one string literal, or a `String` constant bound to one",
5873                    )
5874                    .with_note("write `@name(\"__Host-sid\")`, or `const SidCookie: String = \"__Host-sid\"` and `@name(SidCookie)`");
5875                    // #3445: a bare name that did not resolve (pass `annotation_consts`).
5876                    if let Some(a) = arg
5877                        && let ExprKind::Ident(id) = &a.value.kind
5878                    {
5879                        err = err.with_note(match consts.get(&id.name) {
5880                            Some(c) if matches!(c.ty, TypeRef::Base(BaseType::String, _)) => format!(
5881                                "`{}` is declared `String`, but its value does not end at a string literal: every constant it passes through must be declared exactly `String`, and the last bound to a string literal",
5882                                id.name,
5883                            ),
5884                            Some(c) => format!(
5885                                "`{}` is declared `{}`; `@name` needs a constant declared exactly `String` and bound to a string literal (or to another such constant)",
5886                                id.name,
5887                                ts_type_ref_display(&c.ty),
5888                            ),
5889                            None => format!("`{}` is not a constant in scope", id.name),
5890                        });
5891                    }
5892                    errors.push(err);
5893                    continue;
5894                };
5895                // #3445: where a diagnostic about the value points: at the
5896                // reference, where the author can act, when there is one.
5897                let (at, origin) = match arg {
5898                    Some(a) if a.from_const.is_some() => (a.value.span, Some(a)),
5899                    _ => (ann.span, None),
5900                };
5901                if external.is_some() {
5902                    errors.push(CompileError::new(
5903                        "bynk.types.field_name_duplicate",
5904                        ann.span,
5905                        format!("field `{}` has more than one `@name`", f.name.name),
5906                    ));
5907                    continue;
5908                }
5909                if surfaces.is_empty() {
5910                    // One error per record: the root cause is the record's use, not each `@name`.
5911                    if reported_not_request {
5912                        external = Some((literal, at));
5913                        continue;
5914                    }
5915                    reported_not_request = true;
5916                    errors.push(
5917                        CompileError::new(
5918                            "bynk.types.field_name_not_request_record",
5919                            ann.span,
5920                            format!(
5921                                "`@name` is on a field of `{name}`, which is not the `cookies`, `query` or `@form`/`@multipart` `body` record of an HTTP handler"
5922                            ),
5923                        )
5924                        .with_note(
5925                            "`@name` renames the key a request reader looks for; on any other record it would do nothing",
5926                        ),
5927                    );
5928                } else {
5929                    let bad = if surfaces.contains(&RequestSurface::Cookies)
5930                        && !is_http_token(&literal)
5931                    {
5932                        Some(
5933                            "a cookie name must be an RFC 9110 token (no spaces, quotes or separators)",
5934                        )
5935                    } else if literal.is_empty() {
5936                        Some("a wire name must not be empty")
5937                    } else {
5938                        None
5939                    };
5940                    if let Some(why) = bad {
5941                        let shown = match origin.and_then(|a| a.from_const.as_ref()) {
5942                            Some(c) => format!(
5943                                "`@name({})` is not a valid name here: {why} (`{literal}`)",
5944                                c.name.name
5945                            ),
5946                            None => {
5947                                format!("`@name(\"{literal}\")` is not a valid name here: {why}")
5948                            }
5949                        };
5950                        let err = CompileError::new("bynk.types.field_name_invalid", at, shown);
5951                        errors.push(match origin {
5952                            Some(a) => crate::annotation_consts::with_const_origin(err, a),
5953                            None => err,
5954                        });
5955                    }
5956                }
5957                external = Some((literal, at));
5958            }
5959            let (key, span) = external.unwrap_or_else(|| (f.name.name.clone(), f.name.span));
5960            wire.push((key, span));
5961        }
5962        if surfaces.is_empty() {
5963            // No request surface: the wire-name checks would only echo the one error above.
5964            continue;
5965        }
5966        let case_matters = surfaces
5967            .iter()
5968            .any(|s| matches!(s, RequestSurface::Cookies | RequestSurface::Query));
5969        for (i, (a, span)) in wire.iter().enumerate() {
5970            for (b, _) in &wire[..i] {
5971                if a == b {
5972                    errors.push(CompileError::new(
5973                        "bynk.types.field_name_duplicate",
5974                        *span,
5975                        format!("two fields of `{name}` read the same wire name `{a}`"),
5976                    ));
5977                } else if case_matters && a.eq_ignore_ascii_case(b) {
5978                    errors.push(
5979                        CompileError::new(
5980                            "bynk.types.field_name_case_conflict",
5981                            *span,
5982                            format!("wire names `{a}` and `{b}` of `{name}` differ only in case"),
5983                        )
5984                        .with_note("cookie and query names are case-sensitive but easily confused; rename one"),
5985                    );
5986                }
5987            }
5988        }
5989    }
5990}
5991
5992/// #3277: an HTTP handler's `cookies` parameter is a record whose fields are each
5993/// a leaf a cookie can carry (the typed-`query` set: a `String`, `Int`, `Bool` or
5994/// `Decimal`, a refined or opaque type over one, an enum), an `Option` of one, or
5995/// a `List` of one (a name sent twice).
5996fn validate_cookies_param(
5997    p: &Param,
5998    types: &HashMap<String, Arc<TypeDecl>>,
5999    errors: &mut Vec<CompileError>,
6000) {
6001    // #3277: the raw view is the other legal form, for a name a field cannot spell.
6002    if matches!(p.type_ref, TypeRef::RequestCookies(_)) {
6003        return;
6004    }
6005    let record = match &p.type_ref {
6006        TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
6007            Some(TypeBody::Record(r)) => Some(r),
6008            _ => None,
6009        },
6010        _ => None,
6011    };
6012    let Some(record) = record else {
6013        errors.push(
6014            CompileError::new(
6015                "bynk.http.cookies_wrong_type",
6016                p.type_ref.span(),
6017                format!(
6018                    "an HTTP handler's `cookies` parameter must be a record type or `RequestCookies` (got `{}`)",
6019                    ts_type_ref_display(&p.type_ref),
6020                ),
6021            )
6022            .with_note(
6023                "`cookies: Session` decodes the request's `Cookie` header into the record `Session`, one field per cookie name, and answers `400` when it does not fit; `cookies: RequestCookies` reads them raw, for a name a field cannot spell (`__Host-sid`)",
6024            ),
6025        );
6026        return;
6027    };
6028    for f in &record.fields {
6029        if !is_query_field_type(&f.type_ref, types) {
6030            errors.push(
6031                CompileError::new(
6032                    "bynk.http.cookies_field_not_stringy",
6033                    f.type_ref.span(),
6034                    format!(
6035                        "field `{}` of the `cookies` record has type `{}`, which a cookie cannot carry",
6036                        f.name.name,
6037                        ts_type_ref_display(&f.type_ref),
6038                    ),
6039                )
6040                .with_note(
6041                    "a cookie field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, optionally in an `Option` or a `List` (a name sent twice)",
6042                ),
6043            );
6044        }
6045    }
6046}
6047
6048/// #2854: a HTTP handler's `query` parameter is `RequestQuery`, or a record
6049/// whose fields are each a query leaf, an `Option` of one or a `List` of one.
6050fn validate_query_param(
6051    p: &Param,
6052    types: &HashMap<String, Arc<TypeDecl>>,
6053    errors: &mut Vec<CompileError>,
6054) {
6055    if matches!(p.type_ref, TypeRef::RequestQuery(_)) {
6056        return;
6057    }
6058    let record = match &p.type_ref {
6059        TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
6060            Some(TypeBody::Record(r)) => Some(r),
6061            _ => None,
6062        },
6063        _ => None,
6064    };
6065    let Some(record) = record else {
6066        errors.push(
6067            CompileError::new(
6068                "bynk.http.query_wrong_type",
6069                p.type_ref.span(),
6070                format!(
6071                    "an HTTP handler's `query` parameter must be a record type or `RequestQuery` (got `{}`)",
6072                    ts_type_ref_display(&p.type_ref),
6073                ),
6074            )
6075            .with_note(
6076                "`query: Filter` decodes the query string into the record `Filter` and answers `400` when it does not fit; `query: RequestQuery` reads it raw",
6077            ),
6078        );
6079        return;
6080    };
6081    for f in &record.fields {
6082        if !is_query_field_type(&f.type_ref, types) {
6083            errors.push(
6084                CompileError::new(
6085                    "bynk.http.query_field_not_stringy",
6086                    f.type_ref.span(),
6087                    format!(
6088                        "field `{}` of the `query` record has type `{}`, which a query string cannot carry",
6089                        f.name.name,
6090                        ts_type_ref_display(&f.type_ref),
6091                    ),
6092                )
6093                .with_note(
6094                    "a query field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, optionally in an `Option` or a `List` (a repeated key)",
6095                ),
6096            );
6097        }
6098    }
6099}
6100
6101/// Validate a handler's handler-position annotations (v0.140, ADR 0163). The one
6102/// handler annotation is `@cache(maxAge: <Duration>, scope: public|private)`,
6103/// legal solely on an `on http GET` handler. This runs for *every* handler —
6104/// services and agents — so a misplaced `@cache` (a non-GET route, another
6105/// protocol, or an agent handler) is caught wherever it is written, and an
6106/// unknown annotation name is flagged rather than silently ignored. The
6107/// automatic conditional `ETag`/`304` half carries no author surface, so `@cache`
6108/// is the only annotation validated here.
6109fn validate_handler_annotations(
6110    handler: &Handler,
6111    service_cap: Option<i64>,
6112    errors: &mut Vec<CompileError>,
6113) {
6114    let is_get = matches!(
6115        handler.kind,
6116        HandlerKind::Http {
6117            method: HttpMethod::Get,
6118            ..
6119        }
6120    );
6121    // v0.142 (ADR 0165): `@limit` is the inverse of `@cache` — it caps a request
6122    // body, so it is valid only on a body-taking route (POST/PUT/PATCH); a GET or
6123    // DELETE (and any non-HTTP handler) has no body to limit.
6124    let is_body_method = matches!(
6125        handler.kind,
6126        HandlerKind::Http {
6127            method: HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch,
6128            ..
6129        }
6130    );
6131    let mut seen_cache = false;
6132    let mut seen_limit = false;
6133    let mut seen_raw = false;
6134    let mut seen_form = false;
6135    let mut seen_json = false;
6136    // #3276: `@raw` and `@form` each fix the body's one wire format, so a handler
6137    // carries at most one of them.
6138    let mut body_kind: Option<&str> = None;
6139    for ann in &handler.annotations {
6140        match ann.name.name.as_str() {
6141            "cache" => {
6142                if seen_cache {
6143                    errors.push(CompileError::new(
6144                        "bynk.http.cache_duplicate",
6145                        ann.span,
6146                        "a handler carries at most one `@cache` annotation",
6147                    ));
6148                    continue;
6149                }
6150                seen_cache = true;
6151                if !is_get {
6152                    errors.push(
6153                        CompileError::new(
6154                            "bynk.http.cache_on_non_get",
6155                            ann.span,
6156                            "`@cache` is only valid on an `on http GET` handler",
6157                        )
6158                        .with_note(
6159                            "conditional caching applies to safe, idempotent reads — a `GET` route",
6160                        ),
6161                    );
6162                    continue;
6163                }
6164                validate_cache_args(ann, errors);
6165                // #3277: a response that depends on the request's cookies is one
6166                // user's, so it must not be stored by a shared cache.
6167                let public = ann.args.iter().any(|a| {
6168                    a.label.as_ref().is_some_and(|n| n.name == "scope")
6169                        && matches!(&a.value.kind, ExprKind::Ident(id) if id.name == "public")
6170                });
6171                if public && handler.params.iter().any(|p| p.name.name == "cookies") {
6172                    errors.push(
6173                        CompileError::new(
6174                            "bynk.http.cache_public_reads_cookies",
6175                            ann.span,
6176                            "a `@cache(scope: public)` handler reads `cookies`, so a shared cache could replay one user's response to another",
6177                        )
6178                        .with_note("use `scope: private`, or drop the `cookies` parameter"),
6179                    );
6180                }
6181            }
6182            "limit" => {
6183                if seen_limit {
6184                    errors.push(CompileError::new(
6185                        "bynk.http.limit_duplicate",
6186                        ann.span,
6187                        "a handler carries at most one `@limit` annotation",
6188                    ));
6189                    continue;
6190                }
6191                seen_limit = true;
6192                if !is_body_method {
6193                    errors.push(
6194                        CompileError::new(
6195                            "bynk.http.limit_on_bodyless",
6196                            ann.span,
6197                            "`@limit` is only valid on a body-taking `on http` route (POST/PUT/PATCH)",
6198                        )
6199                        .with_note(
6200                            "a request-body size cap applies to routes that read a body — a GET or DELETE has none",
6201                        ),
6202                    );
6203                    continue;
6204                }
6205                validate_limit_args(
6206                    ann,
6207                    handler
6208                        .annotations
6209                        .iter()
6210                        .any(|a| a.name.name == "multipart"),
6211                    errors,
6212                );
6213            }
6214            "raw" => {
6215                if seen_raw {
6216                    errors.push(CompileError::new(
6217                        "bynk.http.raw_duplicate",
6218                        ann.span,
6219                        "a handler carries at most one `@raw` annotation",
6220                    ));
6221                    continue;
6222                }
6223                seen_raw = true;
6224                if let Some(other) = body_kind.filter(|k| *k != "raw") {
6225                    errors.push(body_kind_conflict(ann, "raw", other));
6226                    continue;
6227                }
6228                body_kind = Some("raw");
6229                let body = handler.params.iter().find(|p| p.name.name == "body");
6230                let Some(body) = body.filter(|_| is_body_method) else {
6231                    errors.push(
6232                        CompileError::new(
6233                            "bynk.http.raw_on_bodyless",
6234                            ann.span,
6235                            "`@raw` is only valid on a POST/PUT/PATCH `on http` route with a `body` parameter",
6236                        )
6237                        .with_note(
6238                            "a raw request body is the `body: Bytes` parameter of a body-taking route",
6239                        ),
6240                    );
6241                    continue;
6242                };
6243                validate_raw_args(ann, errors);
6244                if !matches!(body.type_ref, TypeRef::Base(BaseType::Bytes, _))
6245                    && !is_byte_stream(&body.type_ref)
6246                {
6247                    errors.push(
6248                        CompileError::new(
6249                            "bynk.http.raw_body_not_bytes",
6250                            body.type_ref.span(),
6251                            format!(
6252                                "the `body` of a `@raw` handler must be `Bytes` or `Stream[Bytes]`, but it is `{}`",
6253                                ts_type_ref_display(&body.type_ref),
6254                            ),
6255                        )
6256                        .with_note("a raw body is handed to the handler as its octets, undecoded: whole as `Bytes`, or chunk by chunk as a `Stream[Bytes]`"),
6257                    );
6258                }
6259                let route_cap = handler.limit_max_body();
6260                if route_cap.or(service_cap).is_none() {
6261                    errors.push(
6262                        CompileError::new(
6263                            "bynk.http.raw_body_unbounded",
6264                            ann.span,
6265                            "a `@raw` route needs a request-body cap",
6266                        )
6267                        .with_note(
6268                            "add `@limit(maxBody: …)` to the handler or `limits { maxBody = … }` to the service; an unbounded binary upload is the denial of service ADR 0165 exists to stop",
6269                        ),
6270                    );
6271                }
6272            }
6273            kind @ ("form" | "multipart") => {
6274                // #3276: `@form` and `@multipart` each fix the wire format of the
6275                // one `body`: a urlencoded form, or a `multipart/form-data` one.
6276                if seen_form {
6277                    errors.push(CompileError::new(
6278                        "bynk.http.form_duplicate",
6279                        ann.span,
6280                        format!("a handler carries at most one `@{kind}` annotation"),
6281                    ));
6282                    continue;
6283                }
6284                seen_form = true;
6285                if let Some(other) = body_kind.filter(|k| *k != kind) {
6286                    errors.push(body_kind_conflict(ann, kind, other));
6287                    continue;
6288                }
6289                body_kind = Some(kind);
6290                let has_body = handler.params.iter().any(|p| p.name.name == "body");
6291                if !is_body_method || !has_body {
6292                    errors.push(
6293                        CompileError::new(
6294                            "bynk.http.form_on_bodyless",
6295                            ann.span,
6296                            format!(
6297                                "`@{kind}` is only valid on a POST/PUT/PATCH `on http` route with a `body` parameter"
6298                            ),
6299                        )
6300                        .with_note(format!(
6301                            "a {kind} body is the `body` parameter of a body-taking route"
6302                        )),
6303                    );
6304                    continue;
6305                }
6306                if let Some(arg) = ann.args.first() {
6307                    errors.push(
6308                        CompileError::new(
6309                            "bynk.http.form_unknown_arg",
6310                            arg.span,
6311                            format!("`@{kind}` takes no arguments"),
6312                        )
6313                        .with_note(format!(
6314                            "write `@{kind}`: the media type is fixed, and the caps are `@limit` and `limits {{ }}`"
6315                        )),
6316                    );
6317                }
6318                // A multipart body is held in memory beside its parsed copy, so
6319                // it must be bounded, as a `@raw` one is.
6320                if kind == "multipart" && handler.limit_max_body().or(service_cap).is_none() {
6321                    errors.push(
6322                        CompileError::new(
6323                            "bynk.http.multipart_body_unbounded",
6324                            ann.span,
6325                            "a `@multipart` route needs a request-body cap",
6326                        )
6327                        .with_note(
6328                            "add `@limit(maxBody: …)` to the handler or `limits { maxBody: … }` to the service; a multipart body is buffered whole, so an unbounded upload is the denial of service ADR 0165 exists to stop",
6329                        ),
6330                    );
6331                } else if kind == "multipart"
6332                    && handler
6333                        .limit_max_body()
6334                        .or(service_cap)
6335                        .is_some_and(|cap| cap > MULTIPART_LARGE_CAP)
6336                {
6337                    errors.push(
6338                        CompileError::new(
6339                            "bynk.http.multipart_large_cap",
6340                            ann.span,
6341                            "this `@multipart` route's body cap is over 32 MiB",
6342                        )
6343                        .with_note(
6344                            "the body is buffered with a parsed copy beside it, and a Worker has 128 MB for everything; lower `maxBody`, or hold large uploads to a presigned or multipart-to-R2 flow",
6345                        ),
6346                    );
6347                }
6348            }
6349            "json" => {
6350                if seen_json {
6351                    errors.push(CompileError::new(
6352                        "bynk.http.json_duplicate",
6353                        ann.span,
6354                        "a handler carries at most one `@json` annotation",
6355                    ));
6356                    continue;
6357                }
6358                seen_json = true;
6359                if !matches!(handler.kind, HandlerKind::Http { .. }) {
6360                    errors.push(
6361                        CompileError::new(
6362                            "bynk.http.json_on_non_http",
6363                            ann.span,
6364                            "`@json` is only valid on an `on http` handler",
6365                        )
6366                        .with_note("it chooses how an HTTP response body writes `Option`"),
6367                    );
6368                    continue;
6369                }
6370                validate_json_args(ann, errors);
6371            }
6372            other => {
6373                errors.push(
6374                    CompileError::new(
6375                        "bynk.http.unknown_handler_annotation",
6376                        ann.name.span,
6377                        format!(
6378                            "unknown handler annotation `@{other}` — the handler annotations are `@cache`, `@limit`, `@raw`, `@form`, `@multipart` and `@json`"
6379                        ),
6380                    )
6381                    .with_note("handler annotations are a closed set (ADR 0163, ADR 0165)"),
6382                );
6383            }
6384        }
6385    }
6386}
6387
6388/// #3380: whether `r` is exactly `Stream[Bytes]`, the one stream type a `@raw`
6389/// handler's `body` may be.
6390pub(crate) fn is_byte_stream(r: &TypeRef) -> bool {
6391    matches!(r, TypeRef::Stream(inner, _) if matches!(**inner, TypeRef::Base(BaseType::Bytes, _)))
6392}
6393
6394/// #3276: the body cap above which a `@multipart` route is warned about: a quarter
6395/// of a Worker's 128 MB isolate, since the body is buffered with a parsed copy.
6396const MULTIPART_LARGE_CAP: i64 = 32 * 1024 * 1024;
6397
6398/// #3276: the diagnostic for a handler that declares two request-body wire formats
6399/// (`@raw` with `@form`): each fixes how the one `body` is read, so they exclude
6400/// each other.
6401fn body_kind_conflict(ann: &Annotation, this: &str, other: &str) -> CompileError {
6402    CompileError::new(
6403        "bynk.http.body_kind_conflict",
6404        ann.span,
6405        format!("a handler cannot carry both `@{other}` and `@{this}`"),
6406    )
6407    .with_note("`@raw`, `@form` and `@multipart` each fix the wire format of the one `body` parameter; use one")
6408}
6409
6410/// #3276: whether `r` is a `Bool`, or a refined or opaque type over one (the
6411/// leaves a browser's unchecked checkbox leaves absent).
6412fn is_bool_leaf(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
6413    match r {
6414        TypeRef::Base(b, _) => matches!(b, BaseType::Bool),
6415        TypeRef::Named(id) => matches!(
6416            types.get(&id.name).map(|t| &t.body),
6417            Some(TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. })
6418                if matches!(base, BaseType::Bool)
6419        ),
6420        _ => false,
6421    }
6422}
6423
6424/// #3277: whether `decl` (the type table's entry for `name`) is a type the `bynk`
6425/// adapter exports, found by its first-party span.
6426pub fn is_std_bynk_type(
6427    name: &str,
6428    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
6429    decl: &TypeDecl,
6430) -> bool {
6431    types.get(name).is_some_and(|d| d.span == decl.span)
6432        && crate::firstparty::unit(bynk_std::BYNK_UNIT)
6433            .is_some_and(|unit| decl.span.file == crate::project_model::firstparty_file_id(unit))
6434}
6435
6436/// #3276: whether `name` is the `File` record `bynk` exports, found by its
6437/// declaration's first-party span (as `is_crypto_key_type` finds a key), so a
6438/// user type that happens to be called `File` is not mistaken for it.
6439pub fn is_std_file_type(
6440    name: &str,
6441    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
6442) -> bool {
6443    name == "File"
6444        && types.get(name).is_some_and(|decl| {
6445            crate::firstparty::unit(bynk_std::BYNK_UNIT).is_some_and(|unit| {
6446                decl.span.file == crate::project_model::firstparty_file_id(unit)
6447            })
6448        })
6449}
6450
6451/// #3276: whether `r` is a `@multipart` file field: `File`, or an `Option` or a
6452/// `List` of it (one layer, as a form leaf is). `File` is the record `bynk`
6453/// exports (`consumes bynk { File }`).
6454fn is_file_field_type(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
6455    let named = |t: &TypeRef| matches!(t, TypeRef::Named(id) if is_std_file_type(&id.name, types));
6456    match r {
6457        TypeRef::Option(inner, _) | TypeRef::List(inner, _) => named(inner),
6458        other => named(other),
6459    }
6460}
6461
6462/// #3276: the field path by which `t` reaches a `File`, if it does: `Some(vec![])`
6463/// for a `File` itself, otherwise the record fields (or sum payloads) through
6464/// which a type carries one, as [`bynk_syntax::ast::stream_path`] does a stream.
6465fn file_path(t: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> Option<Vec<String>> {
6466    fn walk(
6467        t: &TypeRef,
6468        types: &HashMap<String, Arc<TypeDecl>>,
6469        visited: &mut std::collections::HashSet<String>,
6470    ) -> Option<Vec<String>> {
6471        match t {
6472            TypeRef::Named(id) if is_std_file_type(&id.name, types) => Some(Vec::new()),
6473            TypeRef::Named(id) => named(&id.name, types, visited),
6474            TypeRef::App { name, args, .. } => named(&name.name, types, visited)
6475                .or_else(|| args.iter().find_map(|a| walk(a, types, visited))),
6476            TypeRef::Option(a, _) | TypeRef::List(a, _) | TypeRef::Set(a, _) => {
6477                walk(a, types, visited)
6478            }
6479            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
6480                walk(a, types, visited).or_else(|| walk(b, types, visited))
6481            }
6482            _ => None,
6483        }
6484    }
6485    fn named(
6486        name: &str,
6487        types: &HashMap<String, Arc<TypeDecl>>,
6488        visited: &mut std::collections::HashSet<String>,
6489    ) -> Option<Vec<String>> {
6490        if !visited.insert(name.to_string()) {
6491            return None;
6492        }
6493        let decl = types.get(name)?;
6494        let found = match &decl.body {
6495            TypeBody::Record(r) => r.fields.iter().find_map(|f| {
6496                walk(&f.type_ref, types, visited).map(|mut p| {
6497                    p.insert(0, f.name.name.clone());
6498                    p
6499                })
6500            }),
6501            TypeBody::Sum(s) => s.variants.iter().find_map(|v| {
6502                v.payload.iter().find_map(|f| {
6503                    walk(&f.type_ref, types, visited).map(|mut p| {
6504                        p.insert(0, f.name.name.clone());
6505                        p
6506                    })
6507                })
6508            }),
6509            _ => None,
6510        };
6511        visited.remove(name);
6512        found
6513    }
6514    walk(t, types, &mut std::collections::HashSet::new())
6515}
6516
6517/// #3276: the `body` of a `@form` handler is a record whose fields are each a
6518/// form leaf: the typed `query` set (a `String`, `Int`, `Bool` or `Decimal`, a
6519/// refined or opaque type over one, an enum), optionally in an `Option` or a
6520/// `List` (a repeated key). A `Bool` that is neither optional, listed nor
6521/// defaulted is a warning: an unchecked checkbox sends nothing.
6522fn validate_form_body(
6523    p: &Param,
6524    kind: &str,
6525    types: &HashMap<String, Arc<TypeDecl>>,
6526    errors: &mut Vec<CompileError>,
6527) {
6528    let multipart = kind == "multipart";
6529    let record = match &p.type_ref {
6530        TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
6531            Some(TypeBody::Record(r)) => Some(r),
6532            _ => None,
6533        },
6534        _ => None,
6535    };
6536    let Some(record) = record else {
6537        errors.push(
6538            CompileError::new(
6539                "bynk.http.form_body_not_record",
6540                p.type_ref.span(),
6541                format!(
6542                    "the `body` of a `@{kind}` handler must be a record type (got `{}`)",
6543                    ts_type_ref_display(&p.type_ref),
6544                ),
6545            )
6546            .with_note(
6547                "a form body decodes into a record, one field per form key: `body: SignupForm`",
6548            ),
6549        );
6550        return;
6551    };
6552    for f in &record.fields {
6553        let is_file = multipart && is_file_field_type(&f.type_ref, types);
6554        if !is_file && !is_query_field_type(&f.type_ref, types) {
6555            errors.push(
6556                CompileError::new(
6557                    "bynk.http.form_field_not_stringy",
6558                    f.type_ref.span(),
6559                    format!(
6560                        "field `{}` of the `@{kind}` body record has type `{}`, which a {kind} body cannot carry",
6561                        f.name.name,
6562                        ts_type_ref_display(&f.type_ref),
6563                    ),
6564                )
6565                .with_note(if multipart {
6566                    "a multipart field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, or a `File`, optionally in an `Option` or a `List` (a repeated part); keys are flat, so a nested record is not allowed"
6567                } else {
6568                    "a form field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, optionally in an `Option` or a `List` (a repeated key); form keys are flat, so a nested record is not allowed"
6569                }),
6570            );
6571        } else if f.init.is_none() && is_bool_leaf(&f.type_ref, types) {
6572            errors.push(
6573                CompileError::new(
6574                    "bynk.http.form_bool_without_default",
6575                    f.type_ref.span(),
6576                    format!(
6577                        "`Bool` field `{}` of a `@{kind}` body has no default, so an unchecked checkbox is a `400`",
6578                        f.name.name,
6579                    ),
6580                )
6581                .with_note(
6582                    "a browser sends nothing for an unchecked checkbox; give the field `= false`, or make it an `Option[Bool]`",
6583                ),
6584            );
6585        }
6586    }
6587}
6588
6589/// Validate `@cache`'s arguments on a GET handler (v0.140, ADR 0163): a required
6590/// `maxAge:` positive `Duration` literal (the freshness window — the one thing the
6591/// compiler cannot derive) and an optional `scope:` of `public`/`private`
6592/// (defaulting to `private` at emit time). Any other argument — a stray label or a
6593/// positional value — is a diagnostic; the vocabulary is closed.
6594fn validate_cache_args(ann: &Annotation, errors: &mut Vec<CompileError>) {
6595    let mut max_age: Option<&AnnotationArg> = None;
6596    let mut scope: Option<&AnnotationArg> = None;
6597    let mut immutable: Option<&AnnotationArg> = None;
6598    for arg in &ann.args {
6599        match arg.label.as_ref().map(|l| l.name.as_str()) {
6600            Some("maxAge") => max_age = Some(arg),
6601            Some("scope") => scope = Some(arg),
6602            Some("immutable") => immutable = Some(arg),
6603            _ => {
6604                errors.push(
6605                    CompileError::new(
6606                        "bynk.http.cache_unknown_arg",
6607                        arg.span,
6608                        "`@cache` accepts only the `maxAge:`, `scope:` and `immutable:` arguments",
6609                    )
6610                    .with_note("write `@cache(maxAge: 5.minutes, scope: private)`"),
6611                );
6612            }
6613        }
6614    }
6615    // `maxAge` is required and must be a *positive* `Duration` literal — the same
6616    // positive-duration rule the `@ttl` store annotation uses. It must also
6617    // resolve to a *whole* number of seconds: `Cache-Control: max-age` has no
6618    // finer granularity, so `lower_route_cache_ir` (`bynk-emit/src/ir/lower.rs`)
6619    // divides by 1000 to get there — a value with any fractional-second
6620    // remainder (`500.milliseconds`, or `1500.milliseconds`, which resolves to a
6621    // real but wrong `max-age=1`) would previously type-check cleanly and then
6622    // silently drop the remainder, with no diagnostic anywhere in the pipeline
6623    // (#1230). `>= 1000` alone would only catch the *total-loss* case
6624    // (`max-age=0`) and let the partial-loss case through, which is the same
6625    // silent-truncation defect at a smaller magnitude, not a different one —
6626    // review of #1231 is what found the guard needed to be exact-division, not
6627    // a floor.
6628    match max_age.map(|a| &a.value.kind) {
6629        Some(ExprKind::DurationLit { millis, .. }) if *millis > 0 && *millis % 1000 == 0 => {}
6630        Some(ExprKind::DurationLit { millis, .. }) if *millis > 0 => {
6631            errors.push(
6632                CompileError::new(
6633                    "bynk.http.cache_max_age_fractional_seconds",
6634                    max_age.unwrap().span,
6635                    "`@cache` `maxAge` must be a whole number of seconds",
6636                )
6637                .with_note(
6638                    "`Cache-Control: max-age` is whole seconds — a value with a fractional \
6639                     second would silently drop the remainder rather than round or reject, \
6640                     so it is not honoured exactly",
6641                ),
6642            );
6643        }
6644        Some(_) => {
6645            let arg = max_age.unwrap();
6646            errors.push(crate::annotation_consts::with_const_origin(
6647                CompileError::new(
6648                    "bynk.http.cache_bad_max_age",
6649                    arg.span,
6650                    "`@cache` `maxAge` must be a positive `Duration` literal (e.g. `5.minutes`), or a `Duration` constant bound to one",
6651                ),
6652                arg,
6653            ));
6654        }
6655        None => {
6656            errors.push(
6657                CompileError::new(
6658                    "bynk.http.cache_bad_max_age",
6659                    ann.span,
6660                    "`@cache` requires a `maxAge:` argument — the freshness window",
6661                )
6662                .with_note(
6663                    "the `ETag` revalidation is automatic; only the freshness window is declared",
6664                ),
6665            );
6666        }
6667    }
6668    // `scope`, when present, is the bare identifier `public` or `private`.
6669    if let Some(scope) = scope {
6670        let ok = matches!(
6671            &scope.value.kind,
6672            ExprKind::Ident(id) if id.name == "public" || id.name == "private"
6673        );
6674        if !ok {
6675            errors.push(CompileError::new(
6676                "bynk.http.cache_bad_scope",
6677                scope.span,
6678                "`@cache` `scope` must be `public` or `private`",
6679            ));
6680        }
6681    }
6682    // `immutable`, when present, is a `Bool` literal (caching raw responses): the
6683    // author's promise that the representation never changes, emitted as the
6684    // RFC 8246 `immutable` directive when `true`.
6685    if let Some(immutable) = immutable
6686        && !matches!(immutable.value.kind, ExprKind::BoolLit(_))
6687    {
6688        errors.push(
6689            CompileError::new(
6690                "bynk.http.cache_bad_immutable",
6691                immutable.span,
6692                "`@cache` `immutable` must be `true` or `false`",
6693            )
6694            .with_note(
6695                "`immutable: true` promises the response at this URL never changes, so caches \
6696                 do not revalidate it within `maxAge` — true of content-addressed paths",
6697            ),
6698        );
6699    }
6700}
6701
6702/// Validate `@limit`'s arguments on a body-taking route (v0.142, ADR 0165): a
6703/// required `maxBody:` positive `Int` literal — a byte count, the one ceiling only
6704/// the author knows. Any other argument — a stray label or a positional value — is
6705/// a diagnostic; the vocabulary is closed. A route `@limit` overrides the service
6706/// `limits { }` default at emit time. There is no `Size` literal yet, so the byte
6707/// count is a plain `Int` (DECISION C).
6708fn validate_limit_args(ann: &Annotation, is_multipart: bool, errors: &mut Vec<CompileError>) {
6709    let mut max_body: Option<&AnnotationArg> = None;
6710    let mut multipart_args = 0;
6711    for arg in &ann.args {
6712        match arg.label.as_ref().map(|l| l.name.as_str()) {
6713            Some("maxBody") => max_body = Some(arg),
6714            // #3276: the per-file and part-count caps of a `@multipart` route.
6715            Some(name @ ("maxFile" | "maxParts")) => {
6716                multipart_args += 1;
6717                if !is_multipart {
6718                    errors.push(
6719                        CompileError::new(
6720                            "bynk.http.limit_on_non_multipart",
6721                            arg.span,
6722                            format!("`@limit` `{name}` is only valid on a `@multipart` route"),
6723                        )
6724                        .with_note(
6725                            "a per-file or part-count cap governs the parts of a multipart body",
6726                        ),
6727                    );
6728                } else if !matches!(&arg.value.kind, ExprKind::IntLit { value: n, .. } if *n > 0) {
6729                    errors.push(crate::annotation_consts::with_const_origin(
6730                        CompileError::new(
6731                            "bynk.http.limit_bad_max_file",
6732                            arg.span,
6733                            format!(
6734                                "`@limit` `{name}` must be a positive `Int` literal, or an `Int` constant bound to one"
6735                            ),
6736                        ),
6737                        arg,
6738                    ));
6739                }
6740            }
6741            _ => {
6742                errors.push(
6743                    CompileError::new(
6744                        "bynk.http.limit_unknown_arg",
6745                        arg.span,
6746                        "`@limit` accepts only the `maxBody:` argument (and, on a `@multipart` route, `maxFile:` and `maxParts:`)",
6747                    )
6748                    .with_note("write `@limit(maxBody: 26_214_400)`"),
6749                );
6750            }
6751        }
6752    }
6753    // A `@limit` that only tightens a multipart route's file or part caps may leave
6754    // `maxBody` to the service's `limits { }`.
6755    if max_body.is_none() && multipart_args > 0 {
6756        return;
6757    }
6758    // `maxBody` is required and must be a *positive* `Int` literal — a byte count.
6759    match max_body.map(|a| &a.value.kind) {
6760        Some(ExprKind::IntLit { value: n, .. }) if *n > 0 => {}
6761        Some(_) => {
6762            let arg = max_body.unwrap();
6763            errors.push(crate::annotation_consts::with_const_origin(
6764                CompileError::new(
6765                    "bynk.http.limit_bad_max_body",
6766                    arg.span,
6767                    "`@limit` `maxBody` must be a positive `Int` literal — a byte count (e.g. `26_214_400`), or an `Int` constant bound to one",
6768                ),
6769                arg,
6770            ));
6771        }
6772        None => {
6773            errors.push(
6774                CompileError::new(
6775                    "bynk.http.limit_bad_max_body",
6776                    ann.span,
6777                    "`@limit` requires a `maxBody:` argument — the byte ceiling",
6778                )
6779                .with_note(
6780                    "the ceiling is a policy the compiler cannot derive; only the author knows it",
6781                ),
6782            );
6783        }
6784    }
6785}
6786
6787/// Validate `@raw`'s arguments on a body-taking route (ADR 0143's request-side
6788/// counterpart): a required `contentType:` string literal that is a media type
6789/// (`type/subtype`) or `"*/*"`. The vocabulary is closed.
6790fn validate_raw_args(ann: &Annotation, errors: &mut Vec<CompileError>) {
6791    let mut content_type: Option<&AnnotationArg> = None;
6792    for arg in &ann.args {
6793        match arg.label.as_ref().map(|l| l.name.as_str()) {
6794            Some("contentType") => content_type = Some(arg),
6795            _ => {
6796                errors.push(
6797                    CompileError::new(
6798                        "bynk.http.raw_unknown_arg",
6799                        arg.span,
6800                        "`@raw` accepts only the `contentType:` argument",
6801                    )
6802                    .with_note("write `@raw(contentType: \"application/octet-stream\")`"),
6803                );
6804            }
6805        }
6806    }
6807    match content_type.map(|a| &a.value.kind) {
6808        Some(ExprKind::StrLit(s)) if bynk_syntax::ast::is_media_type(s) => {}
6809        Some(_) => {
6810            let arg = content_type.unwrap();
6811            errors.push(crate::annotation_consts::with_const_origin(
6812                CompileError::new(
6813                    "bynk.http.raw_bad_content_type",
6814                    arg.span,
6815                    "`@raw` `contentType` must be a media type string literal (or a `String` constant bound to one) — `type/subtype`, or `\"*/*\"` to accept any",
6816                ),
6817                arg,
6818            ));
6819        }
6820        None => {
6821            errors.push(
6822                CompileError::new(
6823                    "bynk.http.raw_bad_content_type",
6824                    ann.span,
6825                    "`@raw` requires a `contentType:` argument — the media type the route accepts",
6826                )
6827                .with_note("use `\"*/*\"` to accept any content type"),
6828            );
6829        }
6830    }
6831}
6832
6833/// #3873: the schedule must be valid Cloudflare cron syntax
6834/// ([`bynk_syntax::cron::is_cron_expression`]); the message names the failing
6835/// field. A valid one may draw the two advisory warnings (`numeric_weekday`,
6836/// `uneven_step`), both silenced by writing a name or an explicit list.
6837fn check_cron_schedule(handler: &Handler, expr: &str, errors: &mut Vec<CompileError>) {
6838    match bynk_syntax::cron::is_cron_expression(expr) {
6839        Err(fault) => {
6840            let mut err = CompileError::new(
6841                "bynk.cron.invalid_schedule",
6842                handler.span,
6843                format!("cron schedule `{expr}` is invalid: {}", fault.message()),
6844            )
6845            .with_note(
6846                "the fields are: minute hour day-of-month month day-of-week, separated by exactly one space",
6847            );
6848            let single_spaced = expr.split_whitespace().collect::<Vec<_>>().join(" ");
6849            if single_spaced != expr
6850                && bynk_syntax::cron::is_cron_expression(&single_spaced).is_ok()
6851            {
6852                err = err.with_note(format!(
6853                    "write it with single spaces: `{single_spaced}` (Cloudflare matches the schedule character for character)"
6854                ));
6855            }
6856            errors.push(err);
6857        }
6858        Ok(()) => {
6859            if bynk_syntax::cron::numeric_weekday(expr) {
6860                errors.push(
6861                    CompileError::new(
6862                        "bynk.cron.numeric_weekday",
6863                        handler.span,
6864                        format!("cron schedule `{expr}` names a day of the week by number"),
6865                    )
6866                    .with_note(
6867                        "on Cloudflare `1` is Sunday, so a number is a day earlier than standard cron's (`5` is Thursday, not Friday); write the name (`FRI`) to be explicit",
6868                    ),
6869                );
6870            }
6871            if let Some(when) = bynk_syntax::cron::uneven_step(expr) {
6872                errors.push(
6873                    CompileError::new(
6874                        "bynk.cron.uneven_step",
6875                        handler.span,
6876                        format!("cron schedule `{expr}` has an uneven step"),
6877                    )
6878                    .with_note(when)
6879                    .with_note(
6880                        "list the times you mean, or use a step that divides the field's range",
6881                    ),
6882                );
6883            }
6884        }
6885    }
6886}
6887
6888/// Validate an `on schedule("expr") (at: Instant?) -> Effect[Result[(), E]]`
6889/// handler (v0.10a §4.1): at most one `Instant` parameter (the scheduled time), a structurally well-formed schedule, and the unit-Result
6890/// return shape. The service-only rule is enforced earlier, in the parser
6891/// (`bynk.parse.handler_in_agent`).
6892fn validate_cron_handler(handler: &Handler, expr: &str, errors: &mut Vec<CompileError>) {
6893    // A cron handler takes at most one parameter — the scheduled time, typed
6894    // `Instant`. A scheduled trigger has no other payload.
6895    if handler.params.len() > 1 {
6896        errors.push(
6897            CompileError::new(
6898                "bynk.cron.bad_params",
6899                handler.params[1].span,
6900                "`on schedule` handlers take at most one parameter (the scheduled time)",
6901            )
6902            .with_note("a scheduled trigger's only input is the time it fired"),
6903        );
6904    } else if let Some(p) = handler.params.first()
6905        && !matches!(p.type_ref, TypeRef::Base(BaseType::Instant, _))
6906    {
6907        errors.push(
6908            CompileError::new(
6909                "bynk.cron.bad_params",
6910                p.type_ref.span(),
6911                format!(
6912                    "an `on schedule` parameter must be `Instant` (the scheduled time), got `{}`",
6913                    ts_type_ref_display(&p.type_ref),
6914                ),
6915            )
6916            .with_note(
6917                "declare it as `at: Instant`; where the body needs the number, use `at.toEpochMillis()`",
6918            ),
6919        );
6920    }
6921    check_cron_schedule(handler, expr, errors);
6922    // The return type must be `Effect[Result[(), E]]`.
6923    let return_ok = match &handler.return_type {
6924        TypeRef::Effect(inner, _) => match inner.as_ref() {
6925            TypeRef::Result(ok, _err, _) => matches!(ok.as_ref(), TypeRef::Unit(_)),
6926            _ => false,
6927        },
6928        _ => false,
6929    };
6930    if !return_ok {
6931        errors.push(CompileError::new(
6932            "bynk.cron.return_not_effect_result",
6933            handler.return_type.span(),
6934            format!(
6935                "`on cron` handler must return `Effect[Result[(), E]]`, but got `{}`",
6936                ts_type_ref_display(&handler.return_type),
6937            ),
6938        ));
6939    }
6940}
6941
6942/// Validate an `on message(message: T) -> Effect[QueueResult]` handler of a
6943/// `from queue("name")` service (v0.10b §4.2, v0.44): a queue name Cloudflare
6944/// accepts (`is_queue_name`), exactly one parameter (the message, any
6945/// wire-deserialisable type), and the `Effect[QueueResult]` return — the verdict
6946/// sum, where `Ack` acknowledges the message and `Retry(...)` has it redelivered. The service-only rule is
6947/// enforced earlier, in the parser (`bynk.parse.handler_in_agent`).
6948fn validate_queue_handler(handler: &Handler, name: &str, errors: &mut Vec<CompileError>) {
6949    if name.is_empty() {
6950        errors.push(CompileError::new(
6951            "bynk.queue.invalid_name",
6952            handler.span,
6953            "`on queue` requires a non-empty queue name",
6954        ));
6955    } else if !crate::project_model::is_queue_name(name) {
6956        errors.push(
6957            CompileError::new(
6958                "bynk.queue.invalid_name",
6959                handler.span,
6960                format!("`{name}` is not a queue name Cloudflare accepts"),
6961            )
6962            .with_note(
6963                "a queue name is 1 to 63 lowercase letters, digits or `-`, and starts and ends with a letter or digit",
6964            ),
6965        );
6966    }
6967    // Exactly one parameter — the message. (Conventionally named `message`.)
6968    if handler.params.len() != 1 {
6969        errors.push(
6970            CompileError::new(
6971                "bynk.queue.bad_params",
6972                handler.span,
6973                format!(
6974                    "`on message` handlers take exactly one parameter (the message), got {}",
6975                    handler.params.len(),
6976                ),
6977            )
6978            .with_note("a queue consumer processes one message per invocation"),
6979        );
6980    }
6981    // v0.44: the return type must be `Effect[QueueResult]` (the verdict sum).
6982    let return_ok = match &handler.return_type {
6983        TypeRef::Effect(inner, _) => matches!(inner.as_ref(), TypeRef::QueueResult(_)),
6984        _ => false,
6985    };
6986    if !return_ok {
6987        errors.push(CompileError::new(
6988            "bynk.queue.return_not_queue_result",
6989            handler.return_type.span(),
6990            format!(
6991                "`on message` handler must return `Effect[QueueResult]`, but got `{}`",
6992                ts_type_ref_display(&handler.return_type),
6993            ),
6994        ));
6995    }
6996}
6997
6998/// True when `r` resolves to `String`, a refined-base `String`, or an
6999/// opaque-base `String`. v0.9 path parameter requirement.
7000fn is_string_constructible(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
7001    match r {
7002        TypeRef::Base(BaseType::String, _) => true,
7003        TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
7004            Some(TypeBody::Refined { base, .. }) => *base == BaseType::String,
7005            Some(TypeBody::Opaque { base, .. }) => *base == BaseType::String,
7006            _ => false,
7007        },
7008        _ => false,
7009    }
7010}
7011
7012/// v0.20a: function types are confined to non-boundary positions — fn/lambda
7013/// parameters, returns, and locals. Walk a type reference and reject any
7014/// function type found in a position that would serialise, persist, or cross
7015/// a boundary (`bynk.types.function_at_boundary`).
7016/// v0.102 (§2.9): true if a type *is or wraps* a held resource (`Connection`),
7017/// looking through `Option`/`Effect` — the shapes a held value legitimately
7018/// takes: an `Option[Connection]` cell value, an `Effect[Connection]` capability
7019/// return, a bare `Connection` handler parameter.
7020pub fn type_ref_is_held(r: &TypeRef) -> bool {
7021    match r {
7022        TypeRef::Connection(..) => true,
7023        TypeRef::Option(inner, _) | TypeRef::Effect(inner, _) => type_ref_is_held(inner),
7024        _ => false,
7025    }
7026}
7027
7028/// v0.102 (§2.9.3): validate one agent `store` field's value types, applying the
7029/// held-resource storage rules. Held values are admitted in
7030/// `Cell[Option[Connection]]` / `Map[K, Connection]` (an exception to the
7031/// serialisable-value rule — hibernation preserves them, not JSON), and rejected
7032/// in `Set`/`Log`/`Cache`. Non-held value types fall through to the ordinary
7033/// boundary check.
7034pub fn validate_store_field_value_types(
7035    f: &StoreField,
7036    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
7037    errors: &mut Vec<CompileError>,
7038) {
7039    let head = f.kind.head.name.as_str();
7040    let reject_held_storage = |span: Span, errors: &mut Vec<CompileError>| {
7041        errors.push(
7042            CompileError::new(
7043                "bynk.held.unsupported_storage",
7044                span,
7045                format!(
7046                    "a held value cannot be stored in a `{head}` — held resources may only live in `Cell[Option[Connection]]` or `Map[K, Connection]` (§2.9.3)"
7047                ),
7048            )
7049            .with_note(
7050                "`Set` needs value-equality, and `Log`/`Cache` would retain or evict a held resource without disposing it",
7051            ),
7052        );
7053    };
7054    match head {
7055        // The value position(s) where a held resource is admitted.
7056        "Cell" => match f.kind.args.first() {
7057            Some(v) if type_ref_is_held(v) => {} // admitted
7058            Some(v) => reject_fn_types(v, "an agent store field", types, errors),
7059            None => {}
7060        },
7061        "Map" => match f.kind.args.as_slice() {
7062            [k, v] => {
7063                reject_fn_types(k, "an agent store field", types, errors); // key
7064                if !type_ref_is_held(v) {
7065                    reject_fn_types(v, "an agent store field", types, errors);
7066                }
7067            }
7068            args => {
7069                for arg in args {
7070                    reject_fn_types(arg, "an agent store field", types, errors);
7071                }
7072            }
7073        },
7074        // Kinds that reject held values outright.
7075        "Set" | "Cache" | "Log" => {
7076            for arg in &f.kind.args {
7077                if type_ref_is_held(arg) {
7078                    reject_held_storage(arg.span(), errors);
7079                } else {
7080                    reject_fn_types(arg, "an agent store field", types, errors);
7081                }
7082            }
7083        }
7084        _ => {
7085            for arg in &f.kind.args {
7086                reject_fn_types(arg, "an agent store field", types, errors);
7087            }
7088        }
7089    }
7090}
7091
7092/// The `what` labels of the boundary positions whose rule differs by position
7093/// (a `Stream` or a `bynk.crypto` key passes through some). [`reject_fn_types`]
7094/// decides by them, so every caller names its position through these rather
7095/// than a literal, and a reworded label can't silently change a check.
7096pub const CAPABILITY_SIGNATURE: &str = "a capability operation signature";
7097pub const RECORD_FIELD: &str = "a record field";
7098pub const SUM_PAYLOAD: &str = "a sum-variant payload";
7099/// #3343: the `cookies`, `query` or `@form` `body` record of an `on http` handler:
7100/// the one position where a record with `@name` fields is allowed. Every other
7101/// boundary check still applies to it.
7102pub const REQUEST_RECORD_PARAM: &str = "a request record parameter";
7103
7104pub fn reject_fn_types(
7105    r: &TypeRef,
7106    what: &str,
7107    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
7108    errors: &mut Vec<CompileError>,
7109) {
7110    match r {
7111        TypeRef::Fn(_, _, span) => {
7112            errors.push(
7113                CompileError::new(
7114                    "bynk.types.function_at_boundary",
7115                    *span,
7116                    format!(
7117                        "a function type cannot appear in {what} — functions cannot serialise or cross a boundary"
7118                    ),
7119                )
7120                .with_note(
7121                    "function types are confined to fn/lambda parameters, returns, and locals",
7122                ),
7123            );
7124        }
7125        // v0.91 (ADR 0115 D2): a `Query[T]` is non-storable and non-boundary —
7126        // built, passed within an agent, and executed, never persisted or sent.
7127        TypeRef::Query(_, span) => {
7128            errors.push(
7129                CompileError::new(
7130                    "bynk.types.query_at_boundary",
7131                    *span,
7132                    format!(
7133                        "a `Query` type cannot appear in {what} — a query is built and executed in place, never persisted or sent across a boundary"
7134                    ),
7135                )
7136                .with_note(
7137                    "terminate the query (`.collect`/`.first`/…) and store or send the result instead",
7138                ),
7139            );
7140        }
7141        // #2380 (L5): `TokenClaims` are an `Oidc` actor's verified token, read
7142        // through its binder where the request arrives — never stored or sent.
7143        TypeRef::TokenClaims(span) => {
7144            errors.push(
7145                CompileError::new(
7146                    "bynk.types.claims_at_boundary",
7147                    *span,
7148                    format!(
7149                        "a `TokenClaims` type cannot appear in {what} — it is a verified token's claims, read in the handler that received the token, never persisted or sent"
7150                    ),
7151                )
7152                .with_note(
7153                    "read the claim you need (`who.claims.get(\"repository\")`) and store or send that value instead",
7154                ),
7155            );
7156        }
7157        // #2341 (decision A): `RequestHeaders` is an HTTP handler's view of
7158        // the request it is answering — read where it arrives, never stored
7159        // or sent. Its one legal position, a handler's `headers` parameter,
7160        // is not checked here.
7161        TypeRef::RequestHeaders(span) => {
7162            errors.push(
7163                CompileError::new(
7164                    "bynk.types.headers_at_boundary",
7165                    *span,
7166                    format!(
7167                        "a `RequestHeaders` type cannot appear in {what} — it is the request's headers, read in the handler that receives them, never persisted or sent"
7168                    ),
7169                )
7170                .with_note(
7171                    "read the header you need (`headers.get(\"…\")`) and store or send that value instead",
7172                ),
7173            );
7174        }
7175        // #2854 (decision B): `RequestQuery`, the same way — read in the
7176        // handler's `query` parameter, never stored or sent.
7177        TypeRef::RequestQuery(span) => {
7178            errors.push(
7179                CompileError::new(
7180                    "bynk.types.request_query_at_boundary",
7181                    *span,
7182                    format!(
7183                        "a `RequestQuery` type cannot appear in {what} — it is the request's query string, read in the handler that receives it, never persisted or sent"
7184                    ),
7185                )
7186                .with_note(
7187                    "read the value you need (`query.get(\"…\")`) and store or send that value instead",
7188                ),
7189            );
7190        }
7191        // #3277: `RequestCookies`, the same way — read in the handler's `cookies`
7192        // parameter, never stored or sent.
7193        TypeRef::RequestCookies(span) => {
7194            errors.push(
7195                CompileError::new(
7196                    "bynk.types.request_cookies_at_boundary",
7197                    *span,
7198                    format!(
7199                        "a `RequestCookies` type cannot appear in {what} — it is the request's cookies, read in the handler that receives it, never persisted or sent"
7200                    ),
7201                )
7202                .with_note(
7203                    "read the value you need (`cookies.get(\"…\")`) and store or send that value instead",
7204                ),
7205            );
7206        }
7207        // #2341 (decision C): a `BoundaryRejection` is the router's account of
7208        // a request it refused, read by `on rejected` and never kept.
7209        TypeRef::BoundaryRejection(span) => {
7210            errors.push(
7211                CompileError::new(
7212                    "bynk.types.rejection_at_boundary",
7213                    *span,
7214                    format!(
7215                        "a `BoundaryRejection` type cannot appear in {what} — it describes a request the router refused, read by `on rejected`, never persisted or sent"
7216                    ),
7217                )
7218                .with_note(
7219                    "match on the rejection in `on rejected` and store or send what you need from it instead",
7220                ),
7221            );
7222        }
7223        // K-streams (#2623): a capability operation's provider runs in the
7224        // caller's isolate, so a stream passes through its signature as the
7225        // same iterable; and a record or sum may carry one, becoming
7226        // non-boundary itself (the `Named` arm below finds it at each use).
7227        TypeRef::Stream(..) if stream_passes(what) => {}
7228        // v0.100: a `Stream[T]` is non-storable and non-boundary — a live
7229        // value-over-time source, built and consumed in place, never persisted
7230        // or sent.
7231        TypeRef::Stream(_, span) => {
7232            errors.push(
7233                CompileError::new(
7234                    "bynk.types.stream_at_boundary",
7235                    *span,
7236                    format!(
7237                        "a `Stream` type cannot appear in {what} — a stream is a live value-over-time source, never persisted or sent across a boundary"
7238                    ),
7239                )
7240                .with_note(
7241                    "drain the stream (`.collect()`) and store or send the resulting `List` instead",
7242                ),
7243            );
7244        }
7245        // v0.102: a `Connection[F]` (a held resource) is non-boundary — built
7246        // and disposed in place under the linearity discipline, never persisted
7247        // or sent across a boundary.
7248        TypeRef::Connection(_, span) => {
7249            errors.push(
7250                CompileError::new(
7251                    "bynk.types.held_at_boundary",
7252                    *span,
7253                    format!(
7254                        "a `Connection` type cannot appear in {what} — a held resource is built and disposed in place, never persisted or sent across a boundary"
7255                    ),
7256                )
7257                .with_note(
7258                    "hold the connection in agent state (`Cell[Option[Connection]]` / `Map[K, Connection]`) instead of crossing a boundary with it",
7259                ),
7260            );
7261        }
7262        // v0.20b: the boundary rule looks through collections — a
7263        // `List[Int -> Int]` field is still `function_at_boundary`.
7264        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
7265            reject_fn_types(a, what, types, errors);
7266            reject_fn_types(b, what, types, errors);
7267        }
7268        TypeRef::Option(a, _)
7269        | TypeRef::Effect(a, _)
7270        | TypeRef::HttpResult(a, _)
7271        | TypeRef::List(a, _)
7272        | TypeRef::Set(a, _) => reject_fn_types(a, what, types, errors),
7273        // v0.119: a `History[Agent]` reaching a declared position is already
7274        // reported by the resolver (`bynk.history.outside_property`); nothing to
7275        // add here.
7276        TypeRef::History(_, _) => {}
7277        // v0.174 (#592): a generic record instantiation is boundary-serialisable
7278        // through its monomorphised codec (`serialise_Paginated_User`) — so the
7279        // application itself is admitted, and the rule instead looks *through* it
7280        // into the type arguments. A non-serialisable argument (a function, a
7281        // `Query`, …) is rejected there, with the argument's own boundary error.
7282        // #3192: a *recursive* generic (one that transitively contains itself)
7283        // has no codec yet, but declares and works in memory, so — as for a
7284        // stream (K-streams, #2623) — a record field, a sum payload and a
7285        // capability signature pass it, and it is refused where it is used at
7286        // a position that serialises, naming the field path when it is reached
7287        // through another type (the resolver's `recursive_record_field` guard
7288        // only catches a direct self-edge in a non-generic record).
7289        TypeRef::App { name, args, span } => {
7290            if !stream_passes(what)
7291                && let Some(rg) = bynk_syntax::ast::recursive_generic_path(
7292                    &TypeRef::App {
7293                        name: name.clone(),
7294                        args: Vec::new(),
7295                        span: *span,
7296                    },
7297                    types,
7298                )
7299            {
7300                errors.push(recursive_generic_at_boundary(&rg, *span, what));
7301            }
7302            for a in args {
7303                reject_fn_types(a, what, types, errors);
7304            }
7305            // K-streams (#2623): a generic record whose own fields carry a
7306            // stream (`Wrap[T] = { s: Stream[T] }`) is found through its
7307            // declaration; a stream argument was reported just above.
7308            if !stream_passes(what)
7309                && let Some(path) =
7310                    bynk_syntax::ast::stream_path(&TypeRef::Named(name.clone()), types)
7311            {
7312                errors.push(stream_carrying_at_boundary(&name.name, &path, *span, what));
7313            }
7314        }
7315        // #1883, slice 1a: an `Asset` names a file the platform serves; it
7316        // is not data. What crosses a boundary or is stored is its `.url`.
7317        TypeRef::Asset(span) => {
7318            errors.push(
7319                CompileError::new(
7320                    "bynk.types.asset_at_boundary",
7321                    *span,
7322                    format!(
7323                        "an `Asset` type cannot appear in {what} — an asset names a file the platform serves, not a value to persist or send"
7324                    ),
7325                )
7326                .with_note("store or send the asset's `.url` (a `String`) instead"),
7327            );
7328        }
7329        // P4c (#2628): a `SqlStatement` restored or received from outside
7330        // would carry SQL that was never a literal. `D1.batch` takes one, so a
7331        // capability operation's signature is exempt, as for keys.
7332        TypeRef::Named(id)
7333            if what != CAPABILITY_SIGNATURE
7334                && crate::checker::is_sql_statement_type(&id.name, types) =>
7335        {
7336            errors.push(statement_at_boundary(id.span, what, &id.name));
7337        }
7338        // K4: a `bynk.crypto` key holds a non-extractable platform key. It is
7339        // imported where it is used and lives for that call: persisting,
7340        // serialising or sending it would either leak the secret or be
7341        // meaningless, so it is non-storable and non-boundary like a `Stream`.
7342        // A capability operation is where a key is meant to flow (`Crypto.sign`
7343        // takes one), in-process, so its signature is exempt.
7344        TypeRef::Named(id)
7345            if what != CAPABILITY_SIGNATURE && is_crypto_key_type(&id.name, types) =>
7346        {
7347            errors.push(
7348                CompileError::new(
7349                    "bynk.types.key_at_boundary",
7350                    id.span,
7351                    format!(
7352                        "a `{}` cannot appear in {what} — a key is held non-extractable by the platform and lives for the call that imported it, never persisted, logged or sent across a boundary",
7353                        id.name
7354                    ),
7355                )
7356                .with_note(
7357                    "keep the key bytes in `Secrets` and import the key again where it is used (`Crypto.importSigningKey` / `Crypto.importVerifyKey`)",
7358                ),
7359            );
7360        }
7361        // #3343: a record with `@name` fields is read off an HTTP request by name,
7362        // so its JSON form is not its wire form: it may not be a body, a result,
7363        // a store field, an event or a call argument.
7364        TypeRef::Named(id)
7365            if what != REQUEST_RECORD_PARAM && record_has_field_names(&id.name, types) =>
7366        {
7367            errors.push(
7368                CompileError::new(
7369                    "bynk.types.field_name_record_not_boundary",
7370                    id.span,
7371                    format!(
7372                        "`{}` has `@name` fields, so it can only be a `cookies`, `query` or `@form`/`@multipart` `body` parameter, not {what}",
7373                        id.name
7374                    ),
7375                )
7376                .with_note(
7377                    "a record's JSON form uses its field names, so a `@name` rename would split the two; use a separate record for this position",
7378                ),
7379            );
7380        }
7381        // #3276: a `File` is a file part of a `@multipart` request, held in
7382        // memory for the handler that receives it. A record field or sum payload
7383        // may carry one (that is how a `@multipart` body names its parts), but it
7384        // is never persisted, sent across a boundary or returned.
7385        TypeRef::Named(id) if !stream_passes(what) && is_std_file_type(&id.name, types) => {
7386            errors.push(file_at_boundary(&id.name, &[], id.span, what));
7387        }
7388        // K-streams (#2623): a record or sum that carries a stream, at any
7389        // depth, is non-boundary like the stream.
7390        TypeRef::Named(id) if !stream_passes(what) => {
7391            if let Some(path) = file_path(r, types) {
7392                errors.push(file_at_boundary(&id.name, &path, id.span, what));
7393            }
7394            if let Some(path) = bynk_syntax::ast::stream_path(r, types) {
7395                errors.push(stream_carrying_at_boundary(&id.name, &path, id.span, what));
7396            }
7397            // #3192: a type that merely contains a recursive generic.
7398            if let Some(rg) = bynk_syntax::ast::recursive_generic_path(r, types) {
7399                errors.push(recursive_generic_at_boundary(&rg, id.span, what));
7400            }
7401        }
7402        TypeRef::Base(..)
7403        | TypeRef::Named(_)
7404        | TypeRef::QueueResult(_)
7405        | TypeRef::ValidationError(_)
7406        | TypeRef::DecodeError(_)
7407        | TypeRef::Unit(_) => {}
7408    }
7409}
7410
7411/// #3343: whether `name` is a record with a `@name`-annotated field.
7412fn record_has_field_names(name: &str, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
7413    matches!(
7414        types.get(name).map(|t| &t.body),
7415        Some(TypeBody::Record(r)) if r.fields.iter().any(|f| !f.annotations.is_empty())
7416    )
7417}
7418
7419/// #3276: `bynk.types.file_at_boundary` for a `File`, or a type that carries one,
7420/// at a position that persists or sends it.
7421fn file_at_boundary(name: &str, path: &[String], span: Span, what: &str) -> CompileError {
7422    let reach = if path.is_empty() {
7423        String::new()
7424    } else {
7425        let chain = path
7426            .iter()
7427            .map(|f| format!("`{f}`"))
7428            .collect::<Vec<_>>()
7429            .join(", then ");
7430        format!(" (it is reached through {chain})")
7431    };
7432    CompileError::new(
7433        "bynk.types.file_at_boundary",
7434        span,
7435        format!(
7436            "`{name}` cannot appear in {what} — it holds a file part of a multipart request in memory, never persisted, sent across a boundary or returned{reach}"
7437        ),
7438    )
7439    .with_note(
7440        "take the part's `bytes` (and `filename`, `contentType`) in the `@multipart` handler and store them where they belong, as `R2.put(key, f.bytes)` does",
7441    )
7442}
7443
7444/// K-streams (#2623): the positions a `Stream` may appear in. A capability
7445/// operation's provider runs in the caller's isolate, so nothing in its
7446/// signature is serialised; a record field or sum payload makes its type
7447/// stream-carrying, which is then checked where the type is used.
7448fn stream_passes(what: &str) -> bool {
7449    [CAPABILITY_SIGNATURE, RECORD_FIELD, SUM_PAYLOAD].contains(&what)
7450}
7451
7452/// #3192: `bynk.generics.recursive_generic_at_boundary` for a recursive generic
7453/// type at a position that serialises. The noun comes from the declaration
7454/// (`record` or `sum`); a type that only contains the generic names the field
7455/// chain it is reached through.
7456pub(crate) fn recursive_generic_at_boundary(
7457    rg: &bynk_syntax::ast::RecursiveGenericPath,
7458    span: Span,
7459    what: &str,
7460) -> CompileError {
7461    let err = CompileError::new(
7462        "bynk.generics.recursive_generic_at_boundary",
7463        span,
7464        format!(
7465            "recursive generic {} `{}` cannot appear in {what} — it has no codec yet",
7466            rg.noun, rg.name
7467        ),
7468    );
7469    let chain = rg
7470        .path
7471        .iter()
7472        .map(|f| format!("`{f}`"))
7473        .collect::<Vec<_>>()
7474        .join(", then ");
7475    let reach = if rg.path.is_empty() {
7476        String::new()
7477    } else {
7478        format!(" (it is reached through {chain})")
7479    };
7480    err.with_note(format!(
7481        "a recursive generic type declares and works inside a context, but has no codec yet{reach}; \
7482         use a concrete recursive type, or keep it inside the context"
7483    ))
7484}
7485
7486/// K-streams (#2623): `bynk.types.stream_at_boundary` for a type that carries
7487/// a stream in a field, naming the field chain it is reached through.
7488fn stream_carrying_at_boundary(
7489    name: &str,
7490    path: &[String],
7491    span: Span,
7492    what: &str,
7493) -> CompileError {
7494    let chain = path
7495        .iter()
7496        .map(|f| format!("`{f}`"))
7497        .collect::<Vec<_>>()
7498        .join(", then ");
7499    CompileError::new(
7500        "bynk.types.stream_at_boundary",
7501        span,
7502        format!(
7503            "`{name}` cannot appear in {what} — it carries a `Stream`, a live value-over-time source, never persisted or sent across a boundary"
7504        ),
7505    )
7506    .with_note(format!(
7507        "the stream is reached through {chain}; drain it (`.collect()`) into a type without one before it crosses"
7508    ))
7509}
7510
7511/// Whether `name`, in the project's type table, is one of `bynk.crypto`'s key
7512/// types ([`crate::firstparty::CRYPTO_KEY_TYPES`]). Found by the declaration's
7513/// span file, which is the unit's reserved first-party id, so a user type that
7514/// happens to share the name is not mistaken for one.
7515pub(crate) fn is_crypto_key_type(
7516    name: &str,
7517    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
7518) -> bool {
7519    crate::firstparty::CRYPTO_KEY_TYPES.contains(&name)
7520        && types.get(name).is_some_and(|decl| {
7521            crate::firstparty::unit(crate::firstparty::CRYPTO_UNIT).is_some_and(|unit| {
7522                decl.span.file == crate::project_model::firstparty_file_id(unit)
7523            })
7524        })
7525}
7526
7527/// #1170: `TypedCommons::actor_bindings` persistence — every case
7528/// `handler_actor_binding` itself distinguishes (Some vs. None, single
7529/// actor vs. sum, the binder-shadows-param suppression), pinned through
7530/// the real `check_context_declarations` entry point on a certified
7531/// program, not by calling `handler_actor_binding` directly.
7532#[cfg(test)]
7533mod actor_binding_persistence_tests {
7534    use super::*;
7535    use crate::checker::CheckedProgram;
7536    use crate::{resolver, symbols};
7537    use bynk_project::UnitKind;
7538    use bynk_syntax::ast::{ActorDecl, Commons, CommonsItem, ServiceDecl, SourceUnit};
7539    use bynk_syntax::{lexer, parser};
7540
7541    /// Parse+resolve+check+context-check a whole `context` unit from
7542    /// source, stopping short of `certify` — mirrors `bynk-emit`'s own
7543    /// `checked_context_program` test helper (`bynk-emit/src/ir/lower.rs`)
7544    /// closely, but populates `services`/`actors` on the `UnitTable` too
7545    /// (that helper's own agent-only scope never needed them). Returns the
7546    /// raw `(TypedCommons, errors)` pair rather than a `CheckedProgram` so
7547    /// [`binder_shadowing_a_param_persists_no_binding`] can inspect
7548    /// `actor_bindings` even on a source that *cannot* certify (a hard
7549    /// `bynk.actor.binder_shadows_param` error) — every other test here
7550    /// wraps this in [`checked_context_program`] instead.
7551    fn checked_context_commons(source: &str) -> (checker::TypedCommons, Vec<CompileError>) {
7552        let tokens = lexer::tokenize(source).expect("lex");
7553        let unit = parser::parse_unit(&tokens, source).expect("parse");
7554        let SourceUnit::Context(ctx) = unit else {
7555            panic!("expected a context unit, got {unit:?}")
7556        };
7557        let commons = Commons {
7558            name: ctx.name,
7559            items: ctx.items,
7560            uses: ctx.uses,
7561            documentation: ctx.documentation,
7562            form: ctx.form,
7563            span: ctx.span,
7564            trivia: ctx.trivia,
7565            trailing_comments: ctx.trailing_comments,
7566        };
7567        let resolved = resolver::resolve(commons).expect("resolve");
7568        let mut typed = checker::check(resolved).expect("check");
7569        let services: HashMap<String, ServiceDecl> = typed
7570            .commons
7571            .items
7572            .iter()
7573            .filter_map(|item| match item {
7574                CommonsItem::Service(s) => Some((s.name.name.clone(), s.clone())),
7575                _ => None,
7576            })
7577            .collect();
7578        let actors: HashMap<String, ActorDecl> = typed
7579            .commons
7580            .items
7581            .iter()
7582            .filter_map(|item| match item {
7583                CommonsItem::Actor(a) => Some((a.name.name.clone(), a.clone())),
7584                _ => None,
7585            })
7586            .collect();
7587        let table = symbols::UnitTable {
7588            kind: Some(UnitKind::Context),
7589            types: typed.types.clone(),
7590            services,
7591            actors,
7592            ..symbols::UnitTable::default()
7593        };
7594        let tys = typed.ty_intern.clone();
7595        let errors = check_context_declarations(
7596            &mut typed,
7597            &table,
7598            &resolver::CrossContextInfo::default(),
7599            true,
7600            &HashSet::new(),
7601            &HashMap::new(),
7602            &mut RefSink::new(),
7603            &mut HintSink::new(),
7604            &mut LocalsSink::new(),
7605            &mut RequirementSink::new(),
7606            &tys,
7607        );
7608        (typed, errors)
7609    }
7610
7611    fn checked_context_program(source: &str) -> CheckedProgram {
7612        let (typed, errors) = checked_context_commons(source);
7613        checker::certify(typed, errors).expect("certify")
7614    }
7615
7616    fn find_service<'a>(typed: &'a checker::TypedCommons, name: &str) -> &'a ServiceDecl {
7617        typed
7618            .commons
7619            .items
7620            .iter()
7621            .find_map(|item| match item {
7622                CommonsItem::Service(s) if s.name.name == name => Some(s),
7623                _ => None,
7624            })
7625            .unwrap_or_else(|| panic!("no service named `{name}` in this fixture"))
7626    }
7627
7628    #[test]
7629    fn single_actor_by_clause_persists_the_binder_and_sealed_identity_ty() {
7630        let program = checked_context_program(
7631            r#"
7632context demo
7633
7634type UserId = String
7635
7636actor Buyer { auth = Internal, identity = UserId }
7637
7638service Api {
7639  on call(ping: String) -> Effect[String] by u: Buyer {
7640    Effect.pure(ping)
7641  }
7642}
7643"#,
7644        );
7645        let handler = &find_service(program.program(), "Api").handlers[0];
7646        let (binder, ty) = program
7647            .program()
7648            .actor_binding(handler.span)
7649            .unwrap_or_else(|| panic!("expected a persisted actor binding for this handler"));
7650        assert_eq!(binder, "u");
7651        let tys = &program.program().ty_intern;
7652        let Ty::Actor(identity_ty) = &*tys.get(*ty) else {
7653            panic!("expected Ty::Actor, got {:?}", tys.get(*ty))
7654        };
7655        assert_eq!(
7656            identity_ty.display(tys),
7657            "UserId",
7658            "the actor's own declared `identity = UserId` type, sealed"
7659        );
7660    }
7661
7662    #[test]
7663    fn prelude_caller_actor_persists_a_string_identity_binding() {
7664        // `Caller` (v0.54) is a prelude actor — no local `actor` declaration
7665        // needed — whose identity is the calling-context id, `String`.
7666        let program = checked_context_program(
7667            r#"
7668context demo
7669
7670service Api {
7671  on call(ping: String) -> Effect[String] by c: Caller {
7672    Effect.pure(c.identity)
7673  }
7674}
7675"#,
7676        );
7677        let handler = &find_service(program.program(), "Api").handlers[0];
7678        let (binder, ty) = program
7679            .program()
7680            .actor_binding(handler.span)
7681            .unwrap_or_else(|| panic!("expected a persisted actor binding for this handler"));
7682        assert_eq!(binder, "c");
7683        let string_ty = program
7684            .program()
7685            .ty_intern
7686            .intern(Ty::Base(bynk_syntax::ast::BaseType::String));
7687        let expected = program.program().ty_intern.intern(Ty::Actor(string_ty));
7688        assert_eq!(*ty, expected);
7689    }
7690
7691    #[test]
7692    fn sum_by_clause_persists_an_actor_sum_binding() {
7693        // Mirrors `bynk-tests/tests/fixtures/positive/916_bytes_http_sum_body`:
7694        // an HTTP route's `by who: User | Visitor` sum, `User` a real
7695        // `Bearer`-scheme local actor, `Visitor` the prelude unit-identity
7696        // actor — a sum's own peers must carry distinguishable schemes
7697        // (`bynk.actor.duplicate_sum_scheme`), which two `Internal`-scheme
7698        // actors (the only scheme a `call` handler admits) cannot, so this
7699        // one case needs `from http` rather than the plain `call` protocol
7700        // every other test here uses.
7701        let program = checked_context_program(
7702            r#"
7703context demo
7704
7705type UserId = String
7706
7707actor User { auth = Bearer(secret = "AUTH_SECRET"), identity = UserId }
7708
7709service Api from http {
7710  on GET("/whoami") () -> Effect[HttpResult[String]] by who: User | Visitor {
7711    match who {
7712      User(_) => Ok("user")
7713      Visitor => Ok("visitor")
7714    }
7715  }
7716}
7717"#,
7718        );
7719        let handler = &find_service(program.program(), "Api").handlers[0];
7720        let (binder, ty) = program
7721            .program()
7722            .actor_binding(handler.span)
7723            .unwrap_or_else(|| panic!("expected a persisted actor binding for this handler"));
7724        assert_eq!(binder, "who");
7725        let tys = &program.program().ty_intern;
7726        let Ty::ActorSum(members) = &*tys.get(*ty) else {
7727            panic!("expected Ty::ActorSum, got {:?}", tys.get(*ty))
7728        };
7729        assert_eq!(members.len(), 2);
7730        assert_eq!(members[0].0, "User");
7731        assert_eq!(members[0].1.display(tys), "UserId");
7732        assert_eq!(members[1].0, "Visitor");
7733        assert_eq!(
7734            members[1].1.display(tys),
7735            "()",
7736            "Visitor is a unit-identity prelude actor"
7737        );
7738    }
7739
7740    #[test]
7741    fn binderless_by_clause_persists_no_binding() {
7742        let program = checked_context_program(
7743            r#"
7744context demo
7745
7746type UserId = String
7747
7748actor Buyer { auth = Internal, identity = UserId }
7749
7750service Api {
7751  on call(ping: String) -> Effect[String] by Buyer {
7752    Effect.pure(ping)
7753  }
7754}
7755"#,
7756        );
7757        let handler = &find_service(program.program(), "Api").handlers[0];
7758        assert!(
7759            program.program().actor_binding(handler.span).is_none(),
7760            "a binder-less `by <Actor>` clause verifies-and-discards — no identity is bound, \
7761             so no persisted entry should exist for it either"
7762        );
7763    }
7764
7765    #[test]
7766    fn no_by_clause_persists_no_binding() {
7767        let program = checked_context_program(
7768            r#"
7769context demo
7770
7771service Api {
7772  on call(ping: String) -> Effect[String] by Caller {
7773    Effect.pure(ping)
7774  }
7775}
7776"#,
7777        );
7778        let handler = &find_service(program.program(), "Api").handlers[0];
7779        assert!(program.program().actor_binding(handler.span).is_none());
7780    }
7781
7782    #[test]
7783    fn binder_shadowing_a_param_persists_no_binding() {
7784        // `handler_actor_binding` suppresses the binding when the binder name
7785        // collides with a declared param (`bynk.actor.binder_shadows_param`)
7786        // — the body scope keeps the real parameter, not the actor. Pinning
7787        // this through persistence too, not just through the in-scope type.
7788        //
7789        // The shadow is a *hard* diagnostic — this source never certifies —
7790        // so this test reads `typed.actor_bindings` straight off the
7791        // pre-`certify` `TypedCommons` ([`checked_context_commons`]) rather
7792        // than going through [`checked_context_program`], which would panic
7793        // on `.expect("certify")` before this assertion ever ran.
7794        let (typed, _errors) = checked_context_commons(
7795            r#"
7796context demo
7797
7798type UserId = String
7799
7800actor Buyer { auth = Internal, identity = UserId }
7801
7802service Api {
7803  on call(u: String) -> Effect[String] by u: Buyer {
7804    Effect.pure(u)
7805  }
7806}
7807"#,
7808        );
7809        let handler = &find_service(&typed, "Api").handlers[0];
7810        assert!(typed.actor_binding(handler.span).is_none());
7811    }
7812
7813    #[test]
7814    fn multiple_handlers_persist_distinct_bindings_keyed_per_handler() {
7815        // Review of #1170: every fixture above declares exactly one handler,
7816        // so none of them can tell "keyed per handler" apart from "keyed per
7817        // service" (or from an over-broad insert) — a single span in play
7818        // reads the same either way. Three handlers, only two with a
7819        // binder, pins both: each binder lands on its own handler's own
7820        // span, and the binder-less handler contributes no entry at all.
7821        // #3766: a service has one `on call`, so the three are http routes.
7822        let program = checked_context_program(
7823            r#"
7824context demo
7825
7826type UserId = String
7827
7828actor Buyer { auth = Bearer(secret = "AUTH_JWT_SECRET"), identity = UserId }
7829
7830service Api from http {
7831  on GET("/a") () -> Effect[HttpResult[String]] by u: Buyer {
7832    Ok("a")
7833  }
7834  on GET("/b") () -> Effect[HttpResult[String]] by v: Buyer {
7835    Ok("b")
7836  }
7837  on GET("/c") () -> Effect[HttpResult[String]] by Visitor {
7838    Ok("c")
7839  }
7840}
7841"#,
7842        );
7843        let service = find_service(program.program(), "Api");
7844        assert_eq!(service.handlers.len(), 3);
7845        let (first, second, third) = (
7846            &service.handlers[0],
7847            &service.handlers[1],
7848            &service.handlers[2],
7849        );
7850        let (binder, _) = program
7851            .program()
7852            .actor_binding(first.span)
7853            .unwrap_or_else(|| panic!("expected a persisted binding for the first handler"));
7854        assert_eq!(binder, "u");
7855        let (binder, _) = program
7856            .program()
7857            .actor_binding(second.span)
7858            .unwrap_or_else(|| panic!("expected a persisted binding for the second handler"));
7859        assert_eq!(binder, "v");
7860        assert!(
7861            program.program().actor_binding(third.span).is_none(),
7862            "the third handler binds no actor (`by Visitor`, no binder)"
7863        );
7864        assert_eq!(
7865            program.program().actor_bindings.len(),
7866            2,
7867            "exactly the two `by`-bearing handlers, nothing extra persisted for the third"
7868        );
7869    }
7870}