Skip to main content

bynk_check/
test_suites.rs

1//! Test/integration-suite checking (P5.4,
2//! `design/tracks/semantics-in-the-checker.md` §6) — closes category 7 of
3//! `bynk-check/src/analysis.rs`'s own residual-gap accounting, the last of
4//! the seven. `bynk-emit/src/project/tests_emit.rs` held
5//! `process_tests`/`process_integration_tests`, real production code (not
6//! fixture noise, despite the filename) checking + emitting `suite`/`test
7//! integration` bodies — but it ran only inside `bynk-emit::run_checks`
8//! (`Mode::Analyse` included), never inside `bynk_check::analysis::analyse_project`,
9//! the entry point the LSP now uses. That gap meant no diagnostics *and* no
10//! `RefSink` bindings (go-to-definition/find-references) for anything inside
11//! a test file, in the editor — see `analysis.rs`'s own module doc for the
12//! full accounting this closes.
13//!
14//! **What moved here** — every check-only helper `process_tests`/
15//! `process_integration_tests` used, plus every function that is genuinely
16//! **dual-use**: called both by this module's own [`phase_test_bodies`]/
17//! [`phase_integration_bodies`] (the checking half, real diagnostic/`RefSink`
18//! sinks) *and* by `bynk-emit`'s TypeScript lowering (throwaway sinks, needed
19//! only for the resolved-type view a body's emission depends on). Dual-use
20//! functions are `pub`, and `bynk-emit` calls them qualified
21//! (`bynk_check::test_suites::foo(...)`) rather than duplicating them — see
22//! [`build_privileged_resolved`], [`typecheck_case_body`],
23//! [`check_history_binding`], [`register_call_record_types`],
24//! [`history_handlers`], [`history_variant_name`], [`prop_binding_generable`]
25//! and [`infer_participants`] for which and why (each names its own emit-side
26//! call sites). Duplicating a dual-use function instead of relocating it is
27//! exactly the drift risk this whole design track exists to close (§9,
28//! "Relocating checks risks a quiet R4.6/R4.11 regression").
29//!
30//! **What stayed in `bynk-emit`** (pure TypeScript emission, or verified
31//! emit-only by call-site count): `block_uses_observation`,
32//! `target_service_handler_kinds`, `is_attackable_contract`,
33//! `numeric_or_scalar_base`, `attackable_contracts`,
34//! `json_codec_qual_for_target`, `prop_history_binding`, `prop_is_history`,
35//! `SystemCaseInput`, `RunnableTest`, `discovered_location`,
36//! `discovery_manifest`, `sanitise_suite`, `emit_integration_module` and its
37//! http-driver/harness helpers, and the ~2,600-line TypeScript-codegen tail
38//! starting at `emit_test_module` (`emit_stub_class`, `gen_ts_for_ty`,
39//! `emit_test_property_function`, `emit_test_history_property_function`, and
40//! the rest).
41//!
42//! `bynk-emit/src/project/tests_emit.rs`'s own `process_tests`/
43//! `process_integration_tests` keep their exact signatures (`run_checks`'s
44//! callers need no change) — their bodies now call
45//! [`phase_test_bodies`]/[`phase_integration_bodies`] for the checking half,
46//! then proceed to their existing, unmoved Phase-5 emission logic using the
47//! "ready for emission" data these return.
48//!
49//! `bynk-emit` depends on `bynk-check` (a production dependency, never the
50//! reverse), so this move has no circular-dependency subtlety to solve —
51//! unlike P5.3's `phase_platform_lock`, which needed a from-scratch pure
52//! reimplementation because its old home reached into a `bynk-emit`
53//! TypeScript-codegen helper. This is a plain code-motion job, just a large
54//! one.
55
56use std::collections::{BTreeMap, HashMap, HashSet};
57use std::path::PathBuf;
58use std::sync::Arc;
59
60use crate::actors::CallSitePrincipal;
61use crate::checker::{self, Types};
62use crate::context_checks::{build_capability_op_info, ts_type_ref_display};
63use crate::hints::HintSink;
64use crate::index::{RefSink, SymbolKind};
65use crate::locals::LocalsSink;
66use crate::requirements::RequirementSink;
67use crate::resolver::{self, MethodTable as ResolverMethodTable, ResolvedCommons};
68use crate::symbols::{UnitTable, build_cross_context_info};
69use bynk_project::ParsedFile;
70use bynk_project::UnitKind;
71use bynk_project::discovery::{case_effective_tier, suite_effective_tier_is_system};
72use bynk_syntax::ast::*;
73use bynk_syntax::error::CompileError;
74use bynk_syntax::span::Span;
75
76/// Which runs of a target's test module a `stub` clause applies to (#291).
77/// Every suite targeting a unit is emitted into one module, so a clause's
78/// scope is narrowed to its own suite whenever another suite shares the
79/// module (#1860).
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum StubScope {
82    /// Every run: a suite-scoped clause of the target's only suite.
83    Every,
84    /// The run of the case of this name (a case-scoped clause). Case names
85    /// are unique across a target's suites (`bynk.suite.duplicate_case_name`).
86    Case(String),
87    /// Every run of the suite with this ordinal among the target's suites
88    /// ([`suite_ordinal`]): its cases and its properties. A suite-scoped
89    /// clause, when the target has more than one suite.
90    Suite(usize),
91}
92
93/// #1860: the ordinal of the suite at `parsed[i]` among the suites in
94/// `indices` (each index whose file is a suite), or `None` when `i` is not
95/// one. [`StubScope::Suite`] is keyed by it, so emission computes it the same
96/// way for each run.
97pub fn suite_ordinal(i: usize, indices: &[usize], parsed: &[ParsedFile]) -> Option<usize> {
98    indices
99        .iter()
100        .filter(|&&j| parsed[j].test().is_some())
101        .position(|&j| j == i)
102}
103
104/// v0.118: a capability seam with one or more `stub` overrides applied
105/// (testing track slice 6). Groups every `stub Cap.method(…)` clause — both
106/// suite-scoped and case-scoped — targeting the same capability `cap`. The
107/// resolved [`CapabilityDecl`] supplies each overridden method's parameter names
108/// and return type for stub emission.
109#[derive(Debug, Clone)]
110pub struct ResolvedStub {
111    /// The capability being overridden (a declared/consumed seam of the target).
112    pub cap: String,
113    /// The capability declaration, for op parameter names and return types.
114    pub cap_decl: CapabilityDecl,
115    /// #3892: when the seam is a consumed context's services rather than a
116    /// capability, that context's qualified name. `cap_decl` is then a synthetic
117    /// capability with one operation per stubbed service (its parameters and
118    /// return type those of the service's `on call` handler), so the stub
119    /// machinery treats a service as an operation.
120    pub service_context: Option<String>,
121    /// The `stub` clauses for this capability, in match order (case-scoped
122    /// first so they take precedence over suite-scoped in the emitted if-chain).
123    pub clauses: Vec<StubClause>,
124    /// #291: parallel to `clauses` — which runs each clause applies to.
125    pub clause_scopes: Vec<StubScope>,
126    /// #2850: parallel to `clauses` — the `fixture`s of the suite declaring each
127    /// clause, which its values and argument patterns may name.
128    pub clause_fixtures: Vec<Vec<FixtureDecl>>,
129    /// #2907: parallel to `clauses` — the helper `fn`s of the suite declaring
130    /// each clause, which its values and argument patterns may call.
131    pub clause_fns: Vec<Vec<FnDecl>>,
132    /// #3111: parallel to `clauses` — the `type`s and `const`s of the suite
133    /// declaring each clause, which its values may name.
134    pub clause_types: Vec<Vec<TypeDecl>>,
135    pub clause_consts: Vec<Vec<ConstDecl>>,
136    /// The test file declaring the first clause — the recording context for
137    /// edges in its value expressions (v0.25).
138    ///
139    /// ADR 0198/0201: a *recording context* is an index key, so this is the
140    /// file's **identity** (project-relative), not its `include`-root-relative
141    /// unit path. Everything the index keys must name a file the round
142    /// analysed.
143    pub identity_path: PathBuf,
144}
145
146/// P5.4 (`design/tracks/semantics-in-the-checker.md` §6): the checking half
147/// of `test <target>` suite processing — target resolution, duplicate-case-
148/// name detection, `stub`-clause resolution, and case/property body
149/// type-checking. Formerly Phases 2-4 of `bynk-emit`'s own `process_tests`;
150/// Phase 5 (TypeScript emission) stays in
151/// `bynk-driver::project::tests_emit::process_tests`, which calls this
152/// function for its checking half and then emits only for the targets this
153/// returns — every target this function resolves, has no duplicate case
154/// names, and whose bodies type-check clean is exactly "ready for
155/// emission". `bynk_check::analysis::analyse_project` calls this too and
156/// discards the returned map — it never emits, so only the diagnostic/
157/// `RefSink` side effects matter there. Closes category 7 of
158/// `bynk-check/src/analysis.rs`'s own residual-gap accounting, alongside
159/// [`phase_integration_bodies`].
160#[allow(clippy::too_many_arguments)]
161pub fn phase_test_bodies(
162    test_groups: &BTreeMap<String, Vec<usize>>,
163    parsed: &[ParsedFile],
164    kinds: &BTreeMap<String, UnitKind>,
165    unit_tables: &HashMap<String, UnitTable>,
166    exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
167    unit_consumes: &HashMap<String, Vec<String>>,
168    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
169    unit_uses: &HashMap<String, Vec<String>>,
170    // #3162: the declarations recovery skipped, per unit. A case that names
171    // one of its target's (or a used unit's) skipped declarations is not told
172    // the name is unknown: the syntax error already says why.
173    broken: &crate::project_model::BrokenDeclNames,
174    errors: &mut Vec<CompileError>,
175    refs: &mut RefSink,
176    locals: &mut LocalsSink,
177    tys: &Arc<Types>,
178    // #3108: the migrations' schemas, which a literal D1 statement in a case or
179    // property body is prepared against, as in a production body.
180    d1_sql: Option<&crate::d1_sql::D1Sql>,
181) -> HashMap<String, HashMap<String, ResolvedStub>> {
182    let mut ready: HashMap<String, HashMap<String, ResolvedStub>> = HashMap::new();
183
184    let mut sorted_targets: Vec<&String> = test_groups.keys().collect();
185    sorted_targets.sort();
186
187    for target_name in sorted_targets {
188        let indices = test_groups.get(target_name).unwrap();
189        // -- Phase 2: target resolution --
190        let target_kind = match kinds.get(target_name) {
191            Some(k) => *k,
192            None => {
193                let span = first_test_target_span(indices, parsed);
194                errors.push(
195                    CompileError::new(
196                        "bynk.suite.unknown_target",
197                        span,
198                        format!(
199                            "test target `{target_name}` is not a declared commons or context in this project",
200                        ),
201                    )
202                    .with_note(
203                        "the target of a `test` declaration must be a commons or context declared elsewhere in the project",
204                    ),
205                );
206                continue;
207            }
208        };
209
210        // -- Phase 2: duplicate test case names --
211        let mut seen_cases: HashMap<String, Span> = HashMap::new();
212        let mut had_dup = false;
213        for &i in indices {
214            if let Some(t) = parsed[i].test() {
215                for case in &t.cases {
216                    if let Some(prev) = seen_cases.get(&case.name) {
217                        had_dup = true;
218                        errors.push(
219                            CompileError::new(
220                                "bynk.suite.duplicate_case_name",
221                                case.name_span,
222                                format!(
223                                    "test case `\"{}\"` is declared more than once in tests targeting `{target_name}`",
224                                    case.name
225                                ),
226                            )
227                            .with_label(*prev, "previously declared here"),
228                        );
229                    } else {
230                        seen_cases.insert(case.name.clone(), case.name_span);
231                    }
232                }
233            }
234        }
235
236        // -- #2134: each suite's and case's `env` clauses. --
237        for &i in indices {
238            if let Some(t) = parsed[i].test() {
239                crate::test_env::check_env_clauses(t, errors);
240            }
241        }
242
243        // -- Phase 3: resolve `stub` clauses (v0.118, testing track slice 6).
244        // Both suite-scoped and case-scoped `stub` fold into one per-seam
245        // override map. Case-scoped clauses are collected first so they take
246        // precedence over suite-scoped ones in the emitted first-match if-chain
247        // (the case > suite > default order). Each clause applies only to its
248        // own case's run, or its own suite's cases (#291, #1860). Runs
249        // unconditionally, even when `had_dup` — its own diagnostics still
250        // fire, matching `process_tests`'s original Phase 2/3 ordering.
251        let target_stubs = resolve_stubs(
252            target_name,
253            target_kind,
254            indices,
255            parsed,
256            unit_tables,
257            unit_consumes,
258            unit_consumes_aliases,
259            errors,
260        );
261
262        if had_dup {
263            // Skip body/type-checking for this target; we have name conflicts.
264            continue;
265        }
266
267        // -- Phase 4: type-check bodies. --
268        // (We build a resolved view targeting either commons or context;
269        // mock bodies are type-checked with the mocked entity's privileges.)
270        let bodies_errs = check_test_bodies(
271            target_name,
272            target_kind,
273            indices,
274            parsed,
275            &target_stubs,
276            unit_tables,
277            exports_visibility,
278            unit_consumes,
279            unit_consumes_aliases,
280            unit_uses,
281            refs,
282            locals,
283            tys,
284            d1_sql,
285        );
286        // #2618: the suite sees its target's private declarations, but not
287        // those of a commons the target or the suite uses: a reference to one
288        // of those reads as `bynk.visibility.private_item`.
289        let bodies_errs = match unit_tables.get(target_name) {
290            Some(local) => {
291                let mut used: Vec<String> = unit_uses.get(target_name).cloned().unwrap_or_default();
292                for &i in indices {
293                    for u in parsed[i].uses() {
294                        let q = u.target.joined();
295                        if !used.contains(&q) {
296                            used.push(q);
297                        }
298                    }
299                }
300                let private = resolver::private_imports_in(
301                    local,
302                    used.iter()
303                        .filter_map(|t| unit_tables.get(t).map(|u| (t, u))),
304                );
305                resolver::rewrite_private_references(bodies_errs, &private)
306            }
307            None => bodies_errs,
308        };
309        // #3162: as `prepare_unit_check_ctx` does for a unit's own files, the
310        // names visible to the suite are its target's and those of the units
311        // the target `uses` or `consumes`. The echoes still fail the target.
312        // The suite's own `uses` count too, as in the private-reference gate
313        // above: it may use a commons its target does not.
314        let visible_broken = visible_broken_names(
315            std::slice::from_ref(target_name),
316            indices,
317            parsed,
318            unit_uses,
319            unit_consumes,
320            broken,
321        );
322        let bodies_failed = !bodies_errs.is_empty();
323        errors.extend(resolver::split_broken_decl_echoes(bodies_errs, &visible_broken).0);
324
325        if bodies_failed {
326            continue;
327        }
328
329        ready.insert(target_name.clone(), target_stubs);
330    }
331
332    ready
333}
334
335/// v0.118: resolve every `stub Cap.method(…)` clause targeting a unit into a
336/// per-capability [`ResolvedStub`] (testing track slice 6, ADR 0154). Both
337/// suite-scoped and case-scoped clauses fold in; a capability that is neither a
338/// declared seam of the target nor reachable through a consumed context is
339/// `bynk.stub.not_a_seam`, an unknown method is `bynk.stub.unknown_op`,
340/// and an empty `returns each []` is `bynk.stub.bad_sequence`.
341#[allow(clippy::too_many_arguments)]
342fn resolve_stubs(
343    target_name: &str,
344    target_kind: UnitKind,
345    indices: &[usize],
346    parsed: &[ParsedFile],
347    unit_tables: &HashMap<String, UnitTable>,
348    unit_consumes: &HashMap<String, Vec<String>>,
349    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
350    errors: &mut Vec<CompileError>,
351) -> HashMap<String, ResolvedStub> {
352    let target_table = unit_tables.get(target_name);
353    let target_consumed = unit_consumes.get(target_name).cloned().unwrap_or_default();
354
355    // Collect clauses tagged with the declaring file and the cases each
356    // applies to. Case-scoped first so they precede suite-scoped clauses in
357    // each capability's match order.
358    type Collected = (
359        StubClause,
360        StubScope,
361        PathBuf,
362        Vec<FixtureDecl>,
363        Vec<FnDecl>,
364        Vec<TypeDecl>,
365        Vec<ConstDecl>,
366    );
367    let mut collected: Vec<Collected> = Vec::new();
368    for &i in indices {
369        let Some(t) = parsed[i].test() else { continue };
370        for case in &t.cases {
371            for pc in &case.stubs {
372                collected.push((
373                    pc.clone(),
374                    StubScope::Case(case.name.clone()),
375                    parsed[i].identity_path(),
376                    t.fixtures.clone(),
377                    t.fns.clone(),
378                    t.types.clone(),
379                    t.consts.clone(),
380                ));
381            }
382        }
383    }
384    // #1860: a suite-scoped clause applies to its own suite's runs, which
385    // matters only when another suite targets the same unit: all of them are
386    // emitted into one module.
387    let suites = indices
388        .iter()
389        .filter(|&&i| parsed[i].test().is_some())
390        .count();
391    for &i in indices {
392        let Some(t) = parsed[i].test() else { continue };
393        let scope = match suite_ordinal(i, indices, parsed) {
394            Some(n) if suites > 1 => StubScope::Suite(n),
395            _ => StubScope::Every,
396        };
397        for pc in &t.stubs {
398            collected.push((
399                pc.clone(),
400                scope.clone(),
401                parsed[i].identity_path(),
402                t.fixtures.clone(),
403                t.fns.clone(),
404                t.types.clone(),
405                t.consts.clone(),
406            ));
407        }
408    }
409
410    // Resolve a capability name to its declaration: a capability the target
411    // declares (or has flattened in via `consumes U { Cap }`), else a capability
412    // of a consumed context.
413    let resolve_cap = |name: &str| -> Option<CapabilityDecl> {
414        target_table
415            .and_then(|t| t.capabilities.get(name).cloned())
416            .or_else(|| {
417                target_consumed.iter().find_map(|q| {
418                    unit_tables
419                        .get(q)
420                        .and_then(|t| t.capabilities.get(name).cloned())
421                })
422            })
423    };
424
425    let mut out: HashMap<String, ResolvedStub> = HashMap::new();
426    for (pc, scope, identity_path, fixtures, fns, types, consts) in collected {
427        let cap_name = pc.capability.name.clone();
428        // #3892: a consumed context named by its alias or qualified path is a
429        // seam for its services.
430        let consumed_ctx = resolve_cap(&cap_name).is_none().then(|| {
431            unit_consumes_aliases
432                .get(target_name)
433                .and_then(|a| a.get(&cap_name).cloned())
434                .or_else(|| target_consumed.iter().find(|q| **q == cap_name).cloned())
435        });
436        if let Some(Some(ctx)) = consumed_ctx {
437            resolve_service_stub(
438                &ctx,
439                &cap_name,
440                pc,
441                scope,
442                identity_path,
443                fixtures,
444                fns,
445                types,
446                consts,
447                unit_tables,
448                &mut out,
449                errors,
450            );
451            continue;
452        }
453        let Some(cap_decl) = resolve_cap(&cap_name) else {
454            // Commons have no seams at all; contexts may still name a
455            // non-existent capability. Either way it is not a seam.
456            let note = if target_kind == UnitKind::Commons {
457                "commons have no capability seams — `stub` overrides a capability the target context declares or consumes"
458            } else {
459                "a `stub` clause names a capability the target context declares or reaches through a consumed context"
460            };
461            errors.push(
462                CompileError::new(
463                    "bynk.stub.not_a_seam",
464                    pc.capability.span,
465                    format!("`{cap_name}` is not a capability seam of `{target_name}`",),
466                )
467                .with_note(note),
468            );
469            continue;
470        };
471        let Some(op_decl) = cap_decl.ops.iter().find(|o| o.name.name == pc.method.name) else {
472            errors.push(CompileError::new(
473                "bynk.stub.unknown_op",
474                pc.method.span,
475                format!(
476                    "`{}` is not an operation of capability `{cap_name}`",
477                    pc.method.name
478                ),
479            ));
480            continue;
481        };
482        // #926 (Decision F): a generic capability operation cannot be stubbed
483        // — `__Stub_Cap`'s per-op method body has no way to construct a
484        // value of the op's unconstrained `T`. Deferred rather than
485        // supported: the stub class carries no `implements` clause (its
486        // members are duck-typed through an untyped `deps` seam), so
487        // stubbing another, non-generic op of the same capability keeps
488        // type-checking.
489        if !op_decl.type_params.is_empty() {
490            errors.push(
491                CompileError::new(
492                    "bynk.stub.generic_op",
493                    pc.method.span,
494                    format!(
495                        "`{cap_name}.{}` declares its own type parameter — a generic capability operation cannot be stubbed at v1",
496                        pc.method.name
497                    ),
498                )
499                .with_note(
500                    "test through the capability's real (external) provider instead, or restructure the test to avoid stubbing this operation",
501                ),
502            );
503            continue;
504        }
505        if let StubRhs::ReturnsEach(outcomes, span) = &pc.rhs
506            && outcomes.is_empty()
507        {
508            errors.push(CompileError::new(
509                "bynk.stub.bad_sequence",
510                *span,
511                format!(
512                    "`stub {cap_name}.{} returns each []` has no outcomes — a sequence needs at least one",
513                    pc.method.name
514                ),
515            ));
516            continue;
517        }
518        let entry = out.entry(cap_name.clone()).or_insert_with(|| ResolvedStub {
519            cap: cap_name.clone(),
520            cap_decl: cap_decl.clone(),
521            service_context: None,
522            clauses: Vec::new(),
523            clause_scopes: Vec::new(),
524            clause_fixtures: Vec::new(),
525            clause_fns: Vec::new(),
526            clause_types: Vec::new(),
527            clause_consts: Vec::new(),
528            identity_path: identity_path.clone(),
529        });
530        entry.clauses.push(pc);
531        entry.clause_scopes.push(scope);
532        entry.clause_fixtures.push(fixtures);
533        entry.clause_fns.push(fns);
534        entry.clause_types.push(types);
535        entry.clause_consts.push(consts);
536    }
537    out
538}
539
540/// #3892: fold a `stub <context>.<service>(…)` clause into the seam map. The
541/// consumed context is the seam and each stubbed service one operation of it,
542/// typed from the service's `on call` handler, so the clause is checked and
543/// lowered as a capability operation is.
544#[allow(clippy::too_many_arguments)]
545fn resolve_service_stub(
546    ctx: &str,
547    seam: &str,
548    pc: StubClause,
549    scope: StubScope,
550    identity_path: PathBuf,
551    fixtures: Vec<FixtureDecl>,
552    fns: Vec<FnDecl>,
553    types: Vec<TypeDecl>,
554    consts: Vec<ConstDecl>,
555    unit_tables: &HashMap<String, UnitTable>,
556    out: &mut HashMap<String, ResolvedStub>,
557    errors: &mut Vec<CompileError>,
558) {
559    let handler = unit_tables
560        .get(ctx)
561        .and_then(|t| t.services.get(&pc.method.name))
562        .and_then(|s| s.handlers.iter().find(|h| h.kind == HandlerKind::Call));
563    let Some(handler) = handler else {
564        errors.push(
565            CompileError::new(
566                "bynk.stub.unknown_op",
567                pc.method.span,
568                format!("`{}` is not a service of `{ctx}`", pc.method.name),
569            )
570            .with_note("a `stub` on a consumed context names one of its services"),
571        );
572        return;
573    };
574    if let StubRhs::ReturnsEach(outcomes, span) = &pc.rhs
575        && outcomes.is_empty()
576    {
577        errors.push(CompileError::new(
578            "bynk.stub.bad_sequence",
579            *span,
580            format!(
581                "`stub {seam}.{} returns each []` has no outcomes — a sequence needs at least one",
582                pc.method.name
583            ),
584        ));
585        return;
586    }
587    let op = CapabilityOp {
588        name: pc.method.clone(),
589        type_params: Vec::new(),
590        params: handler.params.clone(),
591        return_type: handler.return_type.clone(),
592        annotations: Vec::new(),
593        documentation: None,
594        span: handler.span,
595        trivia: Default::default(),
596    };
597    let entry = out.entry(seam.to_string()).or_insert_with(|| ResolvedStub {
598        cap: seam.to_string(),
599        cap_decl: CapabilityDecl {
600            name: pc.capability.clone(),
601            ops: Vec::new(),
602            derived: None,
603            documentation: None,
604            span: pc.capability.span,
605            trailing_comments: Vec::new(),
606            trivia: Default::default(),
607        },
608        service_context: Some(ctx.to_string()),
609        clauses: Vec::new(),
610        clause_scopes: Vec::new(),
611        clause_fixtures: Vec::new(),
612        clause_fns: Vec::new(),
613        clause_types: Vec::new(),
614        clause_consts: Vec::new(),
615        identity_path: identity_path.clone(),
616    });
617    if !entry
618        .cap_decl
619        .ops
620        .iter()
621        .any(|o| o.name.name == op.name.name)
622    {
623        entry.cap_decl.ops.push(op);
624    }
625    entry.clauses.push(pc);
626    entry.clause_scopes.push(scope);
627    entry.clause_fixtures.push(fixtures);
628    entry.clause_fns.push(fns);
629    entry.clause_types.push(types);
630    entry.clause_consts.push(consts);
631}
632
633/// v0.118: infer a `system`-tier suite's wired participants — the target's
634/// transitive `consumes` closure (testing track slice 6). A BFS from the target
635/// following `consumes` edges; the returned list starts with the target and
636/// includes every context reachable through it (deterministic breadth order).
637/// #1856: contexts only. A unit consumed for its capabilities alone
638/// (`consumes bynk { Clock }`, an adapter) is provided in-process by the
639/// composition root: no Worker, no Service Binding, no wire to cross. The
640/// walk still passes through one, but it is no participant.
641pub fn infer_participants(
642    target: &str,
643    unit_consumes: &HashMap<String, Vec<String>>,
644    kinds: &BTreeMap<String, UnitKind>,
645) -> Vec<String> {
646    let mut seen: HashSet<String> = HashSet::new();
647    let mut order: Vec<String> = Vec::new();
648    let mut queue: Vec<String> = vec![target.to_string()];
649    seen.insert(target.to_string());
650    let mut head = 0;
651    while head < queue.len() {
652        let node = queue[head].clone();
653        head += 1;
654        order.push(node.clone());
655        if let Some(deps) = unit_consumes.get(&node) {
656            for d in deps {
657                if seen.insert(d.clone()) {
658                    queue.push(d.clone());
659                }
660            }
661        }
662    }
663    order.retain(|u| kinds.get(u) == Some(&UnitKind::Context));
664    order
665}
666
667/// #1959: the contexts a `system`-tier suite's harness stands up as Workers:
668/// [`infer_participants`]' set, plus every context subscribing to an event
669/// one of them declares, plus *its* `consumes` closure, transitively. A
670/// subscriber consumes its publisher, and `consumes` cycles are refused, so
671/// no subscriber of the target is ever in the target's own closure; without
672/// it here, the fan-out would deliver to nobody. Only the harness widens: a
673/// case still reaches just [`infer_participants`]' set. Target first, then
674/// breadth order.
675pub fn infer_harness_participants(
676    target: &str,
677    unit_consumes: &HashMap<String, Vec<String>>,
678    kinds: &BTreeMap<String, UnitKind>,
679    event_subscribers: &BTreeMap<(String, String), Vec<(String, String)>>,
680) -> Vec<String> {
681    let mut seen: HashSet<String> = HashSet::new();
682    let mut order: Vec<String> = Vec::new();
683    let mut queue: Vec<String> = vec![target.to_string()];
684    seen.insert(target.to_string());
685    let mut head = 0;
686    while head < queue.len() {
687        let node = queue[head].clone();
688        head += 1;
689        order.push(node.clone());
690        let consumed = unit_consumes.get(&node).into_iter().flatten();
691        let subscribers = event_subscribers
692            .iter()
693            .filter(|((owner, _), _)| *owner == node)
694            .flat_map(|(_, subs)| subs.iter().map(|(ctx, _)| ctx));
695        for next in consumed.chain(subscribers) {
696            if seen.insert(next.clone()) {
697                queue.push(next.clone());
698            }
699        }
700    }
701    order.retain(|u| kinds.get(u) == Some(&UnitKind::Context));
702    order
703}
704
705/// P5.4 (`design/tracks/semantics-in-the-checker.md` §6): the checking half
706/// of `test integration "name"` suite processing — participant inference,
707/// the `system`-needs-a-serialisation-edge gate, duplicate-case-name
708/// detection, the harness-root cross-context view, and per-case body
709/// type-checking (including the `Wire`/`by Nobody` tier gates). Formerly the
710/// pre-emission logic of `bynk-emit`'s own `process_integration_tests`;
711/// emission stays in `bynk-driver::project::tests_emit::process_integration_tests`,
712/// which calls this function for its checking half and then emits only for
713/// the groups this returns. Unlike [`phase_test_bodies`]'s `ResolvedStub`
714/// map, the only thing worth handing back here is the harness's
715/// [`resolver::CrossContextInfo`] — it's built from clone-heavy maps
716/// (`harness_consumes`/`harness_uses`), so recomputing it a second time on
717/// the emit side would be wasted work. `participants`/`uses_targets`/
718/// `case_inputs` are cheap and pure (a BFS, a linear scan), so the emit-side
719/// loop recomputes those itself from `parsed`/`unit_consumes`, using the
720/// now-relocated [`infer_participants`]. `bynk_check::analysis::analyse_project`
721/// calls this too and discards the returned map — it never emits. Closes
722/// category 7 of `bynk-check/src/analysis.rs`'s own residual-gap accounting,
723/// alongside [`phase_test_bodies`].
724#[allow(clippy::too_many_arguments)]
725pub fn phase_integration_bodies(
726    integration_groups: &BTreeMap<String, Vec<usize>>,
727    parsed: &[ParsedFile],
728    kinds: &BTreeMap<String, UnitKind>,
729    unit_tables: &HashMap<String, UnitTable>,
730    unit_consumes: &HashMap<String, Vec<String>>,
731    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
732    unit_uses: &HashMap<String, Vec<String>>,
733    // #3162: the declarations recovery skipped, per unit.
734    broken: &crate::project_model::BrokenDeclNames,
735    errors: &mut Vec<CompileError>,
736    refs: &mut RefSink,
737    tys: &Arc<Types>,
738    // #3147: the migrations' schemas, which a `D1.peek` read is prepared against.
739    d1_sql: Option<&crate::d1_sql::D1Sql>,
740) -> HashMap<String, resolver::CrossContextInfo> {
741    let mut ready: HashMap<String, resolver::CrossContextInfo> = HashMap::new();
742
743    let mut sorted: Vec<&String> = integration_groups.keys().collect();
744    sorted.sort();
745
746    for group_name in sorted {
747        let indices = integration_groups.get(group_name).unwrap();
748        let first = indices[0];
749        let Some(decl) = parsed[first].integration() else {
750            continue;
751        };
752        // v0.118: there is no `suite` string any more — the wired suite is named
753        // for its target context. The participant set is INFERRED from the
754        // target's transitive `consumes` closure (no `wires` list).
755        let suite_target = decl.target.joined();
756        let participants = infer_participants(&suite_target, unit_consumes, kinds);
757
758        let mut bad = false;
759
760        // v0.118 / testing-the-boundary Slice B: a `system` suite needs a real
761        // **serialisation edge** — not merely ≥ 2 participants. The original rule
762        // (`participants.len() < 2`) was a proxy for "nothing to serialise
763        // across", exact only when the sole edge was cross-context. A single
764        // context that exposes an `http` service has a real edge (the public
765        // boundary: deserialise → handler → serialise), so it qualifies.
766        //
767        // `http`, `queue` and `email` qualify; see [`has_serialisation_edge`].
768        let has_serialisation_edge = unit_tables
769            .get(&suite_target)
770            .is_some_and(has_serialisation_edge);
771        if participants.len() < 2 && !has_serialisation_edge {
772            errors.push(
773                CompileError::new(
774                    "bynk.tier.system_needs_wire",
775                    decl.target.span,
776                    format!(
777                        "`system`-tier suite for `{suite_target}` has no serialisation edge — the target consumes no other context and exposes no `http`, `queue` or `email` service",
778                    ),
779                )
780                .with_note(
781                    "a `system` case crosses a real serialise → JSON → deserialise boundary; this target has none to cross, so `unit` already covers it",
782                ),
783            );
784            bad = true;
785        }
786
787        // -- Duplicate case names within the suite. --
788        let mut seen_cases: HashMap<String, Span> = HashMap::new();
789        for &i in indices {
790            let Some(d) = parsed[i].integration() else {
791                continue;
792            };
793            for case in &d.cases {
794                if let Some(prev) = seen_cases.get(&case.name) {
795                    errors.push(
796                        CompileError::new(
797                            "bynk.suite.duplicate_case_name",
798                            case.name_span,
799                            format!(
800                                "test case `\"{}\"` is declared more than once in tests targeting `{suite_target}`",
801                                case.name
802                            ),
803                        )
804                        .with_label(*prev, "previously declared here"),
805                    );
806                    bad = true;
807                } else {
808                    seen_cases.insert(case.name.clone(), case.name_span);
809                }
810            }
811        }
812
813        // -- #2134: each suite's and case's `env` clauses. --
814        for &i in indices {
815            if let Some(d) = parsed[i].integration() {
816                crate::test_env::check_env_clauses(d, errors);
817            }
818        }
819
820        // -- #1738: a `system` case can't share a suite with lower-tier ones. --
821        // Reported without marking the suite `bad`: the per-case tier gates
822        // below (`Wire`, `by Nobody`) still check its bodies, and any error
823        // already stops emission.
824        // A suite with any `system` case is emitted, whole, as the wired module
825        // that drives deployed Workers, where a service is addressed by its
826        // context path (`shop.orders.place(…)`), not `place.call(…)`. A lower-
827        // tier case there has no in-process target to call (it lowered to
828        // `/* unknown */`), so the tiers are kept to separate suites.
829        for &i in indices {
830            let Some(d) = parsed[i].integration() else {
831                continue;
832            };
833            let suite_is_system = d.tier == Some(bynk_syntax::ast::TestTier::System);
834            let has_lower = d
835                .cases
836                .iter()
837                .any(|c| case_effective_tier(c, d) != bynk_syntax::ast::TestTier::System);
838            if !has_lower {
839                continue;
840            }
841            for case in &d.cases {
842                let tier = case_effective_tier(case, d);
843                // In a `system` suite, flag each case that steps down; in any
844                // other suite, flag each case that steps up to `system`.
845                let flagged = if suite_is_system {
846                    tier != bynk_syntax::ast::TestTier::System
847                } else {
848                    case.tier == Some(bynk_syntax::ast::TestTier::System)
849                };
850                if !flagged {
851                    continue;
852                }
853                let (message, advice) = if suite_is_system {
854                    (
855                        format!(
856                            "case `\"{}\"` is `{}`-tier, but its suite is `as system`",
857                            case.name,
858                            tier.as_str()
859                        ),
860                        format!(
861                            "move this case into a separate `suite {suite_target}` without `as system`"
862                        ),
863                    )
864                } else {
865                    (
866                        format!(
867                            "case `\"{}\"` is `as system`, but other cases in its suite run below `system`",
868                            case.name
869                        ),
870                        format!(
871                            "move this case into its own `suite {suite_target} as system {{ … }}`, addressing services by context path (`{suite_target}.<service>(…)`)"
872                        ),
873                    )
874                };
875                errors.push(
876                    CompileError::new("bynk.tier.mixed_system_suite", case.name_span, message)
877                        .with_note(format!(
878                            "a `system` case runs against deployed Workers, so its suite holds `system` cases only; {advice}"
879                        )),
880                );
881            }
882        }
883
884        // -- #2026: a `stub` has nothing to override at `system`. --
885        refuse_stubs_at_system(indices, parsed, &suite_target, errors);
886
887        if bad {
888            continue;
889        }
890
891        // -- Build the harness-root cross-context view (consumes all). --
892        let harness_name = group_name.clone();
893        let mut uses_targets: Vec<String> = Vec::new();
894        for &i in indices {
895            if let Some(d) = parsed[i].integration() {
896                for u in &d.uses {
897                    let q = u.target.joined();
898                    if !uses_targets.contains(&q) {
899                        uses_targets.push(q);
900                    }
901                }
902            }
903        }
904        // The same key is the target's own, but nothing is lost: `participants` is
905        // the target's `consumes` closure (contexts only, and the view reads only
906        // contexts), so it is a superset of the entry it replaces (#2832).
907        let mut harness_consumes = unit_consumes.clone();
908        harness_consumes.insert(harness_name.clone(), participants.clone());
909        // #2832: the harness is named for its target, so its entry here is the
910        // target's own. The target's `uses` stay (they are what its consumed
911        // view, `contract_types_for`, resolves a commons type through) and the
912        // suite's own `uses` join them, where an overwrite lost the commons
913        // types of the context under test and typed a call to a service
914        // returning one as `()`.
915        let mut harness_uses = unit_uses.clone();
916        let entry = harness_uses.entry(harness_name.clone()).or_default();
917        for u in &uses_targets {
918            if !entry.contains(u) {
919                entry.push(u.clone());
920            }
921        }
922        let cross_context = build_cross_context_info(
923            &harness_name,
924            &harness_consumes,
925            unit_consumes_aliases,
926            &harness_uses,
927            unit_tables,
928        );
929
930        // -- Type-check each case body. --
931        let mut body_errs: Vec<CompileError> = Vec::new();
932        // #1814: the harness view every case is checked in, closed over the
933        // types its declarations reach.
934        let view = integration_view(&uses_targets, &participants, unit_tables, unit_uses);
935        // Review of #1814: the harness pairs the suite's own `uses` with the
936        // participants, which no unit's closure sees together, so a reached
937        // name one of them already binds is reported here, at the suite's
938        // `uses` the reaching declaration came through (or its target, for a
939        // participant's).
940        for c in &view.conflicts {
941            let span = indices
942                .iter()
943                .filter_map(|&i| parsed[i].integration())
944                .flat_map(|d| &d.uses)
945                .find(|u| u.target.joined() == c.via)
946                .map(|u| u.target.span)
947                .unwrap_or(decl.target.span);
948            let names = c
949                .bound
950                .as_ref()
951                .map(|b| format!("`{b}`'s type"))
952                .unwrap_or_else(|| "another declaration".to_string());
953            body_errs.push(view_conflict_error(c, span, &names));
954        }
955        // v0.25: the harness root is a synthetic namespace — declare its
956        // resolution order (uses first, then participants) for assembly.
957        let mut harness_resolution = uses_targets.clone();
958        harness_resolution.extend(participants.iter().cloned());
959        refs.declare_namespace(&harness_name, harness_resolution);
960        for &i in indices {
961            let Some(d) = parsed[i].integration() else {
962                continue;
963            };
964            // #2834: as for a unit suite, a system suite's helpers are
965            // definitions of their own file's namespace.
966            let namespace = if SuiteItems::of(d).is_empty() {
967                harness_name.clone()
968            } else {
969                let ns = suite_helper_namespace(&harness_name, &parsed[i].identity_path());
970                let mut resolution = uses_targets.clone();
971                resolution.extend(participants.iter().cloned());
972                refs.declare_namespace(&ns, resolution);
973                ns
974            };
975            refs.enter_file(
976                &parsed[i].identity_path(),
977                &namespace,
978                parsed[i].is_synthetic(),
979            );
980            // #1814: a reached type resolves in the view, but the suite may
981            // not name it.
982            body_errs.extend(resolver::check_hidden_type_names_in_suite(
983                d,
984                None,
985                &view.hidden,
986            ));
987            // #2834: the suite's helpers, checked once in the harness view.
988            let mut helper_view = integration_resolved(&view, &cross_context, SuiteItems::NONE);
989            check_suite_fixtures_in(
990                d,
991                &helper_view,
992                participants.first().and_then(|p| unit_tables.get(p)),
993                &mut body_errs,
994            );
995            add_suite_fns(
996                &mut helper_view,
997                SuiteItems {
998                    fns: &[],
999                    fixtures: &d.fixtures,
1000                    types: &[],
1001                    consts: &[],
1002                },
1003            );
1004            check_suite_decls(
1005                &d.types,
1006                &d.consts,
1007                &mut helper_view,
1008                participants.first().and_then(|p| unit_tables.get(p)),
1009                &mut body_errs,
1010                refs,
1011                &mut LocalsSink::new(),
1012                tys,
1013            );
1014            check_suite_fns(
1015                &d.fns,
1016                &mut helper_view,
1017                participants.first().and_then(|p| unit_tables.get(p)),
1018                &mut body_errs,
1019                refs,
1020                &mut LocalsSink::new(),
1021                tys,
1022            );
1023            // #2906: a suite mixing `system` with lower tiers is already
1024            // `bynk.tier.mixed_system_suite`. Its lower-tier cases have no
1025            // harness to run in, so checking them against the harness view
1026            // would only add false errors (a consumed capability read as
1027            // "not a seam"); the tier error stands for them.
1028            let suite_has_system = d.tier == Some(bynk_syntax::ast::TestTier::System)
1029                || d.cases
1030                    .iter()
1031                    .any(|c| case_effective_tier(c, d) == bynk_syntax::ast::TestTier::System);
1032            for case in &d.cases {
1033                let unchecked = suite_has_system
1034                    && case_effective_tier(case, d) != bynk_syntax::ast::TestTier::System;
1035                // The tier gates below still run on such a case; only its
1036                // body type-check, which has no harness to run in, is skipped.
1037                let case_callees = if unchecked {
1038                    Default::default()
1039                } else {
1040                    let body = IntegrationBody {
1041                        participants: &participants,
1042                        view: &view,
1043                        suite: d,
1044                        case,
1045                        cross_context: &cross_context,
1046                        unit_tables,
1047                    };
1048                    check_integration_body(
1049                        &body,
1050                        d1_sql,
1051                        parsed[first].source(),
1052                        &mut body_errs,
1053                        refs,
1054                        tys,
1055                    )
1056                };
1057                check_faults_tier(case, case_effective_tier(case, d), &mut body_errs);
1058                check_snapshot_placement(case, true, &mut body_errs);
1059                check_event_address_tier(
1060                    case,
1061                    case_effective_tier(case, d),
1062                    &case_callees,
1063                    &mut body_errs,
1064                );
1065                check_ws_address_tier(
1066                    case,
1067                    case_effective_tier(case, d),
1068                    &case_callees,
1069                    &mut body_errs,
1070                );
1071                check_call_address_tier(
1072                    case,
1073                    case_effective_tier(case, d),
1074                    &case_callees,
1075                    &mut body_errs,
1076                );
1077                check_extra_headers_tier(
1078                    case,
1079                    case_effective_tier(case, d),
1080                    &case_callees,
1081                    &mut body_errs,
1082                );
1083                check_extra_headers_let(case, &case_callees, &mut body_errs);
1084                if case_effective_tier(case, d) == bynk_syntax::ast::TestTier::System {
1085                    check_system_claims_literal(case, &mut body_errs);
1086                }
1087                // Slice C: `Wire(…)` is a `system`-only raw argument (it drives the
1088                // real wire); in a non-`system` case it has no wire to be raw
1089                // about, so lowering it would silently pass raw text to a direct
1090                // in-process handler call. Reject it at the tier where it is known.
1091                check_wire_tier(case, case_effective_tier(case, d), &mut body_errs);
1092                // #706: `by Nobody` presents no credential to the real auth seam
1093                // (the 401 path), which exists only at `system`; at a lower tier
1094                // the handler just runs with no identity, silently not a 401.
1095                if !matches!(
1096                    case_effective_tier(case, d),
1097                    bynk_syntax::ast::TestTier::System
1098                ) && block_uses_nobody(&case.body)
1099                {
1100                    body_errs.push(CompileError::new(
1101                        "bynk.test.credential_needs_system",
1102                        case.name_span,
1103                        format!(
1104                            "case `\"{}\"` drives `by Nobody` but is not a `system`-tier case",
1105                            case.name
1106                        ),
1107                    ).with_note(
1108                        "`by Nobody` presents no credential to the real auth seam (the 401 path), which exists only at `system`; promote the case with `as system`, or supply `by <Actor>(<identity>)`",
1109                    ));
1110                }
1111                check_bad_signature_tier(case, case_effective_tier(case, d), &mut body_errs);
1112            }
1113        }
1114        // #3162: a skipped declaration of any participant (or of what the
1115        // participants and the suite use) is a known name, not an unknown one.
1116        let visible_broken = visible_broken_names(
1117            &participants,
1118            indices,
1119            parsed,
1120            unit_uses,
1121            unit_consumes,
1122            broken,
1123        );
1124        let bodies_failed = !body_errs.is_empty();
1125        errors.extend(resolver::split_broken_decl_echoes(body_errs, &visible_broken).0);
1126        if bodies_failed {
1127            continue;
1128        }
1129
1130        ready.insert(group_name.clone(), cross_context);
1131    }
1132
1133    ready
1134}
1135
1136/// #2026: a `stub` has nothing to override at `system`.
1137///
1138/// Each participant runs as the Worker it deploys as, and its composition root
1139/// builds every capability provider from its own `env`, so the harness has no
1140/// seam to put a double in. Refused rather than accepted and dropped. Reported
1141/// without marking the suite `bad`, like #1738.
1142fn refuse_stubs_at_system(
1143    indices: &[usize],
1144    parsed: &[ParsedFile],
1145    suite_target: &str,
1146    errors: &mut Vec<CompileError>,
1147) {
1148    for &i in indices {
1149        let Some(d) = parsed[i].integration() else {
1150            continue;
1151        };
1152        let system = bynk_syntax::ast::TestTier::System;
1153        let suite_stubs = d
1154            .stubs
1155            .iter()
1156            .filter(|_| suite_effective_tier_is_system(d))
1157            .map(|s| (s, "suite"));
1158        let case_stubs = d
1159            .cases
1160            .iter()
1161            .filter(|c| case_effective_tier(c, d) == system)
1162            .flat_map(|c| c.stubs.iter().map(|s| (s, "case")));
1163        for (stub, scope) in suite_stubs.chain(case_stubs) {
1164            errors.push(
1165                    CompileError::new(
1166                        "bynk.stub.at_system",
1167                        stub.span,
1168                        format!(
1169                            "`stub {}.{}` is in a `system`-tier {scope}, where a `stub` has no effect",
1170                            stub.capability.name, stub.method.name
1171                        ),
1172                    )
1173                    .with_note(
1174                        "a `system` case runs each context as the Worker it deploys as, which builds its own capability providers; no seam can be overridden there",
1175                    )
1176                    .with_note(format!(
1177                        "move the case into a `suite {suite_target}` below `system` (`unit`, or `as integration`), where a `stub` overrides the seam"
1178                    )),
1179                );
1180        }
1181    }
1182}
1183
1184/// One integration or `system` case, with what its body is checked against.
1185struct IntegrationBody<'a> {
1186    participants: &'a [String],
1187    view: &'a SuiteView,
1188    suite: &'a SuiteDecl,
1189    case: &'a Case,
1190    cross_context: &'a resolver::CrossContextInfo,
1191    unit_tables: &'a HashMap<String, UnitTable>,
1192}
1193
1194/// Type-check an integration or `system` case body, then prepare what it
1195/// `D1.peek`s (#3147) against its participants' migrations. Returns the body's
1196/// callees.
1197fn check_integration_body(
1198    body: &IntegrationBody<'_>,
1199    d1_sql: Option<&crate::d1_sql::D1Sql>,
1200    source: &str,
1201    errors: &mut Vec<CompileError>,
1202    refs: &mut RefSink,
1203    tys: &Arc<Types>,
1204) -> HashMap<ExprId, checker::Callee> {
1205    let callees = typecheck_integration_case_body(
1206        body.participants,
1207        body.view,
1208        SuiteItems::of(body.suite),
1209        body.case,
1210        body.cross_context,
1211        body.unit_tables,
1212        errors,
1213        refs,
1214        tys,
1215    )
1216    .1;
1217    if let Some(d1_sql) = d1_sql {
1218        errors.extend(d1_sql.check_peek_sites(body.unit_tables, &callees, Some(source)));
1219    }
1220    callees
1221}
1222
1223/// #3162: the declarations recovery skipped in the units a suite can see: the
1224/// `roots` (its target, or an integration suite's participants), the units
1225/// they `use` or `consume`, and the units the suite's own files `use` (a suite
1226/// may use a commons its target does not, as the private-reference gate also
1227/// allows). A reference to one is a known name, so its unknown-name echo is not
1228/// reported; the syntax error already says why.
1229fn visible_broken_names(
1230    roots: &[String],
1231    suite_files: &[usize],
1232    parsed: &[ParsedFile],
1233    unit_uses: &HashMap<String, Vec<String>>,
1234    unit_consumes: &HashMap<String, Vec<String>>,
1235    broken: &crate::project_model::BrokenDeclNames,
1236) -> Vec<String> {
1237    let suite_uses: Vec<String> = suite_files
1238        .iter()
1239        .flat_map(|&i| parsed[i].uses())
1240        .map(|u| u.target.joined())
1241        .collect();
1242    roots
1243        .iter()
1244        .chain(
1245            roots
1246                .iter()
1247                .flat_map(|r| unit_uses.get(r).into_iter().chain(unit_consumes.get(r)))
1248                .flatten(),
1249        )
1250        .chain(suite_uses.iter())
1251        .filter_map(|u| broken.get(u))
1252        .flatten()
1253        .cloned()
1254        .collect()
1255}
1256
1257/// Whether `target` exposes a service a `system` case drives over a real wire:
1258/// `http` (`emit_system_http_support` drives `worker.fetch`), `queue`
1259/// (`emit_system_job_support`, #2136, drives `worker.queue` with a batch whose
1260/// message body has been through the platform's JSON serialisation) or `email`
1261/// (#3328: raw MIME through the Worker's `email()` entry, which parses it).
1262/// `cron` never qualifies on its own: a scheduled event carries only a cron
1263/// string and a time, so there is nothing to serialise, but a cron address is
1264/// legal in a suite that already qualifies, and is driven through
1265/// `worker.scheduled` there.
1266fn has_serialisation_edge(target: &UnitTable) -> bool {
1267    target.services.values().any(|s| {
1268        matches!(
1269            s.protocol,
1270            bynk_syntax::ast::ServiceProtocol::Http
1271                | bynk_syntax::ast::ServiceProtocol::Queue { .. }
1272                | bynk_syntax::ast::ServiceProtocol::Email { .. }
1273        )
1274    })
1275}
1276
1277/// Type-check one integration test case body. The body lives in a synthetic
1278/// harness root that consumes every participant; entry calls
1279/// (`ctx.service(args)`) are therefore ordinary cross-context calls. The body
1280/// has type `Effect[Result[(), ExpectationError]]` (modelled as
1281/// `Effect[Result[(), ValidationError]]`, as in unit tests).
1282///
1283/// Returns the body's `expr_types` and `Callee` classification. As
1284/// [`typecheck_case_body`] does for the unit tier, the **check** path feeds
1285/// real sinks and the **emit** path reuses it with throwaway ones. #1855: the
1286/// emit path once lowered with no types at all, so a literal at a refined
1287/// record field was never branded and the test module failed `tsc`.
1288#[allow(clippy::too_many_arguments)]
1289pub fn typecheck_integration_case_body(
1290    participants: &[String],
1291    view: &SuiteView,
1292    // #2834: the declaring suite's helper `fn`s, callable from the body.
1293    suite_fns: SuiteItems<'_>,
1294    case: &Case,
1295    cross_context: &resolver::CrossContextInfo,
1296    unit_tables: &HashMap<String, UnitTable>,
1297    errors: &mut Vec<CompileError>,
1298    refs: &mut RefSink,
1299    tys: &Arc<Types>,
1300) -> (
1301    HashMap<ExprId, checker::TypedExpr>,
1302    HashMap<ExprId, checker::Callee>,
1303) {
1304    let resolved = integration_resolved(view, cross_context, suite_fns);
1305
1306    let unit_span = case.span;
1307    let synthetic_return = TypeRef::Effect(
1308        Box::new(TypeRef::Result(
1309            Box::new(TypeRef::Unit(unit_span)),
1310            Box::new(TypeRef::ValidationError(unit_span)),
1311            unit_span,
1312        )),
1313        unit_span,
1314    );
1315    let return_ty = checker::resolve_type_ref(&synthetic_return, &resolved.types, tys).unwrap();
1316    let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
1317    let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
1318    // Test bodies record no hints (out of v0.27 scope) — a throwaway sink.
1319    let mut no_hints = HintSink::new();
1320    let mut no_locals = LocalsSink::new();
1321    // Test bodies record no capability requirements either — muted sink.
1322    let mut no_requirements = RequirementSink::new();
1323    let _ = checker::check_body(
1324        &resolved,
1325        &case.body,
1326        return_ty,
1327        case.span,
1328        HashMap::new(),
1329        checker::CapabilityCtx {
1330            // #3147: a case may `D1.peek` its participants' databases.
1331            peek_env: Some(Arc::new(peek_env(
1332                participants,
1333                unit_tables,
1334                &resolved,
1335                tys,
1336            ))),
1337            ..Default::default()
1338        },
1339        // Slice B: a `system` case addresses the target's own service (`api.POST`)
1340        // and names a principal (`by User(...)`), so the checker needs the
1341        // target's services and actors — the same resolution the unit tier does.
1342        target_test_services(
1343            participants.first().map(String::as_str),
1344            unit_tables,
1345            &cross_context.consumed_contexts,
1346        ),
1347        target_test_actors(participants.first().and_then(|t| unit_tables.get(t))),
1348        None,
1349        checker::CheckSinks {
1350            tys,
1351            expr_types: &mut expr_types,
1352            errors,
1353            refs,
1354            hints: &mut no_hints,
1355            locals: &mut no_locals,
1356            requirements: &mut no_requirements,
1357            callees: &mut callees,
1358        },
1359    );
1360    (expr_types, callees)
1361}
1362
1363/// #3147: each participant's capabilities, for `D1.peek` to name.
1364fn peek_env(
1365    participants: &[String],
1366    unit_tables: &HashMap<String, UnitTable>,
1367    resolved: &ResolvedCommons,
1368    tys: &Arc<Types>,
1369) -> checker::peek::PeekEnv {
1370    let mut env = checker::peek::PeekEnv::default();
1371    for p in participants {
1372        let Some(table) = unit_tables.get(p) else {
1373            continue;
1374        };
1375        let caps = table
1376            .capabilities
1377            .iter()
1378            .map(|(name, decl)| {
1379                let ops = decl
1380                    .ops
1381                    .iter()
1382                    .map(|op| build_capability_op_info(op, &resolved.types, tys))
1383                    .collect();
1384                let info = checker::CapabilityInfo {
1385                    name: name.clone(),
1386                    ops,
1387                    derived_from: crate::context_checks::derived_from(
1388                        decl,
1389                        &resolved.cross_context.flattened_caps,
1390                    ),
1391                };
1392                let binding = table.derived.get(name).map(|d| d.binding.clone());
1393                (name.clone(), checker::peek::PeekCap { info, binding })
1394            })
1395            .collect();
1396        env.participants.insert(p.clone(), caps);
1397    }
1398    env
1399}
1400
1401/// The harness-root [`ResolvedCommons`] a `system` case (or a suite helper) is
1402/// checked in: names from the harness view (#1814: closed over reached types),
1403/// plus the declaring suite's helper `fn`s (#2834).
1404pub fn integration_resolved(
1405    view: &SuiteView,
1406    cross_context: &resolver::CrossContextInfo,
1407    suite_fns: SuiteItems<'_>,
1408) -> ResolvedCommons {
1409    let SuiteView {
1410        types,
1411        fns,
1412        methods,
1413        ..
1414    } = view.clone();
1415
1416    let synthetic_commons = Commons {
1417        name: QualifiedName {
1418            parts: vec![Ident {
1419                name: "integration".to_string(),
1420                span: Span::default(),
1421            }],
1422            span: Span::default(),
1423        },
1424        items: Vec::new(),
1425        uses: Vec::new(),
1426        documentation: None,
1427        form: CommonsForm::Brace,
1428        span: Span::default(),
1429        trivia: Trivia::default(),
1430        trailing_comments: Vec::new(),
1431    };
1432    // `synthetic_commons` declares nothing of its own (`items: Vec::new()`
1433    // above) — every entry in `types`/`fns`/`methods` was merged in from a
1434    // `uses`/participant unit, so an empty local table (no local types, no
1435    // local events) is the correct answer here, not a stand-in for one.
1436    let no_local_types = HashMap::new();
1437    let no_local_events = HashMap::new();
1438    let mut resolved = ResolvedCommons::new(
1439        Arc::new(synthetic_commons),
1440        types,
1441        &no_local_types,
1442        fns,
1443        methods,
1444        HashMap::new(),
1445        &no_local_events,
1446        cross_context.clone(),
1447        HashMap::new(),
1448        // Test-scaffold body, not a real context emission — never rebranded.
1449        false,
1450        HashSet::new(),
1451    )
1452    // #1883, slice 3: the assets the case may name and fetch.
1453    .with_assets(view.assets.clone())
1454    .with_embeds(view.embeds.clone())
1455    .with_consts(view.consts.clone());
1456    add_suite_fns(&mut resolved, suite_fns);
1457    resolved
1458}
1459
1460/// #2834/#2841: what a suite declares for its bodies to use besides cases: its
1461/// helper `fn`s and its `fixture` files.
1462#[derive(Clone, Copy)]
1463pub struct SuiteItems<'a> {
1464    pub fns: &'a [FnDecl],
1465    pub fixtures: &'a [FixtureDecl],
1466    /// #3066: the suite's own `type` and `const` declarations.
1467    pub types: &'a [TypeDecl],
1468    pub consts: &'a [ConstDecl],
1469}
1470
1471impl<'a> SuiteItems<'a> {
1472    pub const NONE: SuiteItems<'static> = SuiteItems {
1473        fns: &[],
1474        fixtures: &[],
1475        types: &[],
1476        consts: &[],
1477    };
1478
1479    pub fn of(suite: &'a SuiteDecl) -> Self {
1480        SuiteItems {
1481            fns: &suite.fns,
1482            fixtures: &suite.fixtures,
1483            types: &suite.types,
1484            consts: &suite.consts,
1485        }
1486    }
1487
1488    pub fn is_empty(&self) -> bool {
1489        self.fns.is_empty()
1490            && self.fixtures.is_empty()
1491            && self.types.is_empty()
1492            && self.consts.is_empty()
1493    }
1494}
1495
1496/// #2841: a fixture, as the `String` constant the checker already knows an
1497/// `embed` to be (the view's `embeds` map, read at an identifier).
1498fn fixture_as_embed(f: &FixtureDecl) -> EmbedDecl {
1499    EmbedDecl {
1500        name: f.name.clone(),
1501        path: f.path.clone(),
1502        path_span: f.path_span,
1503        documentation: f.documentation.clone(),
1504        private: None,
1505        span: f.span,
1506        trivia: f.trivia.clone(),
1507    }
1508}
1509
1510/// #2834: add a suite's helper `fn`s to the view its bodies are checked in. The
1511/// helpers are the suite's alone: the unit's own table, and with it everything
1512/// the deployable emits, never sees them.
1513pub fn add_suite_fns(resolved: &mut ResolvedCommons, items: SuiteItems<'_>) {
1514    // #3066: the suite's own types and constants join its view the same way.
1515    for t in items.types {
1516        // #3536: a suite type wins over a standard-library type the target's
1517        // braces leave out, which is not in scope under its own name.
1518        if resolved.unselected_types.remove(&t.name.name) {
1519            resolved
1520                .types
1521                .insert(t.name.name.clone(), Arc::new(t.clone()));
1522        } else {
1523            resolved
1524                .types
1525                .entry(t.name.name.clone())
1526                .or_insert_with(|| Arc::new(t.clone()));
1527        }
1528        resolved.local_type_names.insert(t.name.name.clone());
1529    }
1530    for c in items.consts {
1531        resolved
1532            .consts
1533            .entry(c.name.name.clone())
1534            .or_insert_with(|| c.clone());
1535    }
1536    for f in items.fixtures {
1537        resolved
1538            .embeds
1539            .entry(f.name.name.clone())
1540            .or_insert_with(|| fixture_as_embed(f));
1541    }
1542    for f in items.fns {
1543        if let FnName::Free(name) = &f.name {
1544            resolved
1545                .fns
1546                .entry(name.name.clone())
1547                .or_insert_with(|| Arc::new(f.clone()));
1548        }
1549    }
1550}
1551
1552/// #2834: the index namespace a suite with helpers records under: its target
1553/// (or, for a `system` suite, its harness) and the file it is declared in.
1554pub fn suite_helper_namespace(target: &str, file: &std::path::Path) -> String {
1555    format!("{target}#helpers:{}", file.display())
1556}
1557
1558/// #2841: the fixture-name rules and the unused warning for `suite`, against
1559/// the case scope `resolved` (the view *before* the suite's own items join it).
1560pub fn check_suite_fixtures_in(
1561    suite: &SuiteDecl,
1562    resolved: &ResolvedCommons,
1563    target: Option<&UnitTable>,
1564    errors: &mut Vec<CompileError>,
1565) {
1566    if suite.fixtures.is_empty() {
1567        return;
1568    }
1569    let taken = bound_value_names(resolved, target);
1570    crate::fixtures::check_suite_fixtures(suite, &taken, errors);
1571}
1572
1573/// #2834: the typed-commons counterpart of [`add_suite_fns`], for lowering.
1574pub fn add_suite_fns_to_typed(typed: &mut checker::TypedCommons, suite_fns: &[FnDecl]) {
1575    for f in suite_fns {
1576        if let FnName::Free(name) = &f.name {
1577            typed
1578                .fns
1579                .entry(name.name.clone())
1580                .or_insert_with(|| Arc::new(f.clone()));
1581        }
1582    }
1583}
1584
1585/// #2834: the value names `resolved` already binds in a case body's scope, so a
1586/// helper may not shadow one (`bynk.suite.fn_name_clash`).
1587fn bound_value_names(resolved: &ResolvedCommons, target: Option<&UnitTable>) -> HashSet<String> {
1588    let mut names: HashSet<String> = HashSet::new();
1589    names.extend(resolved.fns.keys().cloned());
1590    // #3536: a type the target's braces leave out is not a name in scope.
1591    names.extend(
1592        resolved
1593            .types
1594            .keys()
1595            .filter(|n| !resolved.unselected_types.contains(*n))
1596            .cloned(),
1597    );
1598    names.extend(resolved.consts.keys().cloned());
1599    names.extend(resolved.embeds.keys().cloned());
1600    names.extend(resolved.assets.keys().cloned());
1601    // The runner declares these itself, ahead of the helpers.
1602    names.insert("deps".to_string());
1603    if let Some(t) = target {
1604        names.extend(t.services.keys().cloned());
1605        names.extend(t.agents.keys().cloned());
1606    }
1607    names
1608}
1609
1610/// #3066: the `type` and `const` declarations of a suite, checked against the
1611/// case scope `resolved` (the view *before* they join it). A name already bound
1612/// in that scope (a target or used-commons declaration, a sum variant), or
1613/// repeated within the suite, is refused rather than shadowed; the rest join
1614/// `resolved` and are checked as a unit's own are. Returns the initialisers'
1615/// `expr_types` and `Callee` classification for the emit path, which re-checks
1616/// with throwaway sinks.
1617#[allow(clippy::too_many_arguments)]
1618pub fn check_suite_decls(
1619    types: &[TypeDecl],
1620    consts: &[ConstDecl],
1621    resolved: &mut ResolvedCommons,
1622    target: Option<&UnitTable>,
1623    errors: &mut Vec<CompileError>,
1624    refs: &mut RefSink,
1625    locals: &mut LocalsSink,
1626    tys: &Arc<Types>,
1627) -> (
1628    HashMap<ExprId, checker::TypedExpr>,
1629    HashMap<ExprId, checker::Callee>,
1630) {
1631    if types.is_empty() && consts.is_empty() {
1632        return Default::default();
1633    }
1634    let mut taken = bound_value_names(resolved, target);
1635    for t in resolved.types.values() {
1636        if let TypeBody::Sum(s) = &t.body
1637            && !resolved.unselected_types.contains(&t.name.name)
1638        {
1639            taken.extend(s.variants.iter().map(|v| v.name.name.clone()));
1640        }
1641    }
1642    let mut seen: HashSet<String> = HashSet::new();
1643    let mut ok_types: Vec<TypeDecl> = Vec::new();
1644    let mut ok_consts: Vec<ConstDecl> = Vec::new();
1645    let mut verdict = |name: &Ident,
1646                       kind: &str,
1647                       dup: &'static str,
1648                       clash: &'static str,
1649                       errors: &mut Vec<CompileError>|
1650     -> bool {
1651        if !seen.insert(name.name.clone()) {
1652            errors.push(CompileError::new(
1653                dup,
1654                name.span,
1655                format!("this suite declares `{}` twice", name.name),
1656            ));
1657            return false;
1658        }
1659        if taken.contains(&name.name) || name.name.starts_with("__") {
1660            errors.push(
1661                CompileError::new(
1662                    clash,
1663                    name.span,
1664                    format!(
1665                        "the suite {kind} `{}` has the name of a declaration already in scope in its cases",
1666                        name.name
1667                    ),
1668                )
1669                .with_note("rename it; a suite `type` or `const` does not shadow the target's or an imported name"),
1670            );
1671            return false;
1672        }
1673        true
1674    };
1675    for t in types {
1676        if !t.type_params.is_empty() {
1677            errors.push(
1678                CompileError::new(
1679                    "bynk.suite.type_generic",
1680                    t.name.span,
1681                    format!("the suite type `{}` is generic", t.name.name),
1682                )
1683                .with_note("a suite type is a plain, non-generic shape; declare a generic type in the target or a `commons`"),
1684            );
1685            continue;
1686        }
1687        if verdict(
1688            &t.name,
1689            "type",
1690            "bynk.suite.duplicate_type",
1691            "bynk.suite.type_name_clash",
1692            errors,
1693        ) {
1694            ok_types.push(t.clone());
1695        }
1696    }
1697    for c in consts {
1698        if verdict(
1699            &c.name,
1700            "const",
1701            "bynk.suite.duplicate_const",
1702            "bynk.suite.const_name_clash",
1703            errors,
1704        ) {
1705            ok_consts.push(c.clone());
1706        }
1707    }
1708    // The variants of the suite's own sum types are values in its cases too: they
1709    // may not clash with anything in scope, with each other, or with a suite
1710    // `type` or `const`.
1711    let item_names: HashSet<&str> = ok_types
1712        .iter()
1713        .map(|t| t.name.name.as_str())
1714        .chain(ok_consts.iter().map(|c| c.name.name.as_str()))
1715        .collect();
1716    let mut variant_seen: HashSet<&str> = HashSet::new();
1717    for t in &ok_types {
1718        let TypeBody::Sum(sum) = &t.body else {
1719            continue;
1720        };
1721        for v in &sum.variants {
1722            let name = v.name.name.as_str();
1723            if taken.contains(name) || item_names.contains(name) || !variant_seen.insert(name) {
1724                errors.push(
1725                    CompileError::new(
1726                        "bynk.suite.type_name_clash",
1727                        v.name.span,
1728                        format!(
1729                            "the variant `{name}` of the suite type `{}` has the name of another value in scope in the suite's cases",
1730                            t.name.name
1731                        ),
1732                    )
1733                    .with_note("rename the variant; a bare variant name would read as either value"),
1734                );
1735            }
1736        }
1737    }
1738    add_suite_fns(
1739        resolved,
1740        SuiteItems {
1741            fns: &[],
1742            fixtures: &[],
1743            types: &ok_types,
1744            consts: &ok_consts,
1745        },
1746    );
1747    // Name resolution over the declarations alone (a field of an unknown type,
1748    // a constant naming an unknown name), as a unit's own are resolved. Checking
1749    // goes no further on a failure: the checker assumes names resolve.
1750    let probe_items: Vec<CommonsItem> = ok_types
1751        .iter()
1752        .cloned()
1753        .map(CommonsItem::Type)
1754        .chain(ok_consts.iter().cloned().map(CommonsItem::Const))
1755        .collect();
1756    let saved = std::mem::replace(&mut Arc::make_mut(&mut resolved.commons).items, probe_items);
1757    let resolution = resolver::resolve_file_record(resolved, refs);
1758    Arc::make_mut(&mut resolved.commons).items = saved;
1759    if let Err(errs) = resolution {
1760        errors.extend(errs);
1761        return Default::default();
1762    }
1763    checker::check_suite_decls(&ok_types, &ok_consts, resolved, tys, errors, refs, locals)
1764}
1765
1766/// #2834: check a suite's helper `fn`s. Each must be a free, pure function
1767/// whose name no value in the case scope already uses and no sibling repeats;
1768/// the helpers are then added to `resolved` (the suite's view) and their
1769/// bodies checked in it. Returns the bodies' `expr_types` and
1770/// `Callee` classification for the emit path, which re-checks with throwaway
1771/// sinks.
1772#[allow(clippy::too_many_arguments)]
1773pub fn check_suite_fns(
1774    suite_fns: &[FnDecl],
1775    resolved: &mut ResolvedCommons,
1776    target: Option<&UnitTable>,
1777    errors: &mut Vec<CompileError>,
1778    refs: &mut RefSink,
1779    locals: &mut LocalsSink,
1780    tys: &Arc<Types>,
1781) -> (
1782    HashMap<ExprId, checker::TypedExpr>,
1783    HashMap<ExprId, checker::Callee>,
1784) {
1785    let mut expr_types = HashMap::new();
1786    let mut callees = HashMap::new();
1787    if suite_fns.is_empty() {
1788        return (expr_types, callees);
1789    }
1790    let taken = bound_value_names(resolved, target);
1791    add_suite_fns(
1792        resolved,
1793        SuiteItems {
1794            fns: suite_fns,
1795            fixtures: &[],
1796            types: &[],
1797            consts: &[],
1798        },
1799    );
1800    let resolved = &*resolved;
1801    let mut seen: HashSet<&str> = HashSet::new();
1802    for f in suite_fns {
1803        let FnName::Free(name) = &f.name else {
1804            errors.push(
1805                CompileError::new(
1806                    "bynk.suite.fn_method",
1807                    f.span,
1808                    format!(
1809                        "a suite helper must be a free function, but `{}` is a method",
1810                        f.name.display()
1811                    ),
1812                )
1813                .with_note("declare the method in the target or a `commons`; a suite `fn` is a plain helper its cases call by name"),
1814            );
1815            continue;
1816        };
1817        if !seen.insert(name.name.as_str()) {
1818            errors.push(CompileError::new(
1819                "bynk.suite.duplicate_fn",
1820                name.span,
1821                format!("this suite declares the helper `{}` twice", name.name),
1822            ));
1823            continue;
1824        }
1825        if taken.contains(&name.name) || name.name.starts_with("__") {
1826            errors.push(
1827                CompileError::new(
1828                    "bynk.suite.fn_name_clash",
1829                    name.span,
1830                    format!(
1831                        "the suite helper `{}` has the name of a declaration already in scope in its cases",
1832                        name.name
1833                    ),
1834                )
1835                .with_note("rename the helper; a suite `fn` does not shadow the target's or an imported name"),
1836            );
1837            continue;
1838        }
1839        if matches!(f.return_type, TypeRef::Effect(..)) {
1840            errors.push(
1841                CompileError::new(
1842                    "bynk.suite.fn_effectful",
1843                    f.return_type.span(),
1844                    format!("the suite helper `{}` returns an `Effect`", name.name),
1845                )
1846                .with_note("a suite helper is a pure function; build the value in the helper and run the effect in the `case`"),
1847            );
1848            continue;
1849        }
1850        refs.set_owner(f.name.display());
1851        checker::check_suite_fn(
1852            f,
1853            resolved,
1854            &mut expr_types,
1855            &mut callees,
1856            errors,
1857            refs,
1858            &mut HintSink::new(),
1859            locals,
1860            &mut RequirementSink::new(),
1861            tys,
1862        );
1863        refs.clear_owner();
1864    }
1865    (expr_types, callees)
1866}
1867
1868/// Review of #1814: `bynk.uses.name_conflict` for a reached name a suite's
1869/// view binds to another declaration, at `span`. `names` says what the view
1870/// binds the name to. The same diagnostic a unit's closure gives (#1807).
1871fn view_conflict_error(
1872    c: &crate::project_model::ViewConflict,
1873    span: Span,
1874    names: &str,
1875) -> CompileError {
1876    CompileError::new(
1877        "bynk.uses.name_conflict",
1878        span,
1879        format!(
1880            "`{via}` brings in declarations that use type `{t}` from `{owner}`, but `{t}` in \
1881             this suite names {names}",
1882            via = c.via,
1883            t = c.name,
1884            owner = c.owner,
1885        ),
1886    )
1887    .with_note(
1888        "rename one of the two types; the imported declarations cannot be checked against a \
1889         different type of the same name",
1890    )
1891}
1892
1893fn first_test_target_span(indices: &[usize], parsed: &[ParsedFile]) -> Span {
1894    indices
1895        .first()
1896        .and_then(|&i| parsed[i].test().map(|t| t.target.span))
1897        .unwrap_or_default()
1898}
1899
1900/// Type-check test/property bodies for a target and validate `stub` RHS
1901/// value types (v0.118). Bodies use the target's privileged view; a `stub`
1902/// value whose type disagrees with the overridden op's return is
1903/// `bynk.stub.rhs_type`.
1904#[allow(clippy::too_many_arguments)]
1905fn check_test_bodies(
1906    target_name: &str,
1907    target_kind: UnitKind,
1908    indices: &[usize],
1909    parsed: &[ParsedFile],
1910    stubs: &HashMap<String, ResolvedStub>,
1911    unit_tables: &HashMap<String, UnitTable>,
1912    exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
1913    unit_consumes: &HashMap<String, Vec<String>>,
1914    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
1915    unit_uses: &HashMap<String, Vec<String>>,
1916    refs: &mut RefSink,
1917    locals: &mut LocalsSink,
1918    tys: &Arc<Types>,
1919    d1_sql: Option<&crate::d1_sql::D1Sql>,
1920) -> Vec<CompileError> {
1921    let mut errors = Vec::new();
1922
1923    // The target's privileged view, built once for the `stub` check and the
1924    // #1814 naming gate and conflict report below.
1925    let privileged = build_privileged_resolved(
1926        target_name,
1927        unit_tables,
1928        unit_uses,
1929        unit_consumes,
1930        unit_consumes_aliases,
1931    );
1932
1933    // v0.118: validate each `stub` RHS value's type against the overridden
1934    // op's declared return type, in the target's privileged view. A best-effort
1935    // check: the value expression is type-checked as if it were the op body's
1936    // tail; any resulting error surfaces as `bynk.stub.rhs_type`.
1937    if !stubs.is_empty()
1938        && let Some((resolved, _)) = &privileged
1939    {
1940        for rp in stubs.values() {
1941            refs.enter_file(&rp.identity_path, target_name, false);
1942            for (clause_idx, clause) in rp.clauses.iter().enumerate() {
1943                let Some(op) = rp
1944                    .cap_decl
1945                    .ops
1946                    .iter()
1947                    .find(|o| o.name.name == clause.method.name)
1948                else {
1949                    continue;
1950                };
1951                // #2850/#2907: the declaring suite's fixtures and helpers are
1952                // in scope in its clauses' values.
1953                let clause_view = if rp.clause_fixtures[clause_idx].is_empty()
1954                    && rp.clause_fns[clause_idx].is_empty()
1955                    && rp.clause_types[clause_idx].is_empty()
1956                    && rp.clause_consts[clause_idx].is_empty()
1957                {
1958                    None
1959                } else {
1960                    build_privileged_resolved(
1961                        target_name,
1962                        unit_tables,
1963                        unit_uses,
1964                        unit_consumes,
1965                        unit_consumes_aliases,
1966                    )
1967                    .map(|(mut view, _)| {
1968                        add_suite_fns(
1969                            &mut view,
1970                            SuiteItems {
1971                                fns: &rp.clause_fns[clause_idx],
1972                                fixtures: &rp.clause_fixtures[clause_idx],
1973                                types: &rp.clause_types[clause_idx],
1974                                consts: &rp.clause_consts[clause_idx],
1975                            },
1976                        );
1977                        view
1978                    })
1979                };
1980                let resolved = clause_view.as_ref().unwrap_or(resolved);
1981                let check_value = |e: &Expr, errors: &mut Vec<CompileError>| {
1982                    let errs = stub_value_errors(e, op, resolved, tys);
1983                    if errs.is_empty() {
1984                        return;
1985                    }
1986                    let unresolved = stub_name_errors(errs);
1987                    if !unresolved.is_empty() {
1988                        errors.extend(unresolved);
1989                    } else {
1990                        errors.push(CompileError::new(
1991                            "bynk.stub.rhs_type",
1992                            e.span,
1993                            format!(
1994                                "the value provided for `{}.{}` does not match the operation's declared return type `{}`",
1995                                rp.cap,
1996                                op.name.name,
1997                                ts_type_ref_display(&op.return_type),
1998                            ),
1999                        ));
2000                    }
2001                };
2002                match &clause.rhs {
2003                    StubRhs::Returns(e) => check_value(e, &mut errors),
2004                    StubRhs::ReturnsEach(outcomes, _) => {
2005                        for o in outcomes {
2006                            if let SeqOutcome::Value(e) = o {
2007                                check_value(e, &mut errors);
2008                            }
2009                        }
2010                    }
2011                    StubRhs::Fails(_) | StubRhs::Never(_) => {}
2012                }
2013                // #2683: `after <d>` is a Duration.
2014                if let Some(after) = &clause.after
2015                    && !stub_after_typechecks(after, resolved, tys)
2016                {
2017                    errors.push(CompileError::new(
2018                        "bynk.stub.after_type",
2019                        after.span,
2020                        format!(
2021                            "`after` in a `stub` for `{}.{}` takes a `Duration`, such as `3.seconds`",
2022                            rp.cap, op.name.name
2023                        ),
2024                    ));
2025                }
2026            }
2027        }
2028    }
2029
2030    // #1737: which target services reach another context, for the tier gate
2031    // in the loop below. Computed once per target.
2032    let crossing = CrossingServices::of(
2033        target_name,
2034        unit_tables,
2035        unit_consumes,
2036        unit_consumes_aliases,
2037    );
2038
2039    // #1814: the types the target's privileged view reaches but does not
2040    // name. A case resolves them; no suite may write one.
2041    // #1927: the imported types the target hides behind its own values,
2042    // with the target's types to find a shadowed sum's variants.
2043    let target_shadowed = privileged
2044        .as_ref()
2045        .map(|(r, _)| (r.shadowed_imports.clone(), r.types.clone()))
2046        .unwrap_or_default();
2047    let reach = privileged.map(|(_, r)| r).unwrap_or_default();
2048    let hidden = reach.hidden;
2049
2050    // Review of #1814: a reached name the view binds to a consumed context's
2051    // unexported type. The target's own table holds only that context's
2052    // exports, so its closure resolved the name to the reached commons type
2053    // and reported nothing; every other conflict here is the target's own,
2054    // which its closure already reported as `bynk.uses.name_conflict`.
2055    for c in &reach.conflicts {
2056        let Some(bound) = &c.bound else {
2057            continue;
2058        };
2059        let consumed = unit_consumes
2060            .get(target_name)
2061            .is_some_and(|cs| cs.contains(bound));
2062        let exported = exports_visibility
2063            .get(bound)
2064            .is_some_and(|e| e.contains_key(&c.name));
2065        if consumed && !exported {
2066            errors.push(view_conflict_error(
2067                c,
2068                first_test_target_span(indices, parsed),
2069                &format!("`{bound}`'s unexported type"),
2070            ));
2071        }
2072    }
2073
2074    // Type-check test case bodies — they live in the target's privileged
2075    // view, with `stub` overriding individual capability seams.
2076    for &i in indices {
2077        let Some(test_decl) = parsed[i].test() else {
2078            continue;
2079        };
2080        let maps = (unit_tables, unit_uses, unit_consumes, unit_consumes_aliases);
2081        errors.extend(suite_naming_errors(
2082            test_decl,
2083            &parsed[i],
2084            target_name,
2085            maps,
2086            (&hidden, &target_shadowed),
2087        ));
2088        // v0.25: test-case edges record in the test file, resolving bare
2089        // names through the *target* unit's namespace.
2090        // #2834: a suite with helpers is its own namespace for the index, so
2091        // its helpers are definitions of its own — two suites of one target
2092        // may each declare a `gh`. Its bare names resolve as the target's do.
2093        let namespace = if SuiteItems::of(test_decl).is_empty() {
2094            target_name.to_string()
2095        } else {
2096            let ns = suite_helper_namespace(target_name, &parsed[i].identity_path());
2097            let mut resolution = vec![target_name.to_string()];
2098            resolution.extend(unit_uses.get(target_name).into_iter().flatten().cloned());
2099            resolution.extend(
2100                unit_consumes
2101                    .get(target_name)
2102                    .into_iter()
2103                    .flatten()
2104                    .cloned(),
2105            );
2106            refs.declare_namespace(&ns, resolution);
2107            ns
2108        };
2109        refs.enter_file(
2110            &parsed[i].identity_path(),
2111            &namespace,
2112            parsed[i].is_synthetic(),
2113        );
2114        // #2517: and so do the case and property locals.
2115        locals.enter_file(&parsed[i].identity_path(), parsed[i].is_synthetic());
2116        // #2834/#2841: the suite's fixtures and helpers, checked once in the
2117        // target's view.
2118        if !SuiteItems::of(test_decl).is_empty()
2119            && let Some((mut helper_view, _)) = build_privileged_resolved(
2120                target_name,
2121                unit_tables,
2122                unit_uses,
2123                unit_consumes,
2124                unit_consumes_aliases,
2125            )
2126        {
2127            register_call_record_types(&mut helper_view, target_name, unit_tables);
2128            check_suite_fixtures_in(
2129                test_decl,
2130                &helper_view,
2131                unit_tables.get(target_name),
2132                &mut errors,
2133            );
2134            add_suite_fns(
2135                &mut helper_view,
2136                SuiteItems {
2137                    fns: &[],
2138                    fixtures: &test_decl.fixtures,
2139                    types: &[],
2140                    consts: &[],
2141                },
2142            );
2143            check_suite_decls(
2144                &test_decl.types,
2145                &test_decl.consts,
2146                &mut helper_view,
2147                unit_tables.get(target_name),
2148                &mut errors,
2149                refs,
2150                locals,
2151                tys,
2152            );
2153            check_suite_fns(
2154                &test_decl.fns,
2155                &mut helper_view,
2156                unit_tables.get(target_name),
2157                &mut errors,
2158                refs,
2159                locals,
2160                tys,
2161            );
2162        }
2163        for case in &test_decl.cases {
2164            let case_callees = check_test_case_body(
2165                target_name,
2166                target_kind,
2167                SuiteItems::of(test_decl),
2168                case,
2169                unit_tables,
2170                unit_uses,
2171                unit_consumes,
2172                unit_consumes_aliases,
2173                &mut errors,
2174                refs,
2175                locals,
2176                tys,
2177            );
2178            check_d1_sql_sites(
2179                d1_sql,
2180                target_name,
2181                unit_tables,
2182                &case_callees,
2183                parsed[i].source(),
2184                &mut errors,
2185            );
2186            let tier = case_effective_tier(case, test_decl);
2187            check_extra_headers_tier(case, tier, &case_callees, &mut errors);
2188            check_extra_headers_let(case, &case_callees, &mut errors);
2189            check_faults_tier(case, tier, &mut errors);
2190            check_snapshot_placement(
2191                case,
2192                tier == bynk_syntax::ast::TestTier::System,
2193                &mut errors,
2194            );
2195            check_bad_signature_tier(case, tier, &mut errors);
2196            check_wire_tier(case, tier, &mut errors);
2197            if tier != bynk_syntax::ast::TestTier::System {
2198                crossing.check_case_stubbed(stubs, target_name, case, tier, &mut errors);
2199            }
2200        }
2201        // v0.114: generative `property` blocks — check their `for all` bindings,
2202        // `where` filter, and predicate body (testing track slice 2).
2203        // v0.118: a `property` never carries a tier — `as <tier>` is a
2204        // `case`-only affordance, and the grammar has no property-tier
2205        // production (`PropertyDecl` has no tier field), so there is nothing to
2206        // check here (#1662 removed an unreachable guard for it).
2207        for prop in &test_decl.properties {
2208            check_property_body(
2209                target_name,
2210                target_kind,
2211                SuiteItems::of(test_decl),
2212                prop,
2213                unit_tables,
2214                unit_uses,
2215                unit_consumes,
2216                unit_consumes_aliases,
2217                &mut errors,
2218                refs,
2219                locals,
2220                tys,
2221                d1_sql,
2222                parsed[i].source(),
2223            );
2224            crossing.check_property_stubbed(stubs, target_name, prop, &mut errors);
2225            check_advance_in_property(prop, &mut errors);
2226            check_snapshot_in_property(prop, &mut errors);
2227        }
2228    }
2229
2230    errors
2231}
2232
2233/// Every `expect … matches snapshot` in `block`, at any depth, in source order
2234/// (#2842).
2235pub fn snapshot_expects(block: &Block) -> Vec<&bynk_syntax::ast::ExpectStmt> {
2236    blocks_deep(block)
2237        .into_iter()
2238        .flat_map(flat_statements)
2239        .filter_map(|s| match s {
2240            Statement::Expect(e) if e.snapshot.is_some() => Some(e),
2241            _ => None,
2242        })
2243        .collect()
2244}
2245
2246/// #2842: where a snapshot may be taken. A snapshot is a stored file per unit
2247/// suite file, compared in the unit harness, so a `system`-tier case or an
2248/// integration/system suite has none (`bynk.test.snapshot_needs_unit_suite`);
2249/// within a case its names are unique (`bynk.test.snapshot_duplicate_name`).
2250fn check_snapshot_placement(case: &Case, no_store: bool, errors: &mut Vec<CompileError>) {
2251    let mut seen: HashSet<&str> = HashSet::new();
2252    for e in snapshot_expects(&case.body) {
2253        let clause = e.snapshot.as_ref().expect("snapshot_expects filters");
2254        if no_store {
2255            errors.push(
2256                CompileError::new(
2257                    "bynk.test.snapshot_needs_unit_suite",
2258                    clause.span,
2259                    "a snapshot is not available in a `system`-tier case or an integration or system suite",
2260                )
2261                .with_note(
2262                    "snapshots are stored per unit suite file; take the snapshot in a unit-tier `case` of a suite that targets a unit",
2263                ),
2264            );
2265        } else if !seen.insert(clause.name.as_str()) {
2266            errors.push(
2267                CompileError::new(
2268                    "bynk.test.snapshot_duplicate_name",
2269                    clause.name_span,
2270                    format!(
2271                        "case `\"{}\"` already has a snapshot named `\"{}\"`",
2272                        case.name, clause.name
2273                    ),
2274                )
2275                .with_note("a snapshot is keyed by its case and name, so give each `matches snapshot` in a case its own name"),
2276            );
2277        }
2278    }
2279}
2280
2281/// #2842: a `property` runs its body once per generated input, so a snapshot
2282/// there would be keyed by a case that has no single value.
2283fn check_snapshot_in_property(
2284    prop: &bynk_syntax::ast::PropertyDecl,
2285    errors: &mut Vec<CompileError>,
2286) {
2287    for e in snapshot_expects(&prop.forall.body) {
2288        let clause = e.snapshot.as_ref().expect("snapshot_expects filters");
2289        errors.push(
2290            CompileError::new(
2291                "bynk.test.snapshot_in_property",
2292                clause.span,
2293                "a snapshot can only be taken in a `case`, not in a `property`",
2294            )
2295            .with_note("a property runs its body for many generated inputs; snapshot a fixed value in a `case`"),
2296        );
2297    }
2298}
2299
2300/// #2137: `advance Clock by …` moves a `case`'s harness clock. A `property`
2301/// runs its body once per generated input with no clock of its own, so an
2302/// `advance` there is `bynk.test.advance_outside_case`, as it is anywhere else
2303/// outside a `case` body.
2304fn check_advance_in_property(
2305    prop: &bynk_syntax::ast::PropertyDecl,
2306    errors: &mut Vec<CompileError>,
2307) {
2308    fn collect(b: &Block, out: &mut Vec<Span>) {
2309        for s in &b.statements {
2310            if let Statement::Advance(a) = s {
2311                out.push(a.keyword.merge(a.cap.span));
2312            }
2313        }
2314        let mut exprs = Vec::new();
2315        for s in &b.statements {
2316            bynk_syntax::ast::statement_exprs(s, &mut exprs);
2317        }
2318        exprs.push(&b.tail);
2319        for e in exprs {
2320            walk(e, out);
2321        }
2322    }
2323    // Descend through every expression, entering a nested block through
2324    // `collect` so its statements are seen once.
2325    fn walk(e: &Expr, out: &mut Vec<Span>) {
2326        match &e.kind {
2327            ExprKind::Block(inner) => collect(inner, out),
2328            ExprKind::If {
2329                cond,
2330                then_block,
2331                else_block,
2332            } => {
2333                walk(cond, out);
2334                collect(then_block, out);
2335                collect(else_block, out);
2336            }
2337            ExprKind::Match { discriminant, arms } => {
2338                walk(discriminant, out);
2339                for arm in arms {
2340                    if let Some(g) = &arm.guard {
2341                        walk(g, out);
2342                    }
2343                    match &arm.body {
2344                        bynk_syntax::ast::MatchBody::Block(b) => collect(b, out),
2345                        bynk_syntax::ast::MatchBody::Expr(x) => walk(x, out),
2346                    }
2347                }
2348            }
2349            _ => {
2350                for c in bynk_syntax::ast::expr_children(e) {
2351                    walk(c, out);
2352                }
2353            }
2354        }
2355    }
2356    let mut spans = Vec::new();
2357    collect(&prop.forall.body, &mut spans);
2358    for span in spans {
2359        errors.push(
2360            CompileError::new(
2361                "bynk.test.advance_outside_case",
2362                span,
2363                format!(
2364                    "`advance` is only valid inside a `case` body, but this is in property `\"{}\"`",
2365                    prop.name
2366                ),
2367            )
2368            .with_note(
2369                "a property runs its body once per generated input, with no clock of its own; move the time-dependent check into a `case`",
2370            ),
2371        );
2372    }
2373}
2374
2375/// v0.118: wrap a single expression as a `{ tail: e }` block, so a `stub`
2376/// value can be type-checked or lowered in the same op-body position a provider
2377/// operation's tail occupies.
2378///
2379/// Dual-use (found during P5.4's move, not in the original slice plan):
2380/// `stub_value_typechecks` (in this module) uses it for the checking path;
2381/// `bynk-emit`'s `lower_stub_value_block` also calls it, qualified, to lower
2382/// a `stub` RHS value in the same op-body tail position. `pub` for that
2383/// second caller, same as every other dual-use function in this module.
2384pub fn value_block(e: &Expr) -> Block {
2385    Block {
2386        statements: Vec::new(),
2387        tail: Box::new(e.clone()),
2388        span: e.span,
2389        tail_leading_comments: Vec::new(),
2390        implicit_tail: false,
2391    }
2392}
2393
2394/// #2907: a name a `stub` value cannot resolve is that, not a mismatch with
2395/// the operation's return type. #3344: nor is a variant name several sums
2396/// declare that the operation's type does not settle.
2397fn stub_name_errors(errs: Vec<CompileError>) -> Vec<CompileError> {
2398    errs.into_iter()
2399        .filter(|e| {
2400            matches!(
2401                e.category,
2402                "bynk.resolve.unknown_name"
2403                    | "bynk.resolve.unknown_function"
2404                    | "bynk.resolve.ambiguous_variant"
2405            )
2406        })
2407        .collect()
2408}
2409
2410/// v0.118: whether a `stub` value expression type-checks against the
2411/// overridden capability op's declared return type (best-effort — a throwaway
2412/// check against the target's privileged view). Any error drives
2413/// `bynk.stub.rhs_type`, but for an unresolved name (#2907).
2414fn stub_value_errors(
2415    e: &Expr,
2416    op: &CapabilityOp,
2417    resolved: &ResolvedCommons,
2418    tys: &Arc<Types>,
2419) -> Vec<CompileError> {
2420    value_errors(e, &op.return_type, &op.params, resolved, tys)
2421}
2422
2423/// #2683: whether a `stub … after <d>` duration is a `Duration`.
2424pub fn stub_after_typechecks(e: &Expr, resolved: &ResolvedCommons, tys: &Arc<Types>) -> bool {
2425    let duration = TypeRef::Effect(Box::new(TypeRef::Base(BaseType::Duration, e.span)), e.span);
2426    value_errors(e, &duration, &[], resolved, tys).is_empty()
2427}
2428
2429fn value_errors(
2430    e: &Expr,
2431    return_type: &TypeRef,
2432    params: &[Param],
2433    resolved: &ResolvedCommons,
2434    tys: &Arc<Types>,
2435) -> Vec<CompileError> {
2436    let block = value_block(e);
2437    let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
2438    let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
2439    let mut errs: Vec<CompileError> = Vec::new();
2440    checker::check_handler_body(
2441        resolved,
2442        checker::HandlerBodyCheck::new(&block, return_type, params, &[]),
2443        checker::CheckSinks {
2444            tys,
2445            expr_types: &mut expr_types,
2446            errors: &mut errs,
2447            refs: &mut RefSink::new(),
2448            hints: &mut HintSink::new(),
2449            locals: &mut LocalsSink::new(),
2450            requirements: &mut RequirementSink::new(),
2451            callees: &mut callees,
2452        },
2453    );
2454    errs
2455}
2456
2457/// Slice C: whether a `case` body uses a `Wire(…)` raw argument anywhere. A
2458/// `Wire` is only meaningful at `system` (it hands pre-validation input to the
2459/// real boundary); used at any other tier it is `bynk.test.wire_needs_system`.
2460fn block_uses_wire(block: &Block) -> bool {
2461    // Ported onto `bynk_syntax::ast::expr_children` (P5.4) — `bynk-emit`'s
2462    // `crate::emitter::walk_exprs` this used before the move is emission-
2463    // private and unreachable from `bynk-check`. `expr_children` is the
2464    // exhaustive total child iterator the checker already walks the same way
2465    // (see `context_checks.rs`/`checker.rs`); this reimplements the original
2466    // statement-value + tail walk faithfully, not a rewrite of its behaviour.
2467    fn contains_wire(e: &Expr) -> bool {
2468        matches!(e.kind, ExprKind::Wire(_))
2469            || bynk_syntax::ast::expr_children(e)
2470                .into_iter()
2471                .any(contains_wire)
2472    }
2473    // #1851: every expression of a statement, a principal's identity
2474    // included, not a hand-picked value.
2475    let mut exprs = Vec::new();
2476    for s in &block.statements {
2477        bynk_syntax::ast::statement_exprs(s, &mut exprs);
2478    }
2479    exprs.into_iter().any(contains_wire) || contains_wire(&block.tail)
2480}
2481
2482/// A cross-context service call: `(context, service)`.
2483type CrossCall = (String, String);
2484
2485/// A same-context agent handler: `(agent, handler)`.
2486type AgentHandler = (String, String);
2487
2488/// #3892: the consumed services a body stubs, as `(context, service)`: every
2489/// clause that applies to every run or its suite's, plus the case's own when
2490/// `case` names one.
2491fn stubbed_services(
2492    stubs: &HashMap<String, ResolvedStub>,
2493    case: Option<&str>,
2494) -> HashSet<CrossCall> {
2495    let mut out = HashSet::new();
2496    for rp in stubs.values() {
2497        let Some(ctx) = &rp.service_context else {
2498            continue;
2499        };
2500        for (clause, scope) in rp.clauses.iter().zip(&rp.clause_scopes) {
2501            let applies = match scope {
2502                StubScope::Case(name) => case == Some(name.as_str()),
2503                _ => true,
2504            };
2505            if applies {
2506                out.insert((ctx.clone(), clause.method.name.clone()));
2507            }
2508        }
2509    }
2510    out
2511}
2512
2513/// #1737: what in the target reaches another context, for the
2514/// `bynk.tier.cross_context_needs_system` gate: each service, and each agent
2515/// handler, that does, with the cross-context call it reaches.
2516///
2517/// Below `system` a case runs in-process: a consumed context is not stood up,
2518/// and `stub` doubles capabilities only, never a context's services. So a case
2519/// that reaches another context's service (directly, or through a target
2520/// service or agent handler that calls one) had no collaborator to call, and
2521/// crashed at runtime on an `undefined` surface. Crossing a context boundary is
2522/// the `system` tier's job; this finds the test bodies that try it below.
2523///
2524/// A cross-context call is recognised the way the resolver resolves one
2525/// (`CrossContextInfo::resolve_prefix`): a method call whose receiver chain is a
2526/// consumed context's alias or qualified name, naming a service that context
2527/// declares. A service or agent handler reaches another context if its own
2528/// body makes such a call, or dispatches to an agent handler that
2529/// (transitively) does. An agent call is recognised inline
2530/// (`Counter(k).bump(…)`) and through a `let`-bound instance
2531/// (`let c = Counter(k)` then `c.bump(…)`).
2532struct CrossingServices<'a> {
2533    /// service name → the cross-context call it reaches.
2534    services: HashMap<String, CrossCall>,
2535    /// agent handler → the cross-context call it reaches.
2536    agents: HashMap<AgentHandler, CrossCall>,
2537    /// The target's own table, for recognising agent calls in a test body.
2538    table: Option<&'a UnitTable>,
2539    /// The target's consumed contexts and aliases, for direct calls in a body.
2540    consumed: &'a [String],
2541    aliases: Option<&'a HashMap<String, String>>,
2542    unit_tables: &'a HashMap<String, UnitTable>,
2543    /// #3892: the consumed services the body under check stubs. A stub makes the
2544    /// call legal below `system`: the double answers, no context is reached.
2545    stubbed: HashSet<CrossCall>,
2546    /// The maps this was built from, to rebuild it per case's stubs.
2547    consumes: &'a HashMap<String, Vec<String>>,
2548    all_aliases: &'a HashMap<String, HashMap<String, String>>,
2549}
2550
2551impl<'a> CrossingServices<'a> {
2552    fn of(
2553        target_name: &str,
2554        unit_tables: &'a HashMap<String, UnitTable>,
2555        unit_consumes: &'a HashMap<String, Vec<String>>,
2556        unit_consumes_aliases: &'a HashMap<String, HashMap<String, String>>,
2557    ) -> Self {
2558        Self::of_stubbed(
2559            target_name,
2560            unit_tables,
2561            unit_consumes,
2562            unit_consumes_aliases,
2563            HashSet::new(),
2564        )
2565    }
2566
2567    /// [`Self::of`], with the consumed services a body stubs (#3892): they are
2568    /// no crossing, whatever reaches them.
2569    fn of_stubbed(
2570        target_name: &str,
2571        unit_tables: &'a HashMap<String, UnitTable>,
2572        unit_consumes: &'a HashMap<String, Vec<String>>,
2573        unit_consumes_aliases: &'a HashMap<String, HashMap<String, String>>,
2574        stubbed: HashSet<CrossCall>,
2575    ) -> Self {
2576        let mut this = CrossingServices {
2577            services: HashMap::new(),
2578            agents: HashMap::new(),
2579            table: unit_tables.get(target_name),
2580            consumed: unit_consumes
2581                .get(target_name)
2582                .map(Vec::as_slice)
2583                .unwrap_or(&[]),
2584            aliases: unit_consumes_aliases.get(target_name),
2585            unit_tables,
2586            consumes: unit_consumes,
2587            all_aliases: unit_consumes_aliases,
2588            stubbed,
2589        };
2590        let Some(table) = this.table else {
2591            return this;
2592        };
2593        if this.consumed.is_empty() {
2594            return this;
2595        }
2596        // Each agent handler's own cross-context call (if any) and the agent
2597        // handlers it dispatches to, then a fixpoint over the dispatch edges.
2598        let mut agent_edges: HashMap<AgentHandler, Vec<AgentHandler>> = HashMap::new();
2599        for (agent, decl) in &table.agents {
2600            for h in &decl.handlers {
2601                let Some(method) = &h.method_name else {
2602                    continue;
2603                };
2604                let key = (agent.clone(), method.name.clone());
2605                let (hit, edges) = this.scan(&h.body);
2606                if let Some(hit) = hit {
2607                    this.agents.insert(key.clone(), hit);
2608                }
2609                agent_edges.insert(key, edges);
2610            }
2611        }
2612        loop {
2613            let mut changed = false;
2614            for (key, edges) in &agent_edges {
2615                if this.agents.contains_key(key) {
2616                    continue;
2617                }
2618                if let Some(hit) = edges.iter().find_map(|e| this.agents.get(e).cloned()) {
2619                    this.agents.insert(key.clone(), hit);
2620                    changed = true;
2621                }
2622            }
2623            if !changed {
2624                break;
2625            }
2626        }
2627        for (name, decl) in &table.services {
2628            for h in &decl.handlers {
2629                let (hit, edges) = this.scan(&h.body);
2630                let reached =
2631                    hit.or_else(|| edges.iter().find_map(|e| this.agents.get(e).cloned()));
2632                if let Some(reached) = reached {
2633                    this.services.entry(name.clone()).or_insert(reached);
2634                }
2635            }
2636        }
2637        this
2638    }
2639
2640    /// The consumed context `chain` names, by alias or qualified name.
2641    fn resolve(&self, chain: &str) -> Option<&String> {
2642        self.aliases
2643            .and_then(|a| a.get(chain))
2644            .or_else(|| self.consumed.iter().find(|c| *c == chain))
2645    }
2646
2647    /// `e` as a cross-context service call.
2648    fn cross_call(&self, e: &Expr) -> Option<CrossCall> {
2649        let ExprKind::MethodCall {
2650            receiver, method, ..
2651        } = &e.kind
2652        else {
2653            return None;
2654        };
2655        let ctx = self.resolve(&receiver_chain(receiver)?)?;
2656        let callee = self.unit_tables.get(ctx)?;
2657        callee
2658            .services
2659            .contains_key(&method.name)
2660            .then(|| (ctx.clone(), method.name.clone()))
2661    }
2662
2663    /// `e` as an agent handler call, inline (`Counter(k).bump(…)`) or through
2664    /// an instance `bound` by a `let` (`c.bump(…)`).
2665    fn dispatch(&self, e: &Expr, bound: &HashMap<String, String>) -> Option<AgentHandler> {
2666        let table = self.table?;
2667        let ExprKind::MethodCall {
2668            receiver, method, ..
2669        } = &e.kind
2670        else {
2671            return None;
2672        };
2673        let agent = match &receiver.kind {
2674            ExprKind::Call { name, .. } if table.agents.contains_key(&name.name) => {
2675                name.name.clone()
2676            }
2677            ExprKind::Ident(x) => bound.get(&x.name)?.clone(),
2678            _ => return None,
2679        };
2680        Some((agent, method.name.clone()))
2681    }
2682
2683    /// The first cross-context call in `block` (in source order), and every
2684    /// agent handler it dispatches to.
2685    fn scan(&self, block: &Block) -> (Option<CrossCall>, Vec<AgentHandler>) {
2686        let bound = self.agent_bindings(block);
2687        let mut hit = None;
2688        let mut edges = Vec::new();
2689        for e in exprs_in_order(block) {
2690            if hit.is_none() {
2691                hit = self.cross_call(e).filter(|c| !self.stubbed.contains(c));
2692            }
2693            if let Some(edge) = self.dispatch(e, &bound) {
2694                edges.push(edge);
2695            }
2696        }
2697        (hit, edges)
2698    }
2699
2700    /// The names `block` binds, at any depth, to an agent instance
2701    /// (`let c = Counter(k)`), mapped to the agent.
2702    fn agent_bindings(&self, block: &Block) -> HashMap<String, String> {
2703        let mut bound = HashMap::new();
2704        let Some(table) = self.table else {
2705            return bound;
2706        };
2707        for b in blocks_deep(block) {
2708            for s in flat_statements(b) {
2709                if let Statement::Let(l) | Statement::EffectLet(l) = s
2710                    && let ExprKind::Call { name, .. } = &l.value.kind
2711                    && table.agents.contains_key(&name.name)
2712                {
2713                    bound.insert(l.name.name.clone(), name.name.clone());
2714                }
2715            }
2716        }
2717        bound
2718    }
2719
2720    /// Report each call in a non-`system` test body that reaches another
2721    /// context: a target service that crosses (`check.call(…)`), an agent
2722    /// handler that crosses (`Counter(k).bump(…)`), or a consumed context's
2723    /// service called directly. `subject` names the body (``case `"…"` ``),
2724    /// and `below` says why it runs in-process.
2725    fn check_block(
2726        &self,
2727        target_name: &str,
2728        subject: &str,
2729        below: &str,
2730        body: &Block,
2731        errors: &mut Vec<CompileError>,
2732    ) {
2733        if self.consumed.is_empty() {
2734            return;
2735        }
2736        let bound = self.agent_bindings(body);
2737        // A name a `let` in the body rebinds is the binding, not a service.
2738        let shadowed: HashSet<String> = blocks_deep(body)
2739            .into_iter()
2740            .flat_map(flat_statements)
2741            .filter_map(|s| match s {
2742                Statement::Let(l) | Statement::EffectLet(l) => Some(l.name.name.clone()),
2743                _ => None,
2744            })
2745            .collect();
2746        for e in exprs_in_order(body) {
2747            let ExprKind::MethodCall {
2748                receiver,
2749                method,
2750                args,
2751                ..
2752            } = &e.kind
2753            else {
2754                continue;
2755            };
2756            // #1883 (review of #1923): `svc.<VERB>(x)` whose first argument is
2757            // not a route string reaches no handler — it is an asset fetch
2758            // (`svc.GET(asset)`, served by the asset tier) or a bad address
2759            // reported elsewhere — so it crosses into no other context.
2760            if bynk_syntax::ast::HttpMethod::from_ident(&method.name).is_some()
2761                && args
2762                    .first()
2763                    .is_some_and(|a| !matches!(a.kind, ExprKind::StrLit(_)))
2764            {
2765                continue;
2766            }
2767            let through = match &receiver.kind {
2768                // `svc.call(…)` / `svc.GET(…)` / … on a target service.
2769                ExprKind::Ident(svc) if !shadowed.contains(&svc.name) => self
2770                    .services
2771                    .get(&svc.name)
2772                    .map(|reached| (format!("`{}`", svc.name), Some(svc.name.clone()), reached)),
2773                _ => None,
2774            };
2775            let through = through.or_else(|| {
2776                let (agent, handler) = self.dispatch(e, &bound)?;
2777                let reached = self.agents.get(&(agent.clone(), handler.clone()))?;
2778                Some((format!("`{agent}.{handler}`"), None, reached))
2779            });
2780            let message = match through {
2781                Some((via, _, (ctx, svc))) => {
2782                    format!(
2783                        "{subject} calls {via}, which calls `{ctx}.{svc}` in another context, but {below}"
2784                    )
2785                }
2786                None => match self.cross_call(e) {
2787                    Some((ctx, svc)) => {
2788                        format!("{subject} calls `{ctx}.{svc}` in another context, but {below}")
2789                    }
2790                    None => continue,
2791                },
2792            };
2793            let service = match &receiver.kind {
2794                ExprKind::Ident(svc) if self.services.contains_key(&svc.name) => {
2795                    Some(svc.name.clone())
2796                }
2797                _ => None,
2798            };
2799            let promote = match service {
2800                Some(s) => format!(
2801                    "move it into a `system` suite (`suite {target_name} as system {{ … }}`), where the service is addressed by its context path (`{target_name}.{s}(…)`)"
2802                ),
2803                None => format!(
2804                    "move it into a `system` suite (`suite {target_name} as system {{ … }}`) and drive it through one of `{target_name}`'s services (`{target_name}.<service>(…)`), which reaches the other context over the real wire"
2805                ),
2806            };
2807            errors.push(
2808                CompileError::new("bynk.tier.cross_context_needs_system", e.span, message)
2809                    .with_note(format!(
2810                        "below `system` a test runs in-process, with no other context stood up to call; stub the service (`stub <context>.<service>(…) returns …`) to substitute it, or {promote}"
2811                    )),
2812            );
2813        }
2814    }
2815
2816    /// This gate over the services `case` (or, with `None`, only its suite) stubs.
2817    fn with_stubs(
2818        &self,
2819        target_name: &str,
2820        stubs: &HashMap<String, ResolvedStub>,
2821        case: Option<&str>,
2822    ) -> Option<CrossingServices<'a>> {
2823        let stubbed = stubbed_services(stubs, case);
2824        (!stubbed.is_empty()).then(|| {
2825            Self::of_stubbed(
2826                target_name,
2827                self.unit_tables,
2828                self.consumes,
2829                self.all_aliases,
2830                stubbed,
2831            )
2832        })
2833    }
2834
2835    /// [`Self::check_case`], with the services the case or its suite stubs.
2836    fn check_case_stubbed(
2837        &self,
2838        stubs: &HashMap<String, ResolvedStub>,
2839        target_name: &str,
2840        case: &Case,
2841        tier: TestTier,
2842        errors: &mut Vec<CompileError>,
2843    ) {
2844        let gate = self.with_stubs(target_name, stubs, Some(&case.name));
2845        gate.as_ref()
2846            .unwrap_or(self)
2847            .check_case(target_name, case, tier, errors);
2848    }
2849
2850    /// [`Self::check_property`], with the services its suite stubs.
2851    fn check_property_stubbed(
2852        &self,
2853        stubs: &HashMap<String, ResolvedStub>,
2854        target_name: &str,
2855        prop: &PropertyDecl,
2856        errors: &mut Vec<CompileError>,
2857    ) {
2858        let gate = self.with_stubs(target_name, stubs, None);
2859        gate.as_ref()
2860            .unwrap_or(self)
2861            .check_property(target_name, prop, errors);
2862    }
2863
2864    /// The gate for a non-`system` `case`.
2865    fn check_case(
2866        &self,
2867        target_name: &str,
2868        case: &Case,
2869        tier: TestTier,
2870        errors: &mut Vec<CompileError>,
2871    ) {
2872        let tier = tier.as_str();
2873        // "an integration", but "a unit" (said with a "y" sound).
2874        let article = if tier == "integration" { "an" } else { "a" };
2875        self.check_block(
2876            target_name,
2877            &format!("case `\"{}\"`", case.name),
2878            &format!("it is {article} `{tier}`-tier case"),
2879            &case.body,
2880            errors,
2881        );
2882    }
2883
2884    /// The gate for a `property`, which has no tier and always runs in-process.
2885    fn check_property(
2886        &self,
2887        target_name: &str,
2888        prop: &PropertyDecl,
2889        errors: &mut Vec<CompileError>,
2890    ) {
2891        self.check_block(
2892            target_name,
2893            &format!("property `\"{}\"`", prop.name),
2894            "a property runs in-process (it generates, and has no `system` tier)",
2895            &prop.forall.body,
2896            errors,
2897        );
2898    }
2899}
2900
2901/// `e` as a dotted name (`Vault`, `demo.vault`), or `None` for anything that
2902/// is not a chain of identifiers.
2903fn receiver_chain(e: &Expr) -> Option<String> {
2904    match &e.kind {
2905        ExprKind::Ident(id) => Some(id.name.clone()),
2906        ExprKind::FieldAccess { receiver, field } => {
2907            Some(format!("{}.{}", receiver_chain(receiver)?, field.name))
2908        }
2909        _ => None,
2910    }
2911}
2912
2913/// Every expression in `block` at any depth, in source order: each statement's
2914/// expressions, then the tail, each visited before its children (via
2915/// [`bynk_syntax::ast::expr_children`]).
2916fn exprs_in_order(block: &Block) -> Vec<&Expr> {
2917    let mut roots: Vec<&Expr> = Vec::new();
2918    for s in &block.statements {
2919        bynk_syntax::ast::statement_exprs(s, &mut roots);
2920    }
2921    roots.push(&block.tail);
2922    // A stack popped from the end, so push in reverse to visit in order.
2923    let mut stack: Vec<&Expr> = roots.into_iter().rev().collect();
2924    let mut out = Vec::new();
2925    while let Some(e) = stack.pop() {
2926        out.push(e);
2927        stack.extend(bynk_syntax::ast::expr_children(e).into_iter().rev());
2928    }
2929    out
2930}
2931
2932/// A block's statements with each `par` block (#2640) opened up: its bindings are
2933/// statements of the case in every respect these scans care about (a name bound,
2934/// a `by` principal), so they are read as if written in sequence.
2935fn flat_statements(block: &Block) -> Vec<&Statement> {
2936    fn push<'a>(s: &'a Statement, out: &mut Vec<&'a Statement>) {
2937        match s {
2938            Statement::Par(p) => p.statements.iter().for_each(|inner| push(inner, out)),
2939            other => out.push(other),
2940        }
2941    }
2942    let mut out = Vec::new();
2943    block.statements.iter().for_each(|s| push(s, &mut out));
2944    out
2945}
2946
2947/// `block` and every block nested in it (a block expression, an `if`'s
2948/// branches, a `match` arm's block body), so a `let` at any depth is seen.
2949fn blocks_deep(block: &Block) -> Vec<&Block> {
2950    let mut out = vec![block];
2951    for e in exprs_in_order(block) {
2952        match &e.kind {
2953            ExprKind::Block(b) => out.push(b),
2954            ExprKind::If {
2955                then_block,
2956                else_block,
2957                ..
2958            } => {
2959                out.push(then_block);
2960                out.push(else_block);
2961            }
2962            ExprKind::Match { arms, .. } => {
2963                for arm in arms {
2964                    if let MatchBody::Block(b) = &arm.body {
2965                        out.push(b);
2966                    }
2967                }
2968            }
2969            _ => {}
2970        }
2971    }
2972    out
2973}
2974
2975/// #1706: whether a `case` body claims a fault anywhere (`expect <call>
2976/// faults`). The claim observes a call *throwing*, which only an in-process
2977/// call does: at `system` a handler's fault crosses the real Worker boundary
2978/// as an error response, never a throw at the harness, so the claim could
2979/// never hold there (`bynk.test.faults_needs_in_process`).
2980fn block_uses_faults(block: &Block) -> bool {
2981    !faults_claims(block).is_empty()
2982}
2983
2984/// Every fault claim (`expect <call> faults`) in `block`, at any depth, in
2985/// source order.
2986fn faults_claims(block: &Block) -> Vec<&bynk_syntax::ast::FaultsExpr> {
2987    fn collect<'a>(e: &'a Expr, out: &mut Vec<&'a bynk_syntax::ast::FaultsExpr>) {
2988        if let ExprKind::Faults(f) = &e.kind {
2989            out.push(f);
2990        }
2991        for c in bynk_syntax::ast::expr_children(e) {
2992            collect(c, out);
2993        }
2994    }
2995    let mut exprs = Vec::new();
2996    for s in &block.statements {
2997        bynk_syntax::ast::statement_exprs(s, &mut exprs);
2998    }
2999    exprs.push(&block.tail);
3000    let mut out = Vec::new();
3001    for e in exprs {
3002        collect(e, &mut out);
3003    }
3004    out
3005}
3006
3007/// #2052: report a `system`-tier case that delivers an event with
3008/// `svc.event(e)`. At `system` an event reaches a subscriber only through its
3009/// publisher's fan-out, which emits to every subscriber of the event rather
3010/// than addressing one service, over a per-edge signed request. A case-built
3011/// delivery to one subscriber has no counterpart there, so the address is an
3012/// in-process one: the case drives the emitting handler instead.
3013fn check_event_address_tier(
3014    case: &Case,
3015    tier: bynk_syntax::ast::TestTier,
3016    callees: &HashMap<ExprId, checker::Callee>,
3017    errors: &mut Vec<CompileError>,
3018) {
3019    if tier != bynk_syntax::ast::TestTier::System {
3020        return;
3021    }
3022    let mut services: Vec<&str> = callees
3023        .values()
3024        .filter_map(|c| match c {
3025            checker::Callee::TestService {
3026                service,
3027                address: checker::HandlerAddress::Event,
3028                ..
3029            } => Some(service.as_str()),
3030            _ => None,
3031        })
3032        .collect();
3033    services.sort_unstable();
3034    services.dedup();
3035    for service in services {
3036        errors.push(
3037            CompileError::new(
3038                "bynk.test.event_needs_in_process",
3039                case.name_span,
3040                format!(
3041                    "case `\"{}\"` delivers an event with `{service}.event(…)`, but is a `system`-tier case",
3042                    case.name
3043                ),
3044            )
3045            .with_note(
3046                "at `system` an event reaches a subscriber only through its publisher's fan-out; drive the handler that emits it, or deliver the event at `unit` or `integration`",
3047            ),
3048        );
3049    }
3050}
3051
3052/// #3051: a `system`-tier case cannot drive a WebSocket lifecycle address: a
3053/// deployed WebSocket is a real upgrade through the Worker and a Durable Object,
3054/// which the system harness does not drive. The address is an in-process one.
3055fn check_ws_address_tier(
3056    case: &Case,
3057    tier: bynk_syntax::ast::TestTier,
3058    callees: &HashMap<ExprId, checker::Callee>,
3059    errors: &mut Vec<CompileError>,
3060) {
3061    if tier != bynk_syntax::ast::TestTier::System {
3062        return;
3063    }
3064    let mut services: Vec<&str> = callees
3065        .values()
3066        .filter_map(|c| match c {
3067            checker::Callee::TestService {
3068                service,
3069                address: checker::HandlerAddress::Ws(_),
3070                ..
3071            } => Some(service.as_str()),
3072            _ => None,
3073        })
3074        .collect();
3075    services.sort_unstable();
3076    services.dedup();
3077    for service in services {
3078        errors.push(
3079            CompileError::new(
3080                "bynk.test.ws_needs_in_process",
3081                case.name_span,
3082                format!(
3083                    "case `\"{}\"` drives the WebSocket service `{service}` by address, but is a `system`-tier case",
3084                    case.name
3085                ),
3086            )
3087            .with_note(
3088                "a deployed WebSocket is a real upgrade through the Worker and a Durable Object, which a `system` case does not drive; drive the service at `unit` or `integration`",
3089            ),
3090        );
3091    }
3092}
3093
3094/// #2910: a trailing `RequestHeaders` sent to a route that declares no
3095/// `headers:` parameter reaches the route only over a real request, so it is a
3096/// `system`-tier form. Below `system` it stays the arity error it always was,
3097/// with a note saying why.
3098fn check_extra_headers_tier(
3099    case: &Case,
3100    tier: bynk_syntax::ast::TestTier,
3101    callees: &HashMap<ExprId, checker::Callee>,
3102    errors: &mut Vec<CompileError>,
3103) {
3104    if tier == bynk_syntax::ast::TestTier::System {
3105        return;
3106    }
3107    for e in exprs_in_order(&case.body) {
3108        let Some(checker::Callee::TestService {
3109            address,
3110            extra_headers: true,
3111            ..
3112        }) = callees.get(&e.id)
3113        else {
3114            continue;
3115        };
3116        let address = address.describe();
3117        errors.push(
3118            CompileError::new(
3119                "bynk.test.service_call_arity",
3120                e.span,
3121                format!(
3122                    "case `\"{}\"` sends extra request headers to `{address}`, which declares no `headers:` parameter, but is a `{}`-tier case",
3123                    case.name,
3124                    tier.as_str()
3125                ),
3126            )
3127            .with_note(
3128                "extra request headers can only be sent in a `system` case; at lower tiers the route sees only its declared parameters",
3129            ),
3130        );
3131    }
3132}
3133
3134/// #2931: the headers value of an extra-headers call may be a top-level `let`
3135/// bound to the literal `RequestHeaders.of([…])`; run the `Authorization`
3136/// check on that initialiser, so the common indirection gets the check-time
3137/// diagnostic rather than the runtime drop.
3138fn check_extra_headers_let(
3139    case: &Case,
3140    callees: &HashMap<ExprId, checker::Callee>,
3141    errors: &mut Vec<CompileError>,
3142) {
3143    use bynk_syntax::ast::ExprKind;
3144    for e in exprs_in_order(&case.body) {
3145        if !matches!(
3146            callees.get(&e.id),
3147            Some(checker::Callee::TestService {
3148                extra_headers: true,
3149                ..
3150            })
3151        ) {
3152            continue;
3153        }
3154        let ExprKind::MethodCall { args, .. } = &e.kind else {
3155            continue;
3156        };
3157        let Some(ExprKind::Ident(name)) = args.last().map(|a| &a.kind) else {
3158            continue;
3159        };
3160        // The nearest `let` of that name before the call.
3161        let init = flat_statements(&case.body)
3162            .into_iter()
3163            .filter_map(|s| match s {
3164                Statement::Let(l) | Statement::EffectLet(l) if l.name.name == name.name => {
3165                    Some(&l.value)
3166                }
3167                _ => None,
3168            })
3169            .take_while(|v| v.span.start < e.span.start)
3170            .last();
3171        if let Some(init) = init {
3172            errors.extend(checker::extra_headers_authorization_errors(init));
3173        }
3174    }
3175}
3176
3177/// #2649: report a `system`-tier case that addresses an `on call` service with
3178/// `svc.call(…)`. An `on call` service has no public route to drive: it is
3179/// internal to the deployment and its calls are signed per caller (#2004), so
3180/// the system driver has nothing to send, and lowering would emit an unresolved
3181/// receiver (`/* unknown */.call(…)`) rather than a real call. The case drives an `http` route that reaches the handler, or runs the
3182/// call at `unit` or `integration`.
3183fn check_call_address_tier(
3184    case: &Case,
3185    tier: bynk_syntax::ast::TestTier,
3186    callees: &HashMap<ExprId, checker::Callee>,
3187    errors: &mut Vec<CompileError>,
3188) {
3189    if tier != bynk_syntax::ast::TestTier::System {
3190        return;
3191    }
3192    let mut services: Vec<&str> = callees
3193        .values()
3194        .filter_map(|c| match c {
3195            checker::Callee::TestService {
3196                service,
3197                address: checker::HandlerAddress::Call,
3198                ..
3199            } => Some(service.as_str()),
3200            _ => None,
3201        })
3202        .collect();
3203    services.sort_unstable();
3204    services.dedup();
3205    for service in services {
3206        errors.push(
3207            CompileError::new(
3208                "bynk.test.call_needs_in_process",
3209                case.name_span,
3210                format!(
3211                    "case `\"{}\"` calls the `on call` service `{service}` with `{service}.call(…)`, but is a `system`-tier case",
3212                    case.name
3213                ),
3214            )
3215            .with_note(
3216                "an `on call` service is internal to a deployment and has no public route for a `system` case to drive; drive an `http` route that reaches it, or call it at `unit` or `integration`",
3217            ),
3218        );
3219    }
3220}
3221
3222/// #2138 (end-to-end testing track §3.7): what a remote run can't honour.
3223/// Under `bynk test --against`, a `system` case runs against a real
3224/// deployment, which only answers on its public `http` routes. Returns the
3225/// `bynk.test.remote_unsupported_*` refusal for `case`, given the callees its
3226/// body was checked with, or `None` when it uses only `http` addresses.
3227///
3228/// Refused, in this order (the first that applies is reported):
3229/// - an `on call` address, its own or another context's — internal, and
3230///   signed per pair (#2004, #2012);
3231/// - `advance Clock` — the deployed Workers read wall-clock time (§3.4);
3232/// - `svc.schedule(…)` and `q.message(…)` — no public wire reaches a cron
3233///   handler or a queue consumer;
3234/// - an asset fetch (`svc.GET(asset)`) — answered in process from the files
3235///   the target ships, not by the deployment.
3236///
3237/// The track's other two refusals, a direct agent read and `svc.event(…)`,
3238/// are already refused at the `system` tier itself (an agent isn't in a
3239/// `system` case's scope; `bynk.test.event_needs_in_process`), so a remote
3240/// build never sees them.
3241pub fn remote_unsupported(
3242    case: &Case,
3243    callees: &HashMap<ExprId, checker::Callee>,
3244) -> Option<CompileError> {
3245    use checker::Callee;
3246    let callee_list: Vec<&Callee> = callees.values().collect();
3247    let refusal = |code: &'static str, what: String, note: &str| {
3248        Some(
3249            CompileError::new(
3250                code,
3251                case.name_span,
3252                format!(
3253                    "case `\"{}\"` {what}, which a run against a real runtime can't honour",
3254                    case.name
3255                ),
3256            )
3257            .with_note(note.to_string())
3258            .with_note(
3259                "run it in process (`bynk test` without `--against`), or pass `--skip-unsupported` to skip it with this reason",
3260            ),
3261        )
3262    };
3263    // `callees` is a hash map: pick deterministically among several hits.
3264    let named = |pick: &dyn Fn(&Callee) -> Option<String>| -> Option<String> {
3265        let mut names: Vec<String> = callee_list.iter().filter_map(|c| pick(c)).collect();
3266        names.sort();
3267        names.into_iter().next()
3268    };
3269    if let Some(svc) = named(&|c| match c {
3270        Callee::Cross { unit, service } => Some(format!("{unit}.{service}")),
3271        Callee::TestService {
3272            service,
3273            address: checker::HandlerAddress::Call,
3274            ..
3275        } => Some(service.clone()),
3276        _ => None,
3277    }) {
3278        return refusal(
3279            "bynk.test.remote_unsupported_call",
3280            format!("addresses the `on call` service `{svc}`"),
3281            "an `on call` service is internal to a deployment, and each call is signed for one caller; drive it through an `http` route",
3282        );
3283    }
3284    if block_has_advance(&case.body) {
3285        return refusal(
3286            "bynk.test.remote_unsupported_advance",
3287            "moves the harness clock with `advance Clock`".to_string(),
3288            "a deployed Worker reads wall-clock time, which the test can't move",
3289        );
3290    }
3291    for (address, code, what) in [
3292        (
3293            "schedule",
3294            "bynk.test.remote_unsupported_schedule",
3295            "runs a cron handler",
3296        ),
3297        (
3298            "message",
3299            "bynk.test.remote_unsupported_queue",
3300            "delivers a queue message",
3301        ),
3302    ] {
3303        if let Some(svc) = named(&|c| match c {
3304            Callee::TestService {
3305                service,
3306                address: checker::HandlerAddress::Schedule { .. },
3307                ..
3308            } if address == "schedule" => Some(service.clone()),
3309            Callee::TestService {
3310                service,
3311                address: checker::HandlerAddress::Message,
3312                ..
3313            } if address == "message" => Some(service.clone()),
3314            _ => None,
3315        }) {
3316            return refusal(
3317                code,
3318                format!("{what} with `{svc}.{address}(…)`"),
3319                "a deployment exposes no public wire to that handler; only its `http` routes are reachable",
3320            );
3321        }
3322    }
3323    // #3147: a read of a participant's in-process test database. A deployment
3324    // has none, and reaching a deployed D1 would make a test run touch real data.
3325    if callee_list
3326        .iter()
3327        .any(|c| matches!(c, Callee::D1Peek { .. }))
3328    {
3329        return refusal(
3330            "bynk.test.remote_unsupported_peek",
3331            "reads a participant's database with `D1.peek`".to_string(),
3332            "a deployment has no in-process test database, and reaching a deployed D1 would make a test run touch real data",
3333        );
3334    }
3335    if let Some(svc) = named(&|c| match c {
3336        Callee::TestAssetFetch { service } => Some(service.clone()),
3337        _ => None,
3338    }) {
3339        return refusal(
3340            "bynk.test.remote_unsupported_asset",
3341            format!("fetches an asset with `{svc}.GET(…)`"),
3342            "an asset fetch is answered in process from the files the target ships, not by the deployment",
3343        );
3344    }
3345    None
3346}
3347
3348/// #2138 (track §3.4): `bynk.test.remote_clock_dependent`, a warning for a
3349/// remote run. In process every `Clock` reads the harness clock; a real
3350/// runtime's Workers read wall-clock time, which the runner can't reach. So an
3351/// `expect` comparing an `Instant` built from constants can pass in process
3352/// and fail remotely, and no `--settle` retry fixes that.
3353///
3354/// An expression is *constant* when nothing the run produced flows into it:
3355/// literals, type and static receivers (`Instant.fromEpochMillis(0)`), calls
3356/// whose receiver and arguments are all constant (`Clock.now()` included: it
3357/// reads the runner's clock, not a Worker's), and `let`s bound to constants.
3358/// Anything reached from an address's result (a `<-` binding, a pattern or
3359/// lambda binding, a field of one, a call on one, or such a value shifted by
3360/// a `Duration`) is *run-derived*. A comparison with an `Instant`-typed
3361/// constant side warns; `expect o.expires > o.created` doesn't.
3362///
3363/// Every `expect` in the case is scanned: top-level, in `if` and `match`
3364/// arms, in nested blocks and in the tail (where a `let … else` puts the
3365/// rest of the case). `let` constness is tracked by name through the case in
3366/// source order. #2181: a `match` arm's pattern, a lambda parameter and an
3367/// `is` test's bindings rebind a name to a run-derived value, so each clears
3368/// it from the constants for its scope (an `is` binding for the whole
3369/// predicate or `if` it sits in, which errs towards not warning). Reported
3370/// once per case, at the first such `expect`.
3371pub fn remote_clock_dependent(
3372    case: &Case,
3373    expr_types: &HashMap<ExprId, checker::TypedExpr>,
3374    tys: &Types,
3375) -> Option<CompileError> {
3376    struct Scan<'a> {
3377        expr_types: &'a HashMap<ExprId, checker::TypedExpr>,
3378        tys: &'a Types,
3379        /// The `let` names bound to a constant.
3380        constants: HashSet<String>,
3381        found: Option<Span>,
3382    }
3383    impl Scan<'_> {
3384        fn is_instant(&self, e: &Expr) -> bool {
3385            self.expr_types.get(&e.id).is_some_and(|t| {
3386                matches!(&*self.tys.get(t.ty), checker::Ty::Base(BaseType::Instant))
3387            })
3388        }
3389        fn constant(&self, e: &Expr) -> bool {
3390            match &e.kind {
3391                // A type or static receiver (`Instant`, `Clock`) is constant;
3392                // a lowercase name is constant only if a `let` bound it to one.
3393                ExprKind::Ident(id) => {
3394                    self.constants.contains(&id.name)
3395                        || id.name.starts_with(|c: char| c.is_ascii_uppercase())
3396                }
3397                _ => expr_children(e).into_iter().all(|c| self.constant(c)),
3398            }
3399        }
3400        /// Run `f` with `names` cleared from the constants, then restore them.
3401        fn without(&mut self, names: Vec<String>, f: impl FnOnce(&mut Self)) {
3402            let saved = self.constants.clone();
3403            for n in &names {
3404                self.constants.remove(n);
3405            }
3406            f(self);
3407            self.constants = saved;
3408        }
3409        /// An `expect`'s predicate: any comparison with a constant `Instant`.
3410        /// The binders inside it (an `is` pattern, a lambda parameter, a
3411        /// `match` arm) rebind their names for the whole predicate.
3412        fn check(&mut self, pred: &Expr, span: Span) {
3413            if self.found.is_some() {
3414                return;
3415            }
3416            let mut binders = Vec::new();
3417            walk_expr_tree(pred, &mut |e: &Expr| binder_names(e, &mut binders));
3418            let saved = self.constants.clone();
3419            for n in &binders {
3420                self.constants.remove(n);
3421            }
3422            let mut hit = false;
3423            walk_expr_tree(pred, &mut |e: &Expr| {
3424                if let ExprKind::BinOp(
3425                    BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq,
3426                    a,
3427                    b,
3428                ) = &e.kind
3429                    && [a, b]
3430                        .into_iter()
3431                        .any(|side| self.is_instant(side) && self.constant(side))
3432                {
3433                    hit = true;
3434                }
3435            });
3436            self.constants = saved;
3437            if hit {
3438                self.found = Some(span);
3439            }
3440        }
3441        fn block(&mut self, b: &Block) {
3442            for stmt in &b.statements {
3443                match stmt {
3444                    Statement::Let(l) => {
3445                        if self.constant(&l.value) {
3446                            self.constants.insert(l.name.name.clone());
3447                        } else {
3448                            self.constants.remove(&l.name.name);
3449                        }
3450                    }
3451                    Statement::EffectLet(l) => {
3452                        self.constants.remove(&l.name.name);
3453                    }
3454                    Statement::Expect(x) => self.check(&x.value, x.span),
3455                    _ => {}
3456                }
3457                let mut exprs = Vec::new();
3458                statement_exprs(stmt, &mut exprs);
3459                for e in exprs {
3460                    self.expr(e);
3461                }
3462            }
3463            self.expr(&b.tail);
3464        }
3465        /// Find the blocks (and `expect` expressions) nested in `e`.
3466        fn expr(&mut self, e: &Expr) {
3467            match &e.kind {
3468                ExprKind::Block(b) => self.block(b),
3469                ExprKind::If {
3470                    cond,
3471                    then_block,
3472                    else_block,
3473                } => {
3474                    self.expr(cond);
3475                    let mut names = Vec::new();
3476                    walk_expr_tree(cond, &mut |e: &Expr| binder_names(e, &mut names));
3477                    self.without(names, |scan| {
3478                        scan.block(then_block);
3479                        scan.block(else_block);
3480                    });
3481                }
3482                ExprKind::Match { discriminant, arms } => {
3483                    self.expr(discriminant);
3484                    for arm in arms {
3485                        let names = arm
3486                            .pattern
3487                            .bound_names()
3488                            .into_iter()
3489                            .map(|id| id.name.clone())
3490                            .collect();
3491                        self.without(names, |scan| {
3492                            if let Some(guard) = &arm.guard {
3493                                scan.expr(guard);
3494                            }
3495                            match &arm.body {
3496                                MatchBody::Expr(body) => scan.expr(body),
3497                                MatchBody::Block(b) => scan.block(b),
3498                            }
3499                        });
3500                    }
3501                }
3502                ExprKind::Lambda(l) => {
3503                    let names = l.params.iter().map(|p| p.name.name.clone()).collect();
3504                    self.without(names, |scan| scan.expr(&l.body));
3505                }
3506                ExprKind::Expect(inner) => {
3507                    self.check(inner, e.span);
3508                    self.expr(inner);
3509                }
3510                _ => {
3511                    for c in expr_children(e) {
3512                        self.expr(c);
3513                    }
3514                }
3515            }
3516        }
3517    }
3518    let mut scan = Scan {
3519        expr_types,
3520        tys,
3521        constants: HashSet::new(),
3522        found: None,
3523    };
3524    scan.block(&case.body);
3525    let span = scan.found?;
3526    Some(
3527        CompileError::new(
3528            "bynk.test.remote_clock_dependent",
3529            span,
3530            format!(
3531                "case `\"{}\"` compares an `Instant` that isn't derived from the run, which can pass in process and fail against a real runtime",
3532                case.name
3533            ),
3534        )
3535        .with_note(
3536            "in process the clock starts at the epoch; a real runtime's Workers read wall-clock time. Assert a relation between instants the run produced (`expires > created`) instead of an absolute instant",
3537        ),
3538    )
3539}
3540
3541/// #2181: the names `e` itself binds for a scope under it: an `is` test's
3542/// pattern, a lambda's parameters, a `match`'s arm patterns.
3543fn binder_names(e: &Expr, out: &mut Vec<String>) {
3544    match &e.kind {
3545        ExprKind::Is { pattern, .. } => {
3546            out.extend(pattern.bound_names().into_iter().map(|id| id.name.clone()));
3547        }
3548        ExprKind::Lambda(l) => out.extend(l.params.iter().map(|p| p.name.name.clone())),
3549        ExprKind::Match { arms, .. } => {
3550            for arm in arms {
3551                out.extend(
3552                    arm.pattern
3553                        .bound_names()
3554                        .into_iter()
3555                        .map(|id| id.name.clone()),
3556                );
3557            }
3558        }
3559        _ => {}
3560    }
3561}
3562
3563/// Visit `e` and every expression under it — the deep walk over
3564/// [`expr_children`]. (`bynk_model::walk_exprs` is the same walk, but `bynk-model`
3565/// depends on this crate, so it can't be reused here.)
3566fn walk_expr_tree(e: &Expr, f: &mut dyn FnMut(&Expr)) {
3567    f(e);
3568    for c in expr_children(e) {
3569        walk_expr_tree(c, f);
3570    }
3571}
3572
3573/// #2138: whether `block` (or a block nested in it) holds an `advance`.
3574fn block_has_advance(block: &Block) -> bool {
3575    fn walk(e: &Expr) -> bool {
3576        match &e.kind {
3577            ExprKind::Block(b) => block_has_advance(b),
3578            ExprKind::If {
3579                cond,
3580                then_block,
3581                else_block,
3582            } => walk(cond) || block_has_advance(then_block) || block_has_advance(else_block),
3583            ExprKind::Match { discriminant, arms } => {
3584                walk(discriminant)
3585                    || arms.iter().any(|a| {
3586                        a.guard.as_ref().is_some_and(walk)
3587                            || match &a.body {
3588                                MatchBody::Block(b) => block_has_advance(b),
3589                                MatchBody::Expr(x) => walk(x),
3590                            }
3591                    })
3592            }
3593            _ => expr_children(e).into_iter().any(walk),
3594        }
3595    }
3596    if block
3597        .statements
3598        .iter()
3599        .any(|s| matches!(s, Statement::Advance(_)))
3600    {
3601        return true;
3602    }
3603    let mut exprs = Vec::new();
3604    for s in &block.statements {
3605        statement_exprs(s, &mut exprs);
3606    }
3607    exprs.push(&block.tail);
3608    exprs.into_iter().any(walk)
3609}
3610
3611/// #3052: at `system` the driver mints an `Oidc` actor's token, so the claims
3612/// a call presents (`by Workload("wid", TokenClaims.of([…]))`) are written into
3613/// it from their `"name: value"` lines. A `TokenClaims` is opaque (a view with
3614/// `get`/`has`, never its lines), so only the literal `TokenClaims.of(…)` form
3615/// can be minted from; any other claims expression is refused rather than
3616/// sent as an empty set (`bynk.test.system_claims_need_literal`).
3617fn check_system_claims_literal(case: &Case, errors: &mut Vec<CompileError>) {
3618    for b in blocks_deep(&case.body) {
3619        for st in flat_statements(b) {
3620            let Statement::EffectLet(l) = st else {
3621                continue;
3622            };
3623            let Some(claims) = l.principal.as_ref().and_then(|p| p.claims.as_deref()) else {
3624                continue;
3625            };
3626            let literal = matches!(
3627                &claims.kind,
3628                ExprKind::MethodCall { receiver, method, args, .. }
3629                    if method.name == "of"
3630                        && args.len() == 1
3631                        && matches!(&receiver.kind, ExprKind::Ident(id) if id.name == "TokenClaims")
3632            );
3633            if !literal {
3634                errors.push(
3635                    CompileError::new(
3636                        "bynk.test.system_claims_need_literal",
3637                        claims.span,
3638                        "a `system`-tier case mints the token's claims from the lines of a `TokenClaims.of([…])` written in the principal",
3639                    )
3640                    .with_note(
3641                        "write `by Actor(\"id\", TokenClaims.of([\"name: value\"]))` here, or move the case to a suite `as integration`, where the handler reads the claims value as given",
3642                    ),
3643                );
3644            }
3645        }
3646    }
3647}
3648
3649/// #1706: report a `system`-tier case that claims a fault — see
3650/// [`block_uses_faults`].
3651///
3652/// #1812: a fault claim driven `by Nobody` is reported too, at any tier.
3653/// `by Nobody` exercises the auth seam that exists only at `system`, where
3654/// the claim cannot hold, so it falls under the same code rather than
3655/// `bynk.test.credential_needs_system`, whose advice (promote the case to
3656/// `system`) would only lead here.
3657fn check_faults_tier(
3658    case: &Case,
3659    tier: bynk_syntax::ast::TestTier,
3660    errors: &mut Vec<CompileError>,
3661) {
3662    if tier != bynk_syntax::ast::TestTier::System {
3663        for p in faults_claims(&case.body)
3664            .into_iter()
3665            .filter_map(|f| f.principal.as_ref())
3666            .filter(|p| CallSitePrincipal::of(&p.actor.name).is_reserved())
3667        {
3668            // #2135: `by Forged` / `by Stale` likewise drive only the
3669            // `system`-tier seam.
3670            let name = &p.actor.name;
3671            let what = if CallSitePrincipal::of(name) == CallSitePrincipal::Nobody {
3672                "the missing credential"
3673            } else {
3674                "the bad credential"
3675            };
3676            errors.push(
3677                CompileError::new(
3678                    "bynk.test.faults_needs_in_process",
3679                    p.span,
3680                    format!("a fault claim cannot be driven `by {name}`: {what} is rejected only by the `system`-tier auth seam, where a fault is never a throw"),
3681                )
3682                .with_note(format!(
3683                    "assert the rejection instead, in a `system` case: `let r <- <call> by {name}` then `expect r is Rejected(Unauthorized)`"
3684                )),
3685            );
3686        }
3687        return;
3688    }
3689    if block_uses_faults(&case.body) {
3690        errors.push(
3691            CompileError::new(
3692                "bynk.test.faults_needs_in_process",
3693                case.name_span,
3694                format!(
3695                    "case `\"{}\"` claims a fault with `faults`, but is a `system`-tier case",
3696                    case.name
3697                ),
3698            )
3699            .with_note(
3700                "at `system` a handler's fault reaches the case as an error response from the deployed Worker, not a throw; claim the fault at `unit` or `integration`, or assert the response at `system`",
3701            ),
3702        );
3703    }
3704}
3705
3706/// Slice C, #2905: `bynk.test.wire_needs_system` — a case below `system` that
3707/// uses `Wire(…)`. Shared by the unit and integration paths: the unit path
3708/// once skipped it, so an http `Wire` in a unit suite reached `tsc`.
3709fn check_wire_tier(case: &Case, tier: bynk_syntax::ast::TestTier, errors: &mut Vec<CompileError>) {
3710    if tier == bynk_syntax::ast::TestTier::System || !block_uses_wire(&case.body) {
3711        return;
3712    }
3713    errors.push(CompileError::new(
3714        "bynk.test.wire_needs_system",
3715        case.name_span,
3716        format!(
3717            "case `\"{}\"` uses `Wire(...)` but is not a `system`-tier case",
3718            case.name
3719        ),
3720    ).with_note(
3721        "`Wire` hands raw, pre-validation input to the real boundary; promote the case with `as system`, or pass a typed argument",
3722    ));
3723}
3724
3725/// #706: whether a `case` body drives an effect-let `by Nobody` — the "no
3726/// credential" principal. It is only meaningful at `system` (there is no auth
3727/// seam to reject a missing credential at `unit`), so a non-`system` case using
3728/// it is `bynk.test.credential_needs_system`. Every block of the body counts,
3729/// not just its top level (#1849): a `by Nobody` inside an `if` or a match arm
3730/// is the same credential-less call.
3731fn block_uses_nobody(block: &Block) -> bool {
3732    blocks_deep(block).into_iter().any(|b| {
3733        flat_statements(b).into_iter().any(|s| {
3734            matches!(s, Statement::EffectLet(l)
3735                if l.principal.as_ref().is_some_and(|p| CallSitePrincipal::of(&p.actor.name) == CallSitePrincipal::Nobody))
3736        })
3737    })
3738}
3739
3740/// #2135: `bynk.test.forged_needs_system` — a case below `system` that drives
3741/// `by Forged`, `by Stale` or `by Expired`. Only the `system` driver signs a
3742/// request, so only there does the real `Signature` or `Bearer` seam see the
3743/// bad credential; in
3744/// process the seam is skipped and the handler would just run. Every block of
3745/// the body counts, as for `by Nobody` (#1849).
3746fn check_bad_signature_tier(
3747    case: &Case,
3748    tier: bynk_syntax::ast::TestTier,
3749    errors: &mut Vec<CompileError>,
3750) {
3751    if tier == bynk_syntax::ast::TestTier::System {
3752        return;
3753    }
3754    let mut names: Vec<&str> = blocks_deep(&case.body)
3755        .into_iter()
3756        .flat_map(flat_statements)
3757        .filter_map(|s| match s {
3758            Statement::EffectLet(l) => {
3759                l.principal
3760                    .as_ref()
3761                    .map(|p| p.actor.name.as_str())
3762                    .filter(|n| {
3763                        matches!(
3764                            CallSitePrincipal::of(n),
3765                            CallSitePrincipal::BadCredential(_)
3766                        )
3767                    })
3768            }
3769            _ => None,
3770        })
3771        .collect();
3772    names.sort_unstable();
3773    names.dedup();
3774    for name in names {
3775        errors.push(
3776            CompileError::new(
3777                "bynk.test.forged_needs_system",
3778                case.name_span,
3779                format!(
3780                    "case `\"{}\"` drives `by {name}` but is a `{}`-tier case",
3781                    case.name,
3782                    tier.as_str()
3783                ),
3784            )
3785            .with_note(format!(
3786                "`by {name}` sends a bad credential to the real `Signature` or `Bearer` seam, which only the `system` driver reaches; in process the seam is skipped. Move the case into a `suite … as system`"
3787            )),
3788        );
3789    }
3790}
3791
3792/// Register a synthetic call-record type per capability operation of the target
3793/// context (v0.117, testing track slice 5), so `trace(Cap.op)` — typed
3794/// `List[<CallRecord>]` — supports field access on its records. The record's
3795/// fields are the operation's parameters.
3796pub fn register_call_record_types(
3797    resolved: &mut ResolvedCommons,
3798    target_name: &str,
3799    unit_tables: &HashMap<String, UnitTable>,
3800) {
3801    let Some(table) = unit_tables.get(target_name) else {
3802        return;
3803    };
3804    // #291: a consumed adapter's capabilities are seams too (its `trace` and
3805    // `with` records); the target's own wins a name clash.
3806    let mut caps: Vec<(&String, &CapabilityDecl)> = table.capabilities.iter().collect();
3807    for (n, d) in flattened_platform_capabilities(unit_tables, resolved) {
3808        if !table.capabilities.contains_key(n) {
3809            caps.push((n, d));
3810        }
3811    }
3812    // #3892: a consumed context's services, whose `with`/`trace` records read
3813    // the `on call` parameters.
3814    let service_seams = consumed_service_seam_decls(
3815        unit_tables,
3816        &resolved.cross_context.consumed_contexts,
3817        &resolved.cross_context.aliases,
3818    );
3819    for (n, d) in &service_seams {
3820        if !table.capabilities.contains_key(n) {
3821            caps.push((n, d));
3822        }
3823    }
3824    for (cap_name, decl) in caps {
3825        for op in &decl.ops {
3826            let fields: Vec<RecordField> = op
3827                .params
3828                .iter()
3829                .map(|p| RecordField {
3830                    annotations: Vec::new(),
3831                    documentation: None,
3832                    trivia: Default::default(),
3833                    name: p.name.clone(),
3834                    type_ref: p.type_ref.clone(),
3835                    refinement: None,
3836                    init: None,
3837                    span: p.span,
3838                })
3839                .collect();
3840            let name = checker::call_record_type_name(cap_name, &op.name.name);
3841            resolved.types.insert(
3842                name.clone(),
3843                Arc::new(TypeDecl {
3844                    derives: Vec::new(),
3845                    derives_kw: None,
3846                    type_params: Vec::new(),
3847                    name: Ident {
3848                        name,
3849                        span: op.name.span,
3850                    },
3851                    body: TypeBody::Record(RecordBody {
3852                        trailing_comments: Default::default(),
3853                        fields,
3854                        span: op.name.span,
3855                    }),
3856                    documentation: None,
3857                    span: op.name.span,
3858                    trivia: Trivia::default(),
3859                    private: None,
3860                }),
3861            );
3862        }
3863    }
3864}
3865
3866fn target_test_actors(table: Option<&UnitTable>) -> HashMap<String, bynk_syntax::ast::ActorDecl> {
3867    table.map(|t| t.actors.clone()).unwrap_or_default()
3868}
3869
3870/// #2052 review: the context that publishes `event` to `target`'s
3871/// subscribers, resolved as the target's `from Events(E)` header resolves
3872/// `E`: the target's own declaration, else the one context among those it
3873/// consumes (`consumed`) that declares it. `Err` lists the candidates when
3874/// there is no unique one (none, or several). A same-named event in a context
3875/// the target does not consume is never a candidate.
3876pub fn event_publisher(
3877    target: &str,
3878    event: &str,
3879    unit_tables: &HashMap<String, UnitTable>,
3880    consumed: &[String],
3881) -> Result<String, Vec<String>> {
3882    if unit_tables
3883        .get(target)
3884        .is_some_and(|t| t.events.contains_key(event))
3885    {
3886        return Ok(target.to_string());
3887    }
3888    let mut owners: Vec<String> = consumed
3889        .iter()
3890        .filter(|c| c.as_str() != target)
3891        .filter(|c| {
3892            unit_tables
3893                .get(*c)
3894                .is_some_and(|t| t.events.contains_key(event))
3895        })
3896        .cloned()
3897        .collect();
3898    owners.sort();
3899    owners.dedup();
3900    match owners.as_slice() {
3901        [one] => Ok(one.clone()),
3902        _ => Err(owners),
3903    }
3904}
3905
3906fn target_test_services(
3907    target: Option<&str>,
3908    unit_tables: &HashMap<String, UnitTable>,
3909    consumed: &[String],
3910) -> HashMap<String, checker::TestServiceSig> {
3911    use bynk_syntax::ast::ServiceProtocol;
3912    let Some((target, t)) = target.and_then(|n| unit_tables.get(n).map(|t| (n, t))) else {
3913        return HashMap::new();
3914    };
3915    // #2052: the events in the target's scope, its own and its consumed
3916    // contexts', for an events service's `bynk.test.event_not_subscribed`.
3917    let scope_events: std::collections::BTreeSet<String> = std::iter::once(target)
3918        .chain(consumed.iter().map(String::as_str))
3919        .filter_map(|u| unit_tables.get(u))
3920        .flat_map(|u| u.events.keys().cloned())
3921        .collect();
3922    t.services
3923        .iter()
3924        .map(|(name, decl)| {
3925            let protocol = match &decl.protocol {
3926                ServiceProtocol::Call => None,
3927                ServiceProtocol::Http => Some("http".to_string()),
3928                ServiceProtocol::Cron => Some("cron".to_string()),
3929                ServiceProtocol::Queue { .. } => Some("queue".to_string()),
3930                ServiceProtocol::WebSocket { .. } => Some("websocket".to_string()),
3931                ServiceProtocol::Events { .. } => Some("events".to_string()),
3932                ServiceProtocol::Email { .. } => Some("email".to_string()),
3933            };
3934            let handlers = decl
3935                .handlers
3936                .iter()
3937                .map(|h| checker::TestHandler {
3938                    kind: h.kind.clone(),
3939                    params: h.params.clone(),
3940                    by_clause: h.by_clause.clone(),
3941                    return_type: h.return_type.clone(),
3942                    span: h.span,
3943                })
3944                .collect();
3945            let (known_events, event_publisher) = match &decl.protocol {
3946                ServiceProtocol::Events {
3947                    event_type: TypeRef::Named(e),
3948                    ..
3949                } => (
3950                    scope_events.clone(),
3951                    Some(event_publisher(target, &e.name, unit_tables, consumed)),
3952                ),
3953                _ => (Default::default(), None),
3954            };
3955            let ws_frames = match &decl.protocol {
3956                ServiceProtocol::WebSocket {
3957                    in_type, out_type, ..
3958                } => Some((in_type.clone(), out_type.clone())),
3959                _ => None,
3960            };
3961            (
3962                name.clone(),
3963                checker::TestServiceSig {
3964                    protocol,
3965                    handlers,
3966                    known_events,
3967                    event_publisher,
3968                    ws_frames,
3969                },
3970            )
3971        })
3972        .collect()
3973}
3974
3975/// #291: the platform capabilities the target flattens in from a consumed
3976/// adapter (`consumes bynk { Logger }`) — seams of the unit under test, like
3977/// the capabilities it declares — with their declarations, sorted by name.
3978fn flattened_platform_capabilities<'a>(
3979    unit_tables: &'a HashMap<String, UnitTable>,
3980    resolved: &ResolvedCommons,
3981) -> Vec<(&'a String, &'a CapabilityDecl)> {
3982    let mut out: Vec<_> = resolved
3983        .cross_context
3984        .flattened_caps
3985        .iter()
3986        .filter_map(|(cap, owner)| {
3987            let t = unit_tables.get(owner)?;
3988            if t.kind != Some(UnitKind::Adapter) {
3989                return None;
3990            }
3991            t.capabilities.get_key_value(cap)
3992        })
3993        .collect();
3994    out.sort_by_key(|(cap, _)| cap.as_str());
3995    out
3996}
3997
3998/// #291: a platform capability the target flattens in from a consumed
3999/// **adapter** (`bynk`'s `Logger`, by `consumes bynk { Logger }`) is a seam of
4000/// the unit under test too, so a test body may observe it (`expect Logger.info
4001/// called once`), as it may already `stub` it. A capability the target declares
4002/// itself wins on a name clash.
4003fn add_consumed_adapter_capabilities(
4004    map: &mut HashMap<String, checker::CapabilityInfo>,
4005    unit_tables: &HashMap<String, UnitTable>,
4006    resolved: &ResolvedCommons,
4007    tys: &Arc<Types>,
4008) {
4009    for (name, decl) in flattened_platform_capabilities(unit_tables, resolved) {
4010        if map.contains_key(name) {
4011            continue;
4012        }
4013        let ops = decl
4014            .ops
4015            .iter()
4016            .map(|op| build_capability_op_info(op, &resolved.types, tys))
4017            .collect();
4018        map.insert(
4019            name.clone(),
4020            checker::CapabilityInfo {
4021                name: name.clone(),
4022                ops,
4023                derived_from: None,
4024            },
4025        );
4026    }
4027}
4028
4029/// #3892: a consumed context's services as seams, one synthetic capability per
4030/// context named by what the target calls it (its alias, else its last path
4031/// segment, the key its surface double sits under in the test `deps`), with one
4032/// operation per service: the parameters and return type of its `on call`
4033/// handler. Observation (`expect Pay.authorise called …`), `with` and `trace`
4034/// read them as they read a capability's.
4035pub fn consumed_service_seam_decls(
4036    unit_tables: &HashMap<String, UnitTable>,
4037    consumed: &[String],
4038    aliases: &HashMap<String, String>,
4039) -> std::collections::BTreeMap<String, CapabilityDecl> {
4040    let mut out = std::collections::BTreeMap::new();
4041    for ctx in consumed {
4042        let Some(table) = unit_tables.get(ctx) else {
4043            continue;
4044        };
4045        if table.kind == Some(UnitKind::Adapter) || table.services.is_empty() {
4046            continue;
4047        }
4048        let mut names: Vec<String> = aliases
4049            .iter()
4050            .filter(|(_, q)| *q == ctx)
4051            .map(|(alias, _)| alias.clone())
4052            .collect();
4053        if names.is_empty() {
4054            names.push(ctx.rsplit('.').next().unwrap_or(ctx).to_string());
4055        }
4056        let mut ops: Vec<CapabilityOp> = table
4057            .services
4058            .values()
4059            .filter_map(|svc| {
4060                let h = svc.handlers.iter().find(|h| h.kind == HandlerKind::Call)?;
4061                Some(CapabilityOp {
4062                    name: svc.name.clone(),
4063                    type_params: Vec::new(),
4064                    params: h.params.clone(),
4065                    return_type: h.return_type.clone(),
4066                    annotations: Vec::new(),
4067                    documentation: None,
4068                    span: h.span,
4069                    trivia: Default::default(),
4070                })
4071            })
4072            .collect();
4073        ops.sort_by(|a, b| a.name.name.cmp(&b.name.name));
4074        for name in names {
4075            out.entry(name.clone()).or_insert_with(|| CapabilityDecl {
4076                name: Ident {
4077                    name: name.clone(),
4078                    span: Span::default(),
4079                },
4080                ops: ops.clone(),
4081                derived: None,
4082                documentation: None,
4083                span: Span::default(),
4084                trailing_comments: Vec::new(),
4085                trivia: Default::default(),
4086            });
4087        }
4088    }
4089    out
4090}
4091
4092/// #3892: the seams of [`consumed_service_seam_decls`] as the observation
4093/// checker reads capabilities.
4094fn add_consumed_service_seams(
4095    map: &mut HashMap<String, checker::CapabilityInfo>,
4096    resolved: &ResolvedCommons,
4097    unit_tables: &HashMap<String, UnitTable>,
4098    tys: &Arc<Types>,
4099) {
4100    let cross = &resolved.cross_context;
4101    for (name, decl) in
4102        consumed_service_seam_decls(unit_tables, &cross.consumed_contexts, &cross.aliases)
4103    {
4104        let ops = decl
4105            .ops
4106            .iter()
4107            .map(|op| build_capability_op_info(op, &resolved.types, tys))
4108            .collect();
4109        map.entry(name.clone())
4110            .or_insert_with(|| checker::CapabilityInfo {
4111                name,
4112                ops,
4113                derived_from: None,
4114            });
4115    }
4116}
4117
4118/// Type-check a test `case`/`property` body against the target unit's privileges,
4119/// returning the inferred `expr_types` map and the `Callee` classification
4120/// recorded alongside it. The **check** path feeds real diagnostic/ref sinks;
4121/// the **emit** path reuses it with throwaway sinks to give the case-body
4122/// lowering full type information (so collection kernels — notably
4123/// `trace(Cap.op)`'s `List[…]` methods — dispatch on the receiver's checked
4124/// type) *and* full `Callee` information (P6.21 review: the emit path's own
4125/// `callees` accumulator was previously built here and silently discarded —
4126/// `bynk-emit`'s `synthetic_typed_commons_for_target` never received it, so
4127/// `Callee::Intrinsic`/`Store`/etc. were never recorded for anything inside a
4128/// `.test.bynk` body, even though this function computed them correctly all
4129/// along).
4130#[allow(clippy::too_many_arguments)]
4131pub fn typecheck_case_body(
4132    target_name: &str,
4133    body: &Block,
4134    unit_span: Span,
4135    unit_tables: &HashMap<String, UnitTable>,
4136    resolved: &ResolvedCommons,
4137    errors: &mut Vec<CompileError>,
4138    refs: &mut RefSink,
4139    // v0.119: bindings already in scope for the body — empty for a `case`, the
4140    // `run: List[Step]` binding for a history property.
4141    initial_scope: HashMap<String, checker::TyId>,
4142    tys: &Arc<Types>,
4143) -> (
4144    HashMap<ExprId, checker::TypedExpr>,
4145    HashMap<ExprId, checker::Callee>,
4146) {
4147    // The emitter has no use for the body's locals — a throwaway sink.
4148    typecheck_case_body_recording(
4149        target_name,
4150        body,
4151        unit_span,
4152        unit_tables,
4153        resolved,
4154        errors,
4155        refs,
4156        &mut LocalsSink::new(),
4157        initial_scope,
4158        tys,
4159    )
4160}
4161
4162/// [`typecheck_case_body`], recording the body's local bindings into `locals`
4163/// (#2517) so the language server can offer inline values inside a test.
4164#[allow(clippy::too_many_arguments)]
4165fn typecheck_case_body_recording(
4166    target_name: &str,
4167    body: &Block,
4168    unit_span: Span,
4169    unit_tables: &HashMap<String, UnitTable>,
4170    resolved: &ResolvedCommons,
4171    errors: &mut Vec<CompileError>,
4172    refs: &mut RefSink,
4173    locals: &mut LocalsSink,
4174    initial_scope: HashMap<String, checker::TyId>,
4175    tys: &Arc<Types>,
4176) -> (
4177    HashMap<ExprId, checker::TypedExpr>,
4178    HashMap<ExprId, checker::Callee>,
4179) {
4180    let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
4181    let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
4182    // Synthesise an Effect[Result[(), ValidationError]] return type as a
4183    // stand-in for Effect[Result[(), ExpectationError]]. v0.7 doesn't model an
4184    // explicit ExpectationError type — the runtime catches it instead.
4185    let synthetic_return = TypeRef::Effect(
4186        Box::new(TypeRef::Result(
4187            Box::new(TypeRef::Unit(unit_span)),
4188            Box::new(TypeRef::ValidationError(unit_span)),
4189            unit_span,
4190        )),
4191        unit_span,
4192    );
4193
4194    // Capabilities of the target context, if any (so the test body can
4195    // call capabilities directly when targeting a context).
4196    let mut capability_info_map: HashMap<String, checker::CapabilityInfo> = HashMap::new();
4197    if let Some(table) = unit_tables.get(target_name) {
4198        for (name, decl) in &table.capabilities {
4199            let ops = decl
4200                .ops
4201                .iter()
4202                .map(|op| build_capability_op_info(op, &resolved.types, tys))
4203                .collect();
4204            capability_info_map.insert(
4205                name.clone(),
4206                checker::CapabilityInfo {
4207                    name: name.clone(),
4208                    ops,
4209                    derived_from: crate::context_checks::derived_from(
4210                        decl,
4211                        &resolved.cross_context.flattened_caps,
4212                    ),
4213                },
4214            );
4215        }
4216    }
4217    add_consumed_adapter_capabilities(&mut capability_info_map, unit_tables, resolved, tys);
4218    add_consumed_service_seams(&mut capability_info_map, resolved, unit_tables, tys);
4219
4220    // All declared capabilities are implicitly "given" inside a test body;
4221    // the test runner wires them via the mocked deps. We feed the same map
4222    // to both `capabilities` (in-scope) and `declared_capabilities`.
4223    let given_declared: Vec<String> = capability_info_map.keys().cloned().collect();
4224
4225    let return_ty = checker::resolve_type_ref(&synthetic_return, &resolved.types, tys).unwrap();
4226    let return_ty_span = unit_span;
4227    // Test bodies record no hints (out of v0.27 scope) — a throwaway sink.
4228    let mut no_hints = HintSink::new();
4229    // Test bodies record no capability requirements either — muted sink.
4230    let mut no_requirements = RequirementSink::new();
4231    let _ = checker::check_body(
4232        resolved,
4233        body,
4234        return_ty,
4235        return_ty_span,
4236        initial_scope,
4237        checker::CapabilityCtx {
4238            capabilities: capability_info_map.clone(),
4239            declared_capabilities: capability_info_map,
4240            given_remaining: given_declared.iter().cloned().collect(),
4241            given_used: HashSet::new(),
4242            given_entries: Vec::new(),
4243            given_anchor: None,
4244            ..Default::default()
4245        },
4246        target_test_services(
4247            Some(target_name),
4248            unit_tables,
4249            &resolved.cross_context.consumed_contexts,
4250        ),
4251        target_test_actors(unit_tables.get(target_name)),
4252        None,
4253        checker::CheckSinks {
4254            tys,
4255            expr_types: &mut expr_types,
4256            errors,
4257            refs,
4258            hints: &mut no_hints,
4259            locals,
4260            requirements: &mut no_requirements,
4261            callees: &mut callees,
4262        },
4263    );
4264    #[cfg(test)]
4265    crate::testkit::note_callees(target_name, callees.iter());
4266    (expr_types, callees)
4267}
4268
4269/// #3108: prepare the literal D1 statements a test body recorded against the
4270/// schema of the target's migrations, as a production body's are.
4271fn check_d1_sql_sites(
4272    d1_sql: Option<&crate::d1_sql::D1Sql>,
4273    target_name: &str,
4274    unit_tables: &HashMap<String, UnitTable>,
4275    callees: &HashMap<ExprId, checker::Callee>,
4276    // The suite file's source, so an error can point inside the SQL literal.
4277    source: &str,
4278    errors: &mut Vec<CompileError>,
4279) {
4280    if let (Some(d1_sql), Some(table)) = (d1_sql, unit_tables.get(target_name)) {
4281        errors.extend(d1_sql.check_unit(target_name, table, callees, Some(source)));
4282    }
4283}
4284
4285#[allow(clippy::too_many_arguments)]
4286fn check_test_case_body(
4287    target_name: &str,
4288    target_kind: UnitKind,
4289    suite_fns: SuiteItems<'_>,
4290    case: &Case,
4291    unit_tables: &HashMap<String, UnitTable>,
4292    unit_uses: &HashMap<String, Vec<String>>,
4293    unit_consumes: &HashMap<String, Vec<String>>,
4294    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
4295    errors: &mut Vec<CompileError>,
4296    refs: &mut RefSink,
4297    locals: &mut LocalsSink,
4298    tys: &Arc<Types>,
4299) -> HashMap<ExprId, checker::Callee> {
4300    let Some((mut resolved, _)) = build_privileged_resolved(
4301        target_name,
4302        unit_tables,
4303        unit_uses,
4304        unit_consumes,
4305        unit_consumes_aliases,
4306    ) else {
4307        return HashMap::new();
4308    };
4309    register_call_record_types(&mut resolved, target_name, unit_tables);
4310    add_suite_fns(&mut resolved, suite_fns);
4311    let _ = target_kind;
4312    let (_, case_callees) = typecheck_case_body_recording(
4313        target_name,
4314        &case.body,
4315        case.span,
4316        unit_tables,
4317        &resolved,
4318        errors,
4319        refs,
4320        locals,
4321        HashMap::new(),
4322        tys,
4323    );
4324    // Don't enforce return-type equality; the test runner discards the
4325    // tail expression and recovers success/failure from expectation outcome.
4326    // Don't enforce "every given used" — capabilities are implicitly
4327    // available in a test body.
4328
4329    // v0.115: flag a `case` that merely restates a contract already declared at
4330    // the source (`bynk.contract.restated_by_test`) — an `expect` that is
4331    // α-equivalent to an `ensures` clause over the same bound arguments. The dev
4332    // guard and the runner attack already check it. Conservative: under-flagging
4333    // is acceptable, over-flagging is not.
4334    check_restated_contract(&case.body, &resolved, errors);
4335    case_callees
4336}
4337
4338/// v0.115: within a test body, flag an `expect` that re-states a contract's
4339/// `ensures`. Fires only on the clearest restatement: a binding `let r = f(args)`
4340/// (or `r <- f(args)`) of a contracted free function's result, followed by an
4341/// `expect E` that is α-equivalent to one of `f`'s `ensures` predicates under the
4342/// substitution `result → r`, `params → args`. Syntactic — never semantic — so a
4343/// merely-equivalent (but differently written) test is not flagged.
4344fn check_restated_contract(
4345    body: &Block,
4346    resolved: &ResolvedCommons,
4347    errors: &mut Vec<CompileError>,
4348) {
4349    // Map each locally-bound name to the contracted free function + call args it
4350    // was bound from (`let r = f(a, b)`).
4351    let mut bound: HashMap<String, (&FnDecl, &[Expr])> = HashMap::new();
4352    for stmt in &body.statements {
4353        let (name, value) = match stmt {
4354            Statement::Let(l) | Statement::EffectLet(l) => (&l.name.name, &l.value),
4355            _ => continue,
4356        };
4357        if let ExprKind::Call {
4358            name: callee, args, ..
4359        } = &value.kind
4360            && let Some(f) = resolved.fns.get(&callee.name)
4361            && matches!(&f.name, FnName::Free(_))
4362            && !f.ensures.is_empty()
4363            && f.params.len() == args.len()
4364        {
4365            bound.insert(name.clone(), (f, args.as_slice()));
4366        }
4367    }
4368    if bound.is_empty() {
4369        return;
4370    }
4371    for stmt in &body.statements {
4372        let Statement::Expect(e) = stmt else { continue };
4373        for (result_name, (f, args)) in &bound {
4374            // subst: result → r, each param → its call argument.
4375            let result_ident = Expr {
4376                id: ExprId::SYNTHETIC,
4377                kind: ExprKind::Ident(Ident {
4378                    name: result_name.clone(),
4379                    span: e.span,
4380                }),
4381                span: e.span,
4382            };
4383            let mut subst: HashMap<&str, &Expr> = HashMap::new();
4384            subst.insert("result", &result_ident);
4385            for (p, a) in f.params.iter().zip(args.iter()) {
4386                subst.insert(p.name.name.as_str(), a);
4387            }
4388            for c in &f.ensures {
4389                if expr_alpha_eq_subst(&c.predicate, &e.value, &subst) {
4390                    let FnName::Free(fname) = &f.name else {
4391                        continue;
4392                    };
4393                    errors.push(
4394                        CompileError::new(
4395                            "bynk.contract.restated_by_test",
4396                            e.span,
4397                            format!(
4398                                "this `expect` restates the `ensures {}` contract of `{}`, which is already checked at every call and by the runner",
4399                                c.name.name, fname.name
4400                            ),
4401                        )
4402                        .with_note(
4403                            "a contract is checked everywhere for free — delete the restating test, or keep a `case` only for a specific witnessed value",
4404                        ),
4405                    );
4406                    break;
4407                }
4408            }
4409        }
4410    }
4411}
4412
4413/// Structural (α-)equality of two predicate expressions, ignoring spans, where a
4414/// bare identifier in `pattern` that appears in `subst` must match the
4415/// corresponding substituted expression in `actual` (the rest compares by shape).
4416/// Deliberately conservative — only the operators/leaves a contract predicate can
4417/// contain are compared; anything unrecognised is unequal.
4418fn expr_alpha_eq_subst(pattern: &Expr, actual: &Expr, subst: &HashMap<&str, &Expr>) -> bool {
4419    if let ExprKind::Ident(id) = &pattern.kind
4420        && let Some(replacement) = subst.get(id.name.as_str())
4421    {
4422        return expr_struct_eq(replacement, actual);
4423    }
4424    match (&pattern.kind, &actual.kind) {
4425        (ExprKind::Ident(a), ExprKind::Ident(b)) => a.name == b.name,
4426        (ExprKind::IntLit { value: a, .. }, ExprKind::IntLit { value: b, .. }) => a == b,
4427        (ExprKind::BoolLit(a), ExprKind::BoolLit(b)) => a == b,
4428        (ExprKind::StrLit(a), ExprKind::StrLit(b)) => a == b,
4429        (ExprKind::Paren(a), _) => expr_alpha_eq_subst(a, actual, subst),
4430        (_, ExprKind::Paren(b)) => expr_alpha_eq_subst(pattern, b, subst),
4431        (ExprKind::BinOp(oa, la, ra), ExprKind::BinOp(ob, lb, rb)) => {
4432            oa == ob && expr_alpha_eq_subst(la, lb, subst) && expr_alpha_eq_subst(ra, rb, subst)
4433        }
4434        (ExprKind::UnaryOp(oa, a), ExprKind::UnaryOp(ob, b)) => {
4435            oa == ob && expr_alpha_eq_subst(a, b, subst)
4436        }
4437        (
4438            ExprKind::MethodCall {
4439                receiver: ra,
4440                method: ma,
4441                args: aa,
4442                ..
4443            },
4444            ExprKind::MethodCall {
4445                receiver: rb,
4446                method: mb,
4447                args: ab,
4448                ..
4449            },
4450        ) => {
4451            ma.name == mb.name
4452                && aa.len() == ab.len()
4453                && expr_alpha_eq_subst(ra, rb, subst)
4454                && aa
4455                    .iter()
4456                    .zip(ab.iter())
4457                    .all(|(x, y)| expr_alpha_eq_subst(x, y, subst))
4458        }
4459        _ => false,
4460    }
4461}
4462
4463/// Plain structural equality of two expressions ignoring spans — used to compare
4464/// a substituted argument against its use in the test predicate.
4465fn expr_struct_eq(a: &Expr, b: &Expr) -> bool {
4466    match (&a.kind, &b.kind) {
4467        (ExprKind::Ident(x), ExprKind::Ident(y)) => x.name == y.name,
4468        (ExprKind::IntLit { value: x, .. }, ExprKind::IntLit { value: y, .. }) => x == y,
4469        (ExprKind::BoolLit(x), ExprKind::BoolLit(y)) => x == y,
4470        (ExprKind::StrLit(x), ExprKind::StrLit(y)) => x == y,
4471        (ExprKind::Paren(x), _) => expr_struct_eq(x, b),
4472        (_, ExprKind::Paren(y)) => expr_struct_eq(a, y),
4473        (ExprKind::BinOp(oa, la, ra), ExprKind::BinOp(ob, lb, rb)) => {
4474            oa == ob && expr_struct_eq(la, lb) && expr_struct_eq(ra, rb)
4475        }
4476        (ExprKind::UnaryOp(oa, x), ExprKind::UnaryOp(ob, y)) => oa == ob && expr_struct_eq(x, y),
4477        (
4478            ExprKind::MethodCall {
4479                receiver: ra,
4480                method: ma,
4481                args: aa,
4482                ..
4483            },
4484            ExprKind::MethodCall {
4485                receiver: rb,
4486                method: mb,
4487                args: ab,
4488                ..
4489            },
4490        ) => {
4491            ma.name == mb.name
4492                && aa.len() == ab.len()
4493                && expr_struct_eq(ra, rb)
4494                && aa.iter().zip(ab.iter()).all(|(x, y)| expr_struct_eq(x, y))
4495        }
4496        _ => false,
4497    }
4498}
4499
4500/// v0.114: the recursion cap for property-binding generability (mirrors the
4501/// checker's `MOCK_DEPTH` for bare `Val`).
4502pub const PROP_GEN_DEPTH: u32 = 12;
4503
4504/// Whether a `for all x: T` binding's type is refinement-generable: refined
4505/// types must not carry a `Matches` or `IsoDate` predicate (no
4506/// refinement-driven generator),
4507/// and sums/records must have every component recursively generable within the
4508/// depth cap. Mirrors the checker's `can_mock_bare`.
4509pub fn prop_binding_generable(
4510    ty: checker::TyId,
4511    types: &HashMap<String, Arc<TypeDecl>>,
4512    depth: u32,
4513    tys: &Arc<Types>,
4514) -> bool {
4515    if depth == 0 {
4516        return false;
4517    }
4518    match &*tys.get(ty) {
4519        checker::Ty::Base(_) => true,
4520        checker::Ty::Named { name, .. } => {
4521            let Some(decl) = types.get(name) else {
4522                return false;
4523            };
4524            match &decl.body {
4525                TypeBody::Refined { refinement, .. } | TypeBody::Opaque { refinement, .. } => {
4526                    !refinement_lacks_generator(refinement.as_ref())
4527                }
4528                TypeBody::Sum(s) => s.variants.first().is_some_and(|v| {
4529                    v.payload.iter().all(|f| {
4530                        checker::resolve_type_ref(&f.type_ref, types, tys)
4531                            .is_some_and(|t| prop_binding_generable(t, types, depth - 1, tys))
4532                    })
4533                }),
4534                TypeBody::Record(r) => r.fields.iter().all(|f| {
4535                    // #2668: an inline `where Matches(…)` on a field is as
4536                    // ungenerable as a declared `Matches` type.
4537                    !refinement_lacks_generator(f.refinement.as_ref())
4538                        && checker::resolve_type_ref(&f.type_ref, types, tys)
4539                            .is_some_and(|t| prop_binding_generable(t, types, depth - 1, tys))
4540                }),
4541            }
4542        }
4543        _ => false,
4544    }
4545}
4546
4547/// Whether a (field-inline) refinement has no refinement-driven generator
4548/// (`Matches`, `IsoDate`), the same set `Val[T]` pins (`refinement_needs_pin`).
4549fn refinement_lacks_generator(refinement: Option<&Refinement>) -> bool {
4550    refinement.is_some_and(crate::checker::refinement_needs_pin)
4551}
4552
4553/// The refinement of a resolved refined/opaque named type, if any — used by the
4554/// conservative restates-refinement check.
4555fn named_refinement<'a>(
4556    ty: checker::TyId,
4557    types: &'a HashMap<String, Arc<TypeDecl>>,
4558    tys: &Arc<Types>,
4559) -> Option<&'a Refinement> {
4560    let node = tys.get(ty);
4561    let checker::Ty::Named { name, .. } = &*node else {
4562        return None;
4563    };
4564    match &types.get(name)?.body {
4565        TypeBody::Refined { refinement, .. } | TypeBody::Opaque { refinement, .. } => {
4566            refinement.as_ref()
4567        }
4568        _ => None,
4569    }
4570}
4571
4572/// v0.114 (DECISION P): does `pred` merely restate a refinement `bound_var`
4573/// already guarantees? A **conservative, syntactic** check — it fires only when
4574/// the predicate is exactly the refinement over the bound variable, never
4575/// guessing (under-flagging is acceptable; over-flagging is not). Handles the
4576/// `Positive` (`v > 0` / `v >= 1`) and `NonNegative` (`v >= 0`) numeric cases.
4577fn predicate_restates_refinement(pred: &Expr, bound_var: &str, refinement: &Refinement) -> bool {
4578    let ExprKind::BinOp(op, lhs, rhs) = &pred.kind else {
4579        return false;
4580    };
4581    // `<var> <op> <int-literal>` only.
4582    let ExprKind::Ident(id) = &lhs.kind else {
4583        return false;
4584    };
4585    if id.name != bound_var {
4586        return false;
4587    }
4588    let ExprKind::IntLit { value: n, .. } = &rhs.kind else {
4589        return false;
4590    };
4591    let n = *n;
4592    let positive = refinement
4593        .predicates
4594        .iter()
4595        .any(|p| matches!(p.kind, PredKind::Positive));
4596    let non_negative = refinement
4597        .predicates
4598        .iter()
4599        .any(|p| matches!(p.kind, PredKind::NonNegative));
4600    match op {
4601        // `v > 0` / `v >= 1` restate `Positive`.
4602        BinOp::Gt if n == 0 => positive,
4603        BinOp::GtEq if n == 1 => positive,
4604        // `v >= 0` restates `NonNegative`.
4605        BinOp::GtEq if n == 0 => non_negative,
4606        _ => false,
4607    }
4608}
4609
4610/// v0.119 (DECISION D): which state-projection rewrite maps a history predicate
4611/// back into the space an `invariant` / `transition` is written in.
4612#[derive(Clone, Copy)]
4613enum HistoryRestate {
4614    /// An `invariant` reads bare state fields: `s.new.F` ≡ `F`.
4615    Invariant,
4616    /// A `transition` reads `old` / `new`: `s.old` ≡ `old`, `s.new` ≡ `new`.
4617    Transition,
4618}
4619
4620/// `Some(field)` when `e` is `s.new.<field>` (the reached-state projection an
4621/// invariant-restating history predicate uses).
4622fn as_new_field<'a>(e: &'a Expr, s: &str) -> Option<&'a str> {
4623    let ExprKind::FieldAccess { receiver, field } = &e.kind else {
4624        return None;
4625    };
4626    let ExprKind::FieldAccess {
4627        receiver: inner,
4628        field: which,
4629    } = &receiver.kind
4630    else {
4631        return None;
4632    };
4633    let ExprKind::Ident(id) = &inner.kind else {
4634        return None;
4635    };
4636    (id.name == s && which.name == "new").then_some(field.name.as_str())
4637}
4638
4639/// `Some("old"|"new")` when `e` is `s.old` / `s.new` (the step projections a
4640/// transition-restating history predicate uses).
4641fn as_step_root<'a>(e: &'a Expr, s: &str) -> Option<&'a str> {
4642    let ExprKind::FieldAccess { receiver, field } = &e.kind else {
4643        return None;
4644    };
4645    let ExprKind::Ident(id) = &receiver.kind else {
4646        return None;
4647    };
4648    (id.name == s && (field.name == "old" || field.name == "new")).then_some(field.name.as_str())
4649}
4650
4651/// Conservative, span-insensitive structural match (DECISION D): does the history
4652/// predicate `body` (over the step binding `s`) restate the declared predicate
4653/// `decl`, modulo the `mode` state-projection rewrite? Under-flags by design — any
4654/// construct not modelled here compares unequal, so a valid test is never blocked.
4655fn history_pred_matches(body: &Expr, s: &str, decl: &Expr, mode: HistoryRestate) -> bool {
4656    // Leaf equivalences the rewrite establishes.
4657    match mode {
4658        HistoryRestate::Invariant => {
4659            if let (Some(f), ExprKind::Ident(id)) = (as_new_field(body, s), &decl.kind) {
4660                return f == id.name;
4661            }
4662        }
4663        HistoryRestate::Transition => {
4664            if let (Some(root), ExprKind::Ident(id)) = (as_step_root(body, s), &decl.kind) {
4665                return root == id.name;
4666            }
4667        }
4668    }
4669    match (&body.kind, &decl.kind) {
4670        (ExprKind::Paren(x), _) => history_pred_matches(x, s, decl, mode),
4671        (_, ExprKind::Paren(y)) => history_pred_matches(body, s, y, mode),
4672        (ExprKind::IntLit { value: x, .. }, ExprKind::IntLit { value: y, .. }) => x == y,
4673        (ExprKind::BoolLit(x), ExprKind::BoolLit(y)) => x == y,
4674        (ExprKind::StrLit(x), ExprKind::StrLit(y)) => x == y,
4675        (ExprKind::Ident(x), ExprKind::Ident(y)) => x.name == y.name,
4676        (ExprKind::None, ExprKind::None) => true,
4677        (ExprKind::Some(x), ExprKind::Some(y)) => history_pred_matches(x, s, y, mode),
4678        (ExprKind::UnaryOp(o1, x), ExprKind::UnaryOp(o2, y)) => {
4679            o1 == o2 && history_pred_matches(x, s, y, mode)
4680        }
4681        // #2018: `x is Variant` — a transition over an enum state (`old.status is
4682        // Closed implies new.status is Closed`) is written with `is`.
4683        (
4684            ExprKind::Is {
4685                value: v1,
4686                pattern: p1,
4687            },
4688            ExprKind::Is {
4689                value: v2,
4690                pattern: p2,
4691            },
4692        ) => history_pattern_matches(p1, p2) && history_pred_matches(v1, s, v2, mode),
4693        (ExprKind::BinOp(o1, l1, r1), ExprKind::BinOp(o2, l2, r2)) => {
4694            o1 == o2
4695                && history_pred_matches(l1, s, l2, mode)
4696                && history_pred_matches(r1, s, r2, mode)
4697        }
4698        (
4699            ExprKind::FieldAccess {
4700                receiver: r1,
4701                field: f1,
4702            },
4703            ExprKind::FieldAccess {
4704                receiver: r2,
4705                field: f2,
4706            },
4707        ) => f1.name == f2.name && history_pred_matches(r1, s, r2, mode),
4708        (
4709            ExprKind::MethodCall {
4710                receiver: r1,
4711                method: m1,
4712                args: a1,
4713                ..
4714            },
4715            ExprKind::MethodCall {
4716                receiver: r2,
4717                method: m2,
4718                args: a2,
4719                ..
4720            },
4721        ) => {
4722            m1.name == m2.name
4723                && a1.len() == a2.len()
4724                && history_pred_matches(r1, s, r2, mode)
4725                && a1
4726                    .iter()
4727                    .zip(a2)
4728                    .all(|(x, y)| history_pred_matches(x, s, y, mode))
4729        }
4730        (
4731            ExprKind::Call {
4732                name: n1, args: a1, ..
4733            },
4734            ExprKind::Call {
4735                name: n2, args: a2, ..
4736            },
4737        ) => {
4738            n1.name == n2.name
4739                && a1.len() == a2.len()
4740                && a1
4741                    .iter()
4742                    .zip(a2)
4743                    .all(|(x, y)| history_pred_matches(x, s, y, mode))
4744        }
4745        _ => false,
4746    }
4747}
4748
4749/// #2018: span-insensitive equality of the pattern in an `is` test, for
4750/// [`history_pred_matches`]. Conservative like the rest of the restate check: only
4751/// a literal or a payload-free variant (same name, same optional `Type.`
4752/// qualifier) is compared; any other pattern shape compares unequal.
4753fn history_pattern_matches(a: &Pattern, b: &Pattern) -> bool {
4754    match (a, b) {
4755        (Pattern::Literal { value: x, .. }, Pattern::Literal { value: y, .. }) => x == y,
4756        (
4757            Pattern::Variant {
4758                type_name: t1,
4759                variant: v1,
4760                bindings: b1,
4761                ..
4762            },
4763            Pattern::Variant {
4764                type_name: t2,
4765                variant: v2,
4766                bindings: b2,
4767                ..
4768            },
4769        ) => {
4770            b1.is_empty()
4771                && b2.is_empty()
4772                && v1.name == v2.name
4773                && t1.as_ref().map(|t| &t.name) == t2.as_ref().map(|t| &t.name)
4774        }
4775        _ => false,
4776    }
4777}
4778
4779/// v0.119 (DECISION D): a history property that merely restates a snapshot/step
4780/// invariant is redundant — the driver only commits states the invariants already
4781/// admit. Recognise the canonical shape `for all run: History[A] { expect
4782/// run.all((s) => P) }` (or `.any`) whose `P` α-matches a declared
4783/// `invariant` (over `s.new`) or `transition` (over `s.old`/`s.new`). Returns the
4784/// body span to flag. Conservative — near-duplicates slip through by design.
4785fn history_restates_invariant(prop: &PropertyDecl, run_var: &str, agent: &AgentDecl) -> bool {
4786    let [stmt] = prop.forall.body.statements.as_slice() else {
4787        return false;
4788    };
4789    let Statement::Expect(e) = stmt else {
4790        return false;
4791    };
4792    // `run.all((s) => P)` / `run.any((s) => P)`.
4793    let ExprKind::MethodCall {
4794        receiver,
4795        method,
4796        args,
4797        ..
4798    } = &e.value.kind
4799    else {
4800        return false;
4801    };
4802    if method.name != "all" && method.name != "any" {
4803        return false;
4804    }
4805    let ExprKind::Ident(recv) = &receiver.kind else {
4806        return false;
4807    };
4808    if recv.name != run_var {
4809        return false;
4810    }
4811    let [arg] = args.as_slice() else {
4812        return false;
4813    };
4814    let ExprKind::Lambda(lam) = &arg.kind else {
4815        return false;
4816    };
4817    let [param] = lam.params.as_slice() else {
4818        return false;
4819    };
4820    let s = &param.name.name;
4821    agent
4822        .invariants
4823        .iter()
4824        .any(|inv| history_pred_matches(&lam.body, s, &inv.predicate, HistoryRestate::Invariant))
4825        || agent
4826            .transitions
4827            .iter()
4828            .any(|tr| history_pred_matches(&lam.body, s, &tr.predicate, HistoryRestate::Transition))
4829}
4830
4831/// v0.119 (ADR 0155): the synthetic type names a `History[Agent]` binding
4832/// registers — a call sum, a step record, and a state record — all keyed off the
4833/// agent name so distinct agents never collide.
4834fn history_call_type_name(agent: &str) -> String {
4835    format!("__History_{agent}_Call")
4836}
4837fn history_step_type_name(agent: &str) -> String {
4838    format!("__History_{agent}_Step")
4839}
4840fn history_state_type_name(agent: &str) -> String {
4841    format!("__History_{agent}_State")
4842}
4843
4844/// The `.call` variant tag for a handler: the handler name with its first letter
4845/// upper-cased (`spend` → `Spend`, `topUp` → `TopUp`). The reader matches this
4846/// with `is` / `match` (`s.call is Spend`).
4847pub fn history_variant_name(handler: &str) -> String {
4848    let mut chars = handler.chars();
4849    match chars.next() {
4850        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
4851        None => handler.to_string(),
4852    }
4853}
4854
4855/// The agent's drivable `on call` handlers — the ones a history sequences. Other
4856/// handler kinds (`http`/`cron`/`message`/`open`/`close`) are not RPC entry points
4857/// and are never part of a generated call-history.
4858pub fn history_handlers(agent: &AgentDecl) -> Vec<&Handler> {
4859    agent
4860        .handlers
4861        .iter()
4862        .filter(|h| matches!(h.kind, HandlerKind::Call) && h.method_name.is_some())
4863        .collect()
4864}
4865
4866/// v0.119 (testing track slice 7, ADR 0155): type-check a `for all run:
4867/// History[Agent]` binding. The subject is a *run* of the agent — a generated,
4868/// driven call-history — bound as an ordinary `List[Step]`. Validates the
4869/// DECISION-B rules (agent-only, every handler parameter generable), registers the
4870/// synthetic call-sum / step / state record types into `resolved.types` so the
4871/// predicate's `List` + value surface (`.call is …`, `.old`/`.new`, `.accepted`)
4872/// type-checks, and returns the bound `List[Step]` type.
4873pub fn check_history_binding(
4874    inner: &TypeRef,
4875    span: Span,
4876    resolved: &mut ResolvedCommons,
4877    refs: &mut RefSink,
4878    tys: &Arc<Types>,
4879) -> Result<checker::Ty, CompileError> {
4880    // DECISION B: only an agent has handlers to sequence and reachable states to
4881    // observe. `History[Value]` / `History[List[…]]` is `not_an_agent`.
4882    let TypeRef::Named(agent_id) = inner else {
4883        return Err(CompileError::new(
4884            "bynk.history.not_an_agent",
4885            span,
4886            format!(
4887                "`for all` cannot generate `History[{}]` — only an agent has handlers to sequence",
4888                ts_type_ref_display(inner)
4889            ),
4890        )
4891        .with_note("generate a driven call-history over an agent: `for all run: History[Agent]`"));
4892    };
4893    let Some(agent) = resolved.agents.get(&agent_id.name).cloned() else {
4894        return Err(CompileError::new(
4895            "bynk.history.not_an_agent",
4896            span,
4897            format!(
4898                "`for all run: History[{}]` names `{}`, which is not an agent in scope",
4899                agent_id.name, agent_id.name
4900            ),
4901        )
4902        .with_note(
4903            "only an agent (with handlers and reachable state) can be driven as a history",
4904        ));
4905    };
4906    refs.record(agent_id.span, SymbolKind::Type, &agent_id.name);
4907
4908    let handlers = history_handlers(&agent);
4909    // DECISION B: the agent must be *drivable* — every handler parameter must be
4910    // refinement-generable (the same rule a value `for all` binding obeys), else
4911    // the runner cannot synthesise a call.
4912    for h in &handlers {
4913        for p in &h.params {
4914            let generable = checker::resolve_type_ref(&p.type_ref, &resolved.types, tys)
4915                .is_some_and(|t| prop_binding_generable(t, &resolved.types, PROP_GEN_DEPTH, tys));
4916            if !generable {
4917                return Err(CompileError::new(
4918                    "bynk.history.not_generable",
4919                    span,
4920                    format!(
4921                        "`History[{}]` cannot be driven — handler `{}`'s parameter `{}: {}` is not generable (e.g. a `Matches` refinement)",
4922                        agent_id.name,
4923                        h.method_name.as_ref().map(|m| m.name.as_str()).unwrap_or(""),
4924                        p.name.name,
4925                        ts_type_ref_display(&p.type_ref),
4926                    ),
4927                )
4928                .with_note(
4929                    "every handler parameter must be refinement-generable for the run to be seeded",
4930                ));
4931            }
4932        }
4933    }
4934
4935    // Register the synthetic types (mirrors `register_call_record_types`). The
4936    // driver returns plain objects of exactly these shapes; the checker sees them
4937    // as ordinary record/sum types so `is`, field access, and `implies` apply
4938    // unchanged (the typed-step shape resolving the track's open question).
4939    let state_name = history_state_type_name(&agent_id.name);
4940    let call_name = history_call_type_name(&agent_id.name);
4941    let step_name = history_step_type_name(&agent_id.name);
4942
4943    // `<Agent>State` — the agent's `Cell` fields, exactly as the emitted state
4944    // record (so `.old.balance` / `.new.balance` read a reached state).
4945    let state_fields: Vec<RecordField> = agent
4946        .store_fields
4947        .iter()
4948        .filter(|f| f.kind.head.name == "Cell" && f.kind.args.len() == 1)
4949        .map(|f| RecordField {
4950            annotations: Vec::new(),
4951            documentation: None,
4952            trivia: Default::default(),
4953            name: f.name.clone(),
4954            type_ref: f.kind.args[0].clone(),
4955            refinement: None,
4956            init: None,
4957            span: f.span,
4958        })
4959        .collect();
4960    resolved.types.insert(
4961        state_name.clone(),
4962        Arc::new(TypeDecl {
4963            derives: Vec::new(),
4964            derives_kw: None,
4965            type_params: Vec::new(),
4966            name: Ident {
4967                name: state_name.clone(),
4968                span,
4969            },
4970            body: TypeBody::Record(RecordBody {
4971                trailing_comments: Default::default(),
4972                fields: state_fields,
4973                span,
4974            }),
4975            documentation: None,
4976            span,
4977            trivia: Trivia::default(),
4978            private: None,
4979        }),
4980    );
4981
4982    // `.call` — a sum over the agent's handlers, each variant carrying the
4983    // handler's generated arguments (`Spend { amount }`, `TopUp { amount }`).
4984    let variants: Vec<Variant> = handlers
4985        .iter()
4986        .map(|h| {
4987            let hname = h.method_name.as_ref().expect("call handler has a name");
4988            Variant {
4989                documentation: None,
4990                trivia: Default::default(),
4991                name: Ident {
4992                    name: history_variant_name(&hname.name),
4993                    span: hname.span,
4994                },
4995                payload: h
4996                    .params
4997                    .iter()
4998                    .map(|p| VariantField {
4999                        documentation: None,
5000                        name: p.name.clone(),
5001                        type_ref: p.type_ref.clone(),
5002                        span: p.span,
5003                    })
5004                    .collect(),
5005                span: hname.span,
5006            }
5007        })
5008        .collect();
5009    resolved.types.insert(
5010        call_name.clone(),
5011        Arc::new(TypeDecl {
5012            derives: Vec::new(),
5013            derives_kw: None,
5014            type_params: Vec::new(),
5015            name: Ident {
5016                name: call_name.clone(),
5017                span,
5018            },
5019            body: TypeBody::Sum(SumBody {
5020                trailing_comments: Default::default(),
5021                variants,
5022                embeds: Vec::new(),
5023                span,
5024            }),
5025            documentation: None,
5026            span,
5027            trivia: Trivia::default(),
5028            private: None,
5029        }),
5030    );
5031
5032    // A `Step` — the driven edge: which call ran (`.call`), whether it committed
5033    // (`.accepted`), and the committed `old` → `new` state pair.
5034    let step_fields = vec![
5035        RecordField {
5036            annotations: Vec::new(),
5037            documentation: None,
5038            trivia: Default::default(),
5039            name: Ident {
5040                name: "call".to_string(),
5041                span,
5042            },
5043            type_ref: TypeRef::Named(Ident {
5044                name: call_name.clone(),
5045                span,
5046            }),
5047            refinement: None,
5048            init: None,
5049            span,
5050        },
5051        RecordField {
5052            annotations: Vec::new(),
5053            documentation: None,
5054            trivia: Default::default(),
5055            name: Ident {
5056                name: "accepted".to_string(),
5057                span,
5058            },
5059            type_ref: TypeRef::Base(BaseType::Bool, span),
5060            refinement: None,
5061            init: None,
5062            span,
5063        },
5064        RecordField {
5065            annotations: Vec::new(),
5066            documentation: None,
5067            trivia: Default::default(),
5068            name: Ident {
5069                name: "old".to_string(),
5070                span,
5071            },
5072            type_ref: TypeRef::Named(Ident {
5073                name: state_name.clone(),
5074                span,
5075            }),
5076            refinement: None,
5077            init: None,
5078            span,
5079        },
5080        RecordField {
5081            annotations: Vec::new(),
5082            documentation: None,
5083            trivia: Default::default(),
5084            name: Ident {
5085                name: "new".to_string(),
5086                span,
5087            },
5088            type_ref: TypeRef::Named(Ident {
5089                name: state_name.clone(),
5090                span,
5091            }),
5092            refinement: None,
5093            init: None,
5094            span,
5095        },
5096    ];
5097    resolved.types.insert(
5098        step_name.clone(),
5099        Arc::new(TypeDecl {
5100            derives: Vec::new(),
5101            derives_kw: None,
5102            type_params: Vec::new(),
5103            name: Ident {
5104                name: step_name.clone(),
5105                span,
5106            },
5107            body: TypeBody::Record(RecordBody {
5108                trailing_comments: Default::default(),
5109                fields: step_fields,
5110                span,
5111            }),
5112            documentation: None,
5113            span,
5114            trivia: Trivia::default(),
5115            private: None,
5116        }),
5117    );
5118
5119    Ok(checker::Ty::List(tys.intern(checker::Ty::Named {
5120        name: step_name,
5121        kind: checker::NamedKind::Record,
5122        args: Vec::new(),
5123    })))
5124}
5125
5126/// v0.114: type-check a generative `property` — its `for all` bindings, the
5127/// optional `where` filter, and the predicate body — in the target's privileged
5128/// view. Bindings type each `x: T`; `where`/`expect` predicates type as pure
5129/// `Bool`; each binding's `T` must be refinement-generable (agents are rejected;
5130/// a `Matches` type must pin); and the body is flagged if it merely restates a
5131/// refinement (DECISION P). v0.119: a `for all run: History[Agent]` binding is a
5132/// driven call-history (the history rung — see [`check_history_binding`]).
5133#[allow(clippy::too_many_arguments)]
5134fn check_property_body(
5135    target_name: &str,
5136    target_kind: UnitKind,
5137    suite_fns: SuiteItems<'_>,
5138    prop: &PropertyDecl,
5139    unit_tables: &HashMap<String, UnitTable>,
5140    unit_uses: &HashMap<String, Vec<String>>,
5141    unit_consumes: &HashMap<String, Vec<String>>,
5142    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5143    errors: &mut Vec<CompileError>,
5144    refs: &mut RefSink,
5145    locals: &mut LocalsSink,
5146    tys: &Arc<Types>,
5147    d1_sql: Option<&crate::d1_sql::D1Sql>,
5148    source: &str,
5149) {
5150    let Some((mut resolved, _)) = build_privileged_resolved(
5151        target_name,
5152        unit_tables,
5153        unit_uses,
5154        unit_consumes,
5155        unit_consumes_aliases,
5156    ) else {
5157        return;
5158    };
5159    register_call_record_types(&mut resolved, target_name, unit_tables);
5160    add_suite_fns(&mut resolved, suite_fns);
5161    let _ = target_kind;
5162
5163    // Bind each `for all x: T` into the predicate scope, checking generability.
5164    let mut binding_scope: HashMap<String, checker::TyId> = HashMap::new();
5165    let mut binding_types: Vec<(String, Option<checker::TyId>)> = Vec::new();
5166    // v0.119: the single `History[Agent]` binding (run-var, agent), for the
5167    // post-body `restates_invariant` check (DECISION D).
5168    let mut history_binding: Option<(String, AgentDecl)> = None;
5169    for b in &prop.forall.bindings {
5170        // v0.119 (ADR 0155): `for all run: History[Agent]` — the history rung. A
5171        // driven call-history, bound as an ordinary `List[Step]`.
5172        if let TypeRef::History(inner, hspan) = &b.type_ref {
5173            match check_history_binding(inner, *hspan, &mut resolved, refs, tys) {
5174                Ok(step_ty) => {
5175                    if let TypeRef::Named(agent_id) = &**inner
5176                        && let Some(agent) = resolved.agents.get(&agent_id.name)
5177                    {
5178                        history_binding = Some((b.name.name.clone(), AgentDecl::clone(agent)));
5179                    }
5180                    binding_scope.insert(b.name.name.clone(), tys.intern(step_ty.clone()));
5181                    binding_types.push((b.name.name.clone(), Some(tys.intern(step_ty))));
5182                }
5183                Err(err) => {
5184                    errors.push(err);
5185                    binding_types.push((b.name.name.clone(), None));
5186                    // #1708: rejected, but still in scope (error-typed), so
5187                    // its uses in the body do not echo as unknown names.
5188                    binding_scope.insert(b.name.name.clone(), tys.intern(checker::Ty::Error));
5189                }
5190            }
5191            continue;
5192        }
5193        // Agents are not a value type — a fabricated state that satisfies every
5194        // invariant need not be reachable (DECISION P); reject up front.
5195        if let TypeRef::Named(id) = &b.type_ref
5196            && resolved.agents.contains_key(&id.name)
5197        {
5198            errors.push(
5199                CompileError::new(
5200                    "bynk.val.agent_not_generable",
5201                    b.type_ref.span(),
5202                    format!(
5203                        "`for all {}: {}` cannot generate an agent — a fabricated agent state need not be reachable",
5204                        b.name.name, id.name
5205                    ),
5206                )
5207                .with_note(
5208                    "generate behaviour over an agent via handler sequences (the history rung), not fabricated states",
5209                ),
5210            );
5211            binding_types.push((b.name.name.clone(), None));
5212            // #1708: rejected, but still in scope (error-typed), so
5213            // its uses in the body do not echo as unknown names.
5214            binding_scope.insert(b.name.name.clone(), tys.intern(checker::Ty::Error));
5215            continue;
5216        }
5217        let ty = match checker::resolve_type_ref(&b.type_ref, &resolved.types, tys) {
5218            Some(t) => {
5219                record_type_refs_in_property(&b.type_ref, &resolved, refs);
5220                t
5221            }
5222            None => {
5223                errors.push(CompileError::new(
5224                    "bynk.val.unknown_type",
5225                    b.type_ref.span(),
5226                    format!(
5227                        "`for all {}: {}` names a type that does not resolve",
5228                        b.name.name,
5229                        ts_type_ref_display(&b.type_ref)
5230                    ),
5231                ));
5232                binding_types.push((b.name.name.clone(), None));
5233                // #1708: rejected, but still in scope (error-typed), so
5234                // its uses in the body do not echo as unknown names.
5235                binding_scope.insert(b.name.name.clone(), tys.intern(checker::Ty::Error));
5236                continue;
5237            }
5238        };
5239        if !prop_binding_generable(ty, &resolved.types, PROP_GEN_DEPTH, tys) {
5240            errors.push(
5241                CompileError::new(
5242                    "bynk.val.needs_pin",
5243                    b.type_ref.span(),
5244                    format!(
5245                        "`for all {}: {}` cannot generate a value (e.g. a `Matches` refinement); a property cannot bind it",
5246                        b.name.name,
5247                        ts_type_ref_display(&b.type_ref)
5248                    ),
5249                )
5250                .with_note("supply the witness in a `case` with a pinned `Val[T](...)` instead"),
5251            );
5252        }
5253        binding_scope.insert(b.name.name.clone(), ty);
5254        binding_types.push((b.name.name.clone(), Some(ty)));
5255    }
5256
5257    // Type the `where`/body predicates in the target's privileged view with the
5258    // bindings in scope — mirroring the `case` body context.
5259    let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
5260    let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
5261    let unit_span = prop.span;
5262    let synthetic_return = TypeRef::Effect(
5263        Box::new(TypeRef::Result(
5264            Box::new(TypeRef::Unit(unit_span)),
5265            Box::new(TypeRef::ValidationError(unit_span)),
5266            unit_span,
5267        )),
5268        unit_span,
5269    );
5270    let mut capability_info_map: HashMap<String, checker::CapabilityInfo> = HashMap::new();
5271    if let Some(table) = unit_tables.get(target_name) {
5272        for (name, decl) in &table.capabilities {
5273            let ops = decl
5274                .ops
5275                .iter()
5276                .map(|op| build_capability_op_info(op, &resolved.types, tys))
5277                .collect();
5278            capability_info_map.insert(
5279                name.clone(),
5280                checker::CapabilityInfo {
5281                    name: name.clone(),
5282                    ops,
5283                    derived_from: crate::context_checks::derived_from(
5284                        decl,
5285                        &resolved.cross_context.flattened_caps,
5286                    ),
5287                },
5288            );
5289        }
5290    }
5291    add_consumed_adapter_capabilities(&mut capability_info_map, unit_tables, &resolved, tys);
5292    add_consumed_service_seams(&mut capability_info_map, &resolved, unit_tables, tys);
5293    let given_declared: Vec<String> = capability_info_map.keys().cloned().collect();
5294    let return_ty = checker::resolve_type_ref(&synthetic_return, &resolved.types, tys).unwrap();
5295    let return_ty_span = prop.span;
5296    let mut no_hints = HintSink::new();
5297    let mut no_requirements = RequirementSink::new();
5298    // The optional `where` filter is checked first (against `Bool`), sharing
5299    // `check_body`'s `Ctx` with the body below; the body is the one predicate
5300    // surface: `expect`s self-check as `Bool`.
5301    let _ = checker::check_body(
5302        &resolved,
5303        &prop.forall.body,
5304        return_ty,
5305        return_ty_span,
5306        binding_scope,
5307        checker::CapabilityCtx {
5308            capabilities: capability_info_map.clone(),
5309            declared_capabilities: capability_info_map,
5310            given_remaining: given_declared.iter().cloned().collect(),
5311            given_used: HashSet::new(),
5312            given_entries: Vec::new(),
5313            given_anchor: None,
5314            ..Default::default()
5315        },
5316        target_test_services(
5317            Some(target_name),
5318            unit_tables,
5319            &resolved.cross_context.consumed_contexts,
5320        ),
5321        target_test_actors(unit_tables.get(target_name)),
5322        prop.forall.where_pred.as_ref(),
5323        checker::CheckSinks {
5324            tys,
5325            expr_types: &mut expr_types,
5326            errors,
5327            refs,
5328            hints: &mut no_hints,
5329            locals,
5330            requirements: &mut no_requirements,
5331            callees: &mut callees,
5332        },
5333    );
5334
5335    check_d1_sql_sites(d1_sql, target_name, unit_tables, &callees, source, errors);
5336
5337    // Conservative restates-refinement flag: a single-binding property whose
5338    // body is exactly `expect <pred>` restating the bound var's refinement.
5339    if let [(var, Some(ty))] = binding_types.as_slice()
5340        && let Some(refinement) = named_refinement(*ty, &resolved.types, tys)
5341        && let [stmt] = prop.forall.body.statements.as_slice()
5342        && let Statement::Expect(e) = stmt
5343        && predicate_restates_refinement(&e.value, var, refinement)
5344    {
5345        errors.push(
5346            CompileError::new(
5347                "bynk.property.restates_refinement",
5348                prop.forall.body.span,
5349                format!(
5350                    "property `{}` merely re-checks a refinement type `{}` already guarantees",
5351                    prop.name,
5352                    ty.display(tys)
5353                ),
5354            )
5355            .with_note(
5356                "a property earns its keep by asserting behaviour over valid inputs, not by restating the type's refinement",
5357            ),
5358        );
5359    }
5360
5361    // v0.119 (DECISION D): a history property that merely restates a declared
5362    // `invariant` / `transition` re-checks a guarantee every reached state already
5363    // has (the driver only commits admissible states). Conservative — near-
5364    // duplicates slip through by design.
5365    if let Some((run_var, agent)) = &history_binding
5366        && history_restates_invariant(prop, run_var, agent)
5367    {
5368        errors.push(
5369            CompileError::new(
5370                "bynk.history.restates_invariant",
5371                prop.forall.body.span,
5372                format!(
5373                    "history property `{}` merely re-checks a guarantee agent `{}`'s `invariant`/`transition` already enforces on every reached state",
5374                    prop.name, agent.name.name
5375                ),
5376            )
5377            .with_note(
5378                "a history property earns its keep by asserting a cross-step protocol, not by restating a per-state invariant",
5379            ),
5380        );
5381    }
5382}
5383
5384/// Record type references named by a `for all` binding so cross-file edges and
5385/// go-to-definition resolve for a property's generated types.
5386fn record_type_refs_in_property(
5387    type_ref: &TypeRef,
5388    resolved: &ResolvedCommons,
5389    refs: &mut RefSink,
5390) {
5391    checker::record_type_refs(type_ref, &resolved.types, &HashSet::new(), refs);
5392}
5393
5394/// #1814: a test suite's composed symbol tables, closed over the types its
5395/// imported declarations reach. `hidden` names each type the closure added,
5396/// with its owning commons: resolvable in the view, never nameable by the
5397/// suite (`resolver::check_hidden_type_names_in_suite`), and imported by the
5398/// test scaffold from that commons.
5399#[derive(Clone, Default)]
5400pub struct SuiteView {
5401    pub types: HashMap<String, Arc<TypeDecl>>,
5402    pub fns: HashMap<String, Arc<FnDecl>>,
5403    pub methods: HashMap<String, ResolverMethodTable>,
5404    pub hidden: BTreeMap<String, String>,
5405    /// Review of #1814: each reached name the view already binds to another
5406    /// declaration (`project_model::close_view_types`).
5407    pub conflicts: Vec<crate::project_model::ViewConflict>,
5408    /// #1883, slice 3 ([DECISION F]): the assets a case may name — those the
5409    /// target's Worker ships: the target's own and its `uses`d commons'
5410    /// (content-hashed and fixed-path), plus the content-hashed assets of the
5411    /// contexts it consumes. An asset name types as `Asset`;
5412    /// `svc.GET(asset)` fetches the file.
5413    pub assets: HashMap<String, bynk_syntax::ast::AssetDecl>,
5414    /// #2387, slice 2: the embeds a unit-tier case may name — the target's
5415    /// own and its `uses`d commons', `String` constants of the target's
5416    /// module. Empty for a `system` view: an embed is code, not something
5417    /// served by a Worker.
5418    pub embeds: HashMap<String, bynk_syntax::ast::EmbedDecl>,
5419    /// #2617: the constants a unit-tier case may name — the target's own and
5420    /// its `uses`d commons', exported `const`s of the target's module, like
5421    /// an embed. Empty for a `system` view.
5422    pub consts: HashMap<String, bynk_syntax::ast::ConstDecl>,
5423}
5424
5425impl SuiteView {
5426    /// #2617: add the constants `unit` sees — its own and those of the
5427    /// commons it `uses`, one level, as for embeds — first name winning.
5428    fn merge_consts(
5429        &mut self,
5430        unit: &str,
5431        unit_tables: &HashMap<String, UnitTable>,
5432        unit_uses: &HashMap<String, Vec<String>>,
5433    ) {
5434        // `unit`'s own `private` constants are visible; a used commons' stay
5435        // in it.
5436        let own = unit_tables.get(unit).into_iter().map(|t| (unit, t, true));
5437        let used = unit_uses
5438            .get(unit)
5439            .into_iter()
5440            .flatten()
5441            .filter_map(|u| unit_tables.get(u).map(|t| (u.as_str(), t, false)));
5442        for (owner, table, is_own) in own.chain(used) {
5443            for (name, decl) in table
5444                .consts
5445                .iter()
5446                .filter(|(_, d)| is_own || d.private.is_none())
5447            {
5448                self.consts.entry(name.clone()).or_insert_with(|| {
5449                    let mut decl = decl.clone();
5450                    // #3065: an imported alias names its target in the
5451                    // declaring unit's scope (see `compose_unit_consts`).
5452                    if !is_own
5453                        && matches!(decl.init.kind, ExprKind::Ident(_))
5454                        && let Some(text) = crate::consts::alias_literal(
5455                            |u| {
5456                                unit_tables
5457                                    .get(u)
5458                                    .map(|t| (t, unit_uses.get(u).map_or(&[][..], Vec::as_slice)))
5459                            },
5460                            owner,
5461                            &decl,
5462                        )
5463                    {
5464                        decl.init.kind = ExprKind::StrLit(text);
5465                    }
5466                    decl
5467                });
5468            }
5469        }
5470    }
5471
5472    /// #2387, slice 2: add the embeds `unit` sees — its own and those of the
5473    /// commons it `uses`, one level, as for functions — first name winning.
5474    fn merge_embeds(
5475        &mut self,
5476        unit: &str,
5477        unit_tables: &HashMap<String, UnitTable>,
5478        unit_uses: &HashMap<String, Vec<String>>,
5479    ) {
5480        // #2618: `unit`'s own `private` embeds are visible; a used commons'
5481        // stay in it.
5482        let own = unit_tables.get(unit).into_iter().map(|t| (t, true));
5483        let used = unit_uses
5484            .get(unit)
5485            .into_iter()
5486            .flatten()
5487            .filter_map(|u| unit_tables.get(u))
5488            .map(|t| (t, false));
5489        for (table, is_own) in own.chain(used) {
5490            for (name, decl) in table
5491                .embeds
5492                .iter()
5493                .filter(|(_, d)| is_own || d.private.is_none())
5494            {
5495                self.embeds
5496                    .entry(name.clone())
5497                    .or_insert_with(|| decl.clone());
5498            }
5499        }
5500    }
5501
5502    /// #1883, slice 3: add the assets `unit` sees — its own and those of the
5503    /// commons it `uses`, one level, as for functions — first name winning.
5504    fn merge_assets(
5505        &mut self,
5506        unit: &str,
5507        unit_tables: &HashMap<String, UnitTable>,
5508        unit_uses: &HashMap<String, Vec<String>>,
5509    ) {
5510        self.merge_assets_where(unit, unit_tables, unit_uses, |_| true);
5511    }
5512
5513    /// [`Self::merge_assets`], keeping only the declarations `keep` admits.
5514    fn merge_assets_where(
5515        &mut self,
5516        unit: &str,
5517        unit_tables: &HashMap<String, UnitTable>,
5518        unit_uses: &HashMap<String, Vec<String>>,
5519        keep: impl Fn(&bynk_syntax::ast::AssetDecl) -> bool,
5520    ) {
5521        // #2618: `unit`'s own `private` assets are visible; a used commons'
5522        // stay in it.
5523        let own = unit_tables.get(unit).into_iter().map(|t| (t, true));
5524        let used = unit_uses
5525            .get(unit)
5526            .into_iter()
5527            .flatten()
5528            .filter_map(|u| unit_tables.get(u))
5529            .map(|t| (t, false));
5530        for (table, is_own) in own.chain(used) {
5531            for (name, decl) in table
5532                .assets
5533                .iter()
5534                .filter(|(_, d)| keep(d) && (is_own || d.private.is_none()))
5535            {
5536                self.assets
5537                    .entry(name.clone())
5538                    .or_insert_with(|| decl.clone());
5539            }
5540        }
5541    }
5542
5543    /// What the closure found, without the tables.
5544    pub fn reach(&self) -> crate::project_model::ViewReach {
5545        crate::project_model::ViewReach {
5546            hidden: self.hidden.clone(),
5547            conflicts: self.conflicts.clone(),
5548        }
5549    }
5550
5551    /// Merge `t`'s types and methods (and its fns, when `with_fns`) into the
5552    /// view, first declaration of a name winning; `with_statics` brings static
5553    /// methods too.
5554    fn merge(&mut self, t: &UnitTable, with_fns: bool, with_statics: bool) {
5555        for (n, d) in &t.types {
5556            self.types.entry(n.clone()).or_insert_with(|| d.clone());
5557        }
5558        if with_fns {
5559            for (n, f) in &t.fns {
5560                self.fns.entry(n.clone()).or_insert_with(|| f.clone());
5561            }
5562        }
5563        for (n, mt) in &t.methods {
5564            let entry = self.methods.entry(n.clone()).or_default();
5565            for (m, decl) in &mt.instance {
5566                entry
5567                    .instance
5568                    .entry(m.clone())
5569                    .or_insert_with(|| decl.clone());
5570            }
5571            if with_statics {
5572                for (m, decl) in &mt.statics {
5573                    entry
5574                        .statics
5575                        .entry(m.clone())
5576                        .or_insert_with(|| decl.clone());
5577                }
5578            }
5579        }
5580    }
5581
5582    /// #3400: add the first-party types the view's declarations still name.
5583    ///
5584    /// The closure ([`SuiteView::close`]) adds only types a commons owns, and
5585    /// the first-party units a unit `consumes` (`bynk`'s `File`, `bynk.cloudflare`'s
5586    /// email types) are adapters, so a `@multipart` body's `File` was never in a
5587    /// `system` harness view. A case that built one then had its fields left
5588    /// unchecked (`check_record_construction` skips a type the view lacks), so a
5589    /// `Bytes` static inside it recorded no callee and lowered to `/* unknown */`.
5590    /// A name no declaration of the view binds, which a first-party unit does, can
5591    /// only have come from that unit's `consumes`, so it is that unit's type.
5592    ///
5593    /// The walk starts from what the view's types and fns name, and from the
5594    /// participants' service handlers' parameters and results, as a type a
5595    /// handler names without any record around it (a JSON `body: Cookie`) is
5596    /// reached by neither.
5597    fn reach_first_party_types(
5598        &mut self,
5599        participants: &[String],
5600        unit_tables: &HashMap<String, UnitTable>,
5601    ) {
5602        let no_vars = HashSet::new();
5603        let mut queue: Vec<String> = self
5604            .types
5605            .values()
5606            .flat_map(|d| crate::project_model::type_decl_ref_names(d))
5607            .collect();
5608        for f in self.fns.values() {
5609            for p in &f.params {
5610                crate::project_model::type_ref_names(&p.type_ref, &no_vars, &mut queue);
5611            }
5612            crate::project_model::type_ref_names(&f.return_type, &no_vars, &mut queue);
5613        }
5614        for table in participants.iter().filter_map(|p| unit_tables.get(p)) {
5615            for h in table.services.values().flat_map(|s| &s.handlers) {
5616                for p in &h.params {
5617                    crate::project_model::type_ref_names(&p.type_ref, &no_vars, &mut queue);
5618                }
5619                crate::project_model::type_ref_names(&h.return_type, &no_vars, &mut queue);
5620            }
5621        }
5622        // `bynk` is read before `bynk.cloudflare`; the two declare no name in
5623        // common, so which unit a participant consumed a name from is not
5624        // ambiguous.
5625        let first_party = [
5626            crate::firstparty::BYNK_UNIT,
5627            crate::firstparty::CLOUDFLARE_UNIT,
5628        ];
5629        while let Some(name) = queue.pop() {
5630            if self.types.contains_key(&name) {
5631                continue;
5632            }
5633            let found = first_party
5634                .into_iter()
5635                .find_map(|u| unit_tables.get(u).and_then(|t| t.types.get(&name)));
5636            if let Some(decl) = found {
5637                queue.extend(crate::project_model::type_decl_ref_names(decl));
5638                self.types.insert(name, decl.clone());
5639            }
5640        }
5641    }
5642
5643    /// #1814: close the view over what the declarations of `imported` reach
5644    /// (`project_model::close_view_types`), recording what it adds.
5645    fn close(
5646        &mut self,
5647        imported: &[String],
5648        unit_tables: &HashMap<String, UnitTable>,
5649        unit_uses: &HashMap<String, Vec<String>>,
5650        actor_identities: bool,
5651    ) {
5652        let reach = crate::project_model::close_view_types(
5653            imported,
5654            unit_tables,
5655            unit_uses,
5656            &mut self.types,
5657            &self.fns,
5658            &mut self.methods,
5659            actor_identities,
5660        );
5661        self.hidden = reach.hidden;
5662        self.conflicts = reach.conflicts;
5663    }
5664}
5665
5666/// `owning_unit`'s privileged view: its types, fns, methods, plus those of
5667/// every commons it `uses`, plus the types and instance methods of every
5668/// consumed context. #1814: closed over the types those imported declarations
5669/// reach, as the unit's own table is, so a case is checked against the same
5670/// types the target is.
5671pub fn privileged_view(
5672    owning_unit: &str,
5673    unit_tables: &HashMap<String, UnitTable>,
5674    unit_uses: &HashMap<String, Vec<String>>,
5675    unit_consumes: &HashMap<String, Vec<String>>,
5676) -> Option<SuiteView> {
5677    let local = unit_tables.get(owning_unit)?;
5678    let mut view = SuiteView {
5679        types: local.types.clone(),
5680        fns: local.fns.clone(),
5681        methods: local.methods.clone(),
5682        ..SuiteView::default()
5683    };
5684    let mut imported: Vec<String> = Vec::new();
5685    for t in unit_uses.get(owning_unit).into_iter().flatten() {
5686        if let Some(used) = unit_tables.get(t) {
5687            // #2618: the target's own `private` declarations are in the view
5688            // (its table, above); a commons it uses keeps its own.
5689            view.merge(&used.importable(), true, true);
5690            imported.push(t.clone());
5691        }
5692    }
5693    // Consumed-context types come in too: every one, not only the exported
5694    // ones, since the view is privileged. Review of #1814: so a reached name
5695    // can bind here to an unexported type the target's own table never
5696    // binds; `check_test_bodies` reports that.
5697    for t in unit_consumes.get(owning_unit).into_iter().flatten() {
5698        if let Some(used) = unit_tables.get(t) {
5699            view.merge(used, false, false);
5700            imported.push(t.clone());
5701        }
5702    }
5703    view.merge_assets(owning_unit, unit_tables, unit_uses);
5704    view.merge_embeds(owning_unit, unit_tables, unit_uses);
5705    view.merge_consts(owning_unit, unit_tables, unit_uses);
5706    // Review of #1923: the content-hashed assets of each consumed context
5707    // too — the target's Worker ships them (`assets::deployed_assets`), so a
5708    // fragment a consumed service returns resolves. Its fixed paths stay
5709    // with its own Worker, so they are not nameable here.
5710    for consumed in unit_consumes.get(owning_unit).into_iter().flatten() {
5711        view.merge_assets_where(consumed, unit_tables, unit_uses, |d| d.at.is_none());
5712    }
5713    // #1925: a function or asset the target hides behind its own declaration
5714    // of another kind is out of scope here too, as in the target's module
5715    // (`project_model::shadowed_imports`): a case names the target's own.
5716    let hidden_by_local = |n: &String| crate::symbols::local_value_kind(local, n).is_some();
5717    view.fns
5718        .retain(|n, _| local.fns.contains_key(n) || !hidden_by_local(n));
5719    view.assets
5720        .retain(|n, _| local.assets.contains_key(n) || !hidden_by_local(n));
5721    view.embeds
5722        .retain(|n, _| local.embeds.contains_key(n) || !hidden_by_local(n));
5723    view.consts
5724        .retain(|n, _| local.consts.contains_key(n) || !hidden_by_local(n));
5725    view.close(&imported, unit_tables, unit_uses, false);
5726    Some(view)
5727}
5728
5729/// #1814: a `system` case's harness view: types, fns and methods from the
5730/// suite's `uses` commons (for constructing arguments), plus each
5731/// participant's types and methods (so return types rebrand and variant
5732/// patterns resolve), closed over the types those declarations reach.
5733pub fn integration_view(
5734    uses_targets: &[String],
5735    participants: &[String],
5736    unit_tables: &HashMap<String, UnitTable>,
5737    unit_uses: &HashMap<String, Vec<String>>,
5738) -> SuiteView {
5739    let mut view = SuiteView::default();
5740    let mut imported: Vec<String> = Vec::new();
5741    for (units, with_fns) in [(uses_targets, true), (participants, false)] {
5742        for u in units {
5743            if let Some(t) = unit_tables.get(u) {
5744                // #2618: a commons the suite uses keeps its `private`
5745                // declarations; a participant is the system under test.
5746                if with_fns {
5747                    view.merge(&t.importable(), with_fns, true);
5748                } else {
5749                    view.merge(t, with_fns, true);
5750                }
5751                imported.push(u.clone());
5752            }
5753        }
5754    }
5755    // #1883, slice 3: the assets the target's Worker ships, mirroring
5756    // `assets::deployed_assets` — the target's own and its `uses`d commons'
5757    // (hashed and fixed), plus each other participant's content-hashed ones
5758    // (a consumed context, whose fragment may carry its `.url`). Review of
5759    // #1922: a participant's fixed path, or an asset of the suite's own
5760    // `uses` commons, is not served by the target's Worker, so it is not
5761    // nameable either (an ordinary unknown name rather than a `NotFound`).
5762    if let Some((target, others)) = participants.split_first() {
5763        view.merge_assets(target, unit_tables, unit_uses);
5764        for other in others {
5765            view.merge_assets_where(other, unit_tables, unit_uses, |d| d.at.is_none());
5766        }
5767        // #1925: an asset the target hides behind its own declaration of
5768        // another kind is not nameable, as in `privileged_view`. Its file
5769        // still ships: the commons that declares it may use it.
5770        if let Some(local) = unit_tables.get(target) {
5771            view.assets.retain(|n, _| {
5772                local.assets.contains_key(n) || crate::symbols::local_value_kind(local, n).is_none()
5773            });
5774        }
5775    }
5776    // #3328: a `system` case drives an email service through the Worker's
5777    // `email()` entry and reads back the `EmailVerdict` it applied, so the
5778    // first-party email types a participant's handler names are in scope, or the
5779    // result would read as an untyped value and `expect r is Forward(…)` could not
5780    // find the variant's fields.
5781    let has_email = participants.iter().any(|p| {
5782        unit_tables.get(p).is_some_and(|t| {
5783            t.services
5784                .values()
5785                .any(|s| matches!(s.protocol, bynk_syntax::ast::ServiceProtocol::Email { .. }))
5786        })
5787    });
5788    if has_email && let Some(cloudflare) = unit_tables.get(crate::firstparty::CLOUDFLARE_UNIT) {
5789        for name in [
5790            "InboundEmail",
5791            "InboundAttachment",
5792            "EmailVerdict",
5793            "EmailReply",
5794            "DmarcVerdict",
5795            "SenderIdentity",
5796        ] {
5797            if let Some(decl) = cloudflare.types.get(name) {
5798                view.types
5799                    .entry(name.to_string())
5800                    .or_insert_with(|| decl.clone());
5801            }
5802        }
5803    }
5804    // #3147: a case `D1.peek`s a participant's database and binds the values of
5805    // its statements, so the `D1` types are in scope where a participant has one.
5806    let has_d1 = participants.iter().any(|p| {
5807        unit_tables.get(p).is_some_and(|t| {
5808            t.derived
5809                .values()
5810                .any(|d| d.base_unit == crate::firstparty::CLOUDFLARE_UNIT && d.base_cap == "D1")
5811        })
5812    });
5813    if has_d1 && let Some(cloudflare) = unit_tables.get(crate::firstparty::CLOUDFLARE_UNIT) {
5814        for name in [
5815            "SqlValue",
5816            "SqlError",
5817            "SqlReadError",
5818            "SqlRun",
5819            "SqlStatement",
5820        ] {
5821            if let Some(decl) = cloudflare.types.get(name) {
5822                view.types
5823                    .entry(name.to_string())
5824                    .or_insert_with(|| decl.clone());
5825            }
5826        }
5827    }
5828    // #3064: a participant's actors' identity types are reached too.
5829    view.close(&imported, unit_tables, unit_uses, true);
5830    view.reach_first_party_types(participants, unit_tables);
5831    view
5832}
5833
5834/// Build a [`resolver::ResolvedCommons`] backed by `owning_unit`'s
5835/// [`privileged_view`]. The same shape used by the production pipeline.
5836/// Returns the [`ResolvedCommons`] plus what the view's closure found (#1814):
5837/// its hidden types and its conflicts.
5838pub fn build_privileged_resolved(
5839    owning_unit: &str,
5840    unit_tables: &HashMap<String, UnitTable>,
5841    unit_uses: &HashMap<String, Vec<String>>,
5842    unit_consumes: &HashMap<String, Vec<String>>,
5843    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5844) -> Option<(ResolvedCommons, crate::project_model::ViewReach)> {
5845    let local = unit_tables.get(owning_unit)?;
5846    let view = privileged_view(owning_unit, unit_tables, unit_uses, unit_consumes)?;
5847    let reach = view.reach();
5848    let assets = view.assets.clone();
5849    let embeds = view.embeds.clone();
5850    let consts = view.consts.clone();
5851    let SuiteView {
5852        types,
5853        fns,
5854        methods,
5855        ..
5856    } = view;
5857    let cross_context = build_cross_context_info(
5858        owning_unit,
5859        unit_consumes,
5860        unit_consumes_aliases,
5861        unit_uses,
5862        unit_tables,
5863    );
5864    let synthetic_commons = Commons {
5865        name: QualifiedName {
5866            parts: owning_unit
5867                .split('.')
5868                .map(|part| Ident {
5869                    name: part.to_string(),
5870                    span: Span::default(),
5871                })
5872                .collect(),
5873            span: Span::default(),
5874        },
5875        items: Vec::new(),
5876        uses: Vec::new(),
5877        documentation: None,
5878        form: CommonsForm::Brace,
5879        span: Span::default(),
5880        trivia: Trivia::default(),
5881        trailing_comments: Vec::new(),
5882    };
5883    let agents_for_resolved = unit_tables
5884        .get(owning_unit)
5885        .map(|t| t.agents.clone())
5886        .unwrap_or_default();
5887    let no_local_events = HashMap::new();
5888    let resolved = ResolvedCommons::new(
5889        Arc::new(synthetic_commons),
5890        types,
5891        &local.types,
5892        fns,
5893        methods,
5894        agents_for_resolved,
5895        // "Privileged" test/stub-body resolved — deliberately relaxed, not a
5896        // real context emission subject to the rebrand — so events stay
5897        // empty rather than reading `local`'s.
5898        &no_local_events,
5899        cross_context,
5900        HashMap::new(),
5901        false,
5902        HashSet::new(),
5903    )
5904    // #1883, slice 3: the target's assets, nameable and fetchable in a case.
5905    .with_assets(assets)
5906    .with_embeds(embeds)
5907    .with_consts(consts)
5908    // #3536: the first-party types the target's braces leave out.
5909    .with_unselected_types(local.unselected_consumed_types.iter().cloned().collect())
5910    // #1925: the imports the target hides, so a case naming one reports the
5911    // conflict as the target's own code would.
5912    .with_shadowed_imports(crate::project_model::shadowed_imports_in(
5913        local,
5914        unit_uses
5915            .get(owning_unit)
5916            .into_iter()
5917            .flatten()
5918            .filter_map(|t| unit_tables.get(t).map(|u| (t, u))),
5919    ));
5920    Some((resolved, reach))
5921}
5922
5923/// #3536: each type a unit the suite's target consumes exports, with that unit,
5924/// leaving out the names the target (or a commons it `uses`) or the suite
5925/// declares itself, which win.
5926fn suite_import_owners(
5927    suite: &SuiteDecl,
5928    target: &str,
5929    unit_tables: &HashMap<String, UnitTable>,
5930    unit_uses: &HashMap<String, Vec<String>>,
5931    unit_consumes: &HashMap<String, Vec<String>>,
5932) -> std::collections::BTreeMap<String, String> {
5933    let own = |n: &String| {
5934        unit_tables
5935            .get(target)
5936            .is_some_and(|t| t.types.contains_key(n))
5937            || unit_uses
5938                .get(target)
5939                .into_iter()
5940                .flatten()
5941                .any(|u| unit_tables.get(u).is_some_and(|t| t.types.contains_key(n)))
5942            || suite.types.iter().any(|t| t.name.name == *n)
5943    };
5944    let mut owners = std::collections::BTreeMap::new();
5945    for unit in unit_consumes.get(target).into_iter().flatten() {
5946        let Some(table) = unit_tables.get(unit) else {
5947            continue;
5948        };
5949        // Two consumed units exporting one name is a clash the target itself
5950        // reports; here the first unit owns it, so a suite that consumes the
5951        // other's version is reported (a rare edge, listed as open in ADR 0849).
5952        for name in table.types.keys().filter(|n| !own(n)) {
5953            owners.entry(name.clone()).or_insert_with(|| unit.clone());
5954        }
5955    }
5956    owners
5957}
5958
5959/// The project's unit tables, `uses`, `consumes` and `consumes` aliases.
5960type ProjectMaps<'a> = (
5961    &'a HashMap<String, UnitTable>,
5962    &'a HashMap<String, Vec<String>>,
5963    &'a HashMap<String, Vec<String>>,
5964    &'a HashMap<String, HashMap<String, String>>,
5965);
5966
5967/// What a target hides behind its own values: the shadowed imports, and the
5968/// target's types.
5969type TargetShadowed = (
5970    HashMap<String, crate::resolver::ShadowedImport>,
5971    HashMap<String, Arc<TypeDecl>>,
5972);
5973
5974/// The naming gates a unit suite goes through before its cases are checked: a
5975/// type reached only through an imported declaration is hidden (#1814), one the
5976/// target hides behind its own value is shadowed (#1927), and (#3536) a type,
5977/// capability or service the suite's own `consumes` does not bring in is an error.
5978fn suite_naming_errors(
5979    suite: &SuiteDecl,
5980    pf: &ParsedFile,
5981    target: &str,
5982    maps: ProjectMaps<'_>,
5983    (hidden, shadowed): (&std::collections::BTreeMap<String, String>, &TargetShadowed),
5984) -> Vec<CompileError> {
5985    let mut errors = resolver::check_hidden_type_names_in_suite(suite, Some(target), hidden);
5986    errors.extend(resolver::check_shadowed_type_names_in_suite(
5987        suite,
5988        &shadowed.0,
5989        &shadowed.1,
5990    ));
5991    errors.extend(check_unselected_suite_imports(
5992        suite,
5993        pf,
5994        target,
5995        maps,
5996        &shadowed.1,
5997    ));
5998    errors
5999}
6000
6001/// #3536: [`check_unselected_suite_types`] for the suite `suite` of `target`,
6002/// reading what it consumes from the project's maps (tables, `uses`,
6003/// `consumes`, aliases).
6004fn check_unselected_suite_imports(
6005    suite: &SuiteDecl,
6006    pf: &ParsedFile,
6007    target: &str,
6008    maps: ProjectMaps<'_>,
6009    types: &HashMap<String, Arc<TypeDecl>>,
6010) -> Vec<CompileError> {
6011    let (unit_tables, unit_uses, unit_consumes, unit_consumes_aliases) = maps;
6012    let owners = suite_import_owners(suite, target, unit_tables, unit_uses, unit_consumes);
6013    let consumed = unit_consumes.get(target).map_or(&[][..], Vec::as_slice);
6014    let none = HashMap::new();
6015    let caps = unit_tables.get(target).map_or(&none, |t| &t.flattened_caps);
6016    let aliases = unit_consumes_aliases.get(target).unwrap_or(&none);
6017    check_unselected_suite_types(suite, pf, &owners, types, consumed, caps, aliases)
6018}
6019
6020/// #3536: `bynk.consumes.type_not_selected` for a suite file: its own `consumes`
6021/// clauses are what bring a name from another unit into scope, not the target's.
6022fn check_unselected_suite_types(
6023    suite: &SuiteDecl,
6024    pf: &ParsedFile,
6025    owners: &std::collections::BTreeMap<String, String>,
6026    types: &HashMap<String, Arc<TypeDecl>>,
6027    consumed: &[String],
6028    caps: &HashMap<String, String>,
6029    aliases: &HashMap<String, String>,
6030) -> Vec<CompileError> {
6031    let consumed: std::collections::BTreeSet<String> = consumed.iter().cloned().collect();
6032    let file = resolver::FileConsumes {
6033        consumed: &consumed,
6034        // A suite-side alias (`consumes x { T as U }`) is not modelled in the
6035        // first stage: an alias names a type of the target's table, so naming
6036        // one in a suite is not reported. A follow-up if suites may alias.
6037        aliases: &HashMap::new(),
6038        clauses: &suite.consumes,
6039        insert_at: new_suite_consumes_position(suite, pf.source()),
6040    };
6041    let mut found = resolver::check_unselected_type_names_in_suite(suite, owners, types, &file);
6042    let caps = caps.iter().map(|(n, o)| (n.clone(), o.clone())).collect();
6043    found.extend(resolver::check_unselected_capabilities_in_suite(
6044        suite, &caps, &file,
6045    ));
6046    let prefixes = consumed
6047        .iter()
6048        .map(|u| (u.clone(), u.clone()))
6049        .chain(aliases.iter().map(|(a, u)| (a.clone(), u.clone())))
6050        .collect();
6051    found.extend(resolver::check_unconsumed_unit_calls_in_suite(
6052        suite, &prefixes, &file,
6053    ));
6054    found
6055}
6056
6057/// Where a `consumes` line a suite lacks is inserted: after its last `uses` or
6058/// `consumes`, else after its `suite <target> [as <tier>]` header
6059/// ([`resolver::new_consumes_position`]).
6060fn new_suite_consumes_position(suite: &SuiteDecl, source: &str) -> Option<(usize, String)> {
6061    let last = suite
6062        .uses
6063        .iter()
6064        .map(|u| u.span.end)
6065        .chain(suite.consumes.iter().map(|c| c.span.end))
6066        .max();
6067    let mut end = suite.target.span.end;
6068    let rest = source.get(end..)?;
6069    let after_blank = rest.trim_start_matches([' ', '\t']);
6070    if let Some(tier) = after_blank
6071        .strip_prefix("as")
6072        .filter(|t| t.starts_with([' ', '\t']))
6073    {
6074        let word = tier.trim_start_matches([' ', '\t']);
6075        let len = word
6076            .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
6077            .unwrap_or(word.len());
6078        end = source.len() - word.len() + len;
6079    }
6080    let braced = suite.form == CommonsForm::Brace;
6081    resolver::new_consumes_position(source, last, end, braced)
6082}
6083
6084#[cfg(test)]
6085mod tests {
6086    use super::*;
6087
6088    /// The body of `service svc`'s single handler in a parsed context.
6089    fn handler_body(src: &str) -> Block {
6090        let tokens = bynk_syntax::lexer::tokenize(src).expect("lex");
6091        let unit = bynk_syntax::parser::parse_unit(&tokens, src).expect("parse");
6092        let SourceUnit::Context(ctx) = unit else {
6093            panic!("expected a context unit");
6094        };
6095        ctx.items
6096            .into_iter()
6097            .find_map(|item| match item {
6098                bynk_syntax::ast::CommonsItem::Service(s) => s.handlers.into_iter().next(),
6099                _ => None,
6100            })
6101            .expect("a service handler")
6102            .body
6103    }
6104
6105    const SRC: &str = "context demo\n\
6106        service svc {\n\
6107          on call(n: Int) -> Effect[Int] by Caller {\n\
6108            let a <- first(n)\n\
6109            let b = if n > 0 { let c = second(n)\n c } else { third(n) }\n\
6110            fourth(a + b)\n\
6111          }\n\
6112        }\n";
6113
6114    /// #1740 review: the walk is in source order (it used to run bottom-up), so
6115    /// "the first cross-context call" and the order errors are reported in
6116    /// both read top to bottom.
6117    #[test]
6118    fn exprs_in_order_is_source_order() {
6119        let body = handler_body(SRC);
6120        let calls: Vec<&str> = exprs_in_order(&body)
6121            .into_iter()
6122            .filter_map(|e| match &e.kind {
6123                ExprKind::Call { name, .. } => Some(name.name.as_str()),
6124                _ => None,
6125            })
6126            .collect();
6127        assert_eq!(calls, ["first", "second", "third", "fourth"]);
6128    }
6129
6130    /// `blocks_deep` reaches a block nested in an `if` branch, so a `let` there
6131    /// (an agent binding, or a name that shadows a service) is seen.
6132    #[test]
6133    fn blocks_deep_reaches_nested_lets() {
6134        let body = handler_body(SRC);
6135        let lets: Vec<String> = blocks_deep(&body)
6136            .iter()
6137            .flat_map(|b| &b.statements)
6138            .filter_map(|s| match s {
6139                Statement::Let(l) | Statement::EffectLet(l) => Some(l.name.name.clone()),
6140                _ => None,
6141            })
6142            .collect();
6143        assert!(lets.contains(&"c".to_string()), "{lets:?}");
6144        assert!(lets.contains(&"a".to_string()) && lets.contains(&"b".to_string()));
6145    }
6146
6147    /// The context of negative fixture `388_credential_needs_system`.
6148    const CART_API: &str = "context shop.api
6149
6150type UserId = String where NonEmpty
6151actor User { auth = Bearer(secret = \"AUTH_SECRET\"), identity = UserId }
6152
6153type Item = { sku: String }
6154
6155service api from http {
6156  on POST(\"/cart\") (body: Item) -> Effect[HttpResult[Item]] by u: User {
6157    Created(body)
6158  }
6159}
6160";
6161
6162    fn nobody_case(body: &str) -> crate::testkit::Analysed {
6163        crate::testkit::analyse(&[
6164            ("shop/api.bynk", CART_API),
6165            (
6166                "shop/tests/api.test.bynk",
6167                &format!(
6168                    "suite shop.api as system {{\n  case \"c\" as unit {{\n{body}\n  }}\n}}\n"
6169                ),
6170            ),
6171        ])
6172    }
6173
6174    #[test]
6175    fn a_unit_case_calling_by_nobody_needs_system() {
6176        nobody_case(
6177            "    let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by Nobody\n    expect r is Rejected(Unauthorized)",
6178        )
6179        .assert_reports("bynk.test.credential_needs_system");
6180    }
6181
6182    /// #2135: a `Signature`-secured context, for the bad-signature principals.
6183    const HOOKS: &str = "context pay.hooks
6184
6185actor Processor { auth = Signature(secret = \"HOOK\", header = \"X-Sig\", timestamp = \"X-Ts\", tolerance = 300) }
6186
6187service webhooks from http {
6188  on POST(\"/hook\") (body: String) -> Effect[HttpResult[String]] by Processor {
6189    Ok(body)
6190  }
6191}
6192
6193service jobs {
6194  on call(n: Int) -> Effect[Int] by Caller { Effect.pure(n) }
6195}
6196";
6197
6198    fn hooks_case(tier: &str, body: &str) -> crate::testkit::Analysed {
6199        crate::testkit::analyse(&[
6200            ("pay/hooks.bynk", HOOKS),
6201            (
6202                "pay/tests/hooks.test.bynk",
6203                &format!("suite pay.hooks{tier} {{\n  case \"c\" {{\n{body}\n  }}\n}}\n"),
6204            ),
6205        ])
6206    }
6207
6208    /// #2155: a `Signature` actor with a timestamp but no tolerance, a sum
6209    /// with a `Signature` member, and a sum with none.
6210    const SUMS: &str = "context pay.sums
6211
6212type UserId = String where NonEmpty
6213
6214actor User { auth = Bearer(secret = \"AUTH\"), identity = UserId }
6215
6216actor Untimed { auth = Signature(secret = \"HOOK\", header = \"X-Sig\", timestamp = \"X-Ts\") }
6217
6218actor Timed { auth = Signature(secret = \"HOOK\", header = \"X-Sig\", timestamp = \"X-Ts\", tolerance = 300) }
6219
6220service api from http {
6221  on POST(\"/untimed\") (body: String) -> Effect[HttpResult[String]] by Untimed {
6222    Ok(body)
6223  }
6224
6225  on POST(\"/mixed\") (body: String) -> Effect[HttpResult[String]] by who: User | Timed {
6226    match who {
6227      User(u) => Ok(u)
6228      Timed => Ok(body)
6229    }
6230  }
6231
6232  on POST(\"/open\") (body: String) -> Effect[HttpResult[String]] by who: Timed | Visitor {
6233    match who {
6234      Timed => Ok(body)
6235      Visitor => Ok(\"stranger\")
6236    }
6237  }
6238
6239  on GET(\"/greet\") () -> Effect[HttpResult[String]] by who: User | Visitor {
6240    match who {
6241      User(u) => Ok(u)
6242      Visitor => Ok(\"stranger\")
6243    }
6244  }
6245}
6246";
6247
6248    fn sums_case(body: &str) -> crate::testkit::Analysed {
6249        crate::testkit::analyse(&[
6250            ("pay/sums.bynk", SUMS),
6251            (
6252                "pay/tests/sums.test.bynk",
6253                &format!("suite pay.sums as system {{\n  case \"c\" {{\n{body}\n  }}\n}}\n"),
6254            ),
6255        ])
6256    }
6257
6258    #[test]
6259    fn a_stale_call_needs_a_tolerance_not_just_a_timestamp() {
6260        sums_case(
6261            "    let r <- api.POST(\"/untimed\", \"x\") by Stale\n    expect r is Rejected(Unauthorized)",
6262        )
6263        .assert_reports("bynk.test.stale_needs_timestamp");
6264    }
6265
6266    #[test]
6267    fn forged_stale_and_nobody_are_admitted_on_a_sum_with_a_signature_member() {
6268        sums_case(
6269            "    let a <- api.POST(\"/mixed\", \"x\") by Forged\n    let b <- api.POST(\"/mixed\", \"x\") by Stale\n    let c <- api.POST(\"/mixed\", \"x\") by Nobody\n    expect a is Rejected(Unauthorized)\n    expect b is Rejected(Unauthorized)\n    expect c is Rejected(Unauthorized)",
6270        )
6271        .assert_clean();
6272    }
6273
6274    /// A sum with `Visitor` resolves a bad or missing credential as
6275    /// `Visitor`, so its seam never answers `401`.
6276    #[test]
6277    fn forged_and_stale_are_refused_on_a_sum_with_visitor() {
6278        for who in ["Forged", "Stale"] {
6279            sums_case(&format!(
6280                "    let r <- api.POST(\"/open\", \"x\") by {who}\n    expect r is Rejected(Unauthorized)"
6281            ))
6282            .assert_reports("bynk.test.forged_needs_signature_route");
6283        }
6284    }
6285
6286    #[test]
6287    fn nobody_is_refused_on_a_sum_with_visitor() {
6288        sums_case(
6289            "    let r <- api.GET(\"/greet\") by Nobody\n    expect r is Rejected(Unauthorized)",
6290        )
6291        .assert_reports("bynk.test.nobody_needs_secured_route");
6292        sums_case(
6293            "    let r <- api.POST(\"/open\", \"x\") by Nobody\n    expect r is Rejected(Unauthorized)",
6294        )
6295        .assert_reports("bynk.test.nobody_needs_secured_route");
6296    }
6297
6298    #[test]
6299    fn a_forged_call_needs_a_signature_member_on_a_sum() {
6300        sums_case(
6301            "    let r <- api.GET(\"/greet\") by Forged\n    expect r is Rejected(Unauthorized)",
6302        )
6303        .assert_reports("bynk.test.forged_needs_signature_route");
6304    }
6305
6306    #[test]
6307    fn an_expired_call_is_refused_off_a_bearer_route() {
6308        sums_case(
6309            "    let r <- api.POST(\"/mixed\", \"x\") by Expired\n    expect r is Rejected(Unauthorized)",
6310        )
6311        .assert_clean();
6312        for route in ["/untimed", "/open"] {
6313            sums_case(&format!(
6314                "    let r <- api.POST(\"{route}\", \"x\") by Expired\n    expect r is Rejected(Unauthorized)"
6315            ))
6316            .assert_reports("bynk.test.expired_needs_bearer_route");
6317        }
6318        hooks_case(" as system", "    let r <- webhooks.POST(\"/hook\", \"x\") by Expired\n    expect r is Rejected(Unauthorized)")
6319            .assert_reports("bynk.test.expired_needs_bearer_route");
6320        hooks_case(
6321            " as system",
6322            "    let r <- jobs.call(1) by Expired\n    expect r == 1",
6323        )
6324        .assert_reports("bynk.test.expired_needs_bearer_route");
6325    }
6326
6327    #[test]
6328    fn an_expired_call_at_unit_needs_system() {
6329        hooks_case(
6330            "",
6331            "    let r <- webhooks.POST(\"/hook\", \"x\") by Expired\n    expect r is Rejected(Unauthorized)",
6332        )
6333        .assert_reports("bynk.test.forged_needs_system");
6334    }
6335
6336    #[test]
6337    fn a_forged_fault_claim_below_system_is_refused() {
6338        hooks_case(
6339            "",
6340            "    expect webhooks.POST(\"/hook\", \"x\") by Forged faults",
6341        )
6342        .assert_reports("bynk.test.faults_needs_in_process");
6343    }
6344
6345    #[test]
6346    fn a_stale_call_at_unit_needs_system() {
6347        hooks_case(
6348            "",
6349            "    let r <- webhooks.POST(\"/hook\", \"x\") by Stale\n    expect r is Rejected(Unauthorized)",
6350        )
6351        .assert_reports("bynk.test.forged_needs_system");
6352    }
6353
6354    #[test]
6355    fn a_forged_call_service_needs_a_signature_route() {
6356        hooks_case("", "    let r <- jobs.call(1) by Forged\n    expect r == 1")
6357            .assert_reports("bynk.test.forged_needs_signature_route");
6358    }
6359
6360    #[test]
6361    fn a_by_nobody_nested_in_a_block_needs_system_too() {
6362        // #1849: only the top-level statements used to be searched.
6363        nobody_case(
6364            "    let ok = if true {\n      let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by Nobody\n      r is Rejected(Unauthorized)\n    } else { false }\n    expect ok",
6365        )
6366        .assert_reports("bynk.test.credential_needs_system");
6367    }
6368}
6369
6370/// #1934: a case's service call is typed by what its handler yields
6371/// (re-opening ADR 0203), and a `system`-tier call that reaches past the
6372/// handler's types by what the wire yields.
6373#[cfg(test)]
6374mod typed_outcome_tests {
6375    const API: &str = "context app.web
6376
6377type Item = { sku: String }
6378
6379service api from http {
6380  on GET(\"/x\") () -> Effect[HttpResult[()]] by Visitor {
6381    Raw(Bytes.fromUtf8(\"hi\"), \"text/plain\")
6382  }
6383  on GET(\"/name\") () -> Effect[HttpResult[String]] by Visitor {
6384    Ok(\"ada\")
6385  }
6386  on GET(\"/item\") () -> Effect[HttpResult[Item]] by Visitor {
6387    Ok(Item { sku: \"w\" })
6388  }
6389}
6390
6391service calc {
6392  on call(n: Int) -> Effect[Int] by Caller {
6393    n
6394  }
6395}
6396
6397service sweeper from cron {
6398  on schedule(\"0 0 * * *\") () -> Effect[Result[(), String]] {
6399    Ok(())
6400  }
6401}
6402
6403service intake from queue(\"orders\") {
6404  on message(item: Item) -> Effect[QueueResult] {
6405    Ack
6406  }
6407}
6408";
6409
6410    fn case(body: &str) -> crate::testkit::Analysed {
6411        crate::testkit::analyse(&[
6412            ("app/web.bynk", API),
6413            (
6414                "app/tests/web.test.bynk",
6415                &format!("suite app.web {{\n  case \"c\" {{\n{body}\n  }}\n}}\n"),
6416            ),
6417        ])
6418    }
6419
6420    /// The case of #1931 and #1934: a method on a value of the handler's
6421    /// result type checks, and a wrong one is reported against that type.
6422    #[test]
6423    fn an_http_outcome_has_the_handlers_result_type() {
6424        let get = "    let r <- api.GET(\"/name\") by Visitor\n";
6425        case(&format!("{get}    match r {{\n      Ok(v) => expect v.length() == 3\n      _ => expect false\n    }}"))
6426            .assert_clean();
6427        case(&format!("{get}    match r {{\n      Ok(v) => expect v.nosuch() == 3\n      _ => expect false\n    }}"))
6428            .assert_reports("bynk.types.method_not_found");
6429        case(&format!(
6430            "{get}    expect r is Ok(v) && v.startsWith(\"a\")"
6431        ))
6432        .assert_clean();
6433        case(&format!("{get}    expect r == Ok(\"ada\")")).assert_clean();
6434        let item = "    let r <- api.GET(\"/item\") by Visitor\n";
6435        case(&format!(
6436            "{item}    expect r is Ok(i) && i.sku.length() == 1"
6437        ))
6438        .assert_clean();
6439        case(&format!("{item}    expect r is Ok(i) && i.nosuch == 1"))
6440            .assert_reports("bynk.types.unknown_field");
6441    }
6442
6443    /// A payload of fixed type binds it, as before; the arms are checked by
6444    /// the ordinary rules.
6445    #[test]
6446    fn fixed_payloads_and_arms_are_checked() {
6447        let get = "    let r <- api.GET(\"/x\") by Visitor\n";
6448        case(&format!("{get}    match r {{\n      Raw(body, ct) => expect body.length() == 2 && ct.startsWith(\"text/\")\n      _ => expect false\n    }}"))
6449            .assert_clean();
6450        case(&format!("{get}    match r {{\n      Raw(_, _) => expect nope == 1\n      _ => expect false\n    }}"))
6451            .assert_reports("bynk.resolve.unknown_name");
6452        case(&format!("{get}    match r {{\n      BadRequest(m) | NotFound => expect m.length() == 9\n      _ => expect false\n    }}"))
6453            .assert_reports("bynk.types.or_pattern_binding_mismatch");
6454        case(&format!("{get}    expect r is Bogus(_)"))
6455            .assert_reports("bynk.types.is_unknown_variant");
6456    }
6457
6458    /// An `on call` handler's return type is what the case binds.
6459    #[test]
6460    fn a_call_outcome_has_the_handlers_return_type() {
6461        case("    let n <- calc.call(2)\n    expect n.abs() == 2").assert_clean();
6462        case("    let n <- calc.call(2)\n    expect n.length() == 2")
6463            .assert_reports("bynk.types.method_not_found");
6464    }
6465
6466    /// cron and queue handlers are typed by their return types too, so a
6467    /// queue verdict is matchable.
6468    #[test]
6469    fn cron_and_queue_outcomes_are_typed() {
6470        case("    let r <- sweeper.schedule(\"0 0 * * *\")\n    match r {\n      Ok(_) => expect true\n      Err(e) => expect e.length() > 0\n    }")
6471            .assert_clean();
6472        case("    let r <- intake.message(Item { sku: \"x\" })\n    expect r is Ack")
6473            .assert_clean();
6474        case("    let r <- intake.message(Item { sku: \"x\" })\n    match r {\n      Retry(why) => expect why.length() > 0\n      Ack => expect true\n    }")
6475            .assert_clean();
6476        case("    let r <- intake.message(Item { sku: \"x\" })\n    expect r is Ok(_)")
6477            .assert_reports("bynk.types.is_unknown_variant");
6478    }
6479
6480    /// The context of `385_system_wire_rejection`, cut down.
6481    const CART_API: &str = "context shop.api
6482
6483type UserId = String where NonEmpty
6484actor User { auth = Bearer(secret = \"AUTH_SECRET\"), identity = UserId }
6485
6486type Item = { sku: String }
6487
6488service api from http {
6489  on POST(\"/cart\") (body: Item) -> Effect[HttpResult[Item]] by u: User {
6490    Created(body)
6491  }
6492}
6493";
6494
6495    fn system_case(body: &str) -> crate::testkit::Analysed {
6496        crate::testkit::analyse(&[
6497            ("shop/api.bynk", CART_API),
6498            (
6499                "shop/tests/api.test.bynk",
6500                &format!("suite shop.api as system {{\n  case \"c\" {{\n{body}\n  }}\n}}\n"),
6501            ),
6502        ])
6503    }
6504
6505    /// A typed `system`-tier call decodes the handler's `HttpResult`.
6506    #[test]
6507    fn a_typed_system_call_is_the_handlers_result() {
6508        system_case("    let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by User(\"a\")\n    expect r is Created(i) && i.sku == \"w\"")
6509            .assert_clean();
6510        system_case("    let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by User(\"a\")\n    expect r is Rejected(_)")
6511            .assert_reports("bynk.types.is_unknown_variant");
6512    }
6513
6514    /// `Wire`, `by Nobody` and a wrong method observe the boundary, so they
6515    /// yield an `HttpOutcome`: its kinds are checked, and `Handled` carries
6516    /// the handler's `HttpResult`.
6517    #[test]
6518    fn a_call_past_the_handlers_types_is_an_http_outcome() {
6519        let wire = "    let r <- api.POST(\"/cart\", Wire(\"{}\")) by User(\"a\")\n";
6520        system_case(&format!("{wire}    match r {{\n      Rejected(RefinementViolation(d)) => expect d.length() > 0\n      Rejected(_) => expect false\n      Handled(Created(i)) => expect i.sku == \"w\"\n      Handled(_) => expect false\n    }}"))
6521            .assert_clean();
6522        system_case(&format!("{wire}    match r {{\n      Rejected(Unauthorized(d)) => expect true\n      _ => expect false\n    }}"))
6523            .assert_reports("bynk.types.pattern_arity");
6524        system_case(&format!("{wire}    expect r is Rejected(Refinement(_))"))
6525            .assert_reports("bynk.types.unknown_variant_in_pattern");
6526        system_case(&format!("{wire}    expect r is Created(_)"))
6527            .assert_reports("bynk.types.is_unknown_variant");
6528        system_case("    let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by Nobody\n    expect r is Rejected(Unauthorized)")
6529            .assert_clean();
6530        // Both at once (the raw no-auth driver) is still an `HttpOutcome`.
6531        system_case("    let r <- api.POST(\"/cart\", Wire(\"{}\")) by Nobody\n    expect r is Rejected(Unauthorized)")
6532            .assert_clean();
6533        system_case(
6534            "    let r <- api.POST(\"/cart\", Wire(\"{}\")) by Nobody\n    expect r is Created(_)",
6535        )
6536        .assert_reports("bynk.types.is_unknown_variant");
6537        system_case(
6538            "    let r <- api.DELETE(\"/cart\")\n    expect r is Rejected(MethodNotAllowed)",
6539        )
6540        .assert_clean();
6541        system_case("    let r <- api.DELETE(\"/cart\")\n    expect r is NotFound")
6542            .assert_reports("bynk.types.is_unknown_variant");
6543    }
6544}
6545
6546#[cfg(test)]
6547mod participant_tests {
6548    use super::*;
6549
6550    /// `(publisher, event)` → its subscribers, as
6551    /// `symbols::discover_event_subscribers` builds it.
6552    type Subscribers = BTreeMap<(String, String), Vec<(String, String)>>;
6553
6554    /// `ops.hub` consumes `ops.store` and the `bynk` adapter, and publishes
6555    /// `Ping`. `ops.audit` subscribes to it and consumes `ops.archive`, a
6556    /// context outside `ops.hub`'s closure. `ops.store` publishes `Saved`, to
6557    /// which `ops.mirror` subscribes, and `ops.audit` publishes `Noted`, to
6558    /// which `ops.digest` subscribes.
6559    fn project() -> (
6560        HashMap<String, Vec<String>>,
6561        BTreeMap<String, UnitKind>,
6562        Subscribers,
6563    ) {
6564        let edges = [
6565            ("ops.hub", &["ops.store", "bynk"][..]),
6566            ("ops.audit", &["ops.hub", "ops.archive"][..]),
6567            ("ops.mirror", &["ops.store"][..]),
6568            ("ops.digest", &["ops.audit"][..]),
6569        ];
6570        let unit_consumes = edges
6571            .iter()
6572            .map(|(u, ds)| (u.to_string(), ds.iter().map(|d| d.to_string()).collect()))
6573            .collect();
6574        let mut kinds: BTreeMap<String, UnitKind> = [
6575            "ops.hub",
6576            "ops.store",
6577            "ops.audit",
6578            "ops.archive",
6579            "ops.mirror",
6580            "ops.digest",
6581        ]
6582        .iter()
6583        .map(|c| (c.to_string(), UnitKind::Context))
6584        .collect();
6585        kinds.insert("bynk".to_string(), UnitKind::Adapter);
6586        let sub = |owner: &str, event: &str, ctx: &str| {
6587            (
6588                (owner.to_string(), event.to_string()),
6589                vec![(ctx.to_string(), "On".to_string())],
6590            )
6591        };
6592        let subscribers = [
6593            sub("ops.hub", "Ping", "ops.audit"),
6594            sub("ops.store", "Saved", "ops.mirror"),
6595            sub("ops.audit", "Noted", "ops.digest"),
6596        ]
6597        .into_iter()
6598        .collect();
6599        (unit_consumes, kinds, subscribers)
6600    }
6601
6602    /// A case reaches the target's `consumes` closure: contexts only, the
6603    /// target first.
6604    #[test]
6605    fn participants_are_the_consumes_closure() {
6606        let (consumes, kinds, _) = project();
6607        assert_eq!(
6608            infer_participants("ops.hub", &consumes, &kinds),
6609            ["ops.hub", "ops.store"]
6610        );
6611    }
6612
6613    /// #1959: the harness also stands up the target's subscriber and its own
6614    /// closure (`ops.archive`), a non-target participant's subscriber
6615    /// (`ops.mirror`), and a subscriber's subscriber (`ops.digest`).
6616    #[test]
6617    fn the_harness_adds_subscribers_and_their_closures_transitively() {
6618        let (consumes, kinds, subscribers) = project();
6619        assert_eq!(
6620            infer_harness_participants("ops.hub", &consumes, &kinds, &subscribers),
6621            [
6622                "ops.hub",
6623                "ops.store",
6624                "ops.audit",
6625                "ops.mirror",
6626                "ops.archive",
6627                "ops.digest"
6628            ]
6629        );
6630    }
6631
6632    /// With no subscribers the two sets agree.
6633    #[test]
6634    fn without_subscribers_the_harness_is_the_case_set() {
6635        let (consumes, kinds, _) = project();
6636        assert_eq!(
6637            infer_harness_participants("ops.hub", &consumes, &kinds, &BTreeMap::new()),
6638            infer_participants("ops.hub", &consumes, &kinds)
6639        );
6640    }
6641}
6642
6643/// #2018: the `is`-pattern comparison the history restate check uses. It is
6644/// conservative: only literals and payload-free variants (same name, same
6645/// optional qualifier) are equal; anything else compares unequal.
6646#[cfg(test)]
6647mod history_pattern_tests {
6648    use super::*;
6649
6650    fn ident(name: &str) -> Ident {
6651        Ident {
6652            name: name.to_string(),
6653            span: Span::default(),
6654        }
6655    }
6656
6657    fn variant(type_name: Option<&str>, name: &str) -> Pattern {
6658        Pattern::Variant {
6659            type_name: type_name.map(ident),
6660            variant: ident(name),
6661            bindings: Vec::new(),
6662            span: Span::default(),
6663        }
6664    }
6665
6666    fn payload_variant(name: &str) -> Pattern {
6667        Pattern::Variant {
6668            type_name: None,
6669            variant: ident(name),
6670            bindings: vec![PatternBinding {
6671                kind: PatternBindingKind::Positional {
6672                    pattern: Pattern::Wildcard(Span::default()),
6673                },
6674                span: Span::default(),
6675            }],
6676            span: Span::default(),
6677        }
6678    }
6679
6680    fn int(n: i64) -> Pattern {
6681        Pattern::Literal {
6682            value: LiteralValue::Int(n),
6683            text: None,
6684            span: Span::default(),
6685        }
6686    }
6687
6688    #[test]
6689    fn same_payload_free_variant_matches() {
6690        assert!(history_pattern_matches(
6691            &variant(None, "Closed"),
6692            &variant(None, "Closed")
6693        ));
6694        assert!(history_pattern_matches(
6695            &variant(Some("Status"), "Closed"),
6696            &variant(Some("Status"), "Closed")
6697        ));
6698    }
6699
6700    #[test]
6701    fn different_variant_names_do_not_match() {
6702        assert!(!history_pattern_matches(
6703            &variant(None, "Open"),
6704            &variant(None, "Closed")
6705        ));
6706    }
6707
6708    #[test]
6709    fn qualifier_present_vs_absent_does_not_match() {
6710        assert!(!history_pattern_matches(
6711            &variant(Some("Status"), "Closed"),
6712            &variant(None, "Closed")
6713        ));
6714        assert!(!history_pattern_matches(
6715            &variant(None, "Closed"),
6716            &variant(Some("Status"), "Closed")
6717        ));
6718        assert!(!history_pattern_matches(
6719            &variant(Some("Status"), "Closed"),
6720            &variant(Some("Other"), "Closed")
6721        ));
6722    }
6723
6724    #[test]
6725    fn literals_match_by_value() {
6726        assert!(history_pattern_matches(&int(3), &int(3)));
6727        assert!(!history_pattern_matches(&int(3), &int(4)));
6728        assert!(!history_pattern_matches(&int(3), &variant(None, "Closed")));
6729    }
6730
6731    #[test]
6732    fn payload_variant_never_matches() {
6733        assert!(!history_pattern_matches(
6734            &payload_variant("Some"),
6735            &payload_variant("Some")
6736        ));
6737        assert!(!history_pattern_matches(
6738            &payload_variant("Some"),
6739            &variant(None, "Some")
6740        ));
6741    }
6742}
6743
6744/// #2052: the `svc.event(e)` address's checks that the fixtures don't pin
6745/// (a note's text) or that need a project shape of their own.
6746#[cfg(test)]
6747mod event_address_tests {
6748    use crate::testkit::analyse;
6749
6750    const ORDER: &str =
6751        "context shop.order\n\nexports transparent { Placed }\n\nevent Placed = { id: String }\n";
6752
6753    fn ledger(consumes: &str, extra: &str) -> String {
6754        format!(
6755            "context shop.ledger\n\n{consumes}\n{extra}\nservice OnPlaced from Events(Placed) {{\n  on event(e: Placed) -> Effect[()] {{\n    ()\n  }}\n}}\n"
6756        )
6757    }
6758
6759    fn suite(body: &str) -> String {
6760        format!("suite shop.ledger {{\n  case \"c\" {{\n{body}\n  }}\n}}\n")
6761    }
6762
6763    #[test]
6764    fn an_envelope_the_suite_cannot_name_notes_consumes_bynk() {
6765        let a = analyse(&[
6766            ("shop/order.bynk", ORDER),
6767            ("shop/ledger.bynk", &ledger("consumes shop.order", "")),
6768            (
6769                "shop/tests/ledger.test.bynk",
6770                &suite("    let _ <- OnPlaced.event(Placed { id: \"o1\" }, \"evt-1\")"),
6771            ),
6772        ]);
6773        let e = a
6774            .analysis
6775            .errors
6776            .iter()
6777            .find(|e| e.error.category == "bynk.types.argument_mismatch")
6778            .expect("an argument mismatch on the envelope");
6779        assert!(
6780            e.error
6781                .notes
6782                .iter()
6783                .any(|n| n.contains("must `consumes bynk`")),
6784            "expected the `consumes bynk` note, got {:?}",
6785            e.error.notes
6786        );
6787    }
6788
6789    #[test]
6790    fn a_same_named_event_outside_the_targets_scope_is_a_plain_mismatch() {
6791        // `shop.archive` declares an event `Note`, but the target doesn't
6792        // consume it; the target's own `Note` is a record, not an event.
6793        let a = analyse(&[
6794            ("shop/order.bynk", ORDER),
6795            (
6796                "shop/archive.bynk",
6797                "context shop.archive\n\nevent Note = { text: String }\n",
6798            ),
6799            (
6800                "shop/ledger.bynk",
6801                &ledger("consumes shop.order", "\ntype Note = { text: String }\n"),
6802            ),
6803            (
6804                "shop/tests/ledger.test.bynk",
6805                &suite("    let _ <- OnPlaced.event(Note { text: \"n\" })"),
6806            ),
6807        ]);
6808        a.assert_reports("bynk.types.argument_mismatch");
6809        assert!(
6810            !a.categories().contains(&"bynk.test.event_not_subscribed"),
6811            "a record named like an unconsumed context's event is not an event: {:?}",
6812            a.categories()
6813        );
6814    }
6815
6816    #[test]
6817    fn a_same_named_event_in_an_unconsumed_context_leaves_the_publisher_unique() {
6818        let a = analyse(&[
6819            ("shop/order.bynk", ORDER),
6820            (
6821                "shop/archive.bynk",
6822                "context shop.archive\n\nexports transparent { Placed }\n\nevent Placed = { id: String }\n",
6823            ),
6824            ("shop/ledger.bynk", &ledger("consumes shop.order", "")),
6825            (
6826                "shop/tests/ledger.test.bynk",
6827                // #3536: a suite consumes what it names.
6828                &suite("    let _ <- OnPlaced.event(Placed { id: \"o1\" })")
6829                    .replace("{\n  case", "{\n  consumes shop.order\n  case"),
6830            ),
6831        ]);
6832        a.assert_clean();
6833    }
6834
6835    #[test]
6836    fn two_consumed_publishers_refuse_a_default_envelope() {
6837        let a = analyse(&[
6838            ("shop/order.bynk", ORDER),
6839            (
6840                "shop/archive.bynk",
6841                "context shop.archive\n\nexports transparent { Placed }\n\nevent Placed = { id: String }\n",
6842            ),
6843            (
6844                "shop/ledger.bynk",
6845                &ledger("consumes shop.order\nconsumes shop.archive", ""),
6846            ),
6847            (
6848                "shop/tests/ledger.test.bynk",
6849                &suite("    let _ <- OnPlaced.event(Placed { id: \"o1\" })"),
6850            ),
6851        ]);
6852        a.assert_reports("bynk.test.event_publisher_ambiguous");
6853    }
6854}