mahbot 0.11.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
//! The durable single-worker round body (`run_implement_with_job`): the worker sub-agent a
//! `send` `worker` call dispatches, with full shell/read/edit/search access.
//!
//! [`crate::tools::SyncDurableCore::Worker`] dispatches the round (sync for the Engineer,
//! async for the admin Assistant and custom roles); this module owns the round body only,
//! the tool half living in [`crate::tools::send`]. The jobs-row kind stays `implement`.

use crate::agent::run_agent;
use crate::session::analyze_agent_id;
use crate::{Role, Workspace};
use anyhow::anyhow;

/// Write a fresh round's durable rows — the jobs row and the single-worker roster, in ONE
/// tx — and return the worker's agent id, taken from the call's own
/// [`CoreJobArgs`](crate::tools::CoreJobArgs).
/// The fresh-spawn half of [`run_implement_with_job`], shared with the command line's
/// handover ([`hand_over_worker_round`]), which needs these rows down BEFORE it answers.
pub(crate) async fn spawn_implement_rows(
    exec: &Workspace,
    task: &str,
    args: &crate::tools::CoreJobArgs<'_>,
) -> anyhow::Result<String> {
    // The helper's own precondition, a fault rather than a caller-facing refusal: rows are
    // written for a FRESH dispatch only, the call whose spawn record is present (a resume
    // inserts no row — see [`CoreJobArgs::spawn`](crate::tools::CoreJobArgs::spawn)).
    let Some(record) = args.spawn.as_ref() else {
        return Err(super::internal_fault(
            "a fresh worker dispatch carries no spawn record",
        ));
    };
    let worker_agent_id =
        analyze_agent_id(&exec.name, Role::Worker.as_str()) + &crate::generate_suffix();
    // Single-worker roster: one tx puts the job + the worker row down before any session write.
    let agents = vec![crate::jobs::NewAgent {
        agent_id: worker_agent_id.clone(),
        kind: crate::jobs::AgentKind::Worker,
        idx: Some(0),
        task: task.to_string(),
    }];
    let conn = &crate::session::store().conn;
    crate::jobs::spawn_job_with_chain(
        conn,
        args.job_id,
        task,
        record.delivery_name,
        args.user_name,
        args.channel,
        args.caller_role,
        &agents,
        &crate::jobs::SpawnChild::Implement,
        args.caller_agent_id,
        // The round's execution directory, so a restart resumes into the same one.
        record.exec_dir,
        // The calling custom role's launch, so a resume rebuilds an envelope to its branch.
        record.custom_launch,
        // A chain step's row carries the chain, so a restart resumes the same chain.
        args.chain,
        // An ordinary round's row carries the schema, so a restart still transforms the answer.
        args.extract,
    )
    .await?;
    Ok(worker_agent_id)
}

/// Who a worker round runs for: the identity its durable `jobs` row carries, the chain it is a
/// step of, and the schema its answer must come back as.
struct RoundCaller<'a> {
    job_id: &'a str,
    caller_role: Role,
    user_name: &'a str,
    channel: &'a str,
    chain: Option<&'a crate::launch::Chain>,
    extract: Option<&'a crate::extract::Extract>,
}

/// The COMMAND LINE's handover of a worker round.
///
/// [`crate::tools::SyncDurableCore::spawn_dispatch`] answers its caller as soon as the round
/// starts, which is right for an agent whose own turn is durable. The command line is
/// answered and gone the moment it returns, so the round's durable rows are written FIRST
/// (awaited) and the round then runs as a RESUME of its own rows — exactly the round a crash
/// between the two would have started at the next boot, so a restart neither loses the
/// handover nor repeats it. The job row carries the command line's own user and channel;
/// there is no agent session and no custom-role launch behind a shell caller, so neither is
/// threaded through. `Err` is a failed row write: nothing was dispatched, and the caller may
/// be told the handover did not happen. `Ok` is the id its acknowledgement names.
pub(crate) async fn hand_over_worker_round(
    delivery: &Workspace,
    place: Option<&Workspace>,
    task: &str,
    caller_role: Role,
    job_id: &str,
    extract: Option<&crate::extract::Extract>,
) -> anyhow::Result<Option<String>> {
    // Read the caller's identity synchronously BEFORE the spawn (task-local contract): the
    // job row must carry the command line's own user and channel.
    let user_name = crate::agent::tool_user_name();
    let channel = crate::agent::tool_channel();
    hand_over_round(
        delivery,
        place,
        task,
        RoundCaller {
            job_id,
            caller_role,
            user_name: &user_name,
            channel: &channel,
            chain: None,
            extract,
        },
    )
    .await
}

/// A CHAIN step's worker round: the same handover, carrying the chain's own identity (a step runs
/// outside any agent turn, so there are no task-locals to read) and its deterministic record id.
/// The chain's record is the chain's own id, opened where the chain starts, so this step opens
/// none and reports none.
pub(crate) async fn hand_over_chain_round(
    origin: &Workspace,
    place: Option<&Workspace>,
    message: &str,
    chain: &crate::launch::Chain,
) -> anyhow::Result<()> {
    hand_over_round(
        origin,
        place,
        message,
        RoundCaller {
            job_id: &crate::launch::record_id(&chain.id, chain.step),
            caller_role: Role::Assistant,
            user_name: &chain.user,
            channel: &chain.channel,
            chain: Some(chain),
            // A chain step's schema travels on the step itself, which the hand-off clones on.
            extract: None,
        },
    )
    .await
    .map(|_| ())
}

/// The handover both callers share: the durable rows are written FIRST — the hand-off the caller
/// depends on exists before anything runs — and the round then runs as a resume of its own rows.
async fn hand_over_round(
    delivery: &Workspace,
    place: Option<&Workspace>,
    task: &str,
    caller: RoundCaller<'_>,
) -> anyhow::Result<Option<String>> {
    let exec = place.unwrap_or(delivery);
    let args = crate::tools::CoreJobArgs {
        job_id: caller.job_id,
        caller_role: caller.caller_role,
        user_name: caller.user_name,
        channel: caller.channel,
        spawn: Some(crate::tools::SpawnRecord {
            delivery_name: &delivery.name,
            exec_dir: place.map(|ws| ws.path.as_str()),
            custom_launch: None,
        }),
        // No agent session behind the caller: no caller session pin, and the row write is not a
        // caller's retry (nothing is running yet).
        caller_agent_id: None,
        fail_on_checkpoint_error: false,
        chain: caller.chain,
        extract: caller.extract,
    };
    spawn_implement_rows(exec, task, &args).await?;

    // The rows are down, so the handover is durable, and the round has not been spawned yet: the
    // command line's own handover opens the record its id answers here. Only this caller reaches
    // here without a chain — a chain step's record is the chain's own id, opened where the chain
    // starts.
    let opened = caller.chain.is_none();
    if opened {
        crate::send_outcome::begin(caller.job_id, None).await;
    }

    // Run the round as a RESUME of them, so a restart landing between the two starts the very
    // round this call promised.
    crate::tools::SyncDurableCore::Worker.spawn_resume_round(
        caller.job_id.to_string(),
        delivery.clone(),
        place.map(|ws| ws.path.clone()),
    );
    Ok(opened.then(|| caller.job_id.to_string()))
}

/// Spawn the implement job + single-worker roster (one tx), then run the worker. A resume
/// (`spawn: None`) reuses the stored roster — ids are never regenerated, or the PK would
/// conflict and the new id would not match the stored row.
pub(crate) async fn run_implement_with_job(
    ws: &Workspace,
    task: &str,
    args: crate::tools::CoreJobArgs<'_>,
) -> anyhow::Result<crate::tools::SyncCoreOutcome> {
    let resume = args.spawn.is_none();
    let (worker_agent_id, pre_done) = match &args.spawn {
        None => {
            let rows = crate::jobs::list_agents_for_job(&crate::session::store().conn, args.job_id)
                .await?;
            let row = rows.first().ok_or_else(|| {
                super::internal_fault("worker round resume found no roster row for the stored job")
            })?;
            // Only a completed worker's outcome is reconstructable — a failed or launched
            // one is re-run with its stored task.
            let pre_done = (row.status == crate::jobs::RowStatus::Done.as_str())
                .then(|| row.outcome.clone())
                .flatten();
            (row.agent_id.clone(), pre_done)
        }
        Some(_) => (spawn_implement_rows(ws, task, &args).await?, None),
    };

    // A completed worker's stored outcome IS the final response: deliver it without re-running.
    if let Some(outcome) = pre_done {
        return Ok(crate::tools::SyncCoreOutcome::Terminal(Ok(outcome)));
    }

    // Fresh (or resume-without-outcome) run. On resume the worker reuses its persisted
    // session, so an interrupted attempt continues rather than redoing the task. A chain step
    // carries its own group (it runs outside any agent turn); everything else inherits the
    // caller's.
    let (parent_key, parent_label) = match &args.chain {
        Some(chain) => (
            Some(crate::agent::registry::ParentKey::Chain(chain.id.clone())),
            Some(chain.task.clone()),
        ),
        None => (
            crate::agent::CURRENT_TOOL_PARENT_KEY
                .try_with(std::clone::Clone::clone)
                .unwrap_or(None),
            crate::agent::CURRENT_TOOL_PARENT_LABEL
                .try_with(std::clone::Clone::clone)
                .unwrap_or(None),
        ),
    };
    let has_session = resume && crate::session::store().has_content(&worker_agent_id).await;
    let (agent, response) = run_agent(
        worker_agent_id.clone(),
        Role::Worker,
        ws,
        None,
        &[if has_session { "" } else { task }],
        args.user_name.to_string(),
        args.channel.to_string(),
        false,
        None,
        resume,
        None,
        parent_key,
        parent_label,
        None,
    )
    .await;

    // CHECKPOINT: persist the worker's terminal outcome so a drain-cut or crash resume can
    // reconstruct it without re-running a completed worker.
    let (status, outcome) = match &response {
        Some(r) => (crate::jobs::RowStatus::Done, r.clone()),
        None => (
            crate::jobs::RowStatus::Failed,
            agent.failure_reason("worker produced no response"),
        ),
    };
    if let Err(e) = crate::jobs::write_agent_outcome(
        &crate::session::store().conn,
        args.job_id,
        &worker_agent_id,
        status,
        Some(&outcome),
    )
    .await
    {
        // Sync calls fail the tool call on a checkpoint DB error so the model
        // retries; async/boot-resume warn-and-continue (the outcome is
        // recomputable on the next resume).
        if args.fail_on_checkpoint_error {
            return Err(e.context("failed to checkpoint worker outcome"));
        }
        tracing::warn!(job = %args.job_id, error = %e, "Failed to checkpoint worker outcome");
    }

    // Drain/shutdown cut the round: leave the job status='launched' for boot
    // resume (the checkpointed outcome is the resume boundary). No routing, no
    // terminalization.
    if crate::shutdown::aborting() {
        return Ok(crate::tools::SyncCoreOutcome::DrainCut);
    }

    Ok(crate::tools::SyncCoreOutcome::Terminal(match response {
        Some(r) => Ok(r),
        None => Err(anyhow!(
            "Sub-agent failed: {}",
            agent.failure_reason("unknown error")
        )),
    }))
}

/// Boot-resume a durable implement round — thin wrapper over
/// [`crate::tools::SyncDurableCore::resume_durable_round`]. `exec_dir` is the
/// recorded target directory the round ran in, when it had one.
pub(crate) async fn resume_implement_round(job_id: &str, ws: &Workspace, exec_dir: Option<&str>) {
    crate::tools::SyncDurableCore::Worker
        .resume_durable_round(job_id, ws, exec_dir)
        .await;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::test::{FakeProvider, install_fake_provider};
    use crate::workspace::test_ws;
    use serde_json::json;

    /// The file the scripted worker writes into its execution workspace — a REAL
    /// write through the `edit` tool, so the round's root is observable on disk.
    const WRITTEN_FILE: &str = "worker-written.txt";

    /// Dispatch one place worker round and assert the shared contract: the
    /// worker writes into `place`'s directory, while the durable job and the
    /// delivered envelope stay keyed to the caller's own workspace and the
    /// envelope names the directory really used.
    async fn assert_place_round_write(delivery: &Workspace, place: &Workspace, job_id: &str) {
        assert!(
            place.name.starts_with("dir-"),
            "a plain directory's identity is the synthetic one, got {}",
            place.name
        );
        let envelope = crate::tools::SyncDurableCore::Worker
            .dispatch_durable(
                delivery,
                Some(place),
                "write the file",
                Role::Assistant,
                "admin",
                "gui",
                job_id,
                None,
                None,
            )
            .await
            .expect("the round completes");
        assert_eq!(
            envelope.workspace_name, delivery.name,
            "the delivery key stays the caller's own workspace"
        );
        assert!(
            envelope.content.contains("WORKER DONE"),
            "{}",
            envelope.content
        );
        assert!(
            envelope
                .content
                .contains(&format!("folder=\"{}\"", place.path)),
            "the worker report names the folder it worked in: {}",
            envelope.content
        );
        let written = std::path::Path::new(&place.path).join(WRITTEN_FILE);
        assert_eq!(
            std::fs::read_to_string(&written).unwrap_or_default(),
            "hello from the worker",
            "the worker wrote into the place directory ({})",
            written.display()
        );
        let conn = &crate::session::store().conn;
        let place_sessions = conn
            .query(
                "SELECT agent_id FROM session_metadata WHERE workspace_name = ?1",
                crate::db::params![place.name.clone()],
            )
            .await
            .unwrap();
        assert_eq!(
            place_sessions.len(),
            1,
            "the worker's session belongs to the place directory"
        );
        assert!(
            place_sessions[0]
                .get::<String>(0)
                .unwrap()
                .contains(&place.name),
            "the worker's agent id carries the place's identity"
        );
        let caller_sessions = conn
            .query(
                "SELECT agent_id FROM session_metadata WHERE workspace_name = ?1",
                crate::db::params![delivery.name.clone()],
            )
            .await
            .unwrap();
        assert!(
            caller_sessions.is_empty(),
            "nothing ran in the caller's own workspace"
        );
    }

    /// The async place path end to end, in both shapes: a delivery of its
    /// own plus a separate place directory, and a place that IS the caller's
    /// own directory — still a place, the reply names the directory and the
    /// worker's session is keyed to the directory's own identity, never silently
    /// downgraded to an unplaced call.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn place_rounds_run_in_the_place_and_cover_the_callers_own_directory() {
        crate::util::test::init_management_test_stores().await;
        let _policy_guard =
            crate::util::test::install_test_retry_policy(crate::retry::tiny_test_policy());
        // Two rounds' scripts in order: each worker really writes the file
        // through `edit`, then answers (`ok` is text-only).
        let _provider_guard = install_fake_provider(std::sync::Arc::new(
            FakeProvider::new()
                .ok_text_and_tool_calls(
                    "writing the file",
                    &[(
                        "edit",
                        json!({ "path": WRITTEN_FILE, "new_string": "hello from the worker" }),
                    )],
                )
                .ok("WORKER DONE")
                .ok_text_and_tool_calls(
                    "writing the file",
                    &[(
                        "edit",
                        json!({ "path": WRITTEN_FILE, "new_string": "hello from the worker" }),
                    )],
                )
                .ok("WORKER DONE"),
        ));

        // Case 1: a delivery of its own plus a separate place tempdir.
        let delivery = test_ws("/tmp/test_ws_place_delivery");
        let dir = tempfile::tempdir().unwrap();
        let dir = std::fs::canonicalize(dir.path()).unwrap();
        let place = crate::tools::delegation::workspace_at_dir(dir.to_str().unwrap())
            .await
            .unwrap();
        assert_place_round_write(&delivery, &place, "implement_place_job").await;

        // Case 2: the place IS the caller's own directory.
        let dir = tempfile::tempdir().unwrap();
        let dir = std::fs::canonicalize(dir.path()).unwrap();
        let dir_path = dir.to_str().unwrap().to_string();
        let delivery = test_ws(&dir_path);
        let place = crate::tools::delegation::workspace_at_dir(&dir_path)
            .await
            .unwrap();
        assert_ne!(
            place.name, delivery.name,
            "the directory's own identity differs from the caller's name"
        );
        assert_place_round_write(&delivery, &place, "implement_own_dir_job").await;
    }

    /// (h) Mirror the analyze durability lifecycle: with drain active the sync dispatch
    /// surfaces [`CallSuspended`] and leaves the caller-owned job launched; a Done-worker
    /// resume then reconstructs "WORKER_RESPONSE", settles it as the tool result contiguous
    /// after the frame, and terminalizes the job.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn sync_implement_draincut_and_completion_resumes_durable_job() {
        crate::util::test::init_management_test_stores().await;
        let ws = test_ws("/tmp/test_ws_sync_implement");
        let pin = "sync_implement_pin";
        let conn = &crate::session::store().conn;
        crate::util::test::seed_session_row(conn, pin, "user", "implement this").await;

        crate::shutdown::drain_begin();
        let res = crate::agent::CURRENT_TOOL_AGENT_ID
            .scope(Some(pin.to_string()), async {
                crate::tools::SyncDurableCore::Worker
                    .run_sync_dispatch(&ws, "implement task", crate::Role::Engineer)
                    .await
            })
            .await;
        crate::shutdown::drain_clear();
        let err = res.expect_err("drain must cut the sync implement dispatch");
        assert!(
            err.downcast_ref::<crate::tools::CallSuspended>().is_some(),
            "CallSuspended carrier expected: {err:#}"
        );

        let jobs = conn
            .query(
                "SELECT id, status, caller_agent_id FROM jobs WHERE caller_agent_id = ?1 AND kind = 'implement'",
                crate::db::params![pin],
            )
            .await
            .unwrap();
        assert_eq!(jobs.len(), 1, "one launched implement job");
        assert_eq!(jobs[0].get::<String>(1).unwrap(), "launched");
        assert_eq!(
            jobs[0].get::<String>(2).unwrap(),
            pin,
            "job is caller-owned by the session pin"
        );
        let job_id = jobs[0].get::<String>(0).unwrap();

        // The worker checkpointed Done just before the drain cut: the drain observed the round
        // mid-flight, the durable outcome is intact.
        let roster = crate::jobs::list_agents_for_job(conn, &job_id)
            .await
            .unwrap();
        let worker_id = roster[0].agent_id.clone();
        crate::jobs::write_agent_outcome(
            conn,
            &job_id,
            &worker_id,
            crate::jobs::RowStatus::Done,
            Some("WORKER_RESPONSE"),
        )
        .await
        .unwrap();

        let frame = crate::providers::reasoning::assistant_replay_payload(
            Some(""),
            &[crate::ToolCall {
                id: "call_implement_h".to_string(),
                name: "send".to_string(),
                arguments: json!({"message": "implement task"}),
            }],
            None,
        )
        .to_string();
        crate::util::test::seed_session_row(conn, pin, "assistant", &frame).await;

        let mut session = crate::session::Session::default();
        session.init(pin).await.unwrap();
        let pending = session
            .pending_tool_frame()
            .expect("dangling implement call")
            .calls;
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].id, "call_implement_h");

        let outcome = crate::tools::SyncDurableCore::Worker
            .resume_sync_core(&ws, &job_id, true)
            .await
            .unwrap();
        let crate::jobs::SyncResumeOutcome::Terminal(_, _, result) = outcome else {
            panic!("expected a terminal resume outcome");
        };
        let text = result.expect("resumed implement result");
        assert_eq!(text, "WORKER_RESPONSE");
        crate::jobs::terminalize_job(conn, &job_id).await.unwrap();
        session
            .settle_tool_results(pin, &[("call_implement_h".to_string(), text.clone())], &[])
            .await
            .unwrap();

        let jobs = conn
            .query(
                "SELECT id FROM jobs WHERE id = ?1",
                crate::db::params![job_id],
            )
            .await
            .unwrap();
        assert!(jobs.is_empty(), "resumed job must be terminalized");
        let rows = conn
            .query(
                "SELECT id, role, content FROM sessions WHERE agent_id = ?1 ORDER BY id",
                crate::db::params![pin],
            )
            .await
            .unwrap();
        assert_eq!(rows.len(), 3);
        assert_eq!(rows[1].get::<String>(1).unwrap(), "assistant");
        assert_eq!(rows[2].get::<String>(1).unwrap(), "tool");
        let payload: crate::ToolResultPayload =
            serde_json::from_str(&rows[2].get::<String>(2).unwrap()).unwrap();
        assert_eq!(payload.tool_call_id, "call_implement_h");
        assert_eq!(payload.content, "WORKER_RESPONSE");
    }

    /// The durable round's own entry point delivers the schema's JSON document as its answer, and
    /// a round that asked for nothing delivers its own text with no transformation call.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn a_durable_round_delivers_the_schema_it_asked_for() {
        crate::util::test::init_management_test_stores().await;
        let _policy_guard =
            crate::util::test::install_test_retry_policy(crate::retry::tiny_test_policy());
        let _provider_guard = install_fake_provider(std::sync::Arc::new(
            FakeProvider::new().ok("WORKER DONE").ok(r#"{"ok":true}"#),
        ));
        let ws = test_ws("/tmp/test_ws_worker_extract");
        let schema = crate::extract::Extract::from_text(
            r#"{"type":"object","properties":{"ok":{"type":"boolean"}}}"#,
        )
        .expect("the schema is accepted");
        let envelope = crate::tools::SyncDurableCore::Worker
            .dispatch_durable(
                &ws,
                None,
                "do the work",
                Role::Assistant,
                "admin",
                "gui",
                "worker_extract_job",
                None,
                Some(&schema),
            )
            .await
            .expect("the round completes");
        assert!(
            envelope.content.contains(r#"{"ok":true}"#),
            "the JSON document replaces the round's answer: {}",
            envelope.content
        );
        assert!(
            !envelope.content.contains("WORKER DONE"),
            "the prose is gone: {}",
            envelope.content
        );
    }

    /// A stop landing while the transformation runs stops the delivery too: the last look before
    /// the route sees it, so nothing reaches the caller — while a round nobody stopped delivers its
    /// JSON, which is what makes the assertion mean something.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn a_stop_during_the_transformation_delivers_nothing() {
        crate::util::test::init_management_test_stores().await;
        let _policy_guard =
            crate::util::test::install_test_retry_policy(crate::retry::tiny_test_policy());
        let gate = std::sync::Arc::new(tokio::sync::Notify::new());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok("WORKER DONE")
                .ok(r#"{"ok":true}"#)
                .hold_call(2, gate.clone())
                .ok("WORKER DONE")
                .ok(r#"{"ok":true}"#),
        );
        let _provider_guard = install_fake_provider(fake.clone());
        let ws = test_ws("/tmp/test_ws_worker_extract_stop");
        let schema = || {
            crate::extract::Extract::from_text(
                r#"{"type":"object","properties":{"ok":{"type":"boolean"}}}"#,
            )
            .expect("the schema is accepted")
        };
        let stopped = "worker_extract_stopped";
        let _cancel_guard = crate::round_cancel::register(stopped, None);
        // The id `envelope_target` computes for this envelope: the owner's Assistant in the
        // round's workspace.
        let caller = crate::jobs::target_agent_id(
            None,
            crate::users::ADMIN_USER_NAME,
            Role::Assistant.as_str(),
            &ws.name,
        );
        let mut rx = crate::agent::message_router::register_agent(&caller);

        crate::agent::CURRENT_TOOL_USER_NAME
            .scope(crate::users::ADMIN_USER_NAME.to_string(), async {
                crate::agent::CURRENT_TOOL_CHANNEL
                    .scope("gui".to_string(), async {
                        crate::tools::SyncDurableCore::Worker.spawn_dispatch(
                            &ws,
                            None,
                            "do the work",
                            Role::Assistant,
                            stopped.to_string(),
                            Some(schema()),
                        );
                        // The transformation is in flight: stop the round, then let it finish.
                        wait_for_calls(&fake, 2).await;
                        crate::round_cancel::cancel(stopped);
                        gate.notify_one();
                        assert!(
                            tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
                                .await
                                .is_err(),
                            "a stopped round delivers nothing"
                        );

                        // The control: the same dispatch, nobody stopping it, delivers its JSON.
                        crate::tools::SyncDurableCore::Worker.spawn_dispatch(
                            &ws,
                            None,
                            "do the work",
                            Role::Assistant,
                            "worker_extract_delivered".to_string(),
                            Some(schema()),
                        );
                        let delivered =
                            tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())
                                .await
                                .expect("the round's answer is delivered")
                                .expect("the envelope");
                        assert!(
                            delivered.content.contains(r#"{"ok":true}"#),
                            "{}",
                            delivered.content
                        );
                    })
                    .await;
            })
            .await;
        crate::agent::message_router::unregister_agent(&caller);
    }

    /// Wait until the fake provider has received `calls` requests.
    async fn wait_for_calls(fake: &FakeProvider, calls: usize) {
        for _ in 0..500 {
            if fake.request_fingerprints.lock().unwrap().len() >= calls {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        panic!("the fake provider never received {calls} calls");
    }

    /// A boot-resumed round settles the record its command-line handover opened: the record's own
    /// existence is the marker, so the resume asks before it writes and the record takes the
    /// round's stored answer.
    #[tokio::test]
    #[serial_test::serial(drain, send_outcome)]
    async fn a_resumed_round_settles_the_record_its_handover_opened() {
        crate::util::test::init_management_test_stores().await;
        let ws = test_ws("/tmp/test_ws_resume_record");
        let conn = &crate::session::store().conn;
        let job_id = "implement_resume_record";
        let worker = format!("{job_id}_worker");
        crate::jobs::spawn_job(
            conn,
            job_id,
            "do the work",
            &ws.name,
            "caller-user",
            "cli",
            Role::Assistant,
            &[crate::jobs::NewAgent {
                agent_id: worker.clone(),
                kind: crate::jobs::AgentKind::Worker,
                idx: Some(0),
                task: "do the work".to_string(),
            }],
            &crate::jobs::SpawnChild::Implement,
            None,
            None,
            None,
        )
        .await
        .expect("the round's own row");
        crate::jobs::write_agent_outcome(
            conn,
            job_id,
            &worker,
            crate::jobs::RowStatus::Done,
            Some("the work is done"),
        )
        .await
        .expect("the worker's stored outcome");
        // The handover opened the record before its round left; the restart kept it running.
        crate::send_outcome::begin(job_id, None).await;
        // The report's own consumer, so the delivered envelope does not start a turn.
        let target =
            crate::jobs::target_agent_id(None, "caller-user", Role::Assistant.as_str(), &ws.name);
        let mut report = crate::agent::message_router::register_agent(&target);

        resume_implement_round(job_id, &ws, None).await;
        crate::agent::message_router::unregister_agent(&target);

        let record = crate::send_outcome::lookup(job_id)
            .await
            .expect("read the record")
            .expect("the handover opened one");
        assert_eq!(record.state, crate::send_outcome::State::Done);
        assert_eq!(record.answer.as_deref(), Some("the work is done"));
        assert!(
            report
                .try_recv()
                .is_ok_and(|job| job.content.contains("<worker-report")),
            "the round's report still reaches its caller"
        );
    }
}