agengo 0.5.3

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
mod complete;
mod dispatch;
mod integrate;

use crate::failure::DependencyMissing;
use crate::process::CANCEL_ASSIGNMENTS;
use crate::{
    adapter::Action,
    agent::{Assignment, Blocker, BlockerKind, Choice, Handoff, Role},
    context,
    contract::{overlaps, string_or_empty},
    handoff, inbox,
    integrity::Baseline,
    plan::{Argv, Plan, Task},
    process::{run, Repo, INTERRUPTED},
    store::{code, parse, request_kind, show, Settings, Store, HANDOFFS},
};
use anyhow::{bail, Context, Result};
use dispatch::run_assignment;
use rusqlite::params;
use serde_json::{json, Value};
use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
    sync::{atomic::Ordering, mpsc, OnceLock},
    thread,
    time::Instant,
};
use uuid::Uuid;

struct CancelAssignments;

struct AssignmentOutput {
    response: Value,
    setup_artifacts: BTreeSet<String>,
    /// Verifier report on the review's blocking findings, when one ran.
    verification: Option<Value>,
}

impl Drop for CancelAssignments {
    fn drop(&mut self) {
        CANCEL_ASSIGNMENTS.store(true, Ordering::Relaxed);
    }
}

pub fn id() -> String {
    Uuid::new_v4().simple().to_string()
}
pub fn reference(id: &str) -> String {
    format!("refs/heads/af/{id}")
}

pub fn rows(store: &Store, id: &str) -> Result<BTreeMap<String, Value>> {
    Ok(store
        .rows("SELECT * FROM tasks WHERE run_id=?", &[&id])?
        .into_iter()
        .map(|value| (string_or_empty(&value["id"]).to_owned(), value))
        .collect())
}
/// Remove a run's worktrees. With `refs`, also delete its temporary build
/// branches and pinned candidate refs; only safe once the run is delivered,
/// because unfinished tasks still point at those commits.
pub fn cleanup(repo: &Repo, id: &str, refs: bool) -> Result<String> {
    let mut worktrees = 0;
    for root in repo.run_worktree_roots(id) {
        worktrees += repo.remove_worktrees_under(&root)?;
    }
    let deleted = if refs {
        repo.delete_refs(&[
            &format!("refs/heads/af-work/{id}/"),
            &format!("{}/{id}/", handoff::BUILD_REFS),
        ])?
        .len()
    } else {
        0
    };
    Ok(format!(
        "Removed {worktrees} worktree(s) and {deleted} temporary ref(s) of run {id}."
    ))
}

pub fn holds(store: &Store, id: &str) -> Result<BTreeSet<String>> {
    Ok(store
        .rows("SELECT task_id FROM task_holds WHERE run_id=?", &[&id])?
        .iter()
        .map(|value| string_or_empty(&value["task_id"]).to_owned())
        .collect())
}
pub fn progress(plan: &Plan, rows: &BTreeMap<String, Value>, held: &BTreeSet<String>) -> String {
    let integrated = rows
        .values()
        .filter(|row| row["state"] == "integrated")
        .count();
    let mut result = format!("Integrated {integrated}/{} tasks.", rows.len());
    let mut active = Vec::new();
    let mut blocked = Vec::new();
    let mut waiting = Vec::new();
    let mut ready = Vec::new();
    for task in &plan.tasks {
        let key = task.id.as_str();
        if held.contains(key) {
            continue;
        }
        match string_or_empty(&rows[key]["state"]) {
            "building" | "verifying" | "ready_review" | "reviewing" | "passed" => active.push(key),
            "blocked" => blocked.push(key),
            "pending"
                if task
                    .depends
                    .iter()
                    .any(|dep| rows[dep.as_str()]["state"] != "integrated") =>
            {
                waiting.push(key)
            }
            "pending" => ready.push(key),
            _ => {}
        }
    }
    for (label, ids) in [
        ("Active", active),
        ("Blocked", blocked),
        ("Waiting on dependencies", waiting),
        ("Ready", ready),
        ("Paused", held.iter().map(String::as_str).collect()),
    ] {
        if !ids.is_empty() {
            result.push_str(&format!(" {label}: {}.", ids.join(", ")));
        }
    }
    result
}

/// Decision offered when an assignment fails for a technical reason such as
/// an agent crash, a timeout, or a reply that breaks the contract.
fn incident_blocker(role: Role) -> Blocker {
    Blocker::decision(format!("Retry the {} attempt; add guidance with --note if needed.", role.as_str()))
        .alternative("Approve a revised plan if the problem comes from the scope, the checks or the environment.")
        .reason("The previous attempt failed for a technical reason (agent error, timeout or a reply that breaks the contract). See status --json for details.")
}

pub fn action_blocker(error: &anyhow::Error) -> Option<Blocker> {
    error
        .downcast_ref::<Action>()
        .map(|action| Blocker::action(&action.recommendation, &action.reason))
}

pub struct Engine<'a> {
    pub repo: &'a Repo,
    pub store: &'a Store,
    pub run: Value,
    pub settings: Settings,
    pub plan: Plan,
    pub profile: Value,
    pub id: &'a str,
    mode: Handoff,
    reference: String,
    /// Hooks, configuration and refs recorded when `execute` starts.
    integrity: OnceLock<Baseline>,
}

impl<'a> Engine<'a> {
    pub fn new(repo: &'a Repo, store: &'a Store, id: &'a str) -> Result<Self> {
        let run = store.run(id)?;
        let plan = store.plan(&run)?;
        let saved = store.one("SELECT body FROM run_role_profiles WHERE run_id=?", &[&id])?;
        let mut profile = match saved {
            Some(row) => parse(&row["body"])?,
            None => crate::contract::profile(None)?,
        };
        // Runs started before the verifier existed saved profiles without it.
        if profile["roles"]["verify"].is_null() {
            profile["roles"]["verify"] = crate::contract::profile(None)?["roles"]["verify"].take();
        }
        let mut settings = Settings::from_row(&run)?;
        settings.config = crate::config::load(&repo.root)?;
        Ok(Self {
            repo,
            store,
            settings,
            run,
            plan,
            profile,
            id,
            mode: if store.handoff_mode(id)? == "commit" {
                Handoff::Commit
            } else {
                Handoff::Worktree
            },
            reference: reference(id),
            integrity: OnceLock::new(),
        })
    }

    /// Remove a worktree that agengo no longer needs. Failure only warns,
    /// because the run's result does not depend on it.
    pub fn discard(&self, path: &Path) {
        if let Err(error) = self.repo.remove_worktree(path) {
            eprintln!(
                "agengo: could not remove worktree {}: {error:#}",
                path.display()
            );
        }
    }

    pub fn tip(&self) -> Result<String> {
        Ok(string_or_empty(&self.store.run(self.id)?["tip"]).into())
    }
    pub fn workspace(&self, phase: &str, key: &str) -> PathBuf {
        self.repo.worktrees.join(self.id).join(phase).join(key)
    }
    pub fn timeout(&self) -> u64 {
        self.settings.timeout
    }
    /// Stop for a person if agents changed Git hooks or configuration.
    fn guard(&self) -> Result<()> {
        match self.integrity.get() {
            Some(baseline) => baseline.check(self.repo),
            None => Ok(()),
        }
    }
    fn notice(
        &self,
        task: Option<&Task>,
        kind: &str,
        detail: Value,
        checkpoint: Option<Value>,
    ) -> Result<Value> {
        self.store.notice(
            self.id,
            task.map(|task| task.id.as_str()),
            kind,
            task.map_or(self.plan.goal.as_str(), Task::title),
            detail,
            checkpoint,
        )
    }
    fn action(&self, task: Option<&str>, phase: &str) -> Result<Option<Value>> {
        let possible = self.store.pending(self.id, task)?;
        if let Some(row) = possible {
            if row["kind"] == "action"
                && row["state"] == "received"
                && parse(&row["checkpoint"])?["phase"] == phase
            {
                return Ok(Some(row));
            }
        }
        Ok(None)
    }
    fn acknowledge(&self, request: &Value, task: Option<&Task>, outcome: &str) -> Result<Value> {
        self.store
            .transition(request, "resolved", None, Some(outcome))?;
        self.notice(
            task,
            "control",
            json!({"situation":format!("{} · {outcome}",code(request).unwrap_or_default())}),
            None,
        )
    }

    fn request(
        &self,
        task: Option<&Task>,
        phase: &str,
        head: &Value,
        message: &str,
        blocker: Option<&Blocker>,
    ) -> Result<Value> {
        let mut detail = json!({"situation":message});
        fn filled(value: &Option<String>) -> Option<&str> {
            value.as_deref().filter(|value| !value.trim().is_empty())
        }
        let recommendation = blocker.and_then(|blocker| filled(&blocker.recommendation));
        let reason = blocker.and_then(|blocker| filled(&blocker.reason));
        let kind = match blocker.map(|blocker| blocker.kind) {
            Some(BlockerKind::Action) => {
                detail["recommendation"] =
                    json!(recommendation.unwrap_or("Resolve the condition that blocks the run."));
                detail["reason"] = json!(
                    reason.unwrap_or("The task needs this condition before it can run again.")
                );
                detail["response"] =
                    json!("Confirm when it is done and briefly note what changed.");
                "action"
            }
            Some(BlockerKind::Decision) => {
                let choice = match blocker.and_then(|blocker| blocker.recommended_choice) {
                    Some(Choice::B) => "B",
                    _ => "A",
                };
                let alternative = blocker.and_then(|blocker| filled(&blocker.alternative));
                let a = if choice == "A" {
                    recommendation
                } else {
                    alternative
                }
                .unwrap_or("Retry with your guidance under the current plan.");
                let b = if choice == "B" {
                    recommendation
                } else {
                    alternative
                }
                .unwrap_or("Approve a revised plan.");
                detail["recommendation"] =
                    json!(format!("{choice} · {}", if choice == "A" { a } else { b }));
                detail["recommended_choice"] = json!(choice);
                detail["reason"] = json!(reason.unwrap_or(if choice == "A" {
                    "Keeps the approved commitments and gives the agent guidance."
                } else {
                    "Changing commitments must be recorded in the plan."
                }));
                detail["options"] = json!([{"id":"A","label":a},{"id":"B","label":b}]);
                detail["response"] = json!("Choose A with guidance, or B with a new plan.");
                "decision"
            }
            _ => {
                detail["response"] = json!(recommendation.unwrap_or(
                    "Provide the information or constraint the task needs to continue."
                ));
                "information"
            }
        };
        let task_id = task.map(|task| task.id.as_str());
        detail["impact"] = json!(if let Some(id) = task_id {
            self.impact(id)?
        } else {
            "Integrated tasks are kept. The run is waiting for final checks.".into()
        });
        let checkpoint = json!({"phase":phase,"head":head});
        if let Some(previous) = self.store.pending(self.id, task_id)? {
            if kind == "action"
                && previous["kind"] == "action"
                && parse(&previous["checkpoint"])? == checkpoint
                && parse(&previous["detail"])?["situation"] == message
            {
                self.store.transition(
                    &previous,
                    "open",
                    None,
                    Some("The condition is still not met."),
                )?;
                self.store.0.execute(
                    "UPDATE notices SET detail=? WHERE id=?",
                    params![detail.to_string(), previous["id"].as_i64()],
                )?;
                return self
                    .store
                    .pending(self.id, task_id)?
                    .context("missing reopened request");
            }
            self.store.transition(
                &previous,
                "superseded",
                None,
                Some("The run raised a newer request."),
            )?;
        }
        self.notice(task, kind, detail, Some(checkpoint))
    }

    fn notify(&self, notice: &Value) -> Result<()> {
        if request_kind(notice) {
            inbox::publish(self.store, self.id, &self.plan, false)
        } else {
            show(notice)
        }
    }

    fn impact(&self, task: &str) -> Result<String> {
        let tasks = rows(self.store, self.id)?;
        let waits = inbox::waiting_dependents(&self.plan, &tasks, task);
        let consequence = if waits.is_empty() {
            String::new()
        } else {
            format!(". Waiting dependents: {}", waits.join(", "))
        };
        Ok(format!(
            "{task} is on hold{consequence}. Independent tasks continue."
        ))
    }

    fn reconcile(&self) -> Result<()> {
        let current = self.repo.current(&self.reference)?;
        if let Some(intent) = self
            .store
            .one("SELECT * FROM integrations WHERE run_id=?", &[&self.id])?
        {
            let previous = string_or_empty(&intent["previous"]);
            let candidate = string_or_empty(&intent["candidate"]);
            let task = string_or_empty(&intent["task_id"]);
            if current.as_deref() == Some(previous) && previous != candidate {
                if self.repo.checked_out(&self.reference)? {
                    bail!(
                        "switch away from {} before resuming the run",
                        self.reference
                    );
                }
                self.repo
                    .set_ref(&self.reference, candidate, Some(previous))?;
            } else if current.as_deref() != Some(candidate) {
                bail!(
                    "{} changed outside agengo during integration",
                    self.reference
                );
            }
            let applied = self.store.atomic(|| {
                self.store.0.execute(
                    "UPDATE runs SET tip=? WHERE id=?",
                    params![candidate, self.id],
                )?;
                self.store.0.execute(
                    "UPDATE tasks SET state='integrated',message=NULL WHERE run_id=? AND id=?",
                    params![self.id, task],
                )?;
                self.store.0.execute(
                    "INSERT OR REPLACE INTO integrated_tasks VALUES (?,?,?)",
                    params![self.id, task, candidate],
                )?;
                self.store
                    .0
                    .execute("DELETE FROM integrations WHERE run_id=?", params![self.id])?;
                self.action(Some(task), "integration")?
                    .map(|action| {
                        self.acknowledge(
                            &action,
                            Some(self.plan.task(task)?),
                            &format!("Unblocked {task}. Integration checks passed."),
                        )
                    })
                    .transpose()
            })?;
            if let Some(applied) = applied {
                show(&applied)?;
            }
            return Ok(());
        }
        let base = string_or_empty(&self.run["base"]);
        let current = if self.store.run(self.id)?["ref_initialized"] == 0 {
            if current.is_none() {
                self.repo.set_ref(&self.reference, base, None)?;
            }
            let current = current.unwrap_or_else(|| base.into());
            if current == base {
                self.store.0.execute(
                    "UPDATE runs SET ref_initialized=1 WHERE id=?",
                    params![self.id],
                )?;
            }
            Some(current)
        } else {
            current
        };
        if current.as_deref() != Some(self.tip()?.as_str()) {
            bail!(
                "{} differs from the recorded integration commit {tip}; restore it with `git update-ref {} {tip}` before resuming",
                self.reference,
                self.reference,
                tip = self.tip()?
            );
        }
        Ok(())
    }

    pub fn attempt(
        &self,
        attempt: &str,
        task: Option<&str>,
        role: &str,
        request: &Value,
    ) -> Result<()> {
        self.store.0.execute(
            "INSERT INTO attempts VALUES (?,?,?,?,'active',?,NULL)",
            params![attempt, self.id, task, role, request.to_string()],
        )?;
        Ok(())
    }
    pub fn result(&self, attempt: &str, state: &str, report: &Value) -> Result<()> {
        self.store.0.execute(
            "UPDATE attempts SET state=?,result=? WHERE id=?",
            params![state, report.to_string(), attempt],
        )?;
        Ok(())
    }

    pub fn checks<'b>(
        &self,
        commands: impl IntoIterator<Item = &'b Argv>,
        path: &Path,
        role: &str,
        task: Option<&str>,
    ) -> Result<()> {
        for command in commands {
            let key = id();
            let head = self.repo.sha_at("HEAD", path)?;
            self.attempt(
                &key,
                task,
                role,
                &json!({"command":command,"worktree":path,"head":head}),
            )?;
            let started = Instant::now();
            // Setup commands keep the network (they install dependencies), also
            // when they run again on a candidate commit.
            let phase = if role.ends_with("_setup") {
                crate::sandbox::Phase::Setup
            } else {
                crate::sandbox::Phase::Check
            };
            let result = run(
                &mut crate::sandbox::plan_command(command, path, &self.settings.config, phase)?,
                None,
                Some(self.timeout()),
            );
            let report = match &result {
                Ok(output) => match self.repo.snapshot(path, &head) {
                    Ok(()) => {
                        json!({"exit":output.status.code().unwrap_or(-1),"stdout":String::from_utf8_lossy(&output.stdout),
                        "stderr":String::from_utf8_lossy(&output.stderr)})
                    }
                    Err(error) => json!({"exit":null,"stderr":error.to_string()}),
                },
                Err(error) => json!({"exit":null,"stderr":format!("{error:#}")}),
            };
            let elapsed = started.elapsed();
            let success = report["exit"] == 0;
            self.store.atomic(|| {
                self.store.record_duration(&key, elapsed)?;
                self.result(&key, if success { "ok" } else { "failed" }, &report)
            })?;
            // Checks run code the agents wrote.
            self.guard()?;
            if !success {
                let message = format!(
                    "check failed ({})\n{}",
                    json!(command),
                    context::last_chars(context::failure_text(&report), 1500)
                );
                if let Err(error) = result {
                    if error.downcast_ref::<std::io::Error>().is_some_and(|error| {
                        matches!(
                            error.kind(),
                            std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied
                        )
                    }) {
                        return Err(Action {
                            message,
                            recommendation: format!(
                                "Check that {} is installed and executable.",
                                command.first().map_or("", String::as_str)
                            ),
                            reason: "The check command could not start.".into(),
                        }
                        .into());
                    }
                }
                bail!("{message}");
            }
        }
        Ok(())
    }

    pub fn execute(&self) -> Result<bool> {
        if matches!(
            string_or_empty(&self.run["state"]),
            "awaiting_approval" | "approval_rejected"
        ) {
            inbox::publish(self.store, self.id, &self.plan, false)?;
            return Ok(false);
        }
        self.reconcile()?;
        if self.run["state"] == "done" {
            show(
                &json!({"kind":"delivery","run_id":self.id,"title":self.plan.goal,"detail":self.delivery(&self.tip()?)?.to_string()}),
            )?;
            return Ok(true);
        }
        if self.run["state"] == "final_failed" {
            let blocked = self.store.atomic(|| {
                if let Some(pending) = self.store.pending(self.id, None)? {
                    if pending["kind"] == "action" && pending["state"] == "open" {
                        return Ok(Some(pending));
                    }
                    if pending["kind"] == "decision" {
                        self.store.transition(
                            &pending,
                            "superseded",
                            None,
                            Some("Final checks re-run requested."),
                        )?;
                    }
                }
                self.store.0.execute(
                    "UPDATE runs SET state='running',message=NULL WHERE id=?",
                    params![self.id],
                )?;
                Ok(None)
            })?;
            if blocked.is_some() {
                inbox::publish(self.store, self.id, &self.plan, false)?;
                return Ok(false);
            }
        }
        self.store.atomic(|| {
            self.store.0.execute("UPDATE attempts SET state='interrupted' WHERE run_id=? AND state='active'",params![self.id])?;
            self.store.0.execute("UPDATE tasks SET attempt=NULL,state=CASE state WHEN 'building' THEN 'pending' WHEN 'reviewing' THEN 'ready_review' END
                WHERE run_id=? AND state IN ('building','reviewing')",params![self.id])?;
            Ok(())
        })?;
        self.store.atomic(|| {
            for (task,row) in rows(self.store,self.id)? {
                if row["state"] != "blocked" || self.store.one(
                    "SELECT 1 FROM notices WHERE run_id=? AND task_id=? AND (state IN ('open','received') OR kind='incident')",
                    &[&self.id,&task])?.is_some() { continue; }
                let phase = if row["retry_state"] == "ready_review" {"review"} else {"build"};
                self.request(Some(self.plan.task(&task)?),phase,
                    if phase == "review" {&row["head"]} else {&Value::Null},
                    row["message"].as_str().unwrap_or("Task blocked."),None)?;
            }
            Ok(())
        })?;
        inbox::publish(self.store, self.id, &self.plan, false)?;
        if self.integrity.get().is_none() {
            let _ = self.integrity.set(Baseline::capture(self.repo)?);
        }
        let (send, receive) = mpsc::channel();
        let result = thread::scope(|scope| -> Result<bool> {
            let _cancel_workers = CancelAssignments;
            let mut active = BTreeMap::<String, Assignment>::new();
            let mut integrated = rows(self.store, self.id)?
                .values()
                .filter(|row| row["state"] == "integrated")
                .count();
            loop {
                if INTERRUPTED.load(Ordering::Relaxed) {
                    bail!("run interrupted");
                }
                for record in self.store.rows(&format!("{HANDOFFS} AND EXISTS(SELECT 1 FROM tasks t WHERE t.run_id=a.run_id
                    AND t.id=a.task_id AND t.attempt=a.id AND t.state='verifying') ORDER BY a.rowid"),&[&self.id])? {
                    self.finish_handoff(&record)?;
                }
                let held = holds(self.store, self.id)?;
                for (task_id, row) in rows(self.store, self.id)? {
                    if row["state"] == "passed" && !held.contains(&task_id) {
                        self.integrate(self.plan.task(&task_id)?, &row)?;
                    }
                }
                let current = rows(self.store, self.id)?;
                let now_integrated = current
                    .values()
                    .filter(|row| row["state"] == "integrated")
                    .count();
                if now_integrated == current.len() {
                    return self.final_steps();
                }
                for (role, state) in [(Role::Review, "ready_review"), (Role::Build, "pending")] {
                    for task in &self.plan.tasks {
                        if active.len() >= self.settings.jobs {
                            break;
                        }
                        let task_id = task.id.as_str();
                        if current[task_id]["state"] != state
                            || held.contains(task_id)
                            || task
                                .depends
                                .iter()
                                .any(|dep| current[dep.as_str()]["state"] != "integrated")
                            || active
                                .values()
                                .any(|job| overlaps(&task.owns, &job.task.owns))
                        {
                            continue;
                        }
                        let request = match self.dispatch(task, &current, role) {
                            Ok(Some(request)) => request,
                            Ok(None) => continue,
                            Err(error) if error.is::<DependencyMissing>() => {
                                let notice = self.store.atomic(|| {
                                    self.store.0.execute("UPDATE tasks SET state='blocked',retry_state=?,message=? WHERE run_id=? AND id=?",
                                        params![state,error.to_string(),self.id,task_id])?;
                                    self.request(Some(task),role.as_str(),if role == Role::Review {&current[task_id]["head"]} else {&Value::Null},
                                        &error.to_string(),Some(&Blocker::decision("Approve a revised plan whose dependencies match the integrated tasks.")
                                            .recommend_b()
                                            .alternative(format!("Retry after checking branch af/{}.",self.id))
                                            .reason("The task's starting commit lacks an integrated dependency.")))
                                })?;
                                self.notify(&notice)?;
                                continue;
                            }
                            Err(error) => return Err(error),
                        };
                        let key = request.attempt_id.clone();
                        active.insert(key.clone(), request.clone());
                        let sender = send.clone();
                        let (repo, settings, plan, profile) =
                            (self.repo, &self.settings, &self.plan, &self.profile);
                        scope.spawn(move || {
                            let started = Instant::now();
                            let (usage, reply) =
                                run_assignment(repo, settings, plan, profile, &request);
                            let _ = sender.send((key, started.elapsed(), usage, reply));
                        });
                    }
                }
                if active.is_empty() || now_integrated > integrated {
                    let latest = rows(self.store, self.id)?;
                    self.report_progress(progress(&self.plan, &latest, &held))?;
                    inbox::publish(self.store, self.id, &self.plan, true)?;
                }
                if active.is_empty() {
                    return Ok(false);
                }
                integrated = now_integrated;
                if let Ok((key, elapsed, usage, reply)) =
                    receive.recv_timeout(std::time::Duration::from_millis(250))
                {
                    self.store.record_duration(&key, elapsed)?;
                    self.store.record_usage(&key, usage.as_ref())?;
                    let request = active.remove(&key).context("unknown completed attempt")?;
                    // Reject the attempt's result if it tampered with Git.
                    let reply = self.guard().and(reply);
                    self.complete(&request, reply)?;
                }
            }
        });
        CANCEL_ASSIGNMENTS.store(false, Ordering::Relaxed);
        let timings = receive.try_iter().try_for_each(|(key, elapsed, usage, _)| {
            self.store.record_duration(&key, elapsed)?;
            self.store.record_usage(&key, usage.as_ref())
        });
        let completed = result?;
        timings?;
        Ok(completed)
    }
}