Skip to main content

bynk_check/
unit_signature.rs

1//! P8.1 (#1512): `UnitId` and `UnitSignature` — the load-bearing types this
2//! whole phase's firewall (R3.14) is stated in terms of. `UnitSignature`
3//! projects a [`UnitTable`] into design notes §15's four required-annotation
4//! categories — cross-context types, fn signatures (free functions and
5//! methods), handler signatures plus storage, capability sets — with every
6//! body/body-adjacent field excluded ([DECISION B],
7//! `design/tracks/incrementality.md` §3.4/Q4) rather than merely ignored by
8//! the comparison: `body`/`requires`/`ensures` never reach [`FnSignature`],
9//! `body` never reaches [`HandlerSignature`], `init`/`annotations` never
10//! reach [`StoreFieldSignature`] — the type system, not a comparison
11//! function's own discipline, makes "no body reachable from `UnitSignature`"
12//! a fact.
13//!
14//! Stability is proved by comparing [`UnitSignature::canonical`], not the raw
15//! struct: every included fragment still carries its own `Span` (`Ident`,
16//! `Param`, every `TypeRef` variant, `TypeDecl`'s own `trivia`/
17//! `documentation`), and editing a body shifts every later declaration's own
18//! spans in the same file (the byte-offset cascade PR #1509's bot review
19//! caught one level up, in `UnitSignature`'s own design). [DECISION C]
20//! extends `contract.rs`'s `canon_type`/`service_normal_form` (ADR 0200) —
21//! already a span-free canonical rendering, proven correct by
22//! `contract_hash.rs`'s own no-false-positive fixture — to reach the new
23//! signature shapes here, rather than inventing a second erasure scheme.
24//!
25//! **The R3.14 firewall has two directions, and this module is responsible
26//! for both**: a body edit must not move [`UnitSignature::canonical`] (the
27//! exclusions above), and a genuine signature edit MUST move it — a false
28//! "unchanged" verdict silently skips recomputing every downstream
29//! consumer, the more expensive failure mode for an incrementality firewall.
30//! PR #1517's own bot review caught three real gaps on the second direction
31//! before this module first merged: [`HandlerKind`] was dropped entirely
32//! (so renaming an HTTP route or changing `on GET` to `on POST` didn't move
33//! the form), methods never reached [`UnitSignature`] at all (`UnitTable.fns`
34//! only holds free functions — `FnName::Method` is filed under
35//! `UnitTable.methods` instead, `symbols.rs:596-619`), and a `capability`
36//! declaration's own operation signatures (`CapabilityDecl.ops`, itself
37//! already body-free — "signature only; no body", `ast.rs:564`) were never
38//! projected, so retyping a capability op left every consumer's own
39//! `UnitSignature` unchanged even though its compiled contract with that
40//! capability's provider did change. All three are fixed here; see each
41//! type's own doc comment for what closed the gap.
42//!
43//! **Deliberately still excluded, named explicitly so a future reviewer
44//! doesn't have to re-derive it:** `ProviderDecl.provider_name` (an internal
45//! selector used only in tests/config to pick an implementation — never part
46//! of a `Cap.op(...)` call site, so it carries no information a consumer's
47//! own compile depends on) and handler-position annotations (`@cache`, …,
48//! `Handler.annotations: Vec<Annotation>`) — an `AnnotationArg.value` is an
49//! arbitrary `Expr`, and canonicalising `Expr` the way `canon_type` already
50//! does for `TypeRef` is real, unscoped work this slice does not take on;
51//! flagged for whichever future slice needs it, the same "flag for the slice
52//! that will actually pin it" discipline this phase has applied throughout.
53//! `ServiceProtocol::Events`'s own `pattern`/`schema_dispatch` fields (the
54//! structural payload filter and `via schema(N)` clause) are captured only
55//! as "present or absent", not rendered field-by-field, for the same
56//! Expr/pattern-canonicalisation reason — narrower than ideal, but strictly
57//! better than the pre-fix state where the whole protocol was invisible.
58//!
59//! [`unit_signature_for`]'s only caller is `tests/unit_signature_stability.rs`
60//! (P8.2), and that is deliberate: this module is R3.14's own *proof* — the
61//! firewall stated as a type and checked by a test — not a production path.
62//! Phase 8's two structural consumers-to-be (`ProjectGraph`, P8.3, and the
63//! `DefId`-keyed `Body`/`TypeOf` queries, P8.5) were built beside it and
64//! deleted on 2 September 2026 (#1537, ADR in that PR's pending file): nothing
65//! called them and no scheduler existed to. This module stays because
66//! R3.15's trigger (#1523 — keystroke-to-diagnostic latency *attributed by
67//! level*) presupposes a unit level to attribute to; the gated
68//! `incremental_query_types` probe certifies it is present and its
69//! stability test exists.
70
71use std::collections::{BTreeMap, BTreeSet, HashMap};
72use std::sync::Arc;
73
74use bynk_syntax::ast::{CapRef, Handler, HandlerKind, Param, ServiceProtocol, TypeDecl, TypeRef};
75
76use crate::symbols::UnitTable;
77
78/// [DECISION A]: a stable, hashable identity for a unit, reusing the
79/// unit-name `String` every `UnitTable`/`combined_types_for` caller already
80/// keys on today, rather than introducing a fresh interned-integer scheme —
81/// no `index_vec` crate (or hand-rolled equivalent) exists anywhere in this
82/// codebase, confirmed by grep. `UnitSignature` only needs `UnitId` to be a
83/// stable, hashable, comparable identity for R3.14's own proof; it does not
84/// need to be dense or `IndexVec`-compatible. P8.3 resolved the fork this
85/// left open by adapting `ProjectGraph` to the string-keyed `UnitId` (ADR
86/// 0415); that graph was deleted by #1537, so if R3.15's trigger ever fires,
87/// ADR 0415's recorded shape is what a rebuild adapts to — this type stays
88/// a string newtype either way.
89#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
90pub struct UnitId(pub String);
91
92/// [DECISION B]: [`Param`], body-free (it already is — kept as its own type
93/// only so [`FnSignature`]/[`HandlerSignature`] don't reach back into
94/// `bynk-syntax::ast::Param` and risk a future field being added there and
95/// silently flowing through unexamined).
96#[derive(Debug, Clone)]
97pub struct ParamSignature {
98    pub name: String,
99    pub type_ref: TypeRef,
100}
101
102fn param_signatures(params: &[Param]) -> Vec<ParamSignature> {
103    params
104        .iter()
105        .map(|p| ParamSignature {
106            name: p.name.name.clone(),
107            type_ref: p.type_ref.clone(),
108        })
109        .collect()
110}
111
112/// [DECISION B]: [`bynk_syntax::ast::FnDecl`], body-free. Excludes `body`,
113/// `requires`, `ensures` (all body-adjacent — `requires`/`ensures` scope over
114/// parameters and the result but are not part of design notes §15's own
115/// required-annotation list, per Q4) and `documentation`. Used for both free
116/// functions ([`UnitSignature::fns`]) and methods ([`UnitSignature::methods`]).
117#[derive(Debug, Clone)]
118pub struct FnSignature {
119    /// Each type parameter as written, bounds included (`T`, `T: Eq`): a bound
120    /// is part of what a caller must satisfy, so it is part of the signature.
121    pub type_params: Vec<String>,
122    /// The method's `where` entries, as written (`A: Eq`).
123    pub where_bounds: Vec<String>,
124    pub name: String,
125    pub params: Vec<ParamSignature>,
126    pub return_type: TypeRef,
127    pub has_self: bool,
128}
129
130/// `T` or `T: Eq + C`.
131fn bound_text(name: &str, bounds: &[bynk_syntax::ast::Ident]) -> String {
132    if bounds.is_empty() {
133        return name.to_string();
134    }
135    let names: Vec<&str> = bounds.iter().map(|b| b.name.as_str()).collect();
136    format!("{name}: {}", names.join(" + "))
137}
138
139fn fn_signature(name: &str, decl: &bynk_syntax::ast::FnDecl) -> FnSignature {
140    FnSignature {
141        type_params: decl
142            .type_params
143            .iter()
144            .map(|tp| bound_text(&tp.name.name, &tp.bounds))
145            .collect(),
146        where_bounds: decl
147            .where_bounds
148            .iter()
149            .map(|wb| bound_text(&wb.param.name, &wb.bounds))
150            .collect(),
151        name: name.to_string(),
152        params: param_signatures(&decl.params),
153        return_type: decl.return_type.clone(),
154        has_self: decl.has_self,
155    }
156}
157
158/// The `instance`/`statics` split PR #1517's bot review found missing
159/// entirely: `UnitTable.fns` (what [`UnitSignature::fns`] projects) only
160/// ever holds `FnName::Free` entries — `FnName::Method` is filed under
161/// `UnitTable.methods: HashMap<String, MethodTable>` instead
162/// (`symbols.rs:596-619`), keyed by the attached type's name, with instance
163/// and static methods in their own sub-maps (mirroring
164/// [`crate::resolver::MethodTable`]'s own shape exactly, rather than
165/// flattening into one map keyed by method name alone — an instance and a
166/// static method can share a name for the same type without colliding in
167/// `MethodTable` itself, so flattening here would silently drop one).
168#[derive(Debug, Clone, Default)]
169pub struct MethodTableSignature {
170    pub instance: BTreeMap<String, FnSignature>,
171    pub statics: BTreeMap<String, FnSignature>,
172}
173
174/// A closed, body-free mirror of [`HandlerKind`] — every field `HandlerKind`
175/// itself carries (`HttpMethod`, a route/cron-expression `String`) is already
176/// a plain value with nothing body-adjacent to exclude. PR #1517's own bot
177/// review: dropping this entirely let two handlers with the same params and
178/// return type but different HTTP methods or routes canonicalise identically
179/// — renaming a route is not a body edit, and R3.14's own firewall must
180/// treat it as a real signature change.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub enum HandlerKindSignature {
183    Call,
184    Http { method: String, path: String },
185    Cron { expr: String },
186    Message,
187    Open,
188    Close,
189    Event,
190    Rejected,
191}
192
193fn handler_kind_signature(k: &HandlerKind) -> HandlerKindSignature {
194    match k {
195        HandlerKind::Call => HandlerKindSignature::Call,
196        HandlerKind::Http { method, path } => HandlerKindSignature::Http {
197            method: method.as_str().to_string(),
198            path: path.clone(),
199        },
200        HandlerKind::Cron { expr } => HandlerKindSignature::Cron { expr: expr.clone() },
201        HandlerKind::Message => HandlerKindSignature::Message,
202        HandlerKind::Open => HandlerKindSignature::Open,
203        HandlerKind::Close => HandlerKindSignature::Close,
204        HandlerKind::Event => HandlerKindSignature::Event,
205        HandlerKind::Rejected => HandlerKindSignature::Rejected,
206    }
207}
208
209/// [DECISION B]: [`Handler`], body-free. Excludes `body`, `by_clause` (an
210/// actor binder, resolved at the call boundary rather than part of the
211/// wire-visible shape), `annotations` (see this module's own doc comment —
212/// deferred, needs `Expr` canonicalisation) and `documentation`. `given` is
213/// kept — it's this handler's own slice of the capability-set category.
214/// `kind` is kept (see [`HandlerKindSignature`]) — dropping it was PR
215/// #1517's own bot review finding #1.
216#[derive(Debug, Clone)]
217pub struct HandlerSignature {
218    pub kind: HandlerKindSignature,
219    pub method_name: Option<String>,
220    pub params: Vec<ParamSignature>,
221    pub return_type: TypeRef,
222    pub given: Vec<String>,
223}
224
225fn handler_signature(h: &Handler) -> HandlerSignature {
226    HandlerSignature {
227        kind: handler_kind_signature(&h.kind),
228        method_name: h.method_name.as_ref().map(|i| i.name.clone()),
229        params: param_signatures(&h.params),
230        return_type: h.return_type.clone(),
231        given: cap_ref_names(&h.given),
232    }
233}
234
235/// [DECISION B]: [`bynk_syntax::ast::StoreField`], body-free. Excludes `init`
236/// and `annotations` (both body-adjacent per Q4 — annotations govern the
237/// field's own storage behaviour, not its externally-relevant shape) and
238/// `documentation`.
239#[derive(Debug, Clone)]
240pub struct StoreFieldSignature {
241    pub name: String,
242    pub kind_head: String,
243    pub kind_args: Vec<TypeRef>,
244}
245
246/// A body-free mirror of [`bynk_syntax::ast::CapabilityOp`] — already
247/// "signature only; no body" in its own doc comment (`ast.rs:564`), so
248/// nothing here needs excluding beyond `documentation`/`span`/`trivia`.
249/// Added by PR #1517's own bot review (finding #3): a `capability`
250/// declaration's own ops are the abstract signature every consumer compiles
251/// its `Cap.op(...)` call sites against, not `ProviderDecl.ops` (which carry
252/// a real `body: Block` each — a provider's own implementation, correctly
253/// excluded, same as any other body).
254#[derive(Debug, Clone)]
255pub struct CapabilityOpSignature {
256    pub name: String,
257    pub type_params: Vec<String>,
258    pub params: Vec<ParamSignature>,
259    pub return_type: TypeRef,
260}
261
262/// The capability-set category (design notes §15's fourth): what a unit
263/// exports (`table.exported_capabilities`, already plain strings), what a
264/// unit itself declares (`table.capabilities`'s own op signatures — added by
265/// PR #1517's own bot review), and what each provider/service declares it
266/// needs (`given`/`default_given`). Every `CapRef` collapses to its rendered
267/// name (`context.capability`, or bare `capability` when local) — its own
268/// `Span` is dropped, matching every other category's span-erasure
269/// discipline.
270#[derive(Debug, Clone, Default)]
271pub struct CapabilitySignature {
272    pub exported: BTreeSet<String>,
273    /// Keyed by capability name (`table.capabilities`).
274    pub declared: BTreeMap<String, Vec<CapabilityOpSignature>>,
275    /// Keyed by the implemented capability's own name (`ProviderDecl.capability`).
276    pub provider_given: BTreeMap<String, Vec<String>>,
277    /// Keyed by service name (`ServiceDecl.default_given`).
278    pub service_given: BTreeMap<String, Vec<String>>,
279}
280
281/// A `CapRef`'s canonical name: `context.capability` when cross-context,
282/// bare `capability` when local. Spans are dropped — matching every other
283/// category's span-erasure discipline.
284fn cap_ref_name(c: &CapRef) -> String {
285    match &c.context {
286        Some(q) => format!("{}.{}", q.joined(), c.key()),
287        None => c.key().to_string(),
288    }
289}
290
291fn cap_ref_names(refs: &[CapRef]) -> Vec<String> {
292    refs.iter().map(cap_ref_name).collect()
293}
294
295/// A body-free mirror of [`ServiceProtocol`] — added by PR #1517's own bot
296/// review ("worth a look"): `from http` vs. `from queue(...)` vs.
297/// `from websocket(...)` changes a service's entire external surface, and
298/// nothing about that fact is a body or body-adjacent to a handler. `Events`'
299/// own `pattern`/`schema_dispatch` are collapsed to `bool` presence (see this
300/// module's own doc comment for why — deferred `Expr`/pattern
301/// canonicalisation) rather than dropped outright.
302///
303/// No `PartialEq`/`Eq` derive: `TypeRef` (used by `WebSocket`/`Events`) does
304/// not implement either — compare through [`crate::contract::canon_unit_signature`]'s
305/// own rendering, the same "compare the canonical form" posture
306/// [`UnitSignature`] itself takes.
307#[derive(Debug, Clone)]
308pub enum ProtocolSignature {
309    Call,
310    Http,
311    Cron,
312    Queue {
313        name: String,
314    },
315    /// `from email("addr")` (#3328): the claimed recipient address.
316    Email {
317        address: String,
318    },
319    WebSocket {
320        in_type: TypeRef,
321        out_type: TypeRef,
322    },
323    Events {
324        event_type: TypeRef,
325        has_pattern: bool,
326        has_schema_dispatch: bool,
327    },
328}
329
330fn protocol_signature(p: &ServiceProtocol) -> ProtocolSignature {
331    match p {
332        ServiceProtocol::Call => ProtocolSignature::Call,
333        ServiceProtocol::Http => ProtocolSignature::Http,
334        ServiceProtocol::Cron => ProtocolSignature::Cron,
335        ServiceProtocol::Queue { name } => ProtocolSignature::Queue { name: name.clone() },
336        ServiceProtocol::Email { address } => ProtocolSignature::Email {
337            address: address.clone(),
338        },
339        ServiceProtocol::WebSocket { in_type, out_type } => ProtocolSignature::WebSocket {
340            in_type: in_type.clone(),
341            out_type: out_type.clone(),
342        },
343        ServiceProtocol::Events {
344            event_type,
345            pattern,
346            schema_dispatch,
347        } => ProtocolSignature::Events {
348            event_type: event_type.clone(),
349            has_pattern: pattern.is_some(),
350            has_schema_dispatch: schema_dispatch.is_some(),
351        },
352    }
353}
354
355/// P8.1 (#1512): a unit's stable signature — everything about it that must
356/// survive an edit inside a function/handler body untouched (R3.14, the
357/// phase's firewall).
358///
359/// Deliberately does not derive `PartialEq`: two signatures compare equal
360/// through [`UnitSignature::canonical`] ([DECISION C]), not by structural
361/// equality on the raw fields — the same "compare the canonical form, not
362/// the raw AST value" shape `contract_hash.rs`'s own fixture already trusts
363/// for ADR 0200. Comparing the raw struct would reintroduce exactly the
364/// span-instability this type exists to erase.
365#[derive(Debug, Clone)]
366pub struct UnitSignature {
367    pub id: UnitId,
368    /// `combined_types_for`'s own output, reused unchanged ([DECISION A] of
369    /// ADR 0412, Q1) — the cross-context-types category.
370    pub combined_types: HashMap<String, Arc<TypeDecl>>,
371    /// Free functions only — keyed by `FnName`'s own rendered form, matching
372    /// `UnitTable.fns`'s own key. Methods live in [`Self::methods`] instead
373    /// (see [`MethodTableSignature`]'s own doc comment for why).
374    pub fns: BTreeMap<String, FnSignature>,
375    /// Keyed by the attached type's name, matching `UnitTable.methods`.
376    pub methods: BTreeMap<String, MethodTableSignature>,
377    /// Keyed by owning service name; each maps to its handlers in
378    /// declaration order. Kept separate from [`Self::agent_handlers`] (PR
379    /// #1517's own bot review, lower-priority item): a flat shared namespace
380    /// let a `service Foo`'s handlers be silently overwritten by an
381    /// `agent Foo`'s own handlers, and the rendering couldn't distinguish
382    /// the two owners either.
383    pub service_handlers: BTreeMap<String, Vec<HandlerSignature>>,
384    /// Keyed by owning agent name.
385    pub agent_handlers: BTreeMap<String, Vec<HandlerSignature>>,
386    /// Keyed by service name (`ServiceDecl.protocol`).
387    pub service_protocols: BTreeMap<String, ProtocolSignature>,
388    /// Keyed by owning agent name; `UnitTable.services`/`.providers` carry no
389    /// store fields of their own.
390    pub store_fields: BTreeMap<String, Vec<StoreFieldSignature>>,
391    pub capabilities: CapabilitySignature,
392}
393
394/// Builds a [`UnitSignature`] for `name` from `table`, reusing `combined_types`
395/// (typically a fresh `combined_types_for(name, ..)` call, mirrored here as a
396/// parameter rather than recomputed so a caller building both alongside each
397/// other pays for one traversal, not two).
398///
399/// Every category below is a direct, field-by-field projection off
400/// `UnitTable`'s own real shapes — see this module's own doc comment and
401/// `design/tracks/incrementality.md` §3.4 (Q4) for which fields are excluded
402/// and why.
403pub fn unit_signature_for(
404    name: &str,
405    table: &UnitTable,
406    combined_types: HashMap<String, Arc<TypeDecl>>,
407) -> UnitSignature {
408    let fns = table
409        .fns
410        .iter()
411        .map(|(fname, decl)| (fname.clone(), fn_signature(fname, decl)))
412        .collect();
413
414    let methods = table
415        .methods
416        .iter()
417        .map(|(type_name, mt)| {
418            let sig = MethodTableSignature {
419                instance: mt
420                    .instance
421                    .iter()
422                    .map(|(mname, decl)| (mname.clone(), fn_signature(mname, decl)))
423                    .collect(),
424                statics: mt
425                    .statics
426                    .iter()
427                    .map(|(mname, decl)| (mname.clone(), fn_signature(mname, decl)))
428                    .collect(),
429            };
430            (type_name.clone(), sig)
431        })
432        .collect();
433
434    let mut service_handlers: BTreeMap<String, Vec<HandlerSignature>> = BTreeMap::new();
435    let mut service_protocols: BTreeMap<String, ProtocolSignature> = BTreeMap::new();
436    for (sname, sdecl) in &table.services {
437        service_handlers.insert(
438            sname.clone(),
439            sdecl.handlers.iter().map(handler_signature).collect(),
440        );
441        service_protocols.insert(sname.clone(), protocol_signature(&sdecl.protocol));
442    }
443
444    let mut agent_handlers: BTreeMap<String, Vec<HandlerSignature>> = BTreeMap::new();
445    let mut store_fields: BTreeMap<String, Vec<StoreFieldSignature>> = BTreeMap::new();
446    for (aname, adecl) in &table.agents {
447        agent_handlers.insert(
448            aname.clone(),
449            adecl.handlers.iter().map(handler_signature).collect(),
450        );
451        store_fields.insert(
452            aname.clone(),
453            adecl
454                .store_fields
455                .iter()
456                .map(|f| StoreFieldSignature {
457                    name: f.name.name.clone(),
458                    kind_head: f.kind.head.name.clone(),
459                    kind_args: f.kind.args.clone(),
460                })
461                .collect(),
462        );
463    }
464
465    let declared: BTreeMap<String, Vec<CapabilityOpSignature>> = table
466        .capabilities
467        .iter()
468        .map(|(cname, cdecl)| {
469            let ops = cdecl
470                .ops
471                .iter()
472                .map(|op| CapabilityOpSignature {
473                    name: op.name.name.clone(),
474                    type_params: op
475                        .type_params
476                        .iter()
477                        .map(|tp| tp.name.name.clone())
478                        .collect(),
479                    params: param_signatures(&op.params),
480                    return_type: op.return_type.clone(),
481                })
482                .collect();
483            (cname.clone(), ops)
484        })
485        .collect();
486
487    let mut provider_given: BTreeMap<String, Vec<String>> = BTreeMap::new();
488    for pdecl in table.providers.values() {
489        provider_given.insert(pdecl.capability.name.clone(), cap_ref_names(&pdecl.given));
490    }
491
492    let mut service_given: BTreeMap<String, Vec<String>> = BTreeMap::new();
493    for (sname, sdecl) in &table.services {
494        service_given.insert(sname.clone(), cap_ref_names(&sdecl.default_given));
495    }
496
497    UnitSignature {
498        id: UnitId(name.to_string()),
499        combined_types,
500        fns,
501        methods,
502        service_handlers,
503        agent_handlers,
504        service_protocols,
505        store_fields,
506        capabilities: CapabilitySignature {
507            exported: table.exported_capabilities.iter().cloned().collect(),
508            declared,
509            provider_given,
510            service_given,
511        },
512    }
513}
514
515impl UnitSignature {
516    /// [DECISION C]: the canonical, span-free rendering R3.14's own proof
517    /// compares (`unit_signature_before.canonical() ==
518    /// unit_signature_after.canonical()`), never the raw struct. Delegates
519    /// every fragment through `contract.rs`'s canonical renderers so this
520    /// type and `service_contract_hash` cannot silently diverge on what
521    /// "the same type" means.
522    pub fn canonical(&self) -> String {
523        crate::contract::canon_unit_signature(self)
524    }
525}
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530    use std::path::PathBuf;
531
532    use bynk_project::{ParsedFile, UnitKind};
533    use bynk_syntax::ast::SourceUnit;
534
535    use crate::symbols::{build_unit_table, combined_types_for};
536
537    fn parsed(source_path: &str, src: &str) -> ParsedFile {
538        let tokens = bynk_syntax::lexer::tokenize(src).expect("lex");
539        let unit = bynk_syntax::parser::parse_unit(&tokens, src).expect("parse");
540        let kind = match &unit {
541            SourceUnit::Commons(_) => UnitKind::Commons,
542            SourceUnit::Context(_) => UnitKind::Context,
543            SourceUnit::Suite(_) | SourceUnit::Adapter(_) => unreachable!("fixture only"),
544        };
545        ParsedFile::new(
546            PathBuf::from(source_path),
547            PathBuf::from(source_path),
548            None,
549            src.to_string(),
550            unit,
551            kind,
552            false,
553        )
554    }
555
556    const SHARED_SRC: &str = r#"commons demo.shared
557
558type Widget = {
559  id: String,
560}
561"#;
562
563    const CONTEXT_SRC: &str = r#"context demo.svc
564
565uses demo.shared
566
567exports capability { Notifier }
568
569fn double(x: Int) -> Int {
570  x * 2
571}
572
573capability Notifier {
574  fn ping(seed: Int) -> Effect[Int]
575}
576
577provides Notifier = StubNotifier {
578  fn ping(seed: Int) -> Effect[Int] {
579    Effect.pure(seed + 1)
580  }
581}
582
583agent Counter {
584  key id: String
585
586  store count: Cell[Int]
587
588  on call increment() -> Effect[Int] {
589    count := count + 1
590    Effect.pure(count)
591  }
592}
593
594service api from http {
595  on GET("/widgets/:id") (id: String) -> Effect[HttpResult[Widget]] by Visitor given Notifier {
596    Ok(Widget { id: id })
597  }
598}
599"#;
600
601    fn build_signature() -> UnitSignature {
602        let shared = parsed("demo/shared.bynk", SHARED_SRC);
603        let context = parsed("demo/svc.bynk", CONTEXT_SRC);
604
605        let mut errors = Vec::new();
606        let shared_table = build_unit_table(
607            "demo.shared",
608            UnitKind::Commons,
609            &[0],
610            &[shared],
611            &mut errors,
612        );
613        let context_table =
614            build_unit_table("demo.svc", UnitKind::Context, &[0], &[context], &mut errors);
615        assert!(errors.is_empty(), "fixture must parse cleanly: {errors:?}");
616
617        let mut unit_tables = HashMap::new();
618        unit_tables.insert("demo.shared".to_string(), shared_table);
619        unit_tables.insert("demo.svc".to_string(), context_table.clone());
620        let mut unit_uses = HashMap::new();
621        unit_uses.insert("demo.svc".to_string(), vec!["demo.shared".to_string()]);
622
623        let combined = combined_types_for("demo.svc", &unit_tables, &unit_uses);
624        unit_signature_for("demo.svc", &context_table, combined)
625    }
626
627    /// P8.1 (#1512), the issue's own "Done when": builds a `UnitSignature`
628    /// for a fixture unit carrying a function (`double`), a handler in both
629    /// a service (`api`'s `GET` route) and an agent (`Counter`'s
630    /// `increment`), a `store` field (`Counter.count`) and a cross-context
631    /// type reference (`Widget`, reached via `uses demo.shared`) — every
632    /// category [DECISION B]'s field list names — and proves the
633    /// field-exclusion list is complete for all of them.
634    ///
635    /// The exclusion itself is a **compile-time fact, not a runtime
636    /// assertion**, per [DECISION B]: `FnSignature`/`HandlerSignature`/
637    /// `StoreFieldSignature` have no `body`/`requires`/`ensures`/`init`/
638    /// `annotations` field to hold one — this test's real job is proving the
639    /// builder actually reaches every category on real parsed source (a
640    /// hand-assembled AST fixture could hide a field the builder silently
641    /// skips), and asserting the shape that *does* survive is exactly the
642    /// externally-relevant one.
643    #[test]
644    fn unit_signature_excludes_every_body_and_body_adjacent_field() {
645        let sig = build_signature();
646
647        assert_eq!(sig.id, UnitId("demo.svc".to_string()));
648
649        // Cross-context type reference: `Widget` reached only through `uses`.
650        assert!(sig.combined_types.contains_key("Widget"));
651
652        // Fn signature.
653        let f = sig.fns.get("double").expect("double must be projected");
654        assert_eq!(f.params.len(), 1);
655        assert_eq!(f.params[0].name, "x");
656
657        // Service handler, including its own `given` and `kind`.
658        let api_handlers = sig
659            .service_handlers
660            .get("api")
661            .expect("api's handler must be projected");
662        assert_eq!(api_handlers.len(), 1);
663        assert_eq!(api_handlers[0].given, vec!["Notifier".to_string()]);
664        assert_eq!(
665            api_handlers[0].kind,
666            HandlerKindSignature::Http {
667                method: "GET".to_string(),
668                path: "/widgets/:id".to_string(),
669            }
670        );
671
672        // Service protocol.
673        assert!(matches!(
674            sig.service_protocols.get("api"),
675            Some(ProtocolSignature::Http)
676        ));
677
678        // Agent handler and store field.
679        let agent_handlers = sig
680            .agent_handlers
681            .get("Counter")
682            .expect("Counter's handler must be projected");
683        assert_eq!(agent_handlers.len(), 1);
684        assert_eq!(agent_handlers[0].method_name.as_deref(), Some("increment"));
685
686        let store = sig
687            .store_fields
688            .get("Counter")
689            .expect("store field must be projected");
690        assert_eq!(store.len(), 1);
691        assert_eq!(store[0].name, "count");
692        assert_eq!(store[0].kind_head, "Cell");
693
694        // Capability-set category: what's exported, what's declared, and what
695        // a provider needs.
696        assert!(sig.capabilities.exported.contains("Notifier"));
697        let ops = sig
698            .capabilities
699            .declared
700            .get("Notifier")
701            .expect("Notifier's own op signatures must be projected");
702        assert_eq!(ops.len(), 1);
703        assert_eq!(ops[0].name, "ping");
704        assert_eq!(
705            sig.capabilities.provider_given.get("Notifier"),
706            Some(&Vec::<String>::new())
707        );
708
709        // The canonical rendering must actually run over every category above
710        // without panicking, and must be deterministic.
711        let rendered = sig.canonical();
712        assert_eq!(rendered, sig.canonical());
713        assert!(rendered.contains("double"));
714        assert!(rendered.contains("Widget"));
715        assert!(rendered.contains("count"));
716        assert!(rendered.contains("Notifier"));
717        assert!(rendered.contains("ping"));
718    }
719
720    /// PR #1517's own bot review: every assertion in the fixture above is
721    /// positive ("this category got projected"), which cannot fail for a
722    /// signature-changing edit the canonical form fails to notice. These
723    /// four mutations are the other direction of R3.14's own firewall — each
724    /// is a real signature change (never a body edit) and each must move
725    /// `canonical()`, closing the review's three material findings (dropped
726    /// `HandlerKind`, missing methods — covered by the `double`/capability-op
727    /// assertions above plus the route/method/protocol mutations below — and
728    /// missing capability-op signatures). The service/agent handler
729    /// namespace collision (the review's lower-priority item) is closed
730    /// structurally instead, by [`UnitSignature`] now keeping
731    /// `service_handlers`/`agent_handlers` as separate fields — the same
732    /// "make it a compile-time fact, not a runtime assertion" posture
733    /// [DECISION B] already established for body-field exclusion.
734    #[test]
735    fn a_genuine_signature_edit_always_changes_the_canonical_form() {
736        let base = build_signature().canonical();
737
738        let renamed_route = CONTEXT_SRC.replacen("/widgets/:id", "/things/:id", 1);
739        assert_ne!(base, signature_for_context(&renamed_route), "route rename");
740
741        let different_method = CONTEXT_SRC.replacen("on GET(", "on POST(", 1);
742        assert_ne!(
743            base,
744            signature_for_context(&different_method),
745            "GET -> POST"
746        );
747
748        let retyped_cap_op = CONTEXT_SRC.replacen(
749            "fn ping(seed: Int) -> Effect[Int]",
750            "fn ping(seed: String) -> Effect[Int]",
751            1,
752        );
753        assert_ne!(
754            base,
755            signature_for_context(&retyped_cap_op),
756            "capability op retyped"
757        );
758
759        // The queue protocol requires `on message`, not `on GET`, so a real
760        // `from queue(...)` fixture would need its own handler shape; the
761        // protocol tag itself is checked directly at the `ServiceProtocol`
762        // projection level instead of through a full re-parse.
763        assert_ne!(
764            crate::contract::canon_unit_signature(&with_protocol(ServiceProtocol::Queue {
765                name: "q".to_string()
766            })),
767            crate::contract::canon_unit_signature(&with_protocol(ServiceProtocol::Http)),
768            "http -> queue"
769        );
770    }
771
772    fn signature_for_context(context_src: &str) -> String {
773        let shared = parsed("demo/shared.bynk", SHARED_SRC);
774        let context = parsed("demo/svc.bynk", context_src);
775
776        let mut errors = Vec::new();
777        let shared_table = build_unit_table(
778            "demo.shared",
779            UnitKind::Commons,
780            &[0],
781            &[shared],
782            &mut errors,
783        );
784        let context_table =
785            build_unit_table("demo.svc", UnitKind::Context, &[0], &[context], &mut errors);
786        assert!(
787            errors.is_empty(),
788            "mutated fixture must still parse cleanly: {errors:?}"
789        );
790
791        let mut unit_tables = HashMap::new();
792        unit_tables.insert("demo.shared".to_string(), shared_table);
793        unit_tables.insert("demo.svc".to_string(), context_table.clone());
794        let mut unit_uses = HashMap::new();
795        unit_uses.insert("demo.svc".to_string(), vec!["demo.shared".to_string()]);
796
797        let combined = combined_types_for("demo.svc", &unit_tables, &unit_uses);
798        unit_signature_for("demo.svc", &context_table, combined).canonical()
799    }
800
801    fn with_protocol(protocol: ServiceProtocol) -> UnitSignature {
802        let mut sig = build_signature();
803        sig.service_protocols
804            .insert("api".to_string(), protocol_signature(&protocol));
805        sig
806    }
807}