made-core 0.7.4

Domain core of MADE: entities, value objects, events, ports. No IO.
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
//! [`Deliberation`] aggregate.
//!
//! The Deliberation is the central aggregate root of MADE.
//! It owns the lifecycle of one deliberation from proposal generation
//! through peer review to scoring and completion. State transitions
//! are explicit and protected so no caller can place the aggregate in
//! an inconsistent shape.
//!
//! Phase graph (linear):
//!
//! ```text
//! Proposing -> Revising -> Validating -> Scoring -> Completed
//! ```
//!
//! Transitions are one-way. `Revising` accepts many `revise_proposal`
//! calls so the use-case layer can run multiple peer-review rounds
//! (critique → revise) without adding externally-observable phases.
//! Methods reject operations that do not match the current phase.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

use crate::entities::{DeliberationPhase, Proposal, RankedOutcome, ValidationOutcome};
use crate::error::DomainError;
use crate::value_objects::{DurationMs, ProposalContent, ProposalId, Rounds, Specialty, TaskId};

/// Aggregate root: one deliberation over one task.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Deliberation {
    task_id: TaskId,
    specialty: Specialty,
    rounds_budget: Rounds,
    phase: DeliberationPhase,

    proposals: BTreeMap<ProposalId, Proposal>,
    outcomes: BTreeMap<ProposalId, ValidationOutcome>,
    ranking: Vec<ProposalId>,

    #[serde(with = "time::serde::rfc3339")]
    started_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    completed_at: Option<OffsetDateTime>,
}

impl Deliberation {
    #[must_use]
    pub fn start(
        task_id: TaskId,
        specialty: Specialty,
        rounds_budget: Rounds,
        now: OffsetDateTime,
    ) -> Self {
        Self {
            task_id,
            specialty,
            rounds_budget,
            phase: DeliberationPhase::Proposing,
            proposals: BTreeMap::new(),
            outcomes: BTreeMap::new(),
            ranking: Vec::new(),
            started_at: now,
            completed_at: None,
        }
    }

    #[must_use]
    pub fn task_id(&self) -> &TaskId {
        &self.task_id
    }
    #[must_use]
    pub fn specialty(&self) -> &Specialty {
        &self.specialty
    }
    #[must_use]
    pub fn rounds_budget(&self) -> Rounds {
        self.rounds_budget
    }
    #[must_use]
    pub fn phase(&self) -> DeliberationPhase {
        self.phase
    }
    #[must_use]
    pub fn proposals(&self) -> &BTreeMap<ProposalId, Proposal> {
        &self.proposals
    }
    #[must_use]
    pub fn outcomes(&self) -> &BTreeMap<ProposalId, ValidationOutcome> {
        &self.outcomes
    }
    #[must_use]
    pub fn started_at(&self) -> OffsetDateTime {
        self.started_at
    }
    #[must_use]
    pub fn completed_at(&self) -> Option<OffsetDateTime> {
        self.completed_at
    }

    /// Add a new proposal. Only allowed while `Proposing`. Duplicate
    /// proposal ids are rejected.
    pub fn add_proposal(&mut self, proposal: Proposal) -> Result<(), DomainError> {
        self.require_phase(DeliberationPhase::Proposing)?;
        if self.proposals.contains_key(proposal.id()) {
            return Err(DomainError::AlreadyExists {
                what: "deliberation.proposal",
            });
        }
        self.proposals.insert(proposal.id().clone(), proposal);
        Ok(())
    }

    /// Revise an existing proposal. Only allowed in the `Revising` phase.
    pub fn revise_proposal(
        &mut self,
        proposal_id: &ProposalId,
        new_content: impl Into<ProposalContent>,
        now: OffsetDateTime,
    ) -> Result<(), DomainError> {
        self.require_phase(DeliberationPhase::Revising)?;
        let proposal = self
            .proposals
            .get_mut(proposal_id)
            .ok_or(DomainError::NotFound {
                what: "deliberation.proposal",
            })?;
        proposal.revise(new_content, now)
    }

    /// Attach a validation outcome for a proposal. Only allowed in
    /// `Validating`. Every proposal must receive exactly one outcome
    /// before advancing to `Scoring`.
    pub fn attach_outcome(
        &mut self,
        proposal_id: &ProposalId,
        outcome: ValidationOutcome,
    ) -> Result<(), DomainError> {
        self.require_phase(DeliberationPhase::Validating)?;
        if !self.proposals.contains_key(proposal_id) {
            return Err(DomainError::NotFound {
                what: "deliberation.proposal",
            });
        }
        if self.outcomes.contains_key(proposal_id) {
            return Err(DomainError::AlreadyExists {
                what: "deliberation.outcome",
            });
        }
        self.outcomes.insert(proposal_id.clone(), outcome);
        Ok(())
    }

    /// Advance to the next phase, enforcing the preconditions of the
    /// transition:
    ///
    /// - `Proposing -> Revising`: at least one proposal present.
    /// - `Validating -> Scoring`: every proposal has an outcome.
    /// - Other transitions are unconditional.
    #[allow(unknown_lints, clippy::collapsible_match)] // collapsible_match added in clippy 1.95; rust 1.90 toolchain doesn't know it
    pub fn advance(&mut self) -> Result<DeliberationPhase, DomainError> {
        let next = self.phase.next().ok_or(DomainError::InvalidTransition {
            from: "Completed",
            to: "Completed",
        })?;

        match (self.phase, next) {
            (DeliberationPhase::Proposing, DeliberationPhase::Revising) => {
                if self.proposals.is_empty() {
                    return Err(DomainError::InvariantViolated {
                        reason: "cannot leave Proposing without proposals",
                    });
                }
            }
            (DeliberationPhase::Validating, DeliberationPhase::Scoring) => {
                if self.outcomes.len() != self.proposals.len() {
                    return Err(DomainError::InvariantViolated {
                        reason: "every proposal must have an outcome before Scoring",
                    });
                }
            }
            _ => {}
        }

        self.phase = next;
        Ok(self.phase)
    }

    /// Compute the ranking and mark the deliberation complete. Only
    /// allowed from `Scoring`. The winning proposal gets rank 0; ties
    /// are broken by proposal id to keep the ordering deterministic.
    pub fn complete(&mut self, now: OffsetDateTime) -> Result<Vec<RankedOutcome>, DomainError> {
        self.require_phase(DeliberationPhase::Scoring)?;

        let mut ranked =
            self.materialize_ranked_tuples(&self.proposals.keys().cloned().collect::<Vec<_>>())?;

        ranked.sort_by(|a, b| b.2.score().cmp(&a.2.score()).then_with(|| a.0.cmp(&b.0)));

        self.ranking = ranked.iter().map(|(id, _, _)| id.clone()).collect();
        self.phase = DeliberationPhase::Completed;
        self.completed_at = Some(now);

        Ok(ranked
            .into_iter()
            .enumerate()
            .map(|(i, (_, proposal, outcome))| {
                RankedOutcome::new(proposal, outcome, u32::try_from(i).unwrap_or(u32::MAX))
            })
            .collect())
    }

    /// Reorder the final ranking after completion while preserving the
    /// same proposal set. This lets the application layer impose a
    /// deterministic post-scoring preference (for example, valid
    /// structured outputs before invalid ones) without mutating
    /// proposals or outcomes.
    pub fn reprioritize(
        &mut self,
        ranking: Vec<ProposalId>,
    ) -> Result<Vec<RankedOutcome>, DomainError> {
        self.require_phase(DeliberationPhase::Completed)?;
        let current: std::collections::BTreeSet<_> = self.ranking.iter().cloned().collect();
        let proposed: std::collections::BTreeSet<_> = ranking.iter().cloned().collect();
        if ranking.len() != self.ranking.len() || current != proposed {
            return Err(DomainError::InvariantViolated {
                reason: "reprioritized ranking must contain every completed proposal exactly once",
            });
        }

        let ranked = self.materialize_ranked_tuples(&ranking)?;
        self.ranking = ranking;
        Ok(ranked
            .into_iter()
            .enumerate()
            .map(|(i, (_, proposal, outcome))| {
                RankedOutcome::new(proposal, outcome, u32::try_from(i).unwrap_or(u32::MAX))
            })
            .collect())
    }

    /// Total duration from start to completion, when completed.
    #[must_use]
    pub fn duration(&self) -> Option<DurationMs> {
        self.completed_at.map(|end| {
            let delta = end - self.started_at;
            let millis = delta.whole_milliseconds();
            let bounded = u64::try_from(millis).unwrap_or(0);
            DurationMs::from_millis(bounded)
        })
    }

    #[must_use]
    pub fn ranking(&self) -> &[ProposalId] {
        &self.ranking
    }

    /// Reconstruct [`RankedOutcome`]s from the persisted ranking + the
    /// stored proposals and outcomes. Useful when an upstream caller
    /// (e.g. `RunCouncilDecisionUseCase` in Warn mode) needs to read a
    /// completed deliberation back from a repository without re-running
    /// the algorithm.
    ///
    /// Fails with [`DomainError::InvalidTransition`] if the deliberation
    /// is not yet in the `Completed` phase.
    pub fn ranked_outcomes(&self) -> Result<Vec<RankedOutcome>, DomainError> {
        self.require_phase(DeliberationPhase::Completed)?;
        Ok(self
            .materialize_ranked_tuples(&self.ranking)?
            .into_iter()
            .enumerate()
            .map(|(i, (_, proposal, outcome))| {
                RankedOutcome::new(proposal, outcome, u32::try_from(i).unwrap_or(u32::MAX))
            })
            .collect())
    }

    fn require_phase(&self, expected: DeliberationPhase) -> Result<(), DomainError> {
        if self.phase == expected {
            Ok(())
        } else {
            Err(DomainError::InvalidTransition {
                from: self.phase.name(),
                to: expected.name(),
            })
        }
    }

    fn materialize_ranked_tuples(
        &self,
        ranking: &[ProposalId],
    ) -> Result<Vec<(ProposalId, Proposal, ValidationOutcome)>, DomainError> {
        ranking
            .iter()
            .map(|id| {
                let proposal =
                    self.proposals
                        .get(id)
                        .cloned()
                        .ok_or(DomainError::InvariantViolated {
                            reason: "missing proposal in ranking",
                        })?;
                let outcome =
                    self.outcomes
                        .get(id)
                        .cloned()
                        .ok_or(DomainError::InvariantViolated {
                            reason: "missing outcome at Scoring",
                        })?;
                Ok::<_, DomainError>((id.clone(), proposal, outcome))
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entities::ValidatorReport;
    use crate::value_objects::{AgentId, Attributes, Score, TaskId};
    use time::macros::datetime;

    fn now() -> OffsetDateTime {
        datetime!(2026-04-15 12:00:00 UTC)
    }

    fn specialty() -> Specialty {
        Specialty::new("triage").unwrap()
    }

    fn start() -> Deliberation {
        Deliberation::start(
            TaskId::new("t1").unwrap(),
            specialty(),
            Rounds::default(),
            now(),
        )
    }

    fn proposal(id: &str, content: &str) -> Proposal {
        Proposal::new(
            ProposalId::new(id).unwrap(),
            AgentId::new("a").unwrap(),
            specialty(),
            content,
            Attributes::empty(),
            now(),
        )
        .unwrap()
    }

    fn outcome(score: f64) -> ValidationOutcome {
        ValidationOutcome::new(
            Score::new(score).unwrap(),
            vec![ValidatorReport::new("x", true, "", Attributes::empty()).unwrap()],
        )
    }

    #[test]
    fn starts_in_proposing() {
        let d = start();
        assert_eq!(d.phase(), DeliberationPhase::Proposing);
        assert!(d.proposals().is_empty());
        assert!(d.completed_at().is_none());
    }

    #[test]
    fn proposals_only_accepted_while_proposing() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        d.advance().unwrap(); // Revising
        let err = d.add_proposal(proposal("p2", "y")).unwrap_err();
        assert!(matches!(err, DomainError::InvalidTransition { .. }));
    }

    #[test]
    fn duplicate_proposal_id_is_rejected() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        assert!(matches!(
            d.add_proposal(proposal("p1", "y")).unwrap_err(),
            DomainError::AlreadyExists { .. }
        ));
    }

    #[test]
    fn cannot_leave_proposing_without_proposals() {
        let mut d = start();
        assert!(matches!(
            d.advance().unwrap_err(),
            DomainError::InvariantViolated { .. }
        ));
        assert_eq!(d.phase(), DeliberationPhase::Proposing);
    }

    #[test]
    fn revise_only_allowed_while_revising() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        assert!(matches!(
            d.revise_proposal(&ProposalId::new("p1").unwrap(), "y", now())
                .unwrap_err(),
            DomainError::InvalidTransition { .. }
        ));
        d.advance().unwrap(); // Revising
        d.revise_proposal(&ProposalId::new("p1").unwrap(), "y", now())
            .unwrap();
        assert_eq!(
            d.proposals()
                .get(&ProposalId::new("p1").unwrap())
                .unwrap()
                .content(),
            "y"
        );
    }

    #[test]
    fn cannot_enter_scoring_with_missing_outcomes() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        d.add_proposal(proposal("p2", "y")).unwrap();
        for _ in 0..2 {
            d.advance().unwrap();
        }
        // Now in Validating. Attach only one outcome.
        d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.9))
            .unwrap();
        assert!(matches!(
            d.advance().unwrap_err(),
            DomainError::InvariantViolated { .. }
        ));
    }

    #[test]
    fn duplicate_outcome_is_rejected() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        for _ in 0..2 {
            d.advance().unwrap();
        }
        d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.8))
            .unwrap();
        assert!(matches!(
            d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.9))
                .unwrap_err(),
            DomainError::AlreadyExists { .. }
        ));
    }

    #[test]
    fn complete_ranks_descending_by_score() {
        let mut d = start();
        d.add_proposal(proposal("p1", "a")).unwrap();
        d.add_proposal(proposal("p2", "b")).unwrap();
        d.add_proposal(proposal("p3", "c")).unwrap();
        for _ in 0..2 {
            d.advance().unwrap();
        }
        d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.5))
            .unwrap();
        d.attach_outcome(&ProposalId::new("p2").unwrap(), outcome(0.9))
            .unwrap();
        d.attach_outcome(&ProposalId::new("p3").unwrap(), outcome(0.7))
            .unwrap();
        d.advance().unwrap(); // Scoring

        let ranked = d.complete(datetime!(2026-04-15 12:00:01 UTC)).unwrap();
        assert_eq!(d.phase(), DeliberationPhase::Completed);
        assert_eq!(ranked[0].rank(), 0);
        assert_eq!(ranked[0].proposal().id().as_str(), "p2");
        assert_eq!(ranked[1].proposal().id().as_str(), "p3");
        assert_eq!(ranked[2].proposal().id().as_str(), "p1");
    }

    #[test]
    fn reprioritize_reorders_completed_ranking() {
        let mut d = start();
        d.add_proposal(proposal("p1", "a")).unwrap();
        d.add_proposal(proposal("p2", "b")).unwrap();
        for _ in 0..2 {
            d.advance().unwrap();
        }
        d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.9))
            .unwrap();
        d.attach_outcome(&ProposalId::new("p2").unwrap(), outcome(0.1))
            .unwrap();
        d.advance().unwrap();
        d.complete(now()).unwrap();

        let reprioritized = d
            .reprioritize(vec![
                ProposalId::new("p2").unwrap(),
                ProposalId::new("p1").unwrap(),
            ])
            .unwrap();
        assert_eq!(reprioritized[0].proposal().id().as_str(), "p2");
        assert_eq!(reprioritized[1].proposal().id().as_str(), "p1");
        assert_eq!(d.ranking()[0].as_str(), "p2");
    }

    #[test]
    fn ties_are_broken_by_proposal_id() {
        let mut d = start();
        d.add_proposal(proposal("p2", "a")).unwrap();
        d.add_proposal(proposal("p1", "b")).unwrap();
        for _ in 0..2 {
            d.advance().unwrap();
        }
        d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.7))
            .unwrap();
        d.attach_outcome(&ProposalId::new("p2").unwrap(), outcome(0.7))
            .unwrap();
        d.advance().unwrap();

        let ranked = d.complete(now()).unwrap();
        assert_eq!(ranked[0].proposal().id().as_str(), "p1");
        assert_eq!(ranked[1].proposal().id().as_str(), "p2");
    }

    #[test]
    fn complete_only_allowed_from_scoring() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        assert!(matches!(
            d.complete(now()).unwrap_err(),
            DomainError::InvalidTransition { .. }
        ));
    }

    #[test]
    fn completed_deliberation_has_duration() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        for _ in 0..2 {
            d.advance().unwrap();
        }
        d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.5))
            .unwrap();
        d.advance().unwrap();
        d.complete(datetime!(2026-04-15 12:00:00.750 UTC)).unwrap();

        assert_eq!(d.duration().unwrap().get(), 750);
    }

    #[test]
    fn cannot_advance_past_completed() {
        let mut d = start();
        d.add_proposal(proposal("p1", "x")).unwrap();
        for _ in 0..2 {
            d.advance().unwrap();
        }
        d.attach_outcome(&ProposalId::new("p1").unwrap(), outcome(0.5))
            .unwrap();
        d.advance().unwrap();
        d.complete(now()).unwrap();
        assert!(matches!(
            d.advance().unwrap_err(),
            DomainError::InvalidTransition { .. }
        ));
    }
}