synaps-engine 0.12.0

Runtime engine — streaming, tools, MCP, skills, extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
//! `synaps daemon reload` (PLAN-phase3 §2.8, C3): version gate → drain →
//! `Checkpoint{Reload}` every session → reload-state → announce
//! `Reloading`/`Bye{Reloading}` → `execv` self (same pid, adopted flock,
//! CLOEXEC listener) → new image rehydrates sessions from reload-state
//! BEFORE accepting.
//!
//! What reload cannot preserve (§2.8, stated once): in-flight turns
//! (checkpointed = cancelled; partial history + restart marker kept), pending prompts (answered
//! `None`), PTY/background shells (closed, announced), `turn_replay`,
//! input ownership (the owner reclaims it on
//! reconnect via `was_owner`). What it preserves — each session's
//! `Checkpoint{Reload}` reply carries a `SessionReloadRecord`: its journal
//! and id (the rehydrated session continues the same journal), its
//! `SessionConfig` as created (cwd, system, prompt manifest, compaction
//! policy, auto-compact, …), its keep-warm pin, its lifecycle (a Parked
//! session comes back Parked), the non-persisted runtime knobs
//! (`settings_replay`: context window, compaction model, retries,
//! timeouts, tool-output cap, worker grants, `/system`), the CURRENT
//! model/thinking (`/model` mid-session survives), and the session's exact
//! tool activations (pins only, re-validated by the new runtime at its first
//! turn start — `SessionToolSet::restore_carried`).
//!
//! Windows has no `execv`, and a byte-range lock cannot be inherited, so
//! step 5 is a hand-off between two processes (see `daemon::win`): the old
//! image starts the new one with the reload-state and a hand-off event; the
//! new image queues its `daemon.lock` request behind the old one and sets
//! the event; the old image exits — discarding what an exec would — and its
//! release grants the queued request, so the liveness oracle never reads
//! "free". The new image does this before booting anything, then proceeds
//! exactly as after an exec. Same guarantees, one difference: the pid
//! changes (clients learn it from the next `Welcome`).

use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};

use super::registry::{self, DaemonLock, DaemonPaths};
use super::DaemonState;
use crate::session::wire::{ClientFrame, CHECKPOINT_QUERY_ID, PROTOCOL_VERSION};
use crate::session::{
    CheckpointReason, SessionCommand, SessionConfig, SessionEventWire, SessionHandle,
    SessionLifecycle, SessionReloadRecord, SessionSetting,
};

/// Env: path of the reload-state file handed to the new image.
pub const RELOAD_STATE_ENV: &str = "SYNAPS_DAEMON_RELOAD_STATE";
/// Env: inherited `daemon.lock` fd (mandatory when `RELOAD_STATE_ENV` is set).
pub const LOCK_FD_ENV: &str = "SYNAPS_DAEMON_LOCK_FD";
/// Env: the subagent handle counter read at the `execv` itself, later than
/// `ReloadState::next_subagent_id` (written after the checkpoints): a worker
/// that ignored its stop could still dispatch in between.
pub const SUBAGENT_ID_FLOOR_ENV: &str = "SYNAPS_DAEMON_SUBAGENT_ID_FLOOR";
/// Windows: env naming the event the new image sets once its `daemon.lock`
/// request is queued behind the old image (which then exits).
pub const HANDOFF_EVENT_ENV: &str = "SYNAPS_DAEMON_HANDOFF_EVENT";
/// Windows: env carrying the old image's pid; the new image waits for it to
/// be gone (and its pipe instances with it) before it binds.
pub const HANDOFF_PID_ENV: &str = "SYNAPS_DAEMON_HANDOFF_PID";
/// Windows: how long the old image waits for the new one to queue its lock
/// request — process start and reading the reload-state; nothing boots first.
#[cfg(windows)]
const HANDOFF_ARM_TIMEOUT: Duration = Duration::from_secs(15);
/// Windows: how long the new image waits for the old one to let go.
#[cfg(windows)]
const HANDOFF_EXIT_TIMEOUT: Duration = Duration::from_secs(30);
/// Env: default drain budget in seconds.
pub const DRAIN_SECS_ENV: &str = "SYNAPS_DAEMON_RELOAD_DRAIN_SECS";
const DEFAULT_DRAIN: Duration = Duration::from_secs(30);
const VERSION_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
/// Per-session `Checkpoint{Reload}` wait: `cancel_turn` (the drain + its
/// bounded save) + stopping the session's workers + the checkpoint's own
/// bounded save + 1 s margin.
const CHECKPOINT_BUDGET: Duration =
    Duration::from_secs(crate::session::budgets::RELOAD_CHECKPOINT_BUDGET_SECS);
/// What clients are told to wait before reconnecting.
pub const RETRY_AFTER_MS: u64 = 500;

#[derive(Debug, Clone, Default)]
pub struct ReloadRequest {
    pub now: bool,
    pub drain_secs: Option<u64>,
    pub exe: Option<PathBuf>,
}

impl ReloadRequest {
    pub fn from_frame(frame: &ClientFrame) -> Option<Self> {
        match frame {
            ClientFrame::Reload { now, drain_secs, exe } => {
                Some(Self { now: *now, drain_secs: *drain_secs, exe: exe.clone() })
            }
            _ => None,
        }
    }
}

#[derive(Debug)]
pub enum ReloadError {
    /// Refused before anything was disturbed (`RefuseReason::ReloadRefused`).
    Refused(String),
    /// `execv` returned: the old image continues; sessions are checkpointed.
    ExecFailed(String),
}

impl std::fmt::Display for ReloadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Refused(w) => write!(f, "reload refused: {w}"),
            Self::ExecFailed(e) => write!(f, "reload exec failed: {e}"),
        }
    }
}

/// `<exe> daemon --print-version` output.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PrintVersion {
    pub binary_version: String,
    pub protocol_version: u32,
}

impl PrintVersion {
    pub fn current() -> Self {
        Self {
            binary_version: crate::session::wire::binary_version(),
            protocol_version: PROTOCOL_VERSION,
        }
    }
}

/// One recorded session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReloadSession {
    pub id: String,
    pub journal_id: String,
    pub config: SessionConfig,
    pub keep_warm: bool,
    pub lifecycle: SessionLifecycle,
    /// Non-persisted knobs re-`Set` after create (incl. `/system`).
    #[serde(default)]
    pub settings_replay: Vec<SessionSetting>,
    /// Per-session `/keepwarm` override (task #444), re-applied after create.
    #[serde(default)]
    pub cache_keepwarm: Option<String>,
    pub input_owner_kind: Option<crate::session::ClientKind>,
    /// Workers the checkpoint stopped (or that still owed the parent a
    /// completion wake), handed to the new image (`AdoptWorkers`).
    #[serde(default)]
    pub workers: Vec<crate::runtime::subagent::CarriedWorker>,
    /// The session's exact tool activations, restored into the new image's
    /// runtime (re-validated there; see `SessionToolSet::restore_carried`).
    /// Empty from an older image or a checkpoint that did not confirm.
    #[serde(default)]
    pub tool_activations: Vec<crate::tools::activation::CarriedActivation>,
    /// An owned session's owner token (`SessionConfig::owned` never rides
    /// the config): the next image restores it owned and unbound, waiting
    /// the re-bind grace for its owner. Never the forwarded secrets: the
    /// owner sends them again when it re-binds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner_token: Option<crate::session::OwnerToken>,
}

/// `registry_dir()/daemon[-P].reload.json` body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReloadState {
    pub generation: u64,
    pub written_at: chrono::DateTime<chrono::Utc>,
    pub sessions: Vec<ReloadSession>,
    pub expected_clients: usize,
    /// The subagent handle counter (`sa_N`) at the exec. The new image never
    /// hands out a lower id, so a model's remembered handles keep meaning
    /// the worker they named. `0` (older reload-state): derived from the
    /// carried workers only.
    #[serde(default)]
    pub next_subagent_id: u64,
}

impl ReloadState {
    /// The first handle number the new image may use: past the old image's
    /// counter and every carried worker id.
    pub fn subagent_id_floor(&self) -> u64 {
        let carried = self
            .sessions
            .iter()
            .flat_map(|s| &s.workers)
            .filter_map(|w| crate::runtime::subagent::handle_number(&w.id))
            .max()
            .map_or(0, |n| n + 1);
        self.next_subagent_id.max(carried)
    }
}

pub fn reload_state_path(paths: &DaemonPaths) -> PathBuf {
    let stem = paths
        .json
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "daemon".into());
    paths.dir.join(format!("{stem}.reload.json"))
}

/// The executable to re-exec: argv[0] canonicalised (NOT `/proc/self/exe`,
/// which reads "(deleted)" after an in-place rebuild); `current_exe` only
/// as a fallback when argv[0] is not resolvable (e.g. bare name on PATH).
pub fn resolve_exe() -> PathBuf {
    if let Some(a0) = std::env::args_os().next() {
        let p = PathBuf::from(&a0);
        if p.components().count() > 1 {
            if let Ok(c) = p.canonicalize() {
                return c;
            }
        }
    }
    std::env::current_exe().unwrap_or_else(|_| PathBuf::from("synaps"))
}

fn semver_tuple(s: &str) -> Option<(u64, u64, u64)> {
    let core = s.split(['-', '+']).next()?;
    let mut it = core.split('.').map(|p| p.parse::<u64>().ok());
    Some((it.next()??, it.next()??, it.next()??))
}

/// Directional gate (§2.1): new protocol ≥ ours (clients must still be able
/// to reconnect) and new binary ≥ ours (newer OR EQUAL; same-version
/// rebuilds are the common case).
pub fn version_gate(current: &PrintVersion, new: &PrintVersion) -> Result<(), String> {
    if new.protocol_version < current.protocol_version {
        return Err(format!(
            "new binary speaks protocol {} < {}: reconnecting clients would be refused",
            new.protocol_version, current.protocol_version
        ));
    }
    match (semver_tuple(&current.binary_version), semver_tuple(&new.binary_version)) {
        (Some(c), Some(n)) if n < c => Err(format!(
            "new binary {} is older than the running {} (reload is newer-or-equal only)",
            new.binary_version, current.binary_version
        )),
        (Some(_), Some(_)) => Ok(()),
        _ => Err(format!(
            "cannot compare versions {:?} vs {:?}",
            current.binary_version, new.binary_version
        )),
    }
}

/// M8: `--exe` must be something we would trust to `execv` in our own pid:
/// an existing regular file (canonicalised), executable, owned by our uid
/// (or root — package-installed binaries), not group/world-writable.
/// Returns the canonical path. Same-uid 0600 socket → not a privilege
/// boundary; this is a footgun guard, not a sandbox.
#[cfg(unix)]
pub fn validate_exe(exe: &Path) -> Result<PathBuf, String> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    let canon = exe
        .canonicalize()
        .map_err(|e| format!("--exe {}: {e}", exe.display()))?;
    let md = std::fs::metadata(&canon).map_err(|e| format!("--exe {}: {e}", canon.display()))?;
    if !md.is_file() {
        return Err(format!("--exe {}: not a regular file", canon.display()));
    }
    let mode = md.permissions().mode();
    if mode & 0o111 == 0 {
        return Err(format!("--exe {}: not executable", canon.display()));
    }
    // SAFETY: getuid has no preconditions.
    let uid = unsafe { libc::getuid() };
    if md.uid() != uid && md.uid() != 0 {
        return Err(format!(
            "--exe {}: owned by uid {} (expected {} or root)",
            canon.display(),
            md.uid(),
            uid
        ));
    }
    if mode & 0o022 != 0 {
        return Err(format!(
            "--exe {}: group/world-writable (mode {:o})",
            canon.display(),
            mode & 0o777
        ));
    }
    Ok(canon)
}

#[cfg(not(unix))]
pub fn validate_exe(exe: &Path) -> Result<PathBuf, String> {
    exe.canonicalize().map_err(|e| format!("--exe {}: {e}", exe.display()))
}

/// Run `<exe> daemon --print-version` (5 s) and parse it.
pub async fn probe_version(exe: &Path) -> Result<PrintVersion, String> {
    let out = tokio::time::timeout(
        VERSION_PROBE_TIMEOUT,
        tokio::process::Command::new(exe)
            .args(["daemon", "--print-version"])
            .env("SYNAPS_DAEMON", "1")
            .stdin(std::process::Stdio::null())
            .stderr(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .output(),
    )
    .await
    .map_err(|_| format!("{} --print-version timed out", exe.display()))?
    .map_err(|e| format!("cannot run {}: {e}", exe.display()))?;
    if !out.status.success() {
        return Err(format!(
            "{} --print-version exited {:?}: {}",
            exe.display(),
            out.status.code(),
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    serde_json::from_slice(&out.stdout)
        .map_err(|e| format!("{} --print-version: unparsable output ({e})", exe.display()))
}

/// `Checkpoint{Reload}` → the actor's `SessionReloadRecord` (`None` when
/// the checkpoint did not confirm in budget).
async fn checkpoint_one(handle: SessionHandle) -> Option<SessionReloadRecord> {
    let mut rx = handle.subscribe();
    if handle
        .send(SessionCommand::Checkpoint { reason: CheckpointReason::Reload })
        .await
        .is_err()
    {
        return None;
    }
    let wait = async {
        loop {
            match rx.recv().await {
                Ok(env) => {
                    if let SessionEventWire::QueryResult { id, value } = env.event {
                        if id == CHECKPOINT_QUERY_ID {
                            return serde_json::from_value(value["record"].clone()).ok();
                        }
                    }
                }
                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                Err(tokio::sync::broadcast::error::RecvError::Closed) => return None,
            }
        }
    };
    tokio::time::timeout(CHECKPOINT_BUDGET, wait).await.unwrap_or(None)
}

/// The session as it IS: the actor's record when the checkpoint confirmed,
/// else what the handle alone knows (journal, cwd, keep-warm, lifecycle,
/// current model from the published view, the `/keepwarm` override).
fn record(handle: &SessionHandle, rec: Option<SessionReloadRecord>) -> ReloadSession {
    let meta = handle.meta();
    let journal_id = handle.journal_id();
    if rec.is_none() {
        tracing::warn!(
            session = %handle.id,
            "reload: no checkpoint reply in time — this session's workers are not carried: \
             no archive is guaranteed and their parent will not be woken"
        );
    }
    let (config, keep_warm, lifecycle, settings_replay, cache_keepwarm, model, workers, tool_activations) = match rec {
        Some(r) => (
            r.config,
            r.keep_warm,
            r.lifecycle,
            r.settings_replay,
            r.cache_keepwarm,
            r.model,
            r.workers,
            r.tool_activations,
        ),
        None => (
            SessionConfig {
                cwd: meta.cwd.clone(),
                env: None,
            env_stripped: Vec::new(),
                ..SessionConfig::default()
            },
            // The pin is on the handle too, so it survives a reload whose
            // checkpoint did not confirm.
            handle.pinned(),
            handle.lifecycle(),
            Vec::new(),
            // Persisted independently of the checkpoint: an explicit
            // `/keepwarm` choice must survive a reload that timed out.
            handle.cache_keepwarm_override(),
            handle.view().model.clone(),
            // No checkpoint reply: whatever workers ran are lost to the exec
            // without a record (the actor never answered).
            Vec::new(),
            // Nor are its tool activations known.
            Vec::new(),
        ),
    };
    ReloadSession {
        id: meta.id.as_str().to_string(),
        journal_id: journal_id.clone(),
        config: SessionConfig {
            continue_session: Some(Some(journal_id)),
            model_override: Some(model),
            keep_warm,
            // The journal carries the CURRENT name (saveas after create);
            // re-applying the create-time `--name` would undo a rename.
            name: None,
            ..config
        },
        keep_warm,
        lifecycle,
        settings_replay,
        cache_keepwarm,
        input_owner_kind: None,
        workers,
        tool_activations,
        owner_token: handle.owner_token().cloned(),
    }
}

/// Steps 1–4 (§2.8): gate, drain, checkpoint, reload-state, announce.
/// Nothing irreversible has happened when this returns `Ok`; the caller
/// (the requesting connection) sends its own `Bye{Reloading}`, flushes,
/// then calls [`exec`].
pub struct Prepared {
    pub exe: PathBuf,
    pub rs_path: PathBuf,
    pub generation: u64,
}

pub async fn prepare(
    state: &Arc<DaemonState>,
    paths: &DaemonPaths,
    req: ReloadRequest,
) -> Result<Prepared, ReloadError> {
    // 1. version gate — before anything is disturbed.
    // The recorded exe from this image's own record (not daemon.json, which
    // can be lost while the daemon runs).
    let exe = req.exe.clone().unwrap_or_else(|| state.daemon_info().exe.unwrap_or_else(resolve_exe));
    let exe = validate_exe(&exe).map_err(ReloadError::Refused)?;
    let new = probe_version(&exe).await.map_err(ReloadError::Refused)?;
    version_gate(&PrintVersion::current(), &new).map_err(ReloadError::Refused)?;
    if state.reloading.swap(true, Ordering::SeqCst) {
        return Err(ReloadError::Refused("a reload is already in progress".into()));
    }
    let generation = state.generation + 1;
    tracing::info!(exe = %exe.display(), new = %new.binary_version, generation, "daemon: reload accepted");

    // 2. drain (refuse new work), then checkpoint every session concurrently.
    let drain = if req.now {
        Duration::ZERO
    } else {
        req.drain_secs
            .map(Duration::from_secs)
            .or_else(|| std::env::var(DRAIN_SECS_ENV).ok()?.parse().ok().map(Duration::from_secs))
            .unwrap_or(DEFAULT_DRAIN)
    };
    let t0 = std::time::Instant::now();
    while t0.elapsed() < drain {
        let mut all_idle = true;
        for h in state.live_sessions() {
            if !super::session_is_idle(&h).await {
                all_idle = false;
                break;
            }
        }
        if all_idle {
            break;
        }
        tokio::time::sleep(Duration::from_millis(200)).await;
    }
    let handles = state.live_sessions();
    let results = futures::future::join_all(handles.iter().cloned().map(checkpoint_one)).await;
    let mut sessions = Vec::with_capacity(handles.len());
    for (h, rec) in handles.iter().zip(results) {
        if rec.is_none() {
            tracing::warn!(session = %h.id, "reload: checkpoint did not confirm; recording from the handle");
        }
        sessions.push(record(h, rec));
    }

    // 3. reload-state (0600, atomic).
    let rs = ReloadState {
        generation,
        written_at: chrono::Utc::now(),
        sessions,
        expected_clients: state.connections.load(Ordering::SeqCst),
        // After every checkpoint: no session can launch a worker any more.
        next_subagent_id: crate::tools::peek_next_subagent_id(),
    };
    let rs_path = reload_state_path(paths);
    // If either write fails we early-return WITHOUT reaching exec() (which is the
    // only other place `reloading` is cleared), so reset the drain flag here —
    // otherwise a failed reload-state write bricks the daemon (it refuses every
    // new Create/Submit/Compact until restart).
    let written = serde_json::to_vec_pretty(&rs)
        .map_err(|e| e.to_string())
        .and_then(|body| registry::write_private_atomic(&rs_path, &body).map_err(|e| e.to_string()));
    if let Err(e) = written {
        // No exec will follow: every checkpointed session lifts its fence
        // and hears about the workers its checkpoint stopped.
        abort_checkpoints(state).await;
        state.reloading.store(false, Ordering::SeqCst);
        return Err(ReloadError::ExecFailed(e));
    }

    // 4. announce — every OTHER conn selects on `reload_announce` and sends
    //    Event(Reloading) + Bye{Reloading}; give their writers ≤ 1 s.
    state.reload_generation.store(generation, Ordering::SeqCst);
    state.fire_announce();
    let t1 = std::time::Instant::now();
    while state.connections.load(Ordering::SeqCst) > 1 && t1.elapsed() < Duration::from_secs(crate::session::budgets::RELOAD_ANNOUNCE_WAIT_SECS) {
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    Ok(Prepared { exe, rs_path, generation })
}

/// Step 5: rewrite `daemon.json` (generation+1, same pid), stop sidecars,
/// hand the flock to the next image and `execv`. Returns only on failure —
/// then `daemon.json`/reload-state are restored, extension discovery is
/// re-spawned (the sidecars were stopped for the exec — M4: no zombie
/// daemon without hooks), and the old image keeps serving (sessions
/// checkpointed but alive; clients that got `Bye` reconnect to THIS image
/// — a `reconnect_of.generation` mismatch is tolerated, the daemon answers
/// with its own generation).
pub async fn exec(state: &Arc<DaemonState>, p: Prepared) -> ReloadError {
    // From this image's own record, not daemon.json (which can be lost while
    // the daemon runs). The record is held and written under the metadata
    // lock, so a heal in the hand-off window writes the same.
    // `previous` stays untouched: a failed exec puts it back whole.
    let previous = state.daemon_info();
    let prev_generation = previous.generation;
    let info = registry::DaemonInfo {
        generation: p.generation,
        started_at: chrono::Utc::now(),
        exe: Some(p.exe.clone()),
        ..previous.clone()
    };
    if let Err(e) = state.meta.publish(info) {
        tracing::warn!(path = %state.paths.json.display(), error = %e, "daemon: daemon.json write failed at reload");
    }
    let _ = tokio::time::timeout(
        Duration::from_secs(crate::session::budgets::RELOAD_EXT_SHUTDOWN_SECS),
        async { state.host.ext_manager().write().await.shutdown_all().await },
    )
    .await;

    #[cfg(unix)]
    let err = exec_self(&p.exe, &p.rs_path, state);
    #[cfg(windows)]
    let err = exec_successor(&p.exe, &p.rs_path, state).await;
    tracing::error!(error = %err, "daemon: reload exec failed; continuing on the old image");
    // The record before this attempt, whole: exe and started_at too, so the
    // next default reload uses the old exe, not the one that failed.
    if let Err(e) = state.meta.publish(previous) {
        tracing::warn!(
            path = %state.paths.json.display(),
            error = %e,
            "daemon: daemon.json write failed after the failed reload exec"
        );
    }
    let _ = std::fs::remove_file(&p.rs_path);
    state.reload_generation.store(prev_generation, Ordering::SeqCst);
    state.reset_announce();
    // Sidecars were shut down for the exec: bring them back (bounded like
    // `run_foreground`'s first discovery) so the surviving image has hooks.
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
    let _loader = crate::extensions::loader::spawn_discover_and_load(
        Arc::clone(state.host.ext_manager()),
        tx,
        None,
    );
    let wait = async {
        while let Some(ev) = rx.recv().await {
            if let crate::extensions::loader::ExtensionLoaderEvent::Finished { loaded, failed } = ev {
                tracing::info!(loaded = loaded.len(), failed = failed.len(), "daemon: extensions re-discovered after failed reload");
                break;
            }
        }
    };
    if tokio::time::timeout(
        Duration::from_secs(crate::session::budgets::RELOAD_EXT_REDISCOVERY_SECS),
        wait,
    )
    .await
    .is_err()
    {
        tracing::warn!("daemon: extension re-discovery still running; resuming the sessions");
    }
    // The checkpoint fenced every session and stopped its workers for an
    // exec that did not happen: their parents are still here and still
    // waiting — lift the fences and tell them.
    abort_checkpoints(state).await;
    state.reloading.store(false, Ordering::SeqCst);
    ReloadError::ExecFailed(err)
}

#[cfg(unix)]
fn exec_self(exe: &Path, rs_path: &Path, state: &DaemonState) -> String {
    use std::os::unix::process::CommandExt;
    let Some(lock_fd) = state.lock_fd.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|l| l.raw_fd()) else {
        return "no lock fd to inherit".into();
    };
    // Clear FD_CLOEXEC on the lock so the new image adopts the SAME flock
    // (liveness oracle never flickers). The listener keeps CLOEXEC: it is
    // closed at exec and the new image rebinds the path.
    // SAFETY: fcntl on an fd we own.
    unsafe {
        let flags = libc::fcntl(lock_fd, libc::F_GETFD);
        if flags >= 0 {
            libc::fcntl(lock_fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC);
        }
    }
    let mut args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
    if args.is_empty() || args.iter().all(|a| a != "daemon") {
        args = vec!["daemon".into(), "--foreground".into()];
    }
    let mut cmd = std::process::Command::new(exe);
    cmd.args(&args)
        .env("SYNAPS_DAEMON", "1")
        .env(LOCK_FD_ENV, lock_fd.to_string())
        .env(RELOAD_STATE_ENV, rs_path)
        .env(SUBAGENT_ID_FLOOR_ENV, crate::tools::peek_next_subagent_id().to_string());
    let e = cmd.exec();
    // Only reached on failure: restore CLOEXEC.
    // SAFETY: as above.
    unsafe {
        let flags = libc::fcntl(lock_fd, libc::F_GETFD);
        if flags >= 0 {
            libc::fcntl(lock_fd, libc::F_SETFD, flags | libc::FD_CLOEXEC);
        }
    }
    e.to_string()
}

/// Windows `execv`: start the new image with the reload-state and a
/// hand-off event, wait for it to queue its `daemon.lock` request behind
/// ours, then exit — no destructors (they would unlink the `daemon.json`
/// that now names the next generation), no session `End` (the new image
/// rehydrates them): what the exec discards on Unix. Returns only on
/// failure, with this image intact.
#[cfg(windows)]
async fn exec_successor(exe: &Path, rs_path: &Path, state: &DaemonState) -> String {
    use super::win;
    let armed = match win::Event::create_unique("handoff") {
        Ok(e) => e,
        Err(e) => return format!("hand-off event: {e}"),
    };
    let mut args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
    if args.is_empty() || args.iter().all(|a| a != "daemon") {
        args = vec!["daemon".into(), "--foreground".into()];
    }
    let mut env = crate::process_scope::inherited_env();
    env.retain(|(k, _)| k != super::READY_EVENT_ENV);
    crate::process_scope::set_env(&mut env, "SYNAPS_DAEMON", "1");
    crate::process_scope::set_env(&mut env, RELOAD_STATE_ENV, rs_path.as_os_str());
    crate::process_scope::set_env(&mut env, HANDOFF_EVENT_ENV, armed.name());
    crate::process_scope::set_env(&mut env, HANDOFF_PID_ENV, std::process::id().to_string());
    crate::process_scope::set_env(&mut env, SUBAGENT_ID_FLOOR_ENV, crate::tools::peek_next_subagent_id().to_string());
    let child = match win::spawn_detached(exe, &args, &env) {
        Ok(c) => c,
        Err(e) => return format!("cannot start {}: {e}", exe.display()),
    };
    let waited = tokio::task::spawn_blocking(move || {
        let outcome = win::wait_event_or_exit(&armed, &child, HANDOFF_ARM_TIMEOUT);
        (child, outcome)
    })
    .await;
    let (child, outcome) = match waited {
        Ok(r) => r,
        Err(e) => return format!("hand-off wait: {e}"),
    };
    match outcome {
        win::Wait::Signalled => {
            tracing::info!(pid = child.id(), "daemon: reload hand-off armed; this image exits");
            state.host.flush_logs();
            std::process::exit(0);
        }
        win::Wait::Exited => {
            let mut child = child;
            let code = child.wait(Duration::ZERO);
            let tail = win::stderr_tail(child.take_stderr(), 64 * 1024, Duration::from_millis(500));
            let why = tail
                .lines()
                .map(str::trim)
                .rfind(|l| !l.is_empty())
                .map(|l| l.trim_start_matches("synaps daemon: ").to_string())
                .unwrap_or_else(|| "no output".into());
            format!(
                "new image exited (code {}) before taking over: {why}",
                code.map_or_else(|| "?".to_string(), |c| c.to_string())
            )
        }
        win::Wait::TimedOut => {
            child.kill();
            let _ = child.wait(Duration::from_secs(5));
            format!("new image did not take over within {HANDOFF_ARM_TIMEOUT:?}")
        }
    }
}

/// What a new image adopts: the held lock, the reload-state and its path.
type Adopted = (DaemonLock, ReloadState, PathBuf);

/// Windows: the hand-off taken at the top of `run_foreground`, held here
/// for [`adopt_from_env`].
#[cfg(windows)]
static TAKEN_OVER: std::sync::Mutex<Option<Adopted>> = std::sync::Mutex::new(None);

/// Windows: take `daemon.lock` over from the previous image now, before
/// anything boots (the previous image exits on our signal, as the exec
/// would have replaced it). A no-op unless this is a reload.
#[cfg(windows)]
pub fn take_over_from_env(paths: &DaemonPaths) -> anyhow::Result<()> {
    if let Some(adopted) = handoff_from_env(paths)? {
        *TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()) = Some(adopted);
    }
    Ok(())
}

/// New-image side (`Daemon::start`), Windows: what [`take_over_from_env`]
/// took, or the hand-off done now.
#[cfg(windows)]
pub fn adopt_from_env(paths: &DaemonPaths) -> anyhow::Result<Option<Adopted>> {
    if let Some(adopted) = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()).take() {
        return Ok(Some(adopted));
    }
    handoff_from_env(paths)
}

/// Windows hand-off, new-image side: parse the reload-state first (a bad
/// one fails while the old image can still carry on), queue `daemon.lock`
/// behind the old image and set its hand-off event, take the grant when it
/// exits, then wait for its process to be gone. The event is mandatory —
/// without it the old image would never let go (refuse, as Unix refuses a
/// reload-state without its lock fd).
#[cfg(windows)]
fn handoff_from_env(paths: &DaemonPaths) -> anyhow::Result<Option<Adopted>> {
    let Some(rs_path) = std::env::var_os(RELOAD_STATE_ENV) else {
        return Ok(None);
    };
    let rs_path = PathBuf::from(rs_path);
    std::env::remove_var(RELOAD_STATE_ENV);
    let event = std::env::var(HANDOFF_EVENT_ENV).ok();
    std::env::remove_var(HANDOFF_EVENT_ENV);
    let old_pid = std::env::var(HANDOFF_PID_ENV).ok().and_then(|s| s.parse::<u32>().ok());
    std::env::remove_var(HANDOFF_PID_ENV);
    let id_floor = std::env::var(SUBAGENT_ID_FLOOR_ENV).ok().and_then(|s| s.parse::<u64>().ok());
    std::env::remove_var(SUBAGENT_ID_FLOOR_ENV);
    let event = event.ok_or_else(|| {
        anyhow::anyhow!("{RELOAD_STATE_ENV} set without {HANDOFF_EVENT_ENV}: refusing to start (the lock is the liveness oracle)")
    })?;
    let body = std::fs::read_to_string(&rs_path)?;
    let mut rs: ReloadState = serde_json::from_str(&body)?;
    if let Some(floor) = id_floor {
        rs.next_subagent_id = rs.next_subagent_id.max(floor);
    }
    // Opened before the signal, so its pid cannot be reused under us.
    let old = old_pid.and_then(super::win::Process::open);
    let mut signal_err = None;
    let lock = DaemonLock::acquire_handoff(paths, HANDOFF_EXIT_TIMEOUT, || {
        signal_err = super::win::signal_event(&event).err();
    })
    .map_err(|e| match &signal_err {
        Some(s) => anyhow::anyhow!("taking daemon.lock over: {e} (the previous image was never told: {s})"),
        None => anyhow::anyhow!("taking daemon.lock over from the previous image: {e}"),
    })?;
    if let Some(old) = old {
        if !old.wait(Duration::from_secs(10)) {
            tracing::warn!(pid = old_pid, "daemon: the previous image still runs after releasing daemon.lock");
        }
    }
    tracing::info!(generation = rs.generation, "daemon: took daemon.lock over from the previous image");
    // The previous image read our stderr; it is gone.
    super::win::detach_stdio();
    Ok(Some((lock, rs, rs_path)))
}

/// New-image side (`Daemon::start`): when `RELOAD_STATE_ENV` is set, the
/// lock is ADOPTED from `LOCK_FD_ENV` (mandatory — refuse to start without
/// it, risk §6.8) and the recorded generation is returned.
#[cfg(unix)]
pub fn adopt_from_env(_paths: &DaemonPaths) -> anyhow::Result<Option<Adopted>> {
    let Some(rs_path) = std::env::var_os(RELOAD_STATE_ENV) else {
        return Ok(None);
    };
    let rs_path = PathBuf::from(rs_path);
    std::env::remove_var(RELOAD_STATE_ENV);
    let fd: i32 = std::env::var(LOCK_FD_ENV)
        .ok()
        .and_then(|s| s.parse().ok())
        .ok_or_else(|| anyhow::anyhow!("{RELOAD_STATE_ENV} set without {LOCK_FD_ENV}: refusing to start (the flock is the liveness oracle)"))?;
    std::env::remove_var(LOCK_FD_ENV);
    let id_floor = std::env::var(SUBAGENT_ID_FLOOR_ENV).ok().and_then(|s| s.parse::<u64>().ok());
    std::env::remove_var(SUBAGENT_ID_FLOOR_ENV);
    let lock = DaemonLock::adopt(fd)?;
    let body = std::fs::read_to_string(&rs_path)?;
    let mut rs: ReloadState = serde_json::from_str(&body)?;
    if let Some(floor) = id_floor {
        rs.next_subagent_id = rs.next_subagent_id.max(floor);
    }
    Ok(Some((lock, rs, rs_path)))
}

/// Rehydrate every recorded session BEFORE accepting. A session that
/// fails to come back is logged and skipped (its journal is on disk;
/// `--continue` brings it back).
///
/// A session whose journal was never written (no turn yet — `save` skips
/// an empty conversation) cannot be continued; it is recreated fresh under
/// a new id and aliased from the old one.
/// F23: detect "is live in another process" in the error string — this is
/// the `SessionLockError::Held` case, where an in-process runtime holds
/// the journal lock. Instead of aliasing to an empty impostor, register a
/// Parked placeholder under the SAME id.
pub(crate) fn is_lock_held_error(e: &str) -> bool {
    e.contains("is live in another process")
}

/// Extract `"pid N (kind)"` from the lock-held error message.
pub(crate) fn parse_holder_from_error(e: &str) -> String {
    // "session X is live in another process (pid N, kind) — …"
    if let Some(start) = e.find("(pid ") {
        let after = &e[start + 1..]; // "pid N, kind) — …"
        if let Some(end) = after.find(')') {
            return after[..end].to_string();
        }
    }
    "unknown holder".to_string()
}

/// No exec after the checkpoints (it failed, or the reload stopped before
/// it): every live session lifts its reload fence and is handed back the
/// workers its checkpoint stopped (`ReloadAborted`, a no-op for a session
/// that never checkpointed). The actor re-announces from its own record,
/// so a checkpoint that answered too late for the reload record is covered.
async fn abort_checkpoints(state: &Arc<DaemonState>) {
    let budget = Duration::from_secs(crate::session::budgets::RELOAD_ABORT_SEND_SECS);
    let sends = state
        .live_sessions()
        .into_iter()
        .map(|h| async move { send_reload_aborted(&h, budget).await });
    futures::future::join_all(sends).await;
}

/// `ReloadAborted` must arrive: dropped, the session would wait out the
/// fence's backstop. `SessionHandle::send` never waits for queue room, so
/// retry a full queue (the actor drains it) for up to `budget`.
pub(crate) async fn send_reload_aborted(h: &SessionHandle, budget: Duration) -> bool {
    use crate::session::TransportError;
    let deadline = tokio::time::Instant::now() + budget;
    loop {
        match h.send(SessionCommand::ReloadAborted).await {
            Ok(()) => return true,
            Err(TransportError::Backpressure) if tokio::time::Instant::now() < deadline => {
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
            Err(e) => {
                tracing::warn!(
                    session = %h.id,
                    error = %e,
                    "reload: could not tell the session the exec failed; its reload fence lifts at the backstop"
                );
                return false;
            }
        }
    }
}

/// The config a session is restored with: as saved, except that the
/// restore never waits on `on_session_start`. Each restored session runs
/// the hook in the background (the deferred path quick-start sessions
/// use), so the restore of N sessions does not take N hook round trips
/// while the socket waits. A session restored Parked runs it only once it
/// is unparked.
///
/// A folder that is no longer there is dropped ([`restorable_folder`]), as
/// the pinned restore drops it (`pins::restore_one`): the chat `chat` then
/// runs in the daemon's folder and its project. Kept, the dead path gave
/// the chat no project at all: discovery fails on a path it cannot resolve,
/// the memory tools answer "host project scope unavailable" and the next
/// rollover cannot seal.
fn restore_config(saved: &SessionConfig, lifecycle: SessionLifecycle, chat: &str) -> SessionConfig {
    SessionConfig {
        await_extensions: false,
        restore_parked: matches!(lifecycle, SessionLifecycle::Parked | SessionLifecycle::Parking),
        cwd: restorable_folder(saved.cwd.clone(), chat),
        ..saved.clone()
    }
}

/// The folder a chat is restored in, by a reload, as a pinned session or by
/// an unpark (`session/actor.rs`):
/// `folder` as saved, or `None` when it is gone, and the chat then runs in
/// the daemon's folder and that folder's project.
///
/// Gone means that the path does not exist, is not a directory, or runs
/// through something that is not a directory (a file where one of its
/// parents was), which no folder can be under. A folder that cannot be
/// looked at for a reason that can pass (no permission, a mount that is
/// away for a moment, an I/O error) is kept: the chat stays in its
/// own project, where its tools fail until the folder is back, rather than
/// being moved to another project's files and memory without a word. Every
/// drop is logged with the folder and the chat. The lines name no host: an
/// unpark in a host that is not the daemon writes them too.
pub(crate) fn restorable_folder(folder: Option<PathBuf>, chat: &str) -> Option<PathBuf> {
    let folder = folder?;
    let gone = match std::fs::metadata(&folder) {
        Ok(found) if found.is_dir() => return Some(folder),
        Ok(_) => "it is not a directory",
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => "it does not exist",
        Err(error) if error.kind() == std::io::ErrorKind::NotADirectory => {
            "its path runs through something that is not a directory"
        }
        Err(error) => {
            tracing::warn!(
                session = %chat,
                folder = %folder.display(),
                error = %error,
                "{}",
                UNSEEN_NOTICE
            );
            return Some(folder);
        }
    };
    tracing::warn!(
        session = %chat,
        folder = %folder.display(),
        "{}",
        gone_notice(gone)
    );
    None
}

/// What [`restorable_folder`] logs for a folder it keeps without having
/// seen it. Like [`gone_notice`] it names no host.
const UNSEEN_NOTICE: &str = "the chat's folder cannot be looked at; restored with it all the same";

/// What [`restorable_folder`] logs for a folder it drops, `gone` being why.
/// It names no host ("daemon:" it once began with): a reload and a pinned
/// restore run in the daemon, an unpark in whichever host holds the chat.
fn gone_notice(gone: &str) -> String {
    format!(
        "the chat's folder is gone ({gone}); it is restored in the host process's folder \
         and that folder's project"
    )
}

pub async fn rehydrate(state: &Arc<DaemonState>, rs: &ReloadState) {
    // Before any session can dispatch: ids continue where the old image
    // stopped, so `sa_1` never names two different workers.
    crate::tools::seed_next_subagent_id(rs.subagent_id_floor());
    for s in &rs.sessions {
        // Owned: restored unbound, its grace armed only once this image
        // accepts connections (`Daemon::start`), its autonomous work held
        // until the owner re-binds.
        let owned = s.owner_token.clone().map(|token| crate::session::OwnedConfig { token, restored: true });
        let config = SessionConfig { owned, ..restore_config(&s.config, s.lifecycle, &s.id) };
        let created = match state.create(config.clone()).await {
            Ok(h) => Ok(h),
            // F23: journal locked by another process — register a Parked
            // placeholder under the SAME id. No alias, no fresh session.
            Err(e) if is_lock_held_error(&e) => {
                let holder = parse_holder_from_error(&e);
                tracing::warn!(
                    session = %s.id, holder = %holder,
                    "daemon: journal locked by another process; registering Parked placeholder"
                );
                let sid = crate::session::SessionId::from(s.id.as_str());
                // `config`, not `s.config`: an owned session stays owned.
                let (handle, _task) = crate::session::handle::locked_placeholder::spawn(
                    sid,
                    config.clone(),
                    holder,
                );
                state.insert(handle);
                continue;
            }
            Err(e) if s.config.continue_session.is_some() => {
                tracing::warn!(session = %s.id, error = %e, "daemon: journal not continuable; recreating fresh");
                state
                    .create(SessionConfig {
                        continue_session: None,
                        ..config.clone()
                    })
                    .await
            }
            Err(e) => Err(e),
        };
        match created {
            Ok(h) => {
                let new_id = h.id.as_str().to_string();
                // First, before anything can start a turn: the same
                // conversation continues in this image, so the grants it
                // held come with it (re-validated by the new runtime at its
                // first turn start). A session recreated fresh (journal not
                // continuable) is a new conversation and inherits none.
                let continued = h.meta().continued;
                if continued && !s.tool_activations.is_empty() {
                    let _ = h
                        .send(SessionCommand::RestoreToolActivations {
                            activations: s.tool_activations.clone(),
                        })
                        .await;
                }
                if new_id != s.id {
                    state
                        .reload_aliases
                        .lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .insert(s.id.clone(), new_id.clone());
                }
                // Non-persisted knobs (host-originated `Set`: no owner check).
                for (i, setting) in s.settings_replay.iter().enumerate() {
                    let _ = h
                        .send(SessionCommand::Set {
                            id: u64::MAX - i as u64,
                            setting: setting.clone(),
                        })
                        .await;
                }
                if s.keep_warm {
                    let _ = h.send(SessionCommand::KeepWarm { on: true }).await;
                }
                if let Some(mode) = &s.cache_keepwarm {
                    let _ = h
                        .send(SessionCommand::EngineCommand {
                            id: u64::MAX,
                            name: "keepwarm".into(),
                            arg: mode.clone(),
                        })
                        .await;
                }
                // Before any Park: re-register the stopped workers and wake
                // their parent (it was waiting on completions the exec ate).
                if !s.workers.is_empty() {
                    let _ = h
                        .send(SessionCommand::AdoptWorkers { workers: s.workers.clone() })
                        .await;
                }
                if matches!(s.lifecycle, SessionLifecycle::Parked | SessionLifecycle::Parking) {
                    let _ = h.send(SessionCommand::Park).await;
                } else {
                    // Last, after the pin, keep-warm and workers it weighs:
                    // the old image's park timer died with the exec, and a
                    // session nobody reconnects to gets no detach to arm one.
                    let _ = h.send(SessionCommand::ArmPark).await;
                }
                tracing::info!(old = %s.id, new = %new_id, lifecycle = ?s.lifecycle, "daemon: session rehydrated after reload");
            }
            Err(e) => tracing::warn!(session = %s.id, error = %e, "daemon: session could not be rehydrated"),
        }
    }
}

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

    /// The session's tool activations ride the reload-state file; a file
    /// from an older image (no field) reads as none.
    #[test]
    fn reload_session_carries_tool_activations() {
        use crate::tools::activation::{CarriedActivation, CarriedProvenance};
        let carried = vec![CarriedActivation {
            tool_id: "builtin:subagent_start".into(),
            schema_digest: "cd".repeat(32),
            provenance: CarriedProvenance::BuiltinRuntime,
        }];
        let s = ReloadSession {
            id: "s".into(),
            journal_id: "j".into(),
            config: SessionConfig::default(),
            keep_warm: false,
            lifecycle: SessionLifecycle::Live,
            settings_replay: Vec::new(),
            cache_keepwarm: None,
            input_owner_kind: None,
            workers: Vec::new(),
            tool_activations: carried.clone(),
            owner_token: None,
        };
        let v = serde_json::to_value(&s).unwrap();
        let back: ReloadSession = serde_json::from_value(v.clone()).unwrap();
        assert_eq!(back.tool_activations, carried);
        // Never via the create config's wire form.
        assert!(v["config"].get("restore_tool_activations").is_none());

        let mut older = v;
        older.as_object_mut().unwrap().remove("tool_activations");
        let back: ReloadSession = serde_json::from_value(older).unwrap();
        assert!(back.tool_activations.is_empty());
    }

    /// Reload-state written by an older image (no workers, no counter)
    /// still parses: the new fields default.
    #[test]
    fn reload_state_from_an_older_image_parses() {
        let rs: ReloadState = serde_json::from_value(serde_json::json!({
            "generation": 9,
            "written_at": "2026-10-14T18:17:03Z",
            "sessions": [],
            "expected_clients": 1
        }))
        .unwrap();
        assert_eq!(rs.next_subagent_id, 0);
        assert_eq!(rs.subagent_id_floor(), 0);
    }

    /// The new image's first handle is past the old counter AND past every
    /// carried id (an older writer that only carried workers still works).
    #[test]
    fn subagent_id_floor_covers_the_counter_and_every_carried_id() {
        let worker = |id: &str| crate::runtime::subagent::CarriedWorker {
            id: id.into(),
            subagent_id: 0,
            agent: String::new(),
            status: "cancelled".into(),
            archive_path: None,
            stopped_by_reload: true,
            wake_lost: false,
            wake: true,
            elapsed_secs: 0,
            preview: String::new(),
        };
        let session = |workers| ReloadSession {
            id: "s".into(),
            journal_id: "j".into(),
            config: SessionConfig::default(),
            keep_warm: false,
            lifecycle: SessionLifecycle::Live,
            settings_replay: Vec::new(),
            cache_keepwarm: None,
            input_owner_kind: None,
            workers,
            tool_activations: Vec::new(),
            owner_token: None,
        };
        let mut rs = ReloadState {
            generation: 10,
            written_at: chrono::Utc::now(),
            sessions: vec![session(vec![worker("sa_288"), worker("sa_286")]), session(vec![])],
            expected_clients: 0,
            next_subagent_id: 0,
        };
        assert_eq!(rs.subagent_id_floor(), 289);
        rs.next_subagent_id = 300;
        assert_eq!(rs.subagent_id_floor(), 300);
        // Round trip keeps both.
        let back: ReloadState = serde_json::from_slice(&serde_json::to_vec(&rs).unwrap()).unwrap();
        assert_eq!(back.subagent_id_floor(), 300);
        assert_eq!(back.sessions[0].workers.len(), 2);
    }

    fn pv(b: &str, p: u32) -> PrintVersion {
        PrintVersion { binary_version: b.into(), protocol_version: p }
    }

    #[test]
    fn gate_is_directional_newer_or_equal() {
        let cur = pv("0.9.0", 2);
        assert!(version_gate(&cur, &pv("0.9.0", 2)).is_ok(), "equal allowed");
        assert!(version_gate(&cur, &pv("0.9.1", 2)).is_ok());
        assert!(version_gate(&cur, &pv("1.0.0-rc1", 3)).is_ok());
        assert!(version_gate(&cur, &pv("0.8.9", 2)).is_err(), "older refused");
        assert!(version_gate(&cur, &pv("0.9.0", 1)).is_err(), "older protocol refused");
        assert!(version_gate(&cur, &pv("garbage", 2)).is_err());
        // Two-digit minor (daemon dev builds report 0.9.1 → 0.10.0): compared
        // numerically, not as strings — "10" < "9" lexically would refuse it.
        assert!(
            version_gate(&pv("0.9.1", 3), &pv("0.10.0", 3)).is_ok(),
            "0.10.0 is newer than 0.9.1"
        );
        assert!(
            version_gate(&pv("0.10.0", 3), &pv("0.9.1", 3)).is_err(),
            "0.9.1 is older than 0.10.0"
        );
    }

    #[cfg(unix)]
    #[test]
    fn validate_exe_refuses_missing_dirs_non_exec_and_writable() {
        use std::os::unix::fs::PermissionsExt;
        let d = tempfile::tempdir().unwrap();
        assert!(validate_exe(&d.path().join("nope")).unwrap_err().contains("nope"));
        assert!(validate_exe(d.path()).unwrap_err().contains("not a regular file"));
        let f = d.path().join("bin");
        std::fs::write(&f, "#!/bin/sh\nexit 0\n").unwrap();
        std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o644)).unwrap();
        assert!(validate_exe(&f).unwrap_err().contains("not executable"));
        std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o777)).unwrap();
        assert!(validate_exe(&f).unwrap_err().contains("writable"));
        std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
        assert_eq!(validate_exe(&f).unwrap(), f.canonicalize().unwrap());
        // A symlink resolves to its target.
        let l = d.path().join("link");
        std::os::unix::fs::symlink(&f, &l).unwrap();
        assert_eq!(validate_exe(&l).unwrap(), f.canonicalize().unwrap());
    }

    /// A restored session never waits on `on_session_start` at create; the
    /// rest of its saved config is kept. One restored Parked defers the hook
    /// to its unpark, and that flag never goes on the wire.
    #[test]
    fn a_restore_does_not_wait_on_the_session_start_hook() {
        let saved = SessionConfig {
            model_override: Some("claude-sonnet-4-5".into()),
            keep_warm: true,
            await_extensions: true,
            ..Default::default()
        };
        let restored = restore_config(&saved, SessionLifecycle::Live, "chat");
        assert!(!restored.await_extensions);
        assert!(!restored.restore_parked);
        let as_saved = SessionConfig {
            await_extensions: true,
            ..restored
        };
        assert_eq!(
            serde_json::to_value(&as_saved).unwrap(),
            serde_json::to_value(&saved).unwrap()
        );
        for parked in [SessionLifecycle::Parked, SessionLifecycle::Parking] {
            let restored = restore_config(&saved, parked, "chat");
            assert!(restored.restore_parked, "{parked:?}");
            assert!(!restored.await_extensions);
            let wire = serde_json::to_value(&restored).unwrap();
            assert!(wire.get("restore_parked").is_none(), "never on the wire");
        }
    }

    /// A chat whose folder was deleted while the daemon held it. The pinned
    /// restore drops such a folder (`pins::restore_one`, by the same
    /// [`restorable_folder`]) and the chat runs in the
    /// daemon's folder: a runtime without a folder of its own takes the
    /// process's. A reload kept the dead path. The chat's memory binding was
    /// then built on a path project discovery cannot resolve, so it had no
    /// project: memory tools answered "host project scope unavailable" and a
    /// rollover could not seal. Reload now drops it too.
    #[test]
    fn a_restore_drops_a_folder_that_is_gone_as_the_pinned_restore_does() {
        let parent = tempfile::tempdir().unwrap();
        let (kept, gone) = (parent.path().join("kept"), parent.path().join("gone"));
        std::fs::create_dir(&kept).unwrap();
        let saved = |folder: &Path| SessionConfig {
            cwd: Some(folder.to_path_buf()),
            ..Default::default()
        };

        // What the dead path does to a chat that keeps it.
        let binding = crate::memory_backend::MemoryBinding::for_cwd(Some(gone.clone()));
        let error = binding.scope().unwrap_err().to_string();
        assert!(error.contains("host project scope unavailable"), "{error}");
        let binding = crate::memory_backend::MemoryBinding::for_cwd(Some(kept.clone()));
        assert!(binding.scope().is_ok());

        for lifecycle in [SessionLifecycle::Live, SessionLifecycle::Parked] {
            assert_eq!(restore_config(&saved(&kept), lifecycle, "chat").cwd, Some(kept.clone()));
            assert_eq!(restore_config(&saved(&gone), lifecycle, "chat").cwd, None, "{lifecycle:?}");
        }
        // A file where the folder was is not a folder to run in either.
        std::fs::write(&gone, b"").unwrap();
        assert_eq!(restore_config(&saved(&gone), SessionLifecycle::Live, "chat").cwd, None);
        // No folder saved: nothing to drop.
        assert_eq!(restore_config(&SessionConfig::default(), SessionLifecycle::Live, "chat").cwd, None);
    }

    /// The two lines `restorable_folder` logs do not say "daemon": an unpark
    /// in a host that is not the daemon goes through the same function.
    /// (The text is checked, not a captured log: a log captured on one test
    /// thread loses lines to tracing's callsite cache when another test
    /// reaches the same line first.)
    #[test]
    fn the_lines_about_a_chats_folder_name_no_host() {
        let gone = gone_notice("it does not exist");
        assert!(gone.starts_with("the chat's folder is gone (it does not exist); "), "{gone}");
        for line in [gone.as_str(), UNSEEN_NOTICE] {
            assert!(line.starts_with("the chat's folder "), "{line}");
            assert!(!line.contains("daemon"), "{line}");
        }
    }

    /// The rule a reload and the pinned restore share. A folder is dropped,
    /// and the chat moved to the daemon's folder and project, only when it
    /// is known to be gone. `is_dir()` said "gone" for every failure, so a
    /// folder that could not be looked at for a moment (a mount that was
    /// away, a permission) moved the chat as well, without a log line.
    #[cfg(unix)]
    #[test]
    fn a_folder_is_dropped_only_when_it_is_absent_or_not_a_directory() {
        use std::os::unix::fs::PermissionsExt;
        let parent = tempfile::tempdir().unwrap();
        let at = |name: &str| parent.path().join(name);
        let restored = |folder: &Path| restorable_folder(Some(folder.to_path_buf()), "chat");
        assert_eq!(restorable_folder(None, "chat"), None);

        // Absent, and a file: dropped.
        assert_eq!(restored(&at("absent")), None);
        std::fs::write(at("file"), b"").unwrap();
        assert_eq!(restored(&at("file")), None);
        // A path under a file (ENOTDIR, not ENOENT): no folder can be
        // there, so it is absent, whatever is asked for under it.
        let under = at("file").join("project");
        let not_a_directory = std::fs::metadata(&under).unwrap_err().kind();
        assert_eq!(not_a_directory, std::io::ErrorKind::NotADirectory);
        assert_eq!(restored(&under), None);
        assert_eq!(restored(&under.join("deeper")), None);
        // A link to nothing is absent too.
        std::os::unix::fs::symlink(at("absent"), at("dangling")).unwrap();
        assert_eq!(restored(&at("dangling")), None);

        // A directory, and a link to one: kept, as saved.
        std::fs::create_dir(at("dir")).unwrap();
        assert_eq!(restored(&at("dir")), Some(at("dir")));
        std::os::unix::fs::symlink(at("dir"), at("link")).unwrap();
        assert_eq!(restored(&at("link")), Some(at("link")));

        // A folder that is there and cannot be looked at: kept. The same
        // answer whether or not it exists behind the closed directory, which
        // is the point: nobody can tell from here.
        let closed = at("closed");
        std::fs::create_dir_all(closed.join("project")).unwrap();
        let mode = |mode: u32| {
            std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(mode)).unwrap()
        };
        mode(0o000);
        let denied = |path: &Path| {
            std::fs::metadata(path).is_err_and(|e| e.kind() == std::io::ErrorKind::PermissionDenied)
        };
        // Root reads through any mode: nothing to test there.
        if denied(&closed.join("project")) {
            assert!(!closed.join("project").is_dir(), "what the old rule went by");
            for hidden in [closed.join("project"), closed.join("nothing")] {
                assert_eq!(restored(&hidden), Some(hidden.clone()));
            }
        }
        mode(0o700);
        assert_eq!(restored(&closed.join("project")), Some(closed.join("project")));
        assert_eq!(restored(&closed.join("nothing")), None);
    }

    #[test]
    fn reload_state_path_follows_profile() {
        let d = tempfile::tempdir().unwrap();
        let p = registry::daemon_paths_in(d.path(), Some("work"));
        assert!(reload_state_path(&p).ends_with("daemon-work.reload.json"), "{:?}", reload_state_path(&p));
        let p = registry::daemon_paths_in(d.path(), None);
        assert!(reload_state_path(&p).ends_with("daemon.reload.json"));
    }

    /// Task #444: a reload whose checkpoint did not confirm (`rec == None`)
    /// still carries the explicit `/keepwarm` choice, read from the handle,
    /// instead of resurrecting the config default.
    #[test]
    fn keepwarm_override_survives_an_unconfirmed_checkpoint() {
        use crate::core::config::CacheKeepWarm;
        use crate::session::handle::echo::{meta_for, view_for};
        let id = crate::session::SessionId("kw-reload".into());
        let (handle, ep) = SessionHandle::new(meta_for(&id), view_for());
        assert_eq!(record(&handle, None).cache_keepwarm, None, "no override yet");
        // What the actor writes on `/keepwarm off`.
        *ep.cache_keepwarm.lock().unwrap() = Some(CacheKeepWarm::Off);
        assert_eq!(record(&handle, None).cache_keepwarm.as_deref(), Some("off"));
        *ep.cache_keepwarm.lock().unwrap() = Some(CacheKeepWarm::Hours(6));
        assert_eq!(record(&handle, None).cache_keepwarm.as_deref(), Some("6h"));
    }

    /// Likewise the pin: an unconfirmed checkpoint must not unpin a
    /// session (it would park, and stop holding the daemon's idle exit).
    #[test]
    fn the_pin_survives_an_unconfirmed_checkpoint() {
        use crate::session::handle::echo::{meta_for, view_for};
        let id = crate::session::SessionId("pin-reload".into());
        let (handle, ep) = SessionHandle::new(meta_for(&id), view_for());
        assert!(!record(&handle, None).keep_warm);
        ep.keep_warm.store(true, std::sync::atomic::Ordering::Release);
        let r = record(&handle, None);
        assert!(r.keep_warm && r.config.keep_warm);
    }

    /// T-B4: a session config written before the session memory mode was
    /// removed still carries `memory_mode`. It is read and ignored, in the
    /// config alone and inside a reload state, whatever its value, and the
    /// rest of the config is kept.
    #[test]
    fn an_old_memory_mode_is_read_and_ignored() {
        for v in [
            serde_json::json!("capture_and_recall"),
            serde_json::json!("off"),
            serde_json::json!("recall_forever"),
            serde_json::json!(7),
            serde_json::Value::Null,
        ] {
            let cfg: SessionConfig = serde_json::from_value(serde_json::json!({
                "memory_mode": v,
                "model_override": "claude-sonnet-4-5",
                "keep_warm": true
            }))
            .unwrap_or_else(|e| panic!("memory_mode = {v}: {e}"));
            assert_eq!(cfg.model_override.as_deref(), Some("claude-sonnet-4-5"));
            assert!(cfg.keep_warm);
            let back = serde_json::to_value(&cfg).unwrap();
            assert!(back.get("memory_mode").is_none(), "not written back: {back}");
        }
        let rs: ReloadState = serde_json::from_value(serde_json::json!({
            "generation": 2,
            "written_at": "2026-10-14T18:17:03Z",
            "sessions": [{
                "id": "s1", "journal_id": "s1", "keep_warm": false, "lifecycle": "live",
                "config": { "memory_mode": "capture_and_recall", "cwd": "/srv/chat" }
            }],
            "expected_clients": 0
        }))
        .expect("the reload state still parses");
        assert_eq!(rs.sessions.len(), 1);
        let restored = restore_config(&rs.sessions[0].config, SessionLifecycle::Live, "s1");
        assert!(!restored.await_extensions);
    }

    /// The restore without the hook wait, Parked or not.
    #[test]
    fn a_restore_keeps_the_sessions_memory_choice() {
        let saved = SessionConfig {
            await_extensions: true,
            ..Default::default()
        };
        for lifecycle in [SessionLifecycle::Live, SessionLifecycle::Parked, SessionLifecycle::Parking] {
            let restored = restore_config(&saved, lifecycle, "chat");
            assert!(!restored.await_extensions, "{lifecycle:?}");
        }
    }

    /// `ReloadAborted` reaches a session whose command queue is full (the
    /// actor drains it) instead of being dropped, which would leave the
    /// session fenced until the backstop.
    #[tokio::test]
    async fn reload_aborted_waits_for_room_in_a_full_queue() {
        use crate::session::handle::echo::{meta_for, view_for};
        let id = crate::session::SessionId("abort-full".into());
        let (handle, mut ep) = SessionHandle::new(meta_for(&id), view_for());
        while handle.send(SessionCommand::Save).await.is_ok() {}
        let drain = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            let mut got_abort = false;
            while let Some(a) = ep.cmd_rx.recv().await {
                if matches!(a.cmd, SessionCommand::ReloadAborted) {
                    got_abort = true;
                    break;
                }
            }
            got_abort
        });
        assert!(send_reload_aborted(&handle, Duration::from_secs(5)).await);
        assert!(drain.await.unwrap(), "delivered");
        // No room ever: gives up within its budget, reporting it.
        let id = crate::session::SessionId("abort-stuck".into());
        let (stuck, _ep) = SessionHandle::new(meta_for(&id), view_for());
        while stuck.send(SessionCommand::Save).await.is_ok() {}
        assert!(!send_reload_aborted(&stuck, Duration::from_millis(100)).await);
    }
}