reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
#![cfg(test)]

use std::{error::Error, num::NonZeroU64};

use super::lifecycle::{Coord, CoordError, Outcome, StepIndex};

fn nz(value: u64) -> NonZeroU64 {
    NonZeroU64::new(value).expect("test numbers are non-zero")
}

fn step_index(turn: u64, step: u64, step_in_run: u64) -> StepIndex {
    StepIndex::new(nz(turn), nz(step), nz(step_in_run)).unwrap()
}

#[test]
fn outcomes_are_closed_terminal_facts() {
    let outcomes = [
        Outcome::Completed,
        Outcome::Stopped,
        Outcome::Cancelled,
        Outcome::Failed,
    ];
    for (index, outcome) in outcomes.iter().enumerate() {
        for (other_index, other) in outcomes.iter().enumerate() {
            assert_eq!(outcome == other, index == other_index);
        }
    }
}

#[test]
fn every_valid_coordinate_layer_is_constructible_and_read_only() {
    let position = step_index(2, 3, 5);
    assert_eq!(position.turn(), nz(2));
    assert_eq!(position.step_in_turn(), nz(3));
    assert_eq!(position.step_in_run(), nz(5));

    let run = Coord::at_run("session-2".into(), "run-7".into()).unwrap();
    let turn = Coord::at_turn("session-2".into(), "run-7".into(), nz(2)).unwrap();
    let step = Coord::at_step("session-2".into(), "run-7".into(), position).unwrap();
    let generation =
        Coord::at_generation("session-2".into(), "run-7".into(), position, nz(1)).unwrap();
    let tool_call = Coord::at_tool_call(
        "session-2".into(),
        "run-7".into(),
        position,
        nz(1),
        "call-1".into(),
        "grep".into(),
    )
    .unwrap();

    assert_coord(&run, [0, 0, 0, 0], "", "", "run-7");
    assert_coord(&turn, [2, 0, 0, 0], "", "", "run-7/turn-2");
    assert_coord(&step, [2, 3, 5, 0], "", "", "run-7/turn-2/step-3");
    assert_coord(
        &generation,
        [2, 3, 5, 1],
        "",
        "",
        "run-7/turn-2/step-3/gen-1",
    );
    assert_coord(
        &tool_call,
        [2, 3, 5, 1],
        "call-1",
        "grep",
        "run-7/turn-2/step-3/gen-1/call-call-1",
    );
    assert_eq!(tool_call.session_id(), "session-2");
    assert_eq!(tool_call.run_id(), "run-7");
    assert_eq!(tool_call.clone(), tool_call);
}

fn assert_coord(coord: &Coord, numbers: [u64; 4], call_id: &str, tool_name: &str, rendered: &str) {
    assert_eq!(
        [
            coord.turn(),
            coord.step_in_turn(),
            coord.step_in_run(),
            coord.generation(),
        ],
        numbers
    );
    assert_eq!(coord.call_id(), call_id);
    assert_eq!(coord.tool_name(), tool_name);
    assert_eq!(coord.to_string(), rendered);
}

/// ADR-017 D4 freezes `Coord`'s `Display` as the **run-relative path**
/// `run_id[/turn-N][/step-N][/gen-N][/call-ID]`.
///
/// Consumers parse it out of logs, so this is a published contract rather than a
/// convenience rendering. The two properties worth pinning separately from the
/// per-layer renderings above are that the session identity is deliberately
/// *not* in the string, and that any future dimension is therefore exposed
/// through an accessor rather than by extending it.
#[test]
fn the_display_format_is_the_frozen_run_relative_path() {
    let tool_call = Coord::at_tool_call(
        "session-2".into(),
        "run-7".into(),
        step_index(2, 3, 5),
        nz(1),
        "call-1".into(),
        "grep".into(),
    )
    .unwrap();

    assert_eq!(
        tool_call.to_string(),
        "run-7/turn-2/step-3/gen-1/call-call-1"
    );
    assert_eq!(tool_call.session_id(), "session-2");
    assert!(
        !tool_call.to_string().contains("session-2"),
        "the frozen path is run-relative: session identity is read structurally"
    );
    // The tool name is likewise structural only; the path carries the call id.
    assert_eq!(tool_call.tool_name(), "grep");
    assert!(!tool_call.to_string().contains("grep"));
}

#[test]
fn equal_step_numbers_are_valid() {
    assert!(StepIndex::new(nz(1), nz(4), nz(4)).is_ok());
}

#[test]
fn empty_containing_identities_return_typed_errors() {
    let empty_session = Coord::at_run(String::new(), "run".into()).unwrap_err();
    let empty_run = Coord::at_run("session".into(), String::new()).unwrap_err();

    assert_error(&empty_session);
    assert_eq!(empty_session, CoordError::EmptySessionId);
    assert_eq!(empty_session.to_string(), "session ID must not be empty");
    assert_eq!(empty_run, CoordError::EmptyRunId);
    assert_eq!(empty_run.to_string(), "run ID must not be empty");
}

#[test]
fn inconsistent_step_numbers_return_a_typed_error() {
    let error = StepIndex::new(nz(1), nz(3), nz(2)).unwrap_err();
    let expected = CoordError::StepExceedsStepInRun {
        step: nz(3),
        step_in_run: nz(2),
    };

    assert_eq!(error, expected);
    assert_eq!(error.to_string(), "step 3 must not exceed run-wide step 2");
}

#[test]
fn empty_tool_call_fields_return_typed_errors() {
    let position = step_index(1, 1, 1);
    let empty_call = Coord::at_tool_call(
        "session".into(),
        "run".into(),
        position,
        nz(1),
        String::new(),
        "tool".into(),
    )
    .unwrap_err();
    let empty_tool = Coord::at_tool_call(
        "session".into(),
        "run".into(),
        position,
        nz(1),
        "call".into(),
        String::new(),
    )
    .unwrap_err();

    assert_eq!(empty_call, CoordError::EmptyCallId);
    assert_eq!(empty_call.to_string(), "tool-call ID must not be empty");
    assert_eq!(empty_tool, CoordError::EmptyToolName);
    assert_eq!(empty_tool.to_string(), "tool name must not be empty");
}

fn assert_error(error: &dyn Error) {
    assert!(error.source().is_none());
}

/// The tripwire that keeps `Outcome`'s out-of-crate wire table in step with the enum.
///
/// `tests/serde_format.rs` pins the positional wire index and tag of every
/// [`Outcome`], but it is an integration-test crate and sees the public API only.
/// [`Outcome`] is `#[non_exhaustive]`, so no crate outside `reef-core` can write
/// an exhaustive `match` to prove that table names every variant: a brand-new
/// variant appended at the next index would simply be absent from it and ship
/// unpinned. This module is an **adjacent compile-time reminder** for that gap,
/// not the thing that closes it: the production `match`es over [`Outcome`] —
/// `value::lifecycle`'s serde `Serialize` index/tag table and `runtime::run`'s
/// `lifecycle_end` — already carry the same protection, so a new variant fails
/// the build in production first. This module simply puts a second, test-local
/// exhaustive `match` beside the pinned table, so the reminder lands where the
/// table lives.
///
/// The variant list and the tag function are generated together from one macro
/// invocation, so they cannot drift apart, and [`tag`]'s `match` is exhaustive.
/// Adding a variant to [`Outcome`] therefore makes that `match` non-exhaustive
/// and **fails the build** — which is the reminder to extend the list below and
/// the positional table in `tests/serde_format.rs` as one change.
mod outcome_tripwire {
    use super::super::lifecycle::Outcome;

    macro_rules! outcome_tripwire {
        ($($variant:ident => $tag:literal),+ $(,)?) => {
            /// Every [`Outcome`] variant, in the order the wire indices declare them.
            pub(super) const VARIANTS: &[Outcome] = &[$(Outcome::$variant),+];

            /// The wire tag of an [`Outcome`], as `tests/serde_format.rs` pins it.
            ///
            /// The `match` has no wildcard arm on purpose: within `reef-core`,
            /// `#[non_exhaustive]` does not relax exhaustiveness, so a variant
            /// that is missing here is a compile error rather than a silent
            /// omission.
            pub(super) const fn tag(outcome: Outcome) -> &'static str {
                match outcome {
                    $(Outcome::$variant => $tag,)+
                }
            }
        };
    }

    outcome_tripwire! {
        Completed => "completed",
        Stopped => "stopped",
        Cancelled => "canceled",
        Failed => "failed",
    }

    /// The list names each variant once and gives it a tag of its own.
    ///
    /// This is not what catches a new variant — the exhaustive `match` in `tag`
    /// does that at compile time. It catches the hand-edit that keeps the list
    /// compiling while corrupting it: a line copied and not renamed, so two
    /// variants share a tag and the positional table would pin one twice.
    #[test]
    fn every_outcome_variant_has_one_distinct_tag() {
        for (position, &outcome) in VARIANTS.iter().enumerate() {
            let rendered = tag(outcome);
            assert!(
                !rendered.is_empty(),
                "a wire tag is never empty: {outcome:?} at position {position}"
            );
            for &other in &VARIANTS[position + 1..] {
                assert_ne!(
                    rendered,
                    tag(other),
                    "{outcome:?} and {other:?} share the wire tag `{rendered}`"
                );
            }
        }
    }
}

/// What the `serde` feature adds to this module, and what it refuses.
#[cfg(feature = "serde")]
mod serde_format {
    use super::super::lifecycle::{Coord, Outcome};
    use super::outcome_tripwire::{VARIANTS, tag};
    use super::{nz, step_index};
    use crate::wire::wire_tests::{assert_expecting, assert_refusal, encode, round_trip};

    fn coord_document(
        turn: u64,
        step: u64,
        step_in_run: u64,
        generation: u64,
        call_id: &str,
        tool_name: &str,
    ) -> String {
        format!(
            r#"{{"session_id":"s","run_id":"r","turn":{turn},"step":{step},"step_in_run":{step_in_run},"generation":{generation},"call_id":"{call_id}","tool_name":"{tool_name}"}}"#
        )
    }

    #[test]
    fn every_outcome_tag_survives_a_round_trip() {
        // The variant list and its tags live in `outcome_tripwire`, whose
        // exhaustive `match` keeps this corpus in step with the enum at compile
        // time.
        for &outcome in VARIANTS {
            assert_eq!(encode(&outcome), format!("\"{}\"", tag(outcome)));
            assert_eq!(round_trip(&outcome), outcome);
        }
    }

    /// An older reef refuses a newer reef's outcome rather than degrading it.
    #[test]
    fn an_unknown_outcome_tag_is_refused_rather_than_folded_into_a_wildcard() {
        assert_refusal(
            serde_json::from_str::<Outcome>(r#""abandoned""#),
            "unknown variant `abandoned`",
        );
        assert_expecting::<Outcome>("a lifecycle outcome");
    }

    #[test]
    fn every_coordinate_layer_round_trips_through_both_forms() {
        let index = step_index(1, 1, 2);
        let coords = [
            Coord::at_run("s".into(), "r".into()).unwrap(),
            Coord::at_turn("s".into(), "r".into(), nz(1)).unwrap(),
            Coord::at_step("s".into(), "r".into(), index).unwrap(),
            Coord::at_generation("s".into(), "r".into(), index, nz(1)).unwrap(),
            Coord::at_tool_call("s".into(), "r".into(), index, nz(1), "c".into(), "t".into())
                .unwrap(),
        ];
        for coord in &coords {
            assert_eq!(round_trip(coord), *coord);
        }
        assert_eq!(encode(&coords[0]), coord_document(0, 0, 0, 0, "", ""));
        assert_eq!(encode(&coords[4]), coord_document(1, 1, 2, 1, "c", "t"));

        let from_sequence: Coord = serde_json::from_str(r#"["s","r",1,1,2,1,"c","t"]"#)
            .expect("a compact format writes a struct as its fields in order");
        assert_eq!(from_sequence, coords[4]);
    }

    /// A coordinate no `at_*` constructor could produce is refused by name.
    #[test]
    fn an_impossible_layer_combination_is_refused() {
        let impossible = [
            // A run-wide step number without a step.
            coord_document(0, 0, 1, 0, "", ""),
            // A turn that already carries a call identity.
            coord_document(1, 0, 0, 0, "c", "t"),
            // A step with no run-wide step number.
            coord_document(1, 1, 0, 0, "", ""),
            // A step below no turn.
            coord_document(0, 1, 1, 0, "", ""),
            // A generation with half a tool call.
            coord_document(1, 1, 2, 1, "c", ""),
            // A tool call below no generation.
            coord_document(1, 1, 2, 0, "c", "t"),
        ];
        for document in impossible {
            assert_refusal(
                serde_json::from_str::<Coord>(&document),
                "do not describe a run, turn, step, generation or tool call",
            );
        }
    }

    /// The step invariant is checked on ingress by the constructor that owns it.
    #[test]
    fn a_step_that_outruns_its_run_wide_step_is_refused() {
        assert_refusal(
            serde_json::from_str::<Coord>(&coord_document(1, 3, 2, 0, "", "")),
            "step 3 must not exceed run-wide step 2",
        );
    }

    #[test]
    fn an_empty_identity_is_refused_on_ingress() {
        assert_refusal(
            serde_json::from_str::<Coord>(
                r#"{"session_id":"","run_id":"r","turn":0,"step":0,"step_in_run":0,"generation":0,"call_id":"","tool_name":""}"#,
            ),
            "session ID must not be empty",
        );
        assert_refusal(
            serde_json::from_str::<Coord>(
                r#"{"session_id":"s","run_id":"","turn":1,"step":0,"step_in_run":0,"generation":0,"call_id":"","tool_name":""}"#,
            ),
            "run ID must not be empty",
        );
    }

    #[test]
    fn a_coordinate_refuses_an_unknown_repeated_missing_or_mistyped_document() {
        assert_refusal(
            serde_json::from_str::<Coord>(r#"{"session_id":"s","session":"s"}"#),
            "unknown field `session`",
        );
        assert_refusal(
            serde_json::from_str::<Coord>(r#"{"session_id":"s","session_id":"s"}"#),
            "duplicate field `session_id`",
        );
        assert_refusal(
            serde_json::from_str::<Coord>(r#"{"session_id":"s","run_id":"r","turn":0}"#),
            "missing field `step`",
        );
        assert_refusal(
            serde_json::from_str::<Coord>(r#"["s"]"#),
            "every struct field",
        );
        assert_expecting::<Coord>("a lifecycle coordinate");
    }
}