cordance-core 0.1.1

Cordance core types, schemas, and ports. No I/O.
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
//! `pai-axiom-project-harness-target.v1` — verbatim conformance with the
//! axiom schema at `pai-axiom/PAI/Policy/PROJECT_HARNESS_TARGET.schema.json`.
//!
//! Cordance does **not** invent fields here. If axiom adds fields, this
//! struct grows; if axiom changes enum variants, this enum changes. Never the
//! other direction.
//!
//! ## Construction policy (mirrors `receipt.rs`, `BUILD_SPEC` §11.2)
//!
//! Every struct here is marked `#[non_exhaustive]`, so external crates must
//! use the typed `new` constructor on each type rather than struct-literal
//! syntax. Inside this crate, struct-literal construction continues to work
//! for the constructors and unit tests.
//!
//! ## Deserialisation hardening (Round-4 codereview HIGH R4-codereview-1)
//!
//! `#[non_exhaustive]` blocks struct-literal construction across crates, but
//! it does **not** block `serde::Deserialize` from producing values with
//! arbitrary field combinations. A hostile harness-target JSON could
//! deserialise to an `AxiomProjectHarnessTargetV1` whose
//! `harness.allowed_operations` contains `WriteProjectFiles`, by-passing the
//! Cordance construction-time invariants entirely.
//!
//! Two defences ride together — identical to `receipt.rs`:
//!
//! 1. Every struct carries `#[serde(deny_unknown_fields)]`, so an extra key
//!    such as `extra_authority_grant: true` makes the parser error rather
//!    than silently widen the type.
//! 2. [`AxiomProjectHarnessTargetV1::validate_invariants`] re-asserts the
//!    construction-time invariants after deserialisation. External callers
//!    that obtain a harness target via `serde_json::from_slice` (etc.) **must**
//!    run `validate_invariants()` before trusting any field.

use camino::Utf8PathBuf;
use serde::{Deserialize, Serialize};

/// The schema literal is `"pai-axiom-project-harness-target.v1"`. When the
/// `pai-axiom` → `axiom` rename lands in ADR 0045, this constant is the only
/// thing that needs to change.
pub const SCHEMA_LITERAL: &str = "pai-axiom-project-harness-target.v1";

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AxiomProjectHarnessTargetV1 {
    pub schema: String,
    pub version: u32,
    pub project: ProjectBlock,
    pub authority_surfaces: AuthoritySurfaces,
    pub harness: HarnessBlock,
}

impl AxiomProjectHarnessTargetV1 {
    /// Construct an `AxiomProjectHarnessTargetV1`. All fields are required:
    /// this is the only construction path for callers outside this crate
    /// because the struct is `#[non_exhaustive]`.
    #[must_use]
    pub const fn new(
        schema: String,
        version: u32,
        project: ProjectBlock,
        authority_surfaces: AuthoritySurfaces,
        harness: HarnessBlock,
    ) -> Self {
        Self {
            schema,
            version,
            project,
            authority_surfaces,
            harness,
        }
    }

    /// Validate structural invariants after deserialisation.
    ///
    /// External callers MUST run this after any `serde_json::from_slice` /
    /// `serde::Deserialize` call before trusting the harness target. See the
    /// module docs and round-4 codereview HIGH R4-codereview-1.
    ///
    /// # Errors
    /// Returns `HarnessInvariantError` describing the first violated
    /// invariant.
    pub fn validate_invariants(&self) -> Result<(), HarnessInvariantError> {
        // 5. denied_operations ⊇ {WriteProjectFiles, PromoteProjectDoctrine,
        //    MutateRuntimeRoots, ModifyReleaseGates, RewriteAdrs}. Each one
        //    must be explicitly denied so a future field addition can't
        //    silently slip an authority grant past the boundary.
        //
        // (Declared first so clippy::items_after_statements is happy; the
        // *check order* below still runs 1→5 to surface the most obvious
        // violations first.)
        const REQUIRED_DENIED: &[(HarnessOperations, &str)] = &[
            (HarnessOperations::WriteProjectFiles, "write-project-files"),
            (
                HarnessOperations::PromoteProjectDoctrine,
                "promote-project-doctrine",
            ),
            (
                HarnessOperations::MutateRuntimeRoots,
                "mutate-runtime-roots",
            ),
            (
                HarnessOperations::ModifyReleaseGates,
                "modify-release-gates",
            ),
            (HarnessOperations::RewriteAdrs, "rewrite-adrs"),
        ];

        // 1. schema must be the canonical literal.
        if self.schema != SCHEMA_LITERAL {
            return Err(HarnessInvariantError::SchemaMismatch {
                expected: SCHEMA_LITERAL,
                actual: self.schema.clone(),
            });
        }
        // 2. harness.classification must indicate read-only/advisory.
        if self.harness.classification != HarnessClassification::ReadOnlyAdvisory {
            return Err(HarnessInvariantError::NotReadOnlyAdvisory);
        }
        // 3. project.access_mode mirrors the classification check — the only
        //    sanctioned mode at v1 is read-only-advisory.
        if self.project.access_mode != AccessMode::ReadOnlyAdvisory {
            return Err(HarnessInvariantError::NotReadOnlyAdvisory);
        }
        // 4. allowed_operations ⊆ {Inspect, ValidateTarget, EmitCandidateReport}.
        //    Any forbidden token in allowed_operations is a policy violation
        //    that grants axiom write authority Cordance is not entitled to
        //    extend.
        for op in &self.harness.allowed_operations {
            if !matches!(
                op,
                HarnessOperations::Inspect
                    | HarnessOperations::ValidateTarget
                    | HarnessOperations::EmitCandidateReport
            ) {
                return Err(HarnessInvariantError::AllowedOperationForbidden(format!(
                    "{op:?}"
                )));
            }
        }
        // 5. Check the required-denied table (declared at the top of this fn).
        for (op, name) in REQUIRED_DENIED {
            if !self.harness.denied_operations.contains(op) {
                return Err(HarnessInvariantError::DeniedOperationMissing(name));
            }
        }
        Ok(())
    }
}

/// First-violation error from
/// [`AxiomProjectHarnessTargetV1::validate_invariants`].
///
/// Mirrors `ReceiptInvariantError` in `receipt.rs`: the typed shape lets call
/// sites match the specific gate that rejected the value rather than scraping
/// a string.
#[derive(Debug, thiserror::Error)]
pub enum HarnessInvariantError {
    #[error("schema must be {expected:?}, got {actual:?}")]
    SchemaMismatch {
        expected: &'static str,
        actual: String,
    },
    #[error("harness.classification must be read_only_advisory")]
    NotReadOnlyAdvisory,
    #[error("forbidden flag '{0}' was set")]
    ForbiddenFlagSet(&'static str),
    #[error("required denied_operation '{0}' missing")]
    DeniedOperationMissing(&'static str),
    #[error("allowed_operations contains forbidden token '{0}'")]
    AllowedOperationForbidden(String),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ProjectBlock {
    pub name: String,
    pub repo: String,
    pub access_mode: AccessMode,
}

impl ProjectBlock {
    /// Construct a `ProjectBlock`.
    #[must_use]
    pub const fn new(name: String, repo: String, access_mode: AccessMode) -> Self {
        Self {
            name,
            repo,
            access_mode,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AccessMode {
    /// The only mode the axiom schema currently allows.
    ReadOnlyAdvisory,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AuthoritySurfaces {
    pub product_spec: Vec<Utf8PathBuf>,
    pub adrs: Vec<Utf8PathBuf>,
    pub doctrine: Vec<Utf8PathBuf>,
    pub tests_or_evals: Vec<Utf8PathBuf>,
    pub runtime_roots: Vec<Utf8PathBuf>,
    pub release_gates: Vec<Utf8PathBuf>,
}

impl AuthoritySurfaces {
    /// Construct an `AuthoritySurfaces`.
    #[must_use]
    pub const fn new(
        product_spec: Vec<Utf8PathBuf>,
        adrs: Vec<Utf8PathBuf>,
        doctrine: Vec<Utf8PathBuf>,
        tests_or_evals: Vec<Utf8PathBuf>,
        runtime_roots: Vec<Utf8PathBuf>,
        release_gates: Vec<Utf8PathBuf>,
    ) -> Self {
        Self {
            product_spec,
            adrs,
            doctrine,
            tests_or_evals,
            runtime_roots,
            release_gates,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct HarnessBlock {
    pub classification: HarnessClassification,
    pub allowed_operations: Vec<HarnessOperations>,
    pub denied_operations: Vec<HarnessOperations>,
    pub claim_ceiling: ClaimCeiling,
}

impl HarnessBlock {
    /// Construct a `HarnessBlock`.
    #[must_use]
    pub const fn new(
        classification: HarnessClassification,
        allowed_operations: Vec<HarnessOperations>,
        denied_operations: Vec<HarnessOperations>,
        claim_ceiling: ClaimCeiling,
    ) -> Self {
        Self {
            classification,
            allowed_operations,
            denied_operations,
            claim_ceiling,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HarnessClassification {
    ReadOnlyAdvisory,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HarnessOperations {
    Inspect,
    ValidateTarget,
    EmitCandidateReport,
    WriteProjectFiles,
    PromoteProjectDoctrine,
    MutateRuntimeRoots,
    ModifyReleaseGates,
    RewriteAdrs,
}

/// The three-tier ceiling axiom already uses.
/// **Cordance does not add ceilings here. ADR 0008 forbids invented vocab.**
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ClaimCeiling {
    Candidate,
    Partial,
    Advisory,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a canonical harness target that satisfies every invariant. Used
    /// as the starting point for tamper tests, mirroring `valid_receipt()` in
    /// `receipt.rs`.
    fn valid_harness_target() -> AxiomProjectHarnessTargetV1 {
        AxiomProjectHarnessTargetV1::new(
            SCHEMA_LITERAL.into(),
            1,
            ProjectBlock::new("fixture".into(), ".".into(), AccessMode::ReadOnlyAdvisory),
            AuthoritySurfaces::new(
                vec!["README.md".into()],
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
            ),
            HarnessBlock::new(
                HarnessClassification::ReadOnlyAdvisory,
                vec![
                    HarnessOperations::Inspect,
                    HarnessOperations::ValidateTarget,
                    HarnessOperations::EmitCandidateReport,
                ],
                vec![
                    HarnessOperations::WriteProjectFiles,
                    HarnessOperations::PromoteProjectDoctrine,
                    HarnessOperations::MutateRuntimeRoots,
                    HarnessOperations::ModifyReleaseGates,
                    HarnessOperations::RewriteAdrs,
                ],
                ClaimCeiling::Partial,
            ),
        )
    }

    #[test]
    fn schema_literal_matches_axiom_constant() {
        assert_eq!(SCHEMA_LITERAL, "pai-axiom-project-harness-target.v1");
    }

    #[test]
    fn minimum_valid_target() {
        let t = valid_harness_target();
        let s = serde_json::to_string(&t).expect("ser");
        assert!(s.contains("pai-axiom-project-harness-target.v1"));
        assert!(s.contains("read-only-advisory"));
        assert!(s.contains("write-project-files"));
    }

    #[test]
    fn valid_harness_target_passes_invariants() {
        let t = valid_harness_target();
        // Round-trip through JSON, then validate — mirrors the receipt test
        // shape so future contributors can copy the pattern.
        let s = serde_json::to_string(&t).expect("ser");
        let back: AxiomProjectHarnessTargetV1 = serde_json::from_str(&s).expect("de");
        back.validate_invariants()
            .expect("canonical harness target must validate after round-trip");
    }

    /// Round-4 codereview HIGH R4-codereview-1: serde deserialisation
    /// bypasses `#[non_exhaustive]`. A tampered JSON that sets
    /// `harness.classification` to something other than `read-only-advisory`
    /// would currently deserialise (no other variant exists in this enum
    /// today; the test uses the project-level `access_mode` as a proxy by
    /// constructing a value that fails the classification check).
    ///
    /// Since `HarnessClassification` has only one variant right now, the
    /// "tampered" case is exercised by hand-constructing a value with a
    /// mismatched discriminant — the only way to do that without inventing
    /// a new variant is to validate the equality check via a value built
    /// through `new` and then mutate. We instead exercise the
    /// `NotReadOnlyAdvisory` arm by directly hitting `access_mode`'s code
    /// path: see `tampered_access_mode_fails_invariants` below.
    #[test]
    fn tampered_classification_fails_invariants() {
        // The classification enum has only `ReadOnlyAdvisory` today, so the
        // only way to fail the classification gate is for serde to
        // deserialise a JSON whose string literal is canonical but whose
        // sibling `access_mode` field is corrupted. We exercise that path:
        // any non-`read-only-advisory` value for `access_mode` (e.g. a
        // future-added enum variant) would fail the check. To pin the
        // *gate's behaviour* without adding a real enum variant, we
        // synthesise a value whose `access_mode` discriminant has been
        // overwritten by transmute-free means: build the value and replace
        // the field via JSON round-trip with a known-invalid serialisation
        // — serde will refuse to deserialise an unknown variant, so we
        // instead assert that the gate accepts the canonical case here,
        // and rely on the explicit `access_mode` arm in
        // `tampered_access_mode_fails_invariants` for the negative case.
        let t = valid_harness_target();
        t.validate_invariants().expect("canonical case must pass");
    }

    /// Round-4 codereview HIGH R4-codereview-1: when `access_mode` doesn't
    /// match `ReadOnlyAdvisory`, `validate_invariants` must reject. The enum
    /// only has one variant today, so we exercise the gate via the
    /// classification mirror — the implementation uses the same
    /// `NotReadOnlyAdvisory` variant for both.
    #[test]
    fn tampered_access_mode_fails_invariants() {
        // Force the classification check by directly mutating the in-memory
        // value. Tests can use struct-literal construction inside this crate
        // because `#[non_exhaustive]` is a cross-crate barrier only.
        let mut t = valid_harness_target();
        // Today both `AccessMode` and `HarnessClassification` have only the
        // `ReadOnlyAdvisory` variant, so the negative path is exercised via
        // a forbidden allowed_operation instead. See the
        // `tampered_authority_flag_fails_invariants` test for the live
        // tamper case.
        t.harness
            .allowed_operations
            .push(HarnessOperations::WriteProjectFiles);
        let err = t
            .validate_invariants()
            .expect_err("forbidden allowed_operation must fail");
        match err {
            HarnessInvariantError::AllowedOperationForbidden(tok) => {
                assert!(tok.contains("WriteProjectFiles"), "got {tok}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    /// Round-4 codereview HIGH R4-codereview-1: a tampered JSON that pushes
    /// a forbidden token into `allowed_operations` must be rejected by
    /// `validate_invariants` even though it deserialises fine.
    #[test]
    fn tampered_authority_flag_fails_invariants() {
        let t = valid_harness_target();
        let mut value = serde_json::to_value(&t).expect("to_value");
        // Inject a forbidden token into `allowed_operations`.
        value["harness"]["allowed_operations"]
            .as_array_mut()
            .expect("allowed_operations array")
            .push(serde_json::Value::String("mutate-runtime-roots".into()));
        let tampered: AxiomProjectHarnessTargetV1 =
            serde_json::from_value(value).expect("tampered JSON parses");
        let err = tampered
            .validate_invariants()
            .expect_err("tampered allowed_operations must fail");
        match err {
            HarnessInvariantError::AllowedOperationForbidden(tok) => {
                assert!(
                    tok.contains("MutateRuntimeRoots"),
                    "expected MutateRuntimeRoots, got {tok}"
                );
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    /// Round-4 codereview HIGH R4-codereview-1: removing a required denied
    /// operation must fail validation.
    #[test]
    fn missing_required_denied_operation_fails_invariants() {
        let t = valid_harness_target();
        let mut value = serde_json::to_value(&t).expect("to_value");
        // Drop `mutate-runtime-roots` from denied_operations.
        let denied = value["harness"]["denied_operations"]
            .as_array_mut()
            .expect("denied_operations array");
        denied.retain(|v| v.as_str() != Some("mutate-runtime-roots"));
        let tampered: AxiomProjectHarnessTargetV1 =
            serde_json::from_value(value).expect("tampered JSON parses");
        let err = tampered
            .validate_invariants()
            .expect_err("missing required denied_operation must fail");
        match err {
            HarnessInvariantError::DeniedOperationMissing("mutate-runtime-roots") => {}
            other => panic!("unexpected error: {other:?}"),
        }
    }

    /// Round-4 codereview HIGH R4-codereview-1: tampering with the schema
    /// literal must fail validation even though the JSON deserialises.
    #[test]
    fn tampered_schema_fails_invariants() {
        let t = valid_harness_target();
        let mut value = serde_json::to_value(&t).expect("to_value");
        value["schema"] = serde_json::Value::String("not-the-axiom-schema".into());
        let tampered: AxiomProjectHarnessTargetV1 = serde_json::from_value(value).expect("parses");
        let err = tampered.validate_invariants().unwrap_err();
        match err {
            HarnessInvariantError::SchemaMismatch { expected, actual } => {
                assert_eq!(expected, SCHEMA_LITERAL);
                assert_eq!(actual, "not-the-axiom-schema");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    /// Round-4 codereview HIGH R4-codereview-1: extra keys on the top-level
    /// harness target must be rejected by serde itself thanks to
    /// `#[serde(deny_unknown_fields)]`.
    #[test]
    fn unknown_top_level_field_rejected_by_serde() {
        let t = valid_harness_target();
        let mut value = serde_json::to_value(&t).expect("to_value");
        value.as_object_mut().expect("top-level object").insert(
            "extra_authority_grant".into(),
            serde_json::Value::Bool(true),
        );
        let result = serde_json::from_value::<AxiomProjectHarnessTargetV1>(value);
        assert!(
            result.is_err(),
            "extra top-level field must be rejected by deny_unknown_fields"
        );
    }

    /// Round-4 codereview HIGH R4-codereview-1: same defence on the nested
    /// `AuthoritySurfaces` — a hostile peer could try to inject a new
    /// authority field there.
    #[test]
    fn unknown_authority_surfaces_field_rejected_by_serde() {
        let t = valid_harness_target();
        let mut value = serde_json::to_value(&t).expect("to_value");
        value["authority_surfaces"]
            .as_object_mut()
            .expect("authority_surfaces object")
            .insert(
                "runtime_write_capability".into(),
                serde_json::Value::Array(vec![]),
            );
        let result = serde_json::from_value::<AxiomProjectHarnessTargetV1>(value);
        assert!(
            result.is_err(),
            "extra authority_surfaces field must be rejected by deny_unknown_fields"
        );
    }

    /// Defence-in-depth: also check that an extra key on `HarnessBlock` is
    /// rejected.
    #[test]
    fn unknown_harness_block_field_rejected_by_serde() {
        let t = valid_harness_target();
        let mut value = serde_json::to_value(&t).expect("to_value");
        value["harness"]
            .as_object_mut()
            .expect("harness object")
            .insert("cordance_god_mode".into(), serde_json::Value::Bool(true));
        let result = serde_json::from_value::<AxiomProjectHarnessTargetV1>(value);
        assert!(
            result.is_err(),
            "extra harness field must be rejected by deny_unknown_fields"
        );
    }
}