Skip to main content

bynk_syntax/
diagnostics.rs

1//! Central registry of diagnostic codes.
2//!
3//! This is the single source of truth for the `bynk.*` codes the compiler can
4//! emit. The reference page `site/src/content/docs/book/reference/diagnostics.md` is generated
5//! from [`render_markdown`], and the test `tests/diagnostics_registry.rs`
6//! asserts that this table matches exactly the set of codes used across the
7//! compiler source — so a new code cannot be introduced without documenting it
8//! here, and a removed code cannot linger in the docs.
9//!
10//! Each entry is a `(code, summary)` pair, optionally tagged with the grammar
11//! production(s) it constrains (`grammar_symbol`), and carries a severity
12//! (`Error` unless built via the crate-private `warn` helper). The category
13//! shown in the generated reference is derived from the second dotted segment
14//! of the code; the grammar weave (`docs/grammar-semantics.json`, the
15//! `{{#grammar-semantics}}` directive, and the diagnostics page's Construct
16//! column) is generated from `grammar_symbol`.
17
18use crate::error::Severity;
19
20/// One documented diagnostic: its stable code and a one-line summary of the
21/// cause. Richer "cause and fix" material for the common diagnostics lives in
22/// the troubleshooting how-to guides.
23pub struct DiagnosticInfo {
24    pub code: &'static str,
25    pub summary: &'static str,
26    /// The grammar production(s) this diagnostic constrains, by `tree-sitter`
27    /// rule name (e.g. `http_handler`). This is the single source of the
28    /// "static semantics" weave: a grammar-reference entry embeds the
29    /// diagnostics for a rule via `{{#grammar-semantics <rule>}}`, generated
30    /// from here. Empty for diagnostics with no single governing construct
31    /// (e.g. `bynk.boundary.structural_mismatch`). Every non-empty name is
32    /// checked against the grammar by `tests/diagnostics_registry.rs`.
33    pub grammar_symbol: &'static [&'static str],
34    /// This code's severity (ADR 0117): `Error` rejects the program; `Warning`
35    /// surfaces but never fails the build. The single source of truth for
36    /// [`crate::error::Severity::for_error`], which looks a code up here
37    /// instead of hardcoding its own copy of the (small) warning set —
38    /// `tests/diagnostics_registry.rs` asserts the two never drift apart.
39    /// Defaults to `Error` via the crate-private `d`/`dg` constructors; only
40    /// the crate-private `warn` helper's call sites override it.
41    pub severity: Severity,
42}
43
44/// The hosted Book, the stable target for `codeDescription` links (#853,
45/// DECISION C). No trailing slash — an [`Explain::page`] path (which begins
46/// with `/`) is appended directly.
47pub const BOOK_BASE_URL: &str = "https://bynk-lang.org";
48
49/// A curated, offline-complete explanation of a diagnostic code (#853).
50///
51/// This is the compiler-owned `code → { blurb, href }` table (DECISION A): the
52/// `blurb`/`example` are the offline answer `bynk explain` prints, while
53/// `page`/`anchor` compose the hosted-Book href the LSP hangs off the code as a
54/// clickable `codeDescription` link (DECISION C). Only the highest-traffic,
55/// newcomer-facing codes are curated; every other code simply has no entry and
56/// falls back gracefully — no link, no error (DECISION B).
57///
58/// The mapping points at *existing* Book concept pages rather than duplicating
59/// their prose; the reference-page generator ([`render_markdown`]) links every
60/// explained code at its `page`/`anchor` as an in-site link, so
61/// `astro build`'s link checker fails if a page moves or an anchor is renamed —
62/// the doc-drift guard the rest of the site already relies on.
63pub struct Explain {
64    /// The diagnostic code this explains. Must be a real [`REGISTRY`] code
65    /// (enforced by `tests/diagnostics_registry.rs`).
66    pub code: &'static str,
67    /// A longer-form paragraph: what the rule is and, crucially, *why* it
68    /// exists. This is the offline-complete answer — useful without network.
69    pub blurb: &'static str,
70    /// A minimal example of the violation and its fix.
71    pub example: &'static str,
72    /// The target Book page as a site-root-relative path, no extension and no
73    /// trailing slash, e.g. `/book/reference/types`. Used verbatim as an
74    /// in-site link by [`render_markdown`] (so the site link checker guards it)
75    /// and prefixed with [`BOOK_BASE_URL`] for the hosted `codeDescription`.
76    pub page: &'static str,
77    /// The in-page heading anchor (slug), or `""` for the page top.
78    pub anchor: &'static str,
79}
80
81impl Explain {
82    /// The hosted-Book URL for this explanation: [`BOOK_BASE_URL`] + the page
83    /// (Starlight serves pages with a trailing slash) + `#anchor` when set.
84    pub fn href(&self) -> String {
85        let mut url = format!("{BOOK_BASE_URL}{}/", self.page);
86        if !self.anchor.is_empty() {
87            url.push('#');
88            url.push_str(self.anchor);
89        }
90        url
91    }
92
93    /// The site-root-relative link used inside the generated reference page,
94    /// e.g. `/book/reference/types/#record-types`. Same shape as [`href`], sans
95    /// the host, so the in-site link checker resolves it.
96    ///
97    /// [`href`]: Explain::href
98    pub fn in_site_link(&self) -> String {
99        let mut link = format!("{}/", self.page);
100        if !self.anchor.is_empty() {
101            link.push('#');
102            link.push_str(self.anchor);
103        }
104        link
105    }
106}
107
108/// The curated explanations, keyed by code (DECISION B: highest-traffic,
109/// newcomer-facing codes first). Kept sorted by code; every `code` must be a
110/// real [`REGISTRY`] entry and every `page` an existing Book page — both
111/// enforced by `tests/diagnostics_registry.rs`.
112pub const EXPLANATIONS: &[Explain] = &[
113    Explain {
114        code: "bynk.given.undeclared_capability",
115        blurb: "A handler may only use a capability it has itself declared with \
116                `given`. Effects in Bynk are explicit: the `given` clause is the \
117                handler's honest, checkable statement of every capability it \
118                reaches for, so a reader (and the compiler) can see a handler's \
119                full reach from its signature alone. Using a capability that is \
120                not in `given` is the missing half of that contract.",
121        example: "on get \"/now\" -> Text {           // ✗ uses Clock without declaring it\n    \
122                    Clock.now()\n}\n\n\
123                  on get \"/now\" given Clock -> Text { // ✓ declared, then used\n    \
124                    Clock.now()\n}",
125        page: "/book/guides/effects-and-capabilities/understand-the-capability-model",
126        anchor: "",
127    },
128    Explain {
129        code: "bynk.given.unknown_capability",
130        blurb: "A `given` clause names a capability that no provider declares. A \
131                capability is a typed interface to the outside world; it has to be \
132                *declared* (as a `capability`, or brought in from a consumed \
133                context) before a handler can ask for it. This usually means a \
134                typo in the capability name, or a missing `uses`/`consumes` that \
135                would bring the capability into scope.",
136        example: "on get \"/\" given Clok -> Text { … }  // ✗ no capability named `Clok`\n\n\
137                  on get \"/\" given Clock -> Text { … }  // ✓ matches the declared capability",
138        page: "/book/reference/capabilities",
139        anchor: "declaring-a-capability",
140    },
141    Explain {
142        code: "bynk.resolve.missing_field",
143        blurb: "A record must be constructed with every one of its fields. Bynk \
144                records have no defaults and no partial construction: a value of a \
145                record type is only valid once all its fields are present, so a \
146                downstream reader never has to wonder whether a field was set. \
147                Omitting a field is therefore an error, not a fill-in-later.",
148        example: "type User = { name: Text, age: Int }\n\n\
149                  User { name: \"Ada\" }            // ✗ missing `age`\n\
150                  User { name: \"Ada\", age: 36 }   // ✓ every field present",
151        page: "/book/reference/types",
152        anchor: "record-types",
153    },
154    Explain {
155        code: "bynk.resolve.unknown_field",
156        blurb: "A field access names a field the record type does not have. A \
157                record's fields are fixed by its type declaration; only those \
158                names exist on the value. This is usually a typo in the field \
159                name, or an access meant for a different type.",
160        example: "type User = { name: Text }\n\n\
161                  user.nmae   // ✗ no field `nmae`\n\
162                  user.name   // ✓ the declared field",
163        page: "/book/reference/types",
164        anchor: "record-types",
165    },
166    Explain {
167        code: "bynk.resolve.unknown_name",
168        blurb: "A name was referenced that is not in scope. Every name in Bynk \
169                must be introduced before use — as a `let` binding, a parameter, \
170                a `fn`, a type, or a member brought in through `uses`/`consumes`. \
171                An unknown name is typically a typo, a missing declaration, or a \
172                reference to something defined in a module that has not been \
173                brought into scope.",
174        example: "let greeting = \"hi\"\n\
175                  greetng          // ✗ no name `greetng` in scope\n\
176                  greeting         // ✓ the bound name",
177        page: "/book/guides/program-structure/how-a-program-is-shaped",
178        anchor: "",
179    },
180    Explain {
181        code: "bynk.resolve.unknown_type",
182        blurb: "A type name was referenced that does not exist. Types must be \
183                declared (with `type`), be one of Bynk's built-in types, or be \
184                brought into scope from another module before they can be named. \
185                An unknown type is usually a typo or a missing declaration/import.",
186        example: "fn greet(u: Usr) -> Text { … }   // ✗ no type `Usr`\n\
187                  fn greet(u: User) -> Text { … }  // ✓ the declared type",
188        page: "/book/reference/types",
189        anchor: "",
190    },
191];
192
193/// The curated explanation for a diagnostic `code`, or `None` when the code has
194/// no explanation yet (the designed graceful-fallback state, DECISION B).
195pub fn explain(code: &str) -> Option<&'static Explain> {
196    EXPLANATIONS.iter().find(|e| e.code == code)
197}
198
199/// Look up a code's registry entry by exact match — the one place
200/// [`crate::error::Severity::for_error`] reads a code's severity, instead of
201/// hardcoding its own copy of the (small) warning set.
202pub fn lookup(code: &str) -> Option<&'static DiagnosticInfo> {
203    REGISTRY.iter().find(|d| d.code == code)
204}
205
206/// Every diagnostic code the compiler emits, sorted by code.
207pub const REGISTRY: &[DiagnosticInfo] = &[
208    d(
209        "bynk.actor.bearer_identity_not_string_constructible",
210        "A `Bearer` actor's identity is not a string-constructible type.",
211    ),
212    d(
213        "bynk.actor.bearer_missing_secret",
214        "A `Bearer` actor does not name its signing secret.",
215    ),
216    d(
217        "bynk.actor.binder_shadows_param",
218        "A `by` actor binder collides with a handler parameter of the same name.",
219    ),
220    d(
221        "bynk.actor.by_on_agent",
222        "A `by` actor clause was placed on an agent `on call` handler, which has no actor.",
223    ),
224    d(
225        "bynk.actor.duplicate_sum_scheme",
226        "Two peers in a multi-actor sum share an authentication scheme.",
227    ),
228    d(
229        "bynk.actor.identity_not_sealed",
230        "An actor identity type is not a context-ownable (sealed) value type.",
231    ),
232    d(
233        "bynk.actor.missing_by_on_http",
234        "An HTTP handler lacks the required `by` actor clause.",
235    ),
236    d(
237        "bynk.actor.oidc_identity_not_string_constructible",
238        "An `Oidc` actor's identity is not a string-constructible type.",
239    ),
240    d(
241        "bynk.actor.oidc_missing_audience",
242        "An `Oidc` actor does not name its `audience`.",
243    ),
244    d(
245        "bynk.actor.oidc_missing_issuer",
246        "An `Oidc` actor does not name its `issuer`.",
247    ),
248    d(
249        "bynk.actor.oidc_missing_jwks",
250        "An `Oidc` actor does not name its `jwks` endpoint.",
251    ),
252    d(
253        "bynk.actor.oidc_not_in_sum",
254        "An `Oidc` actor appears as a member of a multi-actor sum.",
255    ),
256    d(
257        "bynk.actor.outside_context",
258        "An `actor` was declared outside a context (e.g. in a commons).",
259    ),
260    d(
261        "bynk.actor.refinement_base_unsupported",
262        "A refinement actor's base is not a `Bearer` actor (no claims to authorise against).",
263    ),
264    d(
265        "bynk.actor.refinement_in_sum",
266        "A refinement actor appears as a member of a multi-actor sum.",
267    ),
268    d(
269        "bynk.actor.refinement_predicate_unsupported",
270        "A refinement actor's `where` predicate is outside the closed claim-predicate set.",
271    ),
272    d(
273        "bynk.actor.scheme_not_admissible",
274        "An actor's scheme is not admissible on this handler's protocol.",
275    ),
276    d(
277        "bynk.actor.signature_identity_unsupported",
278        "A `Signature` actor declared an `identity`, which is not yet supported.",
279    ),
280    d(
281        "bynk.actor.signature_missing_header",
282        "A `Signature` actor does not name its signature header.",
283    ),
284    d(
285        "bynk.actor.signature_missing_secret",
286        "A `Signature` actor does not name its signing secret.",
287    ),
288    d(
289        "bynk.actor.signature_requires_body",
290        "A `Signature` handler does not take a `body` parameter.",
291    ),
292    d(
293        "bynk.actor.signature_tolerance_without_timestamp",
294        "A `Signature` actor set `tolerance` without a `timestamp` header.",
295    ),
296    d(
297        "bynk.actor.sum_requires_binder",
298        "A multi-actor sum `by` clause has no binder to match the resolved actor.",
299    ),
300    d(
301        "bynk.actor.unknown_actor",
302        "A handler's `by` clause names an actor that is not declared.",
303    ),
304    d(
305        "bynk.actor.unknown_scheme",
306        "An actor declares an authentication scheme that is not compiler-known.",
307    ),
308    d(
309        "bynk.actor.unreachable_sum_arm",
310        "A multi-actor sum has an arm unreachable after a catch-all (`None`) peer.",
311    ),
312    dg(
313        "bynk.adapter.consumes_context",
314        "An `adapter` consumed a context; adapter dependencies are adapter-to-adapter.",
315        &["consumes_decl"],
316    ),
317    dg(
318        "bynk.adapter.consumes_requires_selection",
319        "An `adapter` used a whole-unit or aliased `consumes`; adapters must select capabilities with `consumes U { Cap, … }`.",
320        &["consumes_decl"],
321    ),
322    dg(
323        "bynk.adapter.disallowed_item",
324        "An `adapter` declared a `service`, `agent`, or other item it may not contain.",
325        &["adapter_decl"],
326    ),
327    dg(
328        "bynk.adapter.duplicate_binding",
329        "An `adapter` declared more than one `binding` clause.",
330        &["binding_decl"],
331    ),
332    dg(
333        "bynk.adapter.no_binding",
334        "An `adapter` declares an external provider but no `binding` module to supply it.",
335        &["adapter_decl"],
336    ),
337    dg(
338        "bynk.adapter.provider_has_body",
339        "A provider inside an `adapter` has a Bynk body; adapter providers must be external.",
340        &["provider_decl"],
341    ),
342    dg(
343        "bynk.agent.construction_arity",
344        "An agent was constructed with the wrong number of key arguments.",
345        &["agent_decl"],
346    ),
347    dg(
348        "bynk.agent.handler_arity",
349        "An agent handler was called with the wrong number of arguments.",
350        &["agent_decl"],
351    ),
352    dg(
353        "bynk.agent.handler_not_found",
354        "Called a handler the agent does not declare.",
355        &["agent_decl"],
356    ),
357    dg(
358        "bynk.agent.key_mismatch",
359        "An agent key argument has the wrong type.",
360        &["agent_decl"],
361    ),
362    dg(
363        "bynk.agent.outside_context",
364        "An `agent` was declared outside a context.",
365        &["agent_decl"],
366    ),
367    dg(
368        "bynk.agent.return_not_effect",
369        "An agent handler's return type is not an `Effect`.",
370        &["agent_decl"],
371    ),
372    d(
373        "bynk.agent.state_name_conflict",
374        "A type is named `<Agent>State` beside agent `<Agent>`; that name is the agent's state record (its `Cell` fields), which its handlers and invariants see in place of the type.",
375    ),
376    dg(
377        "bynk.agents.bad_state_initialiser",
378        "An agent `store` field initialiser is not a static value of the field's type.",
379        &["store_field"],
380    ),
381    dg(
382        "bynk.agents.non_zeroable_state_field",
383        "An agent `store` field has no initialiser and no implicit zero value.",
384        &["store_field"],
385    ),
386    d(
387        "bynk.asset.duplicate",
388        "An `asset` name is declared more than once in the same unit.",
389    ),
390    d(
391        "bynk.asset.invalid_at_path",
392        "An `asset`'s `at` path is not a URL path naming one file, or lies under `/_assets/` or `/_bynk/`.",
393    ),
394    warn(d(
395        "bynk.asset.may_shadow_route",
396        "A parameterised HTTP route matches a fixed asset path, so it never sees requests for that path (a warning).",
397    )),
398    d(
399        "bynk.asset.missing_file",
400        "An `asset` names a file that is not in the project's `assets/` folder.",
401    ),
402    d(
403        "bynk.asset.needs_project",
404        "A single-file build met an `asset` declaration; assets need a project build.",
405    ),
406    warn(d(
407        "bynk.asset.not_served",
408        "A deployable Bundle build met an `asset`; a Bundle ships no files, so its `.url` would not be served (a warning).",
409    )),
410    d(
411        "bynk.asset.outside_assets_dir",
412        "An `asset` path does not name a file in the project's `assets/` folder.",
413    ),
414    d(
415        "bynk.asset.outside_context_or_commons",
416        "An `asset` declaration appears outside a context or commons.",
417    ),
418    d(
419        "bynk.asset.path_conflict",
420        "Two different asset files would be served at one fixed path by the same Worker.",
421    ),
422    d(
423        "bynk.asset.shadows_route",
424        "A fixed asset path equals a literal HTTP route, which the platform-served asset makes unreachable.",
425    ),
426    d(
427        "bynk.asset.unreadable_file",
428        "An `asset` names a file in the project's `assets/` folder that could not be read.",
429    ),
430    d(
431        "bynk.asset.unsafe_path",
432        "An `asset` path is empty, absolute, or contains a `..` segment.",
433    ),
434    d(
435        "bynk.boundary.structural_mismatch",
436        "Data crossing a context boundary did not match the expected shape.",
437    ),
438    dg(
439        "bynk.capability.not_provided",
440        "On the Workers target, a capability a context requires has no provider in it.",
441        &["given_clause"],
442    ),
443    dg(
444        "bynk.capability.op_arity",
445        "A capability operation was called with the wrong number of arguments.",
446        &["capability_decl"],
447    ),
448    dg(
449        "bynk.capability.outside_context",
450        "A `capability` was declared outside a context.",
451        &["capability_decl"],
452    ),
453    dg(
454        "bynk.capability.unknown_operation",
455        "Referenced an operation the capability does not declare.",
456        &["capability_decl"],
457    ),
458    d(
459        "bynk.cell.invalid_target",
460        "A `:=` write targets something that is not a `store Cell` field.",
461    ),
462    d(
463        "bynk.cell.self_reference",
464        "A `:=` right-hand side reads the cell being written (a read-modify-write); use `.update`.",
465    ),
466    dg(
467        "bynk.consumes.alias_conflict",
468        "Two `consumes` aliases collide.",
469        &["consumes_decl"],
470    ),
471    dg(
472        "bynk.consumes.capability_name_clash",
473        "Two flattened `consumes U { Cap }` capabilities collide, or one clashes with a local capability.",
474        &["consumes_decl"],
475    ),
476    dg(
477        "bynk.consumes.name_conflict",
478        "A `consumes` name collides with another name in scope.",
479        &["consumes_decl"],
480    ),
481    dg(
482        "bynk.consumes.self_reference",
483        "A context `consumes` itself.",
484        &["consumes_decl"],
485    ),
486    dg(
487        "bynk.consumes.service_arity",
488        "A consumed service was called with the wrong number of arguments.",
489        &["consumes_decl"],
490    ),
491    dg(
492        "bynk.consumes.target_is_commons",
493        "`consumes` targets a `commons` instead of a context.",
494        &["consumes_decl"],
495    ),
496    dg(
497        "bynk.consumes.unknown_context",
498        "`consumes` names a context that does not exist.",
499        &["consumes_decl"],
500    ),
501    dg(
502        "bynk.consumes.unknown_service",
503        "Called a service the consumed context does not declare.",
504        &["consumes_decl"],
505    ),
506    d(
507        "bynk.context.consumes_cycle",
508        "Contexts form a `consumes` dependency cycle.",
509    ),
510    d(
511        "bynk.context.external_construction",
512        "A context-owned type was constructed from outside that context.",
513    ),
514    dg(
515        "bynk.context.external_provider",
516        "A bodiless (external) provider was declared outside an `adapter`.",
517        &["provider_decl"],
518    ),
519    d(
520        "bynk.context.opaque_inspection",
521        "An opaquely-exported type was inspected from outside its context.",
522    ),
523    d(
524        "bynk.context.rebrand_construction",
525        "A variant of a `uses`-sourced commons sum type was constructed directly inside a context, where the emitter's per-context rebrand leaves its constructors out of scope.",
526    ),
527    d(
528        "bynk.contract.duplicate_name",
529        "A function declares two contract clauses (`requires`/`ensures`) with the same name.",
530    ),
531    d(
532        "bynk.contract.impure_predicate",
533        "A contract predicate uses an effectful or test-only construct; a contract clause must be pure.",
534    ),
535    d(
536        "bynk.contract.not_bool",
537        "A contract predicate does not have type `Bool`.",
538    ),
539    d(
540        "bynk.contract.restated_by_test",
541        "A `case`/`property` merely restates a contract clause already declared at the function; the test is redundant.",
542    ),
543    d(
544        "bynk.contract.result_in_requires",
545        "A precondition (`requires`) references `result`; the return value is only in scope inside an `ensures`.",
546    ),
547    dg(
548        "bynk.cron.bad_params",
549        "A cron handler declares more than one parameter, or a non-`Int` one.",
550        &["cron_handler"],
551    ),
552    dg(
553        "bynk.cron.duplicate_schedule",
554        "Two cron handlers declare the same schedule.",
555        &["cron_handler"],
556    ),
557    dg(
558        "bynk.cron.invalid_schedule",
559        "A cron expression is not five whitespace-separated fields.",
560        &["cron_handler"],
561    ),
562    dg(
563        "bynk.cron.return_not_effect_result",
564        "A cron handler does not return `Effect[Result[(), E]]`.",
565        &["cron_handler"],
566    ),
567    d(
568        "bynk.deploy.contract_skew",
569        "A worker was compiled against a contract its live dependencies no longer provide, so `bynk deploy` refuses to ship it.",
570    ),
571    d(
572        "bynk.duration.literal_overflow",
573        "A `Duration` literal (`<int>.<unit>`) exceeds the representable millisecond range.",
574    ),
575    dg(
576        "bynk.effect.bind_in_pure_context",
577        "An `<-` bind was used in a pure (non-effectful) context.",
578        &["effect_let_stmt"],
579    ),
580    dg(
581        "bynk.effect.bind_on_non_effect",
582        "An `<-` bind was applied to a non-`Effect` value.",
583        &["effect_let_stmt"],
584    ),
585    d(
586        "bynk.effect.capability_in_pure_context",
587        "A capability was used in a pure context.",
588    ),
589    d(
590        "bynk.effect.cross_context_in_pure_context",
591        "A cross-context call was made in a pure context.",
592    ),
593    dg(
594        "bynk.effect.do_in_pure_context",
595        "A `do` statement was used in a pure (non-effectful) context.",
596        &["do_stmt"],
597    ),
598    dg(
599        "bynk.effect.do_on_non_effect",
600        "A `do` statement was applied to a non-`Effect` value.",
601        &["do_stmt"],
602    ),
603    dg(
604        "bynk.effect.do_requires_unit",
605        "A `do` statement was applied to a valued `Effect[T]`; `do` performs a unit effect, so a real result would be dropped — use `let _ <- e` instead.",
606        &["do_stmt"],
607    ),
608    dg(
609        "bynk.effect.fn_value_in_pure_context",
610        "An effectful function value was called in a pure context; like a capability call, it is legal only where the enclosing body is effectful.",
611        &["call"],
612    ),
613    d(
614        "bynk.effect.unbound_effect",
615        "An `Effect` value in an effectful body was built but not bound with `<-`, sequenced with `do` or returned — in a plain `let`, a list element or a constructor payload — so it runs eagerly and unawaited (#1658).",
616    ),
617    d(
618        "bynk.event.bad_field_default",
619        "An event field's default expression (`field: T = expr`) is not a static, wire-representable value of the field's declared type — a literal (including one admitted to a refined type), a sum variant, `Some`/`None`/`Ok`/`Err`, a record, or `T.unsafe(lit)` for an opaque type whose literal also satisfies the refinement.",
620    ),
621    d(
622        "bynk.event.bad_params",
623        "An `on event` handler declared the wrong number of parameters, or a second parameter whose type is not `EventEnvelope` — it takes the event payload and, optionally, the runtime envelope.",
624    ),
625    d(
626        "bynk.event.bad_schema_dispatch",
627        "A `via schema(...)` dispatch clause's argument is malformed — it must be a single, positive, positional `Int` literal.",
628    ),
629    d(
630        "bynk.event.bad_schema_version",
631        "An event's `@schema(N)` annotation is malformed — `N` must be a single, positive, positional `Int` literal, and `@schema` may appear at most once on an event.",
632    ),
633    d(
634        "bynk.event.default_outside_event",
635        "A field default (`field: T = expr`) was written on a record field outside an `event` declaration — a default is only meaningful on an event's own field, since it exists to let an older wire event missing this key still deserialise.",
636    ),
637    dg(
638        "bynk.event.duplicate_handler",
639        "A `from Events` service declares more than one `on event` handler; it has exactly one.",
640        &["event_handler"],
641    ),
642    d(
643        "bynk.event.emit_not_an_event",
644        "`Events.emit[E]` named a type `E` that is declared in this context, but is not itself an `event` — only an `event` type may be emitted.",
645    ),
646    d(
647        "bynk.event.emit_outside_owner",
648        "`Events.emit[E]` named an event `E` not declared in the emitting context — only an event's declaring context may emit it.",
649    ),
650    d(
651        "bynk.event.handler_param_type_mismatch",
652        "An `on event(e: T)` handler's declared parameter type does not match its `from Events(E)` header's event type.",
653    ),
654    d(
655        "bynk.event.non_additive_schema_change",
656        "An event's field shape changed in a way the schema registry cannot evolve additively — a field was removed, retyped, added without a default, or lost a default it previously had. Give the new shape a new event type name, or make the change additive.",
657    ),
658    d(
659        "bynk.event.outside_context",
660        "An `event` was declared outside a context.",
661    ),
662    d(
663        "bynk.event.pattern_duplicate_field",
664        "A `from Events(E { ... })` subscription pattern listed the same field more than once.",
665    ),
666    d(
667        "bynk.event.pattern_type_mismatch",
668        "A `from Events(E { ... })` subscription pattern field's matched value is not compatible with that field's declared type.",
669    ),
670    d(
671        "bynk.event.pattern_unknown_field",
672        "A `from Events(E { ... })` subscription pattern named a field that `E` does not declare.",
673    ),
674    d(
675        "bynk.event.pattern_unknown_variant",
676        "A `from Events(E { ... })` subscription pattern's variant value names a variant that does not exist on the field's declared sum type.",
677    ),
678    d(
679        "bynk.event.pattern_variant_payload",
680        "A `from Events(E { ... })` subscription pattern's variant value names a variant that carries a payload — only nullary variants are admitted, since testing the tag alone would silently ignore the payload.",
681    ),
682    dg(
683        "bynk.event.return_not_effect_unit",
684        "An `on event` handler returns an `Effect` of something other than `()`; emission is fire-and-forget, so it returns `Effect[()]`.",
685        &["event_handler"],
686    ),
687    d(
688        "bynk.event.schema_version_mismatch",
689        "An event's `@schema(N)` annotation disagrees with the version the schema registry computes from the event's build history.",
690    ),
691    d(
692        "bynk.event.unknown_annotation",
693        "An `event` declaration carried an `@`-annotation other than `@schema` — event annotations are a closed set.",
694    ),
695    d(
696        "bynk.event.unknown_subscription",
697        "A `from Events(E)` subscription named `E`, which is not a declared event in this context or any consumed context.",
698    ),
699    dg(
700        "bynk.expect.faults_not_effect",
701        "A fault claim's subject (`expect <call> faults`) is not an effectful call: a value, or a call whose type is not `Effect[_]`.",
702        &["faults_expr"],
703    ),
704    dg(
705        "bynk.expect.not_bool",
706        "`expect` was given a non-`Bool` predicate.",
707        &["expect_expr"],
708    ),
709    dg(
710        "bynk.expect.outside_case",
711        "`expect` was used outside a `case` body.",
712        &["expect_expr"],
713    ),
714    dg(
715        "bynk.exports.capability_not_provided",
716        "An exported capability has no provider in its context.",
717        &["exports_decl"],
718    ),
719    dg(
720        "bynk.exports.conflicting_visibility",
721        "A type is exported with conflicting visibilities.",
722        &["exports_decl"],
723    ),
724    dg(
725        "bynk.exports.duplicate_export",
726        "The same name is exported more than once.",
727        &["exports_decl"],
728    ),
729    dg(
730        "bynk.exports.duplicate_in_clause",
731        "A name appears twice in one `exports` clause.",
732        &["exports_decl"],
733    ),
734    dg(
735        "bynk.exports.undeclared_capability",
736        "`exports capability` names a capability that is not declared.",
737        &["exports_decl"],
738    ),
739    dg(
740        "bynk.exports.undeclared_type",
741        "`exports` names a type that is not declared.",
742        &["exports_decl"],
743    ),
744    d(
745        "bynk.fmt.comment_loss",
746        "The formatter would drop a comment, so it leaves the file unchanged.",
747    ),
748    d(
749        "bynk.fmt.roundtrip",
750        "The formatter's output does not re-parse to the same program, so it leaves the file unchanged.",
751    ),
752    dg(
753        "bynk.generics.duplicate_type_param",
754        "A `type` or `fn` declares the same type-parameter name more than once (v0.157, ADR 0183).",
755        &[],
756    ),
757    dg(
758        "bynk.generics.generic_non_record",
759        "A `type` declaration carries type parameters on a refined or opaque body; only a record (`type Name[T] = { … }`) or sum (`type Name[T] = | … | …`) body may be generic (v0.157/#593, ADRs 0183/0197).",
760        &["type_decl"],
761    ),
762    dg(
763        "bynk.generics.generic_record_at_boundary",
764        "A `Val[…]` fabricates a value of a generic type; per-instantiation value fabrication is not yet wired (ADR 0197). Since v0.174 a generic-record instantiation may otherwise cross a boundary through its monomorphised codec.",
765        &[],
766    ),
767    dg(
768        "bynk.generics.generic_sum_embeds",
769        "A generic sum type carries an `embeds` clause; embedding into a generic sum is not supported (#593).",
770        &["type_decl"],
771    ),
772    dg(
773        "bynk.generics.method_on_generic_type",
774        "A *static* method is attached to a generic type; static methods on generic types are deferred (they have no receiver to supply the type's parameters). Instance methods on generic types are supported (#594).",
775        &["fn_decl"],
776    ),
777    dg(
778        "bynk.generics.no_bounds",
779        "A type parameter carries a bound (`[A: …]`); bounded generics are not in v0.20a.",
780        &["fn_decl"],
781    ),
782    dg(
783        "bynk.generics.recursive_generic_at_boundary",
784        "A recursive generic record (one that transitively contains itself, through any wrapper or generic argument) appears at a boundary; it has no finite set of monomorphised codecs, so it is not yet boundary-serialisable (ADR 0197).",
785        &[],
786    ),
787    dg(
788        "bynk.generics.type_arg_count",
789        "A user-declared generic type is applied to the wrong number of type arguments, or a generic type is named without its `[…]` arguments (v0.157, ADR 0183).",
790        &["applied_type_ref"],
791    ),
792    dg(
793        "bynk.generics.type_arg_mismatch",
794        "Inferred or explicit type arguments conflict, have the wrong arity, target a non-generic function, or a type parameter shadows a declared type.",
795        &["call"],
796    ),
797    dg(
798        "bynk.generics.uninferable_type_arg",
799        "A generic function's type parameter could not be inferred from the arguments and was not given explicitly (`name[T](…)`); a bare generic function also cannot be passed as a value in v0.20a.",
800        &["call"],
801    ),
802    dg(
803        "bynk.given.cross_context_unknown_capability",
804        "`given B.Cap` names a capability the consumed context does not export.",
805        &["given_clause"],
806    ),
807    dg(
808        "bynk.given.undeclared_capability",
809        "A handler uses a capability it did not declare with `given`.",
810        &["given_clause"],
811    ),
812    dg(
813        "bynk.given.unknown_capability",
814        "`given` names a capability that does not exist.",
815        &["given_clause"],
816    ),
817    warn(dg(
818        "bynk.given.unused_capability",
819        "A `given` capability is never used (warning).",
820        &["given_clause"],
821    )),
822    d(
823        "bynk.held.branch_divergence",
824        "Branches of a conditional leave a held value (e.g. `Connection[F]`) in inconsistent ownership states — one consumes or stores it, another leaves it owned (§2.9.5, real-time track slice 2).",
825    ),
826    d(
827        "bynk.held.consume_on_borrow",
828        "A consuming operation (`close`/`put`/`take`) is called on a *borrowed* held reference — borrows admit only non-consuming operations like `send` (§2.9.3, real-time track slice 2).",
829    ),
830    d(
831        "bynk.held.leak",
832        "A held value (`Connection[F]`) is still owned at scope exit — it must be disposed (stored, closed, or transferred) before the handler or function returns (§2.9.1, real-time track slice 2).",
833    ),
834    d(
835        "bynk.held.query_accessor_on_held_map",
836        "A key-aware query accessor (`.entries`/`.keys`/`.values`) is used on a held `Map[K, Connection]` — a held resource is iterated with the broadcast ops (`forEach`/`parTraverse`), not a key query.",
837    ),
838    d(
839        "bynk.held.unsupported_map_op",
840        "A held `Map[K, Connection]` is given an `update`/`upsert` — a held resource cannot be transformed by a `(Connection) -> Connection` function; use `put`/`get`/`remove` (real-time track slice 3b-ii).",
841    ),
842    d(
843        "bynk.held.unsupported_storage",
844        "A held value (`Connection[F]`) is stored in a `Set`/`Log`/`Cache` — held values may only live in `Cell[Option[Connection]]` or `Map[K, Connection]` (§2.9.3, real-time track slice 2).",
845    ),
846    d(
847        "bynk.held.use_after_consume",
848        "A held value (`Connection[F]`) is used after a consuming operation (`close`/`put`/`take`) ended its lifetime (§2.9.2, real-time track slice 2).",
849    ),
850    d(
851        "bynk.history.not_an_agent",
852        "A `for all run: History[T]` names a `T` that is not an agent — only an agent has handlers to sequence and reachable states to observe (testing track slice 7, ADR 0155).",
853    ),
854    d(
855        "bynk.history.not_generable",
856        "A `for all run: History[Agent]` targets an agent with a handler parameter whose type cannot be generated (e.g. a `Matches` refinement), so its call-history cannot be driven (testing track slice 7, ADR 0155).",
857    ),
858    d(
859        "bynk.history.outside_property",
860        "`History[Agent]` appears outside a `property`'s `for all` binding — it is a test-only generator, not a value type (testing track slice 7, ADR 0155).",
861    ),
862    d(
863        "bynk.history.restates_invariant",
864        "A history property merely re-checks a guarantee a declared `invariant`/`transition` already enforces on every reached state (testing track slice 7, ADR 0155).",
865    ),
866    dg(
867        "bynk.http.body_on_get_or_delete",
868        "A GET or DELETE handler declares a `body` parameter.",
869        &["http_handler"],
870    ),
871    d(
872        "bynk.http.cache_bad_max_age",
873        "A `@cache` annotation's `maxAge` is missing or not a positive `Duration` literal.",
874    ),
875    d(
876        "bynk.http.cache_bad_scope",
877        "A `@cache` annotation's `scope` is not `public` or `private`.",
878    ),
879    d(
880        "bynk.http.cache_duplicate",
881        "A handler carries more than one `@cache` annotation.",
882    ),
883    d(
884        "bynk.http.cache_max_age_fractional_seconds",
885        "A `@cache` annotation's `maxAge` is positive but does not resolve to a whole number of seconds.",
886    ),
887    d(
888        "bynk.http.cache_on_non_get",
889        "A `@cache` annotation is placed on a handler that is not `on http GET`.",
890    ),
891    d(
892        "bynk.http.cache_unknown_arg",
893        "A `@cache` annotation has an argument outside the closed set (`maxAge`/`scope`).",
894    ),
895    d(
896        "bynk.http.cors_invalid_field",
897        "A `cors` policy field (`headers`/`credentials`/`maxAge`) has the wrong value shape.",
898    ),
899    d(
900        "bynk.http.cors_invalid_origins",
901        "A `cors` policy's `origins` is missing, empty, or not a list of string literals.",
902    ),
903    d(
904        "bynk.http.cors_not_http",
905        "A `cors { }` policy appears on a service that is not `from http`.",
906    ),
907    d(
908        "bynk.http.cors_unknown_field",
909        "A `cors { }` policy declares a field outside the closed set.",
910    ),
911    d(
912        "bynk.http.cors_wildcard_credentials",
913        "A `cors` policy combines `credentials: true` with the wildcard origin `[\"*\"]`.",
914    ),
915    dg(
916        "bynk.http.duplicate_route",
917        "Two handlers share the same method and route.",
918        &["http_handler"],
919    ),
920    dg(
921        "bynk.http.extra_param",
922        "A handler parameter is neither a path parameter nor `body`.",
923        &["http_handler"],
924    ),
925    dg(
926        "bynk.http.invalid_path",
927        "An HTTP route path is malformed.",
928        &["http_handler"],
929    ),
930    d(
931        "bynk.http.limit_bad_max_body",
932        "A `@limit` annotation's `maxBody` is missing or not a positive `Int` literal.",
933    ),
934    d(
935        "bynk.http.limit_duplicate",
936        "A handler carries more than one `@limit` annotation.",
937    ),
938    d(
939        "bynk.http.limit_on_bodyless",
940        "A `@limit` annotation is placed on a handler that takes no body (a GET or DELETE).",
941    ),
942    d(
943        "bynk.http.limit_unknown_arg",
944        "A `@limit` annotation has an argument outside the closed set (`maxBody`).",
945    ),
946    d(
947        "bynk.http.limits_invalid_field",
948        "A `limits` policy field (`maxBody`) has the wrong value shape.",
949    ),
950    d(
951        "bynk.http.limits_not_http",
952        "A `limits { }` policy appears on a service that is not `from http`.",
953    ),
954    d(
955        "bynk.http.limits_unknown_field",
956        "A `limits { }` policy declares a field outside the closed set.",
957    ),
958    dg(
959        "bynk.http.path_param_not_stringy",
960        "A path parameter's type is not constructible from a string.",
961        &["http_handler"],
962    ),
963    dg(
964        "bynk.http.reserved_prefix",
965        "A route uses the reserved `/_bynk/` prefix.",
966        &["http_handler"],
967    ),
968    dg(
969        "bynk.http.return_not_effect_http_result",
970        "An HTTP handler does not return `Effect[HttpResult[T]]`.",
971        &["http_handler"],
972    ),
973    d(
974        "bynk.http.security_invalid_field",
975        "A `security` policy field (`hsts`/`nosniff`) has the wrong value shape.",
976    ),
977    d(
978        "bynk.http.security_not_http",
979        "A `security { }` policy appears on a service that is not `from http`.",
980    ),
981    d(
982        "bynk.http.security_unknown_field",
983        "A `security { }` policy declares a field outside the closed set.",
984    ),
985    dg(
986        "bynk.http.unbound_path_param",
987        "A `:name` route segment has no matching handler parameter.",
988        &["http_handler"],
989    ),
990    d(
991        "bynk.http.unknown_handler_annotation",
992        "A handler carries an annotation outside the closed set (`@cache`/`@limit`).",
993    ),
994    d(
995        "bynk.index.bad_argument",
996        "An `@indexed` argument is not a `by: <field>` label.",
997    ),
998    warn(d(
999        "bynk.index.missing",
1000        "A query filters a map by equality on a field that is not `@indexed` (a perf-hint warning).",
1001    )),
1002    d(
1003        "bynk.index.unkeyable_key",
1004        "An `@indexed(by: k)` field is not value-keyable.",
1005    ),
1006    d(
1007        "bynk.index.unknown_key",
1008        "An `@indexed(by: k)` field is not a field of the map's value type.",
1009    ),
1010    warn(d(
1011        "bynk.index.unused",
1012        "A declared `@indexed(by: k)` is never used by an equality filter (a hygiene warning).",
1013    )),
1014    d(
1015        "bynk.invariant.cross_agent_reference",
1016        "An invariant predicate references another agent; invariants are per-agent.",
1017    ),
1018    d(
1019        "bynk.invariant.duplicate_name",
1020        "An agent declares two invariants with the same name.",
1021    ),
1022    d(
1023        "bynk.invariant.impure_predicate",
1024        "An invariant predicate uses an effectful or test-only construct.",
1025    ),
1026    d(
1027        "bynk.invariant.not_bool",
1028        "An invariant predicate does not have type `Bool`.",
1029    ),
1030    dg(
1031        "bynk.lambda.unannotated_param",
1032        "A lambda parameter has no type annotation in a position where no function type is expected to infer it from.",
1033        &["lambda_expr"],
1034    ),
1035    dg(
1036        "bynk.lex.bad_escape",
1037        "An invalid escape sequence in a string literal.",
1038        &["string_literal"],
1039    ),
1040    dg(
1041        "bynk.lex.float_literal_overflow",
1042        "A float literal does not fit a finite 64-bit float.",
1043        &["float_literal"],
1044    ),
1045    dg(
1046        "bynk.lex.integer_overflow",
1047        "An integer literal is outside the `Int` range, the JS safe integers ±(2^53 − 1).",
1048        &["number_literal"],
1049    ),
1050    dg(
1051        "bynk.lex.interpolation_too_deep",
1052        "A string interpolation `\\(…)` nests deeper than the lexer's fixed limit.",
1053        &["string_literal"],
1054    ),
1055    d(
1056        "bynk.lex.unclosed_doc_block",
1057        "A documentation block is not closed.",
1058    ),
1059    d(
1060        "bynk.lex.unexpected_character",
1061        "An unexpected character in the source.",
1062    ),
1063    dg(
1064        "bynk.lex.unterminated_interpolation",
1065        "An interpolation hole `\\(…)` is not closed on its line.",
1066        &["string_literal"],
1067    ),
1068    dg(
1069        "bynk.lex.unterminated_string",
1070        "A string literal is not terminated.",
1071        &["string_literal"],
1072    ),
1073    warn(d(
1074        "bynk.list.deprecated_function",
1075        "A `bynk.list` free function (`map`/`filter`/`find`/`any`/`all`) is deprecated in favour of the `List` method form (warning; auto-fixable).",
1076    )),
1077    d(
1078        "bynk.locale.multiple_message_bundles",
1079        "A context consumes `Locale` but its direct `uses` reaches two or more message-bundle commons — there is no single bundle to negotiate against.",
1080    ),
1081    d(
1082        "bynk.messages.format_mismatch",
1083        "A code's placeholder is formatted as a different ICU kind (plain/plural/select/number/date) across declared locales.",
1084    ),
1085    d(
1086        "bynk.messages.incomplete",
1087        "A locale is missing a code the reference locale declares.",
1088    ),
1089    d(
1090        "bynk.messages.invalid_locale_tag",
1091        "A `messages` block's locale tag is not a valid `LocaleTag` (e.g. `messages \"xx\"` where `xx` doesn't match the tag pattern).",
1092    ),
1093    d(
1094        "bynk.messages.malformed_icu_syntax",
1095        "A message template's ICU placeholder syntax is invalid — unbalanced arm braces, an unknown format keyword, `#` outside a plural arm, a missing mandatory `other` arm, or an explicitly out-of-scope construct (`selectordinal`, `offset:`/`=N`, a CLDR skeleton).",
1096    ),
1097    d(
1098        "bynk.messages.missing_locale_dependency",
1099        "A commons declaring `messages` doesn't `uses bynk.locale` and/or `uses bynk.locale.types`, which its generated `render` and the types its signature names need.",
1100    ),
1101    d(
1102        "bynk.messages.missing_reference",
1103        "A message bundle has no `@reference` block.",
1104    ),
1105    d(
1106        "bynk.messages.multiple_reference",
1107        "A message bundle has more than one `@reference` block.",
1108    ),
1109    d(
1110        "bynk.messages.outside_commons",
1111        "A `messages` declaration appears outside a commons.",
1112    ),
1113    d(
1114        "bynk.messages.placeholder_mismatch",
1115        "A locale's template for a code uses a different set of `{name}` placeholders than the reference locale's.",
1116    ),
1117    d(
1118        "bynk.namespace.reserved",
1119        "A user unit is named `bynk` or `bynk.*`; the `bynk` root is reserved for the toolchain.",
1120    ),
1121    d(
1122        "bynk.observe.impure_with",
1123        "A `with` predicate uses an effectful or test-only construct; it must be pure.",
1124    ),
1125    d(
1126        "bynk.observe.not_a_seam",
1127        "An observation targets a capability the unit under test does not consume.",
1128    ),
1129    d(
1130        "bynk.observe.trace_outside_test",
1131        "`trace(Cap.op)` appears outside a `case` body.",
1132    ),
1133    d(
1134        "bynk.observe.unknown_op",
1135        "An observation names an operation the capability does not declare.",
1136    ),
1137    d(
1138        "bynk.observe.with_not_bool",
1139        "A `with` predicate does not have type `Bool`.",
1140    ),
1141    dg(
1142        "bynk.parse.consumes_after_decls",
1143        "`consumes` appears after other declarations.",
1144        &["consumes_decl"],
1145    ),
1146    d(
1147        "bynk.parse.dangling_handler_annotation",
1148        "A handler-position annotation (e.g. `@cache`) is not followed by an `on` handler.",
1149    ),
1150    d(
1151        "bynk.parse.doc_block_contains_code",
1152        "A documentation block's content (outside Markdown code fences) parses as declarations, so a pair of dash dividers has turned code into documentation.",
1153    ),
1154    d(
1155        "bynk.parse.doc_forms_mixed",
1156        "A declaration or member carries both a `---` doc block and `--|` doc lines; a doc is written in one form.",
1157    ),
1158    dg(
1159        "bynk.parse.duplicate_cors",
1160        "A service declares more than one `cors { }` policy.",
1161        &["service_decl"],
1162    ),
1163    dg(
1164        "bynk.parse.duplicate_limits",
1165        "A service declares more than one `limits { }` policy.",
1166        &["service_decl"],
1167    ),
1168    dg(
1169        "bynk.parse.duplicate_security",
1170        "A service declares more than one `security { }` policy.",
1171        &["service_decl"],
1172    ),
1173    dg(
1174        "bynk.parse.empty_agent",
1175        "An `agent` body is empty.",
1176        &["agent_decl"],
1177    ),
1178    dg(
1179        "bynk.parse.empty_capability",
1180        "A `capability` body is empty.",
1181        &["capability_decl"],
1182    ),
1183    d(
1184        "bynk.parse.empty_interpolation",
1185        "An interpolation hole `\\(…)` contains no expression.",
1186    ),
1187    dg(
1188        "bynk.parse.empty_match",
1189        "A `match` has no arms.",
1190        &["match_expr"],
1191    ),
1192    dg(
1193        "bynk.parse.empty_service",
1194        "A `service` body is empty.",
1195        &["service_decl"],
1196    ),
1197    d(
1198        "bynk.parse.event_pattern_empty",
1199        "A `from Events(E { ... })` subscription pattern listed no fields — use `from Events(E)` (no braces) for an unfiltered subscription.",
1200    ),
1201    dg(
1202        "bynk.parse.expected_agent_key",
1203        "Expected a `key` declaration in an agent.",
1204        &["agent_decl"],
1205    ),
1206    d(
1207        "bynk.parse.expected_agent_storage",
1208        "An agent declares no storage — it has no `store` fields.",
1209    ),
1210    dg(
1211        "bynk.parse.expected_base_type",
1212        "Expected a base type.",
1213        &["base_type"],
1214    ),
1215    dg(
1216        "bynk.parse.expected_capability_op",
1217        "Expected a capability operation.",
1218        &["capability_op"],
1219    ),
1220    d("bynk.parse.expected_expression", "Expected an expression."),
1221    dg(
1222        "bynk.parse.expected_handler",
1223        "Expected a handler.",
1224        &["handler"],
1225    ),
1226    d("bynk.parse.expected_item", "Expected a declaration."),
1227    dg(
1228        "bynk.parse.expected_predicate",
1229        "Expected a refinement predicate.",
1230        &["refinement"],
1231    ),
1232    dg(
1233        "bynk.parse.expected_provider_op",
1234        "Expected a provider operation.",
1235        &["provider_op"],
1236    ),
1237    d("bynk.parse.expected_token", "Expected a specific token."),
1238    d("bynk.parse.expected_type", "Expected a type."),
1239    d(
1240        "bynk.parse.expected_unit_header",
1241        "Expected a `commons` or `context` header.",
1242    ),
1243    dg(
1244        "bynk.parse.expected_visibility",
1245        "Expected a visibility keyword.",
1246        &["exports_decl"],
1247    ),
1248    dg(
1249        "bynk.parse.exports_after_decls",
1250        "`exports` appears after other declarations.",
1251        &["exports_decl"],
1252    ),
1253    d(
1254        "bynk.parse.extra_tokens",
1255        "Unexpected tokens after an otherwise complete construct.",
1256    ),
1257    dg(
1258        "bynk.parse.generic_arg_count",
1259        "Wrong number of generic type arguments.",
1260        &["generic_type_ref"],
1261    ),
1262    dg(
1263        "bynk.parse.handler_in_agent",
1264        "A protocol handler (`on GET`/`schedule`/`message`) was declared in an agent.",
1265        &["handler"],
1266    ),
1267    d(
1268        "bynk.parse.invariant_after_handler",
1269        "An `invariant` was declared after a handler; invariants precede handlers.",
1270    ),
1271    dg(
1272        "bynk.parse.malformed_float_literal",
1273        "A float literal is missing a digit on one side of the `.` (`1.`, `.5`).",
1274        &["float_literal"],
1275    ),
1276    d(
1277        "bynk.parse.nesting_too_deep",
1278        "An expression or type nests deeper than the parser's fixed limit.",
1279    ),
1280    dg(
1281        "bynk.parse.non_associative",
1282        "A non-associative operator was chained (e.g. `a == b == c`).",
1283        &["binary_expr"],
1284    ),
1285    warn(d(
1286        "bynk.parse.orphan_doc_block",
1287        "A documentation block is not attached to a declaration (warning).",
1288    )),
1289    dg(
1290        "bynk.parse.policy_order",
1291        "A service's `cors`/`security`/`limits` policy is out of order or follows a handler; they open the body in the order `cors`, `security`, `limits`.",
1292        &["service_decl"],
1293    ),
1294    dg(
1295        "bynk.parse.refined_pattern_inner",
1296        "A refined pattern's inner form is something other than `_`.",
1297        &["refined_pattern"],
1298    ),
1299    dg(
1300        "bynk.parse.reserved_keyword",
1301        "A reserved keyword was used as an identifier.",
1302        &["identifier"],
1303    ),
1304    dg(
1305        "bynk.parse.self_outside_method",
1306        "`self` used outside a method or handler.",
1307        &["self_expr"],
1308    ),
1309    d(
1310        "bynk.parse.storage_after_phase",
1311        "Agent storage (`state` / `store`) is declared after the invariants or handlers.",
1312    ),
1313    d(
1314        "bynk.parse.transition_after_handler",
1315        "A `transition` is declared after an agent handler; step invariants precede the handlers.",
1316    ),
1317    d(
1318        "bynk.parse.unexpected_adapter",
1319        "An `adapter` appeared where it is not allowed.",
1320    ),
1321    dg(
1322        "bynk.parse.unexpected_context",
1323        "A `context` appeared where it is not allowed.",
1324        &["context_decl"],
1325    ),
1326    d("bynk.parse.unexpected_eof", "Unexpected end of input."),
1327    dg(
1328        "bynk.parse.unexpected_suite",
1329        "A `suite` appeared where it is not allowed.",
1330        &["suite_decl"],
1331    ),
1332    d(
1333        "bynk.parse.unknown_effect_method",
1334        "An unknown method on `Effect`.",
1335    ),
1336    dg(
1337        "bynk.parse.unknown_handler_kind",
1338        "An unknown handler form (expected `call`, an HTTP method, `schedule`, or `message`).",
1339        &["handler"],
1340    ),
1341    dg(
1342        "bynk.parse.unknown_predicate",
1343        "An unknown refinement predicate.",
1344        &["predicate_name"],
1345    ),
1346    d(
1347        "bynk.parse.unknown_tier",
1348        "A `case`/`suite` `as <tier>` clause names something other than `unit`, `integration`, or `system`.",
1349    ),
1350    dg(
1351        "bynk.parse.uses_after_decls",
1352        "`uses` appears after other declarations.",
1353        &["uses_decl"],
1354    ),
1355    dg(
1356        "bynk.parse.variant_name_case",
1357        "A sum-type or enum variant name is not capitalised.",
1358        &["sum_variant", "enum_type"],
1359    ),
1360    warn(d(
1361        "bynk.project.duplicate_compatibility_flag",
1362        "`bynk.toml`'s `[workers] compatibility_flags` lists a flag twice, or one every Bynk Worker already has; the duplicate is dropped (warning).",
1363    )),
1364    d(
1365        "bynk.project.duplicate_module_doc",
1366        "More than one file of a multi-file unit carries a module doc.",
1367    ),
1368    d(
1369        "bynk.project.file_and_directory",
1370        "A unit exists as both a file and a directory.",
1371    ),
1372    d(
1373        "bynk.project.inconsistent_commons_name",
1374        "A source file's path does not match its declared name.",
1375    ),
1376    d(
1377        "bynk.project.kind_conflict",
1378        "A name is declared as both a commons and a context.",
1379    ),
1380    d(
1381        "bynk.project.no_root",
1382        "No project root could be determined.",
1383    ),
1384    d(
1385        "bynk.project.no_sources",
1386        "The project contains no source files.",
1387    ),
1388    d(
1389        "bynk.project.read_failed",
1390        "A source file could not be read.",
1391    ),
1392    d(
1393        "bynk.project.schema_registry_corrupt",
1394        "`bynk.schema.lock` (the events schema registry) is missing its version field, empty, truncated, or otherwise unparseable — restore it from version control rather than deleting it, since deleting it would silently re-baseline every event's history.",
1395    ),
1396    dg(
1397        "bynk.property.restates_refinement",
1398        "A `property` merely re-checks a refinement its type already guarantees.",
1399        &["for_all"],
1400    ),
1401    dg(
1402        "bynk.property.where_not_bool",
1403        "A `for all ... where` filter does not type to `Bool`.",
1404        &["for_all"],
1405    ),
1406    dg(
1407        "bynk.provider.dependency_cycle",
1408        "Providers form a capability dependency cycle through `given`.",
1409        &["provider_decl"],
1410    ),
1411    dg(
1412        "bynk.provider.extra_operation",
1413        "A `provides` block implements an operation not in the capability.",
1414        &["provider_decl"],
1415    ),
1416    dg(
1417        "bynk.provider.generic_op_requires_external",
1418        "A Bynk-bodied `provides` implements a capability operation that declares its own type parameter — only an external (bodiless) provider can.",
1419        &["provider_decl"],
1420    ),
1421    dg(
1422        "bynk.provider.missing_operation",
1423        "A `provides` block is missing a capability operation.",
1424        &["provider_decl"],
1425    ),
1426    dg(
1427        "bynk.provider.outside_context",
1428        "`provides` was declared outside a context.",
1429        &["provider_decl"],
1430    ),
1431    dg(
1432        "bynk.provider.signature_mismatch",
1433        "A `provides` operation's signature does not match the capability.",
1434        &["provider_decl"],
1435    ),
1436    dg(
1437        "bynk.provider.unknown_capability",
1438        "`provides` names a capability that does not exist.",
1439        &["provider_decl"],
1440    ),
1441    d(
1442        "bynk.query.join_key_mismatch",
1443        "A `joinOn`/`leftJoin` left and right key function return different types.",
1444    ),
1445    dg(
1446        "bynk.query.sum_needs_numeric",
1447        "A `sum`/`average` key function does not return a numeric type (`Int`, `Float`, or `Duration`).",
1448        &[],
1449    ),
1450    dg(
1451        "bynk.queue.bad_params",
1452        "An `on message` handler does not take exactly one `message` parameter.",
1453        &["queue_handler"],
1454    ),
1455    dg(
1456        "bynk.queue.duplicate_consumer",
1457        "Two `on message` handlers consume the same queue.",
1458        &["queue_handler"],
1459    ),
1460    dg(
1461        "bynk.queue.invalid_name",
1462        "A `from queue(\"…\")` binding has an empty queue name.",
1463        &["queue_handler"],
1464    ),
1465    dg(
1466        "bynk.queue.return_not_queue_result",
1467        "An `on message` handler does not return `Effect[QueueResult]`.",
1468        &["handler"],
1469    ),
1470    dg(
1471        "bynk.record_spread.field_type_mismatch",
1472        "A record-spread override has the wrong type for the field.",
1473        &["record_spread"],
1474    ),
1475    dg(
1476        "bynk.record_spread.non_record_base",
1477        "The base of a record spread is not a record.",
1478        &["record_spread"],
1479    ),
1480    dg(
1481        "bynk.record_spread.type_mismatch",
1482        "A record spread's base is a different record type.",
1483        &["record_spread"],
1484    ),
1485    dg(
1486        "bynk.record_spread.unknown_field",
1487        "A record spread overrides a field the record does not have.",
1488        &["record_spread"],
1489    ),
1490    dg(
1491        "bynk.refine.literal_violates",
1492        "A literal does not satisfy the refined type's predicate.",
1493        &["refined_type"],
1494    ),
1495    dg(
1496        "bynk.requires.unpinned_dependency",
1497        "An adapter `binding … requires { … }` entry has an unpinned version range.",
1498        &["binding_decl"],
1499    ),
1500    d(
1501        "bynk.resolve.ambiguous_variant",
1502        "A variant name is ambiguous across several sum types.",
1503    ),
1504    dg(
1505        "bynk.resolve.arity_mismatch",
1506        "A function was called with the wrong number of arguments.",
1507        &["call"],
1508    ),
1509    d("bynk.resolve.duplicate_actor", "Two actors share a name."),
1510    dg(
1511        "bynk.resolve.duplicate_agent",
1512        "Two agents share a name.",
1513        &["agent_decl"],
1514    ),
1515    dg(
1516        "bynk.resolve.duplicate_capability",
1517        "Two capabilities share a name.",
1518        &["capability_decl"],
1519    ),
1520    dg(
1521        "bynk.resolve.duplicate_field",
1522        "A record declares a field twice.",
1523        &["record_type"],
1524    ),
1525    dg(
1526        "bynk.resolve.duplicate_field_init",
1527        "A record construction initialises a field twice.",
1528        &["record_construction"],
1529    ),
1530    dg(
1531        "bynk.resolve.duplicate_fn",
1532        "Two functions share a name.",
1533        &["fn_decl"],
1534    ),
1535    d(
1536        "bynk.resolve.duplicate_message_code",
1537        "A message bundle declares the same code twice in one block.",
1538    ),
1539    d(
1540        "bynk.resolve.duplicate_message_locale",
1541        "Two `messages` blocks in one bundle declare the same locale tag.",
1542    ),
1543    dg(
1544        "bynk.resolve.duplicate_method",
1545        "Two methods share a name.",
1546        &["fn_decl"],
1547    ),
1548    dg(
1549        "bynk.resolve.duplicate_param",
1550        "A parameter name is repeated.",
1551        &["param"],
1552    ),
1553    dg(
1554        "bynk.resolve.duplicate_provider",
1555        "A capability is provided more than once.",
1556        &["provider_decl"],
1557    ),
1558    dg(
1559        "bynk.resolve.duplicate_service",
1560        "Two services share a name.",
1561        &["service_decl"],
1562    ),
1563    dg(
1564        "bynk.resolve.duplicate_type",
1565        "Two types share a name.",
1566        &["type_decl"],
1567    ),
1568    dg(
1569        "bynk.resolve.duplicate_variant",
1570        "A sum type declares a variant twice.",
1571        &["sum_type"],
1572    ),
1573    d(
1574        "bynk.resolve.fn_without_call",
1575        "A function was referenced without being called.",
1576    ),
1577    dg(
1578        "bynk.resolve.let_shadows_fn",
1579        "A `let` binding shadows a function.",
1580        &["let_stmt"],
1581    ),
1582    dg(
1583        "bynk.resolve.let_shadows_type",
1584        "A `let` binding shadows a type.",
1585        &["let_stmt"],
1586    ),
1587    d(
1588        "bynk.resolve.method_unknown_type",
1589        "A method is defined on an unknown type.",
1590    ),
1591    dg(
1592        "bynk.resolve.missing_field",
1593        "A record construction omits a required field.",
1594        &["record_construction"],
1595    ),
1596    d(
1597        "bynk.resolve.name_conflict",
1598        "Two declarations share a name.",
1599    ),
1600    dg(
1601        "bynk.resolve.not_a_record_type",
1602        "Record syntax was used on a non-record type.",
1603        &["record_construction"],
1604    ),
1605    dg(
1606        "bynk.resolve.opaque_record_construction",
1607        "An opaque type was constructed with record syntax.",
1608        &["record_construction"],
1609    ),
1610    dg(
1611        "bynk.resolve.param_as_function",
1612        "A value (such as a parameter) was called as a function.",
1613        &["call"],
1614    ),
1615    dg(
1616        "bynk.resolve.recursive_record_field",
1617        "A record directly contains a field of its own type.",
1618        &["record_type"],
1619    ),
1620    dg(
1621        "bynk.resolve.reserved_builtin_type",
1622        "A type declaration reuses a compiler-known built-in type name.",
1623        &["type_decl"],
1624    ),
1625    dg(
1626        "bynk.resolve.reserved_host_name",
1627        "A declaration is named `globalThis`, which the generated TypeScript uses to reach host globals.",
1628        &["type_decl", "fn_decl", "agent_decl", "provider_decl"],
1629    ),
1630    dg(
1631        "bynk.resolve.reserved_payload_field",
1632        "A sum variant declares a payload field named `kind`, the variant's wire discriminant.",
1633        &["sum_type"],
1634    ),
1635    dg(
1636        "bynk.resolve.self_outside_method",
1637        "`self` referenced outside a method or handler.",
1638        &["self_expr"],
1639    ),
1640    dg(
1641        "bynk.resolve.type_as_function",
1642        "A type name was called as if it were a function.",
1643        &["call"],
1644    ),
1645    d(
1646        "bynk.resolve.type_in_expr",
1647        "A type name was used where a value is expected.",
1648    ),
1649    dg(
1650        "bynk.resolve.unconsumed_context",
1651        "A context's service was called without a `consumes` declaration.",
1652        &["consumes_decl"],
1653    ),
1654    dg(
1655        "bynk.resolve.unknown_field",
1656        "Accessed a field the record does not have.",
1657        &["field_access"],
1658    ),
1659    dg(
1660        "bynk.resolve.unknown_function",
1661        "Called a function that does not exist.",
1662        &["call"],
1663    ),
1664    d(
1665        "bynk.resolve.unknown_name",
1666        "Referenced a name that is not in scope.",
1667    ),
1668    dg(
1669        "bynk.resolve.unknown_static_member",
1670        "Referenced an unknown static member (e.g. `T.x`).",
1671        &["field_access"],
1672    ),
1673    d(
1674        "bynk.resolve.unknown_type",
1675        "Referenced a type that does not exist.",
1676    ),
1677    warn(d(
1678        "bynk.secrets.computed_name",
1679        "A `bynk.Secrets` read names its secret with a computed expression rather than a literal, so `bynk deploy` cannot plan it (warning).",
1680    )),
1681    dg(
1682        "bynk.send.in_pure_context",
1683        "A `~>` send was used in a pure (non-effectful) context.",
1684        &["effect_send_stmt"],
1685    ),
1686    dg(
1687        "bynk.send.non_effect",
1688        "A `~>` send was applied to a non-`Effect` value.",
1689        &["effect_send_stmt"],
1690    ),
1691    dg(
1692        "bynk.send.requires_unit",
1693        "A `~>` send targets an operation whose reply is not `Effect[()]`.",
1694        &["effect_send_stmt"],
1695    ),
1696    dg(
1697        "bynk.service.missing_from",
1698        "A `from`-less service has a handler other than `on call`.",
1699        &["service_decl"],
1700    ),
1701    dg(
1702        "bynk.service.mixed_protocols",
1703        "A service mixes handler forms that do not match its `from <protocol>`.",
1704        &["service_decl"],
1705    ),
1706    dg(
1707        "bynk.service.outside_context",
1708        "A `service` was declared outside a context.",
1709        &["service_decl"],
1710    ),
1711    dg(
1712        "bynk.service.return_not_effect",
1713        "A service handler's return type is not an `Effect`.",
1714        &["service_decl"],
1715    ),
1716    dg(
1717        "bynk.service.unknown_protocol",
1718        "A `from <protocol>` names an unknown protocol (e.g. a transport like Kafka).",
1719        &["service_decl"],
1720    ),
1721    d(
1722        "bynk.service.unknown_via_clause",
1723        "A `via <name>(...)` clause on a `from Events(...)` header named something other than `schema` — `via` clauses are a closed set, and only `via schema(...)` exists today.",
1724    ),
1725    d(
1726        "bynk.service.websocket_header",
1727        "The `from websocket` header is malformed — it binds frame types as `websocket(in: <type>, out: <type>)` (real-time track slice 3).",
1728    ),
1729    d(
1730        "bynk.service.websocket_multiple",
1731        "A context holds more than one `from websocket` service — at v1 the Workers upgrade routes by the `Upgrade: websocket` header alone, so one WebSocket service per context (real-time track slice 3b).",
1732    ),
1733    d(
1734        "bynk.service.websocket_open_arity",
1735        "A `from websocket` service must hold exactly one `on open` handler (the edge upgrade), and at most one `on message` (inbound) and one `on close` (real-time track slice 3/3b-iii).",
1736    ),
1737    d(
1738        "bynk.service.websocket_param_not_stringy",
1739        "A `from websocket` service's `on open` parameter has a type not constructible from `String`; it arrives as a query-string value (#1657).",
1740    ),
1741    d(
1742        "bynk.store.annotation_kind_mismatch",
1743        "A storage annotation is used on a kind it does not apply to (e.g. `@ttl` on a `Map`).",
1744    ),
1745    d(
1746        "bynk.store.annotation_unsupported",
1747        "A known storage annotation (`@ttl`/`@retain`/`@indexed`/`@bounded`) is used before the slice that supports it.",
1748    ),
1749    d(
1750        "bynk.store.cache_needs_clock",
1751        "A handler performs a `Cache` operation (TTL expiry reads the clock) without declaring `given Clock`.",
1752    ),
1753    d(
1754        "bynk.store.cache_ttl_required",
1755        "A `Cache` field is missing its required `@ttl(<duration>)` annotation (a keyed store with no expiry is a `Map`).",
1756    ),
1757    d(
1758        "bynk.store.kind_arity",
1759        "A storage kind was applied to the wrong number of type arguments (e.g. `Cell[A, B]`).",
1760    ),
1761    d(
1762        "bynk.store.kind_unsupported",
1763        "A known storage kind (`Queue`) is used before the slice that supports it.",
1764    ),
1765    d(
1766        "bynk.store.log_needs_clock",
1767        "A handler calls `Log.append` (which stamps the current time) without declaring `given Clock`.",
1768    ),
1769    d(
1770        "bynk.store.unkeyable_key",
1771        "A store `Set` element or `Map`/`Cache` key is not value-keyable — it must be `String`, `Int`, or a refined/opaque type over them (#1680).",
1772    ),
1773    d(
1774        "bynk.store.unknown_annotation",
1775        "A `store` field carries an annotation outside the closed `@indexed`/`@ttl`/`@retain`/`@bounded` set.",
1776    ),
1777    d(
1778        "bynk.store.unknown_kind",
1779        "A `store` field's type is not a known storage kind.",
1780    ),
1781    d(
1782        "bynk.store.unknown_map_accessor",
1783        "A `store Map` field access is not one of its query accessors (`entries`/`keys`/`values`).",
1784    ),
1785    d(
1786        "bynk.store.unknown_op",
1787        "A storage-`Map`/`Set` operation is not a recognised entry/membership method.",
1788    ),
1789    d(
1790        "bynk.stub.bad_sequence",
1791        "A `stub … returns each […]` sequence is malformed (e.g. empty).",
1792    ),
1793    d(
1794        "bynk.stub.generic_op",
1795        "A test `stub` targets a capability operation that declares its own type parameter — not supported at v1.",
1796    ),
1797    d(
1798        "bynk.stub.not_a_seam",
1799        "A test `stub` overrides a capability the unit under test does not consume.",
1800    ),
1801    d(
1802        "bynk.stub.rhs_type",
1803        "A test `stub … returns <value>` right-hand side does not match the operation's return type.",
1804    ),
1805    d(
1806        "bynk.stub.unknown_op",
1807        "A test `stub` names an operation the capability does not declare.",
1808    ),
1809    dg(
1810        "bynk.suite.duplicate_case_name",
1811        "Two `case`s share a description.",
1812        &["case"],
1813    ),
1814    dg(
1815        "bynk.suite.unknown_target",
1816        "A `suite` targets a unit that does not exist.",
1817        &["suite_decl"],
1818    ),
1819    d(
1820        "bynk.target.browser_bundle_only",
1821        "The `browser` platform builds only the in-process `Bundle` topology; `--target workers` is not a browser build.",
1822    ),
1823    dg(
1824        "bynk.target.vendor_conflict",
1825        "One deployment unit's in-process closure uses platform-native capabilities from two mutually-exclusive platforms.",
1826        &["consumes_decl"],
1827    ),
1828    dg(
1829        "bynk.target.vendor_required",
1830        "A deployment unit uses a platform-native capability but the build selects another `--platform`.",
1831        &["consumes_decl"],
1832    ),
1833    dg(
1834        "bynk.test.actor_identity_required",
1835        "A call-site `by <Actor>` omits the identity an identity-carrying actor requires.",
1836        &["case"],
1837    ),
1838    dg(
1839        "bynk.test.actor_no_identity",
1840        "A call-site `by <Actor>(x)` supplies an identity to an actor that takes none — a unit-identity actor (e.g. `Visitor`) or `Nobody`.",
1841        &["case"],
1842    ),
1843    dg(
1844        "bynk.test.asset_address_method",
1845        "A suite fetches an asset with a method other than `GET`; the platform serves assets to `GET` and answers other methods with 405.",
1846        &["case"],
1847    ),
1848    dg(
1849        "bynk.test.credential_needs_system",
1850        "A case drives `by Nobody` (the no-credential principal, which tests the auth seam's 401) outside a `system`-tier case, where there is no real seam to reject it.",
1851        &["case"],
1852    ),
1853    dg(
1854        "bynk.test.faults_needs_in_process",
1855        "A `system`-tier case claims a fault with `expect <call> faults`, or a fault claim at any tier is driven `by Nobody`; at `system` a fault reaches the case as an error response from the deployed Worker, never a throw, so the claim belongs at `unit` or `integration`.",
1856        &["case"],
1857    ),
1858    dg(
1859        "bynk.test.nobody_needs_secured_route",
1860        "A case drives `by Nobody` at a route that is not Bearer-secured (e.g. a public `Visitor` route) — there is no auth seam to reject the missing credential.",
1861        &["case"],
1862    ),
1863    dg(
1864        "bynk.test.principal_identity_mismatch",
1865        "A call-site `by <Actor>` acts as an actor whose identity is incompatible with the addressed handler's actor.",
1866        &["case"],
1867    ),
1868    dg(
1869        "bynk.test.principal_on_asset",
1870        "A suite's asset fetch carries a `by` clause; an asset is public and served before the Worker runs.",
1871        &["case"],
1872    ),
1873    dg(
1874        "bynk.test.principal_on_wrong_method",
1875        "A wrong-method `405` test carries a `by <Actor>` clause; it reaches no handler, so a principal is meaningless.",
1876        &["case"],
1877    ),
1878    dg(
1879        "bynk.test.principal_required",
1880        "A test drives an identity-carrying handler with no call-site `by <Actor>(<identity>)`.",
1881        &["case"],
1882    ),
1883    dg(
1884        "bynk.test.service_bad_address",
1885        "A test body addresses a service the wrong way for its protocol (e.g. an http route without a leading path string).",
1886        &["case"],
1887    ),
1888    dg(
1889        "bynk.test.service_call_arity",
1890        "A test body's `svc.call(...)` passes the wrong number of arguments for the service's `on call` handler.",
1891        &["case"],
1892    ),
1893    dg(
1894        "bynk.test.service_no_call_handler",
1895        "A test body invokes `svc.call(...)` on a service with no `on call` handler (a `from http`/`cron`/`queue` service).",
1896        &["case"],
1897    ),
1898    dg(
1899        "bynk.test.service_unknown_route",
1900        "A test body addresses an http route / cron schedule / queue message the service does not declare.",
1901        &["case"],
1902    ),
1903    dg(
1904        "bynk.test.unknown_actor",
1905        "A call-site `by <Actor>` names an actor the target context does not declare and that is not a prelude actor.",
1906        &["case"],
1907    ),
1908    dg(
1909        "bynk.test.wire_needs_system",
1910        "A `Wire(...)` raw argument is used outside a `system`-tier service address; `Wire` hands pre-validation input to the boundary and is meaningless at `unit` or in any other position.",
1911        &["case"],
1912    ),
1913    dg(
1914        "bynk.tier.cross_context_needs_system",
1915        "A `unit` or `integration` case, or a `property`, reaches another context's service, directly or through a target service or agent handler that calls one; below `system` no other context is stood up to call, so the flow belongs in a `suite … as system`.",
1916        &["case"],
1917    ),
1918    dg(
1919        "bynk.tier.mixed_system_suite",
1920        "A suite mixes `system` cases with `unit` or `integration` ones; a `system` case runs against deployed Workers and addresses services by context path, so it needs a `suite … as system` of its own.",
1921        &["case"],
1922    ),
1923    d(
1924        "bynk.tier.system_needs_wire",
1925        "An `as system` test stands up fewer than two contexts; the system tier wires across contexts.",
1926    ),
1927    d(
1928        "bynk.transition.cross_agent_reference",
1929        "A transition predicate references another agent; step invariants are per-agent.",
1930    ),
1931    d(
1932        "bynk.transition.duplicate_name",
1933        "An agent declares two transitions with the same name.",
1934    ),
1935    d(
1936        "bynk.transition.impure_predicate",
1937        "A transition predicate uses an effectful or test-only construct; a step invariant must be pure.",
1938    ),
1939    d(
1940        "bynk.transition.no_step_reference",
1941        "A transition references neither `old` nor `new`; it constrains one state, so it is an `invariant`, not a step.",
1942    ),
1943    d(
1944        "bynk.transition.not_bool",
1945        "A transition predicate does not have type `Bool`.",
1946    ),
1947    dg(
1948        "bynk.types.argument_mismatch",
1949        "A call, method, capability, or constructor argument has the wrong type.",
1950        &["call"],
1951    ),
1952    d(
1953        "bynk.types.asset_at_boundary",
1954        "An `Asset` type appears in a record field, boundary or store position; pass its `.url` instead.",
1955    ),
1956    dg(
1957        "bynk.types.call_arity",
1958        "A function value was applied with the wrong number of arguments.",
1959        &["call"],
1960    ),
1961    dg(
1962        "bynk.types.cannot_infer_option_type_param",
1963        "The value type of `None` could not be inferred.",
1964        &["none_expr"],
1965    ),
1966    d(
1967        "bynk.types.cannot_infer_result_type_params",
1968        "The type parameters of a `Result` could not be inferred.",
1969    ),
1970    dg(
1971        "bynk.types.catastrophic_regex",
1972        "A `Matches` pattern can match the same text in exponentially many ways (nested or ambiguous repetition, bounded or not), or cannot be analysed, risking catastrophic backtracking (ReDoS).",
1973        &["refinement"],
1974    ),
1975    dg(
1976        "bynk.types.combinator_return_mismatch",
1977        "A callback passed to a combinator (`map`/`andThen`/`flatMap`/`traverseAll`/…) returns the wrong type.",
1978        &["call"],
1979    ),
1980    d(
1981        "bynk.types.constructor_arity",
1982        "A variant constructor got the wrong number of arguments.",
1983    ),
1984    d(
1985        "bynk.types.constructor_base_mismatch",
1986        "A `.of` constructor was given an argument of the wrong base type.",
1987    ),
1988    dg(
1989        "bynk.types.duplicate_literal_arm",
1990        "A `match` has two arms for the same literal value.",
1991        &["match_arm"],
1992    ),
1993    dg(
1994        "bynk.types.duplicate_variant_arm",
1995        "A `match` has two arms for the same variant.",
1996        &["match_arm"],
1997    ),
1998    d(
1999        "bynk.types.embeds_ambiguous",
2000        "A type is embedded by more than one variant of a sum, so `?`'s conversion would be ambiguous.",
2001    ),
2002    d(
2003        "bynk.types.embeds_unknown_variant",
2004        "An `embeds … as V` clause names a variant the sum does not declare.",
2005    ),
2006    d(
2007        "bynk.types.embeds_variant_shape",
2008        "An `embeds E as V` target variant must have exactly one payload field, of type `E`.",
2009    ),
2010    dg(
2011        "bynk.types.empty_refinement",
2012        "A refinement admits no values (contradictory predicates).",
2013        &["refinement"],
2014    ),
2015    dg(
2016        "bynk.types.err_value_mismatch",
2017        "An `Err` payload has the wrong type.",
2018        &["err_expr"],
2019    ),
2020    dg(
2021        "bynk.types.field_access_on_non_record",
2022        "Field access on a value that is not a record.",
2023        &["field_access"],
2024    ),
2025    dg(
2026        "bynk.types.field_refinement_not_base",
2027        "An inline field refinement requires a base or refined type.",
2028        &["record_field"],
2029    ),
2030    dg(
2031        "bynk.types.field_value_mismatch",
2032        "A record field was given a value of the wrong type.",
2033        &["record_construction"],
2034    ),
2035    dg(
2036        "bynk.types.function_at_boundary",
2037        "A function type appeared in a serialisable or boundary position (a record field, sum payload, service/agent handler signature, capability operation signature, agent state field, or agent key); functions cannot serialise or cross a boundary.",
2038        &["function_type_ref"],
2039    ),
2040    dg(
2041        "bynk.types.guard_not_bool",
2042        "A match-arm `if` guard is not a `Bool` expression.",
2043        &["match_arm"],
2044    ),
2045    d(
2046        "bynk.types.held_at_boundary",
2047        "A held value (`Connection[F]`) appears in a serialisable or boundary position — a held resource is built and disposed in place, never persisted or sent across a boundary (§2.9, real-time track slice 2).",
2048    ),
2049    d(
2050        "bynk.types.held_not_comparable",
2051        "A held value (`Connection[F]`) is compared with `==`/`!=` — held values have identity, not value-equality (§2.9.3, real-time track slice 2).",
2052    ),
2053    dg(
2054        "bynk.types.if_branch_mismatch",
2055        "The branches of an `if` have different types.",
2056        &["if_expr"],
2057    ),
2058    dg(
2059        "bynk.types.if_non_bool_cond",
2060        "An `if` condition is not a `Bool`.",
2061        &["if_expr"],
2062    ),
2063    dg(
2064        "bynk.types.if_without_else_requires_unit",
2065        "An `if` with no `else` branch has a non-unit then-branch; the missing else defaults to `()`, so the branch must be `()` or `Effect[()]`.",
2066        &["if_expr"],
2067    ),
2068    d(
2069        "bynk.types.interpolation_non_scalar",
2070        "An interpolation hole holds a value with no string form.",
2071    ),
2072    dg(
2073        "bynk.types.invalid_regex",
2074        "A `Matches` predicate contains an invalid regular expression.",
2075        &["refinement"],
2076    ),
2077    dg(
2078        "bynk.types.inverted_range",
2079        "An `InRange` predicate has its bounds inverted.",
2080        &["refinement"],
2081    ),
2082    dg(
2083        "bynk.types.is_base_mismatch",
2084        "An `is` refinement check is applied to a value of the wrong base type.",
2085        &["is_expr"],
2086    ),
2087    dg(
2088        "bynk.types.is_literal_pattern",
2089        "A literal was used on the right of `is`; `is` tests type/refinement, not value equality (use `==`).",
2090        &["is_expr"],
2091    ),
2092    dg(
2093        "bynk.types.is_non_sum",
2094        "`is` was applied to a value that is not a sum type.",
2095        &["is_expr"],
2096    ),
2097    dg(
2098        "bynk.types.is_refined_pattern",
2099        "A refined (`where`) pattern was used on the right of `is`; refined patterns are `match`-only.",
2100        &["is_expr"],
2101    ),
2102    dg(
2103        "bynk.types.is_unknown_variant",
2104        "`is` names a variant the type does not have.",
2105        &["is_expr"],
2106    ),
2107    dg(
2108        "bynk.types.json_uncodable",
2109        "A `Json.encode`/`Json.decode` target type cannot pass through the typed JSON codec (functions, effects, error builtins).",
2110        &["method_call"],
2111    ),
2112    dg(
2113        "bynk.types.key_not_orderable",
2114        "A `sortBy`/`min`/`max` key function does not return an orderable type (`Int`, `Float`, `String`, `Duration`, or `Instant`).",
2115        &[],
2116    ),
2117    dg(
2118        "bynk.types.lambda_mismatch",
2119        "A lambda's parameter count, parameter annotations, or body type do not match the expected function type.",
2120        &["lambda_expr"],
2121    ),
2122    dg(
2123        "bynk.types.let_annotation_mismatch",
2124        "A `let` value does not match its type annotation.",
2125        &["let_stmt"],
2126    ),
2127    dg(
2128        "bynk.types.list_element_mismatch",
2129        "A list-literal element has a different type from the list's element type.",
2130        &["list_literal"],
2131    ),
2132    dg(
2133        "bynk.types.match_arm_mismatch",
2134        "A `match` arm has a different type from the others.",
2135        &["match_arm"],
2136    ),
2137    dg(
2138        "bynk.types.match_non_sum_discriminant",
2139        "`match` was applied to a value that is not a sum type.",
2140        &["match_expr"],
2141    ),
2142    dg(
2143        "bynk.types.method_arity",
2144        "A method was called with the wrong number of arguments.",
2145        &["method_call"],
2146    ),
2147    dg(
2148        "bynk.types.method_not_found",
2149        "Called a method the type does not have.",
2150        &["method_call"],
2151    ),
2152    dg(
2153        "bynk.types.method_on_non_named_type",
2154        "A method was called on a built-in type that has no methods.",
2155        &["method_call"],
2156    ),
2157    dg(
2158        "bynk.types.mixed_pattern_bindings",
2159        "A pattern mixes named and positional bindings.",
2160        &["variant_pattern"],
2161    ),
2162    dg(
2163        "bynk.types.negative_length",
2164        "A length predicate was given a negative value.",
2165        &["refinement"],
2166    ),
2167    dg(
2168        "bynk.types.no_numeric_coercion",
2169        "`Int` and `Float` were mixed without an explicit conversion — in an operation or in refinement bounds.",
2170        &["binary_expr", "refinement"],
2171    ),
2172    dg(
2173        "bynk.types.non_exhaustive_match",
2174        "A `match` does not cover every variant.",
2175        &["match_expr"],
2176    ),
2177    d(
2178        "bynk.types.not_comparable",
2179        "A value compared with `==`/`!=` contains a function, `Effect`, or `Query` somewhere inside it — those have no value equality, so the type is not equality-supporting (type-system §2.3.5, #1652).",
2180    ),
2181    dg(
2182        "bynk.types.ok_value_mismatch",
2183        "An `Ok` payload has the wrong type.",
2184        &["ok_expr"],
2185    ),
2186    dg(
2187        "bynk.types.opaque_raw_outside",
2188        "`.raw` on an opaque type was used outside its defining commons.",
2189        &["field_access"],
2190    ),
2191    dg(
2192        "bynk.types.opaque_unsafe_outside",
2193        "`.unsafe` on an opaque type was used outside its defining context.",
2194        &["field_access"],
2195    ),
2196    dg(
2197        "bynk.types.or_pattern_binding_mismatch",
2198        "An or-pattern's alternatives don't all bind the same set of names.",
2199        &["match_arm", "is_expr"],
2200    ),
2201    dg(
2202        "bynk.types.or_pattern_type_mismatch",
2203        "An or-pattern's alternatives give a shared binding different types (or refinements).",
2204        &["match_arm", "is_expr"],
2205    ),
2206    dg(
2207        "bynk.types.pattern_arity",
2208        "A pattern binds the wrong number of payload fields.",
2209        &["variant_pattern"],
2210    ),
2211    dg(
2212        "bynk.types.pattern_type_mismatch",
2213        "A pattern's type does not match the matched value.",
2214        &["variant_pattern"],
2215    ),
2216    dg(
2217        "bynk.types.polynomial_regex",
2218        "A `Matches` pattern can split the same text between repetitions, so matching time grows polynomially with input length, and no length predicate bounds the input small enough for its degree.",
2219        &["refinement"],
2220    ),
2221    warn(dg(
2222        "bynk.types.polynomial_regex_capped",
2223        "A `Matches` pattern's matching time grows polynomially with input length, but a `MaxLength` or `Length` predicate bounds the input small enough for its degree (warning).",
2224        &["refinement"],
2225    )),
2226    dg(
2227        "bynk.types.predicate_base_mismatch",
2228        "A predicate does not apply to the type's base (e.g. a string predicate on an `Int`).",
2229        &["refinement"],
2230    ),
2231    d(
2232        "bynk.types.query_at_boundary",
2233        "A `Query` type appears in a storable or boundary-crossing position — a query is built and executed in place, never persisted or sent (ADR 0115).",
2234    ),
2235    dg(
2236        "bynk.types.question_error_mismatch",
2237        "`?` propagates an error type incompatible with the function's.",
2238        &["question_expr"],
2239    ),
2240    dg(
2241        "bynk.types.question_on_non_result",
2242        "`?` was applied to a non-`Result` value.",
2243        &["question_expr"],
2244    ),
2245    dg(
2246        "bynk.types.question_option_outside_http",
2247        "`?` lifts an `Option` only inside a handler returning `HttpResult` (`None` becomes `NotFound`); elsewhere use `.okOr(err)`.",
2248        &["question_expr"],
2249    ),
2250    dg(
2251        "bynk.types.question_outside_result",
2252        "`?` used in a function that does not return a `Result`.",
2253        &["question_expr"],
2254    ),
2255    d(
2256        "bynk.types.return_mismatch",
2257        "A returned value does not match the declared return type.",
2258    ),
2259    dg(
2260        "bynk.types.some_value_mismatch",
2261        "A `Some` payload has the wrong type.",
2262        &["some_expr"],
2263    ),
2264    d(
2265        "bynk.types.stream_at_boundary",
2266        "A `Stream` type appears in a storable or boundary-crossing position — a stream is a live value-over-time source, never persisted or sent across a boundary (real-time track slice 0).",
2267    ),
2268    d(
2269        "bynk.types.stream_not_comparable",
2270        "A `Stream` value is compared with `==`/`!=` — a stream is a live value-over-time source, not a comparable value (real-time track slice 0).",
2271    ),
2272    d(
2273        "bynk.types.type_mismatch",
2274        "Two types that were required to match did not.",
2275    ),
2276    dg(
2277        "bynk.types.uninferable_element_type",
2278        "An empty `[]` (or `List.empty()` / `Map.empty()`) has no expected type to infer its element type from.",
2279        &["list_literal"],
2280    ),
2281    dg(
2282        "bynk.types.unkeyable_distinct",
2283        "A `distinct`/`distinctBy` element or key is not value-keyable (`String`, `Int`, or a refined/opaque type over them).",
2284        &[],
2285    ),
2286    dg(
2287        "bynk.types.unkeyable_map_key",
2288        "A `Map` key type is not value-keyable (`String`, `Int`, or a refined/opaque type over them).",
2289        &["generic_type_ref"],
2290    ),
2291    dg(
2292        "bynk.types.unknown_field",
2293        "Referenced a field the record type does not declare.",
2294        &["field_access"],
2295    ),
2296    dg(
2297        "bynk.types.unknown_pattern_field",
2298        "A pattern names a field the variant does not have.",
2299        &["variant_pattern"],
2300    ),
2301    dg(
2302        "bynk.types.unknown_static_member",
2303        "Referenced an unknown static member on a type.",
2304        &["field_access"],
2305    ),
2306    dg(
2307        "bynk.types.unknown_variant_in_pattern",
2308        "A pattern names a variant the sum type does not have.",
2309        &["variant_pattern"],
2310    ),
2311    dg(
2312        "bynk.types.unreachable_arm",
2313        "A `match` arm is unreachable.",
2314        &["match_arm"],
2315    ),
2316    d(
2317        "bynk.types.variant_arity",
2318        "A variant constructor got the wrong number of payload values.",
2319    ),
2320    d(
2321        "bynk.types.variant_missing_payload",
2322        "A variant requiring a payload was used without one.",
2323    ),
2324    d(
2325        "bynk.types.variant_payload_mismatch",
2326        "A variant payload has the wrong type.",
2327    ),
2328    dg(
2329        "bynk.uses.name_conflict",
2330        "A `uses` name collides with another name, a value crosses between a unit's code and an imported declaration's position whose type the unit shadows, or a reference names an import the unit's own declaration shadows.",
2331        &["uses_decl"],
2332    ),
2333    dg(
2334        "bynk.uses.self_reference",
2335        "A commons `uses` itself.",
2336        &["uses_decl"],
2337    ),
2338    dg(
2339        "bynk.uses.target_is_context",
2340        "`uses` targets a context instead of a commons.",
2341        &["uses_decl"],
2342    ),
2343    dg(
2344        "bynk.uses.unknown_commons",
2345        "`uses` names a commons that does not exist.",
2346        &["uses_decl"],
2347    ),
2348    dg(
2349        "bynk.val.agent_not_generable",
2350        "A `for all`/`Val` cannot generate an agent — fabricated agent states need not be reachable.",
2351        &["for_all"],
2352    ),
2353    dg(
2354        "bynk.val.arity",
2355        "`Val[T]` was given the wrong number of pin arguments.",
2356        &["val_expr"],
2357    ),
2358    dg(
2359        "bynk.val.literal_violates",
2360        "A pinned `Val[T]` value violates the type's refinement.",
2361        &["val_expr"],
2362    ),
2363    dg(
2364        "bynk.val.needs_pin",
2365        "A bare `Val[T]` cannot generate a value (e.g. a `Matches` string); pin one.",
2366        &["val_expr"],
2367    ),
2368    dg(
2369        "bynk.val.outside_test",
2370        "`Val[T]` was used outside a test case body.",
2371        &["val_expr"],
2372    ),
2373    dg(
2374        "bynk.val.pin_not_literal",
2375        "A `Val[T]` pin argument is not a compile-time literal.",
2376        &["val_expr"],
2377    ),
2378    dg(
2379        "bynk.val.pin_unsupported",
2380        "A pin was given for a type kind that does not support pinning.",
2381        &["val_expr"],
2382    ),
2383    dg(
2384        "bynk.val.unknown_type",
2385        "`Val[T]` names a type that does not resolve.",
2386        &["val_expr"],
2387    ),
2388    dg(
2389        "bynk.val.unsupported_kind",
2390        "`Val[T]` cannot fabricate a value for this kind of type.",
2391        &["val_expr"],
2392    ),
2393    d(
2394        "bynk.wasm.panic",
2395        "The in-browser compiler panicked internally (a compiler bug, reported as a diagnostic instead of crashing the page).",
2396    ),
2397    d(
2398        "bynk.wasm.strip_failed",
2399        "The in-browser compiler could not strip the emitted TypeScript to JavaScript.",
2400    ),
2401    d(
2402        "bynk.ws.message_frame_param",
2403        "A WebSocket `on message` handler does not have exactly one parameter of the service's inbound (`in:`) frame type — the decoded frame (real-time track slice 3b-iii).",
2404    ),
2405    d(
2406        "bynk.ws.open_given_unsupported",
2407        "A WebSocket `on open` handler declares `given` capabilities — unsupported at v1, since on Workers the handler runs inside the connection-hosting Durable Object, which has no composition root to supply them (real-time track slice 3b).",
2408    ),
2409    d(
2410        "bynk.ws.open_transfer_shape",
2411        "A WebSocket `on open` handler does not transfer its `connection` into exactly one agent, so the Workers upgrade has no single Durable Object to route to (real-time track slice 3b).",
2412    ),
2413    d(
2414        "bynk.ws.route_param_mismatch",
2415        "A WebSocket `on message`/`on close` route parameter does not match the `on open` parameter at the same position — route values are recovered positionally from the connection, so they must be a type-compatible prefix of the `on open` parameters (real-time track slice 3b-iii).",
2416    ),
2417];
2418
2419/// A diagnostic with no single governing grammar construct. `Error` severity.
2420const fn d(code: &'static str, summary: &'static str) -> DiagnosticInfo {
2421    DiagnosticInfo {
2422        code,
2423        summary,
2424        grammar_symbol: &[],
2425        severity: Severity::Error,
2426    }
2427}
2428
2429/// A diagnostic that constrains one or more grammar productions. `Error` severity.
2430const fn dg(
2431    code: &'static str,
2432    summary: &'static str,
2433    grammar_symbol: &'static [&'static str],
2434) -> DiagnosticInfo {
2435    DiagnosticInfo {
2436        code,
2437        summary,
2438        grammar_symbol,
2439        severity: Severity::Error,
2440    }
2441}
2442
2443/// Downgrades a [`d`]/[`dg`]-built entry to `Warning` severity (ADR 0117) —
2444/// non-failing, surfaced alongside a clean build. Its call sites here are
2445/// the single source of truth [`crate::error::Severity::for_error`] reads.
2446const fn warn(mut info: DiagnosticInfo) -> DiagnosticInfo {
2447    info.severity = Severity::Warning;
2448    info
2449}
2450
2451/// The category segment of a code (the part between the first two dots), e.g.
2452/// `"types"` for `"bynk.types.type_mismatch"`.
2453pub fn category(code: &str) -> &str {
2454    code.split('.').nth(1).unwrap_or("")
2455}
2456
2457/// A human-readable heading for a category segment.
2458fn category_title(cat: &str) -> &'static str {
2459    match cat {
2460        "agent" | "agents" => "Agents",
2461        "asset" => "Static assets",
2462        "boundary" => "Boundaries",
2463        "capability" => "Capabilities",
2464        "consumes" => "Consumes",
2465        "context" => "Contexts",
2466        "contract" => "Contracts",
2467        "cron" => "Cron",
2468        "effect" => "Effects",
2469        "expect" => "Expectations",
2470        "exports" => "Exports",
2471        "given" => "Given capabilities",
2472        "http" => "HTTP",
2473        "lex" => "Lexer",
2474        "messages" => "Message bundles",
2475        "mock" => "Mocks (collaborators)",
2476        "observe" => "Observation",
2477        "parse" => "Parser",
2478        "project" => "Project",
2479        "property" => "Properties (generative tests)",
2480        "provider" => "Providers",
2481        "queue" => "Queue",
2482        "record_spread" => "Record spread",
2483        "refine" => "Refinement",
2484        "resolve" => "Resolution",
2485        "service" => "Services",
2486        "suite" => "Suites and cases",
2487        "transition" => "Transitions (step invariants)",
2488        "types" => "Type checking",
2489        "uses" => "Uses",
2490        "val" => "Value fabrication",
2491        _ => "Other",
2492    }
2493}
2494
2495/// Render the diagnostic index as a Markdown reference page, grouped by
2496/// category. This is the generator behind
2497/// `site/src/content/docs/book/reference/diagnostics.md`.
2498pub fn render_markdown() -> String {
2499    use std::collections::BTreeMap;
2500
2501    // Group codes by their category title, preserving sorted code order.
2502    let mut by_category: BTreeMap<&str, Vec<&DiagnosticInfo>> = BTreeMap::new();
2503    for info in REGISTRY {
2504        by_category
2505            .entry(category_title(category(info.code)))
2506            .or_default()
2507            .push(info);
2508    }
2509
2510    let mut out = String::new();
2511    out.push_str("# Diagnostic index\n\n");
2512    out.push_str(
2513        "<!-- GENERATED FILE — do not edit by hand.\n     \
2514         Source: bynkc/src/diagnostics.rs (`render_markdown`).\n     \
2515         Regenerate with: BYNK_BLESS=1 cargo test -p bynkc --test diagnostics_registry -->\n\n",
2516    );
2517    out.push_str(
2518        "Every diagnostic code the compiler can emit, with a one-line summary of \
2519         the cause, grouped by category. For step-by-step cause-and-fix guidance \
2520         on the most common ones, see the [troubleshooting guides](../troubleshooting/index.md).\n\n",
2521    );
2522    out.push_str(&format!(
2523        "There are **{}** codes in total.\n",
2524        REGISTRY.len()
2525    ));
2526
2527    for (title, infos) in &by_category {
2528        out.push_str(&format!("\n## {title}\n\n"));
2529        out.push_str("| Code | Summary | Construct | Severity |\n|---|---|---|---|\n");
2530        for info in infos {
2531            // The construct column deep-links each governing production to its
2532            // entry in the annotated grammar reference; generated from
2533            // `grammar_symbol` (each value is an embeddable rule, so the
2534            // `#rule-<raw>` anchor resolves — enforced in diagnostics_registry).
2535            let construct = info
2536                .grammar_symbol
2537                .iter()
2538                .map(|sym| format!("[`{sym}`](grammar.md#rule-{sym})"))
2539                .collect::<Vec<_>>()
2540                .join(", ");
2541            // A curated (`bynk explain`-able) code links to its Book concept
2542            // page; the in-site link is validated by the site's link checker,
2543            // so a moved page or renamed anchor fails the build (#853). Codes
2544            // without an explanation render as plain inline code.
2545            let code_cell = match explain(info.code) {
2546                Some(e) => format!("[`{}`]({})", info.code, e.in_site_link()),
2547                None => format!("`{}`", info.code),
2548            };
2549            // ADR 0117/finding #50: every code's severity, straight from the
2550            // registry — `Error` (the overwhelming majority) renders as "—"
2551            // to keep the common case unobtrusive; only a `warn`-built entry
2552            // shows "Warning".
2553            let severity = match info.severity {
2554                Severity::Error => "—",
2555                Severity::Warning => "Warning",
2556            };
2557            out.push_str(&format!(
2558                "| {} | {} | {} | {} |\n",
2559                code_cell, info.summary, construct, severity
2560            ));
2561        }
2562    }
2563
2564    out
2565}
2566
2567/// Invert the registry into a `{ "<rule>": [ { code, summary }, … ], … }` map,
2568/// serialised as pretty JSON with sorted keys and sorted codes. Only rules with
2569/// at least one diagnostic appear. This is the generator behind
2570/// `docs/grammar-semantics.json`, which the `{{#grammar-semantics <rule>}}`
2571/// preprocessor directive consumes.
2572pub fn render_grammar_semantics_json() -> String {
2573    use std::collections::BTreeMap;
2574
2575    // REGISTRY is sorted by code, so each rule's vector comes out code-sorted;
2576    // the BTreeMap gives sorted rule names.
2577    let mut by_symbol: BTreeMap<&str, Vec<&DiagnosticInfo>> = BTreeMap::new();
2578    for info in REGISTRY {
2579        for sym in info.grammar_symbol {
2580            by_symbol.entry(sym).or_default().push(info);
2581        }
2582    }
2583
2584    let mut map = serde_json::Map::new();
2585    map.insert(
2586        "_generated".to_string(),
2587        serde_json::Value::String(
2588            "Generated from the grammar_symbol field of bynkc/src/diagnostics.rs. \
2589             Do not edit by hand. Regenerate with: BYNK_BLESS=1 cargo test -p \
2590             bynkc --test diagnostics_registry"
2591                .to_string(),
2592        ),
2593    );
2594    for (sym, infos) in by_symbol {
2595        let arr: Vec<serde_json::Value> = infos
2596            .iter()
2597            .map(|info| serde_json::json!({ "code": info.code, "summary": info.summary }))
2598            .collect();
2599        map.insert(sym.to_string(), serde_json::Value::Array(arr));
2600    }
2601
2602    let mut s =
2603        serde_json::to_string_pretty(&serde_json::Value::Object(map)).expect("serialise semantics");
2604    s.push('\n');
2605    s
2606}