agent-works 0.16.0

Batteries-included Agent toolbox built on agent-base
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
//! Agent lifecycle registry — the single source of truth for child state.
//!
//! Session 20260904_c6559510 redesign: an agent's status is **derived from
//! observable facts**, never stored as a marker. The old `set_status` protocol
//! made every caller responsible for marking state at the right moment; one
//! forgotten call produced a phantom-idle registry and the watcher fired the
//! fan-in batch early (7 reports → 53,276 tokens of re-synthesis). Under the
//! fact model there is nothing to forget: the two facts below are maintained
//! at exactly the two places the runtime structure forces work through.
//!
//! # Facts (per agent)
//!
//! ```text
//! queue_len      : tasks enqueued but not yet dequeued (send_task / dequeue)
//! in_flight      : a dequeued task is executing and its result is unposted
//! results_posted : monotonic count of results this agent has delivered
//! results_handed_over : results included in a fired fan-in batch
//! last_result    : how the most recent delivered task ended
//!                  (Success / Failed(error) / Cancelled) + its error text
//! ```
//!
//! `results_posted` vs `results_handed_over` is the **delivery gap**: how
//! many of an agent's reports exist but have not reached the parent yet.
//! Session 20260904_841ed65b: a mid-turn parent saw `done` children but no
//! reports (Progress never wakes the parent; the batch flushes at turn end)
//! and concluded "the system didn't deliver" — then re-did the work itself.
//! Surfacing the gap through `list_agents` turns that blind faith into a
//! checkable fact.
//!
//! | Fact change      | Maintained by       | Timing                          |
//! |------------------|---------------------|---------------------------------|
//! | `queue_len += 1` | `note_enqueued`     | when `send_task` queues a task  |
//! | `queue_len -= 1` | `note_dequeued`     | when the child loop dequeues    |
//! | `in_flight=true` | `note_dequeued`     | same dequeue                    |
//! | `in_flight=false`| `note_posted`       | **before** `post_result` bumps the seq — the watcher wakes on that bump and must see the settled facts |
//! | `results_posted+=1`| `note_posted`     | same delivery                   |
//! | `last_result`    | `note_posted`       | same delivery (the run's outcome) |
//!
//! # Derived status
//!
//! [`AgentStatus`] is a pure function of the facts — see
//! [`derive_status`]. There is deliberately no `Idle`: a spawned-but-never-
//! tasked agent has the same facts (`queue_len==0 && !in_flight`) as a
//! finished one, and forcing the model to distinguish the two only breeds
//! polling. A failed/cancelled result derives `Failed`/`Cancelled` — the
//! outcome is a fact like any other, so a UI never has to guess (before
//! this, a failed child derived `Done` and panels showed it green).
//!
//! # Quiescence (fan-in)
//!
//! [`AgentRegistry::quiescent`] is the watcher's batch predicate: nobody is
//! working (`!in_flight && queue_len==0` everywhere) **and** every registered
//! agent has delivered at least once. The delivery clause seals the
//! spawn→send window: a freshly spawned agent (registered, zero deliveries)
//! cannot satisfy quiescence, so a batch can never fire while a sibling's
//! `send_task` is still in flight.
//!
//! # Lifecycle broadcast
//!
//! Every fact-driven transition emits an [`AgentLifecycleEvent`] (ring buffer,
//! [`AgentRegistry::recent_events`]) and republishes a [`RegistrySnapshot`]
//! through a `tokio::sync::watch` channel ([`AgentRegistry::subscribe`]).
//! Consumers (UI panel, `list_agents`, logging) read "what is each agent's
//! status *now*" from the snapshot; the event ring is for diagnostics.

use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Instant;

use tokio::sync::watch;

use super::config::MultiAgentConfig;
use super::path::AgentPath;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Lifecycle status of a sub-agent — **derived**, never stored.
///
/// See [`derive_status`] for the derivation and the registry module docs for
/// why no variant carries a marker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AgentStatus {
    /// Task(s) queued but nothing executing (before the first dequeue, or
    /// between posts while another task waits).
    Queued,
    /// Executing a dequeued task (from dequeue to `note_posted`).
    Running,
    /// Queue empty, nothing in flight — the last result was a success (or no
    /// result yet: a freshly spawned agent lands here, its facts
    /// indistinguishable until the first `send_task`).
    Done,
    /// Queue empty, nothing in flight — the last result failed (error or
    /// timeout). The most recent result speaks: a new task flips the agent
    /// back to `Running`, and a later success derives `Done` again.
    Failed,
    /// Queue empty, nothing in flight — the last run was cancelled (or the
    /// agent was closed before reporting).
    Cancelled,
    /// Unregistered (closed or cleaned up).
    Closed,
    /// Reserved for Phase 6+ (user/guard pause). Not produced yet.
    Paused,
    /// A wire name this build does not know (forward compatibility). Only
    /// produced by [`AgentStatus::from_name`]; never derived. Consumers must
    /// treat it conservatively (see `from_name`).
    Unknown,
}

impl AgentStatus {
    /// Lowercase name used on the wire (`list_agents`, close results).
    pub fn name(&self) -> &'static str {
        match self {
            Self::Queued => "queued",
            Self::Running => "running",
            Self::Done => "done",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
            Self::Closed => "closed",
            Self::Paused => "paused",
            Self::Unknown => "unknown",
        }
    }

    /// Parse a wire name back into a status — the single vocabulary source
    /// for consumers (never match the raw string yourself; a new word from a
    /// newer registry then degrades to [`AgentStatus::Unknown`] instead of
    /// silently mis-classifying). Unknown names are the conservative kind:
    /// not terminal, not alarming — treat as still-working so nothing is
    /// reaped or red-flagged on a word this build does not understand.
    pub fn from_name(name: &str) -> AgentStatus {
        match name {
            "queued" => Self::Queued,
            "running" => Self::Running,
            "done" => Self::Done,
            "failed" => Self::Failed,
            "cancelled" => Self::Cancelled,
            "closed" => Self::Closed,
            "paused" => Self::Paused,
            _ => Self::Unknown,
        }
    }
}

/// How an agent's most recent delivered task ended — the outcome fact
/// recorded at [`AgentRegistry::note_posted`].
///
/// Derived status is a pure function of this (plus the work facts): a
/// failure or cancellation is never laundered into `Done`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResultKind {
    /// The task completed (successfully or with a soft "continuing" nudge).
    Success,
    /// The task failed: unrecoverable error, turn cap, or timeout. Carries
    /// the error text for ledger lines (`FAILED (...)`) — consumers must not
    /// invent detail (like exit codes) that the text does not contain.
    Failed(String),
    /// The run was cancelled before it reported.
    Cancelled,
}

/// Derive a sub-agent's status from the observable facts (pure function).
///
/// ```text
/// (unregistered)            → Closed
/// in_flight                 → Running   (queued siblings don't change this)
/// queue_len > 0             → Queued    (work waiting, nothing executing)
/// last result failed        → Failed    (most recent result speaks)
/// last result cancelled     → Cancelled
/// else                      → Done      (delivered and nothing pending)
/// ```
pub fn derive_status(
    registered: bool,
    in_flight: bool,
    queue_len: usize,
    last_result: Option<&ResultKind>,
) -> AgentStatus {
    match (registered, in_flight, queue_len) {
        (false, _, _) => AgentStatus::Closed,
        (_, true, _) => AgentStatus::Running,
        (_, false, 0) => match last_result {
            Some(ResultKind::Failed(_)) => AgentStatus::Failed,
            Some(ResultKind::Cancelled) => AgentStatus::Cancelled,
            _ => AgentStatus::Done,
        },
        (_, false, _) => AgentStatus::Queued,
    }
}

/// A registered agent entry in the registry.
///
/// The fields below `results_posted` are the facts; `status()` derives the
/// lifecycle from them. `tool_calls` / `last_activity` remain plain metrics
/// (stall diagnostics) and play no part in the derivation.
#[derive(Clone, Debug)]
pub struct AgentEntry {
    /// The agent's tree path.
    pub path: AgentPath,
    /// Depth from root (root=0, direct child=1, etc.).
    pub depth: i32,
    /// Tasks enqueued but not yet dequeued.
    pub queue_len: usize,
    /// A dequeued task is executing and its result is unposted.
    pub in_flight: bool,
    /// When the current `Running` period began (the last dequeue). `None`
    /// outside `Running`; feeds stall detection (Phase 6 reaper).
    pub running_since: Option<Instant>,
    /// A cancel was requested for this agent (`close_agent` / `cancel_all`).
    ///
    /// Terminal fact: the child will never run its normal result epilogue
    /// (`note_posted` lives in the child loop), so before this flag existed a
    /// force-killed child stayed `in_flight=true, results_posted=0` forever
    /// and permanently blocked fan-in quiescence — a held batch could never
    /// fire (session 20260914_50cf809d: two specialist reports lost). A
    /// closing agent counts as settled for `quiescent()` and derives to
    /// `Closed` immediately (observers see the close land at cancel time,
    /// not at the child's eventual unwind). Cleared only by unregistration.
    pub closing: bool,
    /// Monotonic count of results this agent has delivered. Drives the
    /// fan-in delivery-completeness clause — a registered agent with zero
    /// deliveries (spawn→send window) can never be part of a settled batch.
    pub results_posted: usize,
    /// Results already included in a fired batch (see field docs).
    pub results_handed_over: usize,
    /// Results of this agent that have been included in a fired fan-in
    /// batch (the watcher stamps every batch member when it drains). The
    /// delivery gap `results_posted - results_handed_over` is what
    /// `list_agents` surfaces as `pending_results`: reports that exist but
    /// have not reached the parent yet.
    /// Tool calls the agent has actually executed (monotonic). Surfaced by
    /// `list_agents` so the parent can distinguish "working" from "stalled":
    /// a live agent's count grows; a frozen count with a stale
    /// `last_activity` is the real stall signal.
    ///
    /// (This deliberately replaced the former static `tool_count` — the size
    /// of the child's tool *inventory*, fixed at spawn — which the parent
    /// misread as progress: "stuck at 9 tool calls".)
    pub tool_calls: usize,
    /// Last observed activity (task start or tool call). `None` until the
    /// agent receives its first task.
    pub last_activity: Option<Instant>,
    /// The task the agent is currently assigned (first `send_task` wins).
    /// Recorded so `list_agents` can show *what* each agent is doing, not
    /// just its lifecycle status.
    pub task: Option<String>,
    /// How the most recent delivered task ended (`None` until the first
    /// `note_posted`). The outcome fact behind `Failed`/`Cancelled`.
    pub last_result: Option<ResultKind>,
    /// Error text of the most recent failed result (kept for ledger lines;
    /// `None` on success/cancel). Cleared when a later result succeeds.
    pub last_error: Option<String>,
}

impl AgentEntry {
    /// Derived lifecycle status (this entry is by definition registered).
    ///
    /// A closing agent derives straight to `Closed`: the cancel decision is
    /// the externally observable truth, the future's unwind is an internal
    /// detail that may lag by seconds.
    pub fn status(&self) -> AgentStatus {
        if self.closing {
            return AgentStatus::Closed;
        }
        derive_status(
            true,
            self.in_flight,
            self.queue_len,
            self.last_result.as_ref(),
        )
    }
}

/// One status transition, emitted when a fact change moves an agent between
/// derived states. The event stream is diagnostics only — state consumers
/// read the [`RegistrySnapshot`].
#[derive(Clone, Debug)]
pub struct AgentLifecycleEvent {
    /// The agent's tree path.
    pub path: AgentPath,
    /// Previously derived status.
    pub from: AgentStatus,
    /// Newly derived status.
    pub to: AgentStatus,
    /// Human-readable cause: `"task_enqueued"` / `"task_dequeued"` /
    /// `"result_posted"` / `"unregistered"`.
    pub reason: &'static str,
}

/// Point-in-time view of every registered agent, published through the
/// registry's `watch` channel on each transition. This is what read-only
/// consumers (UI panel, `list_agents`) subscribe to.
#[derive(Clone, Debug, Default)]
pub struct RegistrySnapshot {
    /// One entry per registered agent, sorted by path.
    pub agents: Vec<AgentSnapshot>,
}

/// Per-agent row of a [`RegistrySnapshot`].
#[derive(Clone, Debug)]
pub struct AgentSnapshot {
    /// Agent path as a string (e.g. `"root/worker"`).
    pub path: String,
    /// Derived status name (`queued` / `running` / `done` / `failed` /
    /// `cancelled`; `paused` is reserved and never produced yet). `closed`
    /// appears only between `note_closing` and unregistration. Snapshot rows
    /// exist only for registered agents; unregistration shows up as the
    /// agent leaving the snapshot. Consumers should parse with
    /// [`AgentStatus::from_name`], not by matching strings.
    pub status: String,
    /// Seconds spent in the current `Running` period; `None` unless running.
    pub running_secs: Option<u64>,
    /// Seconds since the agent's last observed activity (metrics — task
    /// start or tool call; `None` until the first task).
    pub last_activity_secs: Option<u64>,
    /// Executed tool calls (monotonic) — metrics, not lifecycle.
    pub tool_calls: usize,
    /// What the agent was asked to do (first task wins).
    pub task: Option<String>,
    /// Reports that exist but have not been included in a fired batch yet
    /// (`results_posted - results_handed_over`). Zero is the common case.
    pub pending_results: usize,
    /// Error text of the most recent failed result (`Some` while `status` is
    /// `"failed"` and the failure carried an error). Ledger lines render it
    /// as-is — consumers must not fabricate detail (e.g. exit codes) that is
    /// not in this string.
    pub last_error: Option<String>,
}

/// Errors that can occur during spawn attempts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpawnError {
    /// Spawning would exceed the maximum number of sub-agents.
    MaxAgentsReached { max: usize },
    /// Spawning would exceed the maximum agent nesting depth.
    DepthLimitReached { max: i32, attempted: i32 },
    /// An agent with this path already exists.
    AlreadyExists,
}

impl std::fmt::Display for SpawnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MaxAgentsReached { max } => {
                write!(f, "max agents reached (limit: {})", max)
            }
            Self::DepthLimitReached { max, attempted } => {
                write!(
                    f,
                    "agent depth limit reached (max: {}, attempted: {})",
                    max, attempted
                )
            }
            Self::AlreadyExists => {
                write!(f, "agent with this path already exists")
            }
        }
    }
}

// ---------------------------------------------------------------------------
// AgentRegistry
// ---------------------------------------------------------------------------

/// Tracks active sub-agents and enforces spawn limits.
///
/// # Lifecycle (derived, not marked)
///
/// ```text
/// register()                    → facts (0,false)   → Done
/// note_enqueued  (send_task)    → queue_len += 1    → Queued
/// note_dequeued  (child loop)   → -1, in_flight     → Running
/// note_posted    (child loop)   → in_flight=false   → Done / Failed /
///                                                    Cancelled per the
///                                                    result (or Queued if
///                                                    more queued)
/// close()                       → entry removed     → Closed (event ring only —
///                                                    never a snapshot row)
/// ```
///
/// Done agents still count toward the quota until explicitly `close()`d.
/// There is no automatic garbage collection in v1.
pub struct AgentRegistry {
    config: MultiAgentConfig,
    agents: HashMap<AgentPath, AgentEntry>,
    /// Lifecycle event ring (diagnostics; oldest dropped at capacity).
    events: VecDeque<AgentLifecycleEvent>,
    /// Watch channel carrying the latest [`RegistrySnapshot`].
    snapshot_tx: watch::Sender<Arc<RegistrySnapshot>>,
}

/// Ring-buffer capacity for lifecycle events. Same order of magnitude as
/// agent-base's event bus default (2048, inline in `builder.rs` — the value
/// is duplicated here, not shared).
const EVENT_RING_CAP: usize = 2048;

impl AgentRegistry {
    /// Create a new registry with the given configuration.
    pub fn new(config: MultiAgentConfig) -> Self {
        let (snapshot_tx, _) = watch::channel(Arc::new(RegistrySnapshot::default()));
        Self {
            config,
            agents: HashMap::new(),
            events: VecDeque::new(),
            snapshot_tx,
        }
    }

    /// Check whether a new agent can be spawned at the given depth.
    ///
    /// Returns `Ok(())` if spawning is allowed, or a [`SpawnError`] describing
    /// which limit was exceeded.
    pub fn can_spawn(&self, depth: i32) -> Result<(), SpawnError> {
        // Check total count limit
        if self.config.enabled && self.agents.len() >= self.config.max_sub_agents {
            return Err(SpawnError::MaxAgentsReached {
                max: self.config.max_sub_agents,
            });
        }

        // Check depth limit
        if self.config.enabled && depth > self.config.max_agent_depth {
            return Err(SpawnError::DepthLimitReached {
                max: self.config.max_agent_depth,
                attempted: depth,
            });
        }

        Ok(())
    }

    /// Register a new agent.
    ///
    /// Returns `Ok(())` on success, or a [`SpawnError`] if limits are exceeded
    /// or the path already exists.
    pub fn register(&mut self, path: &AgentPath, depth: i32) -> Result<(), SpawnError> {
        self.can_spawn(depth)?;

        if self.agents.contains_key(path) {
            return Err(SpawnError::AlreadyExists);
        }

        self.agents.insert(
            path.clone(),
            AgentEntry {
                path: path.clone(),
                depth,
                queue_len: 0,
                in_flight: false,
                running_since: None,
                closing: false,
                results_posted: 0,
                results_handed_over: 0,
                tool_calls: 0,
                last_activity: None,
                task: None,
                last_result: None,
                last_error: None,
            },
        );

        Ok(())
    }

    /// Close (remove) an agent from the registry.
    ///
    /// Returns the removed entry, or `None` if the agent was not registered.
    /// This releases the agent's quota slot. Emits an `unregistered`
    /// transition (→ `Closed`) and republishes the snapshot without the agent.
    pub fn close(&mut self, path: &AgentPath) -> Option<AgentEntry> {
        let entry = self.agents.remove(path)?;
        self.push_event(AgentLifecycleEvent {
            path: path.clone(),
            from: entry.status(),
            to: AgentStatus::Closed,
            reason: "unregistered",
        });
        self.publish_snapshot();
        Some(entry)
    }

    /// Record a fact change and emit a transition event if the derived status
    /// moved. Shared body of the three `note_*` methods.
    fn transition(
        &mut self,
        path: &AgentPath,
        reason: &'static str,
        apply: impl FnOnce(&mut AgentEntry),
    ) -> bool {
        let Some(entry) = self.agents.get_mut(path) else {
            return false;
        };
        let from = entry.status();
        apply(entry);
        let to = entry.status();
        if from != to {
            self.push_event(AgentLifecycleEvent {
                path: path.clone(),
                from,
                to,
                reason,
            });
            self.publish_snapshot();
        }
        true
    }

    /// Record that a task was enqueued for the agent (fact: `queue_len += 1`).
    ///
    /// Called by `send_task` after the mailbox accepted the task. Returns
    /// `true` if the agent was found.
    pub fn note_enqueued(&mut self, path: &AgentPath) -> bool {
        self.transition(path, "task_enqueued", |e| {
            e.queue_len += 1;
        })
    }

    /// Record that the child loop dequeued a task (facts: `queue_len -= 1`,
    /// `in_flight = true`, `running_since = now`).
    ///
    /// Returns `true` if the agent was found.
    pub fn note_dequeued(&mut self, path: &AgentPath) -> bool {
        self.transition(path, "task_dequeued", |e| {
            e.queue_len = e.queue_len.saturating_sub(1);
            e.in_flight = true;
            e.running_since = Some(Instant::now());
        })
    }

    /// Record that the child loop delivered a task's result (facts:
    /// `in_flight = false`, `results_posted += 1`, `running_since = None`,
    /// `last_result`/`last_error` = this run's outcome).
    ///
    /// Must be called **before** `post_result` bumps the mailbox sequence:
    /// the watcher wakes on that bump and must observe the settled facts —
    /// this ordering is what makes "result drained ⇒ producer quiescent"
    /// hold structurally instead of by caller discipline.
    ///
    /// Returns `true` if the agent was found.
    pub fn note_posted(&mut self, path: &AgentPath, result: ResultKind) -> bool {
        self.transition(path, "result_posted", |e| {
            e.in_flight = false;
            e.results_posted += 1;
            e.running_since = None;
            e.last_error = match &result {
                ResultKind::Failed(error) => Some(error.clone()),
                _ => None,
            };
            e.last_result = Some(result);
        })
    }

    /// Record that a cancel was requested for the agent (facts: `closing =
    /// true`, `in_flight = false`, `queue_len = 0`, `running_since = None`).
    ///
    /// Called by `close_agent` / `cancel_all` the moment they fire the cancel
    /// token — **before** the child's future unwinds (which may lag seconds
    /// behind: cancellation only lands at its next await point). From this
    /// moment the agent counts as settled for fan-in quiescence (`closing`
    /// short-circuits the per-agent clause) and derives to `Closed`.
    ///
    /// Queued tasks are dropped from the facts: a closing agent will never
    /// dequeue them, so keeping the count would block `busy_count` /
    /// quiescence for work that is already abandoned.
    ///
    /// Returns `true` if the agent was found.
    pub fn note_closing(&mut self, path: &AgentPath) -> bool {
        self.transition(path, "closing", |e| {
            e.closing = true;
            e.in_flight = false;
            e.queue_len = 0;
            e.running_since = None;
        })
    }

    /// Roll back a `note_enqueued` whose `send_task` subsequently failed
    /// (mailbox entry vanished, or the task channel rejected the task). The
    /// enqueue fact is always recorded **before** the task is sent, so a
    /// failed send must give the count back — otherwise a phantom
    /// `queue_len` would block quiescence forever (nothing will ever dequeue
    /// or deliver it).
    ///
    /// Returns `true` if the agent was found.
    pub fn note_send_failed(&mut self, path: &AgentPath) -> bool {
        self.transition(path, "task_send_failed", |e| {
            e.queue_len = e.queue_len.saturating_sub(1);
        })
    }

    /// Record that every result this agent has posted so far was included in
    /// a fired fan-in batch (the watcher stamps each batch member at drain
    /// time). This closes the agent's delivery gap: `pending_results` drops
    /// to zero until it posts again (e.g. a follow-up task's answer).
    ///
    /// Deliberately not a `transition`: the derived status does not move, so
    /// no lifecycle event is emitted — but the snapshot is republished so
    /// watch consumers see the delivery gap close promptly.
    ///
    /// Returns `true` if the agent was found (closed agents are a no-op:
    /// their entries are gone, and their pending reports left with them).
    pub fn note_batch_handed_over(&mut self, path: &AgentPath) -> bool {
        let Some(entry) = self.agents.get_mut(path) else {
            return false;
        };
        entry.results_handed_over = entry.results_posted;
        self.publish_snapshot();
        true
    }

    /// Record the agent's assigned task (first write wins).
    ///
    /// `list_agents` surfaces this so the parent — and the user asking
    /// "what is that agent doing?" — can tell agents apart by *what* they
    /// were asked to do, not just by name and lifecycle status.
    pub fn set_task(&mut self, path: &AgentPath, task: String) -> bool {
        match self.agents.get_mut(path) {
            Some(entry) => {
                if entry.task.is_none() {
                    entry.task = Some(task);
                }
                true
            }
            None => false,
        }
    }

    /// Mark the agent as active (liveness heartbeat) without counting a tool
    /// call — used on task start, where there is work but no tool call yet.
    ///
    /// Returns `true` if the agent was found and updated.
    pub fn touch(&mut self, path: &AgentPath) -> bool {
        match self.agents.get_mut(path) {
            Some(entry) => {
                entry.last_activity = Some(Instant::now());
                true
            }
            None => false,
        }
    }

    /// Record one executed tool call: bumps the monotonic counter and the
    /// activity timestamp.
    ///
    /// Called from the child event bridge on every `ActionStarted`, so
    /// `list_agents` can show real progress (see [`AgentEntry::tool_calls`]).
    /// Returns `true` if the agent was found and updated.
    pub fn record_tool_call(&mut self, path: &AgentPath) -> bool {
        match self.agents.get_mut(path) {
            Some(entry) => {
                entry.tool_calls += 1;
                entry.last_activity = Some(Instant::now());
                true
            }
            None => false,
        }
    }

    /// Number of agents with work outstanding (executing or queued).
    ///
    /// The fan-in coordinator does not use counts — it uses
    /// [`Self::quiescent`] — but operators and tests still want the number.
    pub fn busy_count(&self) -> usize {
        self.agents
            .values()
            .filter(|e| !e.closing && (e.in_flight || e.queue_len > 0))
            .count()
    }

    /// Fan-in quiescence predicate — may a pending batch fire now?
    ///
    /// All three clauses must hold:
    /// 1. nobody is working: `!in_flight && queue_len == 0` for every agent;
    /// 2. every registered agent has delivered ≥1 result (delivery
    ///    completeness — structurally seals the spawn→send window, where a
    ///    freshly spawned agent would otherwise derive `Done` and let a
    ///    sibling's result fire a batch that excludes it);
    /// 3. (caller side) the batch itself is non-empty.
    ///
    /// A closing agent satisfies both clauses unconditionally: its cancel was
    /// requested, so it will never post a result through the child-loop
    /// epilogue that clause 2 counts on. Requiring a report from it would
    /// deadlock the batch forever (session 20260914_50cf809d).
    pub fn quiescent(&self) -> bool {
        let all_quiet = self
            .agents
            .values()
            .all(|e| e.closing || (!e.in_flight && e.queue_len == 0 && e.results_posted >= 1));
        if !all_quiet {
            let blocking: Vec<String> = self
                .agents
                .values()
                .filter(|e| !e.closing && (e.in_flight || e.queue_len > 0 || e.results_posted < 1))
                .map(|e| {
                    format!(
                        "{}: in_flight={}, queue_len={}, results_posted={}",
                        e.path, e.in_flight, e.queue_len, e.results_posted
                    )
                })
                .collect();
            tracing::info!(
                blocking_agents = ?blocking,
                "registry: quiescent=false"
            );
        }
        all_quiet
    }

    /// Get an agent entry by path.
    pub fn get(&self, path: &AgentPath) -> Option<&AgentEntry> {
        self.agents.get(path)
    }

    /// List all registered agents (all statuses).
    pub fn list(&self) -> Vec<&AgentEntry> {
        let mut entries: Vec<&AgentEntry> = self.agents.values().collect();
        entries.sort_by(|a, b| a.path.cmp(&b.path));
        entries
    }

    /// Return the total number of registered agents.
    pub fn count(&self) -> usize {
        self.agents.len()
    }

    /// Return whether the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.agents.is_empty()
    }

    /// Check if an agent path is registered.
    pub fn contains(&self, path: &AgentPath) -> bool {
        self.agents.contains_key(path)
    }

    /// Build a point-in-time [`RegistrySnapshot`] (sorted by path).
    pub fn snapshot(&self) -> RegistrySnapshot {
        RegistrySnapshot {
            agents: self
                .list()
                .into_iter()
                .map(|e| AgentSnapshot {
                    path: e.path.to_string(),
                    status: e.status().name().to_string(),
                    running_secs: if e.status() == AgentStatus::Running {
                        e.running_since.map(|t| t.elapsed().as_secs())
                    } else {
                        None
                    },
                    last_activity_secs: e.last_activity.map(|t| t.elapsed().as_secs()),
                    tool_calls: e.tool_calls,
                    task: e.task.clone(),
                    pending_results: e.results_posted.saturating_sub(e.results_handed_over),
                    last_error: e.last_error.clone(),
                })
                .collect(),
        }
    }

    /// Subscribe to snapshot updates (watch channel; carries the latest
    /// snapshot only — consumers want "now", not a replay).
    ///
    /// Republishes happen on derived-status **transitions** (and close) only.
    /// Metric fields (`tool_calls`, `last_activity_secs`, `running_secs`,
    /// `task`) are therefore transition-frozen between events — a UI that
    /// wants live metrics must poll `list_agents`, and should derive only
    /// status from this stream.
    pub fn subscribe(&self) -> watch::Receiver<Arc<RegistrySnapshot>> {
        self.snapshot_tx.subscribe()
    }

    /// Borrow the most recent snapshot without cloning.
    pub fn latest_snapshot(&self) -> Arc<RegistrySnapshot> {
        self.snapshot_tx.borrow().clone()
    }

    /// The last `max` lifecycle events, oldest first (diagnostics).
    pub fn recent_events(&self, max: usize) -> Vec<AgentLifecycleEvent> {
        let skip = self.events.len().saturating_sub(max);
        self.events.iter().skip(skip).cloned().collect()
    }

    fn push_event(&mut self, event: AgentLifecycleEvent) {
        if self.events.len() >= EVENT_RING_CAP {
            self.events.pop_front();
        }
        self.events.push_back(event);
    }

    fn publish_snapshot(&mut self) {
        let snapshot = Arc::new(self.snapshot());
        // `send_replace`, not `send`: publishing must not depend on a
        // receiver existing (`send` errors — and leaves the old value —
        // once every receiver is dropped).
        self.snapshot_tx.send_replace(snapshot);
    }

    /// Get a reference to the configuration.
    pub fn config(&self) -> &MultiAgentConfig {
        &self.config
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests;