khive-runtime 0.10.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
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
//! Crate-private acceptance harness for ADR-115 Amendment 1's first
//! acceptance rung (executable contract §6; RUN_SPEC item 5; test-plan
//! evidence recorded with the change).
//!
//! `#[cfg(test)]`-only: this module exposes nothing past the crate
//! boundary and touches no public/wire surface.
//!
//! ## Scope note (read before extending)
//!
//! The declared entry points are not yet wired to a real storage backend
//! in this run — `secret_gate_finalizer.rs` states plainly: "Nothing in
//! this module is wired to a caller yet". The executable contract's §6
//! description of the harness (direct FTS/vector/edge/event row queries
//! against a live database) describes the harness *after* the
//! runtime-ingress lane lands the real `FinalizationEffects` backend. That
//! backend does not exist in this worktree yet, so this harness cannot
//! honestly claim to query live storage state for the transactional path.
//! Instead it drives the real, already-implemented `transaction::finalize`
//! state machine end-to-end through an in-memory `FinalizationEffects` fake
//! whose own booleans stand in for record/stamp/audit row existence —
//! every row of [`generated_acceptance_matrix`] that is observable through
//! `finalize` is asserted this way, keyed off the declaration itself so no
//! entry point can be silently skipped. This is recorded as a gap, not
//! substituted silently: see `acceptance_harness.md` "Known gaps".
//!
//! Case kinds that belong to the manifest scanner (legacy-scanner
//! behavior, one-byte miss, wrong-scope miss, one-snapshot refresh race)
//! or the reservation boundary (reserved-key mutation) are not
//! re-implemented here against a second, parallel model of that logic —
//! `manifest.rs` and `secret_gate.rs` already exercise them directly
//! against their real production functions. Duplicating them here would
//! either import `super::manifest`'s helpers under a different name (a
//! shadow harness that could silently drift from the real digest/parse
//! logic) or hand-roll the SHA-256 domain separation a second time, which
//! is exactly the parallel-model risk the contract's "generated, not
//! hand-maintained" principle warns against. Instead this module
//! independently cross-checks the fixed regression vectors (§4 of the
//! contract) against the real `manifest.rs` functions, and documents the
//! per-case ownership mapping in `acceptance_harness.md`.

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use uuid::Uuid;

    use crate::secret_gate::reject_reserved_secret_gate_property;
    use crate::secret_gate_finalizer::declaration::{
        Substrate as DeclSubstrate, FINALIZER_ENTRY_POINTS,
    };
    use crate::secret_gate_finalizer::faults;
    use crate::secret_gate_finalizer::log_sink::CapturingLogSink;
    use crate::secret_gate_finalizer::manifest::fixture::TestOnlyManifestFixture;
    use crate::secret_gate_finalizer::manifest::{
        canonical_empty_document_sha256_hex, digest_to_hex, resolve_match, scoped_digest,
        ManifestManager, ManifestSnapshot, RuntimeFieldScope,
    };
    use crate::secret_gate_finalizer::matrix::{generated_acceptance_matrix, MatrixCaseKind};
    use crate::secret_gate_finalizer::outcome::{
        FailureClass, FailureDiagnostic, FinalizerOutcome, ManifestFault, Substrate,
    };
    use crate::secret_gate_finalizer::transaction::{
        finalize, ExemptionMatch, FinalizationEffects, FinalizationInput,
    };

    /// In-memory `FinalizationEffects` used only by this harness. Mirrors
    /// `transaction.rs`'s own `FakeEffects` test double, but is driven from
    /// declaration-derived rows rather than one hand-picked entry point, so
    /// coverage is provably tied to every row of the generated matrix.
    #[derive(Default)]
    struct AcceptanceEffects {
        record_written: bool,
        stamp_written: bool,
        audit_written: bool,
        failure_audits: Vec<FailureDiagnostic>,
    }

    impl AcceptanceEffects {
        fn state(&self) -> (bool, bool, bool) {
            (self.record_written, self.stamp_written, self.audit_written)
        }
    }

    impl FinalizationEffects for AcceptanceEffects {
        fn resolve_manifest(&mut self) -> Result<ExemptionMatch, ManifestFault> {
            Ok(ExemptionMatch {
                digest_sha256: digest_to_hex(&scoped_digest(
                    RuntimeFieldScope::RecordContent,
                    "acceptance-harness-fixture-value",
                )),
                field_scope: "record-content",
                manifest_id: "khive-secret-gate-empty-v1".to_string(),
            })
        }

        fn write_record(&mut self) -> Result<(), ()> {
            self.record_written = true;
            Ok(())
        }

        fn write_stamp(&mut self) -> Result<(), ()> {
            self.stamp_written = true;
            Ok(())
        }

        fn write_success_audit(&mut self) -> Result<(), ()> {
            self.audit_written = true;
            Ok(())
        }

        fn rollback(&mut self) {
            self.record_written = false;
            self.stamp_written = false;
            self.audit_written = false;
        }

        fn write_failure_audit(&mut self, diagnostic: &FailureDiagnostic) -> Result<(), ()> {
            self.failure_audits.push(diagnostic.clone());
            Ok(())
        }
    }

    fn substrate_for(decl: DeclSubstrate) -> Substrate {
        match decl {
            DeclSubstrate::Entity => Substrate::Entity,
            DeclSubstrate::Note => Substrate::Note,
        }
    }

    /// The generated-matrix case kinds that are observable through
    /// `transaction::finalize` (the rest belong to the manifest scanner or
    /// reservation boundary; see the module doc comment).
    const FINALIZE_OBSERVABLE: &[MatrixCaseKind] = &[
        MatrixCaseKind::FixtureMatch,
        MatrixCaseKind::SupportedEcho,
        MatrixCaseKind::RecordWriteFailure,
        MatrixCaseKind::StampFailure,
        MatrixCaseKind::SuccessAuditFailure,
        MatrixCaseKind::SecondOrderFailureAuditFailure,
    ];

    /// The generated-matrix case kinds `transaction::finalize` structurally
    /// never observes — not a storage-wiring gap but a permanent property of
    /// the design: a manifest miss (`LegacyScannerBehavior`, `OneByteMiss`,
    /// `WrongScopeMiss`) "falls through to the unchanged legacy scanner" and
    /// never reaches `finalize` at all (see `outcome::ManifestFault`'s own
    /// doc comment), a caller-supplied reserved key (`ReservedKeyMutation`)
    /// is rejected at the reservation boundary before any candidate is
    /// constructed, and the one-snapshot invariant (`OneSnapshotRefreshRace`)
    /// governs how a candidate obtains its `ManifestSnapshot` *before*
    /// `finalize` is ever called, not anything `finalize` itself decides.
    /// Each is still driven through its real, owning production function
    /// below (`deferred_case_kinds_are_covered_by_their_owning_functions`)
    /// rather than silently skipped — see that test and its doc comment for
    /// the per-case mapping.
    const DEFERRED_TO_OWNING_FUNCTION: &[MatrixCaseKind] = &[
        MatrixCaseKind::LegacyScannerBehavior,
        MatrixCaseKind::OneByteMiss,
        MatrixCaseKind::WrongScopeMiss,
        MatrixCaseKind::ReservedKeyMutation,
        MatrixCaseKind::OneSnapshotRefreshRace,
    ];

    /// Deliverables 2 + 3: drive every generated-matrix row whose case kind
    /// is finalize-observable, for every declared entry point, using the
    /// entry point's own id/substrate straight off the declaration row --
    /// never a hand-picked entry point or a second, independently
    /// maintained list. Asserts the exact outcome variant, that a failure
    /// path leaves state byte-for-byte equal to pre-transaction state (no
    /// survivor), and the second-order audit-gap sink behavior.
    #[test]
    fn generated_matrix_drives_finalize_for_every_declared_entry_point() {
        let rows = generated_acceptance_matrix();
        assert_eq!(
            rows.len(),
            FINALIZER_ENTRY_POINTS.len() * MatrixCaseKind::ALL.len(),
            "harness must consume the full generated cross product, not a subset"
        );

        let mut covered: BTreeSet<(&str, MatrixCaseKind)> = BTreeSet::new();
        let pre_state = AcceptanceEffects::default().state();

        for row in &rows {
            if !FINALIZE_OBSERVABLE.contains(&row.case) {
                continue;
            }
            let ns = format!("acceptance-{}-{:?}", row.entry_point.id, row.case);
            let input = FinalizationInput {
                record_id: Uuid::new_v4(),
                substrate: substrate_for(row.entry_point.substrate),
                namespace: ns.clone(),
                entry_point: row.entry_point.id,
            };

            match row.case {
                MatrixCaseKind::FixtureMatch | MatrixCaseKind::SupportedEcho => {
                    let mut effects = AcceptanceEffects::default();
                    let sink = CapturingLogSink::new();
                    let outcome = finalize(&mut effects, &sink, &input);
                    match &outcome {
                        FinalizerOutcome::Exempted(commit) => {
                            assert_eq!(commit.entry_point, row.entry_point.id);
                            assert_eq!(commit.record_id, input.record_id);
                        }
                        other => panic!(
                            "{}/{:?}: expected Exempted, got {other:?}",
                            row.entry_point.id, row.case
                        ),
                    }
                    assert_eq!(effects.state(), (true, true, true));
                    assert!(sink.snapshot().is_empty());
                }
                MatrixCaseKind::RecordWriteFailure => {
                    let _arm = faults::arm_record_write_fail(&ns);
                    let mut effects = AcceptanceEffects::default();
                    let sink = CapturingLogSink::new();
                    let outcome = finalize(&mut effects, &sink, &input);
                    match outcome {
                        FinalizerOutcome::RecordWriteFailed(d) => {
                            assert_eq!(d.failure_class, FailureClass::RecordWrite);
                            assert_eq!(d.entry_point, row.entry_point.id);
                        }
                        other => panic!(
                            "{}/{:?}: expected RecordWriteFailed, got {other:?}",
                            row.entry_point.id, row.case
                        ),
                    }
                    assert_eq!(
                        effects.state(),
                        pre_state,
                        "{}/{:?}: no partial mutation may survive rollback",
                        row.entry_point.id,
                        row.case
                    );
                    assert_eq!(effects.failure_audits.len(), 1);
                    assert!(sink.snapshot().is_empty());
                }
                MatrixCaseKind::StampFailure => {
                    let _arm = faults::arm_stamp_fail(&ns);
                    let mut effects = AcceptanceEffects::default();
                    let sink = CapturingLogSink::new();
                    let outcome = finalize(&mut effects, &sink, &input);
                    match outcome {
                        FinalizerOutcome::StampFailed(d) => {
                            assert_eq!(d.failure_class, FailureClass::Stamp)
                        }
                        other => panic!(
                            "{}/{:?}: expected StampFailed, got {other:?}",
                            row.entry_point.id, row.case
                        ),
                    }
                    assert_eq!(effects.state(), pre_state);
                }
                MatrixCaseKind::SuccessAuditFailure => {
                    let _arm = faults::arm_success_audit_fail(&ns);
                    let mut effects = AcceptanceEffects::default();
                    let sink = CapturingLogSink::new();
                    let outcome = finalize(&mut effects, &sink, &input);
                    match outcome {
                        FinalizerOutcome::AuditFailed(d) => {
                            assert_eq!(d.failure_class, FailureClass::SuccessAudit)
                        }
                        other => panic!(
                            "{}/{:?}: expected AuditFailed, got {other:?}",
                            row.entry_point.id, row.case
                        ),
                    }
                    assert_eq!(effects.state(), pre_state);
                }
                MatrixCaseKind::SecondOrderFailureAuditFailure => {
                    let _record_arm = faults::arm_record_write_fail(&ns);
                    let _failure_audit_arm = faults::arm_failure_audit_fail(&ns);
                    let mut effects = AcceptanceEffects::default();
                    let sink = CapturingLogSink::new();
                    let outcome = finalize(&mut effects, &sink, &input);
                    let diagnostic = match outcome {
                        FinalizerOutcome::RecordWriteFailed(d) => d,
                        other => panic!(
                            "{}/{:?}: expected RecordWriteFailed, got {other:?}",
                            row.entry_point.id, row.case
                        ),
                    };
                    assert_eq!(
                        effects.state(),
                        pre_state,
                        "second-order case must still leave no survivor"
                    );
                    assert!(
                        effects.failure_audits.is_empty(),
                        "failure-audit write was injected to fail; nothing should have recorded"
                    );
                    let gaps = sink.snapshot();
                    assert_eq!(
                        gaps.len(),
                        1,
                        "exactly one independent audit-gap record for the second-order case"
                    );
                    assert_eq!(gaps[0].diagnostic_id, diagnostic.diagnostic_id);
                    assert_eq!(gaps[0].entry_point, row.entry_point.id);
                    assert_eq!(gaps[0].failure_class, FailureClass::RecordWrite);
                }
                _ => unreachable!("filtered by FINALIZE_OBSERVABLE above"),
            }

            covered.insert((row.entry_point.id, row.case));
        }

        for ep in FINALIZER_ENTRY_POINTS {
            for case in FINALIZE_OBSERVABLE {
                assert!(
                    covered.contains(&(ep.id, *case)),
                    "missing acceptance coverage for {}/{:?}",
                    ep.id,
                    case
                );
            }
        }
    }

    /// Completeness: every one of `MatrixCaseKind::ALL` is
    /// exactly one of finalize-observable or explicitly deferred — no third,
    /// silently-skipped category exists. The generator (`matrix.rs`) is the
    /// sole source of the row set; this test only asserts the two constant
    /// lists above partition it exactly, so a newly added `MatrixCaseKind`
    /// variant that nobody classified fails this test instead of silently
    /// vanishing from coverage.
    #[test]
    fn finalize_observable_and_deferred_partition_every_case_kind_exactly() {
        let observable: BTreeSet<MatrixCaseKind> = FINALIZE_OBSERVABLE.iter().copied().collect();
        let deferred: BTreeSet<MatrixCaseKind> =
            DEFERRED_TO_OWNING_FUNCTION.iter().copied().collect();
        assert!(
            observable.is_disjoint(&deferred),
            "a case kind must not be both finalize-observable and deferred"
        );
        let union: BTreeSet<MatrixCaseKind> = observable.union(&deferred).copied().collect();
        let all: BTreeSet<MatrixCaseKind> = MatrixCaseKind::ALL.iter().copied().collect();
        assert_eq!(
            union, all,
            "every declared MatrixCaseKind must be finalize-observable or explicitly deferred"
        );
    }

    /// Completeness: every entry in `DEFERRED_TO_OWNING_FUNCTION`
    /// is driven through the real production function that owns it — not
    /// re-implemented as a second, parallel model, and not silently skipped.
    /// This runs once per case kind, not once per declared entry point,
    /// because the manifest scanner and reservation boundary behave
    /// identically regardless of which of the six entry points a candidate
    /// originated from: entry-point identity plays no role in manifest
    /// digest matching or reservation-key rejection.
    #[test]
    fn deferred_case_kinds_are_covered_by_their_owning_functions() {
        // LegacyScannerBehavior: on the production-default empty manifest,
        // `resolve_match` reports no candidate hit (falls through), and the
        // pre-existing legacy `secret_gate::check` still rejects
        // secret-shaped content exactly as it did before this finalizer
        // existed — ADR-115 added no new admission path around it.
        let empty = ManifestSnapshot::empty();
        let secret_like = "AKIAFAKELEGACYSCANNER0000000000";
        let scanned = [(RuntimeFieldScope::RecordContent, secret_like)];
        assert_eq!(
            resolve_match(&empty, &scanned).expect("empty snapshot never faults"),
            None,
            "LegacyScannerBehavior: empty manifest must report no candidate hit"
        );
        assert!(
            crate::secret_gate::check(secret_like).is_err(),
            "LegacyScannerBehavior: the unchanged legacy scanner must still reject \
             secret-shaped content when no manifest entry matches"
        );

        // OneByteMiss: a fixture's exact value hits; the same value with its
        // last byte mutated misses, through the real `resolve_match`.
        let fixture = TestOnlyManifestFixture::new();
        let fixture_snapshot = fixture.snapshot();
        let exact = fixture.exact_value();
        assert!(
            resolve_match(&fixture_snapshot, &[(fixture.field_scope(), exact)])
                .expect("fixture snapshot never faults")
                .is_some(),
            "OneByteMiss baseline: the exact fixture value must hit"
        );
        let mut mutated = exact.as_bytes().to_vec();
        let last = mutated.len() - 1;
        mutated[last] = mutated[last].wrapping_add(1);
        let mutated = String::from_utf8(mutated).expect("mutated byte stays valid UTF-8");
        assert_eq!(
            resolve_match(
                &fixture_snapshot,
                &[(fixture.field_scope(), mutated.as_str())]
            )
            .expect("fixture snapshot never faults"),
            None,
            "OneByteMiss: a one-byte-mutated value must miss"
        );

        // WrongScopeMiss: the exact same value, looked up under a different
        // `RuntimeFieldScope` than the one it was entered under, must miss.
        let wrong_scope = if fixture.field_scope() == RuntimeFieldScope::RecordContent {
            RuntimeFieldScope::NameDescription
        } else {
            RuntimeFieldScope::RecordContent
        };
        assert_eq!(
            resolve_match(&fixture_snapshot, &[(wrong_scope, exact)])
                .expect("fixture snapshot never faults"),
            None,
            "WrongScopeMiss: the same exact value under the wrong scope must miss"
        );

        // ReservedKeyMutation: the one shared reservation validator, called
        // directly against a top-level occurrence of the reserved key.
        let reserved =
            serde_json::json!({"khive:secret_gate": "exempted:content-sha256-manifest-v1"});
        assert!(
            reject_reserved_secret_gate_property(Some(&reserved)).is_err(),
            "ReservedKeyMutation: the shared reservation validator must reject the key"
        );

        // OneSnapshotRefreshRace: a snapshot cloned via `ManifestManager::current`
        // before a later `refresh` must not observe that refresh — see
        // `manifest::tests::snapshot_taken_before_refresh_is_unaffected_by_a_later_refresh`
        // for the full end-to-end regression; this call proves the same
        // manager type is reachable and behaves identically from this module.
        let manager = ManifestManager::new();
        let pinned = manager.current();
        assert!(
            pinned.is_empty(),
            "manager starts on the empty default snapshot"
        );
        let _ = manager.refresh(None, None);
        assert!(
            pinned.is_empty(),
            "OneSnapshotRefreshRace: a snapshot cloned before refresh must stay pinned"
        );
    }

    /// Deliverable 1: universal reservation, exercised through the crate's
    /// one reservation surface (`reject_reserved_secret_gate_property`)
    /// across every operation-shape value that a create/patch/replace/
    /// merge/remove caller could present at the top level of `properties`.
    #[test]
    fn reservation_rejects_top_level_key_regardless_of_value_shape() {
        for value in [
            serde_json::json!("exempted:content-sha256-manifest-v1"),
            serde_json::json!("something-else-entirely"),
            serde_json::json!(null),
            serde_json::json!(42),
            serde_json::json!({"nested": true}),
            serde_json::json!([1, 2, 3]),
        ] {
            let props = serde_json::json!({ "khive:secret_gate": value, "other": "ok" });
            assert!(
                reject_reserved_secret_gate_property(Some(&props)).is_err(),
                "reservation must reject top-level key regardless of value shape: {props}"
            );
        }
    }

    /// Reservation must not over-reject: absent properties and a
    /// same-named key nested below the top level are ordinary content.
    #[test]
    fn reservation_allows_absent_properties_and_nested_occurrences() {
        assert!(reject_reserved_secret_gate_property(None).is_ok());
        let nested = serde_json::json!({"notes": {"khive:secret_gate": "not-a-stamp"}});
        assert!(reject_reserved_secret_gate_property(Some(&nested)).is_ok());
    }

    /// Deliverable 4: the closed v1 empty-value digest vectors, called
    /// through the real `manifest.rs` production functions (not a second,
    /// independently maintained SHA-256 implementation) and cross-checked
    /// byte-exact against the executable contract's fixed table
    /// (ADR-115 Amendment 1 §4).
    #[test]
    fn manifest_empty_value_vectors_match_the_executable_contract_table() {
        let vectors: &[(RuntimeFieldScope, &str)] = &[
            (
                RuntimeFieldScope::RecordContent,
                "8babc16495ddbc04d2fd382d3b423d452bedb7567e64cfbe5bb85a5bcb4ff04a",
            ),
            (
                RuntimeFieldScope::NameDescription,
                "db6c4a6305fabfdc246bfc3f37cba55907ee65e5035827f06598a37b478e97d1",
            ),
            (
                RuntimeFieldScope::JsonProperties,
                "2d1a970af8016a1721b1457c7675b08355b6da0b3c859934da1fabf7e660ee28",
            ),
            (
                RuntimeFieldScope::Tags,
                "a1037f3591a751f9d34748fd090a4551d87cbdbb819e7b612e470b6a3a58f833",
            ),
            (
                RuntimeFieldScope::CodeSource,
                "1a53a3a30c62d6c805aabd11ace2124699821b5f046df4c08cf96ac9fa18e892",
            ),
        ];
        for (scope, expected) in vectors {
            let actual = digest_to_hex(&scoped_digest(*scope, ""));
            assert_eq!(
                &actual, expected,
                "empty-value vector mismatch for {scope:?}"
            );
            assert_eq!(actual.len(), 64, "SHA-256 hex must be exactly 64 chars");
        }
    }

    /// Deliverable 4: the canonical EMPTY manifest document's exact bytes
    /// and its regression hash, called through the real production
    /// function and cross-checked against the contract's fixed value.
    #[test]
    fn canonical_empty_document_hash_matches_the_executable_contract_value() {
        let expected = "ee4e2ab801099252459bcf930583bed9e8107aad2cc7af2db361f85ee65a31b9";
        let actual = canonical_empty_document_sha256_hex();
        assert_eq!(actual.len(), 64);
        assert_eq!(actual, expected);
    }
}