wesley-core 0.0.4

Wesley Rust Core - Deterministic compiler kernel
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
//! Runtime optic artifact models.
//!
//! These types are intentionally domain-empty. They describe the GraphQL
//! operation shape, declared bounds, and law claims that a host/runtime can
//! admit, obstruct, witness, or replay.

use crate::domain::ir::TypeReference;
use crate::domain::operation::OperationType;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;

/// Canonical JSON codec for Wesley-owned runtime optic admission requirements.
pub const OPTIC_ADMISSION_REQUIREMENTS_ARTIFACT_CODEC: &str =
    "wesley.requirements.canonical-json.v0";

/// Compiled contract for one runtime-declared GraphQL optic operation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OpticArtifact {
    /// Stable artifact identity derived from the schema and operation identity.
    pub artifact_id: String,
    /// Stable content hash for the full compiled artifact.
    pub artifact_hash: String,
    /// Stable schema identity derived from the lowered Wesley IR.
    pub schema_id: String,
    /// Stable digest of admission requirements and law claim templates.
    pub requirements_digest: String,
    /// Wesley-owned canonical byte artifact for admission requirements.
    pub requirements_artifact: OpticAdmissionRequirementsArtifact,
    /// The selected GraphQL operation compiled into an inspectable contract.
    pub operation: OpticOperation,
    /// Admission requirements Echo or another runtime must enforce.
    pub requirements: OpticAdmissionRequirements,
    /// Descriptor an application can present when registering this artifact.
    pub registration: OpticRegistrationDescriptor,
}

/// Wesley-produced descriptor for registering a compiled optic artifact.
///
/// This is not a runtime handle and it is not an authority grant. It is the
/// small descriptor an application can send to Echo alongside the full artifact
/// so Echo can verify the exact artifact hash and requirements digest it is
/// accepting into its registry.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OpticRegistrationDescriptor {
    /// Stable artifact identity this descriptor refers to.
    pub artifact_id: String,
    /// Stable content hash for the full compiled artifact.
    pub artifact_hash: String,
    /// Stable schema identity for the referenced artifact.
    pub schema_id: String,
    /// Stable operation identity for the referenced artifact.
    pub operation_id: String,
    /// Stable digest of admission requirements and law claim templates.
    pub requirements_digest: String,
}

/// Echo-owned opaque handle for a registered optic artifact.
///
/// Wesley defines the wire shape so callers can name it, but Wesley does not
/// issue this handle. Echo or another runtime returns it after accepting and
/// storing a specific artifact hash.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OpticArtifactHandle {
    /// Runtime-owned discriminator, normally `optic-artifact-handle`.
    pub kind: String,
    /// Runtime-local opaque handle identifier.
    pub id: String,
}

/// Admission requirements for an optic artifact.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OpticAdmissionRequirements {
    /// Identity binding required before a host/runtime admits the handle.
    pub identity: IdentityRequirement,
    /// Permission requirements inferred from the declared optic bounds.
    pub required_permissions: Vec<PermissionRequirement>,
    /// Resource labels that must remain inaccessible to the operation.
    pub forbidden_resources: Vec<String>,
}

/// Wesley-owned canonical admission requirements byte artifact.
///
/// Downstream runtimes import these bytes directly. They should verify the
/// digest and codec, but they should not serialize Wesley structs to create
/// admission truth.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OpticAdmissionRequirementsArtifact {
    /// Stable digest computed from `bytes` exactly.
    pub digest: String,
    /// Explicit codec describing how `bytes` were generated.
    pub codec: String,
    /// Canonical requirements bytes generated by Wesley.
    pub bytes: Vec<u8>,
}

/// Host, user, quorum, or policy authority grant for invoking an artifact.
///
/// Wesley core defines this shape so artifacts and runtime receipts can speak a
/// shared language, but Wesley does not issue these grants. A host, user,
/// quorum, or policy authority owns issuance, expiry, delegation, and
/// attestation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CapabilityGrant {
    /// Stable grant identity.
    pub grant_id: String,
    /// Principal receiving bounded authority.
    pub subject: PrincipalRef,
    /// Artifact hash this grant covers.
    pub artifact_hash: String,
    /// Operation identity this grant covers.
    pub operation_id: String,
    /// Requirements digest this grant covers.
    pub requirements_digest: String,
    /// Optional basis constraint for the invocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_basis: Option<BasisConstraint>,
    /// Aperture constraints accepted by the grant.
    pub allowed_apertures: Vec<ApertureConstraint>,
    /// Budget constraint for invocations using the grant.
    pub budget: BudgetConstraint,
    /// Optional expiration timestamp supplied by the issuing authority.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    /// Rights granted under the artifact requirements.
    pub rights: Vec<String>,
    /// Principal or service that issued the grant.
    pub issuer: PrincipalRef,
    /// Optional signature supplied by the issuer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuer_signature: Option<String>,
    /// Optional digest of the delegation chain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delegation_chain_digest: Option<String>,
    /// Optional observer class bound by the grant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observer_class: Option<ObserverClass>,
    /// Whether the grant may be transferred to another subject.
    pub non_transferable: bool,
}

/// Invocation-time presentation of a capability grant.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CapabilityPresentation {
    /// Grant identity being presented.
    pub grant_id: String,
    /// Principal presenting the grant.
    pub subject: PrincipalRef,
    /// Echo-owned artifact handle used for this invocation.
    pub artifact_handle_id: String,
    /// Operation identity being invoked.
    pub operation_id: String,
    /// Digest of the canonical variable bytes for this invocation.
    pub variables_digest: String,
    /// Optional digest of the requested basis/aperture.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub basis_request_digest: Option<String>,
    /// Nonce preventing replay of the presentation.
    pub nonce: String,
    /// Presentation timestamp supplied by the caller or host.
    pub presented_at: String,
    /// Optional digest of a proof or signature over the presentation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proof_digest: Option<String>,
}

/// Echo-owned authorization for one exact admitted invocation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AdmissionTicket {
    /// Stable ticket identity.
    pub ticket_id: String,
    /// Echo-owned artifact handle used for this invocation.
    pub artifact_handle: OpticArtifactHandle,
    /// Capability grant identity admitted for this invocation.
    pub capability_grant_id: String,
    /// Operation identity admitted for this invocation.
    pub operation_id: String,
    /// Digest of invocation inputs admitted by the runtime.
    pub invocation_digest: String,
    /// Runtime-issued admission timestamp.
    pub issued_at: String,
    /// Optional runtime-issued ticket expiry.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
}

/// Constraint over the state basis allowed by a capability grant.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct BasisConstraint {
    /// Optional exact basis reference the grant permits.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub basis_ref: Option<String>,
    /// Optional maximum staleness in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_staleness_ms: Option<u64>,
}

/// Constraint over a read or rewrite aperture.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ApertureConstraint {
    /// Aperture kind, such as `file_range` or `symbol_context`.
    pub kind: String,
    /// Optional numeric limit owned by the host/runtime policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u64>,
}

/// Budget constraint attached to a capability grant.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct BudgetConstraint {
    /// Optional maximum operation count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_operations: Option<u64>,
    /// Optional maximum byte budget.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_bytes: Option<u64>,
    /// Optional maximum runtime in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_millis: Option<u64>,
}

/// Observer class bound by a capability grant.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ObserverClass {
    /// No runtime observation rights.
    Oc0,
    /// Minimal reading rights.
    Oc1,
    /// Bounded runtime observation rights.
    Oc2,
    /// Broad runtime observation rights under explicit policy.
    Oc3,
}

/// Permission granted by a capability grant.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PermissionGrant {
    /// Granted action.
    pub action: PermissionAction,
    /// Resource label the grant applies to.
    pub resource: String,
    /// Host/session-owned source of the grant.
    pub source: String,
}

/// Artifact resolver input accepted by Wesley-side registries.
pub type OpticArtifactRef = OpticRegistrationDescriptor;

/// Resolves compiled optic artifacts from registration descriptors.
pub trait OpticArtifactResolver {
    /// Resolves a registration descriptor to its full compiled artifact and
    /// verifies the descriptor still matches artifact identity and requirements.
    fn resolve_optic_artifact(
        &self,
        registration: &OpticRegistrationDescriptor,
    ) -> Result<OpticArtifact, ResolveError>;
}

/// In-memory artifact registry for tests and single-process hosts.
#[derive(Debug, Default, Clone)]
pub struct InMemoryOpticArtifactRegistry {
    artifacts: BTreeMap<String, OpticArtifact>,
}

impl InMemoryOpticArtifactRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Stores an artifact and returns its registration descriptor.
    pub fn insert(&mut self, mut artifact: OpticArtifact) -> OpticRegistrationDescriptor {
        let registration = registration_descriptor_for_artifact(&artifact);
        artifact.registration = registration.clone();
        self.artifacts
            .insert(artifact.artifact_id.clone(), artifact);
        registration
    }

    /// Returns the number of stored artifacts.
    pub fn len(&self) -> usize {
        self.artifacts.len()
    }

    /// Returns true when no artifacts are stored.
    pub fn is_empty(&self) -> bool {
        self.artifacts.is_empty()
    }
}

fn registration_descriptor_for_artifact(artifact: &OpticArtifact) -> OpticRegistrationDescriptor {
    OpticRegistrationDescriptor {
        artifact_id: artifact.artifact_id.clone(),
        artifact_hash: artifact.artifact_hash.clone(),
        schema_id: artifact.schema_id.clone(),
        operation_id: artifact.operation.operation_id.clone(),
        requirements_digest: artifact.requirements_digest.clone(),
    }
}

impl OpticArtifactResolver for InMemoryOpticArtifactRegistry {
    fn resolve_optic_artifact(
        &self,
        registration: &OpticRegistrationDescriptor,
    ) -> Result<OpticArtifact, ResolveError> {
        let artifact = self
            .artifacts
            .get(&registration.artifact_id)
            .ok_or_else(|| ResolveError::ArtifactNotFound {
                artifact_id: registration.artifact_id.clone(),
            })?;
        verify_registration_matches_artifact(registration, artifact)?;
        Ok(artifact.clone())
    }
}

fn verify_registration_matches_artifact(
    registration: &OpticRegistrationDescriptor,
    artifact: &OpticArtifact,
) -> Result<(), ResolveError> {
    if registration.artifact_hash != artifact.artifact_hash {
        return Err(ResolveError::ArtifactHashMismatch {
            expected: artifact.artifact_hash.clone(),
            actual: registration.artifact_hash.clone(),
        });
    }

    if registration.schema_id != artifact.schema_id {
        return Err(ResolveError::SchemaIdMismatch {
            expected: artifact.schema_id.clone(),
            actual: registration.schema_id.clone(),
        });
    }

    if registration.operation_id != artifact.operation.operation_id {
        return Err(ResolveError::OperationIdMismatch {
            expected: artifact.operation.operation_id.clone(),
            actual: registration.operation_id.clone(),
        });
    }

    if registration.requirements_digest != artifact.requirements_digest {
        return Err(ResolveError::RequirementsDigestMismatch {
            expected: artifact.requirements_digest.clone(),
            actual: registration.requirements_digest.clone(),
        });
    }

    Ok(())
}

/// Error raised when an optic artifact reference cannot resolve cleanly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolveError {
    /// No artifact exists for the referenced artifact identity.
    ArtifactNotFound {
        /// Artifact identity requested by the descriptor.
        artifact_id: String,
    },
    /// The supplied artifact hash does not match the stored artifact.
    ArtifactHashMismatch {
        /// Artifact hash expected by the stored artifact.
        expected: String,
        /// Artifact hash supplied by the caller.
        actual: String,
    },
    /// The supplied schema id does not match the stored artifact.
    SchemaIdMismatch {
        /// Schema id expected by the stored artifact.
        expected: String,
        /// Schema id supplied by the caller.
        actual: String,
    },
    /// The supplied operation id does not match the stored artifact.
    OperationIdMismatch {
        /// Operation id expected by the stored artifact.
        expected: String,
        /// Operation id supplied by the caller.
        actual: String,
    },
    /// The supplied requirements digest does not match the stored artifact.
    RequirementsDigestMismatch {
        /// Requirements digest expected by the stored artifact.
        expected: String,
        /// Requirements digest supplied by the caller.
        actual: String,
    },
}

impl fmt::Display for ResolveError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ResolveError::ArtifactNotFound { artifact_id } => {
                write!(formatter, "optic artifact '{artifact_id}' was not found")
            }
            ResolveError::ArtifactHashMismatch { expected, actual } => write!(
                formatter,
                "optic artifact hash mismatch: expected '{expected}', got '{actual}'"
            ),
            ResolveError::SchemaIdMismatch { expected, actual } => write!(
                formatter,
                "optic schema id mismatch: expected '{expected}', got '{actual}'"
            ),
            ResolveError::OperationIdMismatch { expected, actual } => write!(
                formatter,
                "optic operation id mismatch: expected '{expected}', got '{actual}'"
            ),
            ResolveError::RequirementsDigestMismatch { expected, actual } => write!(
                formatter,
                "optic requirements digest mismatch: expected '{expected}', got '{actual}'"
            ),
        }
    }
}

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

/// Identity requirement a host/runtime must satisfy before admission.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct IdentityRequirement {
    /// Whether the host/runtime must bind a principal before admission.
    pub required: bool,
    /// Accepted principal kinds, or empty when host policy owns the vocabulary.
    pub accepted_principal_kinds: Vec<String>,
}

/// Opaque principal reference supplied by a host/session layer.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PrincipalRef {
    /// Principal namespace, such as `user`, `agent`, `session`, or `service`.
    pub kind: String,
    /// Principal identifier inside the namespace.
    pub id: String,
}

/// Permission requirement inferred from an optic declaration.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PermissionRequirement {
    /// Required action.
    pub action: PermissionAction,
    /// Resource label the action applies to.
    pub resource: String,
    /// Compiler source of the requirement.
    pub source: String,
}

/// Permission action required for an optic resource label.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PermissionAction {
    /// Read access is required.
    Read,
    /// Write access is required.
    Write,
}

/// Inspectable contract for a selected GraphQL operation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OpticOperation {
    /// Stable operation identity derived from the selected operation shape.
    pub operation_id: String,
    /// Optional GraphQL operation name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// GraphQL operation kind.
    pub kind: OperationKind,
    /// Root schema field selected by the operation.
    pub root_field: String,
    /// Canonical bindings supplied to the selected root field.
    pub root_arguments: Vec<RootArgumentBinding>,
    /// Canonical argument bindings supplied to selected payload fields.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub selection_arguments: Vec<SelectionArgumentBinding>,
    /// Codec shape for the operation variables or root field arguments.
    pub variable_shape: CodecShape,
    /// Codec shape for the selected response payload.
    pub payload_shape: CodecShape,
    /// Directives preserved from the executable operation.
    pub directives: Vec<DirectiveRecord>,
    /// Declared resource footprint, when the operation supplies one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub declared_footprint: Option<Footprint>,
    /// Compiler-produced templates for laws relevant to this operation.
    pub law_claims: Vec<LawClaimTemplate>,
}

/// Canonical binding for one argument supplied to an optic root field.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RootArgumentBinding {
    /// Root argument name.
    pub name: String,
    /// Schema-declared argument type.
    pub type_ref: TypeReference,
    /// Canonical JSON representation of the supplied GraphQL input value.
    pub value_canonical_json: String,
}

/// Canonical binding for one argument supplied to a selected payload field.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SelectionArgumentBinding {
    /// Response-path field that received the argument.
    pub path: String,
    /// Field argument name.
    pub name: String,
    /// Schema-declared argument type.
    pub type_ref: TypeReference,
    /// Canonical JSON representation of the supplied GraphQL input value.
    pub value_canonical_json: String,
}

/// GraphQL executable operation kind.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OperationKind {
    /// GraphQL query operation.
    Query,
    /// GraphQL mutation operation.
    Mutation,
    /// GraphQL subscription operation.
    Subscription,
}

impl From<OperationType> for OperationKind {
    fn from(value: OperationType) -> Self {
        match value {
            OperationType::Query => OperationKind::Query,
            OperationType::Mutation => OperationKind::Mutation,
            OperationType::Subscription => OperationKind::Subscription,
        }
    }
}

impl From<OperationKind> for OperationType {
    fn from(value: OperationKind) -> Self {
        match value {
            OperationKind::Query => OperationType::Query,
            OperationKind::Mutation => OperationType::Mutation,
            OperationKind::Subscription => OperationType::Subscription,
        }
    }
}

/// Named codec view for variables or payload data.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CodecShape {
    /// Logical shape name.
    pub type_name: String,
    /// Fields visible inside the shape.
    pub fields: Vec<CodecField>,
}

/// One field inside a codec shape.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CodecField {
    /// Field name or selected response path.
    pub name: String,
    /// GraphQL type reference for the field.
    pub type_ref: TypeReference,
    /// Whether the field is non-null in the GraphQL type system.
    pub required: bool,
    /// Whether the field has an outer or nested list wrapper.
    pub list: bool,
}

/// Directive preserved from a compiled executable operation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DirectiveRecord {
    /// Schema coordinate or operation coordinate where the directive was found.
    pub coordinate: String,
    /// Directive name without the `@` prefix.
    pub name: String,
    /// Canonical JSON object containing the directive arguments.
    pub arguments_canonical_json: String,
}

/// Declared resource families an operation may read, write, or must not touch.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Footprint {
    /// Resource labels the operation declares it may read.
    pub reads: Vec<String>,
    /// Resource labels the operation declares it may write.
    pub writes: Vec<String>,
    /// Resource labels the operation declares forbidden.
    pub forbids: Vec<String>,
}

/// Compiler-produced declaration that a law is relevant to an operation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct LawClaimTemplate {
    /// Stable law identifier.
    pub law_id: String,
    /// Stable claim identity for this operation and law pairing.
    pub claim_id: String,
    /// Operation identity this claim applies to.
    pub operation_id: String,
    /// Evidence categories a runtime or verifier should produce.
    pub required_evidence: Vec<EvidenceKind>,
}

/// Evidence category requested by a law claim template.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EvidenceKind {
    /// Evidence produced by the Wesley compiler.
    Compiler,
    /// Evidence produced by codec inspection or fixture vectors.
    Codec,
    /// Evidence produced by host/runtime policy.
    HostPolicy,
    /// Evidence produced from runtime trace data.
    RuntimeTrace,
    /// Evidence produced by a domain verifier outside Wesley core.
    DomainVerifier,
}

/// Runtime or verifier-produced verdict for one law claim.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct LawWitness {
    /// Stable law identifier.
    pub law_id: String,
    /// Claim identity this witness evaluates.
    pub claim_id: String,
    /// Optional state basis reference evaluated by the checker.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub basis_ref: Option<String>,
    /// Identifier for the checker that produced the verdict.
    pub checker_id: String,
    /// Optional hash of the checker artifact.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checker_artifact_hash: Option<String>,
    /// Verdict for the law claim.
    pub verdict: LawVerdict,
    /// Digests of evidence artifacts considered by the checker.
    pub evidence_digests: Vec<String>,
    /// Optional digest of the runtime trace considered by the checker.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runtime_trace_digest: Option<String>,
    /// Optional reason for an obstructed verdict.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub obstruction_reason: Option<String>,
    /// Replay hints supplied by the runtime or verifier.
    pub replay_hints: Vec<ReplayHint>,
}

/// Verdict produced for a law claim.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LawVerdict {
    /// The checker found the law satisfied.
    Satisfied,
    /// The checker found a concrete obstruction.
    Obstructed,
    /// The checker cannot establish satisfaction or obstruction.
    Unknown,
}

/// Hint that helps a runtime replay or inspect a witnessed interaction.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ReplayHint {
    /// Hint kind, such as `trace`, `basis`, or `artifact`.
    pub kind: String,
    /// Hint value, intentionally opaque to Wesley core.
    pub value: String,
}