Skip to main content

mlua_swarm_diag/
lib.rs

1//! Unified Clippy-style diagnostic model for the mlua-swarm
2//! authoring-time feedback surface (GH #79).
3//!
4//! ## Why this crate exists
5//!
6//! MSE checks the same class of Blueprint invariants at several stages —
7//! compile-lint (`mse bp build` / `bp_build`), post-register lint
8//! (`bp_doctor`), launch pre-flight, runtime, `$file`/`$agent_md` ref
9//! resolution — and each stage historically produced its own ad-hoc
10//! shape (a typed `CompileError` enum, a substring-matched `FixHint`,
11//! per-family `serde_json::Value` blobs). This crate is the shared
12//! vocabulary those stages converge on, mirroring Clippy's design:
13//!
14//! | Clippy          | here                          |
15//! |-----------------|-------------------------------|
16//! | `Level`         | [`DiagLevel`]                 |
17//! | `Diagnostic`    | [`Diagnostic`]                |
18//! | `Suggestion`    | [`Suggestion`]                |
19//! | `Applicability` | [`Applicability`]             |
20//! | `Lint` registry | [`LintDecl`] / [`LINT_DECLS`] |
21//! | `#[allow]` / `#[warn]` / `#[deny]` | [`LintSetting`] / [`LintConfig`] / [`resolve_level`] |
22//!
23//! ## Boundary discipline
24//!
25//! This crate depends on **no other mlua-swarm crate** (serde only), so
26//! it can sit between producers (`mlua-swarm`'s
27//! `impl From<&CompileError> for Diagnostic`) and consumers
28//! (`mlua-swarm-cli`'s `bp_doctor` response, renderers, future
29//! `mse bp fix` tooling) without either side coupling to the other's
30//! internals. Historically the CLI re-parsed the compiler's
31//! pre-formatted error strings via `contains(...)` precisely to avoid
32//! that coupling — this crate is the typed replacement for that
33//! substring seam.
34//!
35//! ## Adding a new lint
36//!
37//! The 4-step recipe (declare in [`LINT_DECLS`] → document → produce →
38//! test) is documented in the bundled MCP resource
39//! `mse://guides/lint-diagnostic-model`.
40
41use serde::{Deserialize, Serialize};
42use std::collections::BTreeMap;
43
44/// Severity of one [`Diagnostic`]. Mirrors Clippy's `Level`, collapsed
45/// to the three bands the existing MSE surfaces actually use
46/// (`bp_doctor`'s `INFO`/`WARN`/`BLOCK` strings, compile-lint's hard
47/// errors).
48///
49/// The same lint kind may fire at different levels per stage: e.g.
50/// `worker-binding-missing` is [`DiagLevel::Error`] at
51/// [`DiagStage::CompileLint`] (blocks register) but
52/// [`DiagLevel::Warn`] at `bp_doctor` (report-only).
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54pub enum DiagLevel {
55    /// Informational — not a defect (e.g. a capability-manifest
56    /// requirement listing). Never escalates an aggregate verdict.
57    Info,
58    /// Advisory defect — report-only, nothing is blocked.
59    Warn,
60    /// Hard failure — the producing stage refuses to proceed
61    /// (compile-lint fail, register refusal).
62    Error,
63}
64
65/// Confidence grade of a [`Suggestion`]'s `patch` — the gate a future
66/// auto-apply surface (`mse bp fix`) switches on. Mirrors rustc /
67/// Clippy's `Applicability` verbatim.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69pub enum Applicability {
70    /// The patch can be applied mechanically with no human review.
71    MachineApplicable,
72    /// The patch is plausible but may not be what the author meant —
73    /// apply only with review.
74    MaybeIncorrect,
75    /// The patch contains placeholder tokens (e.g. `<subagent-type>`)
76    /// the author must fill in before it is valid.
77    HasPlaceholders,
78    /// No confidence judgment was made.
79    Unspecified,
80}
81
82/// Stable pointer into the bundled `mse://` docs surface. `uri` is
83/// `&'static str` on purpose: every docs target is a bundled MCP
84/// resource compiled into the binary, so a dynamic string here would
85/// only enable dangling references. The `mse://` scheme invariant is
86/// asserted by this crate's tests over [`LINT_DECLS`]. Serialize-only
87/// (like [`Diagnostic`]): the `&'static str` fields make this a
88/// produce-side type — wire consumers read the JSON generically.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
90pub struct DocsRef {
91    /// Bundled resource URI, e.g. `"mse://guides/bp-dsl-templates"`.
92    pub uri: &'static str,
93    /// Optional section anchor within the guide (e.g. `"#worker-binding"`).
94    pub anchor: Option<&'static str>,
95}
96
97/// Which Blueprint element a [`DiagSpan`] points at. Serialized
98/// internally tagged (`{"type": "Agent", "name": "greeter"}`) so
99/// downstream renderers can switch on `type`.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(tag = "type")]
102pub enum DiagElement {
103    /// An `agents[]` entry, addressed by `AgentDef.name`.
104    Agent {
105        /// The agent's declared name.
106        name: String,
107    },
108    /// A flow `Step` node, addressed by its `ref` (agent name).
109    Step {
110        /// The step's `ref` value.
111        #[serde(rename = "ref")]
112        ref_: String,
113    },
114    /// An `operators[]` entry, addressed by `OperatorDef.name`.
115    Operator {
116        /// The operator role's declared name.
117        name: String,
118    },
119    /// A `metas[]` entry, addressed by `MetaDef.name`.
120    Meta {
121        /// The meta pool entry's declared name.
122        name: String,
123    },
124    /// The Blueprint document itself (Blueprint-scoped finding).
125    BlueprintRoot,
126}
127
128/// Location of a [`Diagnostic`] inside the Blueprint document — MSE's
129/// analogue of a source span. Blueprints are JSON documents, not source
130/// text, so the "span" is an element identity plus an optional JSONPath
131/// refinement.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct DiagSpan {
134    /// The Blueprint element this diagnostic is about.
135    pub element: DiagElement,
136    /// Optional JSONPath into the Blueprint document, e.g.
137    /// `"$.agents[?(@.name=='greeter')].profile.worker_binding"`.
138    pub json_path: Option<String>,
139}
140
141/// A concrete recovery suggestion attached to a [`Diagnostic`].
142/// Successor of the CLI's `FixHint` (`reason` / `patch_suggestion`)
143/// with an explicit [`Applicability`] confidence grade.
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub struct Suggestion {
146    /// One-line imperative statement of what to add or change.
147    pub msg: String,
148    /// The patch text the author would paste in place. Format-agnostic —
149    /// single-line snippet or multi-line block; renderers indent it as a
150    /// code block.
151    pub patch: String,
152    /// Confidence grade — the gate an auto-apply surface switches on.
153    pub applicability: Applicability,
154}
155
156/// The `bp_doctor` lint family a [`DiagStage::BpDoctor`] diagnostic
157/// belongs to. One variant per family the tool reports today; new
158/// families (e.g. a `ContextPolicyLint` for GH #78) land here.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160pub enum BpDoctorFamily {
161    /// agent.md size check (bytes / lines vs. authoring-guide targets).
162    AgentMdSize,
163    /// GH #45: phantom MCP tool references in `profile.tools`.
164    ToolLint,
165    /// GH #45: missing / malformed `profile.extras.expected_output`.
166    OutputContractLint,
167    /// GH #61: operator-kind agent without the compile-required
168    /// `profile.worker_binding`.
169    WorkerBindingLint,
170    /// C4: Blueprint-scoped operator-binding advisories.
171    BindingLint,
172    /// GH #76: Skip-tier / `skip_on` DSL cross-checks.
173    SkipOnLint,
174    /// Wrapper-side tool drift (`bp_explain_agent`'s `tool_drift`
175    /// wrapper-only classification).
176    WrapperOnly,
177    /// GH #78: `context_policy` / projection-root vs launch-seed
178    /// cross-checks (silent `file_path: null` prevention).
179    ContextPolicyLint,
180    /// Findings about the `lints` declaration itself rather than about
181    /// the Blueprint's behavior — the meta-lints `unknown-lint-kind` and
182    /// `non-suppressible-lint` (rustc's `unknown_lints` analogue).
183    LintControl,
184    /// Declared `agents[].verdict` contracts nothing downstream reads —
185    /// the reverse-direction verdict lint, surfaced report-only on an
186    /// already-registered Blueprint (the compile stage only fires it under
187    /// `metadata.strict_verdict_handling`).
188    VerdictContractLint,
189    /// `spawner_hints.layers` keys that name a layer no deployment
190    /// installs any more — currently only the removed `operator_delegate`
191    /// axis. Report-only here; the compile stage refuses outright.
192    ///
193    /// This family exists because registering a Blueprint does **not**
194    /// compile it (`blueprints.rs` stores the document; `Compiler::compile`
195    /// runs at launch). Without a `bp_doctor` producer, a Blueprint
196    /// carrying a removed hint would pass its doctor run clean and then
197    /// fail at the first dispatch — the same "retroactively surfaced on an
198    /// already-registered Blueprint" gap [`Self::WorkerBindingLint`] was
199    /// added to close.
200    SpawnerHintLint,
201}
202
203/// Which producing stage emitted a [`Diagnostic`]. Serialized
204/// internally tagged (`{"type": "BpDoctor", "family": "WorkerBindingLint"}`)
205/// so downstream renderers can switch on `type` without knowing every
206/// family.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(tag = "type")]
209pub enum DiagStage {
210    /// Compile lint (`mse bp build` / `bp_build` / `mse bp lint`) —
211    /// the `Compiler::compile` gate.
212    CompileLint,
213    /// Post-register lint (`bp_doctor`), qualified by lint family.
214    BpDoctor {
215        /// The `bp_doctor` family this diagnostic belongs to.
216        family: BpDoctorFamily,
217    },
218    /// Task-launch pre-flight validation (producers land with GH #78).
219    LaunchPreflight,
220    /// Runtime diagnostics (declared for completeness; converting the
221    /// existing runtime error paths is out of GH #79's scope).
222    Runtime,
223    /// `$file` / `$agent_md` ref resolution (the include cascade).
224    RefResolve,
225    /// Blueprint registration (`POST /v1/blueprints/:id`) — the last stage
226    /// that sees the document as the author sent it.
227    Register,
228}
229
230/// One diagnostic finding — the unified shape every MSE feedback stage
231/// produces. Field-by-field mirror of Clippy's `Diagnostic`, adapted to
232/// a JSON-document world (see [`DiagSpan`]). Serialize-only: `kind`
233/// (and any [`DocsRef`]) are `&'static str` registry keys, so this
234/// type is constructed by producers, never parsed back — wire
235/// consumers read the JSON generically.
236#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
237pub struct Diagnostic {
238    /// Machine-readable stable lint key (e.g. `"worker-binding-missing"`).
239    /// Every kind has a matching [`LintDecl`] in [`LINT_DECLS`];
240    /// downstream tooling switches on this, never on message text.
241    pub kind: &'static str,
242    /// The producing stage.
243    pub stage: DiagStage,
244    /// Severity at this stage (may differ from the kind's
245    /// [`LintDecl::default_level`] — see [`DiagLevel`]).
246    pub level: DiagLevel,
247    /// Primary human-readable statement of the finding.
248    pub message: String,
249    /// Additional context lines (rendered after the message).
250    pub notes: Vec<String>,
251    /// Optional "how to think about fixing this" line — prose guidance,
252    /// distinct from the concrete [`Suggestion`] patch.
253    pub help: Option<String>,
254    /// Optional concrete recovery patch with confidence grade.
255    pub suggestion: Option<Suggestion>,
256    /// Optional pointer to the bundled guide covering this lint.
257    pub docs_ref: Option<DocsRef>,
258    /// Optional location inside the Blueprint document.
259    pub span: Option<DiagSpan>,
260}
261
262impl Diagnostic {
263    /// Minimal constructor; use the `with_*` builders for the optional
264    /// fields.
265    pub fn new(
266        kind: &'static str,
267        stage: DiagStage,
268        level: DiagLevel,
269        message: impl Into<String>,
270    ) -> Self {
271        Self {
272            kind,
273            stage,
274            level,
275            message: message.into(),
276            notes: Vec::new(),
277            help: None,
278            suggestion: None,
279            docs_ref: None,
280            span: None,
281        }
282    }
283
284    /// Append one note line.
285    pub fn with_note(mut self, note: impl Into<String>) -> Self {
286        self.notes.push(note.into());
287        self
288    }
289
290    /// Set the help line.
291    pub fn with_help(mut self, help: impl Into<String>) -> Self {
292        self.help = Some(help.into());
293        self
294    }
295
296    /// Attach a concrete recovery suggestion.
297    pub fn with_suggestion(mut self, suggestion: Suggestion) -> Self {
298        self.suggestion = Some(suggestion);
299        self
300    }
301
302    /// Attach a docs pointer.
303    pub fn with_docs_ref(mut self, docs_ref: DocsRef) -> Self {
304        self.docs_ref = Some(docs_ref);
305        self
306    }
307
308    /// Attach a Blueprint-document span.
309    pub fn with_span(mut self, span: DiagSpan) -> Self {
310        self.span = Some(span);
311        self
312    }
313}
314
315/// Coarse lint grouping — Clippy-style categories, collapsed to the
316/// five MSE needs as a baseline (finer user-facing `#[allow]`-style
317/// control is a declared non-goal of GH #79).
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
319pub enum LintCategory {
320    /// The Blueprint is wrong — it will fail to compile, register, or
321    /// dispatch (dangling refs, duplicate names, type mismatches).
322    Correctness,
323    /// The Blueprint is probably wrong — the shape is legal but the
324    /// declared intent and the flow disagree (dead guards, unhandled
325    /// verdict values).
326    Suspicious,
327    /// Authoring-quality concerns that never affect execution
328    /// (agent.md size targets).
329    Style,
330    /// A declared machine-readable contract is missing or violated
331    /// (verdict contracts, output contracts, worker bindings, tool
332    /// registries).
333    Contract,
334    /// A deprecated surface is still in use; a replacement exists
335    /// (legacy `profile.worker_binding` fallback).
336    Migration,
337}
338
339impl LintCategory {
340    /// The lowercase name this category is addressed by in a
341    /// [`LintConfig`] group key (`"category:<name>"`).
342    pub fn as_key(&self) -> &'static str {
343        match self {
344            Self::Correctness => "correctness",
345            Self::Suspicious => "suspicious",
346            Self::Style => "style",
347            Self::Contract => "contract",
348            Self::Migration => "migration",
349        }
350    }
351}
352
353/// Static declaration of one lint kind — the registry row. One
354/// [`LintDecl`] per kind, whatever stages that kind fires at (the
355/// per-stage level lives on the emitted [`Diagnostic`]; the decl
356/// carries the default).
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
358pub struct LintDecl {
359    /// Machine-readable stable lint key ([`Diagnostic::kind`] values
360    /// match exactly one entry).
361    pub kind: &'static str,
362    /// The level this lint fires at when the producing stage does not
363    /// override it.
364    pub default_level: DiagLevel,
365    /// Coarse grouping.
366    pub category: LintCategory,
367    /// One-line description for docs generation / `--help lints`-style
368    /// listings.
369    pub desc: &'static str,
370    /// The bundled guide covering this lint.
371    pub docs_ref: DocsRef,
372}
373
374/// Shorthand for the [`LINT_DECLS`] table below.
375const fn decl(
376    kind: &'static str,
377    default_level: DiagLevel,
378    category: LintCategory,
379    desc: &'static str,
380    docs_uri: &'static str,
381) -> LintDecl {
382    LintDecl {
383        kind,
384        default_level,
385        category,
386        desc,
387        docs_ref: DocsRef {
388            uri: docs_uri,
389            anchor: None,
390        },
391    }
392}
393
394/// The static lint registry: one entry per lint kind across every
395/// stage. This is the single source that enumerates all lints for docs
396/// generation and future opt-out surfaces; [`Diagnostic::kind`] values
397/// are drawn from here (asserted by the producing crates' tests).
398///
399/// Ordering: compile-lint kinds first (one per `CompileError` variant,
400/// plus the two kinds shared with other stages), then the `bp_doctor`
401/// family kinds.
402pub const LINT_DECLS: &[LintDecl] = &[
403    // ─── CompileLint stage (one per CompileError variant) ────────────
404    decl(
405        "bound-agent-resolution",
406        DiagLevel::Error,
407        LintCategory::Correctness,
408        "Runner / Agent / Context binding failed before any spawner was built.",
409        "mse://guides/blueprint-authoring",
410    ),
411    decl(
412        "unknown-agent-kind",
413        DiagLevel::Error,
414        LintCategory::Correctness,
415        "An AgentDef.kind has no matching SpawnerRegistry entry under strategy.strict_kind.",
416        "mse://guides/blueprint-authoring",
417    ),
418    decl(
419        "invalid-agent-spec",
420        DiagLevel::Error,
421        LintCategory::Correctness,
422        "An AgentDef.spec shape does not match what the factory for its kind requires.",
423        "mse://guides/blueprint-authoring",
424    ),
425    decl(
426        "worker-binding-missing",
427        DiagLevel::Error,
428        LintCategory::Contract,
429        "An operator-kind agent lacks the worker binding its backend requires \
430         (Error at compile-lint; Warn at bp_doctor).",
431        "mse://guides/bp-dsl-templates",
432    ),
433    decl(
434        "unresolved-agent-ref",
435        DiagLevel::Error,
436        LintCategory::Correctness,
437        "The flow references an agent name with no corresponding AgentDef.",
438        "mse://guides/blueprint-authoring",
439    ),
440    decl(
441        "duplicate-agent-name",
442        DiagLevel::Error,
443        LintCategory::Correctness,
444        "Two AgentDefs in the same Blueprint share a name.",
445        "mse://guides/blueprint-authoring",
446    ),
447    decl(
448        "invalid-max-concurrency",
449        DiagLevel::Error,
450        LintCategory::Correctness,
451        "An AgentDef declares max_concurrency = 0, so none of its steps could ever run.",
452        "mse://guides/blueprint-authoring",
453    ),
454    decl(
455        "unresolved-operator-ref",
456        DiagLevel::Error,
457        LintCategory::Correctness,
458        "An agent's spec.operator_ref matches no OperatorDef.name in Blueprint.operators.",
459        "mse://guides/operator-execution-model",
460    ),
461    decl(
462        "unresolved-meta-ref",
463        DiagLevel::Error,
464        LintCategory::Correctness,
465        "An AgentMeta.meta_ref or $step_meta.ref names an undefined MetaDef.",
466        "mse://guides/operator-execution-model",
467    ),
468    decl(
469        "step-naming-collision",
470        DiagLevel::Error,
471        LintCategory::Correctness,
472        "Two Steps' canonical/alias projection names collide with a declared projection_name.",
473        "mse://guides/operator-execution-model",
474    ),
475    decl(
476        "invalid-projection-placement",
477        DiagLevel::Error,
478        LintCategory::Correctness,
479        "Blueprint.projection_placement failed validation.",
480        "mse://guides/operator-execution-model",
481    ),
482    decl(
483        "unresolved-audit-agent",
484        DiagLevel::Error,
485        LintCategory::Correctness,
486        "An audits[].agent name matches no AgentDef.name in Blueprint.agents.",
487        "mse://guides/operator-execution-model",
488    ),
489    decl(
490        "verdict-channel-mismatch",
491        DiagLevel::Error,
492        LintCategory::Contract,
493        "A Branch/Loop cond addresses a contract-bearing agent's verdict on the wrong \
494         OUTPUT channel (body vs part).",
495        "mse://guides/blueprint-authoring",
496    ),
497    decl(
498        "verdict-value-not-in-contract",
499        DiagLevel::Error,
500        LintCategory::Contract,
501        "A Branch/Loop cond Lit is not a member of the agent's declared verdict.values.",
502        "mse://guides/blueprint-authoring",
503    ),
504    decl(
505        "verdict-value-unhandled",
506        DiagLevel::Error,
507        LintCategory::Suspicious,
508        "A declared verdict.values member is never referenced by any downstream cond \
509         (compile stage: Error, only under metadata.strict_verdict_handling; bp_doctor \
510         verdict_contract_lint family: Warn, always).",
511        "mse://guides/blueprint-authoring",
512    ),
513    decl(
514        "verdict-contract-never-read",
515        DiagLevel::Warn,
516        LintCategory::Suspicious,
517        "Every declared verdict.values entry on an agent is unhandled — no downstream \
518         cond reads any of them, so the contract is decorative and the step cannot halt \
519         the flow. Per-agent aggregate of `verdict-value-unhandled`; separates a full \
520         gate loss from the per-value baseline that fires on the always-unread PASS token.",
521        "mse://guides/blueprint-authoring",
522    ),
523    decl(
524        "halted-at-missing",
525        DiagLevel::Error,
526        LintCategory::Correctness,
527        "The flow declares a halt-on rule but no halted_at sink.",
528        "mse://guides/bp-dsl-templates",
529    ),
530    // ─── BpDoctor stage (one per family / finding check) ─────────────
531    decl(
532        "agent-md-size",
533        DiagLevel::Warn,
534        LintCategory::Style,
535        "An agent's profile.system_prompt exceeds the authoring-guide size targets.",
536        "mse://guides/agent-md-authoring",
537    ),
538    decl(
539        "tool-unknown-mcp-ref",
540        DiagLevel::Warn,
541        LintCategory::Contract,
542        "profile.tools references an mcp__mse__ tool absent from the live registry.",
543        "mse://guides/mcp-tool-reference",
544    ),
545    decl(
546        "output-contract-missing",
547        DiagLevel::Warn,
548        LintCategory::Contract,
549        "profile.extras.expected_output is absent or malformed (GH #44 convention).",
550        "mse://guides/agent-md-authoring",
551    ),
552    decl(
553        "binding-requirements-info",
554        DiagLevel::Info,
555        LintCategory::Contract,
556        "A Runner-backed agent's capability_manifest requirements (informational).",
557        "mse://guides/operator-execution-model",
558    ),
559    decl(
560        "strict-binding-without-runners",
561        DiagLevel::Warn,
562        LintCategory::Suspicious,
563        "strategy.strict_binding is true but no agent resolves to a Runner (no-op).",
564        "mse://guides/operator-execution-model",
565    ),
566    decl(
567        "legacy-worker-binding",
568        DiagLevel::Warn,
569        LintCategory::Migration,
570        "An agent's Runner resolves from the deprecated profile.worker_binding fallback.",
571        "mse://guides/operator-execution-model",
572    ),
573    decl(
574        "binding-resolution-error",
575        DiagLevel::Warn,
576        LintCategory::Correctness,
577        "Runner bindings could not be resolved for the bp_doctor advisory pass.",
578        "mse://guides/operator-execution-model",
579    ),
580    decl(
581        "skip-on-missing-for-skip-like-verdict-value",
582        DiagLevel::Warn,
583        LintCategory::Suspicious,
584        "A skip-like verdict value (SKIP / NOT_APPLICABLE / N/A) has no skip_on guard.",
585        "mse://guides/skip-tier-and-skip-on",
586    ),
587    decl(
588        "skip-on-declared-but-no-matching-verdict-value",
589        DiagLevel::Warn,
590        LintCategory::Suspicious,
591        "A skip_on list captures a value no agent's verdict.values declares (dead guard).",
592        "mse://guides/skip-tier-and-skip-on",
593    ),
594    decl(
595        "skip-on-pattern-conflicts-with-halt-on",
596        DiagLevel::Warn,
597        LintCategory::Suspicious,
598        "The same value appears in both a skip_on list and a halt_on gate cond.",
599        "mse://guides/skip-tier-and-skip-on",
600    ),
601    decl(
602        "wrapper-only-drift",
603        DiagLevel::Info,
604        LintCategory::Contract,
605        "The worker wrapper grants tools the Blueprint never declares (informational).",
606        "mse://guides/agent-md-authoring",
607    ),
608    decl(
609        "context-policy-strips-projection-roots",
610        DiagLevel::Warn,
611        LintCategory::Suspicious,
612        "An agent's effective context_policy filters out both 'work_dir' and \
613         'project_root', so the projection placement root can never resolve \
614         (step artifacts materialize with file_path: null).",
615        "mse://guides/operator-execution-model",
616    ),
617    decl(
618        "projection-root-seed-missing",
619        DiagLevel::Warn,
620        LintCategory::Contract,
621        "Under the simulated launch payload, no policy-surviving root field \
622         (work_dir / project_root) is seeded, so materialized step artifacts \
623         will carry file_path: null (content_url-only).",
624        "mse://guides/operator-execution-model",
625    ),
626    decl(
627        "removed-spawner-hint",
628        DiagLevel::Error,
629        LintCategory::Migration,
630        "spawner_hints.layers names a layer that no longer exists (operator_delegate).",
631        "mse://guides/blueprint-authoring",
632    ),
633    decl(
634        "flow-node-renamed",
635        DiagLevel::Warn,
636        LintCategory::Migration,
637        "A flow node uses the legacy `assign` kind; it is read as `let` (mlua-flow-ir 0.3.0 \
638         rename).",
639        "mse://guides/blueprint-authoring",
640    ),
641    // ─── Meta-lints (findings about the lints config itself) ─────────
642    decl(
643        "unknown-lint-kind",
644        DiagLevel::Warn,
645        LintCategory::Suspicious,
646        "A lints map key matches no declared lint kind, category, or 'all'.",
647        "mse://guides/lint-diagnostic-model",
648    ),
649    decl(
650        "non-suppressible-lint",
651        DiagLevel::Warn,
652        LintCategory::Suspicious,
653        "A lints map entry targets a compile-hard-error kind with allow; ignored.",
654        "mse://guides/lint-diagnostic-model",
655    ),
656];
657
658/// Look up the [`LintDecl`] for a kind key. `None` for unknown kinds —
659/// producers should treat that as a bug (every emitted
660/// [`Diagnostic::kind`] must be declared).
661pub fn lint_decl(kind: &str) -> Option<&'static LintDecl> {
662    LINT_DECLS.iter().find(|d| d.kind == kind)
663}
664
665/// The recovery attached to every `removed-spawner-hint` diagnostic,
666/// whichever stage emitted it.
667///
668/// Two stages report this kind — the compile gate (`impl
669/// From<&CompileError> for Diagnostic`, which refuses) and `bp_doctor`'s
670/// [`BpDoctorFamily::SpawnerHintLint`] (which reports on an
671/// already-registered Blueprint, since registering does not compile). An
672/// author who meets the same kind at either stage must not be told two
673/// different things, and the two producers live in different crates, so
674/// the text lives here — the same reason
675/// `mlua_swarm::removed_spawner_hint_reason` holds the key table for both.
676///
677/// Before this function the prose was hand-duplicated at the two call
678/// sites and happened to be byte-identical; nothing checked that, and the
679/// tests only asserted `patch.contains("\"operator_ref\"")`, which both
680/// halves of a drifted pair would still satisfy.
681///
682/// [`Applicability::HasPlaceholders`] rather than `MachineApplicable`:
683/// only the author knows which agents were meant to reach the Operator
684/// and what the seat should be called, and every such agent needs its own
685/// `spec.operator_ref`. The patch is a shape to fill in, not a drop-in
686/// replacement.
687pub fn removed_spawner_hint_suggestion() -> Suggestion {
688    Suggestion {
689        msg: "drop the removed layer key, declare an Operator seat, and point each \
690              operator-backed agent at it"
691            .into(),
692        patch: "\"spawner_hints\": { \"layers\": [] },\n\
693                \"operators\": [{ \"name\": \"main_ai\", \"kind\": \"main_ai\" }],\n\
694                \"agents\": [{ \"name\": \"<agent>\", \"kind\": \"operator\", \"spec\": { \
695                \"operator_ref\": \"main_ai\" } }]"
696            .into(),
697        applicability: Applicability::HasPlaceholders,
698    }
699}
700
701/// One `flow-node-renamed` finding for the legacy `assign` node at
702/// `json_path` (a JSONPath into the Blueprint document, e.g.
703/// `$.flow.children[2]`), as reported by `stage`.
704///
705/// The node still runs: it is rewritten to `let` when the Blueprint is
706/// read, so the finding is a warning that the document is in the old
707/// shape, not a refusal. The text lives here so every stage that reports
708/// the kind tells the author the same thing.
709pub fn flow_node_renamed(stage: DiagStage, json_path: impl Into<String>) -> Diagnostic {
710    let json_path = json_path.into();
711    Diagnostic::new(
712        "flow-node-renamed",
713        stage,
714        DiagLevel::Warn,
715        format!(
716            "flow node at {json_path} uses the legacy kind `assign`; it is read as `let`. \
717             Rewrite it to the `let` shape."
718        ),
719    )
720    .with_span(DiagSpan {
721        element: DiagElement::BlueprintRoot,
722        json_path: Some(json_path),
723    })
724    .with_suggestion(Suggestion {
725        msg: "rename the node kind to `let` and write `at` as a bare path string".into(),
726        patch: "{ \"kind\": \"let\", \"at\": \"$.<path>\", \"value\": <expr> }".into(),
727        applicability: Applicability::HasPlaceholders,
728    })
729    .with_docs_ref(DocsRef {
730        uri: "mse://guides/blueprint-authoring",
731        anchor: Some("#legacy-assign-nodes"),
732    })
733}
734
735/// Author-declared level for one lint kind or group — the diag-side twin
736/// of `mlua_swarm_schema::LintSetting` (same three lowercase wire
737/// literals). The twin exists because this crate depends on no other
738/// mlua-swarm crate: the schema owns the Blueprint-side vocabulary, this
739/// crate owns resolution, and the consumer (`bp_doctor`) maps one onto
740/// the other.
741#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
742#[serde(rename_all = "lowercase")]
743pub enum LintSetting {
744    /// Suppress the lint — resolves to [`ResolvedLint::Suppressed`].
745    Allow,
746    /// Report as advisory — resolves to [`DiagLevel::Warn`].
747    Warn,
748    /// Escalate to an error — resolves to [`DiagLevel::Error`].
749    Deny,
750}
751
752impl LintSetting {
753    /// Parse the wire spelling (`"allow"` / `"warn"` / `"deny"`, ASCII
754    /// case-insensitive). `None` for anything else — the call-site layer
755    /// arrives as untyped strings and a typo there must surface as a
756    /// meta-lint, never as a rejected request (see
757    /// [`LintConfig::from_str_map`]).
758    pub fn parse(s: &str) -> Option<Self> {
759        match s.to_ascii_lowercase().as_str() {
760            "allow" => Some(Self::Allow),
761            "warn" => Some(Self::Warn),
762            "deny" => Some(Self::Deny),
763            _ => None,
764        }
765    }
766}
767
768/// One layer of author-declared lint levels, with the entries that could
769/// not be honored kept aside instead of dropped.
770///
771/// A key selects what its setting applies to: an exact lint kind literal
772/// (`"agent-md-size"`), a category group (`"category:style"`, see
773/// [`LintCategory::as_key`]), or `"all"`. Keys are validated here
774/// against [`LINT_DECLS`]; anything unrecognized — and any entry whose
775/// *value* failed to parse — lands in [`LintConfig::unknown_keys`] for
776/// the `unknown-lint-kind` meta-lint rather than failing construction.
777/// Construction is total: no input shape errors or panics.
778#[derive(Debug, Clone, Default, PartialEq, Eq)]
779pub struct LintConfig {
780    entries: BTreeMap<String, LintSetting>,
781    unknown_keys: Vec<String>,
782}
783
784impl LintConfig {
785    /// Build from already-typed pairs — the Blueprint path, where serde
786    /// has already rejected invalid values (the caller maps
787    /// `mlua_swarm_schema::LintSetting` onto [`LintSetting`]). Keys are
788    /// still validated, so an unknown kind literal in a Blueprint is a
789    /// meta-lint, not a register failure.
790    pub fn from_pairs(pairs: impl IntoIterator<Item = (String, LintSetting)>) -> Self {
791        let mut cfg = Self::default();
792        for (key, setting) in pairs {
793            cfg.insert(key, Some(setting));
794        }
795        cfg
796    }
797
798    /// Build from the untyped call-site form (`bp_doctor`'s
799    /// `lints: {kind: level}` request field). Lenient on both axes: an
800    /// unknown key *and* an unparseable value are collected the same way,
801    /// so a typo degrades to a meta-lint instead of rejecting the request.
802    pub fn from_str_map(map: &BTreeMap<String, String>) -> Self {
803        let mut cfg = Self::default();
804        for (key, raw) in map {
805            cfg.insert(key.clone(), LintSetting::parse(raw));
806        }
807        cfg
808    }
809
810    /// The honored entries (registry-known key, parsed value).
811    pub fn entries(&self) -> &BTreeMap<String, LintSetting> {
812        &self.entries
813    }
814
815    /// Keys this layer declared that matched no lint kind, no
816    /// `category:<cat>` group and not `all`, plus keys whose value did
817    /// not parse. One `unknown-lint-kind` diagnostic per entry; the
818    /// emitting layer is the caller's to name.
819    pub fn unknown_keys(&self) -> &[String] {
820        &self.unknown_keys
821    }
822
823    /// `true` when this layer honors no entry at all — it can never win a
824    /// [`resolve_level`] lookup and callers may skip it.
825    pub fn is_empty(&self) -> bool {
826        self.entries.is_empty()
827    }
828
829    /// The setting this layer declares for `decl`, applying within-layer
830    /// specificity: an exact kind key beats `category:<cat>`, which beats
831    /// `all`. `None` = this layer says nothing about `decl`. Kind keys
832    /// match the registry literal exactly; the category name after
833    /// `category:` is matched ASCII case-insensitively (keys are stored
834    /// as the author spelled them, so the meta-lint can quote them back).
835    pub fn setting_for(&self, decl: &LintDecl) -> Option<LintSetting> {
836        if let Some(s) = self.entries.get(decl.kind) {
837            return Some(*s);
838        }
839        let category = decl.category.as_key();
840        let group = self.entries.iter().find(|(key, _)| {
841            key.strip_prefix("category:")
842                .is_some_and(|cat| cat.eq_ignore_ascii_case(category))
843        });
844        if let Some((_, s)) = group {
845            return Some(*s);
846        }
847        self.entries.get("all").copied()
848    }
849
850    /// Record one entry, routing it to `entries` or `unknown_keys`.
851    /// `setting == None` means the value did not parse.
852    fn insert(&mut self, key: String, setting: Option<LintSetting>) {
853        match setting {
854            Some(s) if key_is_known(&key) => {
855                self.entries.insert(key, s);
856            }
857            _ => self.unknown_keys.push(key),
858        }
859    }
860}
861
862/// Whether a [`LintConfig`] key addresses something that exists: a
863/// declared kind literal, a `category:<cat>` group with a known category,
864/// or `all`. Category names are compared ASCII case-insensitively against
865/// [`LintCategory::as_key`].
866fn key_is_known(key: &str) -> bool {
867    if key == "all" || lint_decl(key).is_some() {
868        return true;
869    }
870    match key.strip_prefix("category:") {
871        Some(cat) => LINT_DECLS
872            .iter()
873            .any(|d| d.category.as_key().eq_ignore_ascii_case(cat)),
874        None => false,
875    }
876}
877
878/// Outcome of resolving one lint kind against the declared layers.
879#[derive(Debug, Clone, Copy, PartialEq, Eq)]
880pub enum ResolvedLint {
881    /// The lint is allowed away: the finding must not fold into a verdict
882    /// and must not appear among the reported diagnostics. Consumers move
883    /// it to a visible `suppressed[]` array — omitted ≠ passed.
884    Suppressed,
885    /// The lint fires at this level (the declared override, or the kind's
886    /// [`LintDecl::default_level`] when nothing declared it).
887    Level(DiagLevel),
888}
889
890/// Resolve the effective level of `decl` against the declared layers.
891///
892/// `layers` is **most-specific first** — the consumer passes
893/// `[call_site, agent, blueprint]`, omitting the layers that do not apply
894/// to the diagnostic at hand (an agent layer only applies to diagnostics
895/// spanning that agent or a step referencing it). The first layer with
896/// *any* matching key wins outright, with no merging across layers: this
897/// mirrors rustc's attribute-proximity model, where the innermost
898/// `#[allow]` decides. Within one layer, specificity orders the keys
899/// (exact kind > `category:<cat>` > `all`, see
900/// [`LintConfig::setting_for`]). With no match anywhere the kind's
901/// registry default level applies.
902///
903/// This function is deliberately **stage-agnostic**: it maps settings to
904/// levels and nothing else. The non-suppressible boundary is the
905/// caller's contract and is *stage-scoped*, not kind-scoped — a kind
906/// that is a compile-stage hard error ([`is_compile_hard_error`])
907/// ignores `allow` / `warn` at [`DiagStage::CompileLint`], but the same
908/// kind stays suppressible at `bp_doctor` when that stage emits it at
909/// `Warn` (`worker-binding-missing`, `verdict-value-unhandled`). At
910/// `bp_doctor`, an exact-kind entry targeting a kind the stage never
911/// emits raises the `non-suppressible-lint` meta-lint; `category:` /
912/// `all` keys never do. Encoding that here would require a stage
913/// argument the resolver has no other use for.
914pub fn resolve_level(decl: &LintDecl, layers: &[&LintConfig]) -> ResolvedLint {
915    for layer in layers {
916        match layer.setting_for(decl) {
917            Some(LintSetting::Allow) => return ResolvedLint::Suppressed,
918            Some(LintSetting::Warn) => return ResolvedLint::Level(DiagLevel::Warn),
919            Some(LintSetting::Deny) => return ResolvedLint::Level(DiagLevel::Error),
920            None => continue,
921        }
922    }
923    ResolvedLint::Level(decl.default_level)
924}
925
926/// Whether `decl` is a compile-stage hard error rather than a lint —
927/// i.e. its [`LintDecl::default_level`] is [`DiagLevel::Error`], so
928/// `Compiler::compile` refuses the Blueprint and no author setting can
929/// change that *at compile*.
930///
931/// Callers use this as the guard around [`resolve_level`]'s result,
932/// stage-scoped: at [`DiagStage::CompileLint`] an `allow` / `warn` on
933/// such a kind is ignored outright. At `bp_doctor` the kind stays
934/// suppressible when that stage emits it (at `Warn`); the
935/// `non-suppressible-lint` meta-lint fires only for an exact-kind entry
936/// on a kind `bp_doctor` never emits, and a `category:` / `all` key
937/// skips those without noise.
938pub fn is_compile_hard_error(decl: &LintDecl) -> bool {
939    matches!(decl.default_level, DiagLevel::Error)
940}
941
942#[cfg(test)]
943mod tests {
944    use super::*;
945
946    #[test]
947    fn lint_decl_kinds_are_unique() {
948        let mut seen = std::collections::BTreeSet::new();
949        for d in LINT_DECLS {
950            assert!(seen.insert(d.kind), "duplicate LintDecl kind: {}", d.kind);
951        }
952    }
953
954    #[test]
955    fn lint_decl_docs_refs_use_the_mse_scheme() {
956        for d in LINT_DECLS {
957            assert!(
958                d.docs_ref.uri.starts_with("mse://"),
959                "LintDecl {} docs_ref must use the mse:// scheme, got: {}",
960                d.kind,
961                d.docs_ref.uri
962            );
963            assert!(!d.desc.is_empty(), "LintDecl {} desc must be set", d.kind);
964        }
965    }
966
967    #[test]
968    fn lint_decl_lookup_round_trips_every_entry() {
969        for d in LINT_DECLS {
970            let found = lint_decl(d.kind).expect("every declared kind must resolve");
971            assert_eq!(found.kind, d.kind);
972        }
973        assert!(lint_decl("no-such-lint").is_none());
974    }
975
976    #[test]
977    fn diagnostic_serializes_to_the_documented_wire_shape() {
978        // The GH #79 sample response shape: stage internally tagged with
979        // family, unit enums as bare variant-name strings.
980        let d = Diagnostic::new(
981            "worker-binding-missing",
982            DiagStage::BpDoctor {
983                family: BpDoctorFamily::WorkerBindingLint,
984            },
985            DiagLevel::Warn,
986            "operator agent 'greeter' lacks worker_binding",
987        )
988        .with_note("profile.worker_binding is required for the WS thin-path backend")
989        .with_help("The WS thin-path operator backend requires worker_binding at dispatch.")
990        .with_suggestion(Suggestion {
991            msg: "add explicit Runner or profile.worker_binding".into(),
992            patch: "runner = { backend = \"ws_operator\", variant = \"claude\", tools = {} }"
993                .into(),
994            applicability: Applicability::HasPlaceholders,
995        })
996        .with_docs_ref(DocsRef {
997            uri: "mse://guides/bp-dsl-templates",
998            anchor: Some("#worker-binding"),
999        })
1000        .with_span(DiagSpan {
1001            element: DiagElement::Agent {
1002                name: "greeter".into(),
1003            },
1004            json_path: Some("$.agents[?(@.name=='greeter')].profile.worker_binding".into()),
1005        });
1006
1007        let v = serde_json::to_value(&d).expect("Diagnostic must serialize");
1008        assert_eq!(v["kind"], "worker-binding-missing");
1009        assert_eq!(v["stage"]["type"], "BpDoctor");
1010        assert_eq!(v["stage"]["family"], "WorkerBindingLint");
1011        assert_eq!(v["level"], "Warn");
1012        assert_eq!(v["suggestion"]["applicability"], "HasPlaceholders");
1013        assert_eq!(v["docs_ref"]["uri"], "mse://guides/bp-dsl-templates");
1014        assert_eq!(v["span"]["element"]["type"], "Agent");
1015        assert_eq!(v["span"]["element"]["name"], "greeter");
1016    }
1017
1018    #[test]
1019    fn unit_stage_variants_serialize_internally_tagged() {
1020        let v = serde_json::to_value(DiagStage::CompileLint).expect("stage must serialize");
1021        assert_eq!(v["type"], "CompileLint");
1022        let step = serde_json::to_value(DiagElement::Step {
1023            ref_: "scout".into(),
1024        })
1025        .expect("element must serialize");
1026        assert_eq!(step["type"], "Step");
1027        assert_eq!(step["ref"], "scout");
1028    }
1029
1030    #[test]
1031    fn flow_node_renamed_is_a_declared_migration_warning_with_a_span() {
1032        let d = flow_node_renamed(DiagStage::Register, "$.flow.children[2]");
1033        let decl = lint_decl(d.kind).expect("flow-node-renamed must be declared");
1034        assert_eq!(decl.category, LintCategory::Migration);
1035        assert_eq!(decl.default_level, DiagLevel::Warn);
1036        assert_eq!(d.level, DiagLevel::Warn);
1037        assert_eq!(
1038            d.span.as_ref().and_then(|s| s.json_path.as_deref()),
1039            Some("$.flow.children[2]")
1040        );
1041        assert!(d.message.contains("$.flow.children[2]"));
1042        let patch = &d.suggestion.as_ref().expect("suggestion").patch;
1043        assert!(patch.contains("\"kind\": \"let\""));
1044        let v = serde_json::to_value(&d).expect("diagnostic must serialize");
1045        assert_eq!(v["stage"]["type"], "Register");
1046        assert_eq!(v["docs_ref"]["anchor"], "#legacy-assign-nodes");
1047    }
1048
1049    #[test]
1050    fn minimal_diagnostic_serializes_optional_fields_as_null_or_empty() {
1051        // A minimal Diagnostic (no notes / help / suggestion / docs_ref /
1052        // span) still serializes every field, so wire consumers can rely
1053        // on key presence rather than probing.
1054        let d = Diagnostic::new(
1055            "agent-md-size",
1056            DiagStage::BpDoctor {
1057                family: BpDoctorFamily::AgentMdSize,
1058            },
1059            DiagLevel::Warn,
1060            "agent 'planner' system_prompt is 30 KB",
1061        );
1062        let v = serde_json::to_value(&d).expect("serialize");
1063        assert_eq!(v["notes"], serde_json::json!([]));
1064        assert_eq!(v["help"], serde_json::Value::Null);
1065        assert_eq!(v["suggestion"], serde_json::Value::Null);
1066        assert_eq!(v["docs_ref"], serde_json::Value::Null);
1067        assert_eq!(v["span"], serde_json::Value::Null);
1068    }
1069
1070    // ─── lint level control (LintConfig / resolve_level) ─────────────
1071
1072    /// `agent-md-size` — Warn / Style, the canonical suppressible lint.
1073    fn style_decl() -> &'static LintDecl {
1074        lint_decl("agent-md-size").expect("declared")
1075    }
1076
1077    /// `worker-binding-missing` — Error / Contract, a compile-stage hard
1078    /// error.
1079    fn hard_error_decl() -> &'static LintDecl {
1080        lint_decl("worker-binding-missing").expect("declared")
1081    }
1082
1083    fn cfg(pairs: &[(&str, LintSetting)]) -> LintConfig {
1084        LintConfig::from_pairs(pairs.iter().map(|(k, v)| (k.to_string(), *v)))
1085    }
1086
1087    #[test]
1088    fn resolve_level_falls_through_to_the_registry_default() {
1089        assert_eq!(
1090            resolve_level(style_decl(), &[]),
1091            ResolvedLint::Level(DiagLevel::Warn)
1092        );
1093        let empty = LintConfig::default();
1094        assert_eq!(
1095            resolve_level(style_decl(), &[&empty, &empty]),
1096            ResolvedLint::Level(DiagLevel::Warn)
1097        );
1098    }
1099
1100    #[test]
1101    fn resolve_level_maps_allow_warn_deny() {
1102        for (setting, expected) in [
1103            (LintSetting::Allow, ResolvedLint::Suppressed),
1104            (LintSetting::Warn, ResolvedLint::Level(DiagLevel::Warn)),
1105            (LintSetting::Deny, ResolvedLint::Level(DiagLevel::Error)),
1106        ] {
1107            let layer = cfg(&[("agent-md-size", setting)]);
1108            assert_eq!(
1109                resolve_level(style_decl(), &[&layer]),
1110                expected,
1111                "mapping for {setting:?}"
1112            );
1113        }
1114    }
1115
1116    /// The first layer with any matching key wins outright — an outer
1117    /// layer never overrides or merges into an inner one.
1118    #[test]
1119    fn resolve_level_first_matching_layer_wins() {
1120        let call_site = cfg(&[("agent-md-size", LintSetting::Allow)]);
1121        let agent = cfg(&[("agent-md-size", LintSetting::Deny)]);
1122        let blueprint = cfg(&[("agent-md-size", LintSetting::Warn)]);
1123
1124        assert_eq!(
1125            resolve_level(style_decl(), &[&call_site, &agent, &blueprint]),
1126            ResolvedLint::Suppressed,
1127            "call-site beats agent"
1128        );
1129        assert_eq!(
1130            resolve_level(style_decl(), &[&agent, &blueprint]),
1131            ResolvedLint::Level(DiagLevel::Error),
1132            "agent beats blueprint"
1133        );
1134        assert_eq!(
1135            resolve_level(style_decl(), &[&blueprint]),
1136            ResolvedLint::Level(DiagLevel::Warn)
1137        );
1138    }
1139
1140    /// A less specific key in a nearer layer still wins over an exact
1141    /// key further out (proximity is decided before specificity).
1142    #[test]
1143    fn resolve_level_layer_proximity_beats_key_specificity() {
1144        let agent = cfg(&[("all", LintSetting::Allow)]);
1145        let blueprint = cfg(&[("agent-md-size", LintSetting::Deny)]);
1146        assert_eq!(
1147            resolve_level(style_decl(), &[&agent, &blueprint]),
1148            ResolvedLint::Suppressed
1149        );
1150    }
1151
1152    #[test]
1153    fn resolve_level_within_a_layer_kind_beats_category_beats_all() {
1154        let all_three = cfg(&[
1155            ("agent-md-size", LintSetting::Deny),
1156            ("category:style", LintSetting::Warn),
1157            ("all", LintSetting::Allow),
1158        ]);
1159        assert_eq!(
1160            resolve_level(style_decl(), &[&all_three]),
1161            ResolvedLint::Level(DiagLevel::Error),
1162            "exact kind wins"
1163        );
1164
1165        let category_and_all = cfg(&[
1166            ("category:style", LintSetting::Warn),
1167            ("all", LintSetting::Allow),
1168        ]);
1169        assert_eq!(
1170            resolve_level(style_decl(), &[&category_and_all]),
1171            ResolvedLint::Level(DiagLevel::Warn),
1172            "category beats all"
1173        );
1174
1175        let all_only = cfg(&[("all", LintSetting::Allow)]);
1176        assert_eq!(
1177            resolve_level(style_decl(), &[&all_only]),
1178            ResolvedLint::Suppressed,
1179            "all is the fallback within the layer"
1180        );
1181    }
1182
1183    /// A `category:` key only matches its own category, and the category
1184    /// name is compared case-insensitively.
1185    #[test]
1186    fn category_keys_match_only_their_own_category() {
1187        let style_group = cfg(&[("category:style", LintSetting::Allow)]);
1188        assert_eq!(
1189            resolve_level(style_decl(), &[&style_group]),
1190            ResolvedLint::Suppressed
1191        );
1192        assert_eq!(
1193            resolve_level(hard_error_decl(), &[&style_group]),
1194            ResolvedLint::Level(DiagLevel::Error),
1195            "a Contract kind is untouched by a Style group key"
1196        );
1197
1198        let upper = cfg(&[("category:STYLE", LintSetting::Allow)]);
1199        assert_eq!(
1200            resolve_level(style_decl(), &[&upper]),
1201            ResolvedLint::Suppressed,
1202            "category names are ASCII case-insensitive"
1203        );
1204        assert!(upper.unknown_keys().is_empty());
1205    }
1206
1207    #[test]
1208    fn every_declared_category_is_addressable_as_a_group_key() {
1209        for d in LINT_DECLS {
1210            let key = format!("category:{}", d.category.as_key());
1211            let layer = cfg(&[(key.as_str(), LintSetting::Allow)]);
1212            assert!(
1213                layer.unknown_keys().is_empty(),
1214                "{key} must be a known group key"
1215            );
1216            assert_eq!(
1217                resolve_level(d, &[&layer]),
1218                ResolvedLint::Suppressed,
1219                "{} must be reachable through {key}",
1220                d.kind
1221            );
1222        }
1223    }
1224
1225    #[test]
1226    fn unknown_keys_are_collected_not_honored() {
1227        let layer = cfg(&[
1228            ("agent-md-size", LintSetting::Allow),
1229            ("agent-md-sizes", LintSetting::Deny),
1230            ("category:nonsense", LintSetting::Deny),
1231            ("everything", LintSetting::Deny),
1232        ]);
1233        assert_eq!(
1234            layer.unknown_keys(),
1235            ["agent-md-sizes", "category:nonsense", "everything"]
1236        );
1237        assert_eq!(layer.entries().len(), 1);
1238        assert_eq!(
1239            resolve_level(style_decl(), &[&layer]),
1240            ResolvedLint::Suppressed,
1241            "the one honored entry still resolves"
1242        );
1243    }
1244
1245    /// The untyped call-site form never errors: an unparseable value is
1246    /// collected exactly like an unknown key.
1247    #[test]
1248    fn from_str_map_collects_invalid_values_alongside_unknown_keys() {
1249        let map = BTreeMap::from([
1250            ("agent-md-size".to_string(), "ALLOW".to_string()),
1251            ("category:style".to_string(), "forbid".to_string()),
1252            ("no-such-lint".to_string(), "deny".to_string()),
1253            ("all".to_string(), "warn".to_string()),
1254        ]);
1255        let layer = LintConfig::from_str_map(&map);
1256
1257        assert_eq!(layer.unknown_keys(), ["category:style", "no-such-lint"]);
1258        assert_eq!(
1259            layer.entries().get("agent-md-size"),
1260            Some(&LintSetting::Allow),
1261            "values parse ASCII case-insensitively"
1262        );
1263        assert_eq!(layer.entries().get("all"), Some(&LintSetting::Warn));
1264        assert_eq!(
1265            resolve_level(hard_error_decl(), &[&layer]),
1266            ResolvedLint::Level(DiagLevel::Warn),
1267            "the surviving 'all' entry still applies"
1268        );
1269    }
1270
1271    #[test]
1272    fn empty_config_is_reported_empty_and_never_matches() {
1273        let empty = LintConfig::from_str_map(&BTreeMap::new());
1274        assert!(empty.is_empty());
1275        assert!(empty.unknown_keys().is_empty());
1276        assert_eq!(empty.setting_for(style_decl()), None);
1277
1278        let only_unknown =
1279            LintConfig::from_str_map(&BTreeMap::from([("typo".to_string(), "allow".to_string())]));
1280        assert!(only_unknown.is_empty(), "unknown keys honor nothing");
1281        assert_eq!(only_unknown.unknown_keys(), ["typo"]);
1282    }
1283
1284    /// The boundary helper is a pure `default_level` probe — the stage
1285    /// rules on top of it belong to the consumer.
1286    #[test]
1287    fn is_compile_hard_error_tracks_the_registry_default_level() {
1288        assert!(is_compile_hard_error(hard_error_decl()));
1289        assert!(!is_compile_hard_error(style_decl()));
1290        for d in LINT_DECLS {
1291            assert_eq!(
1292                is_compile_hard_error(d),
1293                d.default_level == DiagLevel::Error,
1294                "{}",
1295                d.kind
1296            );
1297        }
1298    }
1299
1300    /// The two meta-lints are declared like any other kind, so the
1301    /// consumer emits them through the same registry lookup.
1302    #[test]
1303    fn meta_lints_are_declared_in_the_registry() {
1304        for kind in ["unknown-lint-kind", "non-suppressible-lint"] {
1305            let d = lint_decl(kind).expect("meta-lint must be declared");
1306            assert_eq!(d.default_level, DiagLevel::Warn);
1307            assert_eq!(d.category, LintCategory::Suspicious);
1308            assert_eq!(d.docs_ref.uri, "mse://guides/lint-diagnostic-model");
1309            assert!(!is_compile_hard_error(d));
1310        }
1311    }
1312
1313    #[test]
1314    fn lint_setting_parses_and_serializes_the_lowercase_wire_form() {
1315        assert_eq!(LintSetting::parse("allow"), Some(LintSetting::Allow));
1316        assert_eq!(LintSetting::parse("Warn"), Some(LintSetting::Warn));
1317        assert_eq!(LintSetting::parse("DENY"), Some(LintSetting::Deny));
1318        assert_eq!(LintSetting::parse("forbid"), None);
1319        assert_eq!(LintSetting::parse(""), None);
1320        assert_eq!(
1321            serde_json::to_value(LintSetting::Allow).expect("serializes"),
1322            serde_json::json!("allow")
1323        );
1324        assert_eq!(
1325            serde_json::from_value::<LintSetting>(serde_json::json!("deny")).expect("deserializes"),
1326            LintSetting::Deny
1327        );
1328    }
1329}