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
134    fn proposal(key: ContextKey, id: &str) -> ProposedFact {
135        ProposedFact::new(key, id, "content", "test")
136    }
137
138    #[test]
139    fn empty_effect_is_empty() {
140        let e = AgentEffect::empty();
141        assert!(e.is_empty());
142        assert!(e.proposals().is_empty());
143    }
144
145    #[test]
146    fn with_proposal_single() {
147        let e = AgentEffect::with_proposal(proposal(ContextKey::Seeds, "p1"));
148        assert!(!e.is_empty());
149        assert_eq!(e.proposals().len(), 1);
150        assert_eq!(e.proposals()[0].id, "p1");
151    }
152
153    #[test]
154    fn with_proposals_multiple() {
155        let e = AgentEffect::with_proposals(vec![
156            proposal(ContextKey::Seeds, "p1"),
157            proposal(ContextKey::Hypotheses, "p2"),
158        ]);
159        assert_eq!(e.proposals().len(), 2);
160    }
161
162    #[test]
163    fn builder_supports_fluent_proposal_construction() {
164        let e = AgentEffect::builder()
165            .proposal(proposal(ContextKey::Seeds, "p1"))
166            .proposal(proposal(ContextKey::Hypotheses, "p2"))
167            .build();
168
169        assert_eq!(e.proposals().len(), 2);
170        assert_eq!(e.proposals()[0].id, "p1");
171        assert_eq!(e.proposals()[1].id, "p2");
172    }
173
174    #[test]
175    fn builder_supports_mutable_incremental_construction() {
176        let mut builder = AgentEffect::builder();
177        assert!(builder.is_empty());
178
179        builder.push(proposal(ContextKey::Seeds, "p1"));
180        builder.extend([proposal(ContextKey::Hypotheses, "p2")]);
181
182        let e = builder.build();
183        assert_eq!(e.proposals().len(), 2);
184        assert_eq!(e.affected_keys().len(), 2);
185    }
186
187    #[test]
188    fn builder_supports_iterator_construction() {
189        let proposals = [
190            proposal(ContextKey::Seeds, "p1"),
191            proposal(ContextKey::Hypotheses, "p2"),
192        ];
193
194        let e = AgentEffect::builder().proposals(proposals).build();
195
196        assert_eq!(e.proposals().len(), 2);
197    }
198
199    #[test]
200    fn is_empty_false_for_nonempty() {
201        let e = AgentEffect::with_proposal(proposal(ContextKey::Signals, "x"));
202        assert!(!e.is_empty());
203    }
204
205    #[test]
206    fn affected_keys_deduplicates_and_sorts() {
207        let e = AgentEffect::with_proposals(vec![
208            proposal(ContextKey::Signals, "a"),
209            proposal(ContextKey::Seeds, "b"),
210            proposal(ContextKey::Signals, "c"),
211            proposal(ContextKey::Seeds, "d"),
212            proposal(ContextKey::Hypotheses, "e"),
213        ]);
214        let keys = e.affected_keys();
215        assert_eq!(keys.len(), 3);
216        // Sorted by Ord impl
217        for window in keys.windows(2) {
218            assert!(window[0] <= window[1]);
219        }
220        // No duplicates
221        let mut deduped = keys.clone();
222        deduped.dedup();
223        assert_eq!(keys, deduped);
224    }
225
226    #[test]
227    fn affected_keys_empty_for_empty_effect() {
228        let e = AgentEffect::empty();
229        assert!(e.affected_keys().is_empty());
230    }
231
232    mod prop {
233        use super::*;
234        use proptest::prelude::*;
235
236        fn arb_context_key() -> impl Strategy<Value = ContextKey> {
237            prop_oneof![
238                Just(ContextKey::Seeds),
239                Just(ContextKey::Hypotheses),
240                Just(ContextKey::Strategies),
241                Just(ContextKey::Constraints),
242                Just(ContextKey::Signals),
243                Just(ContextKey::Competitors),
244                Just(ContextKey::Evaluations),
245                Just(ContextKey::Proposals),
246                Just(ContextKey::Diagnostic),
247                Just(ContextKey::Votes),
248                Just(ContextKey::Disagreements),
249                Just(ContextKey::ConsensusOutcomes),
250            ]
251        }
252
253        proptest! {
254            #[test]
255            fn affected_keys_never_has_duplicates(
256                keys in proptest::collection::vec(arb_context_key(), 0..50),
257            ) {
258                let proposals: Vec<ProposedFact> = keys
259                    .iter()
260                    .enumerate()
261                    .map(|(i, &k)| ProposedFact::new(k, format!("p{i}"), "c", "prov"))
262                    .collect();
263                let effect = AgentEffect::with_proposals(proposals);
264                let result = effect.affected_keys();
265                let mut deduped = result.clone();
266                deduped.dedup();
267                prop_assert_eq!(result, deduped);
268            }
269        }
270    }
271}