wesley-core 0.2.0

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
//! Operation artifact models.
//!
//! These types are intentionally domain-empty. They describe the GraphQL
//! operation shape, declared bounds, and law claims that an external target can
//! import, evaluate, 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 operation artifact contract requirements.
pub const OPERATION_REQUIREMENTS_ARTIFACT_CODEC: &str = "wesley.requirements.canonical-json.v0";

/// Compiled contract for one GraphQL operation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OperationArtifact {
    /// 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 contract requirements and law claim templates.
    pub requirements_digest: String,
    /// Wesley-owned canonical byte artifact for contract requirements.
    pub requirements_artifact: OperationRequirementsArtifact,
    /// The selected GraphQL operation compiled into an inspectable contract.
    pub operation: CompiledOperation,
    /// Compiler-described requirements an external target may evaluate.
    pub requirements: OperationRequirements,
    /// Descriptor an application can present when registering this artifact.
    pub registration: OperationRegistrationDescriptor,
}

/// Wesley-produced descriptor for registering a compiled operation artifact.
///
/// This is not a runtime handle and it is not an authority grant. It is a small
/// descriptor an external target can compare with the full artifact before it
/// stores or imports compiler-produced evidence.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OperationRegistrationDescriptor {
    /// 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 contract requirements and law claim templates.
    pub requirements_digest: String,
}

/// Contract requirements for an operation artifact.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OperationRequirements {
    /// Identity binding described by the compiler.
    pub identity: IdentityRequirement,
    /// Permission requirements inferred from the declared operation bounds.
    pub required_permissions: Vec<PermissionRequirement>,
    /// Resource labels that must remain inaccessible to the operation.
    pub forbidden_resources: Vec<String>,
}

/// Wesley-owned canonical contract 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
/// target-owned truth.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OperationRequirementsArtifact {
    /// 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>,
}

/// Artifact resolver input accepted by Wesley-side registries.
pub type OperationArtifactRef = OperationRegistrationDescriptor;

/// Resolves compiled operation artifacts from registration descriptors.
pub trait OperationArtifactResolver {
    /// Resolves a registration descriptor to its full compiled artifact and
    /// verifies the descriptor still matches artifact identity and requirements.
    fn resolve_operation_artifact(
        &self,
        registration: &OperationRegistrationDescriptor,
    ) -> Result<OperationArtifact, ResolveError>;
}

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

impl InMemoryOperationArtifactRegistry {
    /// 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: OperationArtifact) -> OperationRegistrationDescriptor {
        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: &OperationArtifact,
) -> OperationRegistrationDescriptor {
    OperationRegistrationDescriptor {
        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 OperationArtifactResolver for InMemoryOperationArtifactRegistry {
    fn resolve_operation_artifact(
        &self,
        registration: &OperationRegistrationDescriptor,
    ) -> Result<OperationArtifact, 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: &OperationRegistrationDescriptor,
    artifact: &OperationArtifact,
) -> 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 operation 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,
                    "operation artifact '{artifact_id}' was not found"
                )
            }
            ResolveError::ArtifactHashMismatch { expected, actual } => write!(
                formatter,
                "operation artifact hash mismatch: expected '{expected}', got '{actual}'"
            ),
            ResolveError::SchemaIdMismatch { expected, actual } => write!(
                formatter,
                "operation artifact schema id mismatch: expected '{expected}', got '{actual}'"
            ),
            ResolveError::OperationIdMismatch { expected, actual } => write!(
                formatter,
                "operation artifact id mismatch: expected '{expected}', got '{actual}'"
            ),
            ResolveError::RequirementsDigestMismatch { expected, actual } => write!(
                formatter,
                "operation requirements digest mismatch: expected '{expected}', got '{actual}'"
            ),
        }
    }
}

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

/// Identity requirement described by compiler output.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct IdentityRequirement {
    /// Whether an external target is expected to bind a principal.
    pub required: bool,
    /// Accepted principal kinds, or empty when target policy owns the vocabulary.
    pub accepted_principal_kinds: Vec<String>,
}

/// Permission requirement inferred from an operation 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 operation 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 CompiledOperation {
    /// 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 operation 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,
}