1use serde::{Deserialize, Serialize};
42use std::collections::BTreeMap;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54pub enum DiagLevel {
55 Info,
58 Warn,
60 Error,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69pub enum Applicability {
70 MachineApplicable,
72 MaybeIncorrect,
75 HasPlaceholders,
78 Unspecified,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
90pub struct DocsRef {
91 pub uri: &'static str,
93 pub anchor: Option<&'static str>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(tag = "type")]
102pub enum DiagElement {
103 Agent {
105 name: String,
107 },
108 Step {
110 #[serde(rename = "ref")]
112 ref_: String,
113 },
114 Operator {
116 name: String,
118 },
119 Meta {
121 name: String,
123 },
124 BlueprintRoot,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct DiagSpan {
134 pub element: DiagElement,
136 pub json_path: Option<String>,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub struct Suggestion {
146 pub msg: String,
148 pub patch: String,
152 pub applicability: Applicability,
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160pub enum BpDoctorFamily {
161 AgentMdSize,
163 ToolLint,
165 OutputContractLint,
167 WorkerBindingLint,
170 BindingLint,
172 SkipOnLint,
174 WrapperOnly,
177 ContextPolicyLint,
180 LintControl,
184 VerdictContractLint,
189 SpawnerHintLint,
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(tag = "type")]
209pub enum DiagStage {
210 CompileLint,
213 BpDoctor {
215 family: BpDoctorFamily,
217 },
218 LaunchPreflight,
220 Runtime,
223 RefResolve,
225 Register,
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
237pub struct Diagnostic {
238 pub kind: &'static str,
242 pub stage: DiagStage,
244 pub level: DiagLevel,
247 pub message: String,
249 pub notes: Vec<String>,
251 pub help: Option<String>,
254 pub suggestion: Option<Suggestion>,
256 pub docs_ref: Option<DocsRef>,
258 pub span: Option<DiagSpan>,
260}
261
262impl Diagnostic {
263 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 pub fn with_note(mut self, note: impl Into<String>) -> Self {
286 self.notes.push(note.into());
287 self
288 }
289
290 pub fn with_help(mut self, help: impl Into<String>) -> Self {
292 self.help = Some(help.into());
293 self
294 }
295
296 pub fn with_suggestion(mut self, suggestion: Suggestion) -> Self {
298 self.suggestion = Some(suggestion);
299 self
300 }
301
302 pub fn with_docs_ref(mut self, docs_ref: DocsRef) -> Self {
304 self.docs_ref = Some(docs_ref);
305 self
306 }
307
308 pub fn with_span(mut self, span: DiagSpan) -> Self {
310 self.span = Some(span);
311 self
312 }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
319pub enum LintCategory {
320 Correctness,
323 Suspicious,
327 Style,
330 Contract,
334 Migration,
337}
338
339impl LintCategory {
340 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
358pub struct LintDecl {
359 pub kind: &'static str,
362 pub default_level: DiagLevel,
365 pub category: LintCategory,
367 pub desc: &'static str,
370 pub docs_ref: DocsRef,
372}
373
374const 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
394pub const LINT_DECLS: &[LintDecl] = &[
403 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 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 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
658pub fn lint_decl(kind: &str) -> Option<&'static LintDecl> {
662 LINT_DECLS.iter().find(|d| d.kind == kind)
663}
664
665pub 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
701pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
742#[serde(rename_all = "lowercase")]
743pub enum LintSetting {
744 Allow,
746 Warn,
748 Deny,
750}
751
752impl LintSetting {
753 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
779pub struct LintConfig {
780 entries: BTreeMap<String, LintSetting>,
781 unknown_keys: Vec<String>,
782}
783
784impl LintConfig {
785 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 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 pub fn entries(&self) -> &BTreeMap<String, LintSetting> {
812 &self.entries
813 }
814
815 pub fn unknown_keys(&self) -> &[String] {
820 &self.unknown_keys
821 }
822
823 pub fn is_empty(&self) -> bool {
826 self.entries.is_empty()
827 }
828
829 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 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
862fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
880pub enum ResolvedLint {
881 Suppressed,
885 Level(DiagLevel),
888}
889
890pub 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
926pub 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 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 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 fn style_decl() -> &'static LintDecl {
1074 lint_decl("agent-md-size").expect("declared")
1075 }
1076
1077 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 #[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 #[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 #[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 #[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 #[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 #[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}