zeph 0.22.3

Lightweight AI agent with hybrid inference, skills-first architecture, and multi-channel I/O
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! CLI handlers for `zeph serve`, `zeph stop`, and `zeph status`.
//!
//! These commands manage the scheduler daemon process. They are Unix-only
//! and require the `scheduler` feature.

#![cfg(all(unix, feature = "scheduler"))]

use anyhow::Context as _;

use crate::bootstrap::{load_config_or_default, resolve_config_path};

/// Handle `zeph serve [--foreground] [--no-catch-up]`.
///
/// Starts the scheduler daemon. Without `--foreground`, re-execs with
/// `--foreground` to detach without forking a live tokio runtime.
///
/// `vault_override`/`vault_key_override`/`vault_path_override` are the `--vault`/`--vault-key`/
/// `--vault-path` CLI flags. Resolved once via [`crate::bootstrap::resolve_vault_paths`] (the
/// same resolution `doctor.rs`/`vault.rs` use post-#6499) for the `--foreground` path, and
/// forwarded verbatim as CLI args to the re-exec'd child on the detach path — the child otherwise
/// falls back to `ZEPH_VAULT_*` env vars (inherited) or `default_vault_dir()`, silently ignoring
/// an operator-supplied override for the long-running daemon process (#6547/#6548).
pub(crate) async fn handle_serve(
    config_path: Option<&std::path::Path>,
    foreground: bool,
    catch_up: bool,
    vault_override: Option<&str>,
    vault_key_override: Option<&std::path::Path>,
    vault_path_override: Option<&std::path::Path>,
) -> anyhow::Result<()> {
    let config_file = resolve_config_path(config_path);
    let config = load_config_or_default(&config_file);
    let daemon_cfg = build_daemon_config(&config);

    if foreground {
        let (vault_key_path, vault_secrets_path) = crate::bootstrap::resolve_vault_paths(
            &config,
            vault_override,
            vault_key_override,
            vault_path_override,
        );
        run_foreground(daemon_cfg, &config, &vault_key_path, &vault_secrets_path).await
    } else {
        // Build args for the re-exec child. Pass --config so the child resolves
        // the same config file, then `serve --foreground` with catch-up flag.
        let config_str = config_file.to_string_lossy();
        let extra = build_detach_args(
            &config_str,
            catch_up,
            vault_override,
            vault_key_override,
            vault_path_override,
        );
        let extra_refs: Vec<&str> = extra.iter().map(String::as_str).collect();
        zeph_scheduler::detach_and_run(&daemon_cfg, &extra_refs)
            .context("failed to detach scheduler daemon")
    }
}

/// Build the CLI argument vector for the detached `--foreground` child process (the
/// non-foreground path of [`handle_serve`]).
///
/// Split out from `handle_serve` so the argument-construction logic — in particular, forwarding
/// `--vault`/`--vault-key`/`--vault-path` to the re-exec'd child — is independently testable
/// without actually spawning/detaching a process. The child otherwise only inherits `ZEPH_VAULT_*`
/// env vars automatically; the CLI-flag form of an override is lost across `std::process::Command`
/// unless explicitly forwarded here, silently dropping an operator-supplied override for the
/// long-running daemon process (#6547/#6548).
fn build_detach_args(
    config_str: &str,
    catch_up: bool,
    vault_override: Option<&str>,
    vault_key_override: Option<&std::path::Path>,
    vault_path_override: Option<&std::path::Path>,
) -> Vec<String> {
    let mut extra: Vec<String> = vec![
        "--config".to_owned(),
        config_str.to_owned(),
        "serve".to_owned(),
        "--foreground".to_owned(),
    ];
    if !catch_up {
        extra.push("--no-catch-up".to_owned());
    }
    if let Some(backend) = vault_override {
        extra.push("--vault".to_owned());
        extra.push(backend.to_owned());
    }
    if let Some(key_path) = vault_key_override {
        extra.push("--vault-key".to_owned());
        extra.push(key_path.to_string_lossy().into_owned());
    }
    if let Some(vault_path) = vault_path_override {
        extra.push("--vault-path".to_owned());
        extra.push(vault_path.to_string_lossy().into_owned());
    }
    extra
}

/// Handle `zeph stop [--timeout-secs N]`.
pub(crate) fn handle_stop(
    config_path: Option<&std::path::Path>,
    timeout_secs: u64,
) -> anyhow::Result<()> {
    let config_file = resolve_config_path(config_path);
    let config = load_config_or_default(&config_file);
    let daemon_cfg = build_daemon_config(&config);

    zeph_scheduler::stop_daemon(&daemon_cfg, timeout_secs)
        .context("failed to stop scheduler daemon")
}

/// Handle `zeph status [--json] [-n N]`.
pub(crate) async fn handle_status(
    config_path: Option<&std::path::Path>,
    json: bool,
    n: usize,
) -> anyhow::Result<()> {
    let config_file = resolve_config_path(config_path);
    let config = load_config_or_default(&config_file);
    let daemon_cfg = build_daemon_config(&config);
    let db_url = crate::db_url::resolve_db_url(&config);

    let status = zeph_scheduler::daemon_status(&daemon_cfg, db_url, n)
        .await
        .context("failed to read daemon status")?;

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&status).context("failed to serialize daemon status")?
        );
    } else {
        print_status_human(&status);
    }
    Ok(())
}

fn build_daemon_config(config: &zeph_core::config::Config) -> zeph_scheduler::DaemonConfig {
    let sched = &config.scheduler.daemon;
    zeph_scheduler::DaemonConfig {
        pid_file: std::path::PathBuf::from(&sched.pid_file),
        log_file: std::path::PathBuf::from(&sched.log_file),
        catch_up: sched.catch_up,
        tick_secs: sched.tick_secs,
        shutdown_grace_secs: sched.shutdown_grace_secs,
        handler_timeout_secs: sched.handler_timeout_secs,
    }
}

async fn run_foreground(
    daemon_cfg: zeph_scheduler::DaemonConfig,
    config: &zeph_core::config::Config,
    vault_key_path: &std::path::Path,
    vault_secrets_path: &std::path::Path,
) -> anyhow::Result<()> {
    let db_url = crate::db_url::resolve_db_url(config);
    let store = zeph_scheduler::JobStore::open(db_url)
        .await
        .context("failed to open scheduler store")?;
    store
        .init()
        .await
        .context("failed to init scheduler store")?;

    let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);

    let sched_cancel = tokio_util::sync::CancellationToken::new();
    let sched_supervisor = zeph_common::TaskSupervisor::new(sched_cancel.clone());

    // Gracefully shut down on SIGTERM/SIGINT.
    {
        let signal_fut = async move {
            use tokio::signal::unix::{SignalKind, signal};
            let mut sigterm =
                signal(SignalKind::terminate()).expect("failed to register SIGTERM handler");
            let mut sigint =
                signal(SignalKind::interrupt()).expect("failed to register SIGINT handler");
            tokio::select! {
                _ = sigterm.recv() => tracing::info!("received SIGTERM"),
                _ = sigint.recv() => tracing::info!("received SIGINT"),
            }
            let _ = shutdown_tx.send(true);
        };
        let cell = std::sync::Arc::new(parking_lot::Mutex::new(Some(signal_fut)));
        sched_supervisor.spawn(zeph_common::TaskDescriptor {
            name: "sched_daemon_signal",
            restart: zeph_common::RestartPolicy::RunOnce,
            factory: move || {
                let f = cell.lock().take();
                async move {
                    if let Some(f) = f {
                        f.await;
                    }
                }
            },
        });
    }

    let (mut scheduler, ctrl_tx) = zeph_scheduler::Scheduler::new(store, shutdown_rx);
    scheduler = scheduler.with_reentry_defense(
        config.scheduler.security.enabled,
        config.scheduler.security.injection_pattern_check,
        config.scheduler.security.attenuate_after_external_read,
    );

    if let Some(adapter) = build_durable_adapter(
        config,
        &sched_supervisor,
        vault_key_path,
        vault_secrets_path,
    )
    .await?
    {
        scheduler = scheduler.with_durable(adapter);
    }

    // Register built-in handlers available without a live agent session.
    // `UpdateCheckHandler` is self-contained (HTTP only); other handlers that
    // require the agent loop (CustomTaskHandler, ExperimentTaskHandler) are not
    // registered in daemon mode — their tasks will be skipped with a warning.
    if config.agent.auto_update_check {
        let (update_tx, _update_rx) = tokio::sync::mpsc::channel(4);
        let handler = zeph_scheduler::UpdateCheckHandler::new(env!("CARGO_PKG_VERSION"), update_tx);
        scheduler.register_handler(&zeph_scheduler::TaskKind::UpdateCheck, Box::new(handler));
    }

    // Load periodic/one-shot tasks declared in [scheduler.tasks].
    crate::scheduler::load_config_tasks(&config.scheduler.tasks, &ctrl_tx);

    let result = zeph_scheduler::run_foreground(scheduler, &daemon_cfg)
        .await
        .context("scheduler daemon exited with error");
    sched_cancel.cancel();
    sched_supervisor
        .shutdown_all(std::time::Duration::from_secs(5))
        .await;
    result
}

/// Open the scheduler's durable backend, attach the write-path AEAD cipher when
/// `[durable] encrypt_payload = true`, the control-entry HMAC key when this deployment is a
/// declared/detected shared database (INV-8), and the high-water-mark key unconditionally
/// (FR-009, addendum to #6451 — previously never attached on this channel at all), then spawn its
/// journal-writer task under `sched_supervisor`.
///
/// Returns `Ok(None)` when durable execution is disabled for the scheduler
/// (`[durable] enabled = false` or `[durable] scheduler = false`), so the caller runs without
/// durable execution unchanged.
///
/// # Errors
///
/// Returns an error if the durable backend cannot be opened or initialized, if the AEAD cipher
/// cannot be resolved when `encrypt_payload = true`, or if the control-entry HMAC key cannot be
/// resolved for a shared database — every case fails closed instead of silently running with a
/// weaker security posture.
async fn build_durable_adapter(
    config: &zeph_core::config::Config,
    sched_supervisor: &zeph_common::TaskSupervisor,
    vault_key_path: &std::path::Path,
    vault_secrets_path: &std::path::Path,
) -> anyhow::Result<Option<zeph_scheduler::durable::SchedulerDurableAdapter>> {
    if !(config.durable.enabled && config.durable.scheduler) {
        return Ok(None);
    }
    // Resolve the write-path cipher (which evaluates the INV-8 encryption_gate, #5996), the
    // control-entry HMAC key (#6043/#6044), and the high-water-mark key (addendum to #6451)
    // before opening the backend, so a forbidden config fails closed without creating a stray
    // empty journal file on disk first.
    let cipher =
        crate::commands::durable::load_write_cipher(config, vault_key_path, vault_secrets_path)?;
    let hmac_keys =
        crate::commands::durable::load_write_hmac_key(config, vault_key_path, vault_secrets_path)?;
    let hwm_keys =
        crate::commands::durable::load_write_hwm_key(config, vault_key_path, vault_secrets_path)?;
    let durable_url = crate::commands::durable::resolve_durable_db_url(config);
    let local = zeph_durable::LocalBackend::open(&durable_url, config.durable.max_payload_bytes)
        .await
        .context("failed to open scheduler durable backend")?;
    local
        .init()
        .await
        .context("failed to init scheduler durable schema")?;
    let local = if let Some(cipher) = cipher {
        local.with_cipher(cipher)
    } else {
        local
    };
    let local = if let Some(key) = hmac_keys.current {
        local.with_hmac_key(key)
    } else {
        local
    };
    let local = if let Some(key) = hmac_keys.previous {
        local.with_previous_hmac_key(key)
    } else {
        local
    };
    let local = if let Some(slot) = hwm_keys.current {
        local.with_hwm_key(slot.epoch, slot.key)
    } else {
        local
    };
    let local = if let Some(slot) = hwm_keys.previous {
        local.with_previous_hwm_key(slot.epoch, slot.key)
    } else {
        local
    };
    let local = std::sync::Arc::new(local);
    let backend = std::sync::Arc::new(zeph_durable::DurableBackendEnum::Local(local.clone()));
    let durable_cfg = std::sync::Arc::new(config.durable.clone());
    let (writer_actor, writer_handle) = zeph_durable::JournalWriter::new(local, &durable_cfg);
    {
        let writer_fut = writer_actor.run();
        let cell = std::sync::Arc::new(parking_lot::Mutex::new(Some(writer_fut)));
        sched_supervisor.spawn(zeph_common::TaskDescriptor {
            name: "journal_writer",
            restart: zeph_common::RestartPolicy::RunOnce,
            factory: move || {
                let f = cell.lock().take();
                async move {
                    if let Some(f) = f {
                        f.await;
                    }
                }
            },
        });
    }
    {
        let retention_backend = std::sync::Arc::clone(&backend);
        let retention_policy = durable_cfg.retention.clone();
        sched_supervisor.spawn(zeph_common::TaskDescriptor {
            name: "durable.retention_sweep",
            restart: zeph_common::RestartPolicy::Restart {
                max: 5,
                base_delay: std::time::Duration::from_secs(5),
            },
            factory: move || {
                zeph_durable::DurableRetentionService::new(
                    std::sync::Arc::clone(&retention_backend),
                    retention_policy.clone(),
                )
                .run()
            },
        });
    }
    Ok(Some(zeph_scheduler::durable::SchedulerDurableAdapter::new(
        backend,
        writer_handle,
        durable_cfg,
    )))
}

fn print_status_human(status: &zeph_scheduler::DaemonStatus) {
    let running = if status.running {
        "running"
    } else {
        "not running"
    };
    let pid_str = status
        .pid
        .map(|p| format!(" (pid {p})"))
        .unwrap_or_default();

    println!("daemon:    {running}{pid_str}");
    println!("pid_file:  {}", status.pid_file.display());
    println!("log_file:  {}", status.log_file.display());
    println!("tasks:     {}", status.task_count);

    if !status.recent_runs.is_empty() {
        println!("last runs:");
        for run in &status.recent_runs {
            let last_run = if run.last_run.is_empty() {
                "never"
            } else {
                run.last_run.as_str()
            };
            println!(
                "  {:<24} last: {:<25} next: {}",
                run.name, last_run, run.next_run
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use zeph_durable::Journal as _;

    // --- build_detach_args (#6547/#6548, tester follow-up) ---
    //
    // `handle_serve`'s non-foreground path re-execs itself as a detached `--foreground` child;
    // these tests isolate the argv-construction logic without actually spawning/detaching a
    // process, covering the exact gap the tester flagged: zero coverage existed for whether
    // `--vault`/`--vault-key`/`--vault-path` actually reach the re-exec'd child's argv.

    #[test]
    fn build_detach_args_forwards_all_three_vault_overrides_when_present() {
        let args = build_detach_args(
            "/some/config.toml",
            true,
            Some("age"),
            Some(std::path::Path::new("/override/vault-key.txt")),
            Some(std::path::Path::new("/override/secrets.age")),
        );
        assert!(args.iter().any(|a| a == "--vault"));
        assert!(args.iter().any(|a| a == "age"));
        assert!(args.iter().any(|a| a == "--vault-key"));
        assert!(args.iter().any(|a| a == "/override/vault-key.txt"));
        assert!(args.iter().any(|a| a == "--vault-path"));
        assert!(args.iter().any(|a| a == "/override/secrets.age"));
        // --vault-key must be immediately followed by its value (argv parsing depends on
        // adjacency), not just present anywhere in the vector.
        let key_idx = args.iter().position(|a| a == "--vault-key").unwrap();
        assert_eq!(args[key_idx + 1], "/override/vault-key.txt");
        let path_idx = args.iter().position(|a| a == "--vault-path").unwrap();
        assert_eq!(args[path_idx + 1], "/override/secrets.age");
    }

    #[test]
    fn build_detach_args_omits_vault_flags_when_no_override_given() {
        let args = build_detach_args("/some/config.toml", true, None, None, None);
        assert!(
            !args.iter().any(|a| a == "--vault"),
            "no --vault override must not appear in the child argv: {args:?}"
        );
        assert!(
            !args.iter().any(|a| a == "--vault-key"),
            "no --vault-key override must not appear in the child argv: {args:?}"
        );
        assert!(
            !args.iter().any(|a| a == "--vault-path"),
            "no --vault-path override must not appear in the child argv: {args:?}"
        );
    }

    #[test]
    fn build_detach_args_forwards_single_override_independently() {
        // --vault-key alone must not pull in --vault-path (and vice versa) — each override is
        // forwarded independently, mirroring resolve_vault_paths' per-field resolution.
        let args = build_detach_args(
            "/some/config.toml",
            true,
            None,
            Some(std::path::Path::new("/override/vault-key.txt")),
            None,
        );
        assert!(args.iter().any(|a| a == "--vault-key"));
        assert!(!args.iter().any(|a| a == "--vault-path"));
        assert!(!args.iter().any(|a| a == "--vault"));
    }

    #[test]
    fn build_detach_args_always_includes_config_and_foreground() {
        let args = build_detach_args("/x/config.toml", true, None, None, None);
        assert_eq!(args[0], "--config");
        assert_eq!(args[1], "/x/config.toml");
        assert!(args.iter().any(|a| a == "serve"));
        assert!(args.iter().any(|a| a == "--foreground"));
    }

    #[test]
    fn build_detach_args_no_catch_up_flag_added_when_catch_up_false() {
        let with_catch_up = build_detach_args("/x/config.toml", true, None, None, None);
        assert!(!with_catch_up.iter().any(|a| a == "--no-catch-up"));

        let without_catch_up = build_detach_args("/x/config.toml", false, None, None, None);
        assert!(without_catch_up.iter().any(|a| a == "--no-catch-up"));
    }

    /// #6264: `build_durable_adapter` must spawn the retention sweep (not just the journal
    /// writer) onto `sched_supervisor`, mirroring the P1/P2 coverage in
    /// `crates/zeph-core/src/agent/durable_bootstrap.rs`. `encrypt_payload = false` avoids a
    /// real vault dependency in this test, same pattern as
    /// `open_backend_reveal_succeeds_without_key_when_encrypt_payload_disabled` in
    /// `src/commands/durable.rs`.
    #[tokio::test]
    async fn spawns_retention_sweep_alongside_journal_writer() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = zeph_core::config::Config::default();
        config.memory.sqlite_path = dir.path().join("zeph.db").to_string_lossy().into_owned();
        config.durable.enabled = true;
        config.durable.scheduler = true;
        config.durable.encrypt_payload = false;

        let cancel = tokio_util::sync::CancellationToken::new();
        let sched_supervisor = zeph_common::TaskSupervisor::new(cancel);

        let vault_dir = zeph_core::vault::default_vault_dir();
        let adapter = build_durable_adapter(
            &config,
            &sched_supervisor,
            &vault_dir.join("vault-key.txt"),
            &vault_dir.join("secrets.age"),
        )
        .await
        .expect("build_durable_adapter must succeed with a local, unencrypted backend");
        assert!(
            adapter.is_some(),
            "durable.enabled && durable.scheduler must produce an adapter"
        );

        let names: Vec<String> = sched_supervisor
            .snapshot()
            .iter()
            .map(|s| s.name.to_string())
            .collect();
        assert!(
            names.contains(&"journal_writer".to_owned()),
            "expected journal_writer among supervised tasks, got {names:?}"
        );
        assert!(
            names.contains(&"durable.retention_sweep".to_owned()),
            "expected durable.retention_sweep among supervised tasks, got {names:?}"
        );
    }

    /// The retention sweep must not spawn at all when the P3 adapter itself is disabled — it
    /// rides the same `durable.enabled && durable.scheduler` gate as backend construction.
    #[tokio::test]
    async fn does_not_spawn_when_scheduler_adapter_disabled() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = zeph_core::config::Config::default();
        config.memory.sqlite_path = dir.path().join("zeph.db").to_string_lossy().into_owned();
        config.durable.enabled = true;
        config.durable.scheduler = false;

        let cancel = tokio_util::sync::CancellationToken::new();
        let sched_supervisor = zeph_common::TaskSupervisor::new(cancel);

        let vault_dir = zeph_core::vault::default_vault_dir();
        let adapter = build_durable_adapter(
            &config,
            &sched_supervisor,
            &vault_dir.join("vault-key.txt"),
            &vault_dir.join("secrets.age"),
        )
        .await
        .expect("build_durable_adapter must succeed (returns None, not an error)");
        assert!(adapter.is_none());
        assert!(sched_supervisor.snapshot().is_empty());
    }

    /// #6451 regression (critic finding 2): the scheduler-daemon read channel is one of the three
    /// runtime paths that must stay able to verify a pre-rotation `EffectIntent` control entry
    /// through an open rotation window. `build_durable_adapter` resolves both HMAC keys via
    /// `load_write_hmac_key` and attaches them (lines above, `hmac_keys.current` /
    /// `hmac_keys.previous`) exactly like this test's own re-derivation, so asserting both that
    /// adapter construction succeeds and that a backend opened with the same resolved keys can
    /// read a payload-less control entry stamped under the previous key is a faithful regression
    /// for this channel's wiring — including the crash-orphan shape (`EffectIntent` never carries
    /// a payload, so the AEAD blob-scan alone could never have caught a missed wiring here).
    #[allow(unsafe_code)]
    #[tokio::test]
    #[serial_test::serial]
    async fn scheduler_daemon_reads_previous_key_control_entry_through_rotation_window() {
        let vault_dir = tempfile::tempdir().unwrap();
        let prev_xdg = std::env::var("XDG_CONFIG_HOME").ok();
        unsafe {
            std::env::set_var("XDG_CONFIG_HOME", vault_dir.path());
        }

        let vault_root = zeph_core::vault::default_vault_dir();
        zeph_core::vault::AgeVaultProvider::init_vault(&vault_root).unwrap();
        let mut provider = zeph_core::vault::AgeVaultProvider::load(
            &vault_root.join("vault-key.txt"),
            &vault_root.join("secrets.age"),
        )
        .unwrap();
        let old_key_b64 = zeph_core::durable::generate_durable_key_b64();
        let new_key_b64 = zeph_core::durable::generate_durable_key_b64();
        provider
            .set_secret_mut(
                "ZEPH_DURABLE_KEY_PREVIOUS".to_owned(),
                old_key_b64.clone(),
                false,
            )
            .unwrap();
        provider
            .set_secret_mut("ZEPH_DURABLE_KEY".to_owned(), new_key_b64, false)
            .unwrap();
        provider.save().unwrap();

        let dir = tempfile::tempdir().unwrap();
        let mut config = zeph_core::config::Config::default();
        config.memory.sqlite_path = dir.path().join("zeph.db").to_string_lossy().into_owned();
        config.durable.enabled = true;
        config.durable.scheduler = true;
        config.durable.shared_db = true;
        config.durable.key_id = 1;
        config.durable.previous_key_id = Some(0);

        // Simulate a pre-rotation control entry: write it directly under the old (now-previous)
        // HMAC key, before the daemon ever opens the backend.
        let old_hmac_key = zeph_core::durable::derive_control_hmac_key_b64(&old_key_b64).unwrap();
        let durable_url = crate::commands::durable::resolve_durable_db_url(&config);
        let exec = zeph_durable::ExecutionId::new();
        {
            let pre_rotation_writer =
                zeph_durable::LocalBackend::open(&durable_url, config.durable.max_payload_bytes)
                    .await
                    .unwrap()
                    .with_hmac_key(old_hmac_key);
            pre_rotation_writer.init().await.unwrap();
            pre_rotation_writer
                .open_execution(exec, zeph_durable::ExecutionKind::AgentTurn)
                .await
                .unwrap();
            let step_id = zeph_durable::StepId::new(0);
            pre_rotation_writer
                .append(zeph_durable::JournalEntry {
                    seq: None,
                    execution_id: exec,
                    kind: zeph_durable::ExecutionKind::AgentTurn,
                    step_id,
                    entry: zeph_durable::EntryKind::EffectIntent {
                        idempotency_key: zeph_durable::IdempotencyKey::derive(
                            exec,
                            step_id,
                            b"transfer",
                        ),
                        effect: zeph_durable::EffectClass::ExactlyOnceGuarded,
                        hmac: None,
                    },
                    created_at_ms: 0,
                })
                .await
                .unwrap();
        }

        let cancel = tokio_util::sync::CancellationToken::new();
        let sched_supervisor = zeph_common::TaskSupervisor::new(cancel);
        let adapter = build_durable_adapter(
            &config,
            &sched_supervisor,
            &vault_root.join("vault-key.txt"),
            &vault_root.join("secrets.age"),
        )
        .await;
        assert!(
            adapter.is_ok() && adapter.unwrap().is_some(),
            "build_durable_adapter must succeed with a consistent rotation window declared"
        );

        // Re-derive the same keys `build_durable_adapter` resolved, and confirm the pre-rotation
        // entry is still readable through the window (the actual regression assertion) — still
        // under the guard's vault dir, before it is restored below.
        let hmac_keys = crate::commands::durable::load_write_hmac_key(
            &config,
            &vault_root.join("vault-key.txt"),
            &vault_root.join("secrets.age"),
        )
        .unwrap();
        let reader =
            zeph_durable::LocalBackend::open(&durable_url, config.durable.max_payload_bytes)
                .await
                .unwrap()
                .with_hmac_key(hmac_keys.current.unwrap())
                .with_previous_hmac_key(hmac_keys.previous.unwrap());
        let read_result = reader.read_execution(exec).await;

        unsafe {
            match &prev_xdg {
                Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
                None => std::env::remove_var("XDG_CONFIG_HOME"),
            }
        }

        assert!(
            read_result.is_ok(),
            "the scheduler-daemon read channel must verify a pre-rotation EffectIntent control \
             entry through the rotation window"
        );
    }

    /// Addendum to #6451 (tester-2 finding): mirrors
    /// `scheduler_daemon_reads_previous_key_control_entry_through_rotation_window` above, but for
    /// the high-water-mark path instead of the control-HMAC path. `build_durable_adapter`
    /// previously never attached an HWM key at all on this channel (confirmed absent before this
    /// addendum — unlike the control-HMAC key, the HWM key is meant to be attached
    /// unconditionally per FR-009, so this test does not need `shared_db = true`), so this proves
    /// both that it now attaches the current epoch unconditionally and the previous epoch while
    /// the window is open, by resuming a pre-rotation execution with a committed `StepResult`
    /// through the daemon's own resolved keys.
    #[allow(unsafe_code)]
    #[tokio::test]
    #[serial_test::serial]
    async fn scheduler_daemon_resumes_previous_epoch_high_water_mark_through_rotation_window() {
        let vault_dir = tempfile::tempdir().unwrap();
        let prev_xdg = std::env::var("XDG_CONFIG_HOME").ok();
        unsafe {
            std::env::set_var("XDG_CONFIG_HOME", vault_dir.path());
        }

        let vault_root = zeph_core::vault::default_vault_dir();
        zeph_core::vault::AgeVaultProvider::init_vault(&vault_root).unwrap();
        let mut provider = zeph_core::vault::AgeVaultProvider::load(
            &vault_root.join("vault-key.txt"),
            &vault_root.join("secrets.age"),
        )
        .unwrap();
        let old_key_b64 = zeph_core::durable::generate_durable_key_b64();
        let new_key_b64 = zeph_core::durable::generate_durable_key_b64();
        provider
            .set_secret_mut(
                "ZEPH_DURABLE_KEY_PREVIOUS".to_owned(),
                old_key_b64.clone(),
                false,
            )
            .unwrap();
        provider
            .set_secret_mut("ZEPH_DURABLE_KEY".to_owned(), new_key_b64, false)
            .unwrap();
        provider.save().unwrap();

        let dir = tempfile::tempdir().unwrap();
        let mut config = zeph_core::config::Config::default();
        config.memory.sqlite_path = dir.path().join("zeph.db").to_string_lossy().into_owned();
        config.durable.enabled = true;
        config.durable.scheduler = true;
        config.durable.key_id = 1;
        config.durable.previous_key_id = Some(0);

        // Commit a StepResult under the OLD (now-previous) HWM key, before the daemon ever opens
        // the backend -- simulating an execution that committed a result pre-rotation.
        let old_hwm_key = zeph_core::durable::derive_hwm_key_b64(&old_key_b64).unwrap();
        let durable_url = crate::commands::durable::resolve_durable_db_url(&config);
        let exec = zeph_durable::ExecutionId::new();
        {
            let pre_rotation_writer =
                zeph_durable::LocalBackend::open(&durable_url, config.durable.max_payload_bytes)
                    .await
                    .unwrap()
                    .with_hwm_key(0, old_hwm_key);
            pre_rotation_writer.init().await.unwrap();
            pre_rotation_writer
                .open_execution(exec, zeph_durable::ExecutionKind::AgentTurn)
                .await
                .unwrap();
            let step_id = zeph_durable::StepId::new(0);
            pre_rotation_writer
                .append(zeph_durable::JournalEntry {
                    seq: None,
                    execution_id: exec,
                    kind: zeph_durable::ExecutionKind::AgentTurn,
                    step_id,
                    entry: zeph_durable::EntryKind::StepResult {
                        idempotency_key: zeph_durable::IdempotencyKey::derive(
                            exec,
                            step_id,
                            b"tool:test",
                        ),
                        payload: bytes::Bytes::copy_from_slice(b"pre-rotation result"),
                        effect: zeph_durable::EffectClass::Idempotent,
                        payload_version: 1,
                    },
                    created_at_ms: 0,
                })
                .await
                .unwrap();
        }

        let cancel = tokio_util::sync::CancellationToken::new();
        let sched_supervisor = zeph_common::TaskSupervisor::new(cancel);
        let adapter = build_durable_adapter(
            &config,
            &sched_supervisor,
            &vault_root.join("vault-key.txt"),
            &vault_root.join("secrets.age"),
        )
        .await;
        assert!(
            adapter.is_ok() && adapter.unwrap().is_some(),
            "build_durable_adapter must succeed with a consistent rotation window declared"
        );

        // Re-derive the same HWM keys `build_durable_adapter` resolved, and confirm the
        // pre-rotation execution still resumes cleanly through the window (the actual regression
        // assertion) -- still under the guard's vault dir, before it is restored below.
        let hwm_keys = crate::commands::durable::load_write_hwm_key(
            &config,
            &vault_root.join("vault-key.txt"),
            &vault_root.join("secrets.age"),
        )
        .unwrap();
        let current = hwm_keys.current.expect("current HWM slot must resolve");
        let previous = hwm_keys
            .previous
            .expect("previous HWM slot must resolve while the window is open");
        let reader =
            zeph_durable::LocalBackend::open(&durable_url, config.durable.max_payload_bytes)
                .await
                .unwrap()
                .with_hwm_key(current.epoch, current.key)
                .with_previous_hwm_key(previous.epoch, previous.key);
        let resume_result = reader
            .open_execution(exec, zeph_durable::ExecutionKind::AgentTurn)
            .await;

        unsafe {
            match &prev_xdg {
                Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
                None => std::env::remove_var("XDG_CONFIG_HOME"),
            }
        }

        assert!(
            resume_result.is_ok(),
            "the scheduler-daemon read channel must resume a pre-rotation execution's \
             high-water-mark through the rotation window: {resume_result:?}"
        );
    }
}