astrid-capsule 0.2.0

Core runtime management for User-Space Capsules in Astrid OS
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
//! Capsule manifest discovery from standard locations.
//!
//! Scans well-known directories for `Capsule.toml` files, providing
//! the entry point for the Manifest-First architecture.

use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};

use tracing::{debug, info, warn};

use crate::error::{CapsuleError, CapsuleResult};
use crate::manifest::{CapsuleManifest, TopicDirection};

/// Standard capsule manifest file name.
pub(crate) const MANIFEST_FILE_NAME: &str = "Capsule.toml";

/// Discover capsule manifests from standard locations.
///
/// Scans the following directories for `Capsule.toml` files:
/// 1. `.astrid/capsules/` (workspace-level, relative to CWD)
/// 2. Any additional paths provided in `extra_paths`
///
/// Each subdirectory containing a `Capsule.toml` is treated as a capsule.
/// Errors in individual manifests are logged as warnings but do not
/// prevent other manifests from loading.
///
/// Returns `(manifest, capsule_dir)` pairs where `capsule_dir` is the
/// directory containing the manifest.
pub fn discover_manifests(extra_paths: Option<&[PathBuf]>) -> Vec<(CapsuleManifest, PathBuf)> {
    let mut manifests = Vec::new();

    // Workspace-level capsules
    let local_capsules_dir = PathBuf::from(".astrid/capsules");
    if local_capsules_dir.exists() {
        info!(path = %local_capsules_dir.display(), "Discovering capsules from local directory");
        match load_manifests_from_dir(&local_capsules_dir) {
            Ok(found) => manifests.extend(found),
            Err(e) => warn!(error = %e, "Failed to load capsules from local directory"),
        }
    }

    // Extra paths (user-level, custom, etc.)
    if let Some(paths) = extra_paths {
        for path in paths {
            if path.exists() {
                info!(path = %path.display(), "Discovering capsules from custom path");
                match load_manifests_from_dir(path) {
                    Ok(found) => manifests.extend(found),
                    Err(e) => warn!(error = %e, "Failed to load capsules from custom path"),
                }
            }
        }
    }

    info!(count = manifests.len(), "Discovered capsule manifests");
    manifests
}

/// Load all capsule manifests from a directory.
///
/// Looks for subdirectories containing `Capsule.toml` files, as well as
/// `Capsule.toml` files directly in the directory.
pub(crate) fn load_manifests_from_dir(
    dir: &Path,
) -> CapsuleResult<Vec<(CapsuleManifest, PathBuf)>> {
    let mut manifests = Vec::new();

    let entries = std::fs::read_dir(dir).map_err(|e| CapsuleError::ManifestParseError {
        path: dir.to_path_buf(),
        message: e.to_string(),
    })?;

    for entry in entries {
        let entry = entry.map_err(|e| CapsuleError::ManifestParseError {
            path: dir.to_path_buf(),
            message: e.to_string(),
        })?;
        let path = entry.path();

        if path.is_dir() {
            // Look for Capsule.toml in subdirectory
            let manifest_path = path.join(MANIFEST_FILE_NAME);
            if manifest_path.exists() {
                match load_manifest(&manifest_path) {
                    Ok(manifest) => {
                        debug!(
                            path = %manifest_path.display(),
                            capsule_name = %manifest.package.name,
                            "Loaded capsule manifest"
                        );
                        manifests.push((manifest, path));
                    },
                    Err(e) => {
                        warn!(
                            path = %manifest_path.display(),
                            error = %e,
                            "Failed to load capsule manifest"
                        );
                    },
                }
            }
        } else if path.is_file()
            && path
                .file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n == MANIFEST_FILE_NAME)
        {
            let capsule_dir = path.parent().unwrap_or(dir).to_path_buf();
            match load_manifest(&path) {
                Ok(manifest) => {
                    debug!(
                        path = %path.display(),
                        capsule_name = %manifest.package.name,
                        "Loaded capsule manifest"
                    );
                    manifests.push((manifest, capsule_dir));
                },
                Err(e) => {
                    warn!(path = %path.display(), error = %e, "Failed to load capsule manifest");
                },
            }
        }
    }

    Ok(manifests)
}

/// Load a single capsule manifest from a TOML file.
pub fn load_manifest(path: &Path) -> CapsuleResult<CapsuleManifest> {
    let content = std::fs::read_to_string(path).map_err(|e| CapsuleError::ManifestParseError {
        path: path.to_path_buf(),
        message: e.to_string(),
    })?;

    let manifest: CapsuleManifest =
        toml::from_str(&content).map_err(|e| CapsuleError::ManifestParseError {
            path: path.to_path_buf(),
            message: e.to_string(),
        })?;

    // Enforce astrid-version (MSRV for Astrid, like rust-version in Cargo.toml).
    // If the capsule requires a newer runtime than we are, reject it.
    // CARGO_PKG_VERSION is a compile-time constant; parse is trivially cheap.
    if let Some(ref constraint) = manifest.package.astrid_version {
        let runtime = semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("valid semver");
        let req = semver::VersionReq::parse(constraint).map_err(|e| {
            CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!("invalid astrid-version '{constraint}' - {e}"),
            }
        })?;

        if !req.matches(&runtime) {
            return Err(CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!(
                    "capsule requires astrid-version {constraint}, \
                     but this runtime is {runtime}"
                ),
            });
        }
    }

    // Validate version is valid semver (same as Cargo.toml).
    if semver::Version::parse(&manifest.package.version).is_err() {
        return Err(CapsuleError::ManifestParseError {
            path: path.to_path_buf(),
            message: format!(
                "invalid version '{}' in [package] - must be valid semver (MAJOR.MINOR.PATCH)",
                manifest.package.version
            ),
        });
    }

    // Validate ipc_publish and interceptor patterns for empty segments.
    let ipc_patterns = manifest
        .capabilities
        .ipc_publish
        .iter()
        .map(|p| ("ipc_publish pattern", p.as_str()));
    let interceptor_patterns = manifest
        .interceptors
        .iter()
        .map(|i| ("interceptor event pattern", i.event.as_str()));

    for (kind, pattern) in ipc_patterns.chain(interceptor_patterns) {
        if !crate::dispatcher::has_valid_segments(pattern) {
            return Err(CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!(
                    "{kind} '{pattern}' contains empty segments \
                     (consecutive dots, leading/trailing dots, or is empty)"
                ),
            });
        }
    }

    // Validate dependency capability strings.
    let dep_caps = manifest
        .dependencies
        .provides
        .iter()
        .map(|c| ("provides", c.as_str()))
        .chain(
            manifest
                .dependencies
                .requires
                .iter()
                .map(|c| ("requires", c.as_str())),
        );

    for (kind, cap) in dep_caps {
        if cap.is_empty() {
            return Err(CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!("[dependencies].{kind} contains an empty capability string"),
            });
        }
        let Some((prefix, body)) = cap.split_once(':') else {
            return Err(CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!(
                    "[dependencies].{kind} '{cap}' must have a type prefix \
                     (e.g. topic:, tool:, llm:, uplink:)"
                ),
            });
        };
        const KNOWN_PREFIXES: &[&str] = &["topic", "tool", "llm", "uplink"];
        if !KNOWN_PREFIXES.contains(&prefix) {
            return Err(CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!(
                    "[dependencies].{kind} '{cap}' has unknown prefix '{prefix}:' \
                     (expected one of: topic:, tool:, llm:, uplink:)"
                ),
            });
        }
        if !crate::dispatcher::has_valid_segments(body) {
            return Err(CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!(
                    "[dependencies].{kind} '{cap}' body contains empty segments \
                     (consecutive dots, leading/trailing dots, or is empty)"
                ),
            });
        }
        // Wildcards are only valid in `requires` (pattern matching).
        // In `provides`, a capsule must declare concrete capabilities.
        if kind == "provides" && body.contains('*') {
            return Err(CapsuleError::ManifestParseError {
                path: path.to_path_buf(),
                message: format!(
                    "[dependencies].provides '{cap}' contains a wildcard - \
                     provides must be concrete capabilities, not patterns"
                ),
            });
        }
    }

    // Uplink capsules load in a partition before non-uplinks.
    // Declaring `requires` on an uplink would violate this ordering.
    if manifest.capabilities.uplink && !manifest.dependencies.requires.is_empty() {
        return Err(CapsuleError::ManifestParseError {
            path: path.to_path_buf(),
            message: "[dependencies].requires is not allowed on uplink capsules \
                      (uplinks load before non-uplinks and cannot depend on them)"
                .into(),
        });
    }

    // Validate [[topic]] declarations (structural only - no filesystem access).
    {
        let mut seen_topics: HashSet<(&str, TopicDirection)> = HashSet::new();
        for topic in &manifest.topics {
            // Topic name must have valid segments (no empty segments).
            if !crate::dispatcher::has_valid_segments(&topic.name) {
                return Err(CapsuleError::ManifestParseError {
                    path: path.to_path_buf(),
                    message: format!(
                        "[[topic]] name '{}' contains empty segments \
                         (consecutive dots, leading/trailing dots, or is empty)",
                        topic.name
                    ),
                });
            }

            // Topic names must contain only alphanumeric, hyphens, underscores, and dots.
            // This implicitly rejects wildcards (*) and other special characters.
            if !topic
                .name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
            {
                // Provide a specific message for wildcards since that's a common mistake.
                if topic.name.contains('*') {
                    return Err(CapsuleError::ManifestParseError {
                        path: path.to_path_buf(),
                        message: format!(
                            "[[topic]] name '{}' must be a concrete topic name, not a pattern \
                             (wildcards are not allowed in topic declarations)",
                            topic.name
                        ),
                    });
                }
                return Err(CapsuleError::ManifestParseError {
                    path: path.to_path_buf(),
                    message: format!(
                        "[[topic]] name '{}' contains invalid characters \
                         (only alphanumeric, hyphens, underscores, and dots are allowed)",
                        topic.name
                    ),
                });
            }

            // Schema path must not escape the capsule directory.
            if let Some(ref schema_path) = topic.schema {
                if schema_path.is_absolute() {
                    return Err(CapsuleError::ManifestParseError {
                        path: path.to_path_buf(),
                        message: format!(
                            "[[topic]] '{}' schema path must be relative, got absolute path '{}'",
                            topic.name,
                            schema_path.display()
                        ),
                    });
                }
                if schema_path
                    .components()
                    .any(|c| matches!(c, Component::ParentDir))
                {
                    return Err(CapsuleError::ManifestParseError {
                        path: path.to_path_buf(),
                        message: format!(
                            "[[topic]] '{}' schema path must not contain '..' components: '{}'",
                            topic.name,
                            schema_path.display()
                        ),
                    });
                }
            }

            // No duplicate (name, direction) pairs.
            if !seen_topics.insert((&topic.name, topic.direction)) {
                return Err(CapsuleError::ManifestParseError {
                    path: path.to_path_buf(),
                    message: format!(
                        "[[topic]] duplicate declaration: '{}' with direction '{}'",
                        topic.name, topic.direction
                    ),
                });
            }
        }
    }

    Ok(manifest)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    /// Write a TOML string to a temp file and call `load_manifest`.
    fn load_from_toml(toml: &str) -> CapsuleResult<crate::manifest::CapsuleManifest> {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("Capsule.toml");
        let mut f = std::fs::File::create(&path).unwrap();
        f.write_all(toml.as_bytes()).unwrap();
        load_manifest(&path)
    }

    const VALID_HEADER: &str = r#"
[package]
name = "test-capsule"
version = "0.1.0"
"#;

    #[test]
    fn load_manifest_accepts_valid_ipc_publish() {
        let toml = format!(
            "{VALID_HEADER}\n[capabilities]\nipc_publish = [\"registry.*\", \"llm.stream.anthropic\"]"
        );
        assert!(load_from_toml(&toml).is_ok());
    }

    #[test]
    fn load_manifest_rejects_empty_segment_in_ipc_publish() {
        for bad in &["a..b", ".a.b", "a.b.", "", ".", "a...b"] {
            let toml = format!("{VALID_HEADER}\n[capabilities]\nipc_publish = [\"{bad}\"]");
            let err = load_from_toml(&toml).unwrap_err();
            let msg = err.to_string();
            assert!(
                msg.contains("empty segments"),
                "expected 'empty segments' error for pattern '{bad}', got: {msg}"
            );
        }
    }

    #[test]
    fn load_manifest_rejects_empty_segment_in_interceptor_event() {
        for bad in &["a..b", ".event", "event.", "", ".", "a...b"] {
            let toml =
                format!("{VALID_HEADER}\n[[interceptor]]\nevent = \"{bad}\"\naction = \"handle\"");
            let err = load_from_toml(&toml).unwrap_err();
            let msg = err.to_string();
            assert!(
                msg.contains("empty segments"),
                "expected 'empty segments' error for event '{bad}', got: {msg}"
            );
        }
    }

    #[test]
    fn load_manifest_accepts_valid_interceptor_event() {
        let toml = format!(
            "{VALID_HEADER}\n[[interceptor]]\nevent = \"user.prompt\"\naction = \"handle\""
        );
        assert!(load_from_toml(&toml).is_ok());
    }

    #[test]
    fn load_manifest_accepts_valid_semver() {
        let toml = "[package]\nname = \"test\"\nversion = \"1.2.3\"\n";
        assert!(load_from_toml(toml).is_ok());
    }

    #[test]
    fn load_manifest_accepts_prerelease_semver() {
        let toml = "[package]\nname = \"test\"\nversion = \"1.0.0-alpha.1\"\n";
        assert!(load_from_toml(toml).is_ok());
    }

    #[test]
    fn load_manifest_rejects_incomplete_semver() {
        let toml = "[package]\nname = \"test\"\nversion = \"1.0\"\n";
        let err = load_from_toml(toml).unwrap_err();
        assert!(
            err.to_string().contains("invalid version"),
            "expected 'invalid version' error, got: {err}"
        );
    }

    #[test]
    fn load_manifest_rejects_non_semver_version() {
        let toml = "[package]\nname = \"test\"\nversion = \"latest\"\n";
        let err = load_from_toml(toml).unwrap_err();
        assert!(
            err.to_string().contains("invalid version"),
            "expected 'invalid version' error, got: {err}"
        );
    }

    #[test]
    fn load_manifest_parses_dependencies_provides_requires() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [dependencies]\n\
             provides = [\"topic:identity.response.ready\"]\n\
             requires = [\"topic:llm.stream.*\"]\n"
        );
        let m = load_from_toml(&toml).unwrap();
        assert_eq!(
            m.dependencies.provides,
            vec!["topic:identity.response.ready"]
        );
        assert_eq!(m.dependencies.requires, vec!["topic:llm.stream.*"]);
    }

    #[test]
    fn load_manifest_defaults_empty_dependencies() {
        let m = load_from_toml(VALID_HEADER).unwrap();
        assert!(m.dependencies.provides.is_empty());
        assert!(m.dependencies.requires.is_empty());
        assert!(m.dependencies.is_empty());
    }

    #[test]
    fn load_manifest_parses_dependencies_provides_only() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [dependencies]\n\
             provides = [\"topic:foo\", \"tool:bar\"]\n"
        );
        let m = load_from_toml(&toml).unwrap();
        assert_eq!(m.dependencies.provides, vec!["topic:foo", "tool:bar"]);
        assert!(m.dependencies.requires.is_empty());
    }

    #[test]
    fn load_manifest_rejects_empty_capability_in_requires() {
        let toml = format!("{VALID_HEADER}\n[dependencies]\nrequires = [\"\"]");
        let err = load_from_toml(&toml).unwrap_err();
        assert!(
            err.to_string().contains("empty capability string"),
            "expected 'empty capability string' error, got: {err}"
        );
    }

    #[test]
    fn load_manifest_rejects_missing_prefix_in_provides() {
        let toml = format!("{VALID_HEADER}\n[dependencies]\nprovides = [\"no_prefix\"]");
        let err = load_from_toml(&toml).unwrap_err();
        assert!(
            err.to_string().contains("must have a type prefix"),
            "expected 'must have a type prefix' error, got: {err}"
        );
    }

    #[test]
    fn load_manifest_rejects_unknown_prefix_in_requires() {
        let toml = format!("{VALID_HEADER}\n[dependencies]\nrequires = [\"service:foo\"]");
        let err = load_from_toml(&toml).unwrap_err();
        assert!(
            err.to_string().contains("unknown prefix"),
            "expected 'unknown prefix' error, got: {err}"
        );
    }

    #[test]
    fn load_manifest_rejects_empty_segments_in_dependency_body() {
        let toml = format!("{VALID_HEADER}\n[dependencies]\nprovides = [\"topic:a..b\"]");
        let err = load_from_toml(&toml).unwrap_err();
        assert!(
            err.to_string().contains("empty segments"),
            "expected 'empty segments' error, got: {err}"
        );
    }

    #[test]
    fn load_manifest_rejects_wildcard_in_provides() {
        let toml = format!("{VALID_HEADER}\n[dependencies]\nprovides = [\"topic:llm.stream.*\"]");
        let err = load_from_toml(&toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("wildcard"),
            "expected 'wildcard' error for provides with *, got: {msg}"
        );
    }

    #[test]
    fn load_manifest_allows_wildcard_in_requires() {
        let toml = format!("{VALID_HEADER}\n[dependencies]\nrequires = [\"topic:llm.stream.*\"]");
        assert!(
            load_from_toml(&toml).is_ok(),
            "wildcards should be allowed in requires"
        );
    }

    #[test]
    fn load_manifest_rejects_uplink_with_requires() {
        let toml = format!(
            "{VALID_HEADER}\n[capabilities]\nuplink = true\n\n[dependencies]\nrequires = [\"topic:foo\"]"
        );
        let err = load_from_toml(&toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not allowed on uplink"),
            "expected uplink+requires rejection, got: {msg}"
        );
    }

    #[test]
    fn load_manifest_allows_uplink_without_requires() {
        let toml = format!("{VALID_HEADER}\n[capabilities]\nuplink = true");
        assert!(
            load_from_toml(&toml).is_ok(),
            "uplink without requires should be valid"
        );
    }

    #[test]
    fn load_manifest_accepts_satisfied_astrid_version() {
        let toml = "[package]\nname = \"test\"\nversion = \"0.1.0\"\nastrid-version = \">=0.1.0\"";
        assert!(load_from_toml(toml).is_ok());
    }

    #[test]
    fn load_manifest_rejects_unsatisfied_astrid_version() {
        let toml = "[package]\nname = \"test\"\nversion = \"0.1.0\"\nastrid-version = \">=99.0.0\"";
        let err = load_from_toml(toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("astrid-version") && msg.contains("99.0.0"),
            "expected astrid-version rejection, got: {msg}"
        );
    }

    #[test]
    fn load_manifest_rejects_invalid_astrid_version() {
        let toml =
            "[package]\nname = \"test\"\nversion = \"0.1.0\"\nastrid-version = \"not-semver\"";
        let err = load_from_toml(toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("invalid astrid-version"),
            "expected parse error, got: {msg}"
        );
    }

    #[test]
    fn load_manifest_accepts_missing_astrid_version() {
        // No astrid-version field at all - should load fine.
        assert!(load_from_toml(VALID_HEADER).is_ok());
    }

    // -----------------------------------------------------------------------
    // [[topic]] validation tests
    // -----------------------------------------------------------------------

    #[test]
    fn topic_parses_valid_publish_and_subscribe() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"llm.v1.response.chunk\"\n\
             direction = \"publish\"\n\
             description = \"Streaming LLM response chunk\"\n\
             \n\
             [[topic]]\n\
             name = \"llm.v1.request.generate\"\n\
             direction = \"subscribe\"\n"
        );
        let manifest = load_from_toml(&toml).expect("valid topics");
        assert_eq!(manifest.topics.len(), 2);
        assert_eq!(manifest.topics[0].direction, TopicDirection::Publish);
        assert_eq!(manifest.topics[1].direction, TopicDirection::Subscribe);
    }

    #[test]
    fn topic_without_optional_fields() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"events.v1.notify\"\n\
             direction = \"publish\"\n"
        );
        let manifest = load_from_toml(&toml).expect("valid topic without optionals");
        assert_eq!(manifest.topics.len(), 1);
        assert!(manifest.topics[0].description.is_none());
        assert!(manifest.topics[0].schema.is_none());
    }

    #[test]
    fn topic_rejects_invalid_direction() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"foo.bar\"\n\
             direction = \"bidirectional\"\n"
        );
        let err = load_from_toml(&toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("unknown variant"),
            "expected serde enum error, got: {msg}"
        );
    }

    #[test]
    fn topic_rejects_empty_segment_name() {
        for bad in &["a..b", ".a.b", "a.b.", "", "."] {
            let toml = format!(
                "{VALID_HEADER}\n\
                 [[topic]]\n\
                 name = \"{bad}\"\n\
                 direction = \"publish\"\n"
            );
            let err = load_from_toml(&toml).unwrap_err();
            let msg = err.to_string();
            assert!(
                msg.contains("empty segments"),
                "expected 'empty segments' error for name '{bad}', got: {msg}"
            );
        }
    }

    #[test]
    fn topic_rejects_absolute_schema_path() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"foo.bar\"\n\
             direction = \"publish\"\n\
             schema = \"/etc/passwd\"\n"
        );
        let err = load_from_toml(&toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("must be relative"),
            "expected relative path error, got: {msg}"
        );
    }

    #[test]
    fn topic_rejects_parent_dir_in_schema_path() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"foo.bar\"\n\
             direction = \"publish\"\n\
             schema = \"../escape.json\"\n"
        );
        let err = load_from_toml(&toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("'..'"),
            "expected parent dir error, got: {msg}"
        );
    }

    #[test]
    fn topic_rejects_wildcard_segment_name() {
        for bad in &["llm.v1.*", "*.response", "a.*.b"] {
            let toml = format!(
                "{VALID_HEADER}\n\
                 [[topic]]\n\
                 name = \"{bad}\"\n\
                 direction = \"publish\"\n"
            );
            let err = load_from_toml(&toml).unwrap_err();
            let msg = err.to_string();
            assert!(
                msg.contains("wildcard"),
                "expected wildcard error for name '{bad}', got: {msg}"
            );
        }
    }

    #[test]
    fn topic_rejects_invalid_characters() {
        for bad in &["llm response", "foo@bar", "a/b/c", "topic!bang"] {
            let toml = format!(
                "{VALID_HEADER}\n\
                 [[topic]]\n\
                 name = \"{bad}\"\n\
                 direction = \"publish\"\n"
            );
            let err = load_from_toml(&toml).unwrap_err();
            let msg = err.to_string();
            assert!(
                msg.contains("invalid characters"),
                "expected invalid characters error for name '{bad}', got: {msg}"
            );
        }
    }

    #[test]
    fn topic_rejects_duplicate_name_direction_pair() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"foo.bar\"\n\
             direction = \"publish\"\n\
             \n\
             [[topic]]\n\
             name = \"foo.bar\"\n\
             direction = \"publish\"\n"
        );
        let err = load_from_toml(&toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("duplicate"),
            "expected duplicate error, got: {msg}"
        );
    }

    #[test]
    fn topic_allows_same_name_different_direction() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"echo.v1\"\n\
             direction = \"publish\"\n\
             \n\
             [[topic]]\n\
             name = \"echo.v1\"\n\
             direction = \"subscribe\"\n"
        );
        let manifest = load_from_toml(&toml).expect("same name different direction is valid");
        assert_eq!(manifest.topics.len(), 2);
    }

    #[test]
    fn topic_backwards_compat_no_topics_section() {
        // Existing manifests without [[topic]] must still parse.
        let manifest = load_from_toml(VALID_HEADER).expect("no topics section is fine");
        assert!(manifest.topics.is_empty());
    }

    #[test]
    fn topic_with_schema_path() {
        let toml = format!(
            "{VALID_HEADER}\n\
             [[topic]]\n\
             name = \"llm.v1.chunk\"\n\
             direction = \"publish\"\n\
             schema = \"schemas/chunk.json\"\n"
        );
        let manifest = load_from_toml(&toml).expect("schema path is valid");
        assert_eq!(
            manifest.topics[0].schema.as_deref(),
            Some(std::path::Path::new("schemas/chunk.json"))
        );
    }
}