wyrd-spec 0.1.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
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
//! Typed side-effect templates dispatched after a failed verification.
//!
//! An Operator names its credential authority by a tenant-scoped connection
//! name, never a secret or an environment variable. Its text, URL, header, and
//! JSON-body templates may reference only the fields of the bounded
//! [`OperatorFailureContext`] through `{{field}}` placeholders; registration
//! rejects any other field through [`OperatorSpec::validate`].

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::card::verifier::VerifierImplementation;
use crate::error::WyrdError;
use crate::ids::{
    BindingId, CardUid, ConnectionName, OperatorDispatchId, VerificationResultId, VerificationRunId,
};
use crate::operator_connection::{
    HttpAuthScheme, HttpsOrigin, OperatorConnectionConfig, OperatorProvider,
};
use crate::verification::VerificationVerdict;

/// Server ceiling on one external delivery attempt, in seconds.
///
/// An authored `timeout_seconds` is clipped to this value; a Card cannot raise it.
pub const MAX_ATTEMPT_SECONDS: u32 = 30;

/// Maximum length, in characters, of the failure-context result summary.
pub const MAX_SUMMARY_CHARS: usize = 512;

/// Authored request headers the server owns and an Operator may never set.
///
/// Compared case-insensitively. `Idempotency-Key` carries the dispatch ID and
/// the rest are transport or credential headers.
pub const FORBIDDEN_HTTP_HEADERS: [&str; 6] = [
    "authorization",
    "host",
    "content-length",
    "transfer-encoding",
    "connection",
    "idempotency-key",
];

/// A server-owned side-effect template.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct OperatorSpec {
    /// Optional human-readable purpose.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The single action performed when this operator fires.
    ///
    /// Flattened so that an inline `on_failure` mapping and a referenced
    /// Operator Card's `spec` share one wire shape.
    #[serde(flatten)]
    pub action: OperatorAction,
    /// Optional execution limits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget: Option<OperatorBudget>,
}

impl OperatorSpec {
    /// Validate the connection-independent shape of this Operator.
    ///
    /// Checks every `{{field}}` template against the closed failure-context
    /// field set. With `implementation`, the Operator is attached to a binding
    /// of that exact Verifier, so a kind-specific field of another
    /// implementation (for example `drift.*` under an Eval Verifier) is
    /// refused; without it (a standalone Operator Card) every known field is
    /// allowed. It also requires a literal `https` (or loopback `http`) URL origin
    /// with templates confined to its path and query, or a `/`-prefixed
    /// path-only URL whose origin comes from the named `auth` connection at
    /// delivery, refuses server-owned
    /// headers, and refuses a custom auth header that is itself forbidden.
    /// Connection existence and authority are checked by the server, which
    /// owns the tenant's connections.
    ///
    /// # Errors
    /// Returns [`WyrdError::SpecInvalidOperator`] naming `field` and the first
    /// violation found, including a path-only URL without a named connection.
    pub fn validate(
        &self,
        field: &str,
        implementation: Option<&VerifierImplementation>,
    ) -> Result<(), WyrdError> {
        let invalid = |at: &str, reason: String| WyrdError::SpecInvalidOperator {
            message: format!("{field}{at}: {reason}"),
            details: serde_json::json!({ "field": format!("{field}{at}"), "reason": reason }),
        };
        let lookup = |name: &str| field_applies(name, implementation).then(String::new);
        let template = |at: &str, value: &str| {
            render_template(value, lookup).map_err(|reason| invalid(at, reason))
        };
        match &self.action {
            OperatorAction::Notify {
                channel:
                    NotifyChannel::Slack {
                        channel_id, text, ..
                    },
            } => {
                if channel_id.trim().is_empty() {
                    return Err(invalid(
                        ".channel.channel_id",
                        "must not be empty".to_owned(),
                    ));
                }
                template(".channel.text", text).map(drop)
            }
            OperatorAction::Notify {
                channel:
                    NotifyChannel::PagerDuty {
                        route,
                        summary,
                        dedup_key,
                        ..
                    },
            } => {
                if route.trim().is_empty() {
                    return Err(invalid(".channel.route", "must not be empty".to_owned()));
                }
                template(".channel.summary", summary)?;
                dedup_key
                    .as_deref()
                    .map_or(Ok(()), |key| template(".channel.dedup_key", key).map(drop))
            }
            OperatorAction::Http {
                url,
                headers,
                body,
                auth,
                expect_status,
                ..
            } => {
                template(".url", url)?;
                if !url.starts_with('/') {
                    operator_url_origin(url).map_err(|reason| invalid(".url", reason))?;
                } else if auth.is_none() {
                    return Err(invalid(
                        ".url",
                        "a path-only URL requires auth naming an http connection".to_owned(),
                    ));
                }
                for (name, value) in headers {
                    let at = format!(".headers.{name}");
                    check_header_name(name).map_err(|reason| invalid(&at, reason))?;
                    template(&at, value)?;
                }
                if let Some(HttpAuth::Header { name, .. }) = auth {
                    check_header_name(name).map_err(|reason| invalid(".auth.name", reason))?;
                    if headers.keys().any(|h| h.eq_ignore_ascii_case(name)) {
                        return Err(invalid(
                            ".auth.name",
                            format!("header {name} is also authored in headers"),
                        ));
                    }
                }
                if let Some(body) = body {
                    check_body_templates(body, &lookup)
                        .map_err(|reason| invalid(".body", reason))?;
                }
                match expect_status {
                    Some(status) if !(100..=599).contains(status) => Err(invalid(
                        ".expect_status",
                        format!("{status} is not an HTTP status"),
                    )),
                    _ => Ok(()),
                }
            }
        }
    }
}

impl OperatorSpec {
    /// The provider and name of the connection this Operator's credential
    /// authority names, or `None` for unauthenticated HTTP.
    #[must_use]
    pub fn connection(&self) -> Option<(OperatorProvider, &ConnectionName)> {
        match &self.action {
            OperatorAction::Notify {
                channel: NotifyChannel::Slack { connection, .. },
            } => Some((OperatorProvider::Slack, connection)),
            OperatorAction::Notify {
                channel: NotifyChannel::PagerDuty { connection, .. },
            } => Some((OperatorProvider::PagerDuty, connection)),
            OperatorAction::Http {
                auth: Some(auth), ..
            } => Some((OperatorProvider::Http, auth.connection())),
            OperatorAction::Http { auth: None, .. } => None,
        }
    }

    /// Whether the stored connection authority `config` authorizes this
    /// Operator.
    ///
    /// The one compatibility predicate registration and every delivery
    /// attempt share. Slack and PagerDuty need only the matching provider; an
    /// authenticated HTTP Operator additionally needs its literal URL origin
    /// to equal the connection origin (a path-only URL takes the connection
    /// origin and so always agrees) and its auth scheme (and custom header
    /// name, case-insensitively) to equal the stored scheme.
    #[must_use]
    pub fn matches_authority(&self, config: &OperatorConnectionConfig) -> bool {
        match (&self.action, config) {
            (
                OperatorAction::Notify {
                    channel: NotifyChannel::Slack { .. },
                },
                OperatorConnectionConfig::Slack { .. },
            )
            | (
                OperatorAction::Notify {
                    channel: NotifyChannel::PagerDuty { .. },
                },
                OperatorConnectionConfig::PagerDuty {},
            ) => true,
            (
                OperatorAction::Http {
                    url,
                    auth: Some(auth),
                    ..
                },
                OperatorConnectionConfig::Http {
                    origin,
                    auth: scheme,
                },
            ) => {
                let same_scheme = match (auth, scheme) {
                    (HttpAuth::Bearer { .. }, HttpAuthScheme::Bearer)
                    | (HttpAuth::Basic { .. }, HttpAuthScheme::Basic) => true,
                    (HttpAuth::Header { name, .. }, HttpAuthScheme::Header { name: stored }) => {
                        name.eq_ignore_ascii_case(stored)
                    }
                    _ => false,
                };
                same_scheme
                    && (url.starts_with('/')
                        || operator_url_origin(url).is_ok_and(|url| url == *origin))
            }
            _ => false,
        }
    }
}

/// The closed set of actions an Operator can perform.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum OperatorAction {
    /// Send a typed notification.
    Notify {
        /// Notification destination and payload.
        channel: NotifyChannel,
    },
    /// Perform an HTTP request.
    Http {
        /// HTTP method.
        method: HttpMethod,
        /// URL template; its origin is literal and `{{field}}` placeholders may
        /// appear only in the path and query. A template beginning with `/` is
        /// path-only and is sent to the origin stored on the `auth`
        /// connection, read at each attempt; it requires `auth`.
        url: String,
        /// Optional request headers; values are templates.
        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
        headers: BTreeMap<String, String>,
        /// Optional structured JSON body; string values are templates.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        body: Option<Value>,
        /// Credential authority; omitted for an unauthenticated request.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        auth: Option<HttpAuth>,
        /// Optional request timeout, clipped to [`MAX_ATTEMPT_SECONDS`].
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_seconds: Option<u32>,
        /// Optional expected response status; any 2xx is accepted when omitted.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expect_status: Option<u16>,
    },
}

/// Typed notification destinations.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum NotifyChannel {
    /// PagerDuty Events API v2 trigger through a tenant Global Integration key.
    PagerDuty {
        /// Name of the tenant's `pager_duty` connection.
        connection: ConnectionName,
        /// Route sent as `payload.custom_details.wyrd_route` for PagerDuty
        /// Service Routes.
        route: String,
        /// PagerDuty event severity.
        severity: PagerDutySeverity,
        /// Event summary template.
        summary: String,
        /// Optional de-duplication key template; the dispatch ID when omitted.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        dedup_key: Option<String>,
    },
    /// Slack `chat.postMessage` through a tenant workspace bot token.
    Slack {
        /// Name of the tenant's `slack` connection.
        connection: ConnectionName,
        /// Slack conversation ID the app may post in.
        channel_id: String,
        /// Message text template.
        text: String,
    },
}

/// PagerDuty Events API v2 severities.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum PagerDutySeverity {
    /// critical.
    Critical,
    /// error.
    Error,
    /// warning.
    Warning,
    /// info.
    Info,
}

/// HTTP methods supported by an HTTP Operator action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum HttpMethod {
    /// GET.
    Get,
    /// POST.
    Post,
    /// PUT.
    Put,
    /// PATCH.
    Patch,
    /// DELETE.
    Delete,
}

/// Credential authority of an HTTP action, bound to a tenant `http` connection.
///
/// The scheme and custom header name must equal the named connection's stored
/// authority at registration and before every attempt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "scheme", rename_all = "snake_case", deny_unknown_fields)]
pub enum HttpAuth {
    /// `Authorization: Bearer` from the connection's token.
    Bearer {
        /// Name of the tenant's `http` connection.
        connection: ConnectionName,
    },
    /// `Authorization: Basic` from the connection's username and password.
    Basic {
        /// Name of the tenant's `http` connection.
        connection: ConnectionName,
    },
    /// A custom header carrying the connection's value.
    Header {
        /// Header name, compared case-insensitively with the connection's.
        name: String,
        /// Name of the tenant's `http` connection.
        connection: ConnectionName,
    },
}

impl HttpAuth {
    /// The connection this auth binding names.
    #[must_use]
    pub const fn connection(&self) -> &ConnectionName {
        match self {
            Self::Bearer { connection }
            | Self::Basic { connection }
            | Self::Header { connection, .. } => connection,
        }
    }
}

/// Operator execution limits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct OperatorBudget {
    /// Maximum wall-clock runtime in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_wall_seconds: Option<u32>,
    /// Maximum tool calls allowed during invocation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_tool_calls: Option<u32>,
}

/// The bounded, immutable context every Operator invocation renders from.
///
/// Frozen on the dispatch row when a failed binding-created run settles, so
/// every retry renders the same payload. It carries identities, the verdict,
/// completion time, and a bounded summary only: no Eval context, media, Drift
/// feature rows, result detail, or secret material. Template placeholder names
/// are exactly [`OperatorFailureContext::FIELDS`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct OperatorFailureContext {
    /// The dispatch being delivered.
    pub dispatch_id: OperatorDispatchId,
    /// The failed run.
    pub run_id: VerificationRunId,
    /// The run's canonical result.
    pub result_id: VerificationResultId,
    /// The binding that configured this Operator.
    pub binding_id: BindingId,
    /// Exact Verifier Card UID.
    pub verifier_card_uid: CardUid,
    /// Exact Verifier identity as `space/name@version`.
    pub verifier_ref: String,
    /// Exact subject Card UID.
    pub subject_uid: CardUid,
    /// Exact subject identity as `space/name@version`.
    pub subject_ref: String,
    /// Always `failed`.
    pub verdict: VerificationVerdict,
    /// When the run settled.
    pub completed_at: DateTime<Utc>,
    /// Bounded human-readable result summary.
    pub summary: String,
    /// Aggregate counts of the failed run's Verifier implementation.
    pub verifier: VerifierCounts,
}

/// Aggregate, count-only numbers of one failed run, per Verifier implementation.
///
/// Frozen into the failure context beside `summary` and derived from the same
/// acknowledged result, so the two never disagree. Carries counts only: no
/// feature names, feature rows, task inputs or outputs, or assertion detail.
/// Templates reach these values as `drift.*` or `eval.*` fields, and a binding
/// may only reference the block of its own Verifier implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "implementation", rename_all = "snake_case", deny_unknown_fields)]
pub enum VerifierCounts {
    /// Counts of a failed Drift run.
    Drift {
        /// Features whose own verdict is `drift`.
        drifted_features: u32,
        /// Features scored in the report.
        total_features: u32,
    },
    /// Counts of a failed Eval run.
    Eval {
        /// Tasks that passed.
        passed_tasks: u32,
        /// Tasks that ran and did not pass.
        failed_tasks: u32,
        /// Tasks that ran.
        total_tasks: u32,
        /// `floor(100 * passed / total)`, or `0` when no task ran.
        pass_rate_percent: u32,
    },
}

impl VerifierCounts {
    /// Eval counts from `passed` of `total` tasks that ran.
    ///
    /// Derives `failed_tasks` and a pass rate rounded down, so a partial pass
    /// never reads `100`. `passed` above `total` is clamped to `total`.
    ///
    /// # Panics
    ///
    /// Panics if a percentage of at most 100 does not fit `u32`, which cannot happen.
    #[must_use]
    pub fn eval(passed: u32, total: u32) -> Self {
        let passed = passed.min(total);
        let pass_rate_percent = if total == 0 {
            0
        } else {
            u32::try_from(u64::from(passed) * 100 / u64::from(total))
                .expect("invariant: a rate of at most 100 fits u32")
        };
        Self::Eval {
            passed_tasks: passed,
            failed_tasks: total - passed,
            total_tasks: total,
            pass_rate_percent,
        }
    }

    /// The rendered value of one `drift.*` or `eval.*` field, or `None` when
    /// the field is unknown or belongs to another implementation.
    fn field(self, name: &str) -> Option<u32> {
        match (self, name) {
            (
                Self::Drift {
                    drifted_features, ..
                },
                "drift.drifted_features",
            ) => Some(drifted_features),
            (Self::Drift { total_features, .. }, "drift.total_features") => Some(total_features),
            (Self::Eval { passed_tasks, .. }, "eval.passed_tasks") => Some(passed_tasks),
            (Self::Eval { failed_tasks, .. }, "eval.failed_tasks") => Some(failed_tasks),
            (Self::Eval { total_tasks, .. }, "eval.total_tasks") => Some(total_tasks),
            (
                Self::Eval {
                    pass_rate_percent, ..
                },
                "eval.pass_rate_percent",
            ) => Some(pass_rate_percent),
            _ => None,
        }
    }
}

/// Whether template field `name` may be used by an Operator bound to
/// `implementation`; every field applies to a standalone Operator (`None`).
fn field_applies(name: &str, implementation: Option<&VerifierImplementation>) -> bool {
    !matches!(
        (name.split_once('.').map(|(kind, _)| kind), implementation),
        (Some("drift"), Some(VerifierImplementation::Eval(_)))
            | (Some("eval"), Some(VerifierImplementation::Drift(_)))
            | (
                Some("drift" | "eval"),
                Some(VerifierImplementation::Task(_))
            )
    )
}

impl OperatorFailureContext {
    /// Every placeholder name a template may reference.
    pub const FIELDS: [&'static str; 17] = [
        "dispatch_id",
        "run_id",
        "result_id",
        "binding_id",
        "verifier_card_uid",
        "verifier_ref",
        "subject_uid",
        "subject_ref",
        "verdict",
        "completed_at",
        "summary",
        "drift.drifted_features",
        "drift.total_features",
        "eval.passed_tasks",
        "eval.failed_tasks",
        "eval.total_tasks",
        "eval.pass_rate_percent",
    ];

    /// The rendered value of one placeholder, or `None` for an unknown name
    /// or a kind-specific field of another Verifier implementation.
    #[must_use]
    pub fn field(&self, name: &str) -> Option<String> {
        Some(match name {
            "dispatch_id" => self.dispatch_id.to_string(),
            "run_id" => self.run_id.to_string(),
            "result_id" => self.result_id.to_string(),
            "binding_id" => self.binding_id.to_string(),
            "verifier_card_uid" => self.verifier_card_uid.to_string(),
            "verifier_ref" => self.verifier_ref.clone(),
            "subject_uid" => self.subject_uid.to_string(),
            "subject_ref" => self.subject_ref.clone(),
            "verdict" => <&'static str>::from(self.verdict).to_owned(),
            "completed_at" => self.completed_at.to_rfc3339(),
            "summary" => self.summary.clone(),
            _ => return self.verifier.field(name).map(|count| count.to_string()),
        })
    }

    /// Render `template` with this context's fields.
    ///
    /// # Errors
    /// Returns the template error for a malformed or unknown placeholder.
    pub fn render(&self, template: &str) -> Result<String, String> {
        render_template(template, |name| self.field(name))
    }
}

/// Render `{{field}}` placeholders in `template` through `lookup`.
///
/// The grammar is closed: `{{`, optional spaces, one known field name,
/// optional spaces, `}}`. Validation and delivery share this one parser;
/// validation passes a lookup that accepts every known field.
///
/// # Errors
/// Returns a reason for an unterminated placeholder or an unknown field.
pub fn render_template(
    template: &str,
    lookup: impl Fn(&str) -> Option<String>,
) -> Result<String, String> {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(start) = rest.find("{{") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        let end = after
            .find("}}")
            .ok_or_else(|| "unterminated {{ placeholder".to_owned())?;
        let name = after[..end].trim();
        if !OperatorFailureContext::FIELDS.contains(&name) {
            return Err(format!(
                "unknown template field {name:?}; allowed: {}",
                OperatorFailureContext::FIELDS.join(", ")
            ));
        }
        out.push_str(&lookup(name).ok_or_else(|| {
            format!("template field {name:?} does not apply to this Verifier implementation")
        })?);
        rest = &after[end + 2..];
    }
    out.push_str(rest);
    Ok(out)
}

/// The literal origin of an HTTP Operator URL template.
///
/// The origin (scheme, host, port) precedes any placeholder, so registration
/// can compare it with a connection's stored authority before any rendering.
///
/// # Errors
/// Returns a reason when a placeholder appears in the origin or the origin is
/// not a valid [`HttpsOrigin`].
pub fn operator_url_origin(url: &str) -> Result<HttpsOrigin, String> {
    let authority_start = url.find("://").map_or(0, |i| i + 3);
    let origin_end = url[authority_start..]
        .find(['/', '?', '#'])
        .map_or(url.len(), |i| authority_start + i);
    let origin = &url[..origin_end];
    if origin.contains("{{") {
        return Err("templates may appear only in the URL path and query".to_owned());
    }
    HttpsOrigin::parse(origin).map_err(|error| error.to_string())
}

/// Refuse an empty, malformed, or server-owned header name.
fn check_header_name(name: &str) -> Result<(), String> {
    let valid = !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b));
    if !valid {
        return Err(format!("{name:?} is not a valid header name"));
    }
    if FORBIDDEN_HTTP_HEADERS
        .iter()
        .any(|forbidden| name.eq_ignore_ascii_case(forbidden))
    {
        return Err(format!("header {name} is owned by the server"));
    }
    Ok(())
}

/// Validate every string template inside a JSON body through `lookup`.
fn check_body_templates(
    value: &Value,
    lookup: &impl Fn(&str) -> Option<String>,
) -> Result<(), String> {
    match value {
        Value::String(text) => render_template(text, lookup).map(drop),
        Value::Array(items) => items
            .iter()
            .try_for_each(|item| check_body_templates(item, lookup)),
        Value::Object(map) => map
            .values()
            .try_for_each(|item| check_body_templates(item, lookup)),
        _ => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    //! Pure validation of Operator templates, origins, and headers.

    use super::*;

    /// Parse one Operator spec from JSON.
    ///
    /// # Panics
    /// Panics when the fixture is not a valid Operator spec.
    fn spec(value: Value) -> OperatorSpec {
        serde_json::from_value(value).expect("test_setup: operator spec parses")
    }

    /// Build an HTTP Operator with `url`, `headers`, and `auth`.
    fn http(url: &str, headers: Value, auth: Value) -> OperatorSpec {
        let mut value = serde_json::json!({
            "kind": "http", "method": "post", "url": url, "headers": headers,
            "body": { "text": "{{ summary }}", "ids": ["{{run_id}}"] }
        });
        if !auth.is_null() {
            value["auth"] = auth;
        }
        spec(value)
    }

    /// Known fields render; unknown and unterminated placeholders are refused.
    #[test]
    fn templates_accept_only_the_closed_context_fields() {
        let rendered = render_template("run {{run_id}} / {{ summary }}", |name| {
            Some(name.to_uppercase())
        })
        .expect("known fields render");
        assert_eq!(rendered, "run RUN_ID / SUMMARY");
        assert!(render_template("{{secret}}", |_| Some(String::new())).is_err());
        assert!(render_template("{{run_id", |_| Some(String::new())).is_err());
    }

    /// Eval counts derive failures and a pass rate that rounds down, never
    /// reading 100 for a partial pass, and read 0 when no task ran.
    #[test]
    fn eval_counts_round_the_pass_rate_down() {
        assert_eq!(
            VerifierCounts::eval(999, 1000),
            VerifierCounts::Eval {
                passed_tasks: 999,
                failed_tasks: 1,
                total_tasks: 1000,
                pass_rate_percent: 99,
            }
        );
        assert_eq!(
            VerifierCounts::eval(0, 0),
            VerifierCounts::Eval {
                passed_tasks: 0,
                failed_tasks: 0,
                total_tasks: 0,
                pass_rate_percent: 0,
            }
        );
    }

    /// Kind fields render from the frozen counts; a field of the other
    /// implementation does not render, and a binding of that implementation
    /// refuses it while a standalone Operator accepts every known field.
    #[test]
    fn kind_fields_follow_the_verifier_implementation() {
        let counts = VerifierCounts::Drift {
            drifted_features: 3,
            total_features: 20,
        };
        let rendered = render_template(
            "{{drift.drifted_features}}/{{ drift.total_features }}",
            |name| counts.field(name).map(|count| count.to_string()),
        )
        .expect("drift fields render");
        assert_eq!(rendered, "3/20");
        let refusal = render_template("{{eval.total_tasks}}", |name| {
            counts.field(name).map(|count| count.to_string())
        })
        .expect_err("an eval field does not render from drift counts");
        assert!(refusal.contains("does not apply"), "{refusal}");

        let eval: VerifierImplementation =
            serde_json::from_value(serde_json::json!({ "kind": "eval", "spec": { "tasks": {} } }))
                .expect("test_setup: eval implementation parses");
        let drift_hook = http(
            "https://hooks.example.com/{{drift.total_features}}",
            serde_json::json!({}),
            Value::Null,
        );
        assert!(drift_hook.validate("spec", None).is_ok());
        let error = drift_hook
            .validate("spec", Some(&eval))
            .expect_err("an eval binding refuses a drift field");
        assert!(
            error.to_string().contains("drift.total_features"),
            "{error}"
        );
        let eval_hook = http(
            "https://hooks.example.com/{{eval.pass_rate_percent}}",
            serde_json::json!({}),
            Value::Null,
        );
        assert!(eval_hook.validate("spec", Some(&eval)).is_ok());
    }

    /// Slack, PagerDuty, and HTTP Operators validate; each violation is refused.
    #[test]
    fn validate_refuses_each_shape_violation() {
        let slack = spec(serde_json::json!({
            "kind": "notify",
            "channel": { "kind": "slack", "connection": "ops-slack", "channel_id": "C1", "text": "{{verifier_ref}} failed" }
        }));
        assert!(slack.validate("spec", None).is_ok());
        let bad_slack = spec(serde_json::json!({
            "kind": "notify",
            "channel": { "kind": "slack", "connection": "ops-slack", "channel_id": "C1", "text": "{{env.TOKEN}}" }
        }));
        assert_eq!(
            bad_slack
                .validate("spec", None)
                .expect_err("unknown field")
                .code(),
            "WYRD_SPEC_400_INVALID_OPERATOR"
        );
        let pager = spec(serde_json::json!({
            "kind": "notify",
            "channel": { "kind": "pager_duty", "connection": "pagerduty", "route": "team-a", "severity": "error", "summary": "{{summary}}" }
        }));
        assert!(pager.validate("spec", None).is_ok());

        let auth =
            serde_json::json!({ "scheme": "header", "name": "X-Api-Key", "connection": "hooks" });
        assert!(
            http(
                "https://hooks.example.com/v1/{{run_id}}",
                serde_json::json!({}),
                auth.clone()
            )
            .validate("spec", None)
            .is_ok()
        );
        for (url, headers, auth) in [
            (
                "https://{{run_id}}.example.com/",
                serde_json::json!({}),
                Value::Null,
            ),
            (
                "ftp://hooks.example.com/",
                serde_json::json!({}),
                Value::Null,
            ),
            (
                "http://hooks.example.com/",
                serde_json::json!({}),
                Value::Null,
            ),
            (
                "https://hooks.example.com/",
                serde_json::json!({ "AUTHORIZATION": "x" }),
                Value::Null,
            ),
            (
                "https://hooks.example.com/",
                serde_json::json!({ "Idempotency-Key": "x" }),
                Value::Null,
            ),
            (
                "https://hooks.example.com/",
                serde_json::json!({ "x-api-key": "x" }),
                auth.clone(),
            ),
            (
                "https://hooks.example.com/",
                serde_json::json!({}),
                serde_json::json!({ "scheme": "header", "name": "Host", "connection": "hooks" }),
            ),
        ] {
            assert!(
                http(url, headers, auth).validate("spec", None).is_err(),
                "{url}"
            );
        }
    }

    /// The URL origin is extracted literally before any placeholder.
    #[test]
    fn url_origin_is_literal_and_normalized() {
        let origin =
            operator_url_origin("https://Hooks.Example.com:443/a/{{run_id}}?q={{summary}}")
                .expect("literal origin");
        assert_eq!(origin.as_str(), "https://hooks.example.com");
        assert!(operator_url_origin("https://user@hooks.example.com/").is_err());
    }

    /// Authority matches only the same provider, and for HTTP only the same
    /// normalized origin and auth scheme, with header names compared
    /// case-insensitively.
    #[test]
    fn authority_matches_provider_origin_and_scheme() {
        let header =
            serde_json::json!({ "scheme": "header", "name": "x-api-key", "connection": "hooks" });
        let op = http(
            "https://Hooks.Example.com:443/v1/{{run_id}}",
            serde_json::json!({}),
            header,
        );
        assert_eq!(
            op.connection().map(|(p, n)| (p, n.as_str())),
            Some((OperatorProvider::Http, "hooks"))
        );
        let stored = |origin: &str, auth: HttpAuthScheme| OperatorConnectionConfig::Http {
            origin: HttpsOrigin::parse(origin).expect("origin"),
            auth,
        };
        let header_scheme = || HttpAuthScheme::Header {
            name: "X-Api-Key".to_owned(),
        };
        assert!(op.matches_authority(&stored("https://hooks.example.com", header_scheme())));
        assert!(!op.matches_authority(&stored("https://hooks.example.com:8443", header_scheme())));
        assert!(!op.matches_authority(&stored("https://other.example.com", header_scheme())));
        assert!(
            !op.matches_authority(&stored("https://hooks.example.com", HttpAuthScheme::Bearer))
        );
        assert!(!op.matches_authority(&OperatorConnectionConfig::PagerDuty {}));
        let open = http(
            "https://hooks.example.com/x",
            serde_json::json!({}),
            Value::Null,
        );
        assert!(open.connection().is_none());
    }

    /// A `/`-prefixed URL validates only with `auth` naming an http
    /// connection, and then agrees with any stored origin of the same scheme.
    #[test]
    fn path_only_url_requires_a_named_http_connection() {
        let auth = serde_json::json!({ "scheme": "bearer", "connection": "hooks" });
        let named = http("/v1/{{run_id}}", serde_json::json!({}), auth);
        assert!(named.validate("spec", None).is_ok());
        assert!(named.matches_authority(&OperatorConnectionConfig::Http {
            origin: HttpsOrigin::parse("https://staging.example.com").expect("origin"),
            auth: HttpAuthScheme::Bearer,
        }));
        let anonymous = http("/v1/{{run_id}}", serde_json::json!({}), Value::Null);
        assert_eq!(
            anonymous
                .validate("spec", None)
                .expect_err("path-only URL without a connection")
                .code(),
            "WYRD_SPEC_400_INVALID_OPERATOR"
        );
    }
}