influxdb3-plugin-cli 0.5.0

InfluxDB 3 author-side CLI for templating, validating, and packaging 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
//! Integration tests for `influxdb3-plugin validate`.
//!
//! Covers the envelope contract: success emits `{"status":"ok","result":{}}`,
//! failure emits `{"status":"error","error":{"code":"validate::failed",...,"diagnostics":[...]}}`.
//! The exit-code mapping: 0 on success, 1 on failure.
//!
//! Fixtures are synthesized inline into per-test `tempfile::TempDir`s so
//! the suite is self-contained.
//!
//! See `version_smoke.rs` for the rationale behind the crate-root allow.

#![allow(unused_crate_dependencies)]

use std::path::Path;

mod common;
use common::{
    SEEDED_INDEX, VALID_INIT, VALID_MANIFEST, assert_absolute_json_path, cli_cmd,
    write_valid_plugin,
};

fn spawn_validate<P: AsRef<Path>>(target: P, extra: &[&str]) -> assert_cmd::assert::Assert {
    let mut cmd = cli_cmd();
    cmd.arg("validate");
    for a in extra {
        cmd.arg(a);
    }
    cmd.arg(target.as_ref());
    cmd.assert()
}

#[test]
fn validate_happy_path_emits_empty_diagnostics_array() {
    let td = tempfile::tempdir().unwrap();
    let dir = td.path().join("p");
    write_valid_plugin(&dir);

    let assert = spawn_validate(&dir, &["--output", "json"]).success();

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value =
        serde_json::from_str(&stdout).expect("validator stdout is JSON");
    assert_eq!(
        payload,
        serde_json::json!({ "status": "ok", "result": {} }),
        "happy path must emit envelope ok with empty result"
    );
    insta::assert_json_snapshot!("validate_happy_path_json", payload);
}

/// Empty plugin directory: `manifest.toml` is the gate, so only the missing
/// manifest is reported (entry-point detection does not run without it).
#[test]
fn validate_empty_plugin_dir_reports_missing_manifest_only() {
    let td = tempfile::tempdir().unwrap();
    let dir = td.path().join("empty");
    std::fs::create_dir_all(&dir).unwrap();

    let assert = spawn_validate(&dir, &["--output", "json"])
        .failure()
        .code(1);

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"]
        .as_array()
        .expect("diagnostics");
    assert_eq!(
        diags.len(),
        1,
        "expected only the missing manifest, got {payload}"
    );
    assert_eq!(diags[0]["code"], "validate::missing_required_file");
    assert_eq!(diags[0]["field"], "manifest.toml");
}

/// Validator idiom: failure path emits a single JSON envelope on STDOUT
/// (not stderr), and exits 1.
#[test]
fn validate_failure_emits_diagnostics_on_stdout_and_exits_one() {
    let td = tempfile::tempdir().unwrap();
    let dir = td.path().join("p");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("manifest.toml"), VALID_MANIFEST).unwrap();
    // No .py files — should surface NoEntryPoint.

    let assert = spawn_validate(&dir, &["--output", "json"])
        .failure()
        .code(1);

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value =
        serde_json::from_str(&stdout).expect("validator stdout is JSON even on failure");
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"]
        .as_array()
        .expect("diagnostics array");
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::no_entry_point");
    insta::assert_json_snapshot!("validate_missing_init_json", payload);
}

#[test]
fn validate_collects_multiple_diagnostics_in_one_pass() {
    let td = tempfile::tempdir().unwrap();
    let dir = td.path().join("p");
    std::fs::create_dir_all(&dir).unwrap();
    // Manifest with 3 distinct field-level defects: bad name, bad
    // version, bad URL scheme.
    let bad_manifest = r#"manifest_schema_version = "1.0"

[plugin]
name = "1bad"
version = "1.2"
description = "x"
triggers = ["process_writes"]
homepage = "ftp://bad"

[dependencies]
database_version = ">=3.0.0"
"#;
    std::fs::write(dir.join("manifest.toml"), bad_manifest).unwrap();
    std::fs::write(dir.join("__init__.py"), VALID_INIT).unwrap();

    let assert = spawn_validate(&dir, &["--output", "json"])
        .failure()
        .code(1);

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"].as_array().unwrap();
    assert_eq!(
        diags.len(),
        3,
        "expected 3 diagnostics, got {}: {payload}",
        diags.len()
    );
    let codes: Vec<&str> = diags.iter().map(|d| d["code"].as_str().unwrap()).collect();
    assert!(
        codes.iter().all(|c| *c == "validate::schema_reported"),
        "all defects should surface as validate::schema_reported, got {codes:?}"
    );
    let fields: Vec<&str> = diags.iter().map(|d| d["field"].as_str().unwrap()).collect();
    assert!(
        fields.contains(&"plugin.name"),
        "missing plugin.name: {fields:?}"
    );
    assert!(
        fields.contains(&"plugin.version"),
        "missing plugin.version: {fields:?}"
    );
    assert!(
        fields.contains(&"plugin.homepage"),
        "missing plugin.homepage: {fields:?}"
    );
    insta::assert_json_snapshot!("validate_multi_defect_json", payload);
}

#[test]
fn validate_async_trigger_diagnostic_points_at_init() {
    let td = tempfile::tempdir().unwrap();
    let dir = td.path().join("p");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("manifest.toml"), VALID_MANIFEST).unwrap();
    std::fs::write(
        dir.join("__init__.py"),
        "async def process_writes(a, b, c):\n    pass\n",
    )
    .unwrap();

    let assert = spawn_validate(&dir, &["--output", "json"])
        .failure()
        .code(1);
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"].as_array().unwrap();
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::async_trigger_fn");
    assert_eq!(diags[0]["field"], "__init__.py");
    insta::assert_json_snapshot!("validate_async_trigger_json", payload);
}

/// `validate --index <path>` runs the same checks plus a uniqueness
/// check against the supplied index. A `(name, version)` collision
/// surfaces as a `NameVersionConflict` diagnostic, NOT a runtime error
/// — same diagnostics array as other validation failures.
#[test]
fn validate_with_index_surfaces_uniqueness_collision() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    write_valid_plugin(&plugin_dir);

    let index = serde_json::json!({
        "index_schema_version": "2.0",
        "artifacts_url": "https://plugins.example.com/artifacts",
        "plugins": [{
            "name": "downsampler",
            "version": "1.2.0",
            "published_at": "2026-04-29T18:45:12Z",
            "description": "preexisting",
            "triggers": ["process_writes"],
            "dependencies": { "database_version": ">=3.0.0", "python": [] },
            "hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
        }]
    });
    let index_path = td.path().join("index.json");
    std::fs::write(&index_path, serde_json::to_string_pretty(&index).unwrap()).unwrap();

    let assert = spawn_validate(
        &plugin_dir,
        &["--output", "json", "--index", index_path.to_str().unwrap()],
    )
    .failure()
    .code(1);

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"].as_array().unwrap();
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::name_version_conflict");
    assert_eq!(diags[0]["field"], "downsampler@1.2.0");
    insta::assert_json_snapshot!("validate_name_version_conflict_json", payload);
}

/// Without `--index`, uniqueness is not checked even if a collision
/// would exist on disk.
#[test]
fn validate_without_index_flag_passes() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    write_valid_plugin(&plugin_dir);

    spawn_validate(&plugin_dir, &["--output", "json"]).success();
}

/// Proves `validate` does NOT auto-discover any index file from conventional
/// paths. We plant an index at the plugin-dir's parent that WOULD collide on
/// `(name, version)` if read; validation without `--index` must still succeed
/// because no implicit discovery occurs.
#[test]
fn validate_does_not_auto_discover_adjacent_index() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    write_valid_plugin(&plugin_dir);

    // SEEDED_INDEX carries a `(downsampler, 1.2.0)` entry that WOULD collide
    // with the plugin's (name, version) if validate auto-discovered it.
    std::fs::write(td.path().join("index.json"), SEEDED_INDEX).unwrap();
    std::fs::write(plugin_dir.join("index.json"), SEEDED_INDEX).unwrap();

    // Run validate without `--index`. Must succeed — no auto-discovery means
    // the planted indexes are invisible.
    spawn_validate(&plugin_dir, &["--output", "json"]).success();
}

/// `validate --index` must compare canonical name forms (lowercase,
/// hyphens replaced with underscores). `foo-bar` and `foo_bar` collide.
#[test]
fn validate_with_index_detects_hyphen_underscore_collision() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    std::fs::create_dir_all(&plugin_dir).unwrap();
    let manifest = r#"manifest_schema_version = "1.0"

[plugin]
name = "foo-bar"
version = "0.1.0"
description = "x"
triggers = ["process_writes"]

[dependencies]
database_version = ">=3.0.0"
"#;
    std::fs::write(plugin_dir.join("manifest.toml"), manifest).unwrap();
    std::fs::write(plugin_dir.join("__init__.py"), VALID_INIT).unwrap();
    let index = serde_json::json!({
        "index_schema_version": "2.0",
        "artifacts_url": "https://x.example/a",
        "plugins": [{
            "name": "foo_bar",
            "version": "0.1.0",
            "published_at": "2026-04-29T18:45:12Z",
            "description": "seed",
            "triggers": ["process_writes"],
            "dependencies": { "database_version": ">=3.0.0", "python": [] },
            "hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
        }]
    });
    let index_path = td.path().join("index.json");
    std::fs::write(&index_path, serde_json::to_string_pretty(&index).unwrap()).unwrap();

    let assert = spawn_validate(
        &plugin_dir,
        &["--output", "json", "--index", index_path.to_str().unwrap()],
    )
    .failure()
    .code(1);
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"].as_array().unwrap();
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::name_version_conflict");
    let field = diags[0]["field"].as_str().unwrap();
    assert!(
        field.ends_with("@0.1.0"),
        "field should pin version: {field}"
    );
}

/// Sister case: case-only collision. `Foo` and `foo` share canonical form.
#[test]
fn validate_with_index_detects_case_collision() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    std::fs::create_dir_all(&plugin_dir).unwrap();
    let manifest = r#"manifest_schema_version = "1.0"

[plugin]
name = "Foo"
version = "0.1.0"
description = "x"
triggers = ["process_writes"]

[dependencies]
database_version = ">=3.0.0"
"#;
    std::fs::write(plugin_dir.join("manifest.toml"), manifest).unwrap();
    std::fs::write(plugin_dir.join("__init__.py"), VALID_INIT).unwrap();
    let index = serde_json::json!({
        "index_schema_version": "2.0",
        "artifacts_url": "https://x.example/a",
        "plugins": [{
            "name": "foo",
            "version": "0.1.0",
            "published_at": "2026-04-29T18:45:12Z",
            "description": "seed",
            "triggers": ["process_writes"],
            "dependencies": { "database_version": ">=3.0.0", "python": [] },
            "hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
        }]
    });
    let index_path = td.path().join("index.json");
    std::fs::write(&index_path, serde_json::to_string_pretty(&index).unwrap()).unwrap();

    let assert = spawn_validate(
        &plugin_dir,
        &["--output", "json", "--index", index_path.to_str().unwrap()],
    )
    .failure()
    .code(1);
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"].as_array().unwrap();
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::name_version_conflict");
}

/// Multiline `plugin.description` must be rejected (one-line rule),
/// surfacing as a `SchemaReported` diagnostic at field `plugin.description`.
#[test]
fn validate_rejects_multiline_description() {
    let td = tempfile::tempdir().unwrap();
    let dir = td.path().join("p");
    std::fs::create_dir_all(&dir).unwrap();
    let manifest = r#"manifest_schema_version = "1.0"

[plugin]
name = "downsampler"
version = "1.2.0"
description = """
top
bottom
"""
triggers = ["process_writes"]

[dependencies]
database_version = ">=3.0.0"
"#;
    std::fs::write(dir.join("manifest.toml"), manifest).unwrap();
    std::fs::write(dir.join("__init__.py"), VALID_INIT).unwrap();

    let assert = spawn_validate(&dir, &["--output", "json"])
        .failure()
        .code(1);
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"].as_array().expect("array");
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::schema_reported");
    assert_eq!(diags[0]["field"], "plugin.description");
}

/// Validator JSON-mode contract: a malformed `--index` file must
/// surface as a JSON envelope on stdout.
#[test]
fn validate_with_malformed_index_emits_json_diagnostic() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    write_valid_plugin(&plugin_dir);
    let index_path = td.path().join("bad.json");
    std::fs::write(&index_path, "not valid json {{").unwrap();

    let assert = spawn_validate(
        &plugin_dir,
        &["--output", "json", "--index", index_path.to_str().unwrap()],
    )
    .failure()
    .code(1);

    let out = assert.get_output();
    assert!(
        out.stderr.is_empty(),
        "stderr must be empty in JSON mode, got: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let payload: serde_json::Value =
        serde_json::from_str(&stdout).expect("stdout must be one JSON envelope on parse failure");
    assert_eq!(payload["status"], "error");
    // Index parse failures map to validate::failed with diagnostics.
    let error = &payload["error"];
    let code = error["code"].as_str().expect("error should have a code");
    assert_eq!(code, "validate::failed");
}

/// Index path that does not exist surfaces as a single
/// `IndexReadFailed` diagnostic on stdout in JSON mode.
#[test]
fn validate_with_unreadable_index_emits_json_diagnostic() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    write_valid_plugin(&plugin_dir);
    let missing = td.path().join("nope.json");

    let assert = spawn_validate(
        &plugin_dir,
        &["--output", "json", "--index", missing.to_str().unwrap()],
    )
    .failure()
    .code(1);

    let out = assert.get_output();
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"].as_array().unwrap();
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::index_read_failed");
    assert_eq!(diags[0]["field"], missing.display().to_string());
}

#[test]
fn validate_json_error_absolutizes_relative_index_path() {
    let td = tempfile::tempdir().unwrap();
    let cwd = std::fs::canonicalize(td.path()).unwrap();
    write_valid_plugin(&cwd.join("p"));

    let mut cmd = cli_cmd();
    let assert = cmd
        .current_dir(&cwd)
        .arg("validate")
        .arg("p")
        .arg("--index")
        .arg("./missing.json")
        .arg("--output")
        .arg("json")
        .assert()
        .failure()
        .code(1);
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout must be JSON: {e}\n{stdout}"));
    let diag = &payload["error"]["diagnostics"][0];
    assert_eq!(diag["code"], "validate::index_read_failed");
    let field = diag["field"].as_str().expect("diagnostic field missing");
    let path = diag["details"]["path"]
        .as_str()
        .expect("diagnostic details.path missing");
    assert_absolute_json_path(field, "diagnostic field");
    assert_absolute_json_path(path, "diagnostic details.path");
}

// ---------------------------------------------------------------------------
// Single-file plugin tests (fixtures from influxdb3-plugin-sdk/tests/fixtures/)
// ---------------------------------------------------------------------------

/// Returns the path to the SDK crate's test fixtures directory.
fn sdk_fixtures() -> std::path::PathBuf {
    std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../influxdb3-plugin-sdk/tests/fixtures")
}

#[test]
fn validate_valid_single_file_plugin_json() {
    let fixture = sdk_fixtures().join("valid_single_file_plugin");
    let assert = spawn_validate(&fixture, &["--output", "json"]).success();

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value =
        serde_json::from_str(&stdout).expect("validator stdout is JSON");
    assert_eq!(
        payload,
        serde_json::json!({ "status": "ok", "result": {} }),
        "valid single-file plugin must pass validation"
    );
    insta::assert_json_snapshot!("validate_valid_single_file_plugin_json", payload);
}

#[test]
fn validate_no_entry_point_json() {
    let fixture = sdk_fixtures().join("invalid_plugins/no_entry_point");
    let assert = spawn_validate(&fixture, &["--output", "json"])
        .failure()
        .code(1);

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"]
        .as_array()
        .expect("diagnostics array");
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::no_entry_point");
    insta::assert_json_snapshot!("validate_no_entry_point_json", payload);
}

#[test]
fn validate_ambiguous_entry_point_json() {
    let fixture = sdk_fixtures().join("invalid_plugins/ambiguous_entry_point");
    let assert = spawn_validate(&fixture, &["--output", "json"])
        .failure()
        .code(1);

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"]
        .as_array()
        .expect("diagnostics array");
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::ambiguous_entry_point");
    let details = diags[0]["details"].as_object().expect("details object");
    let files = details["files"].as_array().expect("files array");
    assert!(
        files.len() >= 2,
        "ambiguous entry point must list multiple files, got {files:?}"
    );
    insta::assert_json_snapshot!("validate_ambiguous_entry_point_json", payload);
}

#[test]
fn validate_single_file_missing_trigger_json() {
    let fixture = sdk_fixtures().join("invalid_plugins/single_file_missing_trigger");
    let assert = spawn_validate(&fixture, &["--output", "json"])
        .failure()
        .code(1);

    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let diags = payload["error"]["diagnostics"]
        .as_array()
        .expect("diagnostics array");
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0]["code"], "validate::trigger_not_implemented");
    assert_eq!(
        diags[0]["field"], "my_plugin.py",
        "field must name the single-file entry point"
    );
    insta::assert_json_snapshot!("validate_single_file_missing_trigger_json", payload);
}

/// An invalid glob pattern in `manifest.toml`'s `exclude` list surfaces as a
/// top-level `validate::invalid_exclude_pattern` error (NOT inside a
/// `diagnostics[]` array), because the CLI maps it via `json_error_from_sdk`
/// directly to a `CliError::runtime(je)`.
#[test]
fn validate_invalid_exclude_pattern_reports_named_error() {
    let td = tempfile::tempdir().unwrap();
    let dir = td.path().join("p");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("manifest.toml"),
        "manifest_schema_version = \"1.2\"\n[plugin]\nname=\"p\"\nversion=\"0.1.0\"\n\
         description=\"x\"\ntriggers=[\"process_writes\"]\nexclude=[\"[z-a]\"]\n\
         [dependencies]\ndatabase_version=\">=3.0.0\"\n",
    )
    .unwrap();
    std::fs::write(dir.join("__init__.py"), "def process_writes(a,b,c): pass\n").unwrap();

    let assert = spawn_validate(&dir, &["--output", "json"]).failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(
        payload["error"]["code"],
        "validate::invalid_exclude_pattern"
    );
    assert_eq!(payload["error"]["field"], "[z-a]");
}

/// Multi-error case: an index with two distinct schema defects (bad URL
/// scheme + non-SemVer version) surfaces via `json_error_from_sdk` for
/// `SdkError::Schema`.
#[test]
fn validate_with_index_schema_errors_emits_all_diagnostics() {
    let td = tempfile::tempdir().unwrap();
    let plugin_dir = td.path().join("p");
    write_valid_plugin(&plugin_dir);
    let bad_index = serde_json::json!({
        "index_schema_version": "2.0",
        "artifacts_url": "s3://nope",
        "plugins": [{
            "name": "downsampler",
            "version": "v1",
            "published_at": "2026-04-29T18:45:12Z",
            "description": "seed",
            "triggers": ["process_writes"],
            "dependencies": { "database_version": ">=3.0.0", "python": [] },
            "hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
        }]
    });
    let index_path = td.path().join("bad-schema.json");
    std::fs::write(
        &index_path,
        serde_json::to_string_pretty(&bad_index).unwrap(),
    )
    .unwrap();

    let assert = spawn_validate(
        &plugin_dir,
        &["--output", "json", "--index", index_path.to_str().unwrap()],
    )
    .failure()
    .code(1);
    let out = assert.get_output();
    assert!(
        out.stderr.is_empty(),
        "stderr must be empty in JSON mode, got: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let payload: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(payload["status"], "error");
    let error = &payload["error"];
    // Schema errors from index parse map to validate::failed with diagnostics.
    let code = error["code"].as_str().expect("error should have a code");
    assert_eq!(code, "validate::failed");
}