mlua-swarm-server 0.16.0

HTTP + WebSocket server for mlua-swarm (task API, Blueprint store, Operator WS sessions).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! Server config file support (`~/.mse/config.toml` by default).
//!
//! Resolution precedence: **CLI flag > config file > built-in default**.
//! CLI flags are represented as `Option<T>` on the `main.rs` `Args` struct
//! (rather than relying on `clap`'s `default_value`) so "not passed" can be
//! distinguished from "matches the default value"; [`resolve`] performs the
//! actual 3-way merge.
//!
//! Design rationale: the config file becomes the lifecycle SoT; the launchd
//! plist's `ProgramArguments` stays fixed at `<server-bin> --config <path>`,
//! so changing settings = editing the file + restarting, not editing the plist.

use mlua_swarm::core::config::CheckPolicy;
use mlua_swarm::LegacyWorkerBindingPolicy;
use serde::Deserialize;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};

/// Default config path, `~/.mse/config.toml`. Falls back to a relative path
/// literal when `$HOME` is unset (best-effort; dev-only edge case).
pub fn default_config_path() -> PathBuf {
    match std::env::var("HOME") {
        Ok(home) => PathBuf::from(home).join(".mse").join("config.toml"),
        Err(_) => PathBuf::from(".mse/config.toml"),
    }
}

/// Default `BlueprintStore` root, `~/.mse/store`. Same `$HOME` fallback
/// rule as [`default_config_path`]. The store is always git-backed;
/// config/CLI only override *where* the repos live, never whether they
/// persist.
pub fn default_store_path() -> PathBuf {
    match std::env::var("HOME") {
        Ok(home) => PathBuf::from(home).join(".mse").join("store"),
        Err(_) => PathBuf::from(".mse/store"),
    }
}

/// Default `TaskStore` SQLite path, `~/.mse/store/task.sqlite` (issue
/// #35 ST1 — persist-by-default). Same `$HOME` fallback as
/// [`default_config_path`].
pub fn default_task_store_path() -> PathBuf {
    match std::env::var("HOME") {
        Ok(home) => PathBuf::from(home)
            .join(".mse")
            .join("store")
            .join("task.sqlite"),
        Err(_) => PathBuf::from(".mse/store/task.sqlite"),
    }
}

/// Default `RunStore` SQLite path, `~/.mse/store/run.sqlite`. Sibling of
/// [`default_task_store_path`].
pub fn default_run_store_path() -> PathBuf {
    match std::env::var("HOME") {
        Ok(home) => PathBuf::from(home)
            .join(".mse")
            .join("store")
            .join("run.sqlite"),
        Err(_) => PathBuf::from(".mse/store/run.sqlite"),
    }
}

/// Default `ReplayStore` SQLite path, `~/.mse/store/replay.sqlite`. Sibling
/// of [`default_run_store_path`] — persisted by default so a restart can
/// consult the replay log (see `mlua_swarm::store::replay` module doc).
pub fn default_replay_store_path() -> PathBuf {
    match std::env::var("HOME") {
        Ok(home) => PathBuf::from(home)
            .join(".mse")
            .join("store")
            .join("replay.sqlite"),
        Err(_) => PathBuf::from(".mse/store/replay.sqlite"),
    }
}

/// TOML config schema. All fields are optional — a missing field falls back
/// to the CLI-supplied value or the built-in default at [`resolve`] time.
/// Unknown fields are a hard error (`deny_unknown_fields`; typo guard).
#[derive(Debug, Default, Clone, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileConfig {
    /// Listen address string (e.g. `"127.0.0.1:7777"`), parsed at [`resolve`] time.
    pub bind: Option<String>,
    /// Whether the enhance flow (Lua + AgentBlock factories) is baked into the registry.
    pub enable_enhance_flow: Option<bool>,
    /// Migration gate for deprecated `profile.worker_binding` Runner fallback.
    pub legacy_worker_binding_policy: Option<LegacyWorkerBindingPolicy>,
    /// Base dir for `$file` / `$agent_md` ref expansion in seeded Blueprints.
    pub blueprint_ref_base: Option<PathBuf>,
    /// Additional dirs (tier 5 of the include cascade — see
    /// `mlua-swarm-compile::ResolveConfig`) searched after the CLI
    /// `--include` list and before the bundled default. `None` = no
    /// server-config includes.
    pub blueprint_ref_includes: Option<Vec<PathBuf>>,
    /// Server-side strict-embed switch (design table row 3 — the
    /// strict opt-in for the register layer). When `true`, `POST
    /// /v1/blueprints/:id` refuses any raw body that still carries
    /// `$file` / `$agent_md` refs (returns 400 with a hint pointing at
    /// `mse bp build --strict-embed`), so ref resolution is pushed onto
    /// the client. Default `false` = the server runs the linker itself
    /// (backward-compat). `None` = fall back to the built-in default
    /// `false`.
    pub blueprint_strict_embed: Option<bool>,
    /// Root path for the git-backed `BlueprintStore` (when using the git2 backend).
    pub git_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `IssueStore`. `None` = fall
    /// back to `InMemoryIssueStore` (process-volatile).
    pub issue_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `EnhanceSettingStore`.
    /// `None` = fall back to `InMemoryEnhanceSettingStore` (process-volatile).
    pub enhance_setting_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `EnhanceLogStore`.
    /// `None` = fall back to `InMemoryEnhanceLogStore` (process-volatile).
    pub enhance_log_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `OutputStore`.
    /// `None` = fall back to `InMemoryOutputStore` (process-volatile).
    pub output_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `TaskStore` (issue #13
    /// ID-hierarchy `POST /v1/tasks` work-item records). `None` = fall back
    /// to `InMemoryTaskStore` (process-volatile).
    pub task_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `RunStore` (one kick of
    /// a Task). `None` = fall back to `InMemoryRunStore` (process-volatile).
    pub run_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `ReplayStore` (per-run
    /// Ctx-snapshot + step-output log). Persisted by default even when
    /// omitted (sibling of `run_store_path`): resolves to
    /// `~/.mse/store/replay.sqlite` unless `ephemeral` is set. `None` = fall
    /// back to `InMemoryReplayStore` (process-volatile).
    pub replay_store_path: Option<PathBuf>,
    /// Opt-out flag: when `true`, restores the InMemory default for
    /// `task_store_path`/`run_store_path` even though the built-in default
    /// (issue #35 ST1) is now to persist. Has no effect when an explicit
    /// `task_store_path`/`run_store_path` (CLI or file) is set — explicit
    /// paths always win. `None` = fall back to `false`.
    pub ephemeral: Option<bool>,
    /// Seed blueprint id used in combined-mode default routing.
    pub seed_blueprint_id: Option<String>,
    /// snake_case `AgentKind` literal (`operator` / `agent_block` / `rust_fn` /
    /// `lua` / `subprocess`). Validated by the caller after [`resolve`].
    pub default_agent_kind: Option<String>,
    /// Shared secret used to verify/sign `CapToken` HMAC signatures.
    pub token_secret: Option<String>,
    /// Ceiling (seconds) for the `POST /v1/tasks` synchronous launch await
    /// (GH #33 Guard 2). Overridable per-request via `TaskLaunchRequest
    /// .timeout_secs`; this is the server-wide fallback when the request
    /// omits it. `None` = fall back to the built-in default (3600s / 60 min, see
    /// [`ResolvedConfig`]'s `Default` impl).
    pub sync_timeout_secs: Option<u64>,
    /// Server-wide [`mlua_swarm::core::config::CheckPolicy`] — governs how
    /// submit-time projection sinks
    /// (`Engine::materialize_final_submission` /
    /// `Engine::materialize_artifact_submission`) react to fail-open
    /// conditions (missing `work_dir`/`project_root`, `OutputStore` write
    /// error, adapter materialize error, state lookup error). `None`
    /// falls back to the built-in default `Warn` (byte-identical to
    /// pre-`CheckPolicy` behaviour); `"silent"` skips both the log and
    /// error, `"strict"` returns
    /// `EngineError::CheckPolicyStrict` so a caller who has opted in can
    /// fail the step / launch fast. Per-task override
    /// (`TaskSpec.check_policy`) wins over this server-wide value.
    pub check_policy: Option<CheckPolicy>,
}

/// CLI-side overrides. Mirrors [`FileConfig`] field-for-field. Kept as a
/// separate type (rather than reusing `clap::Args` directly) so this module
/// stays independent of the `clap` derive on `main.rs::Args`.
#[derive(Debug, Default, Clone)]
pub struct CliOverrides {
    /// `--bind` value, unparsed (mirrors [`FileConfig::bind`]).
    pub bind: Option<String>,
    /// `--enable-enhance-flow` flag.
    pub enable_enhance_flow: Option<bool>,
    /// `--legacy-worker-binding-policy` value.
    pub legacy_worker_binding_policy: Option<LegacyWorkerBindingPolicy>,
    /// `--blueprint-ref-base` value.
    pub blueprint_ref_base: Option<PathBuf>,
    /// `--include` values (repeatable). Merged with the file config's
    /// `blueprint_ref_includes` (CLI wins on conflict — see [`resolve`]).
    pub blueprint_ref_includes: Vec<PathBuf>,
    /// `--blueprint-strict-embed` flag (mirrors
    /// [`FileConfig::blueprint_strict_embed`]).
    pub blueprint_strict_embed: Option<bool>,
    /// `--git-store-path` value.
    pub git_store_path: Option<PathBuf>,
    /// `--issue-store-path` value (mirrors [`FileConfig::issue_store_path`]).
    pub issue_store_path: Option<PathBuf>,
    /// `--enhance-setting-store-path` value.
    pub enhance_setting_store_path: Option<PathBuf>,
    /// `--enhance-log-store-path` value.
    pub enhance_log_store_path: Option<PathBuf>,
    /// `--output-store-path` value.
    pub output_store_path: Option<PathBuf>,
    /// `--task-store-path` value (mirrors [`FileConfig::task_store_path`]).
    pub task_store_path: Option<PathBuf>,
    /// `--run-store-path` value (mirrors [`FileConfig::run_store_path`]).
    pub run_store_path: Option<PathBuf>,
    /// `--replay-store-path` value (mirrors [`FileConfig::replay_store_path`]).
    pub replay_store_path: Option<PathBuf>,
    /// `--ephemeral` flag (mirrors [`FileConfig::ephemeral`]).
    pub ephemeral: Option<bool>,
    /// `--seed-blueprint-id` value.
    pub seed_blueprint_id: Option<String>,
    /// `--default-agent-kind` value (snake_case `AgentKind` literal, unvalidated).
    pub default_agent_kind: Option<String>,
    /// `--token-secret` value.
    pub token_secret: Option<String>,
    /// `--sync-timeout-secs` value (mirrors [`FileConfig::sync_timeout_secs`]).
    pub sync_timeout_secs: Option<u64>,
    /// `--check-policy` value (mirrors [`FileConfig::check_policy`]).
    /// Parsed at the caller (`serve.rs`) before landing here — invalid
    /// tokens are rejected before this struct is ever constructed.
    pub check_policy: Option<CheckPolicy>,
}

/// Fully resolved config — every field has the built-in default applied.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedConfig {
    /// Parsed listen address for the server to bind to.
    pub bind: SocketAddr,
    /// Whether the enhance flow (Lua + AgentBlock factories) is baked into the registry.
    pub enable_enhance_flow: bool,
    /// Migration gate for fresh Blueprint declarations.
    pub legacy_worker_binding_policy: LegacyWorkerBindingPolicy,
    /// Base dir for `$file` / `$agent_md` ref expansion in seeded Blueprints.
    pub blueprint_ref_base: Option<PathBuf>,
    /// Merged include list (CLI `--include` first, then file
    /// `blueprint_ref_includes`) — tier 4+5 of the include cascade.
    /// Always set (may be empty).
    pub blueprint_ref_includes: Vec<PathBuf>,
    /// Server-side strict-embed switch (design table row 3). Always
    /// set — defaults to `false` when neither CLI nor config file
    /// provides one (backward-compat: the server runs the linker
    /// itself). When `true`, `POST /v1/blueprints/:id` refuses raw
    /// bodies that still carry `$file` / `$agent_md` refs.
    pub blueprint_strict_embed: bool,
    /// Root path for the git-backed `BlueprintStore`. Always set — defaults
    /// to [`default_store_path`] (`~/.mse/store`) when neither CLI nor config
    /// file provides one.
    pub git_store_path: PathBuf,
    /// Path to the SQLite database file backing the `IssueStore`. `None` = fall
    /// back to `InMemoryIssueStore` (process-volatile).
    pub issue_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `EnhanceSettingStore`.
    /// `None` = `InMemoryEnhanceSettingStore`.
    pub enhance_setting_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `EnhanceLogStore`.
    /// `None` = `InMemoryEnhanceLogStore`.
    pub enhance_log_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `OutputStore`.
    /// `None` = `InMemoryOutputStore`.
    pub output_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `TaskStore`.
    /// `None` = `InMemoryTaskStore`.
    pub task_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `RunStore`.
    /// `None` = `InMemoryRunStore`.
    pub run_store_path: Option<PathBuf>,
    /// Path to the SQLite database file backing the `ReplayStore`.
    /// `None` = `InMemoryReplayStore`.
    pub replay_store_path: Option<PathBuf>,
    /// Seed blueprint id used in combined-mode default routing.
    pub seed_blueprint_id: String,
    /// snake_case `AgentKind` literal, unvalidated. `None` = caller applies
    /// the schema-impl `Default` (`Operator`).
    pub default_agent_kind: Option<String>,
    /// Shared secret used to verify/sign `CapToken` HMAC signatures.
    pub token_secret: Option<String>,
    /// Ceiling (seconds) for the `POST /v1/tasks` synchronous launch await
    /// (GH #33 Guard 2). Always set — defaults to 3600s / 60 min (see
    /// [`default_sync_timeout_secs`]) when neither CLI nor config file
    /// provides one. A per-request `TaskLaunchRequest.timeout_secs`
    /// override, when present, takes priority over this server-wide value.
    pub sync_timeout_secs: u64,
    /// Server-wide [`mlua_swarm::core::config::CheckPolicy`]. Always set
    /// — defaults to `CheckPolicy::Warn` (byte-identical to the
    /// pre-`CheckPolicy` fail-open behaviour) when neither CLI nor config
    /// file provides one. Per-task `TaskSpec.check_policy` (set via
    /// caller code — HTTP request per-launch override wiring is a
    /// follow-up) takes priority over this server-wide value.
    pub check_policy: CheckPolicy,
}

impl Default for ResolvedConfig {
    fn default() -> Self {
        Self {
            bind: default_bind(),
            enable_enhance_flow: false,
            legacy_worker_binding_policy: LegacyWorkerBindingPolicy::Allow,
            blueprint_ref_base: None,
            blueprint_ref_includes: Vec::new(),
            blueprint_strict_embed: false,
            git_store_path: default_store_path(),
            issue_store_path: None,
            enhance_setting_store_path: None,
            enhance_log_store_path: None,
            output_store_path: None,
            task_store_path: None,
            run_store_path: None,
            replay_store_path: None,
            seed_blueprint_id: "main".into(),
            default_agent_kind: None,
            token_secret: None,
            sync_timeout_secs: default_sync_timeout_secs(),
            check_policy: CheckPolicy::default(),
        }
    }
}

/// Built-in default sync-launch timeout ceiling (GH #33 Guard 2), seconds.
/// 3600s / 60 min — sized for LLM-driven agent flows where individual
/// spawns routinely take 60-180s and full phases run 20-40 min. The
/// previous 300s ceiling under-shot the primary workload; users hitting
/// it were legitimate long-running runs, not stuck ones. Callers who
/// want faster fail-loud can override per-request
/// (`TaskLaunchRequest.timeout_secs`) or server-wide (config or CLI).
/// GH #39.
pub fn default_sync_timeout_secs() -> u64 {
    3600
}

fn default_bind() -> SocketAddr {
    "127.0.0.1:7777"
        .parse()
        .expect("literal default bind must parse")
}

/// Load + parse a TOML config file. A missing file resolves to
/// `Ok(FileConfig::default())` (built-in default fallback, per module doc);
/// any other IO error or a parse error is `Err` — a malformed config file
/// must not be silently ignored (fail-loud).
pub fn load_file_config(path: &Path) -> Result<FileConfig, String> {
    match std::fs::read_to_string(path) {
        Ok(text) => toml::from_str(&text)
            .map_err(|e| format!("config file {} parse error: {e}", path.display())),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(FileConfig::default()),
        Err(e) => Err(format!("config file {} read error: {e}", path.display())),
    }
}

/// 3-way merge: CLI > file > built-in default. `bind` requires a parse step
/// (both CLI and file carry it as a string); a parse error surfaces as `Err`.
pub fn resolve(cli: CliOverrides, file: FileConfig) -> Result<ResolvedConfig, String> {
    let default = ResolvedConfig::default();

    let bind = match cli.bind.or(file.bind) {
        Some(s) => s
            .parse::<SocketAddr>()
            .map_err(|e| format!("bind {s:?}: {e}"))?,
        None => default.bind,
    };

    let ephemeral = cli.ephemeral.or(file.ephemeral).unwrap_or(false);

    Ok(ResolvedConfig {
        bind,
        enable_enhance_flow: cli
            .enable_enhance_flow
            .or(file.enable_enhance_flow)
            .unwrap_or(default.enable_enhance_flow),
        legacy_worker_binding_policy: cli
            .legacy_worker_binding_policy
            .or(file.legacy_worker_binding_policy)
            .unwrap_or(default.legacy_worker_binding_policy),
        blueprint_ref_base: cli.blueprint_ref_base.or(file.blueprint_ref_base),
        blueprint_ref_includes: {
            let mut merged = cli.blueprint_ref_includes;
            merged.extend(file.blueprint_ref_includes.unwrap_or_default());
            merged
        },
        blueprint_strict_embed: cli
            .blueprint_strict_embed
            .or(file.blueprint_strict_embed)
            .unwrap_or(default.blueprint_strict_embed),
        git_store_path: cli
            .git_store_path
            .or(file.git_store_path)
            .unwrap_or_else(default_store_path),
        issue_store_path: cli.issue_store_path.or(file.issue_store_path),
        enhance_setting_store_path: cli
            .enhance_setting_store_path
            .or(file.enhance_setting_store_path),
        enhance_log_store_path: cli.enhance_log_store_path.or(file.enhance_log_store_path),
        output_store_path: cli.output_store_path.or(file.output_store_path),
        task_store_path: cli.task_store_path.or(file.task_store_path).or_else(|| {
            if ephemeral {
                None
            } else {
                Some(default_task_store_path())
            }
        }),
        run_store_path: cli.run_store_path.or(file.run_store_path).or_else(|| {
            if ephemeral {
                None
            } else {
                Some(default_run_store_path())
            }
        }),
        replay_store_path: cli
            .replay_store_path
            .or(file.replay_store_path)
            .or_else(|| {
                if ephemeral {
                    None
                } else {
                    Some(default_replay_store_path())
                }
            }),
        seed_blueprint_id: cli
            .seed_blueprint_id
            .or(file.seed_blueprint_id)
            .unwrap_or(default.seed_blueprint_id),
        default_agent_kind: cli.default_agent_kind.or(file.default_agent_kind),
        token_secret: cli.token_secret.or(file.token_secret),
        sync_timeout_secs: cli
            .sync_timeout_secs
            .or(file.sync_timeout_secs)
            .unwrap_or_else(default_sync_timeout_secs),
        check_policy: cli
            .check_policy
            .or(file.check_policy)
            .unwrap_or(default.check_policy),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolve_cli_flag_wins_over_file_and_default() {
        let cli = CliOverrides {
            bind: Some("127.0.0.1:9999".into()),
            ..Default::default()
        };
        let file = FileConfig {
            bind: Some("127.0.0.1:8888".into()),
            ..Default::default()
        };
        let resolved = resolve(cli, file).expect("resolve");
        assert_eq!(
            resolved.bind,
            "127.0.0.1:9999".parse::<SocketAddr>().unwrap()
        );
    }

    #[test]
    fn resolve_file_wins_over_built_in_default_when_cli_absent() {
        let cli = CliOverrides::default();
        let file = FileConfig {
            seed_blueprint_id: Some("from-file".into()),
            enable_enhance_flow: Some(true),
            ..Default::default()
        };
        let resolved = resolve(cli, file).expect("resolve");
        assert_eq!(resolved.seed_blueprint_id, "from-file");
        assert!(resolved.enable_enhance_flow);
    }

    #[test]
    fn resolve_legacy_worker_binding_policy_uses_cli_file_default_precedence() {
        let resolved = resolve(CliOverrides::default(), FileConfig::default()).unwrap();
        assert_eq!(
            resolved.legacy_worker_binding_policy,
            LegacyWorkerBindingPolicy::Allow
        );

        let file = FileConfig {
            legacy_worker_binding_policy: Some(LegacyWorkerBindingPolicy::Reject),
            ..Default::default()
        };
        let resolved = resolve(CliOverrides::default(), file.clone()).unwrap();
        assert_eq!(
            resolved.legacy_worker_binding_policy,
            LegacyWorkerBindingPolicy::Reject
        );

        let cli = CliOverrides {
            legacy_worker_binding_policy: Some(LegacyWorkerBindingPolicy::Allow),
            ..Default::default()
        };
        let resolved = resolve(cli, file).unwrap();
        assert_eq!(
            resolved.legacy_worker_binding_policy,
            LegacyWorkerBindingPolicy::Allow
        );
    }

    #[test]
    fn resolve_built_in_default_when_cli_and_file_absent() {
        let resolved = resolve(CliOverrides::default(), FileConfig::default()).expect("resolve");
        assert_eq!(resolved.bind, default_bind());
        assert_eq!(resolved.seed_blueprint_id, "main");
        assert!(!resolved.enable_enhance_flow);
        assert_eq!(resolved.git_store_path, default_store_path());
    }

    #[test]
    fn resolve_git_store_path_file_overrides_default_location() {
        let file = FileConfig {
            git_store_path: Some(PathBuf::from("/tmp/custom-store")),
            ..Default::default()
        };
        let resolved = resolve(CliOverrides::default(), file).expect("resolve");
        assert_eq!(resolved.git_store_path, PathBuf::from("/tmp/custom-store"));
    }

    #[test]
    fn resolve_bind_parse_error_is_propagated() {
        let cli = CliOverrides {
            bind: Some("not-a-valid-addr".into()),
            ..Default::default()
        };
        let err = resolve(cli, FileConfig::default()).unwrap_err();
        assert!(err.contains("not-a-valid-addr"), "unexpected error: {err}");
    }

    #[test]
    fn load_file_config_rejects_unknown_fields() {
        let toml_text = "bind = \"127.0.0.1:1234\"\ntypo_field = true\n";
        let err = toml::from_str::<FileConfig>(toml_text).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("typo_field") || msg.contains("unknown field"),
            "unexpected error message: {msg}"
        );
    }

    #[test]
    fn load_file_config_missing_file_falls_back_to_default() {
        let path = std::path::Path::new("/nonexistent/mse-config-test-path/config.toml");
        let cfg = load_file_config(path).expect("missing file should not error");
        assert_eq!(cfg, FileConfig::default());
    }

    #[test]
    fn load_file_config_parses_valid_toml() {
        let dir = std::env::temp_dir().join(format!("server-config-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create tmp dir");
        let path = dir.join("config.toml");
        std::fs::write(
            &path,
            "bind = \"127.0.0.1:7000\"\nenable_enhance_flow = true\nseed_blueprint_id = \"main\"\n",
        )
        .expect("write tmp config");
        let cfg = load_file_config(&path).expect("parse tmp config");
        assert_eq!(cfg.bind.as_deref(), Some("127.0.0.1:7000"));
        assert_eq!(cfg.enable_enhance_flow, Some(true));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_task_and_run_store_path_cli_wins_over_file() {
        let cli = CliOverrides {
            task_store_path: Some(PathBuf::from("/tmp/cli-tasks.db")),
            ..Default::default()
        };
        let file = FileConfig {
            task_store_path: Some(PathBuf::from("/tmp/file-tasks.db")),
            run_store_path: Some(PathBuf::from("/tmp/file-runs.db")),
            ..Default::default()
        };
        let resolved = resolve(cli, file).expect("resolve");
        assert_eq!(
            resolved.task_store_path,
            Some(PathBuf::from("/tmp/cli-tasks.db")),
            "cli task_store_path must win over file"
        );
        assert_eq!(
            resolved.run_store_path,
            Some(PathBuf::from("/tmp/file-runs.db")),
            "run_store_path falls back to file when cli is absent"
        );
    }

    #[test]
    fn resolve_task_and_run_store_path_default_none() {
        let resolved = resolve(CliOverrides::default(), FileConfig::default()).expect("resolve");
        assert_eq!(
            resolved.task_store_path,
            Some(default_task_store_path()),
            "issue #35 ST1: task_store_path now persists by default"
        );
        assert_eq!(
            resolved.run_store_path,
            Some(default_run_store_path()),
            "issue #35 ST1: run_store_path now persists by default"
        );
    }

    #[test]
    fn resolve_ephemeral_true_restores_in_memory_default() {
        let cli = CliOverrides {
            ephemeral: Some(true),
            ..Default::default()
        };
        let resolved = resolve(cli, FileConfig::default()).expect("resolve");
        assert_eq!(resolved.task_store_path, None);
        assert_eq!(resolved.run_store_path, None);
    }

    #[test]
    fn resolve_explicit_path_wins_over_ephemeral() {
        let cli = CliOverrides {
            task_store_path: Some(PathBuf::from("/tmp/explicit-tasks.db")),
            ephemeral: Some(true),
            ..Default::default()
        };
        let resolved = resolve(cli, FileConfig::default()).expect("resolve");
        assert_eq!(
            resolved.task_store_path,
            Some(PathBuf::from("/tmp/explicit-tasks.db")),
            "explicit path must win over ephemeral"
        );
    }

    #[test]
    fn resolve_ephemeral_from_file_config() {
        let file = FileConfig {
            ephemeral: Some(true),
            ..Default::default()
        };
        let resolved = resolve(CliOverrides::default(), file).expect("resolve");
        assert_eq!(resolved.task_store_path, None);
        assert_eq!(resolved.run_store_path, None);
        assert_eq!(resolved.replay_store_path, None);
    }

    // ──────────────────────────────────────────────────────────────────
    // `replay_store_path` resolution cascade (sibling of run_store_path)
    // ──────────────────────────────────────────────────────────────────

    #[test]
    fn resolve_replay_store_path_cli_wins_over_file() {
        let cli = CliOverrides {
            replay_store_path: Some(PathBuf::from("/tmp/cli-replay.db")),
            ..Default::default()
        };
        let file = FileConfig {
            replay_store_path: Some(PathBuf::from("/tmp/file-replay.db")),
            ..Default::default()
        };
        let resolved = resolve(cli, file).expect("resolve");
        assert_eq!(
            resolved.replay_store_path,
            Some(PathBuf::from("/tmp/cli-replay.db")),
            "cli replay_store_path must win over file"
        );
    }

    #[test]
    fn resolve_replay_store_path_file_wins_over_default() {
        let file = FileConfig {
            replay_store_path: Some(PathBuf::from("/tmp/file-replay.db")),
            ..Default::default()
        };
        let resolved = resolve(CliOverrides::default(), file).expect("resolve");
        assert_eq!(
            resolved.replay_store_path,
            Some(PathBuf::from("/tmp/file-replay.db")),
            "file replay_store_path must win over built-in default"
        );
    }

    #[test]
    fn resolve_replay_store_path_default_persists() {
        let resolved = resolve(CliOverrides::default(), FileConfig::default()).expect("resolve");
        assert_eq!(
            resolved.replay_store_path,
            Some(default_replay_store_path()),
            "replay_store_path persists by default (sibling of run_store_path)"
        );
    }

    #[test]
    fn resolve_replay_store_path_ephemeral_restores_in_memory() {
        let cli = CliOverrides {
            ephemeral: Some(true),
            ..Default::default()
        };
        let resolved = resolve(cli, FileConfig::default()).expect("resolve");
        assert_eq!(resolved.replay_store_path, None);
    }

    #[test]
    fn resolve_replay_store_path_explicit_wins_over_ephemeral() {
        let cli = CliOverrides {
            replay_store_path: Some(PathBuf::from("/tmp/explicit-replay.db")),
            ephemeral: Some(true),
            ..Default::default()
        };
        let resolved = resolve(cli, FileConfig::default()).expect("resolve");
        assert_eq!(
            resolved.replay_store_path,
            Some(PathBuf::from("/tmp/explicit-replay.db")),
            "explicit replay path must win over ephemeral"
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #33 Guard 2: `sync_timeout_secs` resolution cascade
    // ──────────────────────────────────────────────────────────────────

    #[test]
    fn resolve_sync_timeout_secs_default_when_cli_and_file_absent() {
        let resolved = resolve(CliOverrides::default(), FileConfig::default()).expect("resolve");
        assert_eq!(resolved.sync_timeout_secs, 3600);
        assert_eq!(resolved.sync_timeout_secs, default_sync_timeout_secs());
    }

    #[test]
    fn resolve_sync_timeout_secs_file_wins_over_default() {
        let file = FileConfig {
            sync_timeout_secs: Some(120),
            ..Default::default()
        };
        let resolved = resolve(CliOverrides::default(), file).expect("resolve");
        assert_eq!(resolved.sync_timeout_secs, 120);
    }

    #[test]
    fn resolve_sync_timeout_secs_cli_wins_over_file() {
        let cli = CliOverrides {
            sync_timeout_secs: Some(45),
            ..Default::default()
        };
        let file = FileConfig {
            sync_timeout_secs: Some(120),
            ..Default::default()
        };
        let resolved = resolve(cli, file).expect("resolve");
        assert_eq!(
            resolved.sync_timeout_secs, 45,
            "cli sync_timeout_secs must win over file"
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // ST1c-2a: `check_policy` resolution cascade
    // ──────────────────────────────────────────────────────────────────

    #[test]
    fn resolve_check_policy_default_when_cli_and_file_absent() {
        let resolved = resolve(CliOverrides::default(), FileConfig::default()).expect("resolve");
        assert_eq!(
            resolved.check_policy,
            CheckPolicy::Warn,
            "default check_policy must preserve pre-CheckPolicy fail-open (Warn)"
        );
        assert_eq!(resolved.check_policy, CheckPolicy::default());
    }

    #[test]
    fn resolve_check_policy_file_wins_over_default() {
        let file = FileConfig {
            check_policy: Some(CheckPolicy::Strict),
            ..Default::default()
        };
        let resolved = resolve(CliOverrides::default(), file).expect("resolve");
        assert_eq!(
            resolved.check_policy,
            CheckPolicy::Strict,
            "file check_policy must win over built-in default"
        );
    }

    #[test]
    fn resolve_check_policy_cli_wins_over_file() {
        let cli = CliOverrides {
            check_policy: Some(CheckPolicy::Silent),
            ..Default::default()
        };
        let file = FileConfig {
            check_policy: Some(CheckPolicy::Strict),
            ..Default::default()
        };
        let resolved = resolve(cli, file).expect("resolve");
        assert_eq!(
            resolved.check_policy,
            CheckPolicy::Silent,
            "cli check_policy must win over file"
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // Phase 6 (issue 4c4e3eb8): `blueprint_strict_embed` resolution cascade
    // ──────────────────────────────────────────────────────────────────

    #[test]
    fn resolve_blueprint_strict_embed_default_false_when_cli_and_file_absent() {
        let resolved = resolve(CliOverrides::default(), FileConfig::default()).expect("resolve");
        assert!(
            !resolved.blueprint_strict_embed,
            "default blueprint_strict_embed = false (backward-compat: linker runs server-side)"
        );
    }

    #[test]
    fn resolve_blueprint_strict_embed_file_wins_over_default() {
        let file = FileConfig {
            blueprint_strict_embed: Some(true),
            ..Default::default()
        };
        let resolved = resolve(CliOverrides::default(), file).expect("resolve");
        assert!(resolved.blueprint_strict_embed);
    }

    #[test]
    fn resolve_blueprint_strict_embed_cli_wins_over_file() {
        let cli = CliOverrides {
            blueprint_strict_embed: Some(false),
            ..Default::default()
        };
        let file = FileConfig {
            blueprint_strict_embed: Some(true),
            ..Default::default()
        };
        let resolved = resolve(cli, file).expect("resolve");
        assert!(
            !resolved.blueprint_strict_embed,
            "cli blueprint_strict_embed=false must win over file=true"
        );
    }

    #[test]
    fn file_config_deserializes_blueprint_strict_embed() {
        let toml_text = "blueprint_strict_embed = true\n";
        let cfg: FileConfig = toml::from_str(toml_text).expect("parse");
        assert_eq!(cfg.blueprint_strict_embed, Some(true));
    }

    #[test]
    fn file_config_deserializes_check_policy_snake_case_literals() {
        let toml_text = "check_policy = \"strict\"\n";
        let cfg: FileConfig = toml::from_str(toml_text).expect("parse");
        assert_eq!(cfg.check_policy, Some(CheckPolicy::Strict));

        let toml_text = "check_policy = \"silent\"\n";
        let cfg: FileConfig = toml::from_str(toml_text).expect("parse");
        assert_eq!(cfg.check_policy, Some(CheckPolicy::Silent));

        let toml_text = "check_policy = \"warn\"\n";
        let cfg: FileConfig = toml::from_str(toml_text).expect("parse");
        assert_eq!(cfg.check_policy, Some(CheckPolicy::Warn));
    }
}