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
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
//! Read-only classification of base stops, including diagnostic-only records.
use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::{Stop, StopKind};
use crate::run::RunState;

/// Original legacy evidence, retained in the authorization rather than invented
/// sequencer checkpoints. The digest also binds the currently approved base.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Evidence {
    /// SHA-256 of the normalized source and approved base.
    pub digest: String,
    /// Original diagnostic, repair records and terminal event with owner identity.
    pub source: serde_json::Value,
}

/// Saved evidence classification, independent of filesystem and Git reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Class {
    /// 整合する構造化停止が保存されている。
    Recorded,
    /// 旧形式の診断と修復履歴から停止を導出できる。
    LegacyTextual,
    /// Git stopped the recording exec without a textual conflict.
    SequencerInfrastructure,
    /// 通常のベース移動予算の枯渇。
    MovementExhausted,
    /// Known pre-sequencer preparation failure, with remaining budget.
    RecoverableUnknown,
    /// 停止を安全に証明する証拠が不足している。
    Insufficient,
}

/// Read-only assessment used by inspection and grant admission alike.
pub struct Assessment {
    /// 保存された証拠の分類。
    pub class: Class,
    /// 保存済み、または証拠から導出した停止。
    pub stop: Option<Stop>,
    /// 承認対象となる旧形式の証拠。
    pub legacy: Option<Evidence>,
    /// 証拠不足や矛盾の具体的な理由。
    pub missing: Option<String>,
}

impl Assessment {
    fn textual(self) -> Result<(Stop, Option<Evidence>)> {
        match self.class {
            Class::Recorded | Class::LegacyTextual => {
                Ok((self.stop.context("missing textual stop")?, self.legacy))
            }
            Class::MovementExhausted => anyhow::bail!(
                "ordinary movement exhaustion; use task control recover-base, not base-conflict repair"
            ),
            Class::SequencerInfrastructure => anyhow::bail!(
                "the rebase sequencer failed without a textual conflict; base-conflict repair is not applicable"
            ),
            Class::RecoverableUnknown => anyhow::bail!(
                "scratch preparation stop; use explicit terminal base recovery, not conflict repair"
            ),
            Class::Insufficient => anyhow::bail!("{}", self.missing.unwrap_or_default()),
        }
    }

    /// Stable labels for the operator-facing JSON report.
    pub fn report(&self) -> serde_json::Value {
        serde_json::json!({
            "classification": match self.class {
                Class::Recorded => "modern-textual-conflict",
                Class::LegacyTextual => "legacy-textual-conflict",
                Class::SequencerInfrastructure => "sequencer-infrastructure",
                Class::MovementExhausted => "movement-exhaustion",
                Class::RecoverableUnknown => "recoverable-unknown-stop",
                Class::Insufficient => "insufficient-evidence",
            },
            "stop": self.stop,
            "legacy": self.legacy,
            "missing_evidence": self.missing,
        })
    }
}

const NO_PATHS: &str = "; remaining conflicted path(s): none recorded";
pub(crate) const LEGACY_EXEC_ACTION: &str = "The saved Git output and empty conflict paths identify a failed recording exec. Restore Git and explicitly resume the retained run. Resume can reopen the original reservation only if ownership and Git state still match; neither conflict repair nor movement recovery applies.";

/// Older versions clipped Git's output to 250 characters. Accept a clipped
/// command only after the known Git-for-Windows shell crash, at that boundary.
fn failed_recording_exec(said: &str) -> bool {
    said.lines().any(|line| {
        let Some(command) = line
            .trim_start()
            .strip_prefix("warning: execution failed: ")
        else {
            return false;
        };
        command == crate::git::REBASE_EXEC
            || (said.chars().count() == 250
                && said.ends_with(command)
                && command.starts_with("git re")
                && crate::git::REBASE_EXEC.starts_with(command)
                && said.contains("sh.exe: *** fatal error - add_item")
                && said.contains("failed, errno "))
    })
}

/// Identify the retained HEAD from the failed exec and its repair records.
/// A missing stop SHA by itself also occurs in genuine legacy conflicts.
pub(crate) fn legacy_sequencer_head(state: &RunState) -> Option<&str> {
    let sync = state.base_sync.as_ref()?;
    let detail = sync.conflict.as_deref()?;
    let (summary, said) = detail.split_once(NO_PATHS)?;
    let said = said.strip_prefix("; git said: ")?;
    let head = state.rebase_fixes.last()?.from.as_deref()?;
    if head.is_empty()
        || !failed_recording_exec(said)
        || !summary.starts_with(&format!(
            "{} conflicts with {}/{} and did not rebase: conflict not resolved after ",
            state.winner()?.branch,
            state.config.merge.remote,
            state.base_branch
        ))
        || !state
            .rebase_fixes
            .iter()
            .filter(|r| r.from.as_deref() == Some(head))
            .all(|r| {
                r.paths.is_empty()
                    && r.stop.is_none()
                    && r.launcher.is_none()
                    && r.onto.as_ref().is_none_or(|tip| tip == &sync.tip)
            })
        || state
            .base_sync_recovery
            .operations
            .last()
            .is_some_and(|op| op.head != head || op.tip != sync.tip || op.validated_head.is_some())
        || state.base_sync_recovery.stop.as_ref().is_some_and(|stop| {
            stop.kind != StopKind::Conflict
                || stop.head != head
                || stop.tip != sync.tip
                || stop.detail != detail
                || stop.attempts != sync.attempts
        })
    {
        return None;
    }
    Some(head)
}

pub(crate) fn resumable_sequencer_stop(state: &RunState) -> bool {
    state.foreign_checkout.is_none()
        && state
            .base_sync_recovery
            .operations
            .last()
            .is_some_and(|op| op.finished)
        && legacy_sequencer_head(state).is_some()
}

/// Match both historical and current movement diagnostics exactly. Leftover
/// legacy repair records do not turn this diagnostic into a textual conflict.
pub fn classify(state: &RunState, head: &str, tip: &str) -> Assessment {
    let current = state.resource_block.as_ref().is_some_and(|block| {
        block.node == "rebase" && block.kind == crate::rebase::SEQUENCER_INFRASTRUCTURE
    });
    if current || legacy_sequencer_head(state) == Some(head) {
        return Assessment {
            class: Class::SequencerInfrastructure,
            stop: state.base_sync_recovery.stop.clone(),
            legacy: None,
            missing: None,
        };
    }
    if state.unknown_preparation_stop(head) {
        return Assessment {
            class: Class::RecoverableUnknown,
            stop: state.base_sync_recovery.stop.clone(),
            legacy: None,
            missing: None,
        };
    }
    if let (Some(sync), Some(winner)) = (&state.base_sync, state.winner()) {
        let exhausted = sync.attempts >= crate::graph::BASE_SYNC_ROUNDS
            && [("rebase(s)", "rebasing"), ("synchronization(s)", "synchronizing")]
                .iter().any(|(noun, verb)| sync.conflict.as_deref() == Some(format!(
                    "{} moved {} commit(s) ahead of {} after {} {}; {} again would only race it",
                    state.base_branch, sync.behind, winner.branch, crate::graph::BASE_SYNC_ROUNDS, noun, verb
                ).as_str()));
        let consistent = state.base_sync_recovery.stop.as_ref().is_none_or(|s| {
            s.kind == StopKind::Exhausted
                && s.head == head
                && s.tip == sync.tip
                && Some(&s.detail) == sync.conflict.as_ref()
                && s.attempts == sync.attempts
        });
        if exhausted && consistent {
            return Assessment {
                class: Class::MovementExhausted,
                stop: state.base_sync_recovery.stop.clone(),
                legacy: None,
                missing: None,
            };
        }
    }
    match derive_textual(state, head, tip) {
        Ok((stop, legacy)) => Assessment {
            class: if legacy.is_some() {
                Class::LegacyTextual
            } else {
                Class::Recorded
            },
            stop: Some(stop),
            legacy,
            missing: None,
        },
        Err(error) => Assessment {
            class: Class::Insufficient,
            stop: None,
            legacy: None,
            missing: Some(error.to_string()),
        },
    }
}

pub(super) fn textual_stop(
    state: &RunState,
    head: &str,
    tip: &str,
) -> Result<(Stop, Option<Evidence>)> {
    classify(state, head, tip).textual()
}

fn derive_textual(state: &RunState, head: &str, tip: &str) -> Result<(Stop, Option<Evidence>)> {
    let sync = state
        .base_sync
        .as_ref()
        .context("missing base synchronization evidence")?;
    let detail = sync
        .conflict
        .as_ref()
        .context("missing stopped synchronization diagnostic")?;
    if detail
        .split_once(NO_PATHS)
        .is_some_and(|(_, tail)| tail.is_empty() || tail.starts_with("; git said: "))
    {
        // "none recorded" is also a possible literal filename.
        ensure!(
            state.rebase_fixes.iter().any(|r| r.from.as_deref() == Some(head)
                && r.paths.as_slice() == ["none recorded"]),
            "no conflict paths were recorded; cannot establish a textual stop from the saved Git output and repair records"
        );
    }
    let old: Vec<_> = state
        .rebase_fixes
        .iter()
        .filter(|r| r.stop.is_none())
        .collect();
    // Completed legacy rounds remain in the append-only history. Prefer proof
    // of the current structured stop; unrelated old rounds cannot downgrade it.
    let structured = state.base_sync_recovery.stop.as_ref().is_some_and(|stop| {
        state
            .base_sync_recovery
            .operations
            .iter()
            .any(|op| op.head == stop.head && op.tip == stop.tip)
            || state
                .rebase_fixes
                .iter()
                .any(|r| r.stop.is_some() && r.from.as_ref() == Some(&stop.head))
    });
    if old.is_empty() || structured {
        let stop = state.base_sync_recovery.stop.as_ref().context(
            "missing structured textual-stop evidence; use task inspect-base-stop <task> --run <run>; movement recovery cannot authorize conflict repair",
        )?;
        ensure!(
            stop.kind == StopKind::Conflict,
            "stop is {:?}, not a textual conflict; movement exhaustion uses task control recover-base",
            stop.kind
        );
        ensure!(
            structured,
            "missing structured operation or sequencer evidence; an empty repair list does not prove a modern textual stop"
        );
        ensure!(
            stop.head == head
                && stop.tip == sync.tip
                && &stop.detail == detail
                && stop.attempts == sync.attempts,
            "structured textual stop disagrees with retained HEAD/base/diagnostic/attempts"
        );
        return Ok((stop.clone(), None));
    }
    let winner = state.winner().context("missing retained winner")?;
    let cap = state.config.graph.review_rounds;
    ensure!(
        cap > 0 && old.len() == cap && old.len() == state.rebase_fixes.len(),
        "legacy evidence ambiguous: expected exactly {cap} legacy repair records, with no mixed sequencer records"
    );
    let paths = &old[0].paths;
    ensure!(
        !paths.is_empty()
            && paths.len() <= 8
            && paths.iter().all(|p| {
                !p.is_empty()
                    && !p.contains([',', '\n', '\r'])
                    && !std::path::Path::new(p).is_absolute()
                    && std::path::Path::new(p)
                        .components()
                        .all(|c| matches!(c, std::path::Component::Normal(_)))
            })
            && paths
                .iter()
                .collect::<std::collections::BTreeSet<_>>()
                .len()
                == paths.len(),
        "legacy evidence ambiguous: missing, truncated or unsafe conflict paths"
    );
    ensure!(
        old.iter().all(|r| r.from.as_deref() == Some(head)
            && !r.finished
            && r.paths == *paths
            && r.index_outside.is_none()
            && r.launcher.is_none()
            && r.infra.is_none()
            && r.outage.is_none()
            && r.error.is_none()),
        "legacy evidence ambiguous: repair from/paths/completion or launcher evidence disagree"
    );
    let prefix = format!(
        "{} conflicts with {}/{} and did not rebase: conflict not resolved after {cap} of {cap} fixer round(s) (the rounds are spent); remaining conflicted path(s): {}",
        winner.branch,
        state.config.merge.remote,
        state.base_branch,
        paths.join(", ")
    );
    ensure!(
        detail == &prefix
            || detail
                .strip_prefix(&prefix)
                .is_some_and(|s| s.starts_with("; git said: ")),
        "legacy textual diagnostic does not match retained branch, repair count and paths; this is missing textual evidence, not movement exhaustion"
    );
    let terminal: Vec<_> = state
        .events
        .iter()
        .filter(|e| e.node == "land" && &e.message == detail)
        .collect();
    ensure!(
        terminal.len() == 1,
        "legacy evidence requires one matching terminal land event (found {})",
        terminal.len()
    );
    ensure!(
        sync.attempts > 0 && sync.behind > 0,
        "legacy evidence missing stopped base reservation"
    );
    let stop = Stop {
        kind: StopKind::Conflict,
        head: head.into(),
        tip: sync.tip.clone(),
        attempts: sync.attempts,
        detail: detail.clone(),
        at: terminal[0].at,
        unverified_sync: false,
    };
    if let Some(saved) = &state.base_sync_recovery.stop {
        ensure!(
            saved == &stop,
            "legacy evidence disagrees with subsequently recorded stop; inspect retained records before authorizing"
        );
    }
    let source = serde_json::json!({"version": 1, "task": state.origin.as_ref().and_then(|o| o.task.as_ref()),
        "run": state.id, "branch": winner.branch, "base_sync": sync, "stop": stop, "repairs": state.rebase_fixes,
        "terminal": terminal[0], "approved_base": tip});
    let digest = Sha256::digest(serde_json::to_vec(&source)?)
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect();
    Ok((stop, Some(Evidence { digest, source })))
}

/// Inspect saved evidence and present Git state without acquiring writable
/// maintenance locks, fetching, changing a checkpoint or queueing a driver.
pub async fn inspect(
    queue: &crate::queue::Queue,
    home: &std::path::Path,
    task: &str,
    run: &str,
) -> Result<serde_json::Value> {
    let task = queue.get(&queue.resolve_id(task)?)?;
    let state = RunState::load_under(run, home)?;
    ensure!(
        task.execution_runs().last() == Some(&state.id)
            && state.origin.as_ref().and_then(|o| o.task.as_deref()) == Some(task.id.as_str()),
        "inspection refused: task/run ownership disagrees"
    );
    let winner = state
        .winner()
        .context("missing retained winner; locate the owned retained branch before recovery")?;
    let head = crate::git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
        .await.context("missing retained branch; locate the owned implementation ref before recovery, without replacing or resetting it")?;
    let tip = crate::git::rev_parse(
        &state.repo,
        &format!(
            "refs/remotes/{}/{}",
            state.config.merge.remote, state.base_branch
        ),
    )
    .await?;
    let mut result = serde_json::json!({"task": task.id, "run": state.id, "head": head, "base": tip,
        "scratch_present": home.join("runs").join(&state.id).join("base-sync").exists(),
        "next_step": "Retain all records and commits. Inspect the missing evidence; do not edit JSON, reset budgets or start another run."});
    let assessment = classify(&state, &head, &tip);
    result
        .as_object_mut()
        .unwrap()
        .extend(assessment.report().as_object().unwrap().clone());
    if assessment.class == Class::SequencerInfrastructure {
        let action = if legacy_sequencer_head(&state).is_some() {
            LEGACY_EXEC_ACTION
        } else {
            result["resource_block"] = serde_json::to_value(&state.resource_block)?;
            "Restore the required resource and explicitly resume the retained run. No conflict repair is needed."
        };
        result["next_step"] = action.into();
        return Ok(result);
    }
    if assessment.class == Class::Insufficient
        && state
            .base_sync_recovery
            .stop
            .as_ref()
            .is_some_and(|s| s.kind == StopKind::Unknown)
    {
        result["next_step"] = "Compare the stop diagnostic and timestamp with the saved land event; inspect the finished operation, unchanged winner HEAD, stopped base tip and remaining episode budget. Only the exact Windows magi-rebase-heads spawn error (os error 267) is supported. Preserve the run and scratch; do not clear the stop or start a new competition.".into();
    }
    if assessment.class == Class::RecoverableUnknown {
        let digest = state.preparation_digest(&head).unwrap();
        result["evidence_digest"] = digest.clone().into();
        let checks = async {
            ensure!(task.assignment_accepts(&state), "task assignment changed");
            ensure!(
                task.status != crate::queue::TaskStatus::Running,
                "task driver is running"
            );
            let claimed =
                crate::daemon::is_working_on_other(home, &state.id, jiff::Timestamp::now())?;
            ensure!(
                state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
                "driver is live or unknown; wait for supported driver cleanup before recovery"
            );
            ensure!(
                crate::git::is_ancestor(&state.repo, &assessment.stop.as_ref().unwrap().tip, &tip)
                    .await,
                "current base does not descend from stopped base"
            );
            crate::git::check_rebase_preparation(&state, &head, &home.join("runs").join(&state.id))
                .await?;
            Ok::<_, anyhow::Error>(())
        }
        .await;
        if let Err(error) = checks {
            result["admission_blocker"] = error.to_string().into();
            result["next_step"] = "Resolve the reported blocker through supported controls, preserve the scratch and branch, and inspect again. Inspection grants no authorization.".into();
        } else {
            result["next_step"] = format!("Install the Windows scratch preparation fix; explicitly authorize with `magi task control recover-base {} --request <unique-id> --head {head} --evidence-digest {digest}` or `magi run --resume {} --recover-base --evidence-digest {digest}`. Authorization probes the current preparation path before allowing the remaining budget.", state.id, state.id).into();
        }
        return Ok(result);
    }
    if assessment.class == Class::MovementExhausted {
        result["next_step"] = format!(
            "Use task control recover-base {} --request <unique-id> --head {head}",
            state.id
        )
        .into();
        return Ok(result);
    }
    if let Ok((stop, evidence)) = assessment.textual() {
        let checks = async {
                ensure!(!state.passes.is_empty(), "missing stopped pass checkpoint; inspect retained run provenance before recovery");
                super::controls(home, &task, &state, super::Kind::BaseConflict, false)?;
                super::owner_effects_settled(home, &task, &state)?;
                super::unique_owner(queue, &task, &state)?;
                ensure!(task.status != crate::queue::TaskStatus::Running, "task driver is running");
                let claimed = crate::daemon::is_working_on_other(home, &state.id, jiff::Timestamp::now())?;
                ensure!(state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
                    "driver is live or unknown; wait for supported driver cleanup before granting recovery");
                super::head_and_public(&state, &head).await?;
                ensure!(
                    crate::git::is_ancestor(&state.repo, &stop.tip, &tip).await,
                    "current base does not descend from stopped base"
                );
                Ok::<_, anyhow::Error>(())
            }
            .await;
        if let Err(error) = checks {
            result["admission_blocker"] = error.to_string().into();
            result["next_step"] = "Resolve the reported ownership, hold or Git-state blocker through its supported owner control, then inspect again. Inspection grants no authorization.".into();
        } else {
            let digest = evidence.as_ref().map_or(String::new(), |e| {
                format!(" --evidence-digest {}", e.digest)
            });
            result["next_step"] = format!("magi task grant-repair {} --run {} --kind base-conflict --rounds 1 --head {head} --tip {tip} --expect-pass {}{digest} --request <unique-id> --reason <reason> --instruction <approved-resolution>", task.id, state.id, state.passes.last().map_or(0, |p| p.index)).into();
        }
    }
    Ok(result)
}