lifeloop-cli 0.3.0

Provider-neutral lifecycle abstraction and normalizer for AI harnesses
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
//! Spec ↔ code alignment guard.
//!
//! Pins `src/lib.rs` against the wire vocabularies declared in
//! `docs/specs/lifecycle-contract/body.md`. This is a **drift detector**, not
//! a wire-shape pin (`tests/wire_contract.rs` does that). The two tests
//! enforce different invariants:
//!
//!   - `wire_contract.rs` — "the JSON shape we serialize must not change
//!     accidentally." Pins the *current* implementation.
//!   - `spec_alignment.rs` — "the implementation must continue to mean
//!     what the spec says it means." Pins against the *target*.
//!
//! Pre-freeze `lifeloop.v0.x` is allowed to break across minor bumps;
//! when this test fails, the failure list IS the migration checklist.
//! Each `#[ignore]`d assertion below is paired with a TODO note naming
//! the issue or tombstone that owns the gap.
//!
//! Vocabularies are hand-encoded as Rust constants per issue #17. A later
//! follow-up may extract them into a machine-readable artifact — see
//! `#17`'s Notes section for the layered plan.

use lifeloop::{
    AcceptablePlacement, AdapterRole, CapabilityDegradation, FailureClass, FrameClass,
    FrameContext, IntegrationMode, LifecycleEventKind, LifecycleReceipt, NegotiationOutcome,
    PayloadEnvelope, PayloadReceipt, PlacementClass, PlacementOutcome, ReceiptStatus,
    RequirementLevel, RetryClass, SCHEMA_VERSION, SupportState, Warning,
};
use serde_json::Value;
use std::collections::BTreeMap;

// ============================================================================
// Vocabularies (hand-encoded from docs/specs/lifecycle-contract/body.md tables)
// ============================================================================

/// The pre-freeze schema-version label.
///
/// **Known divergence from the spec body.** The spec's three illustrative
/// JSON payloads (`docs/specs/lifecycle-contract/body.md` lines 131, 295, 365)
/// use `"schema_version": 1` (integer placeholder), but the spec narrative
/// names the wire-stable version `lifeloop.v0.2` (e.g. lines about the
/// `v0.x → v1` lifecycle gate). The implementation follows the narrative
/// — the JSON payloads in the spec examples appear to be placeholders.
/// Tracked for spec amendment; until then, this constant pins the version
/// label the implementation actually emits.
const SPEC_SCHEMA_VERSION_LABEL: &str = "lifeloop.v0.2";

const SPEC_LIFECYCLE_EVENTS: &[&str] = &[
    "session.starting",
    "session.started",
    "frame.opening",
    "frame.opened",
    "context.pressure_observed",
    "context.compacted",
    "frame.ending",
    "frame.ended",
    "session.ending",
    "session.ended",
    "supervisor.tick",
    "capability.degraded",
    "receipt.emitted",
    "receipt.gap_detected",
];

const SPEC_INTEGRATION_MODES: &[&str] = &[
    "manual_skill",
    "launcher_wrapper",
    "native_hook",
    "reference_adapter",
    "telemetry_only",
];

const SPEC_SUPPORT_STATES: &[&str] = &["native", "synthesized", "manual", "partial", "unavailable"];

/// Trust-neutral manifest placement classes per
/// `docs/specs/lifecycle-contract/body.md` ("Manifest placement classes").
/// Distinct from `SPEC_PLACEMENT_CLASSES` which describes payload
/// routing — see the spec note on the two vocabularies.
const SPEC_MANIFEST_PLACEMENT_CLASSES: &[&str] = &[
    "pre_session",
    "pre_frame_leading",
    "pre_frame_trailing",
    "tool_result",
    "manual_operator",
];

const SPEC_ADAPTER_ROLES: &[&str] = &["primary_worker", "worker", "supervisor", "observer"];

const SPEC_RECEIPT_STATUSES: &[&str] = &["observed", "delivered", "skipped", "degraded", "failed"];

const SPEC_FAILURE_CLASSES: &[&str] = &[
    "adapter_unavailable",
    "capability_unsupported",
    "capability_degraded",
    "placement_unavailable",
    "payload_too_large",
    "payload_rejected",
    "identity_unavailable",
    "transport_error",
    "timeout",
    "operator_required",
    "state_conflict",
    "invalid_request",
    "internal_error",
];

const SPEC_RETRY_CLASSES: &[&str] = &[
    "safe_retry",
    "retry_after_reread",
    "retry_after_reconfigure",
    "retry_after_operator",
    "do_not_retry",
];

const SPEC_PLACEMENT_CLASSES: &[&str] = &[
    "developer_equivalent_frame",
    "pre_prompt_frame",
    "side_channel_context",
    "receipt_only",
];

const SPEC_PLACEMENT_OUTCOMES: &[&str] = &["delivered", "skipped", "degraded", "failed"];

const SPEC_REQUIREMENT_LEVELS: &[&str] = &["required", "preferred", "optional"];

const SPEC_NEGOTIATION_OUTCOMES: &[&str] =
    &["satisfied", "degraded", "unsupported", "requires_operator"];

/// Spec receipt schema. Each entry is (field_name, "required"|"required_nullable"|"optional").
/// "required_nullable" means the key is always present but may be null
/// (per the spec: *"sequence is required and nullable", "parent_receipt_id is required and nullable"*).
const SPEC_LIFECYCLE_RECEIPT_FIELDS: &[(&str, &str)] = &[
    ("schema_version", "required"),
    ("receipt_id", "required"),
    ("idempotency_key", "required_nullable"),
    ("client_id", "required"),
    ("adapter_id", "required"),
    ("invocation_id", "required"),
    ("event", "required"),
    ("event_id", "required"),
    ("sequence", "required_nullable"),
    ("parent_receipt_id", "required_nullable"),
    ("integration_mode", "required"),
    ("status", "required"),
    ("at_epoch_s", "required"),
    ("harness_session_id", "optional"),
    ("harness_run_id", "optional"),
    ("harness_task_id", "optional"),
    ("payload_receipts", "optional"),
    ("telemetry_summary", "optional"),
    ("capability_degradations", "optional"),
    ("failure_class", "required_nullable"),
    ("retry_class", "required_nullable"),
    ("warnings", "optional"),
];

/// Spec payload-envelope schema. Per the spec table; `body` and `body_ref`
/// are individually optional but mutually exclusive (validation rule, not
/// a JSON-shape rule).
const SPEC_PAYLOAD_ENVELOPE_FIELDS: &[(&str, &str)] = &[
    ("schema_version", "required"),
    ("payload_id", "required"),
    ("client_id", "required"),
    ("payload_kind", "required"),
    ("format", "required"),
    ("content_encoding", "required"),
    ("body", "optional"),
    ("body_ref", "optional"),
    ("byte_size", "required"),
    ("content_digest", "optional"),
    ("acceptable_placements", "required"),
    ("idempotency_key", "optional"),
    ("expires_at_epoch_s", "optional"),
    ("redaction", "optional"),
    ("metadata", "optional"),
];

const SPEC_PAYLOAD_RECEIPT_FIELDS: &[(&str, &str)] = &[
    ("payload_id", "required"),
    ("payload_kind", "required"),
    ("placement", "required"),
    ("status", "required"),
    ("byte_size", "required"),
    ("content_digest", "optional"),
];

/// **Self-referential — known gap.** The spec body has no FrameContext
/// table; the values below are inferred from the spec narrative ("a
/// recursive client may create nested frames", `frame_class = subcall`
/// requires `parent_frame_id`). Drift between this constant and the
/// FrameContext struct will not be caught until the spec adds an
/// authoritative table. Tracked as a follow-up to #17.
const SPEC_FRAME_CONTEXT_FIELDS: &[(&str, &str)] = &[
    ("frame_id", "required"),
    ("parent_frame_id", "optional"),
    ("frame_class", "required"),
];

/// Spec adapter manifest schema. Transcribed from the "Required
/// manifest fields" and "Optional manifest fields" tables in
/// `docs/specs/lifecycle-contract/body.md` after the issue #6 spec
/// reconciliation. Issue #6 owns the structured shape; issue #20
/// or later may evolve it.
const SPEC_ADAPTER_MANIFEST_FIELDS: &[(&str, &str)] = &[
    ("contract_version", "required"),
    ("adapter_id", "required"),
    ("adapter_version", "required"),
    ("display_name", "required"),
    ("role", "required"),
    ("integration_modes", "required"),
    ("lifecycle_events", "required"),
    ("placement", "required"),
    ("context_pressure", "required"),
    ("receipts", "required"),
    ("session_identity", "optional"),
    ("session_rename", "optional"),
    ("renewal", "optional"),
    ("approval_surface", "optional"),
    ("failure_modes", "optional"),
    ("telemetry_sources", "optional"),
    ("known_degradations", "optional"),
];

/// Spec failure → default-retry mapping table.
const SPEC_FAILURE_TO_RETRY: &[(&str, &str)] = &[
    ("adapter_unavailable", "retry_after_reconfigure"),
    ("capability_unsupported", "do_not_retry"),
    ("capability_degraded", "retry_after_reread"),
    ("placement_unavailable", "retry_after_reconfigure"),
    ("payload_too_large", "do_not_retry"),
    ("payload_rejected", "retry_after_reconfigure"),
    ("identity_unavailable", "retry_after_reconfigure"),
    ("transport_error", "safe_retry"),
    ("timeout", "safe_retry"),
    ("operator_required", "retry_after_operator"),
    ("state_conflict", "retry_after_reread"),
    ("invalid_request", "do_not_retry"),
    ("internal_error", "retry_after_reread"),
];

// ============================================================================
// Helpers
// ============================================================================

fn wire_names<T: serde::Serialize>(values: &[T]) -> Vec<String> {
    values
        .iter()
        .map(|v| {
            serde_json::to_value(v)
                .expect("serialize")
                .as_str()
                .expect("string wire name")
                .to_string()
        })
        .collect()
}

fn json_keys(value: &Value) -> Vec<String> {
    match value {
        Value::Object(map) => map.keys().cloned().collect(),
        _ => panic!("expected JSON object, got {value:?}"),
    }
}

fn assert_keys_match_spec(actual: &Value, spec: &[(&str, &str)], type_name: &str) {
    let keys: Vec<String> = json_keys(actual);
    let expected: Vec<String> = spec.iter().map(|(name, _)| name.to_string()).collect();
    let missing: Vec<&String> = expected.iter().filter(|n| !keys.contains(n)).collect();
    let extra: Vec<&String> = keys
        .iter()
        .filter(|n| !spec.iter().any(|(s, _)| *s == n.as_str()))
        .collect();
    assert!(
        missing.is_empty() && extra.is_empty(),
        "{type_name} fields drift from spec:\n  missing: {missing:?}\n  extra:   {extra:?}\n  spec:    {expected:?}\n  actual:  {keys:?}"
    );
}

// ============================================================================
// Schema version
// ============================================================================

#[test]
fn schema_version_label_matches_spec_narrative() {
    // Pins the version label, NOT the integer placeholder used in the spec's
    // illustrative JSON payloads. See SPEC_SCHEMA_VERSION_LABEL above.
    assert_eq!(
        SCHEMA_VERSION, SPEC_SCHEMA_VERSION_LABEL,
        "SCHEMA_VERSION drift: code says {SCHEMA_VERSION:?}, spec narrative says {SPEC_SCHEMA_VERSION_LABEL:?}"
    );
}

// ============================================================================
// Wire-vocabulary alignment (one test per public enum)
// ============================================================================

#[test]
fn lifecycle_event_kinds_match_spec() {
    // Lifecycle events are intentionally order-significant — the spec
    // presents them as an ordered narrative (session.* envelopes the
    // frame.* family, etc.). The other enum tests sort before comparing
    // because their spec tables are unordered sets. Don't "fix" this
    // inconsistency.
    assert_eq!(
        wire_names(LifecycleEventKind::ALL),
        SPEC_LIFECYCLE_EVENTS,
        "LifecycleEventKind drift from spec lifecycle-event-vocabulary table"
    );
}

#[test]
fn integration_modes_match_spec() {
    let mut actual = wire_names(IntegrationMode::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_INTEGRATION_MODES
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "IntegrationMode drift from spec integration-modes list"
    );
}

#[test]
fn support_states_match_spec() {
    let mut actual = wire_names(SupportState::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_SUPPORT_STATES.iter().map(|s| s.to_string()).collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "SupportState drift from spec support-values table"
    );
}

#[test]
fn adapter_roles_match_spec() {
    let mut actual = wire_names(AdapterRole::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_ADAPTER_ROLES.iter().map(|s| s.to_string()).collect();
    expected.sort();
    assert_eq!(actual, expected, "AdapterRole drift from spec roles list");
}

#[test]
fn receipt_statuses_match_spec() {
    let mut actual = wire_names(ReceiptStatus::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_RECEIPT_STATUSES
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "ReceiptStatus drift from spec receipt-statuses list"
    );
}

#[test]
fn failure_classes_match_spec() {
    let mut actual = wire_names(FailureClass::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_FAILURE_CLASSES.iter().map(|s| s.to_string()).collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "FailureClass drift from spec failure-classes table"
    );
}

#[test]
fn retry_classes_match_spec() {
    let mut actual = wire_names(RetryClass::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_RETRY_CLASSES.iter().map(|s| s.to_string()).collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "RetryClass drift from spec retry-classes table"
    );
}

#[test]
fn placement_classes_match_spec() {
    let mut actual = wire_names(PlacementClass::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_PLACEMENT_CLASSES
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "PlacementClass drift from spec placement-classes table"
    );
}

#[test]
fn placement_outcomes_match_spec() {
    let mut actual = wire_names(PlacementOutcome::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_PLACEMENT_OUTCOMES
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "PlacementOutcome drift from spec payload-receipt status values"
    );
}

#[test]
fn requirement_levels_match_spec() {
    let mut actual = wire_names(RequirementLevel::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_REQUIREMENT_LEVELS
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "RequirementLevel drift from spec requirement-levels table"
    );
}

#[test]
fn negotiation_outcomes_match_spec() {
    let mut actual = wire_names(NegotiationOutcome::ALL);
    actual.sort();
    let mut expected: Vec<String> = SPEC_NEGOTIATION_OUTCOMES
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "NegotiationOutcome drift from spec negotiation-outcomes table"
    );
}

#[test]
fn frame_classes_present() {
    // Spec doesn't enumerate frame_class values directly — it implies
    // top_level + subcall via "A recursive client may create nested frames".
    // Pin both values; if spec adds more, update both this test and
    // FrameClass::ALL.
    let mut actual = wire_names(FrameClass::ALL);
    actual.sort();
    assert_eq!(actual, vec!["subcall".to_string(), "top_level".to_string()]);
}

// ============================================================================
// Failure → retry default mapping
// ============================================================================

#[test]
fn failure_to_retry_default_table_matches_spec() {
    let actual_pairs: Vec<(String, String)> = FailureClass::ALL
        .iter()
        .map(|fc| {
            let fc_name = serde_json::to_value(fc)
                .unwrap()
                .as_str()
                .unwrap()
                .to_string();
            let rc_name = serde_json::to_value(fc.default_retry())
                .unwrap()
                .as_str()
                .unwrap()
                .to_string();
            (fc_name, rc_name)
        })
        .collect();
    let expected_pairs: Vec<(String, String)> = SPEC_FAILURE_TO_RETRY
        .iter()
        .map(|(fc, rc)| (fc.to_string(), rc.to_string()))
        .collect();

    let actual_map: BTreeMap<&str, &str> = actual_pairs
        .iter()
        .map(|(f, r)| (f.as_str(), r.as_str()))
        .collect();
    let expected_map: BTreeMap<&str, &str> = expected_pairs
        .iter()
        .map(|(f, r)| (f.as_str(), r.as_str()))
        .collect();
    assert_eq!(
        actual_map, expected_map,
        "FailureClass::default_retry() drift from spec failure→retry table"
    );
}

// ============================================================================
// Struct-shape alignment (spec field tables ↔ JSON keys)
// ============================================================================

fn fully_populated_frame_context() -> FrameContext {
    FrameContext::subcall("frm-2", "frm-1")
}

fn fully_populated_payload() -> PayloadEnvelope {
    PayloadEnvelope {
        schema_version: SCHEMA_VERSION.to_string(),
        payload_id: "pay-1".into(),
        client_id: "ccd".into(),
        payload_kind: "instruction_frame".into(),
        format: "client-defined".into(),
        content_encoding: "utf8".into(),
        body: Some("hello".into()),
        body_ref: None,
        byte_size: 5,
        content_digest: Some("sha256:abc".into()),
        acceptable_placements: vec![AcceptablePlacement {
            placement: PlacementClass::PrePromptFrame,
            requirement: RequirementLevel::Required,
        }],
        idempotency_key: Some("idem-1".into()),
        expires_at_epoch_s: Some(1_778_200_000),
        redaction: Some("none".into()),
        metadata: serde_json::Map::from_iter([("k".into(), serde_json::Value::String("v".into()))]),
    }
}

fn fully_populated_receipt() -> LifecycleReceipt {
    LifecycleReceipt {
        schema_version: SCHEMA_VERSION.to_string(),
        receipt_id: "lfr-1".into(),
        idempotency_key: Some("idem-1".into()),
        client_id: "ccd".into(),
        adapter_id: "codex".into(),
        invocation_id: "inv-1".into(),
        event: LifecycleEventKind::FrameOpening,
        event_id: "evt-1".into(),
        sequence: Some(42),
        parent_receipt_id: Some("lfr-0".into()),
        integration_mode: IntegrationMode::NativeHook,
        status: ReceiptStatus::Delivered,
        at_epoch_s: 1_778_100_000,
        harness_session_id: Some("session-123".into()),
        harness_run_id: Some("run-456".into()),
        harness_task_id: Some("task-789".into()),
        payload_receipts: vec![PayloadReceipt {
            payload_id: "pay-1".into(),
            payload_kind: "instruction_frame".into(),
            placement: PlacementClass::PrePromptFrame,
            status: PlacementOutcome::Delivered,
            byte_size: 5,
            content_digest: Some("sha256:pay1".into()),
        }],
        telemetry_summary: serde_json::Map::from_iter([(
            "context_pressure".into(),
            serde_json::Value::String("moderate".into()),
        )]),
        capability_degradations: vec![CapabilityDegradation {
            capability: "context_pressure".into(),
            previous_support: SupportState::Native,
            current_support: SupportState::Unavailable,
            evidence: Some("missing".into()),
            retry_class: Some(RetryClass::RetryAfterReconfigure),
        }],
        failure_class: None,
        retry_class: None,
        warnings: vec![Warning {
            code: "demo".into(),
            message: "demo".into(),
            capability: None,
        }],
    }
}

#[test]
fn frame_context_fields_match_spec() {
    let value = serde_json::to_value(fully_populated_frame_context()).unwrap();
    assert_keys_match_spec(&value, SPEC_FRAME_CONTEXT_FIELDS, "FrameContext");
}

#[test]
fn payload_envelope_fields_match_spec() {
    // body and body_ref are mutually exclusive per spec, so serialize both
    // shapes and union the keys to prove the struct carries both fields.
    let with_body = serde_json::to_value(fully_populated_payload()).unwrap();
    let mut alt = fully_populated_payload();
    alt.body = None;
    alt.body_ref = Some("blob-1".into());
    let with_body_ref = serde_json::to_value(&alt).unwrap();

    let mut union = serde_json::Map::new();
    for v in [&with_body, &with_body_ref] {
        for (k, val) in v.as_object().expect("object") {
            union.insert(k.clone(), val.clone());
        }
    }
    assert_keys_match_spec(
        &Value::Object(union),
        SPEC_PAYLOAD_ENVELOPE_FIELDS,
        "PayloadEnvelope",
    );
}

#[test]
fn lifecycle_receipt_fields_match_spec() {
    let value = serde_json::to_value(fully_populated_receipt()).unwrap();
    assert_keys_match_spec(&value, SPEC_LIFECYCLE_RECEIPT_FIELDS, "LifecycleReceipt");
}

#[test]
fn payload_receipt_fields_match_spec() {
    let receipt = PayloadReceipt {
        payload_id: "pay-1".into(),
        payload_kind: "instruction_frame".into(),
        placement: PlacementClass::PrePromptFrame,
        status: PlacementOutcome::Delivered,
        byte_size: 5,
        content_digest: Some("sha256:pay1".into()),
    };
    let value = serde_json::to_value(receipt).unwrap();
    assert_keys_match_spec(&value, SPEC_PAYLOAD_RECEIPT_FIELDS, "PayloadReceipt");
}

/// `LifecycleReceipt::REQUIRED_NULLABLE_FIELDS` is the runtime gate that
/// rejects inbound JSON missing one of those keys (issue #19). The
/// constant must agree with the spec taxonomy — if the spec adds a new
/// `required_nullable` field, the runtime check must learn about it in
/// the same change. This test makes that drift mechanical instead of a
/// review-time catch.
#[test]
fn lifecycle_receipt_required_nullable_const_matches_spec() {
    let from_spec: std::collections::BTreeSet<&str> = SPEC_LIFECYCLE_RECEIPT_FIELDS
        .iter()
        .filter(|(_, presence)| *presence == "required_nullable")
        .map(|(field, _)| *field)
        .collect();
    let from_code: std::collections::BTreeSet<&str> = LifecycleReceipt::REQUIRED_NULLABLE_FIELDS
        .iter()
        .copied()
        .collect();
    assert_eq!(
        from_code, from_spec,
        "LifecycleReceipt::REQUIRED_NULLABLE_FIELDS disagrees with the spec \
         taxonomy in SPEC_LIFECYCLE_RECEIPT_FIELDS. If the spec added or \
         removed a required-nullable field, update the const in src/lib.rs \
         in the same commit."
    );
}

/// Required-nullable fields must serialize as keys even when their value
/// is `None`. This is the spec rule:
///
///   *"sequence is required and nullable"*
///   *"parent_receipt_id is required and nullable"*
///
/// A serde refactor that quietly added `skip_serializing_if = "is_none"`
/// to one of these fields would silently break the contract; the
/// `lifecycle_receipt_fields_match_spec` test wouldn't catch it because
/// its fixture populates everything. This test uses a minimal fixture
/// where every required-nullable field is None and asserts the keys
/// still appear in the serialized output.
#[test]
fn lifecycle_receipt_required_nullable_fields_present_when_none() {
    let r = LifecycleReceipt {
        schema_version: SCHEMA_VERSION.to_string(),
        receipt_id: "lfr-min".into(),
        idempotency_key: None,
        client_id: "ccd".into(),
        adapter_id: "codex".into(),
        invocation_id: "inv-min".into(),
        event: LifecycleEventKind::SessionStarting,
        event_id: "evt-min".into(),
        sequence: None,
        parent_receipt_id: None,
        integration_mode: IntegrationMode::NativeHook,
        status: ReceiptStatus::Observed,
        at_epoch_s: 1_778_100_000,
        harness_session_id: None,
        harness_run_id: None,
        harness_task_id: None,
        payload_receipts: Vec::new(),
        telemetry_summary: serde_json::Map::new(),
        capability_degradations: Vec::new(),
        failure_class: None,
        retry_class: None,
        warnings: Vec::new(),
    };
    let value = serde_json::to_value(&r).unwrap();
    let keys: std::collections::BTreeSet<String> =
        value.as_object().unwrap().keys().cloned().collect();
    for (field, presence) in SPEC_LIFECYCLE_RECEIPT_FIELDS {
        if *presence == "required" || *presence == "required_nullable" {
            assert!(
                keys.contains(*field),
                "required field `{field}` ({presence}) missing from minimal LifecycleReceipt JSON: {keys:?}"
            );
        }
    }
}

/// **Known gap (TODO lifeloop.v0.x): issue #6 owns the full AdapterManifest.**
///
/// The current `AdapterManifest` is a minimal stub carrying only:
/// `schema_version`, `adapter_id`, `adapter_version`, `display_name`,
/// `roles`, `integration_modes`, `lifecycle_events`. The spec's manifest
/// adds `aliases`, `injection`, `telemetry`, `session_identity`,
/// `receipts`, `statefulness`, `known_failure_classes`. Issue #6 will close
/// this gap; un-ignore when it lands.
/// Pins the full AdapterManifest shape per the spec's required +
/// optional field tables. Built from a fully-populated manifest so
/// every optional field appears at least once.
#[test]
fn adapter_manifest_fields_match_spec() {
    let manifest = lifeloop::AdapterManifest {
        contract_version: SCHEMA_VERSION.to_string(),
        adapter_id: "codex".into(),
        adapter_version: "0.1.0".into(),
        display_name: "Codex".into(),
        role: AdapterRole::PrimaryWorker,
        integration_modes: vec![IntegrationMode::NativeHook],
        lifecycle_events: BTreeMap::from([(
            LifecycleEventKind::SessionStarting,
            lifeloop::ManifestLifecycleEventSupport {
                support: SupportState::Native,
                modes: vec![IntegrationMode::NativeHook],
            },
        )]),
        placement: BTreeMap::from([(
            lifeloop::ManifestPlacementClass::PreSession,
            lifeloop::ManifestPlacementSupport {
                support: SupportState::Native,
                max_bytes: Some(8192),
            },
        )]),
        context_pressure: lifeloop::ManifestContextPressure {
            support: SupportState::Synthesized,
            evidence: None,
        },
        receipts: lifeloop::ManifestReceipts {
            native: false,
            lifeloop_synthesized: true,
            receipt_ledger: SupportState::Unavailable,
        },
        session_identity: Some(lifeloop::ManifestSessionIdentity {
            harness_session_id: SupportState::Native,
            harness_run_id: SupportState::Synthesized,
            harness_task_id: SupportState::Unavailable,
        }),
        session_rename: Some(lifeloop::ManifestSessionRename {
            support: SupportState::Manual,
        }),
        renewal: Some(lifeloop::ManifestRenewal {
            reset: lifeloop::ManifestRenewalReset {
                native: SupportState::Unavailable,
                wrapper_mediated: SupportState::Partial,
                manual: SupportState::Manual,
            },
            continuation: lifeloop::ManifestRenewalContinuation {
                observation: SupportState::Partial,
                payload_delivery: SupportState::Unavailable,
            },
            profiles: vec!["ccd-renewal".into()],
            evidence: Some("renewal capability evidence is lifecycle-only".into()),
        }),
        approval_surface: Some(lifeloop::ManifestApprovalSurface {
            support: SupportState::Manual,
        }),
        failure_modes: vec![FailureClass::TransportError],
        telemetry_sources: vec![lifeloop::ManifestTelemetrySource {
            source: "context-pressure-log".into(),
            support: SupportState::Synthesized,
        }],
        known_degradations: vec![lifeloop::ManifestKnownDegradation {
            capability: "supervisor.tick".into(),
            previous_support: SupportState::Native,
            current_support: SupportState::Unavailable,
            evidence: Some("not exposed on this build".into()),
        }],
    };
    let value = serde_json::to_value(&manifest).unwrap();
    assert_keys_match_spec(&value, SPEC_ADAPTER_MANIFEST_FIELDS, "AdapterManifest");
}

#[test]
fn manifest_placement_classes_match_spec() {
    let mut actual: Vec<String> = lifeloop::ManifestPlacementClass::ALL
        .iter()
        .map(|v| {
            serde_json::to_value(v)
                .expect("serialize")
                .as_str()
                .expect("string wire name")
                .to_string()
        })
        .collect();
    actual.sort();
    let mut expected: Vec<String> = SPEC_MANIFEST_PLACEMENT_CLASSES
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected.sort();
    assert_eq!(
        actual, expected,
        "ManifestPlacementClass drift from spec manifest-placement-classes table"
    );
}