1use std::{
8 collections::{BTreeMap, BTreeSet, HashSet},
9 fmt, fs,
10 path::Path,
11 process::Stdio,
12 time::Duration,
13};
14
15use serde::{
16 de::{self, MapAccess, Visitor},
17 Deserialize, Deserializer,
18};
19use serde_json::Value;
20use subc_protocol::{
21 manifest::{validate_manifest_capability_grammar, CapabilityNeed, ModuleManifest},
22 PROTOCOL_VERSION,
23};
24use tokio::{process::Command, time};
25
26use crate::daemon_config::{self, ConfiguredModule};
27
28pub const MANIFEST_TIMEOUT: Duration = Duration::from_secs(10);
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
34pub enum OperationalClass {
35 ProgramMissing,
36 ProgramNotExecutable,
37 ManifestTimeout,
38 ManifestExitNonzero,
39 ManifestUnparsable,
40 ManifestVersionUnsupported,
41 DuplicateModuleId,
42 ManifestInvalid,
43}
44
45impl OperationalClass {
46 pub const fn as_str(self) -> &'static str {
47 match self {
48 Self::ProgramMissing => "program_missing",
49 Self::ProgramNotExecutable => "program_not_executable",
50 Self::ManifestTimeout => "manifest_timeout",
51 Self::ManifestExitNonzero => "manifest_exit_nonzero",
52 Self::ManifestUnparsable => "manifest_unparsable",
53 Self::ManifestVersionUnsupported => "manifest_version_unsupported",
54 Self::DuplicateModuleId => "duplicate_module_id",
55 Self::ManifestInvalid => "manifest_invalid",
56 }
57 }
58}
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum LintOutcome {
63 Clean,
64 SemanticViolation,
65 OperationalFailure,
66}
67
68impl LintOutcome {
69 pub const fn exit_code(self) -> i32 {
70 match self {
71 Self::Clean => 0,
72 Self::SemanticViolation => 1,
73 Self::OperationalFailure => 2,
74 }
75 }
76}
77
78#[derive(Debug)]
80pub struct LintReport {
81 pub outcome: LintOutcome,
82 pub examined: usize,
83 pub configured: usize,
84 lines: Vec<String>,
85 #[cfg(test)]
86 failures: Vec<OperationalFailure>,
87}
88
89impl LintReport {
90 pub fn render(&self) -> String {
93 self.lines.join("\n")
94 }
95
96 #[cfg(test)]
97 fn has_failure(&self, class: OperationalClass, module: &str) -> bool {
98 self.failures
99 .iter()
100 .any(|failure| failure.class == class && failure.module == module)
101 }
102}
103
104#[derive(Debug)]
105pub struct LintConfigError(String);
106
107impl fmt::Display for LintConfigError {
108 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109 formatter.write_str(&self.0)
110 }
111}
112
113impl std::error::Error for LintConfigError {}
114
115#[derive(Debug)]
116struct OperationalFailure {
117 class: OperationalClass,
118 module: String,
119}
120
121#[derive(Debug)]
122struct ExaminedManifest {
123 module_id: String,
124 enabled: bool,
125 manifest: ModuleManifest,
126}
127
128#[derive(Debug)]
129struct RequirementLine {
130 consumer: String,
131 capability: String,
132 text: String,
133}
134
135pub async fn lint(path: impl AsRef<Path>, verbose: bool) -> Result<LintReport, LintConfigError> {
137 lint_with_timeout(path.as_ref(), verbose, MANIFEST_TIMEOUT).await
138}
139
140async fn lint_with_timeout(
141 path: &Path,
142 verbose: bool,
143 manifest_timeout: Duration,
144) -> Result<LintReport, LintConfigError> {
145 let duplicate_module_ids = duplicate_module_ids(path)?;
146 let config = daemon_config::load(path)
147 .map_err(|error| LintConfigError(format!("failed to parse {}: {error}", path.display())))?
148 .ok_or_else(|| {
149 LintConfigError(format!("daemon config {} does not exist", path.display()))
150 })?;
151
152 let mut modules = config.modules.iter().collect::<Vec<_>>();
153 modules.sort_by(|left, right| left.module_id.cmp(&right.module_id));
154 let mut failures = duplicate_module_ids
155 .into_iter()
156 .map(|module| OperationalFailure {
157 class: OperationalClass::DuplicateModuleId,
158 module,
159 })
160 .collect::<Vec<_>>();
161 let mut skipped_daemons = Vec::new();
162 let mut examined = Vec::new();
163
164 for module in modules {
165 if is_daemon_entry(module) {
166 skipped_daemons.push(module.module_id.clone());
167 continue;
168 }
169
170 match read_manifest(module, manifest_timeout).await {
171 Ok(manifest) => examined.push(ExaminedManifest {
172 module_id: module.module_id.clone(),
173 enabled: module.enabled,
174 manifest,
175 }),
176 Err(class) => failures.push(OperationalFailure {
177 class,
178 module: module.module_id.clone(),
179 }),
180 }
181 }
182
183 let configured = config
184 .modules
185 .iter()
186 .filter(|module| !is_daemon_entry(module))
187 .count();
188 let unavailable = failures
189 .iter()
190 .filter(|failure| failure.class != OperationalClass::DuplicateModuleId)
191 .map(|failure| failure.module.as_str())
192 .collect::<BTreeSet<_>>()
193 .into_iter()
194 .collect::<Vec<_>>();
195 let checked = format!(
196 "checked {} of {configured} configured modules",
197 examined.len()
198 );
199 let mut lines = vec![if unavailable.is_empty() {
200 checked
201 } else {
202 format!(
203 "{checked} — {} do not expose a manifest",
204 unavailable.join(", ")
205 )
206 }];
207
208 if verbose {
209 for module in &skipped_daemons {
210 lines.push(format!("verbose: skipped daemon entry {module}"));
211 }
212 }
213
214 failures.sort_by(|left, right| {
215 left.class
216 .cmp(&right.class)
217 .then_with(|| left.module.cmp(&right.module))
218 });
219 if verbose {
220 for failure in &failures {
221 lines.push(format!(
222 "partial: evaluation incomplete ({}: {})",
223 failure.class.as_str(),
224 failure.module
225 ));
226 }
227 if examined.is_empty() {
228 lines.push("operational failure: no modules examined (vacuity floor)".to_string());
232 }
233 lines.push("deny consistency = self-contradiction check".to_string());
234 }
235
236 let enabled_providers = capability_claimants(&examined, true);
237 let all_providers = capability_claimants(&examined, false);
238 let mut has_semantic_violation = false;
239 let mut deny_violations = Vec::new();
240 let mut requirement_lines = Vec::new();
241
242 for entry in &examined {
243 let Some(capabilities) = &entry.manifest.capabilities else {
244 continue;
245 };
246 if entry.enabled {
247 for requirement in &capabilities.requires {
248 let provided = enabled_providers.contains_key(&requirement.capability);
249 match requirement.need {
250 CapabilityNeed::Required => {
251 let text = if provided {
252 format!(
253 "required {} {}: provided",
254 entry.module_id, requirement.capability
255 )
256 } else {
257 let text = format!(
258 "required {} {}: no enabled provider",
259 entry.module_id, requirement.capability
260 );
261 has_semantic_violation = true;
262 text
263 };
264 requirement_lines.push(RequirementLine {
265 consumer: entry.module_id.clone(),
266 capability: requirement.capability.clone(),
267 text,
268 });
269 }
270 CapabilityNeed::Optional if verbose && !provided => {
271 requirement_lines.push(RequirementLine {
272 consumer: entry.module_id.clone(),
273 capability: requirement.capability.clone(),
274 text: format!(
275 "optional {}: no provider (consumer degrades, by declaration)",
276 requirement.capability
277 ),
278 });
279 }
280 CapabilityNeed::Optional => {}
281 }
282 }
283 }
284
285 let denied = capabilities
286 .must_never_reach
287 .iter()
288 .collect::<BTreeSet<_>>();
289 for requirement in &capabilities.requires {
290 if denied.contains(&requirement.capability) {
291 has_semantic_violation = true;
292 deny_violations.push(format!(
293 "requires_deny_conflict module={} capability={}",
294 entry.module_id, requirement.capability
295 ));
296 }
297 }
298 }
299
300 requirement_lines.sort_by(|left, right| {
301 left.consumer
302 .cmp(&right.consumer)
303 .then_with(|| left.capability.cmp(&right.capability))
304 });
305 lines.extend(requirement_lines.into_iter().map(|line| line.text));
306
307 deny_violations.sort();
308 deny_violations.dedup();
309 lines.extend(deny_violations);
310
311 let mut reserved_lines = Vec::new();
312 let mut reserved_violation = false;
313 for (capability, bound_module) in &config.reserved_capabilities {
314 let claimants = all_providers.get(capability);
315 match claimants {
316 None => reserved_lines.push(format!(
317 "warning: reserved capability {capability} has no configured claimant for {bound_module}"
318 )),
319 Some(claimants) => {
320 for claimant in claimants {
321 if claimant != bound_module {
322 reserved_violation = true;
323 reserved_lines.push(format!(
324 "reserved capability {capability}: claimant {claimant} conflicts with binding {bound_module}"
325 ));
326 }
327 }
328 }
329 }
330 }
331 lines.extend(reserved_lines);
332
333 let mut disabled_notes = Vec::new();
334 for entry in &examined {
335 if entry.enabled {
336 continue;
337 }
338 let Some(capabilities) = &entry.manifest.capabilities else {
339 continue;
340 };
341 for capability in &capabilities.provides {
342 if !enabled_providers.contains_key(capability) {
343 disabled_notes.push(format!(
344 "note: {} (disabled) claims {capability}",
345 entry.module_id
346 ));
347 }
348 }
349 }
350 disabled_notes.sort();
351 disabled_notes.dedup();
352 lines.extend(disabled_notes);
353
354 let outcome = if !failures.is_empty() || examined.is_empty() {
355 LintOutcome::OperationalFailure
356 } else if has_semantic_violation || reserved_violation {
357 LintOutcome::SemanticViolation
358 } else {
359 LintOutcome::Clean
360 };
361
362 Ok(LintReport {
363 outcome,
364 examined: examined.len(),
365 configured,
366 lines,
367 #[cfg(test)]
368 failures,
369 })
370}
371
372fn capability_claimants(
373 examined: &[ExaminedManifest],
374 enabled_only: bool,
375) -> BTreeMap<String, BTreeSet<String>> {
376 let mut claims = BTreeMap::<String, BTreeSet<String>>::new();
377 for entry in examined {
378 if enabled_only && !entry.enabled {
379 continue;
380 }
381 let Some(capabilities) = &entry.manifest.capabilities else {
382 continue;
383 };
384 for capability in &capabilities.provides {
385 claims
386 .entry(capability.clone())
387 .or_default()
388 .insert(entry.module_id.clone());
389 }
390 }
391 claims
392}
393
394fn is_daemon_entry(module: &ConfiguredModule) -> bool {
395 module
396 .program
397 .file_name()
398 .and_then(|name| name.to_str())
399 .is_some_and(|name| matches!(name, "ck-subc" | "ck-subc.exe"))
400}
401
402async fn read_manifest(
403 module: &ConfiguredModule,
404 manifest_timeout: Duration,
405) -> Result<ModuleManifest, OperationalClass> {
406 let metadata = fs::metadata(&module.program).map_err(|error| {
407 if error.kind() == std::io::ErrorKind::NotFound {
408 OperationalClass::ProgramMissing
409 } else {
410 OperationalClass::ProgramNotExecutable
411 }
412 })?;
413 if !is_executable_file(&metadata) {
414 return Err(OperationalClass::ProgramNotExecutable);
415 }
416
417 let mut command = Command::new(&module.program);
418 #[cfg(test)]
421 let isolated = cortexkit_test_support::ScratchDir::new("fleet-lint-manifest");
422 #[cfg(test)]
423 command
424 .env("XDG_DATA_HOME", isolated.path().join("data"))
425 .env("XDG_RUNTIME_DIR", isolated.path().join("runtime"))
426 .env("XDG_CONFIG_HOME", isolated.path().join("config"));
427 command
428 .arg("--manifest")
429 .stdin(Stdio::null())
430 .kill_on_drop(true);
431 let output = match time::timeout(
432 manifest_timeout,
433 subc_os::child_spawn::tokio_output(&mut command),
434 )
435 .await
436 {
437 Ok(Ok(output)) => output,
438 Ok(Err(_)) => return Err(OperationalClass::ProgramNotExecutable),
439 Err(_) => return Err(OperationalClass::ManifestTimeout),
440 };
441 if !output.status.success() {
442 return Err(OperationalClass::ManifestExitNonzero);
443 }
444
445 let value: Value =
446 serde_json::from_slice(&output.stdout).map_err(|_| OperationalClass::ManifestUnparsable)?;
447 validate_manifest_capability_grammar(&value).map_err(|_| OperationalClass::ManifestInvalid)?;
448 let manifest: ModuleManifest =
449 serde_json::from_value(value).map_err(|_| OperationalClass::ManifestUnparsable)?;
450 if manifest.protocol_ver != PROTOCOL_VERSION {
451 return Err(OperationalClass::ManifestVersionUnsupported);
452 }
453 Ok(manifest)
454}
455
456#[cfg(unix)]
457fn is_executable_file(metadata: &fs::Metadata) -> bool {
458 use std::os::unix::fs::PermissionsExt;
459
460 metadata.is_file() && metadata.permissions().mode() & 0o111 != 0
461}
462
463#[cfg(not(unix))]
464fn is_executable_file(metadata: &fs::Metadata) -> bool {
465 metadata.is_file()
466}
467
468fn duplicate_module_ids(path: &Path) -> Result<Vec<String>, LintConfigError> {
469 let document = fs::read_to_string(path)
470 .map_err(|error| LintConfigError(format!("failed to read {}: {error}", path.display())))?;
471 let json = subc_jsonc::jsonc_to_json(&document)
472 .map_err(|error| LintConfigError(format!("failed to parse {}: {error}", path.display())))?;
473 let probe: ModuleIdProbe = serde_json::from_str(&json)
474 .map_err(|error| LintConfigError(format!("failed to parse {}: {error}", path.display())))?;
475 Ok(probe.modules)
476}
477
478#[derive(Deserialize)]
479struct ModuleIdProbe {
480 #[serde(default, deserialize_with = "deserialize_module_ids")]
481 modules: Vec<String>,
482}
483
484fn deserialize_module_ids<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
485where
486 D: Deserializer<'de>,
487{
488 struct ModuleIdsVisitor;
489
490 impl<'de> Visitor<'de> for ModuleIdsVisitor {
491 type Value = Vec<String>;
492
493 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
494 formatter.write_str("an object keyed by module id")
495 }
496
497 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
498 where
499 M: MapAccess<'de>,
500 {
501 let mut duplicates = Vec::new();
502 let mut seen = HashSet::new();
503 while let Some(module_id) = map.next_key::<String>()? {
504 if !seen.insert(module_id.clone()) {
505 duplicates.push(module_id);
506 }
507 map.next_value::<de::IgnoredAny>()?;
508 }
509 Ok(duplicates)
510 }
511 }
512
513 deserializer.deserialize_map(ModuleIdsVisitor)
514}
515
516#[cfg(test)]
517mod tests {
518 use std::{
519 fs,
520 path::{Path, PathBuf},
521 process::Command,
522 time::Duration,
523 };
524
525 use serde_json::{json, Map, Value};
526 use subc_protocol::PROTOCOL_VERSION;
527
528 use super::{lint_with_timeout, LintOutcome, LintReport, OperationalClass, MANIFEST_TIMEOUT};
529 use cortexkit_test_support::ScratchDir as TempDir;
530
531 #[derive(serde::Serialize)]
532 struct FixtureSpec {
533 stdout: String,
534 exit_code: i32,
535 sleep_ms: u64,
536 #[serde(skip)]
537 executable: bool,
538 }
539
540 impl Default for FixtureSpec {
541 fn default() -> Self {
542 Self {
543 stdout: String::new(),
544 exit_code: 0,
545 sleep_ms: 0,
546 executable: true,
547 }
548 }
549 }
550
551 #[track_caller]
574 fn assert_failure(report: &LintReport, class: OperationalClass, module: &str) {
575 assert!(
576 report.has_failure(class, module),
577 "expected {class:?} for module '{module}', but the report carries {:?} \
578 (outcome {:?}, examined {} of {})",
579 report.failures,
580 report.outcome,
581 report.examined,
582 report.configured,
583 );
584 }
585
586 fn fake_aft_stub_path() -> PathBuf {
587 let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
588 assert!(
589 path.exists(),
590 "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
591 path.display()
592 );
593 path
594 }
595
596 fn write_fixture_program(temp: &TempDir, name: &str, fixture: FixtureSpec) -> PathBuf {
597 let filename = if cfg!(windows) {
598 format!("{name}.exe")
599 } else {
600 name.to_string()
601 };
602 let path = temp.path().join(filename);
603 #[cfg(unix)]
606 assert!(Command::new("cp")
607 .arg(fake_aft_stub_path())
608 .arg(&path)
609 .status()
610 .expect("copy executable fixture")
611 .success());
612 #[cfg(not(unix))]
613 fs::copy(fake_aft_stub_path(), &path).unwrap();
614
615 let mut sidecar = path.as_os_str().to_os_string();
618 sidecar.push(".fixture.json");
619 fs::write(
620 PathBuf::from(sidecar),
621 serde_json::to_vec(&fixture).unwrap(),
622 )
623 .unwrap();
624
625 #[cfg(unix)]
626 {
627 use std::os::unix::fs::PermissionsExt;
628 fs::set_permissions(
629 &path,
630 fs::Permissions::from_mode(if fixture.executable { 0o755 } else { 0o644 }),
631 )
632 .unwrap();
633 }
634 #[cfg(not(unix))]
637 let _ = fixture.executable;
638 path
639 }
640
641 #[test]
642 fn fixture_sidecar_absent_preserves_existing_stub_behavior() {
643 let output = Command::new(fake_aft_stub_path())
644 .env("FAKE_AFT_EXIT_CODE", "17")
645 .output()
646 .unwrap();
647 assert_eq!(output.status.code(), Some(17));
648 }
649
650 fn manifest(module_id: &str, capabilities: Value, protocol_ver: u8) -> String {
651 json!({
652 "module_id": module_id,
653 "module_version": "0.1.0",
654 "protocol_ver": protocol_ver,
655 "trust_tier": "first_party",
656 "provides": [],
657 "consumes": [],
658 "bindings": {
659 "storage": {"kind": "sqlite", "scope": "project", "owns_schema": false},
660 "vault_grants": [],
661 "identity": {"requires": [], "optional": []}
662 },
663 "capabilities": capabilities,
664 "runtime_computed": []
665 })
666 .to_string()
667 }
668
669 fn manifest_fixture(temp: &TempDir, module_id: &str, capabilities: Value) -> PathBuf {
670 let document = manifest(module_id, capabilities, PROTOCOL_VERSION);
671 write_fixture_program(
672 temp,
673 module_id,
674 FixtureSpec {
675 stdout: document,
676 ..FixtureSpec::default()
677 },
678 )
679 }
680
681 fn write_config(
682 temp: &TempDir,
683 modules: Vec<(&str, &Path, bool)>,
684 reserved_capabilities: Value,
685 ) -> PathBuf {
686 let mut entries = Map::new();
687 for (module_id, program, enabled) in modules {
688 entries.insert(
689 module_id.to_string(),
690 json!({"program": program, "enabled": enabled}),
691 );
692 }
693 let path = temp.path().join("subc.jsonc");
694 fs::write(
695 &path,
696 json!({
697 "version": 1,
698 "modules": entries,
699 "reserved_capabilities": reserved_capabilities
700 })
701 .to_string(),
702 )
703 .unwrap();
704 path
705 }
706
707 async fn lint_config(path: &Path, verbose: bool) -> super::LintReport {
708 lint_with_timeout(path, verbose, Duration::from_secs(60))
711 .await
712 .unwrap()
713 }
714
715 #[tokio::test]
716 async fn fixture_program_missing_classifies_operational_failure() {
717 let temp = TempDir::new("program-missing");
718 let config = write_config(
719 &temp,
720 vec![("missing", &temp.path().join("missing"), true)],
721 json!({}),
722 );
723
724 let report = lint_config(&config, false).await;
725 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
726 assert_failure(&report, OperationalClass::ProgramMissing, "missing");
727 }
728
729 #[tokio::test]
730 async fn fixture_program_not_executable_classifies_operational_failure() {
731 let temp = TempDir::new("program-not-executable");
732 let script = write_fixture_program(
733 &temp,
734 "not-executable",
735 FixtureSpec {
736 executable: false,
737 ..FixtureSpec::default()
738 },
739 );
740 let config = write_config(&temp, vec![("not-executable", &script, true)], json!({}));
741
742 let report = lint_config(&config, false).await;
743 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
744 #[cfg(unix)]
745 assert_failure(
746 &report,
747 OperationalClass::ProgramNotExecutable,
748 "not-executable",
749 );
750 #[cfg(not(unix))]
751 {
752 assert_failure(
755 &report,
756 OperationalClass::ManifestUnparsable,
757 "not-executable",
758 );
759 }
760 }
761
762 #[tokio::test]
763 async fn fixture_manifest_timeout_classifies_operational_failure() {
764 let temp = TempDir::new("manifest-timeout");
765 let script = write_fixture_program(
766 &temp,
767 "timeout",
768 FixtureSpec {
769 sleep_ms: (MANIFEST_TIMEOUT + Duration::from_secs(1)).as_millis() as u64,
770 ..FixtureSpec::default()
771 },
772 );
773 let config = write_config(&temp, vec![("timeout", &script, true)], json!({}));
774
775 let report = lint_with_timeout(&config, false, Duration::from_millis(5))
776 .await
777 .unwrap();
778 assert_eq!(MANIFEST_TIMEOUT, Duration::from_secs(10));
779 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
780 assert_failure(&report, OperationalClass::ManifestTimeout, "timeout");
781 }
782
783 #[tokio::test]
784 async fn fixture_manifest_exit_nonzero_classifies_operational_failure() {
785 let temp = TempDir::new("manifest-exit-nonzero");
786 let script = write_fixture_program(
787 &temp,
788 "nonzero",
789 FixtureSpec {
790 exit_code: 7,
791 ..FixtureSpec::default()
792 },
793 );
794 let config = write_config(&temp, vec![("nonzero", &script, true)], json!({}));
795
796 let report = lint_config(&config, false).await;
797 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
798 assert_failure(&report, OperationalClass::ManifestExitNonzero, "nonzero");
799 }
800
801 #[tokio::test]
802 async fn fixture_manifest_unparsable_classifies_operational_failure() {
803 let temp = TempDir::new("manifest-unparsable");
804 let script = write_fixture_program(
805 &temp,
806 "unparsable",
807 FixtureSpec {
808 stdout: "not json\\n".to_string(),
809 ..FixtureSpec::default()
810 },
811 );
812 let config = write_config(&temp, vec![("unparsable", &script, true)], json!({}));
813
814 let report = lint_config(&config, false).await;
815 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
816 assert!(
817 report.has_failure(OperationalClass::ManifestUnparsable, "unparsable"),
818 "report:\n{}",
819 report.render()
820 );
821 }
822
823 #[tokio::test]
824 async fn fixture_manifest_version_unsupported_classifies_operational_failure() {
825 let temp = TempDir::new("manifest-version-unsupported");
826 let document = manifest(
827 "unsupported",
828 json!({"provides": [], "requires": [], "must_never_reach": []}),
829 PROTOCOL_VERSION.saturating_add(1),
830 );
831 let script = write_fixture_program(
832 &temp,
833 "unsupported",
834 FixtureSpec {
835 stdout: document,
836 ..FixtureSpec::default()
837 },
838 );
839 let config = write_config(&temp, vec![("unsupported", &script, true)], json!({}));
840
841 let report = lint_config(&config, false).await;
842 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
843 assert!(
844 report.has_failure(OperationalClass::ManifestVersionUnsupported, "unsupported"),
845 "report:\n{}",
846 report.render()
847 );
848 }
849
850 #[tokio::test]
851 async fn fixture_duplicate_module_id_classifies_operational_failure() {
852 let temp = TempDir::new("duplicate-module-id");
853 let script = manifest_fixture(
854 &temp,
855 "duplicate",
856 json!({"provides": [], "requires": [], "must_never_reach": []}),
857 );
858 let config = temp.path().join("subc.jsonc");
859 let program = serde_json::to_string(&script.display().to_string()).unwrap();
865 fs::write(
866 &config,
867 format!(
868 r#"{{"version":1,"modules":{{"duplicate":{{"program":{program}}},"duplicate":{{"program":{program}}}}}}}"#
869 ),
870 )
871 .unwrap();
872
873 let report = lint_config(&config, false).await;
874 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
875 assert_failure(&report, OperationalClass::DuplicateModuleId, "duplicate");
876 assert_eq!(
877 report.render().lines().next().unwrap(),
878 "checked 1 of 1 configured modules",
879 "a duplicate id is an operational error, not a missing manifest"
880 );
881 }
882
883 #[tokio::test]
884 async fn fixture_manifest_invalid_classifies_operational_failure() {
885 let temp = TempDir::new("manifest-invalid");
886 let script = manifest_fixture(
887 &temp,
888 "invalid",
889 json!({"provides": ["Not-valid/v1"], "requires": [], "must_never_reach": []}),
890 );
891 let config = write_config(&temp, vec![("invalid", &script, true)], json!({}));
892
893 let report = lint_config(&config, false).await;
894 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
895 assert_failure(&report, OperationalClass::ManifestInvalid, "invalid");
896 }
897
898 #[tokio::test]
899 async fn disabled_modules_are_still_manifest_validated() {
900 let temp = TempDir::new("disabled-manifest-invalid");
901 let script = manifest_fixture(
902 &temp,
903 "disabled-invalid",
904 json!({"provides": ["Not-valid/v1"], "requires": [], "must_never_reach": []}),
905 );
906 let config = write_config(&temp, vec![("disabled-invalid", &script, false)], json!({}));
907
908 let report = lint_config(&config, false).await;
909 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
910 assert_failure(
911 &report,
912 OperationalClass::ManifestInvalid,
913 "disabled-invalid",
914 );
915 }
916
917 #[tokio::test]
918 async fn golden_disabled_claimant_count_daemon_skip_and_verbose_optional_inventory() {
919 let temp = TempDir::new("disabled-claimant");
920 let consumer = manifest_fixture(
921 &temp,
922 "consumer",
923 json!({
924 "provides": [],
925 "requires": [
926 {"capability": "credentials-provider/v1", "need": "required"},
927 {"capability": "context-transform/v1", "need": "optional"}
928 ],
929 "must_never_reach": []
930 }),
931 );
932 let disabled = manifest_fixture(
933 &temp,
934 "disabled",
935 json!({"provides": ["credentials-provider/v1"], "requires": [], "must_never_reach": []}),
936 );
937 let daemon = temp.path().join("ck-subc");
938 let config = write_config(
939 &temp,
940 vec![
941 ("daemon", &daemon, true),
942 ("consumer", &consumer, true),
943 ("disabled", &disabled, false),
944 ],
945 json!({}),
946 );
947
948 let report = lint_config(&config, true).await;
949 assert_eq!(report.outcome, LintOutcome::SemanticViolation);
950 assert_eq!(report.examined, 2);
951 assert_eq!(report.configured, 2);
952 assert_eq!(
953 report.render(),
954 "checked 2 of 2 configured modules\n\
955verbose: skipped daemon entry daemon\n\
956deny consistency = self-contradiction check\n\
957optional context-transform/v1: no provider (consumer degrades, by declaration)\n\
958required consumer credentials-provider/v1: no enabled provider\n\
959note: disabled (disabled) claims credentials-provider/v1"
960 );
961 let default_report = lint_config(&config, false).await;
962 assert!(
963 !default_report
964 .render()
965 .contains("optional context-transform/v1"),
966 "default report must not style declared optional degradation as a warning:\n{}",
967 default_report.render()
968 );
969 }
970
971 #[tokio::test]
972 async fn golden_requirement_lines_sort_by_consumer_then_capability() {
973 let temp = TempDir::new("requirement-order");
974 let alpha = manifest_fixture(
975 &temp,
976 "alpha",
977 json!({"provides": [], "requires": [{"capability": "alpha/v1", "need": "required"}], "must_never_reach": []}),
978 );
979 let zeta = manifest_fixture(
980 &temp,
981 "zeta",
982 json!({"provides": [], "requires": [{"capability": "zeta/v1", "need": "required"}], "must_never_reach": []}),
983 );
984 let config = write_config(
985 &temp,
986 vec![("zeta", &zeta, true), ("alpha", &alpha, true)],
987 json!({}),
988 );
989
990 let report = lint_config(&config, false).await;
991 let rendered = report.render();
992 assert!(
993 rendered.find("required alpha alpha/v1").unwrap()
994 < rendered.find("required zeta zeta/v1").unwrap(),
995 "report:\n{rendered}"
996 );
997 }
998
999 #[tokio::test]
1000 async fn deny_self_contradiction_mutation_proof_requires_overlap() {
1001 let temp = TempDir::new("deny-self-contradiction");
1002 let self_contradiction = manifest_fixture(
1003 &temp,
1004 "contradictory",
1005 json!({
1006 "provides": [],
1007 "requires": [{"capability": "credentials-provider/v1", "need": "required"}],
1008 "must_never_reach": ["credentials-provider/v1"]
1009 }),
1010 );
1011 let config = write_config(
1012 &temp,
1013 vec![("contradictory", &self_contradiction, true)],
1014 json!({}),
1015 );
1016
1017 let report = lint_config(&config, false).await;
1018 assert_eq!(report.outcome, LintOutcome::SemanticViolation);
1019 assert!(
1020 !report
1021 .render()
1022 .contains("deny consistency = self-contradiction check"),
1023 "internal consistency vocabulary belongs behind --verbose"
1024 );
1025 let verbose = lint_config(&config, true).await;
1026 assert!(verbose
1027 .render()
1028 .contains("deny consistency = self-contradiction check"));
1029 assert!(verbose.render().contains(
1030 "requires_deny_conflict module=contradictory capability=credentials-provider/v1"
1031 ));
1032 }
1033
1034 #[tokio::test]
1035 async fn operational_failure_overrides_semantic_exit_classification() {
1036 let temp = TempDir::new("operational-trump");
1037 let consumer = manifest_fixture(
1038 &temp,
1039 "consumer",
1040 json!({"provides": [], "requires": [{"capability": "credentials-provider/v1", "need": "required"}], "must_never_reach": []}),
1041 );
1042 let broken = write_fixture_program(
1043 &temp,
1044 "broken",
1045 FixtureSpec {
1046 exit_code: 1,
1047 ..FixtureSpec::default()
1048 },
1049 );
1050 let config = write_config(
1051 &temp,
1052 vec![("consumer", &consumer, true), ("broken", &broken, true)],
1053 json!({}),
1054 );
1055
1056 let report = lint_config(&config, false).await;
1057 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
1058 assert!(
1059 report
1060 .render()
1061 .contains("checked 1 of 2 configured modules — broken do not expose a manifest"),
1062 "report:\n{}",
1063 report.render()
1064 );
1065 assert!(
1066 !report.render().contains("partial: evaluation incomplete"),
1067 "instrument detail belongs behind --verbose:\n{}",
1068 report.render()
1069 );
1070 assert!(report
1071 .render()
1072 .contains("required consumer credentials-provider/v1: no enabled provider"));
1073 }
1074
1075 #[tokio::test]
1076 async fn zero_examined_is_an_operational_failure_not_a_vacuous_pass() {
1077 let temp = TempDir::new("vacuity-floor");
1078 let config = write_config(&temp, Vec::new(), json!({}));
1079
1080 let report = lint_config(&config, false).await;
1081 assert_eq!(report.outcome, LintOutcome::OperationalFailure);
1082 assert_eq!(report.render(), "checked 0 of 0 configured modules");
1083 let verbose = lint_config(&config, true).await;
1084 assert!(verbose.render().contains("vacuity floor"));
1085 assert!(verbose
1086 .render()
1087 .contains("deny consistency = self-contradiction check"));
1088 }
1089
1090 #[tokio::test]
1091 async fn reserved_bindings_warn_when_unclaimed_and_fail_for_conflicting_claimants() {
1092 let temp = TempDir::new("reserved-bindings");
1093 let claimant = manifest_fixture(
1094 &temp,
1095 "other",
1096 json!({"provides": ["credentials-provider/v1"], "requires": [], "must_never_reach": []}),
1097 );
1098 let config = write_config(
1099 &temp,
1100 vec![("other", &claimant, true)],
1101 json!({
1102 "credentials-provider/v1": "bound",
1103 "context-transform/v1": "not-installed"
1104 }),
1105 );
1106
1107 let report = lint_config(&config, false).await;
1108 assert_eq!(report.outcome, LintOutcome::SemanticViolation);
1109 let rendered = report.render();
1110 assert!(rendered.contains(
1111 "reserved capability credentials-provider/v1: claimant other conflicts with binding bound"
1112 ));
1113 assert!(rendered.contains(
1114 "warning: reserved capability context-transform/v1 has no configured claimant for not-installed"
1115 ));
1116 }
1117}