Skip to main content

converge_pack/
effect.rs

1// Copyright 2024-2026 Reflective Labs
2// SPDX-License-Identifier: MIT
3
4//! Suggestor effects — what suggestors produce, the engine merges.
5//!
6//! Effects are proposal-only. Suggestors suggest; the engine validates and promotes.
7
8use crate::context::ContextKey;
9use crate::fact::ProposedFact;
10
11/// The output of a suggestor's `execute()` call.
12///
13/// An effect describes what a suggestor wants to suggest to the context.
14/// The engine collects effects from all eligible suggestors, validates them,
15/// and promotes them serially in deterministic order.
16#[derive(Debug, Default)]
17pub struct AgentEffect {
18    /// New proposals to be validated by the engine.
19    proposals: Vec<ProposedFact>,
20}
21
22/// Construction helper for incrementally assembling an [`AgentEffect`].
23///
24/// This keeps mutation in the authoring phase while preserving [`AgentEffect`]
25/// as the finished proposal output value returned by a suggestor.
26#[derive(Debug, Default)]
27pub struct AgentEffectBuilder {
28    proposals: Vec<ProposedFact>,
29}
30
31impl AgentEffectBuilder {
32    /// Creates an empty builder.
33    #[must_use]
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    /// Adds one proposal and returns the builder for fluent construction.
39    #[must_use]
40    pub fn proposal(mut self, proposal: ProposedFact) -> Self {
41        self.proposals.push(proposal);
42        self
43    }
44
45    /// Adds many proposals and returns the builder for fluent construction.
46    #[must_use]
47    pub fn proposals(mut self, proposals: impl IntoIterator<Item = ProposedFact>) -> Self {
48        self.proposals.extend(proposals);
49        self
50    }
51
52    /// Appends one proposal to an existing mutable builder.
53    pub fn push(&mut self, proposal: ProposedFact) {
54        self.proposals.push(proposal);
55    }
56
57    /// Appends many proposals to an existing mutable builder.
58    pub fn extend(&mut self, proposals: impl IntoIterator<Item = ProposedFact>) {
59        self.proposals.extend(proposals);
60    }
61
62    /// Returns true if the builder has no proposals.
63    #[must_use]
64    pub fn is_empty(&self) -> bool {
65        self.proposals.is_empty()
66    }
67
68    /// Finalizes the builder into a suggestor effect.
69    #[must_use]
70    pub fn build(self) -> AgentEffect {
71        AgentEffect::with_proposals(self.proposals)
72    }
73}
74
75impl AgentEffect {
76    /// Starts building an effect incrementally.
77    #[must_use]
78    pub fn builder() -> AgentEffectBuilder {
79        AgentEffectBuilder::new()
80    }
81
82    /// Creates an empty effect (no contributions).
83    #[must_use]
84    pub fn empty() -> Self {
85        Self::default()
86    }
87
88    /// Creates an effect with a single proposal.
89    #[must_use]
90    pub fn with_proposal(proposal: ProposedFact) -> Self {
91        Self {
92            proposals: vec![proposal],
93        }
94    }
95
96    /// Creates an effect with multiple proposals.
97    #[must_use]
98    pub fn with_proposals(proposals: Vec<ProposedFact>) -> Self {
99        Self { proposals }
100    }
101
102    /// Borrows the proposals carried by this effect.
103    #[must_use]
104    pub fn proposals(&self) -> &[ProposedFact] {
105        &self.proposals
106    }
107
108    /// Consumes the effect and returns its proposals.
109    #[must_use]
110    pub fn into_proposals(self) -> Vec<ProposedFact> {
111        self.proposals
112    }
113
114    /// Returns true if this effect contributes nothing.
115    #[must_use]
116    pub fn is_empty(&self) -> bool {
117        self.proposals.is_empty()
118    }
119
120    /// Returns the context keys affected by this effect.
121    #[must_use]
122    pub fn affected_keys(&self) -> Vec<ContextKey> {
123        let mut keys: Vec<ContextKey> = self.proposals.iter().map(|p| p.key).collect();
124        keys.sort();
125        keys.dedup();
126        keys
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use crate::fact::TextPayload;
134
135    fn proposal(key: ContextKey, id: &str) -> ProposedFact {
136        ProposedFact::new(key, id, TextPayload::new("content"), "test")
137    }
138
139    #[test]
140    fn empty_effect_is_empty() {
141        let e = AgentEffect::empty();
142        assert!(e.is_empty());
143        assert!(e.proposals().is_empty());
144    }
145
146    #[test]
147    fn with_proposal_single() {
148        let e = AgentEffect::with_proposal(proposal(ContextKey::Seeds, "p1"));
149        assert!(!e.is_empty());
150        assert_eq!(e.proposals().len(), 1);
151        assert_eq!(e.proposals()[0].id, "p1");
152    }
153
154    #[test]
155    fn with_proposals_multiple() {
156        let e = AgentEffect::with_proposals(vec![
157            proposal(ContextKey::Seeds, "p1"),
158            proposal(ContextKey::Hypotheses, "p2"),
159        ]);
160        assert_eq!(e.proposals().len(), 2);
161    }
162
163    #[test]
164    fn builder_supports_fluent_proposal_construction() {
165        let e = AgentEffect::builder()
166            .proposal(proposal(ContextKey::Seeds, "p1"))
167            .proposal(proposal(ContextKey::Hypotheses, "p2"))
168            .build();
169
170        assert_eq!(e.proposals().len(), 2);
171        assert_eq!(e.proposals()[0].id, "p1");
172        assert_eq!(e.proposals()[1].id, "p2");
173    }
174
175    #[test]
176    fn builder_supports_mutable_incremental_construction() {
177        let mut builder = AgentEffect::builder();
178        assert!(builder.is_empty());
179
180        builder.push(proposal(ContextKey::Seeds, "p1"));
181        builder.extend([proposal(ContextKey::Hypotheses, "p2")]);
182
183        let e = builder.build();
184        assert_eq!(e.proposals().len(), 2);
185        assert_eq!(e.affected_keys().len(), 2);
186    }
187
188    #[test]
189    fn builder_supports_iterator_construction() {
190        let proposals = [
191            proposal(ContextKey::Seeds, "p1"),
192            proposal(ContextKey::Hypotheses, "p2"),
193        ];
194
195        let e = AgentEffect::builder().proposals(proposals).build();
196
197        assert_eq!(e.proposals().len(), 2);
198    }
199
200    #[test]
201    fn is_empty_false_for_nonempty() {
202        let e = AgentEffect::with_proposal(proposal(ContextKey::Signals, "x"));
203        assert!(!e.is_empty());
204    }
205
206    #[test]
207    fn affected_keys_deduplicates_and_sorts() {
208        let e = AgentEffect::with_proposals(vec![
209            proposal(ContextKey::Signals, "a"),
210            proposal(ContextKey::Seeds, "b"),
211            proposal(ContextKey::Signals, "c"),
212            proposal(ContextKey::Seeds, "d"),
213            proposal(ContextKey::Hypotheses, "e"),
214        ]);
215        let keys = e.affected_keys();
216        assert_eq!(keys.len(), 3);
217        // Sorted by Ord impl
218        for window in keys.windows(2) {
219            assert!(window[0] <= window[1]);
220        }
221        // No duplicates
222        let mut deduped = keys.clone();
223        deduped.dedup();
224        assert_eq!(keys, deduped);
225    }
226
227    #[test]
228    fn affected_keys_empty_for_empty_effect() {
229        let e = AgentEffect::empty();
230        assert!(e.affected_keys().is_empty());
231    }
232
233    mod prop {
234        use super::*;
235        use proptest::prelude::*;
236
237        fn arb_context_key() -> impl Strategy<Value = ContextKey> {
238            prop_oneof![
239                Just(ContextKey::Seeds),
240                Just(ContextKey::Hypotheses),
241                Just(ContextKey::Strategies),
242                Just(ContextKey::Constraints),
243                Just(ContextKey::Signals),
244                Just(ContextKey::Competitors),
245                Just(ContextKey::Evaluations),
246                Just(ContextKey::Proposals),
247                Just(ContextKey::Diagnostic),
248                Just(ContextKey::Votes),
249                Just(ContextKey::Disagreements),
250                Just(ContextKey::ConsensusOutcomes),
251            ]
252        }
253
254        proptest! {
255            #[test]
256            fn affected_keys_never_has_duplicates(
257                keys in proptest::collection::vec(arb_context_key(), 0..50),
258            ) {
259                let proposals: Vec<ProposedFact> = keys
260                    .iter()
261                    .enumerate()
262                    .map(|(i, &k)| ProposedFact::new(k, format!("p{i}"), TextPayload::new("c"), "prov"))
263                    .collect();
264                let effect = AgentEffect::with_proposals(proposals);
265                let result = effect.affected_keys();
266                let mut deduped = result.clone();
267                deduped.dedup();
268                prop_assert_eq!(result, deduped);
269            }
270        }
271    }
272}