eclipse-core 0.14.0

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
//! `#171`: a flare run — N read-only sibling agents on one task, and the merge of what they said.
//!
//! A **flare** is one child agent: its own session (`origin = "flare:<run>:<n>"`), its own route,
//! a small iteration budget, and a registry holding **only the readers** ([`READ_TOOLS`]). A
//! **flare run** is the set of them on one task, plus the merge. The lead is unchanged — it is the
//! only agent that writes.
//!
//! This is not a second runtime. A flare is what a `delegate` child is, times N, plus a scheduler:
//! [`DelegateTool::run_child`] builds both, so the preamble, the hooks, the usage capture and the
//! cancellation are one implementation with two callers.
//!
//! # Why local runs are serial, and why that is correct
//!
//! A local server serves one model at a time — llama-swap swaps by stopping one to start another —
//! so N flares on one local route are N sequential turns. Parallelism buys nothing there; what it
//! buys is **isolation**: each flare reads its own files, and the lead's context never fills with
//! them. Mixed routes are the case where concurrency is real: three cheap local readers plus one
//! cloud thinker run in two slots, not four. So the cap is per *server*, which is why a route can
//! name a `group`: two routes pointed at one box are one slot.
//!
//! # What keeps a fan-out safe
//!
//! Every flare is read-only, and read-only is a property of its registry, not of a policy: it is
//! narrowed to [`READ_TOOLS`] by [`crate::tools::ToolRegistry::only`], so a `tool_call` bridge
//! cannot reach anything that is not there. Approvals stay one at a time on purpose (`runtime.rs`'s
//! gate), and a read-only flare asks nothing at all.

use crate::cancel::Cancel;
use crate::config::FlaresConfig;
use crate::session::{FlareJobRow, SessionStore};
use crate::tools::{Approver, CallScope, Tool, ToolError, ToolRegistry};
use crate::tools_delegate::{ChildJob, ChildOrigin, DelegateTool};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// The tools a flare **does** have (`#548`): the readers, named one at a time.
///
/// This is an allowlist on purpose, and the direction is the fix. A denylist was only correct
/// until the next tool was registered: `cronjob_manage` and `skill_manage` sit in the same registry
/// as the readers, so does every plugin tool and every MCP server's tool, and each of those was
/// handed to a read-only flare by default. Approvals `ask` on them is not the guarantee the tool's
/// own doc claims — under `auto`, `smart` or `--yes` a flare could schedule cron runs and rewrite
/// the skills directory while its description said the capability was not there.
///
/// Nothing here writes, schedules work for later, spends a budget nobody is watching, or edits the
/// user's install: a flare reads what it is pointed at and answers. `delegate` and `flares` are
/// absent for the reason a `delegate` child does not get `delegate` — no nesting — and `memory`
/// because a flare is a worker, not an identity: it has no memory of its own to write to. The
/// `tool_search` bridge is absent as well: it reaches whatever the registry holds, so naming it
/// back would hand a flare the deferred half of the lead's capability.
pub const READ_TOOLS: &[&str] = &[
    "read_file",
    "search_files",
    "fetch",
    "session_search",
    "skill_view",
    "skill_search",
];

/// The most jobs one call may name. A model that wants more has not split the task, it has
/// multiplied it; the CLI's `-n` is where a bigger number is typed deliberately.
pub const MAX_FLARES_PER_RUN: usize = 16;

/// One job as the lead states it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareJob {
    pub prompt: String,
    pub route: Option<String>,
    pub max_iterations: Option<usize>,
    pub system: Option<String>,
}

/// How a run's answers come back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Merge {
    /// One block, children in the lead's order.
    Concat,
    /// The children's answers, labelled, with the instruction that the lead writes the merge.
    Lead,
}

impl Merge {
    pub fn parse(text: &str) -> Option<Self> {
        match text.trim().to_ascii_lowercase().as_str() {
            "" | "concat" => Some(Self::Concat),
            "lead" => Some(Self::Lead),
            _ => None,
        }
    }
}

/// How a child ended, as one word the ledger and the readout both use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    Done,
    Failed,
    /// Never started: the run was cancelled, its budget was gone, or its spend cap was reached.
    Dropped,
}

impl State {
    pub fn word(self) -> &'static str {
        match self {
            Self::Done => "done",
            Self::Failed => "failed",
            Self::Dropped => "dropped",
        }
    }
}

/// One child's row in the run's report.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareLine {
    pub n: usize,
    pub route: String,
    pub session_id: Option<String>,
    pub state: State,
    pub text: String,
    pub why: Option<String>,
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub iterations: usize,
}

impl FlareLine {
    fn dropped(n: usize, route: &str, why: &str) -> Self {
        Self {
            n,
            route: route.to_string(),
            session_id: None,
            state: State::Dropped,
            text: String::new(),
            why: Some(why.to_string()),
            prompt_tokens: None,
            completion_tokens: None,
            iterations: 0,
        }
    }
}

/// What a route offers a run: its name, how many flares may share it, and which server it is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteSlot {
    pub name: String,
    pub parallel: usize,
    /// Routes with the same group are one server's worth of slots.
    pub group: Option<String>,
}

impl RouteSlot {
    pub fn of(route: &crate::config::NamedRoute) -> Self {
        Self {
            name: route.name.clone(),
            parallel: route.parallel(),
            group: route.group.clone(),
        }
    }

    fn key(&self) -> String {
        self.group.clone().unwrap_or_else(|| self.name.clone())
    }
}

/// The cap a run actually has: one number per server, and the sum of them, floored by
/// `[flares] max_concurrent`.
///
/// A group takes its **lowest** member's bound — the conservative reading of "these are the same
/// box", because the cost of guessing high is a swap cycle that stops one model mid-turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Slots {
    pub per_group: BTreeMap<String, usize>,
    pub total: usize,
}

pub fn slots(routes: &[RouteSlot], max_concurrent: usize) -> Slots {
    let mut per_group: BTreeMap<String, usize> = BTreeMap::new();
    for route in routes {
        let entry = per_group.entry(route.key()).or_insert(route.parallel);
        *entry = (*entry).min(route.parallel.max(1));
    }
    let available: usize = per_group.values().copied().sum();
    Slots {
        total: max_concurrent.max(1).min(available.max(1)),
        per_group,
    }
}

/// The `flares` tool.
pub struct FlareTool {
    runner: Arc<DelegateTool>,
    /// The registry every flare gets: the lead's, without [`WRITE_TOOLS`].
    tools: Arc<ToolRegistry>,
    store: SessionStore,
    cfg: FlaresConfig,
    routes: Vec<RouteSlot>,
    description: String,
}

impl FlareTool {
    pub fn new(
        runner: Arc<DelegateTool>,
        store: SessionStore,
        cfg: FlaresConfig,
        routes: Vec<RouteSlot>,
    ) -> Self {
        let description = format!(
            "Run several read-only agents on one task at the same time. Name every job: a job is \
             one prompt and the route it runs on. Each agent gets its own session, its own route \
             and a small iteration budget, holds only the readers (`read_file`, `search_files`, \
             `fetch`, `session_search`, `skill_view`, `skill_search`) and cannot write, schedule or \
             delegate. Use it to read several things at once \
             and get one answer back; do not use it for work you could do in one turn. At most \
             {MAX_FLARES_PER_RUN} jobs."
        );
        Self {
            tools: Arc::new(runner.flare_registry()),
            runner,
            store,
            cfg,
            routes,
            description,
        }
    }

    /// The cap this tool's routes give it.
    pub fn slots(&self) -> Slots {
        slots(&self.routes, self.cfg.concurrency())
    }

    fn resolve_route(&self, named: Option<&str>) -> Result<String, ToolError> {
        let name = match named {
            Some(name) => name.to_string(),
            None => self.runner.default_route(),
        };
        if self.routes.iter().any(|r| r.name == name) {
            return Ok(name);
        }
        Err(ToolError::InvalidArgs(format!(
            "`{name}` is not a route this agent can use. Declared: {}",
            self.routes
                .iter()
                .map(|r| r.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        )))
    }
}

#[async_trait]
impl Tool for FlareTool {
    fn name(&self) -> &str {
        "flares"
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "jobs": {
                    "type": "array",
                    "minItems": 1,
                    "maxItems": MAX_FLARES_PER_RUN,
                    "description": "One entry per agent. Name the jobs — never a count.",
                    "items": {
                        "type": "object",
                        "properties": {
                            "prompt": {
                                "type": "string",
                                "description": "The job, stated so it makes sense with no other context."
                            },
                            "route": {
                                "type": "string",
                                "description": "Which route this agent runs on. Unset: the delegate route, else this run's."
                            },
                            "max_iterations": {
                                "type": "integer",
                                "minimum": 1,
                                "description": "Model requests this agent may make. Unset: the configured default."
                            },
                            "system": {
                                "type": "string",
                                "description": "Extra instructions for this agent, added to its preamble."
                            }
                        },
                        "required": ["prompt"]
                    }
                },
                "merge": {
                    "type": "string",
                    "enum": ["concat", "lead"],
                    "description": "`concat` (default) joins the answers; `lead` returns them labelled and the lead writes the merge."
                }
            },
            "required": ["jobs"]
        })
    }

    fn describe_call(&self, args: &Value) -> String {
        let jobs = args
            .get("jobs")
            .and_then(Value::as_array)
            .map(|a| a.len())
            .unwrap_or(0);
        let routes: Vec<String> = args
            .get("jobs")
            .and_then(Value::as_array)
            .map(|jobs| {
                let mut seen: Vec<String> = Vec::new();
                for job in jobs {
                    if let Some(route) = job.get("route").and_then(Value::as_str) {
                        if !seen.iter().any(|r| r == route) {
                            seen.push(route.to_string());
                        }
                    }
                }
                seen
            })
            .unwrap_or_default();
        let routes = if routes.is_empty() {
            self.runner.default_route()
        } else {
            routes.join(", ")
        };
        format!("flare run: {jobs} read-only agent(s) on {routes}")
    }

    async fn call(&self, _args: Value) -> Result<String, ToolError> {
        Err(ToolError::Failed(
            "`flares` only runs inside an agent run".into(),
        ))
    }

    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
        let raw = args
            .get("jobs")
            .and_then(Value::as_array)
            .ok_or_else(|| ToolError::InvalidArgs("`jobs` is not a list".into()))?;
        if raw.is_empty() {
            return Err(ToolError::InvalidArgs("`jobs` is empty".into()));
        }
        if raw.len() > MAX_FLARES_PER_RUN {
            return Err(ToolError::InvalidArgs(format!(
                "{} jobs is more than the {MAX_FLARES_PER_RUN} one run may start; split the task",
                raw.len()
            )));
        }
        let merge = match args.get("merge") {
            None | Some(Value::Null) => Merge::Concat,
            Some(Value::String(s)) => Merge::parse(s).ok_or_else(|| {
                ToolError::InvalidArgs(format!("`merge` is `concat` or `lead`, not {s:?}"))
            })?,
            Some(_) => return Err(ToolError::InvalidArgs("`merge` is not a string".into())),
        };

        let mut jobs = Vec::with_capacity(raw.len());
        for job in raw {
            let prompt = job
                .get("prompt")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .trim();
            if prompt.is_empty() {
                return Err(ToolError::InvalidArgs("every job needs a `prompt`".into()));
            }
            let route = match job.get("route") {
                None | Some(Value::Null) => None,
                Some(Value::String(s)) => Some(self.resolve_route(Some(s))?),
                Some(_) => return Err(ToolError::InvalidArgs("`route` is not a string".into())),
            };
            let max_iterations = match job.get("max_iterations") {
                None | Some(Value::Null) => None,
                Some(Value::Number(n)) => n.as_u64().map(|n| n.max(1) as usize),
                Some(_) => {
                    return Err(ToolError::InvalidArgs(
                        "`max_iterations` is not a number".into(),
                    ))
                }
            };
            jobs.push(FlareJob {
                prompt: prompt.to_string(),
                route: Some(route.unwrap_or_else(|| self.runner.default_route())),
                max_iterations,
                system: job
                    .get("system")
                    .and_then(Value::as_str)
                    .map(str::to_string),
            });
        }

        let run = self.store.new_id();
        let task = crate::compact::clean(&jobs[0].prompt, 200);
        let routes: Vec<String> = {
            let mut seen: Vec<String> = Vec::new();
            for job in &jobs {
                let name = job.route.clone().unwrap_or_default();
                if !seen.contains(&name) {
                    seen.push(name);
                }
            }
            seen
        };
        self.store
            .begin_flare_run(&run, &task, &routes, jobs.len(), &scope.run.session)
            .map_err(store_error)?;

        // The runtime cancels a run by dropping its future (`tokio::select!`), and then nothing
        // after the `.await` below ever runs — so the row stayed `running`, which this file calls
        // "a run nothing can ever cancel" (`#553`). A guard is the one piece of this that a dropped
        // future cannot skip.
        let mut close = CloseOnDrop {
            store: &self.store,
            run: &run,
            armed: true,
        };
        let result = self
            .execute(&run, &jobs, merge, scope.approver, &scope.run.cancel)
            .await;

        let merged = result.merge(merge);
        // The ledger closes even when the run failed: a row left `running` is a run nothing can
        // ever cancel.
        let state = if result.lines.iter().any(|l| l.state == State::Dropped) {
            "cancelled"
        } else if result.lines.iter().any(|l| l.state == State::Failed) {
            "failed"
        } else {
            "done"
        };
        let _ = self.store.finish_flare_run(
            &run,
            state,
            result.prompt_tokens(),
            result.completion_tokens(),
            result.iterations(),
        );
        close.armed = false;

        Ok(result.readout(&run, merge, &merged))
    }
}

/// Closes a flare run's ledger row as `cancelled` if the call is dropped before it can close it.
///
/// The counts are `None` rather than zero: a cancelled run does not know them, and a zero would read
/// as "this ran and cost nothing" (`#553`).
struct CloseOnDrop<'a> {
    store: &'a SessionStore,
    run: &'a str,
    armed: bool,
}

impl Drop for CloseOnDrop<'_> {
    fn drop(&mut self) {
        if self.armed {
            let _ = self
                .store
                .finish_flare_run(self.run, "cancelled", None, None, 0);
        }
    }
}

/// A finished run: its children, in the lead's order.
pub struct RunResult {
    pub run: String,
    pub lines: Vec<FlareLine>,
}

impl RunResult {
    pub fn prompt_tokens(&self) -> Option<u64> {
        self.lines
            .iter()
            .filter_map(|l| l.prompt_tokens)
            .reduce(|a, b| a + b)
    }

    pub fn completion_tokens(&self) -> Option<u64> {
        self.lines
            .iter()
            .filter_map(|l| l.completion_tokens)
            .reduce(|a, b| a + b)
    }

    pub fn iterations(&self) -> usize {
        self.lines.iter().map(|l| l.iterations).sum()
    }

    /// The children's answers, in the order they were asked for.
    pub fn merge(&self, how: Merge) -> String {
        let mut out = String::new();
        for line in &self.lines {
            if !out.is_empty() {
                out.push_str("\n\n");
            }
            match how {
                Merge::Concat => out.push_str(&format!(
                    "--- flare {} ({}) ---\n{}",
                    line.n,
                    line.route,
                    line.text.trim()
                )),
                Merge::Lead => out.push_str(&format!(
                    "--- flare {} ({}) · session {} ---\n{}\n[the lead merges these]",
                    line.n,
                    line.route,
                    line.session_id.as_deref().unwrap_or("-"),
                    line.text.trim()
                )),
            }
        }
        out
    }

    /// The heading, one line per child, and the merge — what the lead's tool result carries.
    fn readout(&self, run: &str, _how: Merge, merged: &str) -> String {
        let done = self.lines.iter().filter(|l| l.state == State::Done).count();
        let dropped = self
            .lines
            .iter()
            .filter(|l| l.state == State::Dropped)
            .count();
        let failed = self.lines.len() - done - dropped;
        let mut out = format!(
            "flare run `{run}`: {done} of {} finished{}{} \u{2014} {} iteration{}, {} prompt / {} completion tokens\n",
            self.lines.len(),
            if failed > 0 {
                format!(", {failed} failed")
            } else {
                String::new()
            },
            if dropped > 0 {
                format!(", {dropped} dropped")
            } else {
                String::new()
            },
            self.iterations(),
            if self.iterations() == 1 { "" } else { "s" },
            count(self.prompt_tokens()),
            count(self.completion_tokens()),
        );
        for line in &self.lines {
            out.push_str(&format!(
                "  {}. {} on {} \u{b7} {}",
                line.n,
                line.state.word(),
                line.route,
                line.session_id.as_deref().unwrap_or("-")
            ));
            if let Some(why) = &line.why {
                out.push_str(&format!(" \u{b7} {why}"));
            }
            out.push('\n');
        }
        out.push('\n');
        out.push_str(merged);
        out
    }
}

impl FlareTool {
    /// Start every job, in the lead's order, under the run's caps.
    ///
    /// One future per lane, `join_all`ed: a lane is a serial queue on one server, so concurrent
    /// lanes are concurrent *servers*. That is why no `tokio::spawn` appears here — everything
    /// lives in the tool call that asked for it, and a cancelled call drops the futures.
    async fn execute(
        &self,
        run: &str,
        jobs: &[FlareJob],
        _merge: Merge,
        approver: &dyn Approver,
        cancel: &Cancel,
    ) -> RunResult {
        let slots = self.slots();
        let mut lanes: Vec<(String, Vec<(usize, &FlareJob)>)> = Vec::new();
        // Lanes are filled round-robin per group, so a group with two slots gets two lanes and a
        // route with one gets one. A job goes to the lane that has least queued at that point.
        let mut lane_of_group: BTreeMap<String, usize> = BTreeMap::new();
        for (index, job) in jobs.iter().enumerate() {
            let route = job
                .route
                .clone()
                .unwrap_or_else(|| self.runner.default_route());
            let key = self
                .routes
                .iter()
                .find(|r| r.name == route)
                .map(RouteSlot::key)
                .unwrap_or_else(|| route.clone());
            let bound = slots.per_group.get(&key).copied().unwrap_or(1).max(1);
            let base = {
                let next = lane_of_group.entry(key.clone()).or_insert(0);
                let lane = *next;
                *next = (*next + 1) % bound;
                lane
            };
            let lane_key = format!("{key}#{base}");
            match lanes.iter_mut().find(|(k, _)| *k == lane_key) {
                Some((_, queue)) => queue.push((index + 1, job)),
                None => lanes.push((lane_key, vec![(index + 1, job)])),
            }
        }

        let budget = Arc::new(Mutex::new(self.cfg.budget()));
        let spent = Arc::new(Mutex::new(0u64));
        let token_cap = self.cfg.total_tokens;
        let lines: Arc<Mutex<Vec<FlareLine>>> = Arc::new(Mutex::new(Vec::new()));
        // `#555`: the cap is a cap. `slots.total` was computed and then never spent — the lanes
        // were built from `per_group` alone, so two groups of four ran eight children with
        // `max_concurrent = 2`, and the setting that exists to protect a shared GPU did nothing.
        let gate = Arc::new(tokio::sync::Semaphore::new(slots.total));

        let lanes = futures_util::future::join_all(lanes.into_iter().map(|(_, queue)| {
            let runner = Arc::clone(&self.runner);
            let tools = Arc::clone(&self.tools);
            let store = self.store.clone();
            let budget = Arc::clone(&budget);
            let spent = Arc::clone(&spent);
            let lines = Arc::clone(&lines);
            let gate = Arc::clone(&gate);
            async move {
                for (n, job) in queue {
                    let route = job.route.clone().unwrap_or_default();
                    // Cancelled, out of budget, or over the spend cap: a dropped flare is a row,
                    // not a silent nothing — `flares list` has to be able to say why.
                    if cancel.is_cancelled() {
                        push(
                            &lines,
                            &store,
                            FlareLine::dropped(n, &route, "the run was cancelled"),
                            run,
                        );
                        continue;
                    }
                    match store.flare_cancel_requested(run) {
                        Ok(true) => {
                            push(
                                &lines,
                                &store,
                                FlareLine::dropped(n, &route, "cancelled from another process"),
                                run,
                            );
                            continue;
                        }
                        Ok(false) => {}
                        Err(_) => {}
                    }
                    if let Some(cap) = token_cap {
                        if *spent.lock().unwrap_or_else(|e| e.into_inner()) >= cap {
                            push(
                                &lines,
                                &store,
                                FlareLine::dropped(n, &route, "the run's token cap was reached"),
                                run,
                            );
                            continue;
                        }
                    }
                    let take = {
                        let mut left = budget.lock().unwrap_or_else(|e| e.into_inner());
                        let want = job
                            .max_iterations
                            .unwrap_or(self.cfg.per_flare())
                            .min(*left);
                        *left -= want;
                        want
                    };
                    if take == 0 {
                        push(
                            &lines,
                            &store,
                            FlareLine::dropped(n, &route, "the run's iteration budget was spent"),
                            run,
                        );
                        continue;
                    }
                    let session_id = runner.new_session_id();
                    let _ = store.flare_job_running(run, n, &route, &session_id);
                    // `#554`: a cancel from another process is a row, and the child used to get
                    // only the parent's in-process token — with every lane busy, the flag was not
                    // read again until the run was over. One per-job token, armed by either source.
                    let job_cancel = Cancel::new();
                    let watch = watch_cancel(
                        cancel.clone(),
                        job_cancel.clone(),
                        store.clone(),
                        run.to_string(),
                    );
                    let outcome = gated(
                        &gate,
                        runner.run_child(
                            Arc::clone(&tools),
                            ChildJob {
                                session_id: &session_id,
                                prompt: &job.prompt,
                                system: job.system.as_deref(),
                                route: &route,
                                budget: take,
                                origin: ChildOrigin::Flare { run, n },
                            },
                            approver,
                            &job_cancel,
                        ),
                    )
                    .await;
                    watch.abort();
                    let (state, text, why) = match outcome.answer {
                        Ok(text) => (State::Done, text, None),
                        Err(reason) => (State::Failed, String::new(), Some(reason)),
                    };
                    if let Some(p) = outcome.prompt_tokens {
                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += p;
                    }
                    if let Some(c) = outcome.completion_tokens {
                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += c;
                    }
                    push(
                        &lines,
                        &store,
                        FlareLine {
                            n,
                            route: outcome.route.clone(),
                            session_id: Some(session_id),
                            state,
                            text,
                            why,
                            prompt_tokens: outcome.prompt_tokens,
                            completion_tokens: outcome.completion_tokens,
                            iterations: outcome.iterations,
                        },
                        run,
                    );
                }
            }
        }))
        .await;
        let _ = lanes;
        let mut lines = lines
            .lock()
            .map(|l| l.clone())
            .unwrap_or_else(|e| e.into_inner().clone());
        lines.sort_by_key(|l| l.n);
        RunResult {
            run: run.to_string(),
            lines,
        }
    }
}

/// Run one child under the run's total slot count (`#555`). The permit is held for the whole
/// child, not for its start: what the cap is about is how many are reading at once.
async fn gated<T>(
    gate: &Arc<tokio::sync::Semaphore>,
    work: impl std::future::Future<Output = T>,
) -> T {
    let permit = gate
        .acquire()
        .await
        .expect("the flare gate is never closed");
    let out = work.await;
    drop(permit);
    out
}

/// How often a running flare looks at the store's cancel flag (`#554`). Fast enough that a
/// dashboard cancel is felt on the next tool call, slow enough that a minute of reading costs a
/// handful of small reads.
const CANCEL_POLL: Duration = Duration::from_millis(200);

/// Stop a child when either source says so: the parent's token (Esc, `#171`) or the store's flag
/// (`flares cancel` in another process, `#554`). The flag is polled because it is a row, and a row
/// cannot notify a process that is not looking at it.
fn watch_cancel(
    parent: Cancel,
    child: Cancel,
    store: SessionStore,
    run: String,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            if parent.is_cancelled() || matches!(store.flare_cancel_requested(&run), Ok(true)) {
                child.cancel();
                return;
            }
            tokio::time::sleep(CANCEL_POLL).await;
        }
    })
}

/// Record one child's row and keep it for the merge.
fn push(lines: &Arc<Mutex<Vec<FlareLine>>>, store: &SessionStore, line: FlareLine, run: &str) {
    let _ = store.flare_job_done(&FlareJobRow {
        run_id: run.to_string(),
        n: line.n,
        route: line.route.clone(),
        session_id: line.session_id.clone(),
        state: line.state.word().to_string(),
        prompt_tokens: line.prompt_tokens,
        completion_tokens: line.completion_tokens,
        iterations: line.iterations,
        why: line.why.clone(),
    });
    if let Ok(mut all) = lines.lock() {
        all.push(line);
    }
}

fn count(tokens: Option<u64>) -> String {
    tokens.map_or_else(|| "?".to_string(), |n| n.to_string())
}

fn store_error(e: crate::error::Error) -> ToolError {
    ToolError::Failed(format!("the flare run's ledger: {e}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::Message;
    use crate::provider::ChatProvider;
    use crate::router::RouteInfo;
    use crate::tools::ToolSpec;
    use crate::tools_delegate::{ChildProviders, DelegateSettings};
    use crate::usage::TurnUsage;

    /// A provider that hands out scripted replies and records the tools it was offered.
    struct Scripted {
        replies: Mutex<Vec<String>>,
        offered: Mutex<Vec<Vec<String>>>,
        usage: Mutex<Option<TurnUsage>>,
        /// When set, `chat` never answers: the shape a cancelled run leaves behind (`#553`).
        hang: bool,
    }

    impl Scripted {
        fn new(replies: &[&str]) -> Arc<Self> {
            Arc::new(Self {
                replies: Mutex::new(replies.iter().rev().map(|r| r.to_string()).collect()),
                offered: Mutex::new(Vec::new()),
                usage: Mutex::new(Some(TurnUsage {
                    prompt_tokens: Some(10),
                    completion_tokens: Some(2),
                    ..TurnUsage::default()
                })),
                hang: false,
            })
        }

        /// A provider that never answers, so a run can be cancelled while it is really in flight.
        fn hanging() -> Arc<Self> {
            let mut me = Self::new(&[]);
            // `new` returns an `Arc`; nothing else holds it yet.
            Arc::get_mut(&mut me).expect("a fresh Arc").hang = true;
            me
        }
    }

    #[async_trait]
    impl ChatProvider for Scripted {
        async fn chat(&self, _: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
            if self.hang {
                std::future::pending::<()>().await;
            }
            self.offered
                .lock()
                .unwrap()
                .push(tools.iter().map(|t| t.function.name.clone()).collect());
            let reply = self
                .replies
                .lock()
                .unwrap()
                .pop()
                .unwrap_or_else(|| "no reply scripted".to_string());
            Ok(Message::assistant(&reply))
        }
        fn take_usage(&self) -> Option<TurnUsage> {
            self.usage.lock().unwrap().take()
        }
    }

    struct Routes {
        routes: Vec<(String, Arc<dyn ChatProvider>)>,
        default: String,
    }

    impl ChildProviders for Routes {
        fn routes(&self) -> Vec<RouteInfo> {
            self.routes
                .iter()
                .map(|(n, _)| RouteInfo {
                    name: n.clone(),
                    model: format!("{n}-model"),
                    endpoint: String::new(),
                })
                .collect()
        }
        fn default_route(&self) -> String {
            self.default.clone()
        }
        fn provider(
            &self,
            name: &str,
        ) -> std::result::Result<crate::tools_delegate::ChildRoute, String> {
            self.routes
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, p)| crate::tools_delegate::ChildRoute {
                    name: name.to_string(),
                    provider: Arc::clone(p),
                    context_budget_tokens: 8000,
                })
                .ok_or_else(|| format!("unknown route `{name}`"))
        }
    }

    /// The tool a lead would hold: three read tools and one write tool, so a flare's registry can
    /// be shown to be missing the one that matters.
    struct ReadFile;
    #[async_trait]
    impl Tool for ReadFile {
        fn name(&self) -> &str {
            "read_file"
        }
        fn description(&self) -> &str {
            "read"
        }
        fn parameters(&self) -> Value {
            json!({"type": "object"})
        }
        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
            Ok("contents".into())
        }
    }
    struct WriteFile;
    #[async_trait]
    impl Tool for WriteFile {
        fn name(&self) -> &str {
            "write_file"
        }
        fn description(&self) -> &str {
            "write"
        }
        fn parameters(&self) -> Value {
            json!({"type": "object"})
        }
        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
            Ok("written".into())
        }
    }

    /// A tool that exists only to be named: these tests are about which names a registry holds,
    /// not about what the tools do.
    struct Named(&'static str);

    #[async_trait]
    impl Tool for Named {
        fn name(&self) -> &str {
            self.0
        }
        fn description(&self) -> &str {
            "named"
        }
        fn parameters(&self) -> Value {
            json!({"type": "object"})
        }
        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
            Ok(String::new())
        }
    }

    fn harness(
        dir: &std::path::Path,
        provider: Arc<Scripted>,
        cfg: FlaresConfig,
    ) -> (FlareTool, SessionStore) {
        let (tool, store, _) = harness_with_extra(dir, provider, cfg, &[]);
        (tool, store)
    }

    /// The same harness with extra tools in the lead's registry, and the names the lead ended up
    /// with — a test about what a flare does *not* hold has to prove the lead held it.
    fn harness_with_extra(
        dir: &std::path::Path,
        provider: Arc<Scripted>,
        cfg: FlaresConfig,
        extra: &[&'static str],
    ) -> (FlareTool, SessionStore, Vec<String>) {
        let store = SessionStore::new(dir.join("sessions"));
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(ReadFile), crate::config::Policy::Allow);
        registry.register(Arc::new(WriteFile), crate::config::Policy::Allow);
        for name in extra {
            registry.register(Arc::new(Named(name)), crate::config::Policy::Allow);
        }
        let lead_names = registry.names();
        let routes = Routes {
            routes: vec![("local".to_string(), provider as Arc<dyn ChatProvider>)],
            default: "local".to_string(),
        };
        let delegate = Arc::new(DelegateTool::new(
            Arc::new(routes),
            Arc::new(registry),
            store.clone(),
            DelegateSettings {
                max_output_bytes: 8000,
                max_malformed_calls: 3,
                tool_concurrency: 1,
                lock_wait: std::time::Duration::from_secs(5),
            },
        ));
        let slots = vec![RouteSlot {
            name: "local".to_string(),
            parallel: 1,
            group: None,
        }];
        (
            FlareTool::new(delegate, store.clone(), cfg, slots),
            store,
            lead_names,
        )
    }

    /// Read-only is an allowlist, not a subtraction (`#548`). A flare's registry used to be the
    /// lead's minus eight names, which left `cronjob_manage`, `skill_manage` and every plugin and
    /// MCP tool in it — under `auto`, `smart` or `--yes` a flare could schedule future cron runs
    /// and rewrite the user's skills directory while its own description said the capability was
    /// not there.
    #[test]
    fn a_flare_holds_the_readers_and_nothing_else() {
        let dir = tempfile::tempdir().unwrap();
        let provider = Scripted::new(&["unused"]);
        let extra = [
            "search_files",
            "fetch",
            "session_search",
            "skill_view",
            "skill_search",
            "cronjob_manage",
            "skill_manage",
            "plugin:notes:publish",
            "tool_call",
        ];
        let (tool, _store, lead) =
            harness_with_extra(dir.path(), provider, FlaresConfig::default(), &extra);

        // The lead really did hold the four, or the assertion below proves nothing.
        for name in &extra {
            assert!(
                lead.iter().any(|held| held == name),
                "the lead's registry holds `{name}`: {lead:?}"
            );
        }

        assert_eq!(
            tool.tools.names(),
            [
                "fetch",
                "read_file",
                "search_files",
                "session_search",
                "skill_search",
                "skill_view"
            ],
            "a flare holds the readers and nothing else"
        );
    }

    #[test]
    fn a_group_is_one_server_worth_of_slots_and_the_cap_is_their_sum() {
        let local = |name: &str, parallel: usize, group: Option<&str>| RouteSlot {
            name: name.to_string(),
            parallel,
            group: group.map(str::to_string),
        };
        // Two routes on one box are one slot, and the box takes its lowest member's bound.
        let plan = slots(
            &[local("a", 1, Some("gpu0")), local("b", 4, Some("gpu0"))],
            4,
        );
        assert_eq!(plan.per_group.get("gpu0"), Some(&1));
        assert_eq!(plan.total, 1, "two routes on one server are one slot");

        // Three local readers and one cloud thinker: two slots, not four.
        let plan = slots(
            &[
                local("read1", 1, Some("gpu0")),
                local("read2", 1, Some("gpu0")),
                local("read3", 1, Some("gpu0")),
                local("cloud", 4, None),
            ],
            4,
        );
        // The local group is one slot and the cloud route four: four in flight, and no more
        // than `max_concurrent` allows.
        assert_eq!(plan.total, 4, "one local slot plus the cloud route's four");
        assert_eq!(plan.per_group.len(), 2);

        // `max_concurrent` is a ceiling, never a floor: a config that allows four on a box with
        // one slot gets one.
        let plan = slots(&[local("a", 1, None)], 16);
        assert_eq!(plan.total, 1, "one slot is one slot");
    }

    #[tokio::test]
    async fn a_run_is_n_read_only_sessions_in_the_leads_order_with_one_merge() {
        let dir = tempfile::tempdir().unwrap();
        let provider = Scripted::new(&["alpha", "beta"]);
        let (tool, store) = harness(dir.path(), Arc::clone(&provider), FlaresConfig::default());
        let scope = crate::tools::RunScope::new("lead-session");
        let call = CallScope {
            approver: &DenyAll,
            run: &scope,
            registry: &ToolRegistry::new(4096),
            call_id: None,
        };
        let args = json!({"jobs": [
            {"prompt": "read the first crate"},
            {"prompt": "read the second crate"}
        ]});
        let text = tool.call_scoped(args, &call).await.unwrap();

        assert!(text.contains("2 of 2 finished"), "{text}");
        assert!(text.contains("--- flare 1 (local) ---"), "{text}");
        assert!(text.contains("alpha") && text.contains("beta"), "{text}");

        // Two sessions, both flares, positions 1 and 2, and the store knows the run.
        let runs = store.flare_runs(10).unwrap();
        assert_eq!(runs.len(), 1, "{runs:?}");
        let run = &runs[0];
        assert_eq!(run.jobs, 2);
        assert_eq!(run.state, "done");
        assert_eq!(run.parent.as_deref(), Some("lead-session"));
        assert_eq!(run.iterations, 2, "one call per flare");
        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
        assert_eq!(
            jobs.iter().map(|j| j.n).collect::<Vec<_>>(),
            vec![1, 2],
            "the ledger keeps the lead's order"
        );
        assert!(jobs.iter().all(|j| j.state == "done"));
        let sessions = store.flares_of(&run.id).unwrap();
        assert_eq!(sessions.len(), 2);
        assert_eq!(sessions[0].flare().unwrap().n, 1);

        // And the one claim that makes a fan-out safe: the write tool was not offered at all.
        let offered = provider.offered.lock().unwrap();
        assert!(
            offered
                .iter()
                .all(|tools| !tools.iter().any(|t| t == "write_file")),
            "a flare was offered write_file: {offered:?}"
        );
        assert!(offered
            .iter()
            .all(|tools| tools.iter().any(|t| t == "read_file")));
    }

    /// `#553`: the runtime cancels by dropping the future, so `call_scoped` never reached the code
    /// that closes the ledger and the row stayed `running` — a run nothing could ever cancel.
    #[tokio::test]
    async fn a_dropped_flare_call_closes_its_run_as_cancelled() {
        let dir = tempfile::tempdir().unwrap();
        let provider = Scripted::hanging();
        let (tool, store) = harness(dir.path(), Arc::clone(&provider), FlaresConfig::default());
        let scope = crate::tools::RunScope::new("lead");
        let call = CallScope {
            approver: &DenyAll,
            run: &scope,
            registry: &ToolRegistry::new(4096),
            call_id: None,
        };
        let mut fut = Box::pin(tool.call_scoped(json!({"jobs": [{"prompt": "one"}]}), &call));
        // One poll writes the ledger row and gets the job in flight; then the future is dropped,
        // which is exactly what `select!` does when the run is cancelled.
        assert!(
            futures_util::poll!(fut.as_mut()).is_pending(),
            "the job must still be running for this to be a cancellation"
        );
        drop(fut);

        let run = &store.flare_runs(10).unwrap()[0];
        assert_eq!(
            run.state, "cancelled",
            "a dropped run is not left `running` for ever"
        );
    }

    #[tokio::test]
    async fn a_run_whose_budget_runs_out_drops_the_rest_and_says_so() {
        let dir = tempfile::tempdir().unwrap();
        let provider = Scripted::new(&["only one"]);
        let cfg = FlaresConfig {
            // One iteration in the whole run: the first flare spends it, the second never starts.
            total_iterations: 1,
            ..Default::default()
        };
        let (tool, store) = harness(dir.path(), Arc::clone(&provider), cfg);
        let scope = crate::tools::RunScope::new("lead");
        let call = CallScope {
            approver: &DenyAll,
            run: &scope,
            registry: &ToolRegistry::new(4096),
            call_id: None,
        };
        let text = tool
            .call_scoped(
                json!({"jobs": [{"prompt": "one", "max_iterations": 1}, {"prompt": "two"}]}),
                &call,
            )
            .await
            .unwrap();
        assert!(text.contains("1 of 2 finished"), "{text}");
        assert!(text.contains("1 dropped"), "{text}");
        assert!(text.contains("budget"), "{text}");

        let run = &store.flare_runs(10).unwrap()[0];
        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
        assert_eq!(jobs[1].state, "dropped");
        assert!(
            jobs[1]
                .why
                .as_deref()
                .unwrap_or_default()
                .contains("budget"),
            "{:?}",
            jobs[1]
        );
        // A dropped flare has no session: there is nothing to open.
        assert!(store.flares_of(&run.id).unwrap().len() == 1);
    }

    struct DenyAll;
    #[async_trait]
    impl Approver for DenyAll {
        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
            crate::approvals::Decision::Deny("no".into())
        }
    }

    /// `#555`: `[flares] max_concurrent` is a cap on children at once, not a number that is
    /// computed and dropped. Six children, two permits: never three live.
    #[tokio::test]
    async fn the_flare_gate_holds_the_run_to_its_total() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let gate = Arc::new(tokio::sync::Semaphore::new(2));
        let live = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));
        let mut handles = Vec::new();
        for _ in 0..6 {
            let (gate, live, peak) = (Arc::clone(&gate), Arc::clone(&live), Arc::clone(&peak));
            handles.push(tokio::spawn(async move {
                gated(&gate, async move {
                    let now = live.fetch_add(1, Ordering::SeqCst) + 1;
                    peak.fetch_max(now, Ordering::SeqCst);
                    tokio::time::sleep(Duration::from_millis(20)).await;
                    live.fetch_sub(1, Ordering::SeqCst);
                })
                .await;
            }));
        }
        for handle in handles {
            handle.await.expect("no panic in the child");
        }
        assert_eq!(
            peak.load(Ordering::SeqCst),
            2,
            "two at a time, not six: the setting did nothing before this"
        );
    }

    /// `#554`: a cancel from another process is a row. With every lane busy the flag was never
    /// read again, so the run kept spending after `flares cancel`. The watcher is the bridge from
    /// that row to the token a child actually watches.
    #[tokio::test]
    async fn a_cancel_from_another_process_stops_a_started_child() {
        let dir = tempfile::tempdir().unwrap();
        let store = SessionStore::new(dir.path().join("sessions"));
        store
            .begin_flare_run("r1", "a task", &["local".into()], 1, "parent")
            .unwrap();
        let parent = Cancel::new();
        let child = Cancel::new();
        let watch = watch_cancel(parent.clone(), child.clone(), store.clone(), "r1".into());
        assert!(!child.is_cancelled(), "nothing has asked it to stop");
        store.cancel_flare_run("r1").unwrap();
        tokio::time::sleep(CANCEL_POLL * 3).await;
        assert!(
            child.is_cancelled(),
            "the store's flag reached the child that was already running"
        );
        watch.abort();

        // And the parent's own token still works, which is the path Esc takes in-process.
        let (parent, child) = (Cancel::new(), Cancel::new());
        let watch = watch_cancel(parent.clone(), child.clone(), store.clone(), "r2".into());
        parent.cancel();
        tokio::time::sleep(CANCEL_POLL * 3).await;
        assert!(child.is_cancelled(), "the parent's token");
        watch.abort();
    }
}