magi-cli 0.274.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
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
//! Task/chat-native decision lifecycle. Delivery, reading and conversation turns
//! are deliberately absent: only an effect receipt or explicit settlement ends
//! a decision. This record travels with the durable inquiry, not a UI card.
use anyhow::{Result, ensure};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};

/// State of the requested decision effect, independent of message transport.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    /// The owner has not requested an operation.
    AwaitingOwner,
    /// An owner request is recorded; the consumer has not confirmed its effect.
    Queued,
    /// The consumer has begun the operation.
    InProgress,
    /// A failure or uncertain outcome needs reconciliation before retry.
    RetryNeeded,
    /// A durable receipt confirms the effect, or explicit settlement ends it.
    Resolved,
}

/// An append-only explanation of a state change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Event {
    /// Time recorded, never used as approval or resolution evidence.
    pub at: Timestamp,
    /// Resulting lifecycle status.
    pub status: Status,
    /// Owner request, effect receipt or settlement evidence.
    pub evidence: String,
}

/// Distinct reasons a decision no longer requires an operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Closure {
    /// The exact effect receipt was confirmed.
    Applied,
    /// The original target no longer admits the decision.
    Obsolete,
    /// The owner explicitly settled the inquiry.
    OwnerSettled,
}

/// The last confirmed read of an approval's exact forge target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetState {
    /// The PR is open.
    Open,
    /// The PR is merged.
    Merged,
    /// The PR is closed without merging.
    Closed,
    /// The forge did not provide a usable observation.
    Unknown,
}

/// Display evidence only; never a receipt or fresh consent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TargetObservation {
    /// Exact saved approval target.
    pub pr: String,
    /// Head the approval was originally about.
    pub target_head: String,
    /// Head returned by the forge, if known.
    pub head: Option<String>,
    /// Lifecycle returned by the forge.
    pub state: TargetState,
}

impl TargetObservation {
    pub(crate) fn stale(&self) -> bool {
        matches!(self.state, TargetState::Merged | TargetState::Closed)
            || (self.state == TargetState::Open
                && self
                    .head
                    .as_ref()
                    .is_some_and(|head| head != &self.target_head))
    }

    pub(crate) fn describe(&self) -> String {
        let state = match self.state {
            TargetState::Open => "open",
            TargetState::Merged => "merged",
            TargetState::Closed => "closed without merging",
            TargetState::Unknown => "unknown (forge observation unavailable)",
        };
        let head = self.head.as_deref().unwrap_or("unknown");
        format!(
            "PR {}: {state}; observed head {head}; approval head {}",
            self.pr, self.target_head
        )
    }
}

/// Display classification shared by the list, its badge and chat triage.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Attention {
    OwnerChoice,
    ReceiptCheck,
    InFlight,
    ReleaseFollowup,
    StaleTarget,
    Resolved,
}

/// Durable decision state embedded in an inquiry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Decision {
    /// Concise reason shown on a phone without opening the conversation.
    pub reason: String,
    /// Current effect status.
    pub status: Status,
    /// Recorded owner request; migration never manufactures one.
    pub request: Option<String>,
    /// Current actionable error, including uncertainty about an external call.
    pub error: Option<String>,
    /// The consumer proved that the last attempt failed before any effect.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub retry_safe: bool,
    /// Exact source response generation accepted by a fresh owner command.
    /// Migration never fills this field from a saved reply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_answer_at: Option<Timestamp>,
    /// Explicit owner confirmation that an accepted legacy effect has no
    /// remaining work. Operational source readers must not consume it again.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub legacy_settled: bool,
    /// Resolution provenance; absent in historical records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closure: Option<Closure>,
    /// A source question proven retired independently of its saved reply.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub source_retired: bool,
    /// Latest read-only forge evidence, not a decision outcome.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_observation: Option<TargetObservation>,
    /// Complete lifecycle history; never pruned by delivery or read receipts.
    pub history: Vec<Event>,
}

impl Decision {
    /// File an inquiry which requires owner input.
    pub fn awaiting(reason: String) -> Self {
        Self {
            reason,
            status: Status::AwaitingOwner,
            request: None,
            error: None,
            retry_safe: false,
            source_answer_at: None,
            legacy_settled: false,
            closure: None,
            source_retired: false,
            last_observation: None,
            history: vec![],
        }
    }

    pub(crate) fn attention(&self, release: bool) -> Attention {
        if self.status == Status::Resolved {
            return Attention::Resolved;
        }
        if self
            .last_observation
            .as_ref()
            .is_some_and(TargetObservation::stale)
        {
            return if self.request.is_some() && !self.retry_safe {
                Attention::ReceiptCheck
            } else {
                Attention::StaleTarget
            };
        }
        if self
            .last_observation
            .as_ref()
            .is_some_and(|o| o.state == TargetState::Unknown)
        {
            return Attention::ReceiptCheck;
        }
        match self.status {
            Status::AwaitingOwner => Attention::OwnerChoice,
            Status::RetryNeeded if self.retry_safe => Attention::OwnerChoice,
            Status::RetryNeeded => Attention::ReceiptCheck,
            Status::Queued | Status::InProgress if release => Attention::ReleaseFollowup,
            Status::Queued | Status::InProgress => Attention::InFlight,
            Status::Resolved => Attention::Resolved,
        }
    }

    pub(crate) fn observe(&mut self, observation: TargetObservation) -> bool {
        if self.status == Status::Resolved || self.last_observation.as_ref() == Some(&observation) {
            return false;
        }
        self.last_observation = Some(observation);
        true
    }

    pub(crate) fn retire_target(&mut self, reason: &str) -> Result<bool> {
        let changed = if self.request.is_some() && self.retry_safe {
            ensure!(
                self.status == Status::RetryNeeded,
                "effect is not proven unstarted"
            );
            ensure!(!reason.trim().is_empty(), "retirement reason is empty");
            self.error = None;
            self.retry_safe = false;
            self.closure = Some(Closure::Obsolete);
            self.event(Status::Resolved, reason)
        } else {
            self.retire(reason)?
        };
        if changed {
            self.source_retired = true;
        }
        Ok(changed)
    }

    fn event(&mut self, status: Status, evidence: &str) -> bool {
        if self.status == status && self.history.last().is_some_and(|e| e.evidence == evidence) {
            return false;
        }
        self.status = status;
        self.history.push(Event {
            at: Timestamp::now(),
            status,
            evidence: evidence.to_owned(),
        });
        true
    }

    /// Record acceptance, without claiming that the command has been applied.
    pub fn accept(&mut self, request: &str) -> Result<bool> {
        ensure!(!request.trim().is_empty(), "decision request is empty");
        if let Some(prior) = &self.request {
            ensure!(
                prior == request,
                "decision already binds a different request"
            );
            return Ok(false);
        }
        ensure!(
            matches!(self.status, Status::AwaitingOwner | Status::RetryNeeded),
            "decision needs reconciliation"
        );
        self.request = Some(request.to_owned());
        self.error = None;
        Ok(self.event(Status::Queued, request))
    }

    /// The consumer begins the accepted effect; no automatic retry of uncertainty.
    pub fn start(&mut self) -> Result<bool> {
        ensure!(self.status == Status::Queued, "decision is not queued");
        ensure!(self.request.is_some(), "decision has no owner request");
        self.retry_safe = false;
        Ok(self.event(Status::InProgress, "effect consumer started"))
    }

    /// The command was accepted but a worker/forge effect is still outstanding.
    pub(crate) fn queued(&mut self) -> Result<bool> {
        ensure!(
            self.request.is_some() && self.status == Status::InProgress,
            "decision is not executing an owner request"
        );
        Ok(self.event(Status::Queued, "command accepted; effect not yet confirmed"))
    }

    /// Retain an unsuccessful or uncertain operation in the active list.
    pub fn fail(&mut self, error: &str) -> Result<bool> {
        ensure!(
            self.status != Status::Resolved,
            "decision is already resolved"
        );
        ensure!(!error.trim().is_empty(), "decision error is empty");
        self.error = Some(error.to_owned());
        self.retry_safe = false;
        Ok(self.event(Status::RetryNeeded, error))
    }

    /// Record proof that no operation began. This is distinct from uncertainty
    /// after a write or external call; only an owner retry may requeue it.
    pub(crate) fn fail_before_effect(&mut self, error: &str) -> Result<bool> {
        let prior = self.retry_safe;
        let changed = self.fail(error)?;
        self.retry_safe = true;
        Ok(changed || !prior)
    }

    /// Requeue the same owner request after a proven pre-execution failure.
    pub(crate) fn retry_unapplied(&mut self) -> Result<bool> {
        ensure!(
            self.status == Status::RetryNeeded && self.retry_safe && self.request.is_some(),
            "effect needs receipt reconciliation before retry"
        );
        self.error = None;
        self.retry_safe = false;
        Ok(self.event(
            Status::Queued,
            "owner retried a request proven not to have started",
        ))
    }

    /// Called only after rereading the operation's authoritative durable receipt.
    /// Also repairs a crash between application and updating this projection.
    pub(crate) fn applied(&mut self, receipt: &str) -> Result<bool> {
        ensure!(!receipt.trim().is_empty(), "effect receipt is empty");
        if self.status == Status::Resolved {
            return Ok(false);
        }
        self.error = None;
        self.retry_safe = false;
        self.closure = Some(Closure::Applied);
        Ok(self.event(Status::Resolved, receipt))
    }

    /// Retire passive history without claiming an owner settlement or effect.
    pub(crate) fn retire(&mut self, reason: &str) -> Result<bool> {
        ensure!(self.request.is_none(), "accepted effects cannot be retired");
        ensure!(!reason.trim().is_empty(), "retirement reason is empty");
        if self.status == Status::Resolved {
            return Ok(false);
        }
        ensure!(
            matches!(self.status, Status::AwaitingOwner | Status::RetryNeeded),
            "active effects cannot be retired"
        );
        self.error = None;
        self.retry_safe = false;
        self.closure = Some(Closure::Obsolete);
        Ok(self.event(Status::Resolved, reason))
    }

    /// Owner settlement is distinct from an application receipt. Legacy
    /// consumers cannot always prove their external outcome; the owner may
    /// explicitly confirm that no effect remains after inspecting it.
    pub(crate) fn settle_legacy(&mut self, reason: &str) -> Result<bool> {
        ensure!(
            self.request
                .as_deref()
                .is_some_and(|r| r.starts_with("decision: ")),
            "only an accepted legacy source decision supports this settlement"
        );
        ensure!(
            self.status != Status::InProgress,
            "effect consumer is still executing"
        );
        ensure!(!reason.trim().is_empty(), "settlement reason is empty");
        if self.status == Status::Resolved {
            return Ok(false);
        }
        self.legacy_settled = true;
        self.error = None;
        self.retry_safe = false;
        self.closure = Some(Closure::OwnerSettled);
        Ok(self.event(Status::Resolved, reason))
    }

    /// Explicitly settle discussion without an operation, or supersede it with
    /// another inquiry. A queued/uncertain effect must first be reconciled by
    /// its consumer; an owner reply alone cannot hide it.
    pub fn settle(&mut self, reason: &str) -> Result<bool> {
        ensure!(
            self.status == Status::AwaitingOwner
                || (self.status == Status::RetryNeeded
                    && (self.request.is_none() || self.retry_safe)),
            "an accepted effect requires receipt reconciliation"
        );
        ensure!(!reason.trim().is_empty(), "settlement reason is empty");
        self.closure = Some(Closure::OwnerSettled);
        Ok(self.event(Status::Resolved, reason))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn acceptance_is_not_application_and_history_explains_completion() {
        let mut decision = Decision::awaiting("Review the publication".into());
        decision.accept("owner requested publication").unwrap();
        assert_eq!(decision.status, Status::Queued);
        assert!(decision.settle("read the message").is_err());
        decision.start().unwrap();
        assert_eq!(decision.status, Status::InProgress);
        decision
            .applied("publication receipt: PR 42 confirmed")
            .unwrap();
        assert_eq!(decision.status, Status::Resolved);
        assert_eq!(decision.closure, Some(Closure::Applied));
        assert_eq!(decision.history.len(), 3);
        assert!(!decision.applied("same receipt after restart").unwrap());
    }

    #[test]
    fn uncertain_effect_cannot_be_blindly_replayed_or_settled() {
        let mut decision = Decision::awaiting("Retry checks".into());
        decision.accept("rerun request 12").unwrap();
        decision.start().unwrap();
        decision
            .fail("network lost after request: inspect receipt 12")
            .unwrap();
        let saved = serde_json::to_vec(&decision).unwrap();
        let mut restarted: Decision = serde_json::from_slice(&saved).unwrap();
        assert_eq!(restarted.status, Status::RetryNeeded);
        assert!(restarted.start().is_err());
        assert!(restarted.settle("reply was read").is_err());
        assert!(restarted.accept("a different request").is_err());
        restarted
            .applied("receipt 12: execution confirmed by forge")
            .unwrap();
        assert_eq!(restarted.status, Status::Resolved);
        assert!(restarted.error.is_none());
    }

    #[test]
    fn explicit_settlement_requires_a_reason_and_executes_nothing() {
        let mut decision = Decision::awaiting("Choose a direction".into());
        assert!(decision.settle("").is_err());
        decision
            .settle("owner explicitly confirmed no change is necessary")
            .unwrap();
        assert_eq!(decision.status, Status::Resolved);
        assert_eq!(decision.closure, Some(Closure::OwnerSettled));
        assert!(decision.request.is_none());
    }
}