nexo-core 0.1.13

Agent runtime: event bus, sessions, plugin trait, heartbeat, A2A delegation.
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
//! Phase 82.10.c — `nexo/admin/agents/*` handlers.
//!
//! Yaml mutation is delegated to a [`YamlPatcher`] trait so this
//! crate stays cycle-free vs `nexo-setup` (which holds the
//! concrete `yaml_patch` impl + already depends on `nexo-core`).
//! Production wiring in `src/main.rs` constructs an adapter that
//! forwards each method to `nexo_setup::yaml_patch::*`.
//!
//! After successful mutation the handler calls the dispatcher's
//! reload signal to trigger Phase 18 hot-reload so the running
//! runtime picks up the change without restart.

use serde_json::Value;

use nexo_tool_meta::admin::agents::{
    AgentDetail, AgentSummary, AgentUpsertInput, AgentsDeleteParams, AgentsDeleteResponse,
    AgentsGetParams, AgentsListFilter, AgentsListResponse, BindingSummary, HeartbeatWire, ModelRef,
};

use crate::agent::admin_rpc::dispatcher::{AdminRpcError, AdminRpcResult};

/// Phase 82.10.c — yaml mutation surface the agents domain
/// handlers consume. Production impl wraps
/// `nexo_setup::yaml_patch`. Tests provide an in-memory mock.
pub trait YamlPatcher: Send + Sync {
    /// List every `agents.yaml.<id>` block in source order.
    fn list_agent_ids(&self) -> anyhow::Result<Vec<String>>;
    /// Read one dotted field (`model.provider`,
    /// `inbound_bindings`, …). `None` when the field is absent.
    fn read_agent_field(&self, agent_id: &str, dotted: &str) -> anyhow::Result<Option<Value>>;
    /// Upsert one dotted field. Atomic via temp+rename in the
    /// production impl.
    fn upsert_agent_field(&self, agent_id: &str, dotted: &str, value: Value) -> anyhow::Result<()>;
    /// Remove the entire `agents.yaml.<id>` block.
    fn remove_agent(&self, agent_id: &str) -> anyhow::Result<()>;
}

/// `nexo/admin/agents/list` — return agents matching `filter`.
pub fn list(patcher: &dyn YamlPatcher, params: Value) -> AdminRpcResult {
    let filter: AgentsListFilter = parse_or_default(params);
    let ids = match patcher.list_agent_ids() {
        Ok(ids) => ids,
        Err(e) => {
            return AdminRpcResult::err(AdminRpcError::Internal(format!("yaml read failed: {e}")));
        }
    };

    let mut summaries: Vec<AgentSummary> = ids
        .into_iter()
        .filter_map(|id| read_summary(patcher, &id).ok().flatten())
        .filter(|s| !filter.active_only || s.active)
        .filter(|s| match &filter.plugin_filter {
            Some(p) => has_plugin_binding(patcher, &s.id, p),
            None => true,
        })
        .filter(|s| match &filter.tenant_id {
            // Phase 83.8.12 — multi-tenant filter. Defense-in-
            // depth: an agent without `tenant_id` is treated
            // as `None` and filtered out when caller requests
            // a specific tenant. Cross-tenant returns empty
            // (no leak of existence).
            Some(want) => agent_tenant_id(patcher, &s.id)
                .as_deref()
                .map(|got| got == want)
                .unwrap_or(false),
            None => true,
        })
        .collect();
    // Stable alpha order — operator UIs rely on it for diff
    // displays.
    summaries.sort_by(|a, b| a.id.cmp(&b.id));

    let response = AgentsListResponse { agents: summaries };
    AdminRpcResult::ok(serde_json::to_value(response).unwrap_or(Value::Null))
}

/// `nexo/admin/agents/get` — return full detail for one agent.
pub fn get(patcher: &dyn YamlPatcher, params: Value) -> AdminRpcResult {
    let p: AgentsGetParams = match serde_json::from_value(params) {
        Ok(p) => p,
        Err(e) => {
            return AdminRpcResult::err(AdminRpcError::InvalidParams(e.to_string()));
        }
    };
    match read_detail(patcher, &p.agent_id) {
        Ok(Some(detail)) => AdminRpcResult::ok(serde_json::to_value(detail).unwrap_or(Value::Null)),
        Ok(None) => AdminRpcResult::err(AdminRpcError::Internal(format!(
            "not_found: agent `{}` not in yaml",
            p.agent_id
        ))),
        Err(e) => AdminRpcResult::err(AdminRpcError::Internal(format!("yaml read failed: {e}"))),
    }
}

/// `nexo/admin/agents/upsert` — create or update an agent block.
pub fn upsert(
    patcher: &dyn YamlPatcher,
    params: Value,
    reload_signal: &dyn Fn(),
) -> AdminRpcResult {
    let input: AgentUpsertInput = match serde_json::from_value(params) {
        Ok(i) => i,
        Err(e) => {
            return AdminRpcResult::err(AdminRpcError::InvalidParams(e.to_string()));
        }
    };

    if let Err(e) = upsert_yaml(patcher, &input) {
        return AdminRpcResult::err(AdminRpcError::Internal(format!("yaml write failed: {e}")));
    }
    reload_signal();

    match read_detail(patcher, &input.id) {
        Ok(Some(d)) => AdminRpcResult::ok(serde_json::to_value(d).unwrap_or(Value::Null)),
        Ok(None) => AdminRpcResult::err(AdminRpcError::Internal(
            "post-upsert read returned None".into(),
        )),
        Err(e) => AdminRpcResult::err(AdminRpcError::Internal(format!(
            "post-upsert read failed: {e}"
        ))),
    }
}

/// `nexo/admin/agents/delete` — soft-delete then remove yaml block.
pub fn delete(
    patcher: &dyn YamlPatcher,
    params: Value,
    reload_signal: &dyn Fn(),
) -> AdminRpcResult {
    let p: AgentsDeleteParams = match serde_json::from_value(params) {
        Ok(p) => p,
        Err(e) => {
            return AdminRpcResult::err(AdminRpcError::InvalidParams(e.to_string()));
        }
    };

    let existed = matches!(
        patcher.list_agent_ids(),
        Ok(ids) if ids.iter().any(|id| id == &p.agent_id)
    );
    if !existed {
        // Idempotent — return removed=false, NOT an error.
        return AdminRpcResult::ok(
            serde_json::to_value(AgentsDeleteResponse { removed: false }).unwrap_or(Value::Null),
        );
    }

    match patcher.remove_agent(&p.agent_id) {
        Ok(()) => {
            reload_signal();
            AdminRpcResult::ok(
                serde_json::to_value(AgentsDeleteResponse { removed: true }).unwrap_or(Value::Null),
            )
        }
        Err(e) => AdminRpcResult::err(AdminRpcError::Internal(format!("yaml remove failed: {e}"))),
    }
}

// ── Internal helpers ────────────────────────────────────────────

fn parse_or_default<T: for<'de> serde::Deserialize<'de> + Default>(v: Value) -> T {
    serde_json::from_value(v).unwrap_or_default()
}

/// Phase 83.8.12 — read `agents.yaml.<id>.tenant_id`. Returns
/// `None` for legacy agents (no field) and on any read error
/// (defense-in-depth: fail closed for cross-tenant filters).
pub(crate) fn agent_tenant_id(patcher: &dyn YamlPatcher, agent_id: &str) -> Option<String> {
    match patcher
        .read_agent_field(agent_id, "tenant_id")
        .ok()
        .flatten()
    {
        Some(Value::String(s)) => Some(s),
        _ => None,
    }
}

fn read_summary(patcher: &dyn YamlPatcher, agent_id: &str) -> anyhow::Result<Option<AgentSummary>> {
    let provider = match patcher.read_agent_field(agent_id, "model.provider")? {
        Some(Value::String(s)) => s,
        _ => return Ok(None),
    };
    let active = match patcher.read_agent_field(agent_id, "active")? {
        Some(Value::Bool(b)) => b,
        // Default active=true when field absent (legacy yaml).
        _ => true,
    };
    let bindings_count = patcher
        .read_agent_field(agent_id, "inbound_bindings")?
        .and_then(|v| v.as_array().map(|a| a.len()))
        .unwrap_or(0);

    Ok(Some(AgentSummary {
        id: agent_id.to_string(),
        active,
        model_provider: provider,
        bindings_count,
    }))
}

fn has_plugin_binding(patcher: &dyn YamlPatcher, agent_id: &str, plugin: &str) -> bool {
    let Some(Value::Array(bindings)) = patcher
        .read_agent_field(agent_id, "inbound_bindings")
        .ok()
        .flatten()
    else {
        return false;
    };
    bindings.iter().any(|b| {
        b.get("plugin")
            .and_then(Value::as_str)
            .is_some_and(|p| p == plugin)
    })
}

fn read_detail(patcher: &dyn YamlPatcher, agent_id: &str) -> anyhow::Result<Option<AgentDetail>> {
    let Some(Value::String(provider)) = patcher.read_agent_field(agent_id, "model.provider")?
    else {
        return Ok(None);
    };
    let model = match patcher.read_agent_field(agent_id, "model.model")? {
        Some(Value::String(s)) => s,
        _ => String::new(),
    };
    let active = match patcher.read_agent_field(agent_id, "active")? {
        Some(Value::Bool(b)) => b,
        _ => true,
    };
    let allowed_tools: Vec<String> = match patcher.read_agent_field(agent_id, "allowed_tools")? {
        Some(Value::Array(arr)) => arr
            .into_iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect(),
        _ => Vec::new(),
    };
    let system_prompt = match patcher.read_agent_field(agent_id, "system_prompt")? {
        Some(Value::String(s)) => s,
        _ => String::new(),
    };
    let language = match patcher.read_agent_field(agent_id, "language")? {
        Some(Value::String(s)) => Some(s),
        _ => None,
    };
    let workspace = match patcher.read_agent_field(agent_id, "workspace")? {
        Some(Value::String(s)) => s,
        _ => String::new(),
    };
    let extra_docs: Vec<String> = match patcher.read_agent_field(agent_id, "extra_docs")? {
        Some(Value::Array(arr)) => arr
            .into_iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect(),
        _ => Vec::new(),
    };
    let inbound_bindings: Vec<BindingSummary> =
        match patcher.read_agent_field(agent_id, "inbound_bindings")? {
            Some(Value::Array(arr)) => arr
                .into_iter()
                .filter_map(|b| {
                    let plugin = b.get("plugin")?.as_str()?.to_string();
                    let instance = b.get("instance").and_then(Value::as_str).map(String::from);
                    Some(BindingSummary { plugin, instance })
                })
                .collect(),
            _ => Vec::new(),
        };

    // M15.18.d — heartbeat is `Some(..)` whenever the operator has
    // authored the block at least once. Absent yaml → None so the
    // microapp distinguishes "framework default" from "explicitly
    // configured but disabled".
    let heartbeat_enabled = patcher.read_agent_field(agent_id, "heartbeat.enabled")?;
    let heartbeat_interval = patcher.read_agent_field(agent_id, "heartbeat.interval")?;
    let heartbeat = match (heartbeat_enabled, heartbeat_interval) {
        (None, None) => None,
        (en, iv) => Some(HeartbeatWire {
            enabled: matches!(en, Some(Value::Bool(true))),
            interval: match iv {
                Some(Value::String(s)) => s,
                _ => "5m".to_string(),
            },
        }),
    };

    Ok(Some(AgentDetail {
        id: agent_id.to_string(),
        model: ModelRef { provider, model },
        active,
        allowed_tools,
        inbound_bindings,
        system_prompt,
        language,
        workspace,
        extra_docs,
        heartbeat,
    }))
}

fn upsert_yaml(patcher: &dyn YamlPatcher, input: &AgentUpsertInput) -> anyhow::Result<()> {
    // Empty `model.provider` / `model.model` mean "don't touch the
    // existing yaml value" — historically the handler overwrote
    // both unconditionally, so partial updates from callers that
    // only wanted to amend (e.g. `extra_docs`) silently bricked the
    // agent. Treat empty as a no-op write; non-empty is the real
    // upsert path.
    if !input.model.provider.is_empty() {
        patcher.upsert_agent_field(
            &input.id,
            "model.provider",
            Value::String(input.model.provider.clone()),
        )?;
    }
    if !input.model.model.is_empty() {
        patcher.upsert_agent_field(
            &input.id,
            "model.model",
            Value::String(input.model.model.clone()),
        )?;
    }
    if let Some(active) = input.active {
        patcher.upsert_agent_field(&input.id, "active", Value::Bool(active))?;
    }
    if let Some(tools) = &input.allowed_tools {
        let arr = Value::Array(tools.iter().map(|s| Value::String(s.clone())).collect());
        patcher.upsert_agent_field(&input.id, "allowed_tools", arr)?;
    }
    if let Some(prompt) = &input.system_prompt {
        patcher.upsert_agent_field(&input.id, "system_prompt", Value::String(prompt.clone()))?;
    }
    if let Some(language) = &input.language {
        patcher.upsert_agent_field(&input.id, "language", Value::String(language.clone()))?;
    }
    if let Some(transcripts_dir) = &input.transcripts_dir {
        patcher.upsert_agent_field(
            &input.id,
            "transcripts_dir",
            Value::String(transcripts_dir.clone()),
        )?;
    }
    if let Some(workspace) = &input.workspace {
        patcher.upsert_agent_field(&input.id, "workspace", Value::String(workspace.clone()))?;
    }
    if let Some(extra_docs) = &input.extra_docs {
        let arr = Value::Array(
            extra_docs
                .iter()
                .map(|s| Value::String(s.clone()))
                .collect(),
        );
        patcher.upsert_agent_field(&input.id, "extra_docs", arr)?;
    }
    // M15.18.d — heartbeat is replace-whole. `Some` writes both
    // `heartbeat.enabled` + `heartbeat.interval`; `None` leaves
    // the existing yaml block untouched. The empty-string
    // interval guard mirrors the `model.*` no-op semantic above —
    // operators sending an empty literal should not silently
    // brick the daemon at next boot, which would refuse to parse
    // an empty humantime string.
    if let Some(hb) = &input.heartbeat {
        patcher.upsert_agent_field(&input.id, "heartbeat.enabled", Value::Bool(hb.enabled))?;
        if !hb.interval.is_empty() {
            patcher.upsert_agent_field(
                &input.id,
                "heartbeat.interval",
                Value::String(hb.interval.clone()),
            )?;
        }
    }
    if let Some(bindings) = &input.inbound_bindings {
        let arr: Vec<Value> = bindings
            .iter()
            .map(|b| {
                let mut map = serde_json::Map::new();
                map.insert("plugin".into(), Value::String(b.plugin.clone()));
                if let Some(i) = &b.instance {
                    map.insert("instance".into(), Value::String(i.clone()));
                }
                Value::Object(map)
            })
            .collect();
        patcher.upsert_agent_field(&input.id, "inbound_bindings", Value::Array(arr))?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

    /// Test-only in-memory `YamlPatcher`. Stores agents as
    /// `agent_id → field_path → Value`. Sufficient for the
    /// admin-domain tests; real yaml-on-disk semantics
    /// (atomicity, ordering) are covered by `nexo-setup`'s own
    /// tests for `yaml_patch::*`.
    #[derive(Debug, Default)]
    struct MockYaml {
        agents: Mutex<HashMap<String, HashMap<String, Value>>>,
    }

    impl MockYaml {
        fn with_fixture() -> Arc<Self> {
            let me = Arc::new(Self::default());
            // ana: active, whatsapp:personal, system_prompt, language=es
            me.set("ana", "model.provider", Value::String("minimax".into()));
            me.set("ana", "model.model", Value::String("MiniMax-M2.5".into()));
            me.set("ana", "active", Value::Bool(true));
            me.set(
                "ana",
                "allowed_tools",
                Value::Array(vec![Value::String("*".into())]),
            );
            me.set(
                "ana",
                "inbound_bindings",
                serde_json::json!([{ "plugin": "whatsapp", "instance": "personal" }]),
            );
            me.set("ana", "system_prompt", Value::String("You are Ana.".into()));
            me.set("ana", "language", Value::String("es".into()));
            // bob: inactive, no bindings
            me.set("bob", "model.provider", Value::String("anthropic".into()));
            me.set(
                "bob",
                "model.model",
                Value::String("claude-opus-4-7".into()),
            );
            me.set("bob", "active", Value::Bool(false));
            me.set("bob", "inbound_bindings", Value::Array(vec![]));
            me
        }

        fn set(&self, agent_id: &str, dotted: &str, value: Value) {
            self.agents
                .lock()
                .unwrap()
                .entry(agent_id.to_string())
                .or_default()
                .insert(dotted.to_string(), value);
        }
    }

    impl YamlPatcher for MockYaml {
        fn list_agent_ids(&self) -> anyhow::Result<Vec<String>> {
            // Source order = insertion order. Use a stable
            // alphabetic sort here so test fixture order matches
            // production yaml read order (which preserves source
            // order for `mapping_for_agent`).
            let mut ids: Vec<String> = self.agents.lock().unwrap().keys().cloned().collect();
            ids.sort();
            Ok(ids)
        }

        fn read_agent_field(&self, agent_id: &str, dotted: &str) -> anyhow::Result<Option<Value>> {
            Ok(self
                .agents
                .lock()
                .unwrap()
                .get(agent_id)
                .and_then(|m| m.get(dotted).cloned()))
        }

        fn upsert_agent_field(
            &self,
            agent_id: &str,
            dotted: &str,
            value: Value,
        ) -> anyhow::Result<()> {
            self.set(agent_id, dotted, value);
            Ok(())
        }

        fn remove_agent(&self, agent_id: &str) -> anyhow::Result<()> {
            self.agents.lock().unwrap().remove(agent_id);
            Ok(())
        }
    }

    fn reload_counter() -> (Arc<AtomicUsize>, impl Fn()) {
        let count = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&count);
        (count, move || {
            counter.fetch_add(1, Ordering::Relaxed);
        })
    }

    #[test]
    fn agents_list_returns_yaml_summary_in_alpha_order() {
        let yaml = MockYaml::with_fixture();
        let result = list(&*yaml, Value::Null);
        let response: AgentsListResponse = serde_json::from_value(result.result.unwrap()).unwrap();
        assert_eq!(response.agents.len(), 2);
        assert_eq!(response.agents[0].id, "ana");
        assert!(response.agents[0].active);
        assert_eq!(response.agents[0].model_provider, "minimax");
        assert_eq!(response.agents[0].bindings_count, 1);
        assert_eq!(response.agents[1].id, "bob");
        assert!(!response.agents[1].active);
    }

    #[test]
    fn agents_list_active_only_filters_inactive() {
        let yaml = MockYaml::with_fixture();
        let result = list(&*yaml, serde_json::json!({ "active_only": true }));
        let response: AgentsListResponse = serde_json::from_value(result.result.unwrap()).unwrap();
        assert_eq!(response.agents.len(), 1);
        assert_eq!(response.agents[0].id, "ana");
    }

    #[test]
    fn agents_list_plugin_filter_only_returns_matching_bindings() {
        let yaml = MockYaml::with_fixture();
        let result = list(&*yaml, serde_json::json!({ "plugin_filter": "whatsapp" }));
        let response: AgentsListResponse = serde_json::from_value(result.result.unwrap()).unwrap();
        assert_eq!(response.agents.len(), 1);
        assert_eq!(response.agents[0].id, "ana");
    }

    #[test]
    fn agents_get_returns_full_detail() {
        let yaml = MockYaml::with_fixture();
        let result = get(&*yaml, serde_json::json!({ "agent_id": "ana" }));
        let detail: AgentDetail = serde_json::from_value(result.result.unwrap()).unwrap();
        assert_eq!(detail.id, "ana");
        assert_eq!(detail.model.provider, "minimax");
        assert_eq!(detail.allowed_tools, vec!["*".to_string()]);
        assert_eq!(detail.inbound_bindings.len(), 1);
        assert_eq!(detail.inbound_bindings[0].plugin, "whatsapp");
        assert_eq!(detail.language.as_deref(), Some("es"));
    }

    #[test]
    fn agents_get_returns_not_found_for_unknown_id() {
        let yaml = MockYaml::with_fixture();
        let result = get(&*yaml, serde_json::json!({ "agent_id": "ghost" }));
        let err = result.error.expect("error");
        match err {
            AdminRpcError::Internal(m) => assert!(m.contains("not_found")),
            other => panic!("expected Internal/not_found, got {other:?}"),
        }
    }

    #[test]
    fn agents_upsert_writes_yaml_and_triggers_reload() {
        let yaml = MockYaml::with_fixture();
        let (count, reload) = reload_counter();
        let input = AgentUpsertInput {
            id: "ana".into(),
            model: ModelRef {
                provider: "minimax".into(),
                model: "MiniMax-M2.5".into(),
            },
            active: None,
            allowed_tools: None,
            inbound_bindings: None,
            system_prompt: None,
            language: Some("en".into()),
            transcripts_dir: None,
            workspace: None,
            extra_docs: None,
            heartbeat: None,
        };
        let result = upsert(&*yaml, serde_json::to_value(&input).unwrap(), &reload);
        let detail: AgentDetail = serde_json::from_value(result.result.unwrap()).unwrap();
        assert_eq!(detail.language.as_deref(), Some("en"));
        assert_eq!(count.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn agents_delete_removes_yaml_block_and_triggers_reload() {
        let yaml = MockYaml::with_fixture();
        let (count, reload) = reload_counter();
        let result = delete(&*yaml, serde_json::json!({ "agent_id": "bob" }), &reload);
        let response: AgentsDeleteResponse =
            serde_json::from_value(result.result.unwrap()).unwrap();
        assert!(response.removed);
        assert_eq!(count.load(Ordering::Relaxed), 1);

        let listed = list(&*yaml, Value::Null);
        let listed_response: AgentsListResponse =
            serde_json::from_value(listed.result.unwrap()).unwrap();
        assert_eq!(listed_response.agents.len(), 1);
        assert_eq!(listed_response.agents[0].id, "ana");
    }

    #[test]
    fn agents_delete_unknown_id_is_idempotent() {
        let yaml = MockYaml::with_fixture();
        let (count, reload) = reload_counter();
        let result = delete(&*yaml, serde_json::json!({ "agent_id": "ghost" }), &reload);
        let response: AgentsDeleteResponse =
            serde_json::from_value(result.result.unwrap()).unwrap();
        assert!(!response.removed);
        assert_eq!(count.load(Ordering::Relaxed), 0);
    }

    /// M15.18.d — agent without `heartbeat.*` fields surfaces
    /// `heartbeat: None` so the microapp shows the framework
    /// default (disabled, 5m).
    #[test]
    fn agents_get_returns_none_heartbeat_when_yaml_omits_block() {
        let yaml = MockYaml::with_fixture();
        let result = get(&*yaml, serde_json::json!({ "agent_id": "ana" }));
        let detail: AgentDetail = serde_json::from_value(result.result.unwrap()).unwrap();
        assert!(detail.heartbeat.is_none());
    }

    /// M15.18.d — upsert with `Some(HeartbeatWire { enabled: true,
    /// interval: "30m" })` writes both yaml fields and the next
    /// `get` returns them on the wire.
    #[test]
    fn agents_upsert_writes_heartbeat_block() {
        let yaml = MockYaml::with_fixture();
        let (_count, reload) = reload_counter();
        let input = AgentUpsertInput {
            id: "ana".into(),
            model: ModelRef {
                provider: "minimax".into(),
                model: "MiniMax-M2.5".into(),
            },
            active: None,
            allowed_tools: None,
            inbound_bindings: None,
            system_prompt: None,
            language: None,
            transcripts_dir: None,
            workspace: None,
            extra_docs: None,
            heartbeat: Some(HeartbeatWire {
                enabled: true,
                interval: "30m".into(),
            }),
        };
        let _ = upsert(&*yaml, serde_json::to_value(&input).unwrap(), &reload);
        let detail = read_detail(&*yaml, "ana").unwrap().unwrap();
        let hb = detail.heartbeat.expect("heartbeat persisted");
        assert!(hb.enabled);
        assert_eq!(hb.interval, "30m");
    }

    /// M15.18.d — empty-string interval is a no-op write so the
    /// daemon doesn't brick on next boot. The toggle still flips.
    #[test]
    fn agents_upsert_heartbeat_with_empty_interval_keeps_existing() {
        let yaml = MockYaml::with_fixture();
        // Seed an existing heartbeat block.
        yaml.set("ana", "heartbeat.enabled", Value::Bool(true));
        yaml.set("ana", "heartbeat.interval", Value::String("1h".into()));
        let (_count, reload) = reload_counter();
        let input = AgentUpsertInput {
            id: "ana".into(),
            model: ModelRef {
                provider: "minimax".into(),
                model: "MiniMax-M2.5".into(),
            },
            active: None,
            allowed_tools: None,
            inbound_bindings: None,
            system_prompt: None,
            language: None,
            transcripts_dir: None,
            workspace: None,
            extra_docs: None,
            heartbeat: Some(HeartbeatWire {
                enabled: false,
                interval: String::new(),
            }),
        };
        let _ = upsert(&*yaml, serde_json::to_value(&input).unwrap(), &reload);
        let detail = read_detail(&*yaml, "ana").unwrap().unwrap();
        let hb = detail.heartbeat.expect("heartbeat persisted");
        assert!(!hb.enabled);
        assert_eq!(hb.interval, "1h");
    }
}