agent-sdk-core 0.1.0-alpha.4

Product-neutral primitive kernel and contracts for a Rust-first Agent SDK.
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
//! Structured-output validation orchestration. Use this module after provider output
//! is available and before typed results are published. Validation is local and
//! deterministic unless a caller-provided validator performs additional work.
//!
use crate as sdk;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use sdk::{
    AgentError, AgentErrorKind, AttemptId, ContentHash, OutputContract, OutputMode,
    OutputSchemaDialect, OutputSchemaId, OutputSchemaRef, PrivacyClass, RetryClassification,
    SchemaVersion, ValidationAttemptId,
    domain::ContentRef,
    structured_output::{
        VALIDATION_RECORD_SCHEMA_VERSION, ValidationErrorCode, ValidationErrorSummary,
        ValidationRecord, ValidationRecordKind,
    },
};

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds output candidate application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct OutputCandidate {
    /// Stable source attempt id used for typed lineage, lookup, or dedupe.
    pub source_attempt_id: AttemptId,
    /// Content reference for the candidate value being validated.
    pub candidate_content_ref: ContentRef,
    /// Text used by this record or request.
    pub text: String,
    /// Privacy class used for projection, telemetry, and raw-content access
    /// decisions.
    pub privacy: PrivacyClass,
}

impl OutputCandidate {
    /// Creates a new application::validation value with explicit
    /// caller-provided inputs. This constructor is data-only and
    /// performs no I/O or external side effects.
    pub fn new(
        source_attempt_id: AttemptId,
        candidate_content_ref: ContentRef,
        text: impl Into<String>,
    ) -> Self {
        Self {
            source_attempt_id,
            candidate_content_ref,
            text: text.into(),
            privacy: PrivacyClass::ContentRefsOnly,
        }
    }

    /// Returns this value with its privacy setting replaced. The method
    /// follows builder-style data construction and does not execute
    /// external work.
    pub fn with_privacy(mut self, privacy: PrivacyClass) -> Self {
        self.privacy = privacy;
        self
    }
}

/// Port or behavior contract for structured output validator.
/// Implementors should preserve policy, redaction, idempotency, and
/// replay expectations from the surrounding module. Implementations may
/// perform side effects only as described by the trait methods.
pub trait StructuredOutputValidator {
    /// Validates the application::validation invariants and returns a
    /// typed error on failure. Validation is pure and does not perform
    /// I/O, dispatch, journal appends, or adapter calls.
    fn validate_candidate(
        &self,
        contract: &OutputContract,
        validation_attempt_id: ValidationAttemptId,
        candidate: &OutputCandidate,
    ) -> Result<ValidationSuccess, Box<ValidationErrorReport>>;
}

#[derive(Clone, Debug, Eq, PartialEq)]
/// Holds json schema subset validator application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct JsonSchemaSubsetValidator {
    /// Schema limits used by this record or request.
    pub schema_limits: HostileSchemaLimits,
}

impl JsonSchemaSubsetValidator {
    /// Creates a new application::validation value with explicit
    /// caller-provided inputs. This constructor is data-only and
    /// performs no I/O or external side effects.
    pub fn new(schema_limits: HostileSchemaLimits) -> Self {
        Self { schema_limits }
    }
}

impl Default for JsonSchemaSubsetValidator {
    fn default() -> Self {
        Self::new(HostileSchemaLimits::default())
    }
}

impl StructuredOutputValidator for JsonSchemaSubsetValidator {
    fn validate_candidate(
        &self,
        contract: &OutputContract,
        validation_attempt_id: ValidationAttemptId,
        candidate: &OutputCandidate,
    ) -> Result<ValidationSuccess, Box<ValidationErrorReport>> {
        let mut schema_errors = ErrorCollector::new(contract.validation.max_errors_returned);

        if contract.dialect != OutputSchemaDialect::JsonSchema2020_12Subset {
            schema_errors.push(ValidationErrorSummary::new(
                ValidationErrorCode::UnsupportedDialect,
                "/dialect",
                "unsupported structured output schema dialect",
            ));
        }

        if contract.mode != OutputMode::FinalOnly {
            schema_errors.push(ValidationErrorSummary::new(
                ValidationErrorCode::SchemaContractViolation,
                "/mode",
                "incremental structured output validation is not owned by this phase",
            ));
        }

        if let Err(error) = contract.validate_shape() {
            schema_errors.push(ValidationErrorSummary::new(
                ValidationErrorCode::SchemaContractViolation,
                "/",
                error.context().message,
            ));
        }

        let inline_schema = match &contract.schema {
            OutputSchemaRef::InlineJson {
                redacted_schema, ..
            } => Some(redacted_schema),
            _ => {
                schema_errors.push(ValidationErrorSummary::new(
                    ValidationErrorCode::UnsupportedSchemaRef,
                    "/schema",
                    "schema content must be inline for local validation in this phase",
                ));
                None
            }
        };

        if let Some(schema) = inline_schema {
            validate_schema_limits(schema, &self.schema_limits, &mut schema_errors);
        }

        if !contract.validation.semantic_validators.is_empty() {
            schema_errors.push(ValidationErrorSummary::new(
                ValidationErrorCode::SemanticValidatorUnavailable,
                "/validation/semantic_validators",
                "host semantic validators are referenced but no local validator was supplied",
            ));
        }

        if !schema_errors.is_empty() {
            let schema_rejected = schema_errors
                .errors
                .iter()
                .any(|error| error.code.is_schema_rejection());
            return Err(Box::new(ValidationErrorReport::new(
                contract,
                validation_attempt_id,
                candidate,
                schema_errors.into_errors(),
                schema_rejected,
            )));
        }

        if candidate.text.len() as u64 > contract.validation.max_candidate_bytes {
            return Err(Box::new(ValidationErrorReport::new(
                contract,
                validation_attempt_id,
                candidate,
                vec![ValidationErrorSummary::new(
                    ValidationErrorCode::CandidateTooLarge,
                    "/",
                    "candidate exceeds configured structured output byte limit",
                )],
                false,
            )));
        }

        let value = match serde_json::from_str::<Value>(&candidate.text) {
            Ok(value) => value,
            Err(_) => {
                return Err(Box::new(ValidationErrorReport::new(
                    contract,
                    validation_attempt_id,
                    candidate,
                    vec![ValidationErrorSummary::new(
                        ValidationErrorCode::InvalidJson,
                        "/",
                        "candidate is not valid JSON",
                    )],
                    false,
                )));
            }
        };

        let schema = inline_schema.expect("inline schema checked above");
        let mut candidate_errors = ErrorCollector::new(contract.validation.max_errors_returned);
        validate_value_against_schema(
            schema,
            &value,
            "/",
            contract.validation.allow_additional_properties,
            &mut candidate_errors,
        );

        if !candidate_errors.is_empty() {
            return Err(Box::new(ValidationErrorReport::new(
                contract,
                validation_attempt_id,
                candidate,
                candidate_errors.into_errors(),
                false,
            )));
        }

        let record = validation_record_succeeded(
            contract,
            validation_attempt_id.clone(),
            candidate,
            "structured output candidate validated locally",
        );

        Ok(ValidationSuccess {
            schema_id: contract.schema_id.clone(),
            schema_version: contract.schema_version,
            schema_fingerprint: contract.schema_fingerprint(),
            validation_attempt_id,
            source_attempt_id: candidate.source_attempt_id.clone(),
            candidate_content_ref: candidate.candidate_content_ref.clone(),
            canonical_value: value,
            privacy: candidate.privacy,
            record,
        })
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds hostile schema limits application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct HostileSchemaLimits {
    /// max schema bytes used for bounds checks, summaries, or truncation
    /// evidence.
    pub max_schema_bytes: usize,
    /// Maximum allowed object depth.
    /// Use it to keep execution, output, or diagnostics bounded.
    pub max_object_depth: usize,
    /// Maximum allowed properties per object.
    /// Use it to keep execution, output, or diagnostics bounded.
    pub max_properties_per_object: usize,
    /// Maximum allowed enum values per field.
    /// Use it to keep execution, output, or diagnostics bounded.
    pub max_enum_values_per_field: usize,
    /// max string pattern bytes used for bounds checks, summaries, or
    /// truncation evidence.
    pub max_string_pattern_bytes: usize,
    /// Typed allow remote refs references. Resolving them is separate from
    /// constructing this record.
    pub allow_remote_refs: bool,
    /// Boolean policy/capability flag for whether allow custom formats is
    /// enabled.
    pub allow_custom_formats: bool,
}

impl Default for HostileSchemaLimits {
    fn default() -> Self {
        Self {
            max_schema_bytes: 64 * 1024,
            max_object_depth: 24,
            max_properties_per_object: 256,
            max_enum_values_per_field: 512,
            max_string_pattern_bytes: 2 * 1024,
            allow_remote_refs: false,
            allow_custom_formats: false,
        }
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
/// Holds validation success application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct ValidationSuccess {
    /// Stable schema id used for typed lineage, lookup, or dedupe.
    pub schema_id: OutputSchemaId,
    /// Wire schema version used for compatibility checks.
    pub schema_version: SchemaVersion,
    /// Deterministic schema fingerprint used for stale checks, package
    /// evidence, or replay comparisons.
    pub schema_fingerprint: ContentHash,
    /// Stable validation attempt id used for typed lineage, lookup, or
    /// dedupe.
    pub validation_attempt_id: ValidationAttemptId,
    /// Stable source attempt id used for typed lineage, lookup, or dedupe.
    pub source_attempt_id: AttemptId,
    /// Content reference for the candidate value being validated.
    pub candidate_content_ref: ContentRef,
    /// Canonical value used by this record or request.
    pub canonical_value: Value,
    /// Privacy class used for projection, telemetry, and raw-content access
    /// decisions.
    pub privacy: PrivacyClass,
    /// Record used by this record or request.
    pub record: ValidationRecord,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds validation error report application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct ValidationErrorReport {
    /// Stable schema id used for typed lineage, lookup, or dedupe.
    pub schema_id: OutputSchemaId,
    /// Wire schema version used for compatibility checks.
    pub schema_version: SchemaVersion,
    /// Deterministic schema fingerprint used for stale checks, package
    /// evidence, or replay comparisons.
    pub schema_fingerprint: ContentHash,
    /// Stable validation attempt id used for typed lineage, lookup, or
    /// dedupe.
    pub validation_attempt_id: ValidationAttemptId,
    /// Stable source attempt id used for typed lineage, lookup, or dedupe.
    pub source_attempt_id: AttemptId,
    /// Content reference for the candidate value being validated.
    pub candidate_content_ref: ContentRef,
    /// Bounded errors included in this record. Limits and truncation are
    /// represented by companion metadata when applicable.
    pub errors: Vec<ValidationErrorSummary>,
    /// Redacted summary for display, logs, events, or telemetry.
    /// It should describe the value without exposing raw private content.
    pub redacted_error_summary: String,
    /// Whether schema rejected is enabled.
    /// Policy, validation, or routing code uses this flag to choose the explicit behavior.
    pub schema_rejected: bool,
    /// Whether retry exhausted is enabled.
    /// Policy, validation, or routing code uses this flag to choose the explicit behavior.
    pub retry_exhausted: bool,
    /// Privacy class used for projection, telemetry, and raw-content access
    /// decisions.
    pub privacy: PrivacyClass,
    /// Record used by this record or request.
    pub record: ValidationRecord,
}

impl ValidationErrorReport {
    fn new(
        contract: &OutputContract,
        validation_attempt_id: ValidationAttemptId,
        candidate: &OutputCandidate,
        errors: Vec<ValidationErrorSummary>,
        schema_rejected: bool,
    ) -> Self {
        let redacted_error_summary = summarize_errors(&errors);
        let record = if schema_rejected {
            validation_record_schema_rejected(
                contract,
                validation_attempt_id.clone(),
                candidate,
                redacted_error_summary.clone(),
                errors.clone(),
            )
        } else {
            validation_record_failed(
                contract,
                validation_attempt_id.clone(),
                candidate,
                redacted_error_summary.clone(),
                errors.clone(),
            )
        };

        Self {
            schema_id: contract.schema_id.clone(),
            schema_version: contract.schema_version,
            schema_fingerprint: contract.schema_fingerprint(),
            validation_attempt_id,
            source_attempt_id: candidate.source_attempt_id.clone(),
            candidate_content_ref: candidate.candidate_content_ref.clone(),
            errors,
            redacted_error_summary,
            schema_rejected,
            retry_exhausted: false,
            privacy: candidate.privacy,
            record,
        }
    }

    /// Returns this value as agent error. The accessor is side-effect
    /// free and keeps ownership with the caller.
    pub fn as_agent_error(&self) -> AgentError {
        let mut error = AgentError::new(
            AgentErrorKind::StructuredOutputFailure,
            if self.retry_exhausted || self.schema_rejected {
                RetryClassification::NotRetryable
            } else {
                RetryClassification::RepairNeeded
            },
            self.redacted_error_summary.clone(),
        );
        error = error.with_policy_ref(sdk::PolicyRef::with_kind(
            sdk::PolicyKind::RuntimePackage,
            self.schema_id.as_str(),
        ));
        error
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds terminal validation failure application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct TerminalValidationFailure {
    /// Stable schema id used for typed lineage, lookup, or dedupe.
    pub schema_id: OutputSchemaId,
    /// Wire schema version used for compatibility checks.
    pub schema_version: SchemaVersion,
    /// Validation policy applied before output is accepted as typed data.
    /// It controls validator selection, bounds, failure visibility, and local validation
    /// behavior.
    pub validation_attempts: Vec<ValidationAttemptId>,
    /// Attempt identifier or attempt history for bounded retry/repair.
    /// Use it to preserve ordering and avoid retry loops that cannot be audited.
    pub repair_attempts: Vec<sdk::RepairAttemptId>,
    /// Attempt identifier or attempt history for bounded retry/repair.
    /// Use it to preserve ordering and avoid retry loops that cannot be audited.
    pub source_attempt_ids: Vec<AttemptId>,
    /// Redacted summary for display, logs, events, or telemetry.
    /// It should describe the value without exposing raw private content.
    pub redacted_error_summary: String,
    /// Content reference for the candidate value being validated.
    pub candidate_content_ref: ContentRef,
    /// Whether retry exhausted is enabled.
    /// Policy, validation, or routing code uses this flag to choose the explicit behavior.
    pub retry_exhausted: bool,
    /// Privacy class used for projection, telemetry, and raw-content access
    /// decisions.
    pub privacy: PrivacyClass,
    /// Record used by this record or request.
    pub record: ValidationRecord,
}

impl TerminalValidationFailure {
    /// Constructs this value from reports. Use it when adapting
    /// canonical SDK records without introducing a second behavior
    /// path.
    pub fn from_reports(
        reports: &[ValidationErrorReport],
        repair_attempts: Vec<sdk::RepairAttemptId>,
        retry_exhausted: bool,
    ) -> Self {
        let last = reports
            .last()
            .expect("terminal validation failure needs at least one report");
        let validation_attempts = reports
            .iter()
            .map(|report| report.validation_attempt_id.clone())
            .collect::<Vec<_>>();
        let mut source_attempt_ids = Vec::new();
        for report in reports {
            if !source_attempt_ids.contains(&report.source_attempt_id) {
                source_attempt_ids.push(report.source_attempt_id.clone());
            }
        }
        let redacted_error_summary = if retry_exhausted {
            format!(
                "structured output validation failed after {} validation attempt(s) and {} repair attempt(s): {}",
                validation_attempts.len(),
                repair_attempts.len(),
                last.redacted_error_summary
            )
        } else {
            last.redacted_error_summary.clone()
        };
        let record = validation_record_terminal_failure(
            last,
            validation_attempts.clone(),
            repair_attempts.clone(),
            source_attempt_ids.clone(),
            redacted_error_summary.clone(),
            retry_exhausted,
        );
        Self {
            schema_id: last.schema_id.clone(),
            schema_version: last.schema_version,
            validation_attempts,
            repair_attempts,
            source_attempt_ids,
            redacted_error_summary,
            candidate_content_ref: last.candidate_content_ref.clone(),
            retry_exhausted,
            privacy: last.privacy,
            record,
        }
    }

    /// Returns this value as agent error. The accessor is side-effect
    /// free and keeps ownership with the caller.
    pub fn as_agent_error(&self) -> AgentError {
        AgentError::new(
            AgentErrorKind::StructuredOutputFailure,
            RetryClassification::NotRetryable,
            self.redacted_error_summary.clone(),
        )
    }
}

fn validation_record_base(
    contract: &OutputContract,
    record_kind: ValidationRecordKind,
    validation_attempt_id: ValidationAttemptId,
    candidate: &OutputCandidate,
    redacted_summary: String,
) -> ValidationRecord {
    ValidationRecord {
        record_schema_version: VALIDATION_RECORD_SCHEMA_VERSION,
        record_kind,
        schema_id: contract.schema_id.clone(),
        output_schema_version: contract.schema_version,
        schema_fingerprint: contract.schema_fingerprint(),
        validation_attempt_id,
        source_attempt_id: candidate.source_attempt_id.clone(),
        candidate_content_ref: candidate.candidate_content_ref.clone(),
        privacy: candidate.privacy,
        redacted_summary,
        errors: Vec::new(),
        validation_attempts: Vec::new(),
        repair_attempts: Vec::new(),
        source_attempt_ids: Vec::new(),
        retry_exhausted: None,
    }
}

fn validation_record_succeeded(
    contract: &OutputContract,
    validation_attempt_id: ValidationAttemptId,
    candidate: &OutputCandidate,
    redacted_summary: impl Into<String>,
) -> ValidationRecord {
    validation_record_base(
        contract,
        ValidationRecordKind::ValidationSucceeded,
        validation_attempt_id,
        candidate,
        redacted_summary.into(),
    )
}

fn validation_record_failed(
    contract: &OutputContract,
    validation_attempt_id: ValidationAttemptId,
    candidate: &OutputCandidate,
    redacted_summary: String,
    errors: Vec<ValidationErrorSummary>,
) -> ValidationRecord {
    let mut record = validation_record_base(
        contract,
        ValidationRecordKind::ValidationFailed,
        validation_attempt_id,
        candidate,
        redacted_summary,
    );
    record.errors = errors;
    record
}

fn validation_record_schema_rejected(
    contract: &OutputContract,
    validation_attempt_id: ValidationAttemptId,
    candidate: &OutputCandidate,
    redacted_summary: String,
    errors: Vec<ValidationErrorSummary>,
) -> ValidationRecord {
    let mut record = validation_record_base(
        contract,
        ValidationRecordKind::SchemaRejected,
        validation_attempt_id,
        candidate,
        redacted_summary,
    );
    record.errors = errors;
    record
}

fn validation_record_terminal_failure(
    last_report: &ValidationErrorReport,
    validation_attempts: Vec<ValidationAttemptId>,
    repair_attempts: Vec<sdk::RepairAttemptId>,
    source_attempt_ids: Vec<AttemptId>,
    redacted_summary: String,
    retry_exhausted: bool,
) -> ValidationRecord {
    ValidationRecord {
        record_schema_version: VALIDATION_RECORD_SCHEMA_VERSION,
        record_kind: ValidationRecordKind::TerminalFailure,
        schema_id: last_report.schema_id.clone(),
        output_schema_version: last_report.schema_version,
        schema_fingerprint: last_report.schema_fingerprint.clone(),
        validation_attempt_id: last_report.validation_attempt_id.clone(),
        source_attempt_id: last_report.source_attempt_id.clone(),
        candidate_content_ref: last_report.candidate_content_ref.clone(),
        privacy: last_report.privacy,
        redacted_summary,
        errors: last_report.errors.clone(),
        validation_attempts,
        repair_attempts,
        source_attempt_ids,
        retry_exhausted: Some(retry_exhausted),
    }
}

struct ErrorCollector {
    max: usize,
    errors: Vec<ValidationErrorSummary>,
}

impl ErrorCollector {
    fn new(max_errors_returned: u16) -> Self {
        Self {
            max: usize::from(max_errors_returned.max(1)),
            errors: Vec::new(),
        }
    }

    fn push(&mut self, error: ValidationErrorSummary) {
        if self.errors.len() < self.max {
            self.errors.push(error);
        }
    }

    fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    fn into_errors(self) -> Vec<ValidationErrorSummary> {
        self.errors
    }
}

fn summarize_errors(errors: &[ValidationErrorSummary]) -> String {
    match errors {
        [] => "structured output validation produced no errors".to_string(),
        [error] => format!(
            "structured output validation failed: {} at {}",
            error.redacted_summary, error.path
        ),
        [first, rest @ ..] => format!(
            "structured output validation failed with {} error(s): {} at {}",
            rest.len() + 1,
            first.redacted_summary,
            first.path
        ),
    }
}

fn validate_schema_limits(
    schema: &Value,
    limits: &HostileSchemaLimits,
    errors: &mut ErrorCollector,
) {
    let schema_bytes = serde_json::to_vec(schema).expect("serde_json::Value serializes");
    if schema_bytes.len() > limits.max_schema_bytes {
        errors.push(ValidationErrorSummary::new(
            ValidationErrorCode::HostileSchema,
            "/schema",
            "schema exceeds maximum byte limit",
        ));
    }
    inspect_schema_node(schema, "/", 0, limits, errors);
}

fn inspect_schema_node(
    value: &Value,
    path: &str,
    depth: usize,
    limits: &HostileSchemaLimits,
    errors: &mut ErrorCollector,
) {
    if depth > limits.max_object_depth {
        errors.push(ValidationErrorSummary::new(
            ValidationErrorCode::HostileSchema,
            path,
            "schema exceeds maximum object depth",
        ));
        return;
    }

    match value {
        Value::Object(fields) => {
            if let Some(Value::String(reference)) = fields.get("$ref") {
                let is_remote = reference.starts_with("http://")
                    || reference.starts_with("https://")
                    || !reference.starts_with('#');
                if is_remote && !limits.allow_remote_refs {
                    errors.push(ValidationErrorSummary::new(
                        ValidationErrorCode::HostileSchema,
                        join_path(path, "$ref"),
                        "remote or external schema references are denied",
                    ));
                } else {
                    errors.push(ValidationErrorSummary::new(
                        ValidationErrorCode::SchemaContractViolation,
                        join_path(path, "$ref"),
                        "local schema references are not supported by this validator phase",
                    ));
                }
            }

            if fields.contains_key("format") && !limits.allow_custom_formats {
                errors.push(ValidationErrorSummary::new(
                    ValidationErrorCode::HostileSchema,
                    join_path(path, "format"),
                    "custom format validators are disabled by default",
                ));
            }

            if let Some(Value::String(pattern)) = fields.get("pattern") {
                if pattern.len() > limits.max_string_pattern_bytes {
                    errors.push(ValidationErrorSummary::new(
                        ValidationErrorCode::HostileSchema,
                        join_path(path, "pattern"),
                        "schema string pattern exceeds maximum byte limit",
                    ));
                }
            }

            if let Some(Value::Object(properties)) = fields.get("properties") {
                if properties.len() > limits.max_properties_per_object {
                    errors.push(ValidationErrorSummary::new(
                        ValidationErrorCode::HostileSchema,
                        join_path(path, "properties"),
                        "schema object has too many properties",
                    ));
                }
            }

            if let Some(Value::Array(values)) = fields.get("enum") {
                if values.len() > limits.max_enum_values_per_field {
                    errors.push(ValidationErrorSummary::new(
                        ValidationErrorCode::HostileSchema,
                        join_path(path, "enum"),
                        "schema enum has too many values",
                    ));
                }
            }

            for (field, child) in fields {
                inspect_schema_node(child, &join_path(path, field), depth + 1, limits, errors);
            }
        }
        Value::Array(items) => {
            for (index, child) in items.iter().enumerate() {
                inspect_schema_node(
                    child,
                    &join_path(path, &index.to_string()),
                    depth + 1,
                    limits,
                    errors,
                );
            }
        }
        _ => {}
    }
}

fn validate_value_against_schema(
    schema: &Value,
    value: &Value,
    path: &str,
    allow_additional_properties: bool,
    errors: &mut ErrorCollector,
) {
    if let Some(enum_values) = schema.get("enum").and_then(Value::as_array) {
        if !enum_values.iter().any(|enum_value| enum_value == value) {
            errors.push(ValidationErrorSummary::new(
                ValidationErrorCode::EnumMismatch,
                path,
                "candidate value is not one of the allowed schema values",
            ));
            return;
        }
    }

    let schema_type = schema.get("type").and_then(Value::as_str);
    match schema_type {
        Some("object") => {
            validate_object_schema(schema, value, path, allow_additional_properties, errors)
        }
        Some("array") => {
            validate_array_schema(schema, value, path, allow_additional_properties, errors)
        }
        Some("string") => validate_string_schema(schema, value, path, errors),
        Some("integer") => {
            if value.as_i64().is_none() && value.as_u64().is_none() {
                errors.push(type_mismatch(path, "integer"));
            }
        }
        Some("number") => {
            if !value.is_number() {
                errors.push(type_mismatch(path, "number"));
            }
        }
        Some("boolean") => {
            if !value.is_boolean() {
                errors.push(type_mismatch(path, "boolean"));
            }
        }
        Some("null") => {
            if !value.is_null() {
                errors.push(type_mismatch(path, "null"));
            }
        }
        Some(_) => errors.push(ValidationErrorSummary::new(
            ValidationErrorCode::SchemaContractViolation,
            path,
            "schema type is outside the supported local subset",
        )),
        None => {
            if schema.get("properties").is_some() || schema.get("required").is_some() {
                validate_object_schema(schema, value, path, allow_additional_properties, errors);
            }
        }
    }
}

fn validate_object_schema(
    schema: &Value,
    value: &Value,
    path: &str,
    allow_additional_properties: bool,
    errors: &mut ErrorCollector,
) {
    let Some(object) = value.as_object() else {
        errors.push(type_mismatch(path, "object"));
        return;
    };

    let properties = schema.get("properties").and_then(Value::as_object);

    if let Some(required) = schema.get("required").and_then(Value::as_array) {
        for required_field in required.iter().filter_map(Value::as_str) {
            if !object.contains_key(required_field) {
                errors.push(ValidationErrorSummary::new(
                    ValidationErrorCode::MissingRequiredField,
                    join_path(path, required_field),
                    "required schema field is missing",
                ));
            }
        }
    }

    if let Some(properties) = properties {
        for (field, field_schema) in properties {
            if let Some(field_value) = object.get(field) {
                validate_value_against_schema(
                    field_schema,
                    field_value,
                    &join_path(path, field),
                    allow_additional_properties,
                    errors,
                );
            }
        }
    }

    let schema_denies_additional = schema
        .get("additionalProperties")
        .and_then(Value::as_bool)
        .is_some_and(|allowed| !allowed);
    let denies_additional = schema_denies_additional || !allow_additional_properties;
    if denies_additional {
        for field in object.keys() {
            let known = properties.is_some_and(|properties| properties.contains_key(field));
            if !known {
                errors.push(ValidationErrorSummary::new(
                    ValidationErrorCode::AdditionalPropertyDenied,
                    path,
                    "candidate contains an additional property denied by schema",
                ));
            }
        }
    }
}

fn validate_array_schema(
    schema: &Value,
    value: &Value,
    path: &str,
    allow_additional_properties: bool,
    errors: &mut ErrorCollector,
) {
    let Some(items) = value.as_array() else {
        errors.push(type_mismatch(path, "array"));
        return;
    };
    if let Some(item_schema) = schema.get("items").filter(|item| item.is_object()) {
        for (index, item) in items.iter().enumerate() {
            validate_value_against_schema(
                item_schema,
                item,
                &join_path(path, &index.to_string()),
                allow_additional_properties,
                errors,
            );
        }
    }
}

fn validate_string_schema(schema: &Value, value: &Value, path: &str, errors: &mut ErrorCollector) {
    let Some(text) = value.as_str() else {
        errors.push(type_mismatch(path, "string"));
        return;
    };

    if let Some(min) = schema.get("minLength").and_then(Value::as_u64) {
        if text.chars().count() < min as usize {
            errors.push(ValidationErrorSummary::new(
                ValidationErrorCode::MinLengthViolation,
                path,
                "candidate string is shorter than the schema minimum",
            ));
        }
    }
    if let Some(max) = schema.get("maxLength").and_then(Value::as_u64) {
        if text.chars().count() > max as usize {
            errors.push(ValidationErrorSummary::new(
                ValidationErrorCode::MaxLengthViolation,
                path,
                "candidate string is longer than the schema maximum",
            ));
        }
    }
}

fn type_mismatch(path: &str, expected: &str) -> ValidationErrorSummary {
    ValidationErrorSummary::new(
        ValidationErrorCode::TypeMismatch,
        path,
        format!("candidate value does not match schema type {expected}"),
    )
}

fn join_path(parent: &str, child: &str) -> String {
    if parent == "/" {
        format!("/{child}")
    } else {
        format!("{parent}/{child}")
    }
}