influxdb3-plugin-sdk 0.4.1

Author-side packaging library for InfluxDB 3 plugins.
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
//! Plugin-directory validation — filesystem + Python-parser mechanism.
//!
//! This module owns the *mechanism* of validating a plugin directory on disk:
//! walking the top level, reading the entry-point file, and extracting
//! top-level Python definitions with `tree-sitter-python`. The *contract* —
//! what counts as a valid entry-point layout and a satisfied trigger — is the
//! pure surface in [`influxdb3_plugin_schemas::plugin_format`]
//! ([`classify_entry_point`], [`check_trigger_bindings`]). This module feeds its
//! mechanical results into those pure checks.
//!
//! Two plugin formats are supported:
//!
//! - **Multi-file** — a directory containing `__init__.py` (entry point) plus
//!   any number of helper modules.
//! - **Single-file** — a directory containing exactly one `.py` file (no
//!   `__init__.py`).
//!
//! Entry-point detection uses `symlink_metadata()` so symbolic links are
//! excluded (matching archive-collection semantics — archives store the link
//! target, not the link itself).
//!
//! # Reference extractor
//!
//! [`extract_top_level_defs`] is the reference implementation of the
//! extraction rules documented on [`influxdb3_plugin_schemas::plugin_format::TopLevelFunctionDef`].
//! It is `pub` so a consumer that accepts a `tree-sitter` dependency (e.g. the
//! future runtime) can reuse it directly instead of reimplementing the rules.
//! The shared [`TOP_LEVEL_DEF_CONFORMANCE_CASES`](influxdb3_plugin_schemas::plugin_format::TOP_LEVEL_DEF_CONFORMANCE_CASES)
//! guards drift between extractors.
//!
//! # Manifest gate and multi-error collection
//!
//! The manifest is the gate: `manifest.toml` is read and parsed before any
//! entry-point work. A missing or malformed manifest is reported on its own —
//! without a valid manifest the `[plugin].exclude` list is unknown, so no
//! source-file selection (and therefore no entry-point detection) can run.
//!
//! With a valid manifest, source-file selection drives entry-point detection,
//! and cross-file failures accumulate into a [`ValidationReport`] so multiple
//! issues surface together in one pass.

use influxdb3_plugin_schemas::plugin_format::{
    TopLevelFunctionDef, ValidatedPluginDefinition, check_trigger_bindings, classify_entry_point,
};
use influxdb3_plugin_schemas::{Index, IndexEntry, Manifest, ValidationError};
use std::path::Path;

use crate::{ValidationFailure, ValidationReport};

/// A parser-level failure from [`extract_top_level_defs`].
///
/// Carries no caller-supplied metadata (e.g. the filename); the orchestrator
/// decorates it into [`ValidationError::PythonParse`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PythonParseError {
    pub message: String,
}

/// Extracts every top-level function definition from `source`, in source
/// order, using `tree-sitter-python`.
///
/// This is the reference implementation of the extraction rules on
/// [`TopLevelFunctionDef`]. It captures top-level `def`/`async def` and decorated
/// top-level functions; it does not capture class methods, nested defs,
/// guarded defs, re-exports, or assignments. It does **not** dedup — a
/// redefined name appears once per occurrence; last-occurrence-wins is
/// resolved by [`check_trigger_bindings`].
///
/// Returns [`PythonParseError`] when the source does not parse as valid
/// Python 3.
pub fn extract_top_level_defs(source: &str) -> Result<Vec<TopLevelFunctionDef>, PythonParseError> {
    let mut parser = tree_sitter::Parser::new();
    let language = tree_sitter_python::LANGUAGE;
    parser
        .set_language(&language.into())
        .expect("tree-sitter-python grammar initializes");

    let Some(tree) = parser.parse(source, None) else {
        return Err(PythonParseError {
            message: "tree-sitter produced no parse tree".into(),
        });
    };

    let root = tree.root_node();
    if root.has_error() {
        return Err(PythonParseError {
            message: format_parse_error(root, source),
        });
    }

    // Recognize top-level `function_definition` and `decorated_definition`
    // (which wraps a `function_definition`). Decorators don't make a def
    // indirect; class methods, re-exports, and assignments do, so those
    // aren't collected here.
    let mut defs: Vec<TopLevelFunctionDef> = Vec::new();
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if let Some(def) = extract_top_level_def(&child, source) {
            defs.push(def);
        }
    }
    Ok(defs)
}

/// If `node` is (or wraps) a top-level function definition, return its name
/// and sync/async kind. Returns `None` for class defs, imports, expressions,
/// assignments, and malformed defs caught by tree-sitter error recovery.
fn extract_top_level_def(
    node: &tree_sitter::Node<'_>,
    source: &str,
) -> Option<TopLevelFunctionDef> {
    let function_def = match node.kind() {
        "function_definition" => *node,
        // `@foo\ndef bar():` parses as a `decorated_definition` wrapping a
        // `function_definition`; descend to the inner node.
        "decorated_definition" => {
            let mut cursor = node.walk();
            node.children(&mut cursor)
                .find(|c| c.kind() == "function_definition")?
        }
        _ => return None,
    };
    let name_node = function_def.child_by_field_name("name")?;
    let name = source[name_node.byte_range()].to_owned();
    Some(TopLevelFunctionDef {
        name,
        is_async: is_async_function(&function_def),
    })
}

/// tree-sitter-python 0.25 emits both `def` and `async def` as
/// `function_definition`; the async case has an `async` keyword child.
fn is_async_function(function_def: &tree_sitter::Node<'_>) -> bool {
    let mut cursor = function_def.walk();
    for child in function_def.children(&mut cursor) {
        if child.kind() == "async" {
            return true;
        }
    }
    false
}

/// Reads a required file, treating `NotFound` as a collectible validation
/// error. Returns `Ok(Some(content))` on success, `Ok(None)` when missing
/// (after recording [`ValidationError::MissingRequiredFile`]), and
/// `Err(ValidationFailure::Io)` for other I/O errors.
fn read_required(
    path: &Path,
    label: &str,
    report: &mut ValidationReport,
) -> Result<Option<String>, ValidationFailure> {
    match std::fs::read_to_string(path) {
        Ok(s) => Ok(Some(s)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            report.push(ValidationError::MissingRequiredFile { file: label.into() });
            Ok(None)
        }
        Err(source) => Err(ValidationFailure::Io {
            source,
            path: Some(path.to_path_buf()),
        }),
    }
}

/// Validates a plugin directory.
///
/// Returns a [`ValidatedPluginDefinition`] (parsed manifest + classified entry point)
/// on success. On failure:
/// - [`ValidationFailure::Io`] — I/O error other than `NotFound` on
///   `manifest.toml`, or an I/O error during source-file selection.
/// - [`ValidationFailure::InvalidExcludePattern`] — a malformed
///   `[plugin].exclude` pattern.
/// - [`ValidationFailure::Invalid`] — structural or cross-file check failures.
///
/// The manifest is the gate. `manifest.toml` is read and parsed first; a
/// missing file surfaces as [`ValidationError::MissingRequiredFile`] and a
/// parse failure surfaces its [`ValidationError::SchemaReported`] diagnostics —
/// in both cases entry-point detection does **not** run, because without a
/// valid manifest the `[plugin].exclude` list (and therefore the source-file
/// selection) is unknown.
///
/// With a valid manifest, [`crate::plugin_source_files::select`] applies the
/// exclude list, the entry point is classified from the selected depth-1 files,
/// and trigger checks run against the entry point's source. An unreadable
/// entry-point file after detection produces [`ValidationError::NoEntryPoint`].
pub fn plugin_dir(dir: &Path) -> Result<ValidatedPluginDefinition, ValidationFailure> {
    let mut report = ValidationReport::new();

    // Step 1: manifest is the gate. Without a valid manifest there is no
    // exclude list, so no source-file selection and no entry-point detection.
    let Some(manifest_raw) =
        read_required(&dir.join("manifest.toml"), "manifest.toml", &mut report)?
    else {
        report.into_result()?;
        unreachable!("non-empty report always returns Err");
    };
    let manifest = match Manifest::parse_toml(&manifest_raw) {
        Ok(manifest) => manifest,
        Err(schema_errors) => {
            report.extend(
                schema_errors
                    .into_iter()
                    .map(ValidationError::SchemaReported),
            );
            report.into_result()?;
            unreachable!("non-empty report always returns Err");
        }
    };

    // Step 2: source-file selection (manifest-driven). Invalid patterns and
    // I/O errors short-circuit; they are not collectible diagnostics.
    let selected = crate::plugin_source_files::select(dir, &manifest.plugin.exclude)
        .map_err(ValidationFailure::from)?;

    // Step 3: derive top-level (depth-1) file names from the selected set.
    let top_level: Vec<String> = selected
        .iter()
        .filter(|f| !f.normalized.contains('/'))
        .map(|f| f.normalized.clone())
        .collect();

    // The manifest must survive selection — exclude can drop it, and the
    // packaged set is what counts. A selected set without manifest.toml is
    // invalid (it would package a manifest-less archive), so report it as the
    // ordinary missing-required-file error rather than a special exclude error.
    if !top_level.iter().any(|name| name == "manifest.toml") {
        report.push(ValidationError::MissingRequiredFile {
            file: "manifest.toml".into(),
        });
    }

    // Step 4: classify the entry point from the selected depth-1 files.
    let entry_point = match classify_entry_point(&top_level) {
        Ok(ep) => Some(ep),
        Err(diag) => {
            report.push(diag);
            None
        }
    };

    // Step 5: entry-point read + extraction + trigger checks.
    if let Some(ep) = &entry_point {
        let file_name = ep.file_name().to_owned();
        match std::fs::read_to_string(dir.join(&file_name)) {
            Err(_) => report.push(ValidationError::NoEntryPoint),
            Ok(source) => match extract_top_level_defs(&source) {
                Err(PythonParseError { message }) => report.push(ValidationError::PythonParse {
                    entry_point: file_name,
                    message,
                }),
                Ok(defs) => {
                    let diagnostics =
                        check_trigger_bindings(&manifest.plugin.triggers, &defs, &file_name);
                    report.extend(diagnostics);
                }
            },
        }
    }

    // Step 6: success only when the report is empty.
    report.into_result()?;
    let entry_point = entry_point.expect("empty report implies a classified entry point");
    Ok(ValidatedPluginDefinition::new(manifest, entry_point))
}

/// [`plugin_dir`] plus an index-relative uniqueness check.
///
/// Runs full [`plugin_dir`] validation first. On success, compares the
/// manifest's `(name, version)` against every entry in `index.plugins[]`; a
/// collision surfaces as [`ValidationFailure::Invalid`] carrying a single
/// [`ValidationError::NameVersionConflict`].
pub fn plugin_dir_with_index(
    dir: &Path,
    index: &Index,
) -> Result<ValidatedPluginDefinition, ValidationFailure> {
    let validated = plugin_dir(dir)?;

    let probe_entry =
        IndexEntry::from_manifest(validated.manifest.clone(), crate::hash::zero_hash());
    if let Err(err) = index.check_entry_insert(&probe_entry) {
        use influxdb3_plugin_schemas::IndexInsertError;
        // Surface a conflict only when the (canonical-name, version) pair
        // already exists in the index. `CanonicalCollision` with a *different*
        // version is intentionally not flagged here; that stricter spelling
        // check runs at publish time in `mutate_index::add_entry`.
        let version_conflict = match &err {
            IndexInsertError::Duplicate { .. } => true,
            IndexInsertError::CanonicalCollision { existing, .. } => {
                existing.iter().any(|(_, v)| v == &probe_entry.version)
            }
            _ => false,
        };
        if version_conflict {
            let mut report = ValidationReport::new();
            report.push(ValidationError::NameVersionConflict {
                name: validated.manifest.plugin.name.as_str().to_owned(),
                version: validated.manifest.plugin.version.to_string(),
            });
            report.into_result()?;
            unreachable!("non-empty report always returns Err");
        }
    }

    Ok(validated)
}

/// Human-readable description of the first parse error in source order.
fn format_parse_error(root: tree_sitter::Node<'_>, source: &str) -> String {
    let Some(err_node) = find_first_error_or_missing(root) else {
        return "parse error (unknown location)".into();
    };
    let start = err_node.start_position();
    let snippet = source_snippet(source, &err_node);
    format!(
        "parse error at line {}, column {}: `{}`",
        start.row + 1,
        start.column + 1,
        snippet
    )
}

fn source_snippet(source: &str, node: &tree_sitter::Node<'_>) -> String {
    let range = node.byte_range();
    let end = range.end.min(range.start + 40);
    let slice = source.get(range.start..end).unwrap_or("");
    slice.replace('\n', "\\n")
}

/// Depth-first pre-order search for the earliest error/missing node.
/// Relies on tree-sitter's `children()` yielding in source order.
fn find_first_error_or_missing(root: tree_sitter::Node<'_>) -> Option<tree_sitter::Node<'_>> {
    if root.is_error() || root.is_missing() {
        return Some(root);
    }
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if let Some(found) = find_first_error_or_missing(child) {
            return Some(found);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use influxdb3_plugin_schemas::plugin_format::{
        EntryPoint, TOP_LEVEL_DEF_CONFORMANCE_CASES, TopLevelDefExpectation,
    };

    // -- extract_top_level_defs  F6-F15 -------------------------------------

    fn names(defs: &[TopLevelFunctionDef]) -> Vec<(String, bool)> {
        defs.iter().map(|d| (d.name.clone(), d.is_async)).collect()
    }

    #[test]
    fn f6_plain_def_captured_sync() {
        let defs = extract_top_level_defs("def foo(): pass").unwrap();
        assert_eq!(names(&defs), vec![("foo".into(), false)]);
    }

    #[test]
    fn f7_async_def_captured_async() {
        let defs = extract_top_level_defs("async def foo(): pass").unwrap();
        assert_eq!(names(&defs), vec![("foo".into(), true)]);
    }

    #[test]
    fn f8_decorated_def_captured() {
        let defs = extract_top_level_defs("@staticmethod\ndef foo(): pass").unwrap();
        assert_eq!(names(&defs), vec![("foo".into(), false)]);
    }

    #[test]
    fn f9_class_methods_not_captured() {
        let defs = extract_top_level_defs("class C:\n    def foo(self): pass").unwrap();
        assert!(defs.is_empty(), "got {defs:?}");
    }

    #[test]
    fn f10_nested_defs_not_captured() {
        let defs = extract_top_level_defs("def outer():\n    def inner(): pass").unwrap();
        assert_eq!(names(&defs), vec![("outer".into(), false)]);
    }

    #[test]
    fn f11_guarded_defs_not_top_level() {
        let defs = extract_top_level_defs("if True:\n    def foo(): pass").unwrap();
        assert!(defs.is_empty(), "got {defs:?}");
    }

    #[test]
    fn f12_reexport_and_assignment_not_captured() {
        assert!(
            extract_top_level_defs("from bar import foo")
                .unwrap()
                .is_empty()
        );
        assert!(extract_top_level_defs("foo = bar").unwrap().is_empty());
    }

    #[test]
    fn f13_redefinition_appears_per_occurrence_in_order() {
        let defs = extract_top_level_defs("def foo(): pass\nasync def foo(): pass").unwrap();
        assert_eq!(
            names(&defs),
            vec![("foo".into(), false), ("foo".into(), true)]
        );
    }

    #[test]
    fn f14_unparseable_source_is_parse_error() {
        let err = extract_top_level_defs("def foo(:").unwrap_err();
        assert!(err.message.contains("parse error"), "got {}", err.message);
    }

    #[test]
    fn f15_empty_source_is_empty() {
        assert!(extract_top_level_defs("").unwrap().is_empty());
    }

    #[test]
    fn def_inside_triple_quoted_string_is_not_a_function() {
        let src = "doc = \"\"\"\ndef process_writes():\n    pass\n\"\"\"\n";
        let defs = extract_top_level_defs(src).unwrap();
        assert!(defs.is_empty(), "got {defs:?}");
    }

    /// Regression guard: the reported parse-error position is the earliest in
    /// source order, not pop-order.
    #[test]
    fn first_parse_error_is_earliest_position() {
        let src = "\ndef first(:\n\nx = (1 + 2\n\nclass Bad[\n";
        let err = extract_top_level_defs(src).unwrap_err();
        assert!(
            err.message.contains("line 2"),
            "expected error on line 2 (earliest), got: {}",
            err.message
        );
    }

    // -- conformance corpus drift guard -------------------------------------

    #[test]
    fn sdk_extractor_satisfies_top_level_def_corpus() {
        for case in TOP_LEVEL_DEF_CONFORMANCE_CASES {
            let result = extract_top_level_defs(case.source);
            match (&case.expected, result) {
                (TopLevelDefExpectation::Defs(expected), Ok(got)) => {
                    let expected: Vec<(String, bool)> = expected
                        .iter()
                        .map(|e| (e.name.to_string(), e.is_async))
                        .collect();
                    assert_eq!(
                        names(&got),
                        expected,
                        "{}: extracted defs drifted",
                        case.label
                    );
                }
                (TopLevelDefExpectation::ParseError, Err(_)) => { /* pass */ }
                (TopLevelDefExpectation::Defs(_), Err(e)) => {
                    panic!(
                        "{}: expected defs, got parse error: {}",
                        case.label, e.message
                    )
                }
                (TopLevelDefExpectation::ParseError, Ok(defs)) => panic!(
                    "{}: expected parse error, got {} def(s)",
                    case.label,
                    defs.len()
                ),
            }
        }
    }

    // -- orchestration: lister, required-file, multi-error ------------------

    fn write(dir: &Path, name: &str, contents: &str) {
        std::fs::write(dir.join(name), contents).unwrap();
    }

    const MINIMAL_MANIFEST: &str = "manifest_schema_version = \"1.0\"\n\
         [plugin]\n\
         name = \"test\"\n\
         version = \"0.1.0\"\n\
         description = \"x\"\n\
         triggers = [\"process_writes\"]\n\
         [dependencies]\n\
         database_version = \">=3.0.0\"\n";

    /// Manifest is the gate: an empty dir reports only the missing manifest;
    /// entry-point detection does not run without a parsed manifest.
    #[test]
    fn empty_dir_reports_only_missing_manifest() {
        let td = tempfile::tempdir().unwrap();
        let err = plugin_dir(td.path()).expect_err("empty dir must fail");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("expected Invalid, got {err:?}")
        };
        assert_eq!(errs.len(), 1, "got {errs:?}");
        assert!(
            matches!(&errs[0], ValidationError::MissingRequiredFile { file } if file == "manifest.toml"),
            "got {:?}",
            errs[0]
        );
    }

    /// B4: a directory named `foo.py` is excluded; with no other entry point,
    /// classification yields `NoEntryPoint`.
    #[test]
    fn b4_directory_named_dot_py_excluded() {
        let td = tempfile::tempdir().unwrap();
        write(td.path(), "manifest.toml", MINIMAL_MANIFEST);
        std::fs::create_dir(td.path().join("foo.py")).unwrap();
        let err = plugin_dir(td.path()).expect_err("dir-named-.py must not count");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("expected Invalid, got {err:?}");
        };
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::NoEntryPoint))
        );
    }

    /// With manifest-gates-entry-point ordering, a malformed manifest is
    /// reported alone — entry-point detection cannot run without a valid
    /// manifest (the exclude list is unknown).
    #[test]
    fn malformed_manifest_reported_without_entry_point_detection() {
        let td = tempfile::tempdir().unwrap();
        write(td.path(), "a.py", "def process_writes(a,b,c): pass\n");
        write(td.path(), "b.py", "def process_writes(a,b,c): pass\n");
        write(
            td.path(),
            "manifest.toml",
            "manifest_schema_version = \"1.0\"\n\
             [plugin]\nname = \"test\"\nversion = \"0.1.0\"\ndescription = \"\"\ntriggers = [\"process_writes\"]\n\
             [dependencies]\ndatabase_version = \">=3.0.0\"\n",
        );
        let err = plugin_dir(td.path()).expect_err("malformed manifest");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("expected Invalid, got {err:?}")
        };
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::SchemaReported(_))),
            "expected SchemaReported among {errs:?}"
        );
        assert!(
            !errs
                .iter()
                .any(|e| matches!(e, ValidationError::AmbiguousEntryPoint { .. })),
            "entry-point detection must not run for a malformed manifest: {errs:?}"
        );
    }

    /// Excluding all .py files yields the normal no-entry-point result;
    /// selection does not special-case required files.
    #[test]
    fn excluding_all_python_yields_no_entry_point() {
        let td = tempfile::tempdir().unwrap();
        write(
            td.path(),
            "__init__.py",
            "def process_writes(a,b,c): pass\n",
        );
        write(
            td.path(),
            "manifest.toml",
            "manifest_schema_version = \"1.2\"\n\
             [plugin]\nname = \"t\"\nversion = \"0.1.0\"\ndescription = \"x\"\ntriggers = [\"process_writes\"]\nexclude = [\"*.py\"]\n\
             [dependencies]\ndatabase_version = \">=3.0.0\"\n",
        );
        let err = plugin_dir(td.path()).expect_err("all py excluded");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("got {err:?}")
        };
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::NoEntryPoint)),
            "got {errs:?}"
        );
    }

    /// Excluding `manifest.toml` removes it from the selected/packaged set, so
    /// the selected set is invalid: validation must report MissingRequiredFile.
    #[test]
    fn excluding_manifest_yields_missing_required_file() {
        let td = tempfile::tempdir().unwrap();
        write(
            td.path(),
            "__init__.py",
            "def process_writes(a,b,c): pass\n",
        );
        write(
            td.path(),
            "manifest.toml",
            "manifest_schema_version = \"1.2\"\n\
             [plugin]\nname = \"t\"\nversion = \"0.1.0\"\ndescription = \"x\"\ntriggers = [\"process_writes\"]\nexclude = [\"manifest.toml\"]\n\
             [dependencies]\ndatabase_version = \">=3.0.0\"\n",
        );
        let err = plugin_dir(td.path()).expect_err("excluding manifest.toml must fail validation");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("expected Invalid, got {err:?}")
        };
        assert!(
            errs.iter().any(|e| matches!(
                e, ValidationError::MissingRequiredFile { file } if file == "manifest.toml")),
            "expected MissingRequiredFile(manifest.toml) among {errs:?}"
        );
    }

    /// Nested .py files never count for entry-point classification.
    #[test]
    fn nested_python_does_not_classify_entry_point() {
        let td = tempfile::tempdir().unwrap();
        write(td.path(), "manifest.toml", MINIMAL_MANIFEST);
        std::fs::create_dir(td.path().join("pkg")).unwrap();
        write(&td.path().join("pkg"), "helper.py", "def helper(): pass\n");
        let err = plugin_dir(td.path()).expect_err("nested-only must fail");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("got {err:?}")
        };
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::NoEntryPoint)),
            "got {errs:?}"
        );
    }

    /// An invalid exclude pattern surfaces as ValidationFailure::InvalidExcludePattern.
    /// NOTE: `ignore` 0.4.25 accepts `a/**b` and `[`; use an inverted character
    /// class `[z-a]`, which it reliably rejects.
    #[test]
    fn invalid_exclude_pattern_surfaces_named() {
        let td = tempfile::tempdir().unwrap();
        write(
            td.path(),
            "__init__.py",
            "def process_writes(a,b,c): pass\n",
        );
        write(
            td.path(),
            "manifest.toml",
            "manifest_schema_version = \"1.2\"\n\
             [plugin]\nname = \"t\"\nversion = \"0.1.0\"\ndescription = \"x\"\ntriggers = [\"process_writes\"]\nexclude = [\"[z-a]\"]\n\
             [dependencies]\ndatabase_version = \">=3.0.0\"\n",
        );
        let err = plugin_dir(td.path()).expect_err("invalid pattern");
        match err {
            ValidationFailure::InvalidExcludePattern { pattern, .. } => {
                assert_eq!(pattern, "[z-a]")
            }
            other => panic!("expected InvalidExcludePattern, got {other:?}"),
        }
    }

    /// C3: an unreadable entry-point file after detection produces
    /// `NoEntryPoint`, not `Io`. Unix-only (uses permission bits).
    #[cfg(unix)]
    #[test]
    fn c3_unreadable_entry_point_is_no_entry_point() {
        use std::os::unix::fs::PermissionsExt;
        let td = tempfile::tempdir().unwrap();
        write(td.path(), "manifest.toml", MINIMAL_MANIFEST);
        let init = td.path().join("__init__.py");
        std::fs::write(&init, "def process_writes(a,b,c): pass\n").unwrap();
        std::fs::set_permissions(&init, std::fs::Permissions::from_mode(0o000)).unwrap();
        let result = plugin_dir(td.path());
        // Restore perms so tempdir cleanup succeeds.
        std::fs::set_permissions(&init, std::fs::Permissions::from_mode(0o644)).unwrap();
        let err = result.expect_err("unreadable entry point must fail");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("expected Invalid (NoEntryPoint), got {err:?}");
        };
        assert!(
            errs.iter()
                .any(|e| matches!(e, ValidationError::NoEntryPoint)),
            "expected NoEntryPoint among {errs:?}"
        );
    }

    /// C2: an unreadable `manifest.toml` surfaces as `ValidationFailure::Io`.
    #[cfg(unix)]
    #[test]
    fn c2_unreadable_manifest_is_io() {
        use std::os::unix::fs::PermissionsExt;
        let td = tempfile::tempdir().unwrap();
        write(
            td.path(),
            "__init__.py",
            "def process_writes(a,b,c): pass\n",
        );
        let manifest = td.path().join("manifest.toml");
        std::fs::write(&manifest, MINIMAL_MANIFEST).unwrap();
        std::fs::set_permissions(&manifest, std::fs::Permissions::from_mode(0o000)).unwrap();
        let result = plugin_dir(td.path());
        std::fs::set_permissions(&manifest, std::fs::Permissions::from_mode(0o644)).unwrap();
        let err = result.expect_err("unreadable manifest must fail");
        assert!(
            matches!(err, ValidationFailure::Io { .. }),
            "expected Io, got {err:?}"
        );
    }

    // -- success payload ----------------------------------------------------

    #[test]
    fn success_multi_file_yields_entry_point_multi() {
        let td = tempfile::tempdir().unwrap();
        write(td.path(), "manifest.toml", MINIMAL_MANIFEST);
        write(
            td.path(),
            "__init__.py",
            "def process_writes(a,b,c): pass\n",
        );
        write(td.path(), "helper.py", "def helper(): pass\n");
        let validated = plugin_dir(td.path()).expect("valid multi-file plugin");
        assert_eq!(validated.entry_point, EntryPoint::Multi);
        assert_eq!(validated.manifest.plugin.name.as_str(), "test");
    }

    #[test]
    fn success_single_file_yields_entry_point_single() {
        let td = tempfile::tempdir().unwrap();
        write(td.path(), "manifest.toml", MINIMAL_MANIFEST);
        write(
            td.path(),
            "my_plugin.py",
            "def process_writes(a,b,c): pass\n",
        );
        let validated = plugin_dir(td.path()).expect("valid single-file plugin");
        assert_eq!(
            validated.entry_point,
            EntryPoint::Single {
                file_name: "my_plugin.py".into()
            }
        );
    }

    // -- plugin_dir_with_index uniqueness (G) -------------------------------

    fn build_index_with_one_entry(name: &str, version: &str) -> Index {
        let json = format!(
            r#"{{
                "index_schema_version": "2.0",
                "artifacts_url": "https://x.example/a",
                "plugins": [{{
                    "name": "{name}",
                    "version": "{version}",
                    "published_at": "2026-04-29T18:45:12Z",
                    "description": "seed",
                    "triggers": ["process_writes"],
                    "dependencies": {{ "database_version": ">=3.0.0", "python": [] }},
                    "hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
                }}]
            }}"#
        );
        Index::parse_json(&json).expect("fixture parses")
    }

    fn write_plugin_with_name(dir: &Path, name: &str, version: &str) {
        std::fs::create_dir_all(dir).unwrap();
        let manifest = format!(
            "manifest_schema_version = \"1.0\"\n\
             [plugin]\nname = \"{name}\"\nversion = \"{version}\"\ndescription = \"x\"\ntriggers = [\"process_writes\"]\n\
             [dependencies]\ndatabase_version = \">=3.0.0\"\n"
        );
        std::fs::write(dir.join("manifest.toml"), manifest).unwrap();
        std::fs::write(
            dir.join("__init__.py"),
            "def process_writes(a, b, c):\n    pass\n",
        )
        .unwrap();
    }

    fn assert_canonical_collision(manifest_name: &str, index_name: &str) {
        let td = tempfile::tempdir().unwrap();
        write_plugin_with_name(td.path(), manifest_name, "0.1.0");
        let index = build_index_with_one_entry(index_name, "0.1.0");

        let err =
            plugin_dir_with_index(td.path(), &index).expect_err("canonical collision must fail");
        let ValidationFailure::Invalid(errs) = err else {
            panic!("expected Invalid, got {err:?}");
        };
        assert_eq!(errs.len(), 1);
        let ValidationError::NameVersionConflict { name, version } = &errs[0] else {
            panic!("expected NameVersionConflict, got {:?}", errs[0]);
        };
        assert_eq!(name, manifest_name, "diagnostic pins the manifest spelling");
        assert_eq!(version, "0.1.0");
    }

    #[test]
    fn plugin_dir_with_index_collides_on_hyphen_underscore() {
        assert_canonical_collision("foo-bar", "foo_bar");
    }

    #[test]
    fn plugin_dir_with_index_collides_on_case() {
        assert_canonical_collision("Foo", "foo");
    }

    #[test]
    fn plugin_dir_with_index_collides_on_mixed_canonical() {
        assert_canonical_collision("Foo-Bar_Baz", "foo_bar_baz");
    }

    #[test]
    fn plugin_dir_with_index_no_collision_when_canonical_differs() {
        let td = tempfile::tempdir().unwrap();
        write_plugin_with_name(td.path(), "foo", "0.1.0");
        let index = build_index_with_one_entry("bar", "0.1.0");
        let validated = plugin_dir_with_index(td.path(), &index).expect("no collision");
        assert_eq!(validated.manifest.plugin.name.as_str(), "foo");
    }

    #[test]
    fn plugin_dir_with_index_no_collision_when_version_differs() {
        let td = tempfile::tempdir().unwrap();
        write_plugin_with_name(td.path(), "foo-bar", "0.2.0");
        let index = build_index_with_one_entry("foo_bar", "0.1.0");
        plugin_dir_with_index(td.path(), &index).expect("different versions, no collision");
    }
}