agentics-domain 0.3.0

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

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use url::Url;

use super::names::MoltbookSubmoltName;

/// User-facing validation message for GitHub repository remotes.
pub const GITHUB_REPO_REMOTE_ERROR_MESSAGE: &str = "repo_url must be a GitHub HTTPS repository URL or git@github.com:{owner}/{repo}.git SSH remote";

/// User-facing validation message for GitHub pull request URLs.
pub const GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE: &str = "pr_url must be a GitHub HTTPS pull request URL like https://github.com/{owner}/{repo}/pull/{number}";

/// User-facing validation message for external data URLs.
pub const EXTERNAL_DATA_URL_ERROR_MESSAGE: &str = "external data url must be an HTTPS URL";

/// User-facing validation message for the platform Moltbook Submolt URL.
pub const MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE: &str =
    "moltbook submolt url must be https://www.moltbook.com/m/{submolt-name}";

/// User-facing validation message for Moltbook discussion post URLs.
pub const MOLTBOOK_POST_URL_ERROR_MESSAGE: &str =
    "moltbook post url must be https://www.moltbook.com/post/{post-id}";

/// Validation message for GitHub App redirect URLs.
pub const GITHUB_APP_REDIRECT_URL_ERROR_MESSAGE: &str =
    "GitHub sign-in redirect URL must be an absolute HTTP(S) URL without query or fragment";

/// Validation message for GitHub App authorization endpoint URLs.
pub const GITHUB_APP_AUTHORIZE_URL_ERROR_MESSAGE: &str =
    "GitHub sign-in authorize URL must be https://github.com/login/oauth/authorize";
pub const GITHUB_SIGN_IN_AUTHORIZATION_URL_ERROR_MESSAGE: &str =
    "GitHub sign-in authorization URL must be an HTTPS GitHub authorize URL without fragment";

/// Validation message for GitHub App token endpoint URLs.
pub const GITHUB_APP_TOKEN_URL_ERROR_MESSAGE: &str =
    "GitHub sign-in token URL must be https://github.com/login/oauth/access_token";

/// Validation message for the GitHub user API URL.
pub const GITHUB_API_USER_URL_ERROR_MESSAGE: &str =
    "github API user URL must be https://api.github.com/user";

/// Validation failure for URL-like Agentics contract fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UrlFieldError {
    message: &'static str,
}

impl UrlFieldError {
    const fn new(message: &'static str) -> Self {
        Self { message }
    }
}

impl fmt::Display for UrlFieldError {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message)
    }
}

impl std::error::Error for UrlFieldError {}

macro_rules! impl_string_url_serde {
    ($type_name:ident) => {
        impl Serialize for $type_name {
            /// Handles serialize for this module.
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                serializer.serialize_str(self.as_str())
            }
        }

        impl<'de> Deserialize<'de> for $type_name {
            /// Handles deserialize for this module.
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                let value = String::deserialize(deserializer)?;
                Self::from_str(&value).map_err(serde::de::Error::custom)
            }
        }
    };
}

macro_rules! impl_string_url_schema {
    ($type_name:ident, $schema_name:literal, $pattern:literal) => {
        impl JsonSchema for $type_name {
            /// Handles inline schema for this module.
            fn inline_schema() -> bool {
                true
            }

            /// Handles schema name for this module.
            fn schema_name() -> Cow<'static, str> {
                $schema_name.into()
            }

            /// Handles json schema for this module.
            fn json_schema(_: &mut SchemaGenerator) -> Schema {
                json_schema!({
                    "type": "string",
                    "format": "uri",
                    "pattern": $pattern
                })
            }
        }
    };
}

/// GitHub repository remote syntax accepted for challenge review record provenance.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GithubRepoRemote {
    /// HTTPS repository URL such as `https://github.com/agentics-reifying/agentics-challenges`.
    Https {
        /// Original validated HTTPS URL.
        url: Url,
        /// Canonical owner/repository key for uniqueness and authorization.
        key: GithubRepoKey,
    },
    /// SSH repository remote such as `git@github.com:agentics-reifying/agentics-challenges.git`.
    Ssh(GithubSshRepoRemote),
}

impl GithubRepoRemote {
    /// Parse and validate a GitHub repository remote.
    pub fn try_new(value: impl AsRef<str>) -> Result<Self, UrlFieldError> {
        value.as_ref().parse()
    }

    /// Borrow the canonical string representation.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Https { url, .. } => url.as_str(),
            Self::Ssh(remote) => remote.as_str(),
        }
    }

    /// Return the canonical GitHub owner/repository key.
    ///
    /// This key is not a URL and does not preserve the submitted remote syntax.
    /// It collapses accepted GitHub HTTPS and SSH remotes for the same
    /// repository into one `owner/repo` identity for duplicate detection and
    /// authorization checks.
    pub fn repository_key(&self) -> &GithubRepoKey {
        match self {
            Self::Https { key, .. } => key,
            Self::Ssh(remote) => remote.repository_key(),
        }
    }
}

impl fmt::Display for GithubRepoRemote {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for GithubRepoRemote {
    type Err = UrlFieldError;

    /// Handles from str for this module.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let value = value.trim();
        if value.starts_with("git@github.com:") {
            return Ok(Self::Ssh(GithubSshRepoRemote::try_new(value)?));
        }

        let url = parse_url(value, GITHUB_REPO_REMOTE_ERROR_MESSAGE)?;
        let key = github_https_repo_key(&url)?;
        Ok(Self::Https { url, key })
    }
}

impl Serialize for GithubRepoRemote {
    /// Handles serialize for this module.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for GithubRepoRemote {
    /// Handles deserialize for this module.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::from_str(&value).map_err(serde::de::Error::custom)
    }
}

impl JsonSchema for GithubRepoRemote {
    /// Handles inline schema for this module.
    fn inline_schema() -> bool {
        true
    }

    /// Handles schema name for this module.
    fn schema_name() -> Cow<'static, str> {
        "GithubRepoRemote".into()
    }

    /// Handles json schema for this module.
    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "type": "string",
            "pattern": r"^(https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\.git)?|git@github\.com:[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\.git)$"
        })
    }
}

/// Validated GitHub SSH repository remote.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GithubSshRepoRemote {
    value: String,
    key: GithubRepoKey,
}

impl GithubSshRepoRemote {
    /// Handles try new for this module.
    fn try_new(value: &str) -> Result<Self, UrlFieldError> {
        reject_whitespace_or_control(value, GITHUB_REPO_REMOTE_ERROR_MESSAGE)?;
        let Some(rest) = value.strip_prefix("git@github.com:") else {
            return Err(UrlFieldError::new(GITHUB_REPO_REMOTE_ERROR_MESSAGE));
        };
        let Some((owner, repo_with_suffix)) = rest.split_once('/') else {
            return Err(UrlFieldError::new(GITHUB_REPO_REMOTE_ERROR_MESSAGE));
        };
        if repo_with_suffix.contains('/') {
            return Err(UrlFieldError::new(GITHUB_REPO_REMOTE_ERROR_MESSAGE));
        }
        let Some(repo) = repo_with_suffix.strip_suffix(".git") else {
            return Err(UrlFieldError::new(GITHUB_REPO_REMOTE_ERROR_MESSAGE));
        };
        let key = GithubRepoKey::try_new(owner, repo)?;
        Ok(Self {
            value: format!("git@github.com:{owner}/{repo}.git"),
            key,
        })
    }

    /// Returns str in the representation required by callers.
    fn as_str(&self) -> &str {
        &self.value
    }

    /// Handles repository key for this module.
    fn repository_key(&self) -> &GithubRepoKey {
        &self.key
    }
}

/// Canonical GitHub repository identity used for duplicate detection.
///
/// The string is always lowercase `owner/repo`. Keep the original
/// `GithubRepoRemote` when provenance or display should preserve whether the
/// contributor submitted an HTTPS URL or SSH remote.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GithubRepoKey(String);

impl GithubRepoKey {
    /// Handles try new for this module.
    fn try_new(owner: &str, repo: &str) -> Result<Self, UrlFieldError> {
        validate_github_path_segment(owner, GITHUB_REPO_REMOTE_ERROR_MESSAGE)?;
        validate_github_path_segment(repo, GITHUB_REPO_REMOTE_ERROR_MESSAGE)?;
        Ok(Self(format!(
            "{}/{}",
            owner.to_ascii_lowercase(),
            repo.to_ascii_lowercase()
        )))
    }

    /// Borrow the canonical `owner/repo` key.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for GithubRepoKey {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// GitHub HTTPS pull request URL.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GithubPullRequestUrl(Url);

impl GithubPullRequestUrl {
    /// Parse and validate a GitHub pull request URL.
    pub fn try_new(value: impl AsRef<str>) -> Result<Self, UrlFieldError> {
        value.as_ref().parse()
    }

    /// Borrow the canonical string representation.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Return the canonical GitHub owner/repository key.
    pub fn repository_key(&self) -> Result<GithubRepoKey, UrlFieldError> {
        github_pull_request_parts(&self.0)
            .map(|(owner, repo, _number)| GithubRepoKey(format!("{owner}/{repo}")))
    }

    /// Return the canonical decimal pull request number.
    pub fn number(&self) -> Result<String, UrlFieldError> {
        github_pull_request_parts(&self.0).map(|(_owner, _repo, number)| number)
    }
}

impl fmt::Display for GithubPullRequestUrl {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for GithubPullRequestUrl {
    type Err = UrlFieldError;

    /// Handles from str for this module.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let url = parse_url(value.trim(), GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE)?;
        validate_github_https_pull_request_url(&url)?;
        Ok(Self(url))
    }
}

impl_string_url_serde!(GithubPullRequestUrl);
impl_string_url_schema!(
    GithubPullRequestUrl,
    "GithubPullRequestUrl",
    r"^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/pull/[0-9]+$"
);

/// External HTTPS URL referenced by challenge-owned setup metadata.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExternalDataUrl(Url);

impl ExternalDataUrl {
    /// Parse and validate an external data URL.
    pub fn try_new(value: impl AsRef<str>) -> Result<Self, UrlFieldError> {
        value.as_ref().parse()
    }

    /// Borrow the canonical string representation.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl fmt::Display for ExternalDataUrl {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for ExternalDataUrl {
    type Err = UrlFieldError;

    /// Handles from str for this module.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let url = parse_url(value.trim(), EXTERNAL_DATA_URL_ERROR_MESSAGE)?;
        validate_https_url(&url, EXTERNAL_DATA_URL_ERROR_MESSAGE)?;
        Ok(Self(url))
    }
}

impl_string_url_serde!(ExternalDataUrl);
impl_string_url_schema!(ExternalDataUrl, "ExternalDataUrl", r"^https://[^?#]+$");

/// Validated Moltbook Submolt URL for the global Agentics communication channel.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MoltbookSubmoltUrl(Url);

impl MoltbookSubmoltUrl {
    /// Parse and validate a Moltbook Submolt URL.
    pub fn try_new(value: impl AsRef<str>) -> Result<Self, UrlFieldError> {
        value.as_ref().parse()
    }

    /// Borrow the canonical string representation.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Return the Submolt name carried by this URL.
    pub fn submolt_name(&self) -> Result<MoltbookSubmoltName, UrlFieldError> {
        moltbook_submolt_name(&self.0)
    }
}

impl fmt::Display for MoltbookSubmoltUrl {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MoltbookSubmoltUrl {
    type Err = UrlFieldError;

    /// Handles from str for this module.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let url = parse_url(value.trim(), MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE)?;
        validate_moltbook_submolt_url(&url)?;
        Ok(Self(url))
    }
}

impl_string_url_serde!(MoltbookSubmoltUrl);
impl_string_url_schema!(
    MoltbookSubmoltUrl,
    "MoltbookSubmoltUrl",
    r"^https://www\.moltbook\.com/m/[a-z0-9](?:[a-z0-9]|-(?!-)){0,28}[a-z0-9]$"
);

/// Validated Moltbook post URL used as an operator-attached challenge discussion anchor.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MoltbookPostUrl(Url);

impl MoltbookPostUrl {
    /// Parse and validate a Moltbook post URL.
    pub fn try_new(value: impl AsRef<str>) -> Result<Self, UrlFieldError> {
        value.as_ref().parse()
    }

    /// Borrow the canonical string representation.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl fmt::Display for MoltbookPostUrl {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MoltbookPostUrl {
    type Err = UrlFieldError;

    /// Handles from str for this module.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let url = parse_url(value.trim(), MOLTBOOK_POST_URL_ERROR_MESSAGE)?;
        validate_moltbook_post_url(&url)?;
        Ok(Self(url))
    }
}

impl_string_url_serde!(MoltbookPostUrl);
impl_string_url_schema!(
    MoltbookPostUrl,
    "MoltbookPostUrl",
    r"^https://www\.moltbook\.com/post/[A-Za-z0-9_-]+$"
);

macro_rules! define_url_wrapper {
    ($type_name:ident, $schema_name:literal, $validator:ident, $message:ident) => {
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        pub struct $type_name(Url);

        impl $type_name {
            /// Parse and validate this configured URL.
            pub fn try_new(value: impl AsRef<str>) -> Result<Self, UrlFieldError> {
                value.as_ref().parse()
            }

            /// Borrow the canonical string representation.
            pub fn as_str(&self) -> &str {
                self.0.as_str()
            }

            /// Clone the underlying URL for query construction.
            pub fn to_url(&self) -> Url {
                self.0.clone()
            }
        }

        impl fmt::Display for $type_name {
            /// Handles fmt for this module.
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }

        impl FromStr for $type_name {
            type Err = UrlFieldError;

            /// Handles from str for this module.
            fn from_str(value: &str) -> Result<Self, Self::Err> {
                let url = parse_url(value.trim(), $message)?;
                $validator(&url)?;
                Ok(Self(url))
            }
        }

        impl_string_url_serde!($type_name);
        impl_string_url_schema!($type_name, $schema_name, r"^https?://[^?#]+$");
    };
}

define_url_wrapper!(
    GithubAppRedirectUrl,
    "GithubAppRedirectUrl",
    validate_github_app_redirect_url,
    GITHUB_APP_REDIRECT_URL_ERROR_MESSAGE
);
define_url_wrapper!(
    GithubAppAuthorizeUrl,
    "GithubAppAuthorizeUrl",
    validate_github_app_authorize_url,
    GITHUB_APP_AUTHORIZE_URL_ERROR_MESSAGE
);
define_url_wrapper!(
    GithubAppTokenUrl,
    "GithubAppTokenUrl",
    validate_github_app_token_url,
    GITHUB_APP_TOKEN_URL_ERROR_MESSAGE
);
define_url_wrapper!(
    GithubApiUserUrl,
    "GithubApiUserUrl",
    validate_github_api_user_url,
    GITHUB_API_USER_URL_ERROR_MESSAGE
);

/// GitHub sign-in authorization URL with request query parameters.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GithubSignInAuthorizationUrl(Url);

impl GithubSignInAuthorizationUrl {
    /// Validate a generated authorization URL.
    pub fn try_from_url(url: Url) -> Result<Self, UrlFieldError> {
        validate_github_sign_in_authorization_url(&url)?;
        Ok(Self(url))
    }

    /// Borrow the canonical string representation.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl fmt::Display for GithubSignInAuthorizationUrl {
    /// Handles fmt for this module.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for GithubSignInAuthorizationUrl {
    type Err = UrlFieldError;

    /// Handles from str for this module.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let url = parse_url(value.trim(), GITHUB_SIGN_IN_AUTHORIZATION_URL_ERROR_MESSAGE)?;
        Self::try_from_url(url)
    }
}

impl_string_url_serde!(GithubSignInAuthorizationUrl);
impl_string_url_schema!(
    GithubSignInAuthorizationUrl,
    "GithubSignInAuthorizationUrl",
    r"^https://github\.com/login/oauth/authorize\?[^#]+$"
);

/// Parses url from an external boundary string.
fn parse_url(value: &str, message: &'static str) -> Result<Url, UrlFieldError> {
    reject_whitespace_or_control(value, message)?;
    Url::parse(value).map_err(|_| UrlFieldError::new(message))
}

/// Handles github https repo key for this module.
fn github_https_repo_key(url: &Url) -> Result<GithubRepoKey, UrlFieldError> {
    validate_github_https_base(url, GITHUB_REPO_REMOTE_ERROR_MESSAGE)?;
    let segments = github_path_segments(url, GITHUB_REPO_REMOTE_ERROR_MESSAGE)?;
    let [owner, repo_with_suffix] = segments.as_slice() else {
        return Err(UrlFieldError::new(GITHUB_REPO_REMOTE_ERROR_MESSAGE));
    };
    let repo = repo_with_suffix
        .strip_suffix(".git")
        .unwrap_or(repo_with_suffix.as_str());
    GithubRepoKey::try_new(owner, repo)
}

/// Validates github https pull request url invariants for this contract.
fn validate_github_https_pull_request_url(url: &Url) -> Result<(), UrlFieldError> {
    validate_github_https_base(url, GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE)?;
    github_pull_request_parts(url).map(|_| ())
}

/// Return canonical repository and pull-request number parts from a validated PR URL.
fn github_pull_request_parts(url: &Url) -> Result<(String, String, String), UrlFieldError> {
    let segments = github_path_segments(url, GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE)?;
    let [owner, repo, pull, number] = segments.as_slice() else {
        return Err(UrlFieldError::new(GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE));
    };
    if pull != "pull" {
        return Err(UrlFieldError::new(GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE));
    }
    validate_github_path_segment(owner, GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE)?;
    validate_github_path_segment(repo, GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE)?;
    if number.is_empty() || !number.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(UrlFieldError::new(GITHUB_PULL_REQUEST_URL_ERROR_MESSAGE));
    }
    Ok((
        owner.to_ascii_lowercase(),
        repo.to_ascii_lowercase(),
        number.to_string(),
    ))
}

/// Validates GitHub App redirect URL invariants for this contract.
fn validate_github_app_redirect_url(url: &Url) -> Result<(), UrlFieldError> {
    if !matches!(url.scheme(), "http" | "https")
        || url.cannot_be_a_base()
        || url.host_str().is_none()
        || url_has_userinfo(url)
        || url.query().is_some()
        || url.fragment().is_some()
    {
        return Err(UrlFieldError::new(GITHUB_APP_REDIRECT_URL_ERROR_MESSAGE));
    }
    Ok(())
}

/// Validates GitHub App authorization endpoint invariants for this contract.
fn validate_github_app_authorize_url(url: &Url) -> Result<(), UrlFieldError> {
    validate_exact_https_url(
        url,
        "github.com",
        "/login/oauth/authorize",
        GITHUB_APP_AUTHORIZE_URL_ERROR_MESSAGE,
    )
}

/// Validates generated GitHub sign-in authorization URL invariants.
fn validate_github_sign_in_authorization_url(url: &Url) -> Result<(), UrlFieldError> {
    if url.scheme() != "https"
        || url.cannot_be_a_base()
        || url.host_str() != Some("github.com")
        || url.port().is_some()
        || url.path() != "/login/oauth/authorize"
        || url.query().is_none()
        || url.fragment().is_some()
    {
        return Err(UrlFieldError::new(
            GITHUB_SIGN_IN_AUTHORIZATION_URL_ERROR_MESSAGE,
        ));
    }
    Ok(())
}

/// Validates GitHub App token endpoint invariants for this contract.
fn validate_github_app_token_url(url: &Url) -> Result<(), UrlFieldError> {
    validate_exact_https_url(
        url,
        "github.com",
        "/login/oauth/access_token",
        GITHUB_APP_TOKEN_URL_ERROR_MESSAGE,
    )
}

/// Validates github api user url invariants for this contract.
fn validate_github_api_user_url(url: &Url) -> Result<(), UrlFieldError> {
    validate_exact_https_url(
        url,
        "api.github.com",
        "/user",
        GITHUB_API_USER_URL_ERROR_MESSAGE,
    )
}

/// Validates Moltbook Submolt URL invariants for this contract.
fn validate_moltbook_submolt_url(url: &Url) -> Result<(), UrlFieldError> {
    validate_moltbook_base(url, MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE)?;
    moltbook_submolt_name(url).map(|_| ())
}

/// Validates Moltbook post URL invariants for this contract.
fn validate_moltbook_post_url(url: &Url) -> Result<(), UrlFieldError> {
    validate_moltbook_base(url, MOLTBOOK_POST_URL_ERROR_MESSAGE)?;
    let segments = moltbook_path_segments(url, MOLTBOOK_POST_URL_ERROR_MESSAGE)?;
    let [post, post_id] = segments.as_slice() else {
        return Err(UrlFieldError::new(MOLTBOOK_POST_URL_ERROR_MESSAGE));
    };
    if post != "post" || !has_moltbook_post_id_syntax(post_id) {
        return Err(UrlFieldError::new(MOLTBOOK_POST_URL_ERROR_MESSAGE));
    }
    Ok(())
}

/// Return the Moltbook Submolt name from a validated Submolt URL.
fn moltbook_submolt_name(url: &Url) -> Result<MoltbookSubmoltName, UrlFieldError> {
    let segments = moltbook_path_segments(url, MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE)?;
    let [m, name] = segments.as_slice() else {
        return Err(UrlFieldError::new(MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE));
    };
    if m != "m" {
        return Err(UrlFieldError::new(MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE));
    }
    let parsed = MoltbookSubmoltName::try_new(name.to_string())
        .map_err(|_| UrlFieldError::new(MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE))?;
    if parsed.as_str() != name {
        return Err(UrlFieldError::new(MOLTBOOK_SUBMOLT_URL_ERROR_MESSAGE));
    }
    Ok(parsed)
}

/// Validate the host and URL decorations shared by all Moltbook links.
fn validate_moltbook_base(url: &Url, message: &'static str) -> Result<(), UrlFieldError> {
    validate_https_url(url, message)?;
    if url.host_str() != Some("www.moltbook.com")
        || url.port().is_some()
        || !url.username().is_empty()
        || url.password().is_some()
    {
        return Err(UrlFieldError::new(message));
    }
    Ok(())
}

/// Return non-empty Moltbook path segments.
fn moltbook_path_segments(url: &Url, message: &'static str) -> Result<Vec<String>, UrlFieldError> {
    let Some(segments) = url.path_segments() else {
        return Err(UrlFieldError::new(message));
    };
    let segments: Vec<String> = segments.map(ToString::to_string).collect();
    if segments.iter().any(|segment| segment.is_empty()) {
        return Err(UrlFieldError::new(message));
    }
    Ok(segments)
}

/// Validate the opaque post id syntax accepted by Moltbook public post URLs.
fn has_moltbook_post_id_syntax(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
}

/// Validates exact https url invariants for this contract.
fn validate_exact_https_url(
    url: &Url,
    host: &str,
    path: &str,
    message: &'static str,
) -> Result<(), UrlFieldError> {
    validate_https_url(url, message)?;
    if url.host_str() != Some(host)
        || url.port().is_some()
        || url_has_userinfo(url)
        || url.path() != path
    {
        return Err(UrlFieldError::new(message));
    }
    Ok(())
}

/// Returns whether the URL includes username or password userinfo.
fn url_has_userinfo(url: &Url) -> bool {
    !url.username().is_empty() || url.password().is_some()
}

/// Validates github https base invariants for this contract.
fn validate_github_https_base(url: &Url, message: &'static str) -> Result<(), UrlFieldError> {
    validate_https_url(url, message)?;
    if url.host_str() != Some("github.com")
        || url.port().is_some()
        || !url.username().is_empty()
        || url.password().is_some()
    {
        return Err(UrlFieldError::new(message));
    }
    Ok(())
}

/// Validates https url invariants for this contract.
fn validate_https_url(url: &Url, message: &'static str) -> Result<(), UrlFieldError> {
    if url.scheme() != "https" || url.cannot_be_a_base() || url.host_str().is_none() {
        return Err(UrlFieldError::new(message));
    }
    if url.query().is_some() || url.fragment().is_some() {
        return Err(UrlFieldError::new(message));
    }
    Ok(())
}

/// Handles github path segments for this module.
fn github_path_segments(url: &Url, message: &'static str) -> Result<Vec<String>, UrlFieldError> {
    let Some(segments) = url.path_segments() else {
        return Err(UrlFieldError::new(message));
    };
    let segments: Vec<String> = segments.map(ToString::to_string).collect();
    if segments.iter().any(|segment| segment.is_empty()) {
        return Err(UrlFieldError::new(message));
    }
    Ok(segments)
}

/// Validates github path segment invariants for this contract.
fn validate_github_path_segment(value: &str, message: &'static str) -> Result<(), UrlFieldError> {
    if value.is_empty()
        || value == ".git"
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
    {
        return Err(UrlFieldError::new(message));
    }
    Ok(())
}

/// Handles reject whitespace or control for this module.
fn reject_whitespace_or_control(value: &str, message: &'static str) -> Result<(), UrlFieldError> {
    if value.is_empty() || value.chars().any(|c| c.is_whitespace() || c.is_control()) {
        Err(UrlFieldError::new(message))
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ExternalDataUrl, GithubApiUserUrl, GithubAppAuthorizeUrl, GithubAppRedirectUrl,
        GithubAppTokenUrl, GithubPullRequestUrl, GithubRepoRemote, MoltbookPostUrl,
        MoltbookSubmoltUrl,
    };

    /// Verifies that parses github repo remotes.
    #[test]
    fn parses_github_repo_remotes() {
        let https =
            GithubRepoRemote::try_new("https://github.com/Agentics-Reifying/Agentics-Challenges")
                .expect("HTTPS remote is valid");
        let https_with_suffix = GithubRepoRemote::try_new(
            "https://github.com/agentics-reifying/agentics-challenges.git",
        )
        .expect("HTTPS .git remote is valid");
        let ssh =
            GithubRepoRemote::try_new("git@github.com:agentics-reifying/agentics-challenges.git")
                .expect("SSH remote is valid");

        assert_eq!(https.repository_key(), https_with_suffix.repository_key());
        assert_eq!(https.repository_key(), ssh.repository_key());
        assert_eq!(
            https.repository_key().as_str(),
            "agentics-reifying/agentics-challenges"
        );
        assert!(GithubRepoRemote::try_new("http://github.com/owner/repo").is_err());
        assert!(GithubRepoRemote::try_new("https://example.com/owner/repo").is_err());
        assert!(GithubRepoRemote::try_new("git@github.com:owner/repo").is_err());
    }

    /// Verifies that parses github pull request urls.
    #[test]
    fn parses_github_pull_request_urls() {
        assert!(
            GithubPullRequestUrl::try_new(
                "https://github.com/agentics-reifying/agentics-challenges/pull/7",
            )
            .is_ok()
        );
        assert!(
            GithubPullRequestUrl::try_new(
                "git@github.com:agentics-reifying/agentics-challenges.git",
            )
            .is_err()
        );
        assert!(GithubPullRequestUrl::try_new("https://github.com/owner/repo/issues/7").is_err());
    }

    /// Verifies that parses challenge external urls.
    #[test]
    fn parses_challenge_external_urls() {
        assert!(ExternalDataUrl::try_new("https://example.com/data.bin").is_ok());
        assert!(ExternalDataUrl::try_new("http://example.com/data.bin").is_err());
        assert!(ExternalDataUrl::try_new("https://example.com/data.bin#section").is_err());
    }

    /// Verifies GitHub App URLs reject embedded credentials.
    #[test]
    fn rejects_github_app_url_userinfo() {
        assert!(GithubAppAuthorizeUrl::try_new("https://github.com/login/oauth/authorize").is_ok());
        assert!(GithubAppTokenUrl::try_new("https://github.com/login/oauth/access_token").is_ok());
        assert!(GithubApiUserUrl::try_new("https://api.github.com/user").is_ok());
        assert!(
            GithubAppRedirectUrl::try_new("http://127.0.0.1:3001/auth/github/callback").is_ok()
        );

        assert!(
            GithubAppAuthorizeUrl::try_new("https://user:pass@github.com/login/oauth/authorize")
                .is_err()
        );
        assert!(
            GithubAppTokenUrl::try_new("https://user:pass@github.com/login/oauth/access_token")
                .is_err()
        );
        assert!(GithubApiUserUrl::try_new("https://user:pass@api.github.com/user").is_err());
        assert!(
            GithubAppRedirectUrl::try_new("http://user:pass@127.0.0.1:3001/auth/github/callback")
                .is_err()
        );
    }

    /// Verifies Moltbook URL wrappers accept only the www Moltbook contracts.
    #[test]
    fn parses_moltbook_urls() {
        let submolt = MoltbookSubmoltUrl::try_new("https://www.moltbook.com/m/agentics-platform")
            .expect("canonical Submolt URL should parse");
        assert_eq!(
            submolt
                .submolt_name()
                .expect("Submolt name should parse")
                .as_str(),
            "agentics-platform"
        );
        assert!(MoltbookPostUrl::try_new("https://www.moltbook.com/post/abc-123_X").is_ok());

        for value in [
            "https://moltbook.com/m/agentics-platform",
            "https://www.moltbook.com/m/Agentics-Platform",
            "https://www.moltbook.com/submolts/agentics-platform",
            "https://www.moltbook.com/m/agentics-platform?x=1",
            "https://example.com/m/agentics-platform",
        ] {
            assert!(MoltbookSubmoltUrl::try_new(value).is_err());
        }

        for value in [
            "https://moltbook.com/post/abc-123",
            "https://www.moltbook.com/posts/abc-123",
            "https://www.moltbook.com/post/abc-123/comments",
            "https://www.moltbook.com/post/abc.123",
            "https://example.com/post/abc-123",
        ] {
            assert!(MoltbookPostUrl::try_new(value).is_err());
        }
    }
}