logit-loom-core 0.2.0

Backend-neutral contracts for mechanistic token-stream manipulation
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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Backend-neutral contracts for bounded structured projection.

use serde::{Deserialize, Serialize};

use crate::{
    CandidateMode, CoreError, Digest, GenerationFinish, GenerationPlanV2, GenerationReceipt,
    TokenId,
};

/// Maximum UTF-8 bytes in one caller-defined projection scope.
pub const MAX_STRUCTURED_SCOPE_BYTES: usize = 256;
/// Maximum caller-explicit attempts retained by one projection controller.
pub const MAX_STRUCTURED_ATTEMPTS: u32 = 64;
/// Maximum generated bytes accepted by one feedback implementation.
pub const MAX_STRUCTURED_OUTPUT_BYTES: u32 = 1024 * 1024;
/// Maximum generated-token decisions accepted by one feedback implementation.
pub const MAX_STRUCTURED_STEPS: u32 = 65_536;
/// Maximum model vocabulary accepted by structured byte feedback.
pub const MAX_STRUCTURED_CANDIDATES: u32 = 1_000_000;

const OUTPUT_DOMAIN: &str = "structured-projection-output-v1";

/// Content identities for one installed compiler, validator, or feedback
/// implementation and its exact configuration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StructuredMechanicIdentityV1 {
    /// Caller-defined implementation identity.
    pub implementation: Digest,
    /// Exact implementation-configuration identity.
    pub configuration: Digest,
}

impl StructuredMechanicIdentityV1 {
    /// Returns the complete component identity.
    ///
    /// # Errors
    ///
    /// Returns a deterministic serialization error.
    pub fn digest(&self) -> Result<Digest, CoreError> {
        Digest::of_serializable("structured-mechanic-identity-v1", self)
    }
}

/// Exact byte-feedback implementation and resource bounds.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ByteFeedbackSpecV1 {
    /// Installed implementation and configuration.
    pub mechanic: StructuredMechanicIdentityV1,
    /// Candidate exposure supplied at each sampling decision.
    pub mode: CandidateMode,
    /// Maximum decisions in one attempt.
    pub max_steps: u32,
    /// Maximum admitted output bytes in one attempt.
    pub max_output_bytes: u32,
}

impl ByteFeedbackSpecV1 {
    /// Validates candidate and resource bounds.
    ///
    /// # Errors
    ///
    /// Returns an error for an invalid candidate mode or zero/excessive
    /// decision or output bounds.
    pub fn validate(&self) -> Result<(), CoreError> {
        self.mode.validate()?;
        if !(1..=MAX_STRUCTURED_STEPS).contains(&self.max_steps)
            || !(1..=MAX_STRUCTURED_OUTPUT_BYTES).contains(&self.max_output_bytes)
        {
            return Err(CoreError::invalid(
                "structured byte feedback",
                "step and output-byte bounds must be positive and within public maxima",
            ));
        }
        Ok(())
    }

    /// Returns the complete byte-feedback identity.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest(&self) -> Result<Digest, CoreError> {
        self.validate()?;
        Digest::of_serializable("byte-feedback-spec-v1", self)
    }
}

/// Complete compiled mechanics for one structured projection controller.
///
/// Semantic compilers and validators remain caller supplied. This plan binds
/// their exact identities to native grammar, byte feedback, ordinary
/// transforms/observers, generation mechanics, and explicit attempt bounds.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StructuredProjectionPlanV1 {
    /// Open caller-defined name for the projection.
    pub scope: String,
    /// Exact target model/topology identity expected by the native adapter.
    pub target_topology: Digest,
    /// Exact source schema or constraint identity.
    pub constraints: Digest,
    /// Compiler that produced the native grammar and feedback configuration.
    pub compiler: StructuredMechanicIdentityV1,
    /// Authoritative post-generation validator.
    pub validator: StructuredMechanicIdentityV1,
    /// Incremental exact-byte feedback implementation.
    pub feedback: ByteFeedbackSpecV1,
    /// Complete generation mechanics, including one eager or lazy grammar.
    pub generation: GenerationPlanV2,
    /// Ordered ordinary transform-pipeline identity, when installed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transform_pipeline: Option<Digest>,
    /// Ordered admitted-token observer identity, when installed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observer_set: Option<Digest>,
    /// Maximum number of calls the caller may explicitly make.
    pub maximum_attempts: u32,
}

impl StructuredProjectionPlanV1 {
    /// Validates complete projection mechanics and resource bounds.
    ///
    /// # Errors
    ///
    /// Returns an error for an empty/excessive scope, absent grammar, invalid
    /// feedback/generation mechanics, or inconsistent attempt/token bounds.
    pub fn validate(&self) -> Result<(), CoreError> {
        if self.scope.trim().is_empty()
            || self.scope.len() > MAX_STRUCTURED_SCOPE_BYTES
            || self.scope.contains('\0')
        {
            return Err(CoreError::invalid(
                "structured projection scope",
                format!(
                    "must be non-empty, NUL-free, and at most {MAX_STRUCTURED_SCOPE_BYTES} bytes"
                ),
            ));
        }
        self.compiler.digest()?;
        self.validator.digest()?;
        self.feedback.validate()?;
        self.generation.validate()?;
        if self.generation.grammar.is_none() {
            return Err(CoreError::invalid(
                "structured projection grammar",
                "one explicit eager or lazy grammar is required",
            ));
        }
        if self.generation.generation.max_tokens > self.feedback.max_steps {
            return Err(CoreError::invalid(
                "structured projection generation",
                "generation token bound exceeds byte-feedback step capacity",
            ));
        }
        if !(1..=MAX_STRUCTURED_ATTEMPTS).contains(&self.maximum_attempts) {
            return Err(CoreError::invalid(
                "structured projection attempts",
                format!("must be in 1..={MAX_STRUCTURED_ATTEMPTS}"),
            ));
        }
        Ok(())
    }

    /// Returns the complete compiled plan identity.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest(&self) -> Result<Digest, CoreError> {
        self.validate()?;
        Digest::of_serializable("structured-projection-plan-v1", self)
    }
}

/// Evidence that an identified compiler produced one complete projection
/// plan.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StructuredCompilationReceiptV1 {
    /// Exact source schema or constraint identity.
    pub constraints: Digest,
    /// Complete compiler identity.
    pub compiler: Digest,
    /// Exact emitted eager/lazy grammar identity.
    pub grammar: Digest,
    /// Exact emitted byte-feedback identity.
    pub feedback: Digest,
    /// Complete resulting projection-plan identity.
    pub plan: Digest,
}

impl StructuredCompilationReceiptV1 {
    /// Validates compilation evidence against its compiler output.
    ///
    /// # Errors
    ///
    /// Returns an error when any source, compiler, grammar, feedback, or plan
    /// identity differs.
    pub fn validate_for(&self, plan: &StructuredProjectionPlanV1) -> Result<(), CoreError> {
        plan.validate()?;
        let grammar = plan.generation.grammar.as_ref().ok_or_else(|| {
            CoreError::invalid("structured compilation", "compiled grammar is absent")
        })?;
        if self.constraints != plan.constraints
            || self.compiler != plan.compiler.digest()?
            || self.grammar != grammar.digest()?
            || self.feedback != plan.feedback.digest()?
            || self.plan != plan.digest()?
        {
            return Err(CoreError::invalid(
                "structured compilation receipt",
                "compiler input or output identity differs from the plan",
            ));
        }
        Ok(())
    }

    /// Returns the exact validated compilation identity.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest_for(&self, plan: &StructuredProjectionPlanV1) -> Result<Digest, CoreError> {
        self.validate_for(plan)?;
        Digest::of_serializable("structured-compilation-receipt-v1", self)
    }
}

/// Exact symbolic decision before one native sampling operation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ByteFeedbackStepReceiptV1 {
    /// Contiguous zero-based sampling step.
    pub step: u32,
    /// Tokens admitted before this decision.
    pub accepted_tokens: u32,
    /// Output bytes admitted before this decision.
    pub output_bytes: u32,
    /// Exact output prefix identity.
    pub output_prefix: Digest,
    /// Exact implementation-local symbolic-state identity.
    pub state: Digest,
    /// Candidate tokens copied into the feedback boundary.
    pub candidate_tokens: u32,
    /// Candidates eligible after preceding transforms; negative infinity is
    /// already suppressed and NaN is invalid.
    pub eligible_candidates: u32,
    /// Eligible candidates retained by feedback.
    pub allowed_candidates: u32,
    /// Eligible candidates suppressed by feedback.
    pub rejected_candidates: u32,
    /// Ordered allowed token-ID identity.
    pub allowed_tokens: Digest,
    /// Ordered rejected token-ID identity.
    pub rejected_tokens: Digest,
}

impl ByteFeedbackStepReceiptV1 {
    fn validate_for(&self, specification: &ByteFeedbackSpecV1) -> Result<(), CoreError> {
        if self.step >= specification.max_steps
            || self.accepted_tokens > specification.max_steps
            || self.output_bytes > specification.max_output_bytes
            || self.candidate_tokens == 0
            || self.eligible_candidates > self.candidate_tokens
            || self.allowed_candidates == 0
            || self.allowed_candidates > self.eligible_candidates
            || self
                .allowed_candidates
                .checked_add(self.rejected_candidates)
                != Some(self.eligible_candidates)
        {
            return Err(CoreError::invalid(
                "byte-feedback step",
                "step, output, or candidate accounting is inconsistent",
            ));
        }
        Ok(())
    }
}

/// Complete exact-byte feedback execution for one projection attempt.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ByteFeedbackReceiptV1 {
    /// Exact feedback specification identity.
    pub feedback: Digest,
    /// Complete ordered tokenizer token/piece/EOG-table identity.
    pub tokenizer: Digest,
    /// Exact causal token history at attempt start.
    pub initial_tokens: Digest,
    /// Initial causal token count.
    pub initial_token_count: u64,
    /// Exact generated output identity.
    pub output: Digest,
    /// Generated output byte count.
    pub output_bytes: u32,
    /// Generated non-EOG tokens accepted by feedback.
    pub accepted_tokens: u32,
    /// Ordered decision receipts.
    pub steps: Vec<ByteFeedbackStepReceiptV1>,
    /// Final feedback-state identity.
    pub final_state: Digest,
    /// Whether the final bytes form a complete symbolic artifact.
    pub complete: bool,
}

impl ByteFeedbackReceiptV1 {
    /// Validates exact-byte feedback identity and monotonic accounting.
    ///
    /// # Errors
    ///
    /// Returns an error for a mismatched specification, excessive bounds,
    /// noncontiguous steps, or nonmonotonic prefix accounting.
    pub fn validate_for(&self, specification: &ByteFeedbackSpecV1) -> Result<(), CoreError> {
        specification.validate()?;
        if self.feedback != specification.digest()?
            || self.output_bytes > specification.max_output_bytes
            || self.accepted_tokens > specification.max_steps
            || self.steps.len() > usize::try_from(specification.max_steps).unwrap_or(usize::MAX)
        {
            return Err(CoreError::invalid(
                "byte-feedback receipt",
                "specification, output, or step accounting differs",
            ));
        }
        let mut prior_tokens = 0;
        let mut prior_bytes = 0;
        for (expected, step) in (0_u32..).zip(&self.steps) {
            step.validate_for(specification)?;
            if step.step != expected
                || step.accepted_tokens < prior_tokens
                || step.output_bytes < prior_bytes
                || step.accepted_tokens > self.accepted_tokens
                || step.output_bytes > self.output_bytes
            {
                return Err(CoreError::invalid(
                    "byte-feedback step order",
                    "steps or output prefixes are not contiguous and monotonic",
                ));
            }
            prior_tokens = step.accepted_tokens;
            prior_bytes = step.output_bytes;
        }
        Ok(())
    }

    /// Returns the exact validated feedback-execution identity.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest_for(&self, specification: &ByteFeedbackSpecV1) -> Result<Digest, CoreError> {
        self.validate_for(specification)?;
        Digest::of_serializable("byte-feedback-receipt-v1", self)
    }
}

/// Authoritative post-generation validation result.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StructuredValidationStatusV1 {
    /// Output parsed and conformed to the caller's constraint.
    Conforms,
    /// Output was mechanically rejected.
    Rejected,
}

/// Content-free evidence from one installed authoritative validator.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StructuredValidationReceiptV1 {
    /// Complete validator identity.
    pub validator: Digest,
    /// Exact source schema or constraint identity.
    pub constraints: Digest,
    /// Exact generated source identity.
    pub source: Digest,
    /// Canonical parsed-artifact identity, when produced.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_artifact: Option<Digest>,
    /// Deterministic validation-report identity, when produced.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation_report: Option<Digest>,
    /// Authoritative mechanical disposition.
    pub status: StructuredValidationStatusV1,
    /// Number of constraint violations.
    pub violations: u32,
    /// Number of bounded parse or validation diagnostics.
    pub diagnostics: u32,
}

impl StructuredValidationReceiptV1 {
    /// Validates this result against the plan and exact output bytes.
    ///
    /// # Errors
    ///
    /// Returns an error for a mismatched validator, constraints, source, or
    /// internally inconsistent conformance accounting.
    pub fn validate_for(
        &self,
        plan: &StructuredProjectionPlanV1,
        output: &Digest,
    ) -> Result<(), CoreError> {
        let valid_status = match self.status {
            StructuredValidationStatusV1::Conforms => self.violations == 0 && self.diagnostics == 0,
            StructuredValidationStatusV1::Rejected => self.violations > 0 || self.diagnostics > 0,
        };
        if self.validator != plan.validator.digest()?
            || self.constraints != plan.constraints
            || self.source != *output
            || !valid_status
        {
            return Err(CoreError::invalid(
                "structured validation receipt",
                "validator, source, constraints, or disposition accounting differs",
            ));
        }
        Ok(())
    }

    /// Returns the exact validated result identity.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest_for(
        &self,
        plan: &StructuredProjectionPlanV1,
        output: &Digest,
    ) -> Result<Digest, CoreError> {
        self.validate_for(plan, output)?;
        Digest::of_serializable("structured-validation-receipt-v1", self)
    }
}

/// Effect of one caller-explicit projection attempt.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StructuredAttemptDispositionV1 {
    /// Cooperative cancellation restored the exact boundary.
    Cancelled,
    /// Authoritative validation rejected output and restored the boundary.
    Rejected,
    /// Conforming output remains admitted.
    Selected,
}

/// One generated, incrementally constrained, and validated projection
/// attempt.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StructuredAttemptReceiptV1 {
    /// Contiguous caller-explicit attempt number.
    pub attempt: u32,
    /// Exact generated output identity.
    pub output: Digest,
    /// Native generation mechanics.
    pub generation: GenerationReceipt,
    /// Exact byte-feedback execution.
    pub feedback: ByteFeedbackReceiptV1,
    /// Authoritative validation, absent only for cancellation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation: Option<StructuredValidationReceiptV1>,
    /// Causal-state disposition.
    pub disposition: StructuredAttemptDispositionV1,
    /// Exact common checkpoint at attempt start.
    pub boundary_state: Digest,
    /// Exact selected or restored terminal checkpoint.
    pub terminal_state: Digest,
}

impl StructuredAttemptReceiptV1 {
    /// Validates one attempt and returns its exact identity.
    ///
    /// # Errors
    ///
    /// Returns an error for mismatched generation/feedback/validation
    /// evidence or a disposition inconsistent with retained causal state.
    pub fn digest_for(&self, plan: &StructuredProjectionPlanV1) -> Result<Digest, CoreError> {
        self.generation.digest()?;
        self.feedback.validate_for(&plan.feedback)?;
        if self.generation.plan != plan.generation.digest()?
            || self.output != self.feedback.output
            || u64::from(self.feedback.output_bytes) != self.generation.admitted_bytes
            || self.feedback.accepted_tokens != self.generation.admitted_tokens
            || self.generation.transform_receipt.is_some() != plan.transform_pipeline.is_some()
            || self.generation.observer_receipts.is_empty() == plan.observer_set.is_some()
        {
            return Err(CoreError::invalid(
                "structured projection attempt",
                "generation, output, or feedback accounting differs from the plan",
            ));
        }
        if let Some(validation) = &self.validation {
            validation.validate_for(plan, &self.output)?;
        }
        match self.disposition {
            StructuredAttemptDispositionV1::Cancelled => {
                if !matches!(self.generation.finish, GenerationFinish::ObserverStop)
                    || self.validation.is_some()
                    || self.terminal_state != self.boundary_state
                {
                    return Err(CoreError::invalid(
                        "cancelled structured attempt",
                        "cancellation must be unvalidated and restore the boundary",
                    ));
                }
            }
            StructuredAttemptDispositionV1::Rejected => {
                if matches!(self.generation.finish, GenerationFinish::ObserverStop)
                    || self.validation.as_ref().is_none_or(|validation| {
                        validation.status != StructuredValidationStatusV1::Rejected
                    })
                    || self.terminal_state != self.boundary_state
                {
                    return Err(CoreError::invalid(
                        "rejected structured attempt",
                        "rejection requires authoritative nonconformance and boundary restore",
                    ));
                }
            }
            StructuredAttemptDispositionV1::Selected => {
                if matches!(self.generation.finish, GenerationFinish::ObserverStop)
                    || self.validation.as_ref().is_none_or(|validation| {
                        validation.status != StructuredValidationStatusV1::Conforms
                    })
                    || self.terminal_state == self.boundary_state
                    || !self.feedback.complete
                {
                    return Err(CoreError::invalid(
                        "selected structured attempt",
                        "selection requires complete conforming output retained in causal state",
                    ));
                }
            }
        }
        Digest::of_serializable("structured-attempt-receipt-v1", self)
    }
}

/// Terminal evidence for a projection selected after zero or more explicit
/// cancelled/rejected attempts.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StructuredProjectionReceiptV1 {
    /// Complete projection plan identity.
    pub plan: Digest,
    /// Exact compiler execution identity.
    pub compilation: Digest,
    /// Shared initial checkpoint identity.
    pub boundary_state: Digest,
    /// Ordered caller-explicit attempts.
    pub attempts: Vec<StructuredAttemptReceiptV1>,
    /// Selected terminal attempt.
    pub selected_attempt: u32,
    /// Final selected causal-state identity.
    pub final_state: Digest,
}

impl StructuredProjectionReceiptV1 {
    /// Validates complete retry and selected-state lineage.
    ///
    /// # Errors
    ///
    /// Returns an error for a mismatched plan/compiler, empty/excessive
    /// attempts, noncontiguous attempt order, inconsistent boundary lineage,
    /// or a selected attempt that is not uniquely terminal.
    pub fn validate_for(
        &self,
        plan: &StructuredProjectionPlanV1,
        compilation: &StructuredCompilationReceiptV1,
    ) -> Result<(), CoreError> {
        if self.plan != plan.digest()?
            || self.compilation != compilation.digest_for(plan)?
            || self.attempts.is_empty()
            || self.attempts.len() > usize::try_from(plan.maximum_attempts).unwrap_or(usize::MAX)
        {
            return Err(CoreError::invalid(
                "structured projection receipt",
                "plan, compilation, or attempt bounds differ",
            ));
        }
        let mut selected = None;
        for (expected, attempt) in (0_u32..).zip(&self.attempts) {
            attempt.digest_for(plan)?;
            if attempt.attempt != expected || attempt.boundary_state != self.boundary_state {
                return Err(CoreError::invalid(
                    "structured projection attempt lineage",
                    "attempt order or common boundary differs",
                ));
            }
            if attempt.disposition == StructuredAttemptDispositionV1::Selected
                && selected.replace(attempt).is_some()
            {
                return Err(CoreError::invalid(
                    "structured projection selection",
                    "more than one attempt was selected",
                ));
            }
        }
        let Some(selected) = selected else {
            return Err(CoreError::invalid(
                "structured projection selection",
                "one selected terminal attempt is required",
            ));
        };
        if selected.attempt != self.selected_attempt
            || selected.attempt.checked_add(1) != u32::try_from(self.attempts.len()).ok()
            || selected.terminal_state != self.final_state
        {
            return Err(CoreError::invalid(
                "structured projection selection",
                "the selected attempt must be last and bind the final state",
            ));
        }
        Ok(())
    }

    /// Returns the complete terminal projection identity.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest_for(
        &self,
        plan: &StructuredProjectionPlanV1,
        compilation: &StructuredCompilationReceiptV1,
    ) -> Result<Digest, CoreError> {
        self.validate_for(plan, compilation)?;
        Digest::of_serializable("structured-projection-receipt-v1", self)
    }
}

/// Returns the stable identity used for exact generated projection bytes.
#[must_use]
pub fn structured_output_digest(bytes: &[u8]) -> Digest {
    Digest::of_bytes(OUTPUT_DOMAIN, bytes)
}

/// Returns the stable identity used for a complete ordered token-ID sequence.
///
/// # Errors
///
/// Returns a deterministic serialization error.
pub fn structured_tokens_digest(tokens: &[TokenId]) -> Result<Digest, CoreError> {
    Digest::of_serializable("structured-projection-tokens-v1", tokens)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        GenerationPlan, Grammar, GrammarActivationV2, GrammarPlanV2, SamplingPlan,
        StructuredValidationStatusV1,
    };

    fn digest(label: &str) -> Digest {
        Digest::of_bytes("structured-contract-test-v1", label.as_bytes())
    }

    fn mechanic(label: &str) -> StructuredMechanicIdentityV1 {
        StructuredMechanicIdentityV1 {
            implementation: digest(label),
            configuration: digest(&format!("{label}-configuration")),
        }
    }

    fn plan() -> StructuredProjectionPlanV1 {
        StructuredProjectionPlanV1 {
            scope: "mechanical-json".to_owned(),
            target_topology: digest("target-topology"),
            constraints: digest("constraints"),
            compiler: mechanic("compiler"),
            validator: mechanic("validator"),
            feedback: ByteFeedbackSpecV1 {
                mechanic: mechanic("feedback"),
                mode: CandidateMode::FullVocabulary,
                max_steps: 4,
                max_output_bytes: 128,
            },
            generation: GenerationPlanV2 {
                generation: GenerationPlan {
                    sampling: SamplingPlan::default(),
                    max_tokens: 4,
                    biases: Vec::new(),
                    grammar: None,
                    stops: Vec::new(),
                },
                grammar: Some(GrammarPlanV2 {
                    grammar: Grammar {
                        source: "root ::= \"{}\"".to_owned(),
                        root: "root".to_owned(),
                    },
                    activation: GrammarActivationV2::Eager,
                }),
            },
            transform_pipeline: None,
            observer_set: None,
            maximum_attempts: 2,
        }
    }

    fn compilation(plan: &StructuredProjectionPlanV1) -> StructuredCompilationReceiptV1 {
        StructuredCompilationReceiptV1 {
            constraints: plan.constraints.clone(),
            compiler: plan.compiler.digest().unwrap(),
            grammar: plan.generation.grammar.as_ref().unwrap().digest().unwrap(),
            feedback: plan.feedback.digest().unwrap(),
            plan: plan.digest().unwrap(),
        }
    }

    fn feedback(plan: &StructuredProjectionPlanV1) -> ByteFeedbackReceiptV1 {
        ByteFeedbackReceiptV1 {
            feedback: plan.feedback.digest().unwrap(),
            tokenizer: digest("tokenizer"),
            initial_tokens: digest("initial-tokens"),
            initial_token_count: 3,
            output: structured_output_digest(b"{}"),
            output_bytes: 2,
            accepted_tokens: 1,
            steps: vec![ByteFeedbackStepReceiptV1 {
                step: 0,
                accepted_tokens: 0,
                output_bytes: 0,
                output_prefix: structured_output_digest(b""),
                state: digest("state"),
                candidate_tokens: 16,
                eligible_candidates: 8,
                allowed_candidates: 2,
                rejected_candidates: 6,
                allowed_tokens: digest("allowed"),
                rejected_tokens: digest("rejected"),
            }],
            final_state: digest("final-feedback"),
            complete: true,
        }
    }

    fn selected_attempt(plan: &StructuredProjectionPlanV1) -> StructuredAttemptReceiptV1 {
        let feedback = feedback(plan);
        StructuredAttemptReceiptV1 {
            attempt: 0,
            output: feedback.output.clone(),
            generation: GenerationReceipt {
                plan: plan.generation.digest().unwrap(),
                initial_position: 3,
                admitted_tokens: 1,
                admitted_bytes: 2,
                final_position: 4,
                finish: GenerationFinish::TokenLimit,
                transform_receipt: None,
                observer_receipts: Vec::new(),
            },
            feedback,
            validation: Some(StructuredValidationReceiptV1 {
                validator: plan.validator.digest().unwrap(),
                constraints: plan.constraints.clone(),
                source: structured_output_digest(b"{}"),
                canonical_artifact: Some(digest("canonical")),
                validation_report: None,
                status: StructuredValidationStatusV1::Conforms,
                violations: 0,
                diagnostics: 0,
            }),
            disposition: StructuredAttemptDispositionV1::Selected,
            boundary_state: digest("boundary"),
            terminal_state: digest("selected"),
        }
    }

    #[test]
    fn compiled_plan_binds_grammar_feedback_and_attempt_bounds() {
        let valid = plan();
        valid.validate().unwrap();
        compilation(&valid).validate_for(&valid).unwrap();

        let mut no_grammar = valid.clone();
        no_grammar.generation.grammar = None;
        assert!(no_grammar.validate().is_err());

        let mut excessive_generation = valid;
        excessive_generation.generation.generation.max_tokens = 5;
        assert!(excessive_generation.validate().is_err());
    }

    #[test]
    fn projection_requires_one_final_selected_attempt() {
        let plan = plan();
        let compilation = compilation(&plan);
        let selected = selected_attempt(&plan);
        let receipt = StructuredProjectionReceiptV1 {
            plan: plan.digest().unwrap(),
            compilation: compilation.digest_for(&plan).unwrap(),
            boundary_state: digest("boundary"),
            attempts: vec![selected.clone()],
            selected_attempt: 0,
            final_state: digest("selected"),
        };
        receipt.validate_for(&plan, &compilation).unwrap();

        let mut not_terminal = receipt;
        let mut rejected = selected;
        rejected.attempt = 1;
        rejected.disposition = StructuredAttemptDispositionV1::Rejected;
        rejected.terminal_state = digest("boundary");
        rejected.validation.as_mut().unwrap().status = StructuredValidationStatusV1::Rejected;
        rejected.validation.as_mut().unwrap().violations = 1;
        not_terminal.attempts.push(rejected);
        assert!(not_terminal.validate_for(&plan, &compilation).is_err());
    }
}