eggsec-nse 0.3.0

Standalone Lua-based Nmap Scripting Engine runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::capabilities::NseCapabilityEvent;
use crate::limits::{NseExecutionLimits, NseExecutionStats};
use crate::profile::ResolvedNseExecutionProfile;
use crate::resolver::{registry, NseLoadDiagnostic, NseScriptSource};

/// Category of evidence extracted from NSE execution.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NseEvidenceKind {
    ServiceFingerprint,
    VersionInfo,
    CertificateInfo,
    VulnerabilitySignal,
    Misconfiguration,
    CapabilityDenial,
    CompatibilityWarning,
    ScriptOutput,
}

impl fmt::Display for NseEvidenceKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ServiceFingerprint => write!(f, "service-fingerprint"),
            Self::VersionInfo => write!(f, "version-info"),
            Self::CertificateInfo => write!(f, "certificate-info"),
            Self::VulnerabilitySignal => write!(f, "vulnerability-signal"),
            Self::Misconfiguration => write!(f, "misconfiguration"),
            Self::CapabilityDenial => write!(f, "capability-denial"),
            Self::CompatibilityWarning => write!(f, "compatibility-warning"),
            Self::ScriptOutput => write!(f, "script-output"),
        }
    }
}

/// A single structured evidence item extracted from NSE script output and runtime context.
///
/// Evidence items are normalized observations — not findings or vulnerabilities.
/// They represent factual records from capability events, compatibility diagnostics,
/// rule evaluation results, and script output capture.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NseEvidenceItem {
    /// Unique identifier for this evidence item (e.g. "nse-ev-0").
    pub id: String,
    /// Category of the evidence.
    pub kind: NseEvidenceKind,
    /// Title summarizing the observation.
    pub title: String,
    /// Detailed summary of the evidence.
    pub summary: String,
    /// Target host/port the evidence relates to.
    pub target: String,
    /// Optional port number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
    /// Optional service name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service: Option<String>,
    /// Confidence level: "confirmed", "likely", "possible", "low".
    pub confidence: String,
    /// Source module/script that produced this evidence.
    pub source: String,
    /// Optional raw excerpt from script output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_excerpt: Option<String>,
    /// References (CWE, CVE, URLs).
    pub references: Vec<String>,
    /// Classification tags.
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseRunReport {
    pub target: String,
    pub script_name: String,
    pub script_source: NseScriptSourceSummary,
    pub profile: NseProfileSummary,
    pub sandbox: NseSandboxSummary,
    pub limits: NseLimitsSummary,
    pub stats: NseExecutionStatsSummary,
    pub resolver: NseResolverSummary,
    /// Per-run libraries required or attempted during execution.
    /// This is not a static capability inventory.
    pub libraries: Vec<NseLibraryUseReport>,
    pub rules: Vec<NseRuleEvaluationReport>,
    pub output: NseOutputSummary,
    pub compatibility: NseCompatibilitySummary,
    /// Capability events recorded during execution (denials, warnings, allowed ops).
    pub capability_events: Vec<NseCapabilityEventSummary>,
    /// Structured evidence items extracted from script output and runtime context.
    pub evidence: Vec<NseEvidenceItem>,
    pub warnings: Vec<String>,
    pub errors: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseScriptSourceSummary {
    pub kind: String,
    pub label: String,
    pub size: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseProfileSummary {
    pub kind: String,
    pub audit_label: String,
    pub warnings: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseSandboxSummary {
    pub enabled: bool,
    pub feature_compiled: bool,
    pub allowed_dir: Option<String>,
    pub allowed_commands_count: usize,
    pub allowed_networks_count: usize,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NseLimitsSummary {
    pub wall_clock_timeout_secs: Option<f64>,
    pub lua_instruction_budget: Option<u64>,
    pub max_output_bytes: Option<usize>,
    pub max_script_bytes: Option<usize>,
    pub max_required_module_bytes: Option<usize>,
    pub max_network_operations: Option<u64>,
    pub max_filesystem_operations: Option<u64>,
    pub max_lua_memory_bytes: Option<usize>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NseExecutionStatsSummary {
    pub elapsed_secs: f64,
    pub output_bytes: usize,
    pub lua_instruction_count: u64,
    pub network_operations: u64,
    pub network_bytes_read: u64,
    pub network_bytes_written: u64,
    pub filesystem_operations: u64,
    pub filesystem_bytes_read: u64,
    pub limit_violation: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NseResolverSummary {
    pub total_diagnostics: usize,
    pub resolved_count: usize,
    pub blocked_count: usize,
    pub rejected_count: usize,
    pub diagnostics: Vec<NseResolverDiagnosticSummary>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseResolverDiagnosticSummary {
    pub kind: String,
    pub source: String,
    pub detail: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Summary of a single observed `require()` attempt.
pub enum NseRequiredModuleSource {
    BuiltinGlobal,
    Filesystem,
    Missing,
    BlockedByPolicy,
    InvalidName,
    Unknown,
}

impl fmt::Display for NseRequiredModuleSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BuiltinGlobal => write!(f, "builtin-global"),
            Self::Filesystem => write!(f, "filesystem"),
            Self::Missing => write!(f, "missing"),
            Self::BlockedByPolicy => write!(f, "blocked-by-policy"),
            Self::InvalidName => write!(f, "invalid-name"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Internal per-run record of an observed `require()` attempt.
pub struct NseRequiredModuleReport {
    pub name: String,
    pub loaded: bool,
    pub source: NseRequiredModuleSource,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseLibraryUseReport {
    pub name: String,
    pub category: String,
    pub registered: bool,
    pub side_effects: Vec<String>,
    pub fallback_behavior: String,
    pub notes: String,
    /// `true` only when the runtime observed a successful load.
    pub loaded: bool,
    pub warnings: Vec<String>,
}

impl NseLibraryUseReport {
    pub fn from_required_module(required: &NseRequiredModuleReport) -> Self {
        let mut warnings = Vec::new();
        if !required.loaded {
            warnings.push(format!("require source: {}", required.source));
        }
        if let Some(error) = &required.error {
            warnings.push(error.clone());
        }

        if let Some(desc) = registry::find_library(&required.name) {
            let side_effects = desc
                .sandbox_side_effects
                .iter()
                .map(|se| se.to_string())
                .collect();
            Self {
                name: desc.name.to_string(),
                category: desc.category.to_string(),
                registered: true,
                side_effects,
                fallback_behavior: desc.fallback_behavior.to_string(),
                notes: desc.notes.to_string(),
                loaded: required.loaded,
                warnings,
            }
        } else {
            Self {
                name: required.name.clone(),
                category: "Unknown".to_string(),
                registered: false,
                side_effects: Vec::new(),
                fallback_behavior: "Unknown".to_string(),
                notes: "not present in NSE library registry".to_string(),
                loaded: required.loaded,
                warnings,
            }
        }
    }
}

pub fn library_use_reports_from_required_modules(
    required_modules: &[NseRequiredModuleReport],
) -> Vec<NseLibraryUseReport> {
    required_modules
        .iter()
        .map(NseLibraryUseReport::from_required_module)
        .collect()
}

pub fn library_use_reports_from_static_requires(names: &[String]) -> Vec<NseLibraryUseReport> {
    names
        .iter()
        .map(|name| {
            let required = NseRequiredModuleReport {
                name: name.clone(),
                loaded: false,
                source: NseRequiredModuleSource::Unknown,
                error: Some(
                    "detected statically; runtime require tracking did not complete".to_string(),
                ),
            };
            NseLibraryUseReport::from_required_module(&required)
        })
        .collect()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseRuleEvaluationReport {
    pub kind: String,
    pub evaluated: bool,
    pub matched: bool,
    pub exactness: String,
    pub error: Option<String>,
    pub summary: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unsupported: Option<String>,
    /// Source of host context used for this rule evaluation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub host_context_source: Option<String>,
    /// Source of port context used for this rule evaluation (portrule only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub port_context_source: Option<String>,
    /// Whether service context was available for this evaluation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_context_available: Option<bool>,
    /// Fidelity reason explaining why the result is exact or approximate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fidelity_reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseOutputSummary {
    pub has_output: bool,
    pub content: String,
    pub line_count: usize,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseCompatibilitySummary {
    pub status: NseRunCompatibilityStatus,
    pub fidelity: NseRunFidelity,
    pub unsupported_features: Vec<String>,
    pub approximations: Vec<String>,
}

/// Summary of a capability event for report integration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseCapabilityEventSummary {
    /// Kind of operation (filesystem_read, network_tcp, etc.).
    pub kind: String,
    /// Operation name (e.g., "io.popen", "socket.connect").
    pub operation: String,
    /// Optional target (host, path, command).
    pub target: Option<String>,
    /// Whether the operation was allowed.
    pub allowed: bool,
    /// Denial or warning reason if applicable.
    pub reason: Option<String>,
}

impl From<&NseCapabilityEvent> for NseCapabilityEventSummary {
    fn from(event: &NseCapabilityEvent) -> Self {
        Self {
            kind: event.kind.to_string(),
            operation: event.operation.clone(),
            target: event.target.clone(),
            allowed: event.allowed,
            reason: event.reason.clone(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NseRunCompatibilityStatus {
    Compatible,
    CompatibleWithWarnings,
    Partial,
    Unsupported,
    Failed,
    Unknown,
}

impl fmt::Display for NseRunCompatibilityStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Compatible => write!(f, "compatible"),
            Self::CompatibleWithWarnings => write!(f, "compatible-with-warnings"),
            Self::Partial => write!(f, "partial"),
            Self::Unsupported => write!(f, "unsupported"),
            Self::Failed => write!(f, "failed"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NseRunFidelity {
    Full,
    Approximate,
    Minimal,
    Unknown,
}

impl fmt::Display for NseRunFidelity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Full => write!(f, "full"),
            Self::Approximate => write!(f, "approximate"),
            Self::Minimal => write!(f, "minimal"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

impl NseRunReport {
    pub fn new(target: &str, script_name: &str) -> Self {
        Self {
            target: target.to_string(),
            script_name: script_name.to_string(),
            script_source: NseScriptSourceSummary {
                kind: "unknown".to_string(),
                label: String::new(),
                size: 0,
            },
            profile: NseProfileSummary {
                kind: "unknown".to_string(),
                audit_label: String::new(),
                warnings: Vec::new(),
            },
            sandbox: NseSandboxSummary {
                enabled: false,
                feature_compiled: false,
                allowed_dir: None,
                allowed_commands_count: 0,
                allowed_networks_count: 0,
            },
            limits: NseLimitsSummary::default(),
            stats: NseExecutionStatsSummary::default(),
            resolver: NseResolverSummary::default(),
            libraries: Vec::new(),
            rules: Vec::new(),
            output: NseOutputSummary {
                has_output: false,
                content: String::new(),
                line_count: 0,
                truncated: false,
            },
            compatibility: NseCompatibilitySummary {
                status: NseRunCompatibilityStatus::Unknown,
                fidelity: NseRunFidelity::Unknown,
                unsupported_features: Vec::new(),
                approximations: Vec::new(),
            },
            capability_events: Vec::new(),
            evidence: Vec::new(),
            warnings: Vec::new(),
            errors: Vec::new(),
        }
    }

    pub fn with_profile(mut self, profile: &ResolvedNseExecutionProfile) -> Self {
        self.profile = NseProfileSummary {
            kind: profile.kind.to_string(),
            audit_label: profile.audit_label.clone(),
            warnings: profile.warnings.clone(),
        };
        self.sandbox = NseSandboxSummary {
            enabled: profile.sandbox.enabled,
            feature_compiled: cfg!(feature = "sandbox"),
            allowed_dir: profile
                .sandbox
                .allowed_dir
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned()),
            allowed_commands_count: profile.sandbox.allowed_commands.len(),
            allowed_networks_count: profile.sandbox.allowed_networks.len(),
        };
        self.limits = NseLimitsSummary::from(&profile.limits);
        self.warnings.extend(profile.warnings.iter().cloned());
        self
    }

    pub fn with_script_source(mut self, source: &NseScriptSource) -> Self {
        self.script_source = NseScriptSourceSummary::from(source);
        self
    }

    pub fn with_stats(mut self, stats: &NseExecutionStats) -> Self {
        self.stats = NseExecutionStatsSummary::from(stats);
        self
    }

    pub fn with_resolver_diagnostics(mut self, diagnostics: &[NseLoadDiagnostic]) -> Self {
        let mut resolved = 0;
        let mut blocked = 0;
        let mut rejected = 0;
        let mut summaries = Vec::new();

        for diag in diagnostics {
            let (kind_str, source, detail) = match diag {
                NseLoadDiagnostic::Resolved { source, bytes } => {
                    resolved += 1;
                    ("resolved", source.to_string(), format!("{} bytes", bytes))
                }
                NseLoadDiagnostic::Blocked { source, reason } => {
                    blocked += 1;
                    ("blocked", source.to_string(), reason.clone())
                }
                NseLoadDiagnostic::OutsideRoot { path, root } => {
                    rejected += 1;
                    (
                        "outside_root",
                        path.display().to_string(),
                        format!("root: {}", root.display()),
                    )
                }
                NseLoadDiagnostic::SymlinkRejected { path, resolved: r } => {
                    rejected += 1;
                    (
                        "symlink_rejected",
                        path.display().to_string(),
                        format!("-> {}", r.display()),
                    )
                }
                NseLoadDiagnostic::ModuleNameRejected { name, reason } => {
                    rejected += 1;
                    ("module_name_rejected", name.clone(), reason.clone())
                }
                NseLoadDiagnostic::OversizedRejected {
                    source,
                    size,
                    limit,
                } => {
                    rejected += 1;
                    (
                        "oversized_rejected",
                        source.to_string(),
                        format!("{} > {} bytes", size, limit),
                    )
                }
                NseLoadDiagnostic::ModuleLoadFailed {
                    name, path, error, ..
                } => {
                    rejected += 1;
                    (
                        "module_load_failed",
                        name.clone(),
                        format!("{}: {}", path.display(), error),
                    )
                }
            };

            summaries.push(NseResolverDiagnosticSummary {
                kind: kind_str.to_string(),
                source,
                detail,
            });
        }

        self.resolver = NseResolverSummary {
            total_diagnostics: diagnostics.len(),
            resolved_count: resolved,
            blocked_count: blocked,
            rejected_count: rejected,
            diagnostics: summaries,
        };
        self
    }

    pub fn with_rules(mut self, rules: Vec<NseRuleEvaluationReport>) -> Self {
        self.rules = rules;
        self
    }

    pub fn with_libraries(mut self, libraries: Vec<NseLibraryUseReport>) -> Self {
        self.libraries = libraries;
        self
    }

    pub fn with_capability_events(mut self, events: Vec<NseCapabilityEvent>) -> Self {
        self.capability_events = events.iter().map(NseCapabilityEventSummary::from).collect();
        self
    }

    pub fn with_output(mut self, output: &str) -> Self {
        let line_count = output.lines().count();
        let truncated = output.len() > 10000;
        let content = if truncated {
            format!("{}...(truncated)", &output[..10000])
        } else {
            output.to_string()
        };
        self.output = NseOutputSummary {
            has_output: !output.is_empty(),
            content,
            line_count,
            truncated,
        };
        self
    }

    pub fn with_evidence(mut self, evidence: Vec<NseEvidenceItem>) -> Self {
        self.evidence = evidence;
        self
    }

    pub fn with_error(mut self, error: &str) -> Self {
        self.errors.push(error.to_string());
        self
    }

    pub fn compute_compatibility(mut self) -> Self {
        let has_errors = !self.errors.is_empty();
        let has_rejected = self.resolver.rejected_count > 0;
        let has_warnings = !self.warnings.is_empty();
        let has_approxs = self.rules.iter().any(|r| r.exactness == "approximate");
        let has_capability_denials = self.capability_events.iter().any(|e| !e.allowed);

        let status = if has_errors {
            NseRunCompatibilityStatus::Failed
        } else if has_rejected || has_capability_denials {
            NseRunCompatibilityStatus::Partial
        } else if has_approxs || has_warnings {
            NseRunCompatibilityStatus::CompatibleWithWarnings
        } else {
            NseRunCompatibilityStatus::Compatible
        };

        let fidelity = if has_approxs {
            NseRunFidelity::Approximate
        } else if has_rejected {
            NseRunFidelity::Minimal
        } else {
            NseRunFidelity::Full
        };

        let unsupported_features: Vec<String> = self
            .resolver
            .diagnostics
            .iter()
            .filter(|d| d.kind == "module_name_rejected" || d.kind == "module_load_failed")
            .map(|d| d.source.clone())
            .collect();

        let approximations: Vec<String> = self
            .rules
            .iter()
            .filter(|r| r.exactness == "approximate")
            .map(|r| format!("{}: {}", r.kind, r.summary))
            .collect();

        self.compatibility = NseCompatibilitySummary {
            status,
            fidelity,
            unsupported_features,
            approximations,
        };
        self
    }
}

/// Evaluate a Lua rule result into a structured report.
///
/// Handles errors, nil, boolean true/false, and non-boolean return values,
/// producing a truthful `NseRuleEvaluationReport` instead of collapsing
/// all non-true cases into `false`.
pub fn evaluate_rule(
    kind: &str,
    lua_result: Result<mlua::Value, mlua::Error>,
) -> NseRuleEvaluationReport {
    match lua_result {
        Ok(mlua::Value::Nil) => NseRuleEvaluationReport {
            kind: kind.to_string(),
            evaluated: true,
            matched: false,
            exactness: "exact".to_string(),
            error: None,
            summary: "rule returned nil".to_string(),
            unsupported: None,
            host_context_source: None,
            port_context_source: None,
            service_context_available: None,
            fidelity_reason: None,
        },
        Ok(mlua::Value::Boolean(true)) => NseRuleEvaluationReport {
            kind: kind.to_string(),
            evaluated: true,
            matched: true,
            exactness: "exact".to_string(),
            error: None,
            summary: "rule matched".to_string(),
            unsupported: None,
            host_context_source: None,
            port_context_source: None,
            service_context_available: None,
            fidelity_reason: None,
        },
        Ok(mlua::Value::Boolean(false)) => NseRuleEvaluationReport {
            kind: kind.to_string(),
            evaluated: true,
            matched: false,
            exactness: "exact".to_string(),
            error: None,
            summary: "rule did not match".to_string(),
            unsupported: None,
            host_context_source: None,
            port_context_source: None,
            service_context_available: None,
            fidelity_reason: None,
        },
        Ok(other) => {
            let type_name = match &other {
                mlua::Value::String(_) => "string",
                mlua::Value::Integer(_) => "integer",
                mlua::Value::Number(_) => "number",
                mlua::Value::Table(_) => "table",
                mlua::Value::Function(_) => "function",
                mlua::Value::Thread(_) => "thread",
                mlua::Value::UserData(_) => "userdata",
                mlua::Value::LightUserData(_) => "lightuserdata",
                mlua::Value::Vector(_) => "vector",
                mlua::Value::Buffer(_) => "buffer",
                mlua::Value::Error(_) => "error",
                mlua::Value::Nil => "nil",
                mlua::Value::Boolean(_) => "boolean",
                _ => "unknown",
            };
            NseRuleEvaluationReport {
                kind: kind.to_string(),
                evaluated: false,
                matched: false,
                exactness: "unsupported".to_string(),
                error: None,
                summary: format!("expected boolean, got {}", type_name),
                unsupported: Some(format!("expected boolean, got {}", type_name)),
                host_context_source: None,
                port_context_source: None,
                service_context_available: None,
                fidelity_reason: None,
            }
        }
        Err(e) => NseRuleEvaluationReport {
            kind: kind.to_string(),
            evaluated: false,
            matched: false,
            exactness: "exact".to_string(),
            error: Some(e.to_string()),
            summary: format!("rule error: {}", e),
            unsupported: None,
            host_context_source: None,
            port_context_source: None,
            service_context_available: None,
            fidelity_reason: None,
        },
    }
}

/// Evaluate a Lua rule result with host/port context metadata.
///
/// This is the preferred entry point for rule evaluation when context
/// provenance is available. It produces the same rule result as
/// `evaluate_rule()` but annotates the report with context source
/// information for fidelity tracking.
pub fn evaluate_rule_with_context(
    kind: &str,
    lua_result: Result<mlua::Value, mlua::Error>,
    host_ctx: &crate::context::NseHostContext,
    port_ctx: Option<&crate::context::NsePortContext>,
) -> NseRuleEvaluationReport {
    let mut report = evaluate_rule(kind, lua_result);

    report.host_context_source = Some(host_ctx.source.to_string());
    report.port_context_source = port_ctx.map(|p| p.source.to_string());
    report.service_context_available = port_ctx
        .and_then(|p| p.service.as_ref())
        .map(|s| s.name.is_some() || s.product.is_some() || s.version.is_some());

    // Compute fidelity reason based on context sources
    let host_synthetic = host_ctx.source == crate::context::NseContextSource::Synthetic;
    let port_synthetic = port_ctx
        .map(|p| p.source == crate::context::NseContextSource::Synthetic)
        .unwrap_or(false);
    let no_service = port_ctx
        .map(|p| p.service.is_none() || p.service.as_ref().map_or(true, |s| s.name.is_none()))
        .unwrap_or(true);

    if report.exactness == "exact" && report.matched {
        if host_synthetic || port_synthetic {
            report.fidelity_reason = Some(format!(
                "rule matched but host context is {} and port context is {}",
                if host_synthetic { "synthetic" } else { "scan" },
                if port_synthetic { "synthetic" } else { "scan" },
            ));
            // Mark as approximate when context is synthetic
            report.exactness = "approximate".to_string();
        } else if no_service && kind == "portrule" {
            report.fidelity_reason =
                Some("rule matched but service context is unavailable".to_string());
        }
    } else if report.exactness == "exact" && !report.matched {
        if host_synthetic || port_synthetic {
            report.fidelity_reason = Some(format!(
                "rule did not match with {} host context and {} port context",
                if host_synthetic { "synthetic" } else { "scan" },
                if port_synthetic { "synthetic" } else { "scan" },
            ));
        }
    }

    report
}

impl From<&NseExecutionLimits> for NseLimitsSummary {
    fn from(limits: &NseExecutionLimits) -> Self {
        Self {
            wall_clock_timeout_secs: limits.wall_clock_timeout.map(|d| d.as_secs_f64()),
            lua_instruction_budget: limits.lua_instruction_budget,
            max_output_bytes: limits.max_output_bytes,
            max_script_bytes: limits.max_script_bytes,
            max_required_module_bytes: limits.max_required_module_bytes,
            max_network_operations: limits.max_network_operations,
            max_filesystem_operations: limits.max_filesystem_operations,
            max_lua_memory_bytes: limits.max_lua_memory_bytes,
        }
    }
}

impl From<&NseExecutionStats> for NseExecutionStatsSummary {
    fn from(stats: &NseExecutionStats) -> Self {
        Self {
            elapsed_secs: stats.elapsed.as_secs_f64(),
            output_bytes: stats.output_bytes,
            lua_instruction_count: stats.lua_instruction_count,
            network_operations: stats.network_operations,
            network_bytes_read: stats.network_bytes_read,
            network_bytes_written: stats.network_bytes_written,
            filesystem_operations: stats.filesystem_operations,
            filesystem_bytes_read: stats.filesystem_bytes_read,
            limit_violation: stats.limit_violation.as_ref().map(|v| v.to_string()),
        }
    }
}

impl From<&NseScriptSource> for NseScriptSourceSummary {
    fn from(source: &NseScriptSource) -> Self {
        match source {
            NseScriptSource::Builtin { name } => Self {
                kind: "builtin".to_string(),
                label: name.clone(),
                size: 0,
            },
            NseScriptSource::TrustedRegistry { name } => Self {
                kind: "registry".to_string(),
                label: name.clone(),
                size: 0,
            },
            NseScriptSource::File { path } => Self {
                kind: "file".to_string(),
                label: path.display().to_string(),
                size: 0,
            },
            NseScriptSource::InlineManual { label, content } => Self {
                kind: "inline".to_string(),
                label: label.clone(),
                size: content.len(),
            },
        }
    }
}

/// Extract structured evidence items from report state.
///
/// Conservative extraction: only produces evidence from structured sources
/// (capability events, compatibility state, rule evaluations, output capture).
/// No fragile prose parsing. Raw output remains available for manual review.
pub fn extract_evidence(
    target: &str,
    script_name: &str,
    capability_events: &[NseCapabilityEventSummary],
    compatibility: &NseCompatibilitySummary,
    rules: &[NseRuleEvaluationReport],
    output: &NseOutputSummary,
) -> Vec<NseEvidenceItem> {
    let mut evidence = Vec::new();
    let mut counter = 0u32;

    // 1. Capability denials → CapabilityDenial evidence
    for event in capability_events.iter().filter(|e| !e.allowed) {
        let id = format!("nse-ev-{}", counter);
        counter += 1;
        let target_detail = event.target.as_deref().unwrap_or(target);
        evidence.push(NseEvidenceItem {
            id,
            kind: NseEvidenceKind::CapabilityDenial,
            title: format!("{} denied by policy", event.kind),
            summary: event.reason.clone().unwrap_or_else(|| {
                format!("{} operation '{}' was denied", event.kind, event.operation)
            }),
            target: target_detail.to_string(),
            port: None,
            service: None,
            confidence: "confirmed".to_string(),
            source: script_name.to_string(),
            raw_excerpt: None,
            references: Vec::new(),
            tags: vec!["capability".to_string(), event.kind.clone()],
        });
    }

    // 2. Compatibility issues → CompatibilityWarning evidence
    for feature in &compatibility.unsupported_features {
        let id = format!("nse-ev-{}", counter);
        counter += 1;
        evidence.push(NseEvidenceItem {
            id,
            kind: NseEvidenceKind::CompatibilityWarning,
            title: format!("Unsupported feature: {}", feature),
            summary: format!("Module '{}' is not supported in this environment", feature),
            target: target.to_string(),
            port: None,
            service: None,
            confidence: "confirmed".to_string(),
            source: script_name.to_string(),
            raw_excerpt: None,
            references: Vec::new(),
            tags: vec!["compatibility".to_string(), "unsupported".to_string()],
        });
    }

    for approx in &compatibility.approximations {
        let id = format!("nse-ev-{}", counter);
        counter += 1;
        evidence.push(NseEvidenceItem {
            id,
            kind: NseEvidenceKind::CompatibilityWarning,
            title: format!("Approximate result: {}", approx),
            summary: format!("Rule evaluation is approximate: {}", approx),
            target: target.to_string(),
            port: None,
            service: None,
            confidence: "likely".to_string(),
            source: script_name.to_string(),
            raw_excerpt: None,
            references: Vec::new(),
            tags: vec!["compatibility".to_string(), "approximate".to_string()],
        });
    }

    // 3. Rule evaluation errors → CompatibilityWarning evidence
    for rule in rules.iter().filter(|r| r.error.is_some()) {
        let id = format!("nse-ev-{}", counter);
        counter += 1;
        evidence.push(NseEvidenceItem {
            id,
            kind: NseEvidenceKind::CompatibilityWarning,
            title: format!("Rule error: {}", rule.kind),
            summary: rule.error.clone().unwrap_or_default(),
            target: target.to_string(),
            port: None,
            service: None,
            confidence: "confirmed".to_string(),
            source: script_name.to_string(),
            raw_excerpt: None,
            references: Vec::new(),
            tags: vec!["rule-error".to_string(), rule.kind.clone()],
        });
    }

    // 4. Script output → ScriptOutput evidence (conservative: only if non-empty)
    if output.has_output && !output.content.is_empty() {
        let excerpt = if output.content.len() > 500 {
            format!("{}...", &output.content[..500])
        } else {
            output.content.clone()
        };
        let id = format!("nse-ev-{}", counter);
        evidence.push(NseEvidenceItem {
            id,
            kind: NseEvidenceKind::ScriptOutput,
            title: "Script output captured".to_string(),
            summary: format!("{} lines of output", output.line_count),
            target: target.to_string(),
            port: None,
            service: None,
            confidence: "confirmed".to_string(),
            source: script_name.to_string(),
            raw_excerpt: Some(excerpt),
            references: Vec::new(),
            tags: vec!["output".to_string()],
        });
    }

    evidence
}