marver 0.0.19

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
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
//! Receiving Claude Code lifecycle hooks and turning them into state changes.
//!
//! Claude Code runs a configured command on each lifecycle event and writes the
//! event as JSON to its stdin. marver generates a settings file per task
//! ([`settings_for_task`]), passes it with `--settings`, and the command
//! forwards the JSON to the daemon over a Unix socket.
//!
//! Three decisions worth stating, because the obvious alternatives are worse:
//!
//! - **The task id is baked into the generated command, not inferred.** The
//!   payload carries `cwd` and `session_id`, but an agent that moves between
//!   worktrees changes `cwd`, and `session_id` is not known until Claude starts.
//!   Since marver writes the settings file itself, it can put the id in the
//!   argument vector where it cannot drift.
//! - **A Unix socket, not the `http` hook type.** No port to collide with, and
//!   access control is the filesystem's job rather than ours.
//! - **Payloads are kept whole.** Known fields are lifted out, but the entire
//!   JSON object is written to the event log, so a field Claude Code adds later
//!   is recorded even though this version does not understand it.

use std::io::{Read, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::time::Duration;

use chrono::{DateTime, Utc};
use serde_json::{Value, json};

use crate::domain::{BlockedKind, TaskState};
use crate::store::{BlockedInfo, Store, Transition};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("malformed hook payload: {0}")]
    Malformed(#[source] serde_json::Error),
    /// The connection misbehaved. Concerns that caller only, never the listener.
    #[error("hook connection rejected: {0}")]
    Rejected(String),
    /// Somebody connected and said nothing — a liveness check, not a hook.
    #[error("liveness probe")]
    Probe,
    /// Another daemon holds the socket. Distinguished from a plain io error
    /// because it is the one failure that is not a fault: the user asked for a
    /// daemon and there is already one, so the answer is to say so and stop,
    /// not to report `Address already in use` and leave them guessing.
    #[error("a marver daemon is already running on {0}")]
    AlreadyRunning(PathBuf),
    /// The socket path exceeded `sockaddr_un`, which is around 100 bytes and
    /// smaller than anything else that accepts a path. Worth its own variant
    /// because the raw message — `path must be shorter than SUN_LEN` — names a
    /// constant from a C header rather than the flag the user passed.
    #[error("the socket path is {len} bytes, past the ~100 a unix socket allows: {path}")]
    SocketPathTooLong { path: PathBuf, len: usize },
    #[error(transparent)]
    Store(#[from] crate::store::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

/// The lifecycle events marver subscribes to.
///
/// Claude Code emits far more than these; the rest are deliberately not
/// configured, since every hook is a subprocess on the agent's critical path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Kind {
    /// A session began or resumed.
    SessionStart,
    /// Claude finished responding. The agent's work is done for now.
    Stop,
    /// A turn ended because of an API error rather than completion.
    StopFailure,
    /// Claude wants the user — a permission prompt, or a question.
    Notification,
    /// The session terminated.
    SessionEnd,
    /// Something marver does not model, kept so it still reaches the log.
    Other(String),
}

impl Kind {
    pub fn parse(name: &str) -> Self {
        match name {
            "SessionStart" => Self::SessionStart,
            "Stop" => Self::Stop,
            "StopFailure" => Self::StopFailure,
            "Notification" => Self::Notification,
            "SessionEnd" => Self::SessionEnd,
            other => Self::Other(other.to_string()),
        }
    }

    /// The hook event names marver configures.
    pub const SUBSCRIBED: &'static [&'static str] = &[
        "SessionStart",
        "Stop",
        "StopFailure",
        "Notification",
        "SessionEnd",
    ];
}

/// One hook event, with the fields marver reads lifted out of the raw JSON.
#[derive(Debug, Clone, PartialEq)]
pub struct Payload {
    pub kind: Kind,
    pub session_id: Option<String>,
    pub cwd: Option<PathBuf>,
    /// Where Claude Code is writing this session's transcript. The only source
    /// of what the agent has spent — no hook carries usage itself.
    pub transcript_path: Option<PathBuf>,
    /// For `Notification`: which sort it is, e.g. `permission_prompt`.
    pub notification_type: Option<String>,
    /// For `Notification`: the text shown to the user.
    pub message: Option<String>,
    /// For `SessionEnd`: `clear`, `logout`, `prompt_input_exit`, `other`, ...
    pub reason: Option<String>,
    /// For `Stop`: the agent's closing message. Worth keeping — it is the
    /// natural summary to show beside a task waiting for review.
    pub last_assistant_message: Option<String>,
    /// The complete payload, preserved verbatim.
    pub raw: Value,
}

impl Payload {
    pub fn from_json(raw: Value) -> Self {
        let text = |key: &str| raw.get(key).and_then(Value::as_str).map(str::to_string);
        Self {
            kind: Kind::parse(
                raw.get("hook_event_name")
                    .and_then(Value::as_str)
                    .unwrap_or(""),
            ),
            session_id: text("session_id"),
            cwd: text("cwd").map(PathBuf::from),
            transcript_path: text("transcript_path").map(PathBuf::from),
            notification_type: text("notification_type"),
            message: text("message"),
            reason: text("reason"),
            last_assistant_message: text("last_assistant_message"),
            raw,
        }
    }

    pub fn parse(bytes: &[u8]) -> Result<Self> {
        serde_json::from_slice(bytes)
            .map(Self::from_json)
            .map_err(Error::Malformed)
    }

    /// Whether a `Notification` means the agent is waiting on the user, and if
    /// so what kind of waiting.
    ///
    /// Only some notifications are requests for attention. `auth_success` and
    /// the elicitation-completed pair are progress reports; treating every
    /// notification as blocking — the obvious implementation — would park a
    /// working task in `blocked` the moment it refreshed its credentials.
    ///
    /// Unrecognised types are assumed to want attention. Over-notifying is
    /// recoverable; an agent stuck invisibly is not.
    fn blocked_kind(&self) -> Option<BlockedKind> {
        match self.notification_type.as_deref() {
            Some("permission_prompt") => Some(BlockedKind::PermissionPrompt),
            Some("idle_prompt") => Some(BlockedKind::Silence),
            Some("elicitation_dialog" | "agent_needs_input") => Some(BlockedKind::Question),
            Some(
                "auth_success"
                | "elicitation_complete"
                | "elicitation_response"
                | "agent_completed",
            ) => None,
            _ => Some(BlockedKind::Question),
        }
    }
}

/// One delivery: a payload plus the task it belongs to.
#[derive(Debug, Clone, PartialEq)]
pub struct Delivery {
    pub task_id: i64,
    pub payload: Payload,
}

impl Delivery {
    /// Wire format: the task id and the raw event, one JSON object.
    pub fn to_json(&self) -> Value {
        json!({ "task_id": self.task_id, "payload": self.payload.raw })
    }

    pub fn from_json(value: Value) -> Option<Self> {
        Some(Self {
            task_id: value.get("task_id")?.as_i64()?,
            payload: Payload::from_json(value.get("payload")?.clone()),
        })
    }
}

/// What a hook implies for a task, given where it currently is.
#[derive(Debug, Clone, PartialEq)]
pub enum Outcome {
    /// The task moved.
    Moved { to: TaskState },
    /// The event was recorded but implied no move, or the move was not legal
    /// from the current state.
    Recorded { reason: &'static str },
}

/// The transition a payload asks for, before legality is considered.
fn requested(payload: &Payload, current: TaskState) -> Option<(TaskState, Transition)> {
    match payload.kind {
        // The scheduler is what starts a task; SessionStart only confirms it.
        Kind::SessionStart => Some((TaskState::Running, Transition::Plain)),
        Kind::Stop => Some((TaskState::AwaitingReview, Transition::Plain)),
        Kind::StopFailure => Some((
            TaskState::Failed,
            Transition::Failed(
                payload
                    .message
                    .clone()
                    .unwrap_or_else(|| "the turn ended with an API error".to_string()),
            ),
        )),
        Kind::Notification => {
            let kind = payload.blocked_kind()?;
            let info = match &payload.message {
                Some(message) => BlockedInfo::with_reason(kind, message.clone()),
                None => BlockedInfo::new(kind),
            };
            Some((TaskState::Blocked, Transition::Blocked(info)))
        }
        // A session ending while work is outstanding means the agent went away
        // without finishing. After review has started it is unremarkable: the
        // user may simply have closed it.
        Kind::SessionEnd => match current {
            TaskState::Running | TaskState::Blocked => Some((
                TaskState::Failed,
                Transition::Failed("the agent's session ended before it finished".to_string()),
            )),
            _ => None,
        },
        Kind::Other(_) => None,
    }
}

/// Record a hook and apply whatever state change it implies.
///
/// The event is logged whether or not it moves the task, so an unmodelled or
/// out-of-order hook still leaves a trace. Legality is left to the store: hooks
/// can arrive in any order, and a `Stop` for a task the user already cancelled
/// must not resurrect it.
pub fn apply(store: &mut Store, delivery: &Delivery, now: DateTime<Utc>) -> Result<Outcome> {
    let task = store.get_task(delivery.task_id)?;

    store.append_event(
        Some(task.id),
        &format!("hook.{}", event_slug(&delivery.payload.kind)),
        &delivery.payload.raw,
        now,
    )?;

    let Some((next, detail)) = requested(&delivery.payload, task.state) else {
        return Ok(Outcome::Recorded {
            reason: "the event implies no state change",
        });
    };

    if next == task.state {
        return Ok(Outcome::Recorded {
            reason: "the task is already in that state",
        });
    }
    if !task.state.can_transition_to(next) {
        return Ok(Outcome::Recorded {
            reason: "the transition is not legal from the current state",
        });
    }

    store.transition(task.id, next, detail, now)?;
    Ok(Outcome::Moved { to: next })
}

fn event_slug(kind: &Kind) -> String {
    match kind {
        Kind::SessionStart => "session-start".into(),
        Kind::Stop => "stop".into(),
        Kind::StopFailure => "stop-failure".into(),
        Kind::Notification => "notification".into(),
        Kind::SessionEnd => "session-end".into(),
        Kind::Other(name) => format!("other.{name}"),
    }
}

// ---- transport ---------------------------------------------------------

/// Whether a daemon is listening on this socket.
///
/// Connecting is the only honest test. The socket *file* outlives the process
/// that made it, so its presence proves nothing — that is why [`Receiver::bind`]
/// has to clear stale ones. A pid file would answer a different question, namely
/// whether some process has that number, which stops being the same question the
/// moment the number is reused.
///
/// The connection is closed without sending anything; the daemon reports that as
/// [`Error::Probe`] and stays quiet.
pub fn is_listening(socket: &Path) -> bool {
    UnixStream::connect(socket).is_ok()
}

/// Send one delivery to the daemon and close.
pub fn send(socket: &Path, delivery: &Delivery) -> Result<()> {
    let mut stream = UnixStream::connect(socket).map_err(|source| Error::Io {
        path: socket.to_path_buf(),
        source,
    })?;
    let body = delivery.to_json().to_string();
    stream
        .write_all(body.as_bytes())
        .and_then(|()| stream.flush())
        .and_then(|()| stream.shutdown(std::net::Shutdown::Write))
        .map_err(|source| Error::Io {
            path: socket.to_path_buf(),
            source,
        })
}

/// Listens for hook deliveries.
/// The largest hook body worth reading. Payloads carry paths, not transcripts.
const MAX_BODY: usize = 1 << 20;

/// How long a connection may take to deliver its body.
///
/// Claude Code gives a hook ten seconds, so a well-behaved one is never near
/// this; the bound exists for the client that connects and then stalls.
const READ_TIMEOUT: Duration = Duration::from_secs(5);

pub struct Receiver {
    listener: UnixListener,
    path: PathBuf,
}

impl Receiver {
    /// Bind the socket, replacing a stale one left by a previous run.
    ///
    /// A socket file outlives the process that made it, so a crash would
    /// otherwise make the daemon permanently unstartable. Removal only happens
    /// when nothing is listening, so a second daemon cannot steal a live one —
    /// it gets [`Error::AlreadyRunning`] instead.
    pub fn bind(path: impl Into<PathBuf>) -> Result<Self> {
        let path = path.into();
        if is_listening(&path) {
            // Checked before the removal below, which is what would otherwise
            // pull the socket out from under a working daemon.
            return Err(Error::AlreadyRunning(path));
        }
        if path.exists() {
            std::fs::remove_file(&path).map_err(|source| Error::Io {
                path: path.clone(),
                source,
            })?;
        }
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|source| Error::Io {
                path: parent.to_path_buf(),
                source,
            })?;
        }
        let listener = UnixListener::bind(&path).map_err(|source| match source.kind() {
            // What `sockaddr_un` overflow surfaces as. Nothing else about a
            // socket path is "invalid input", so this does not swallow a
            // failure that means something else.
            std::io::ErrorKind::InvalidInput => Error::SocketPathTooLong {
                len: path.as_os_str().len(),
                path: path.clone(),
            },
            // Lost a race with another daemon between the check above and here.
            std::io::ErrorKind::AddrInUse => Error::AlreadyRunning(path.clone()),
            _ => Error::Io {
                path: path.clone(),
                source,
            },
        })?;
        Ok(Self { listener, path })
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Accept one connection and read the delivery it carries.
    ///
    /// Only [`Error::Io`] concerns the listener; everything else is that
    /// caller's problem alone. The distinction matters because a broken hook
    /// must not take the daemon's whole event intake down with it, and the
    /// obvious implementation — `read_to_string` — cannot make it: one non-UTF-8
    /// byte surfaces as an io error indistinguishable from a dead listener.
    pub fn accept(&self) -> Result<Delivery> {
        let (mut stream, _) = self.listener.accept().map_err(|source| Error::Io {
            path: self.path.clone(),
            source,
        })?;
        // A client that connects and says nothing would otherwise hold the
        // accept loop forever, and no other hook could be delivered.
        let _ = stream.set_read_timeout(Some(READ_TIMEOUT));

        let mut body = Vec::new();
        // One byte over the limit is enough to notice; the rest is not read.
        std::io::Read::by_ref(&mut stream)
            .take(MAX_BODY as u64 + 1)
            .read_to_end(&mut body)
            .map_err(|source| Error::Rejected(source.to_string()))?;
        if body.len() > MAX_BODY {
            return Err(Error::Rejected(format!(
                "payload is larger than {MAX_BODY} bytes"
            )));
        }
        // A connection that closes without sending anything is how liveness is
        // tested: see `is_listening`. Reported as its own kind so the daemon can
        // stay quiet about it — logging "ignoring hook: malformed" every time
        // someone runs `marver status` would train the reader to skim the log.
        if body.is_empty() {
            return Err(Error::Probe);
        }
        let body = String::from_utf8(body)
            .map_err(|_| Error::Rejected("payload is not valid UTF-8".to_string()))?;

        let value: Value = serde_json::from_str(&body).map_err(Error::Malformed)?;
        Delivery::from_json(value).ok_or_else(|| {
            Error::Malformed(serde::de::Error::custom(
                "missing task_id or payload".to_string(),
            ))
        })
    }
}

impl Drop for Receiver {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

// ---- settings generation -----------------------------------------------

/// The Claude Code settings a task's agent runs with.
///
/// Every subscribed event runs the same command with the task id fixed in the
/// argument vector. `args` is set deliberately: that selects exec form, so no
/// shell tokenises a path that might contain spaces.
pub fn settings_for_task(task_id: i64, marver_bin: &Path, socket: &Path) -> Value {
    let entry = json!({
        "hooks": [{
            "type": "command",
            "command": marver_bin.to_string_lossy(),
            "args": [
                "hook",
                "--task", task_id.to_string(),
                "--socket", socket.to_string_lossy(),
            ],
            "timeout": 10
        }]
    });

    let mut hooks = serde_json::Map::new();
    for event in Kind::SUBSCRIBED {
        hooks.insert((*event).to_string(), json!([entry]));
    }
    json!({ "hooks": Value::Object(hooks) })
}

/// Write a task's settings file and return its path, for `claude --settings`.
pub fn write_settings(
    dir: &Path,
    task_id: i64,
    marver_bin: &Path,
    socket: &Path,
) -> Result<PathBuf> {
    std::fs::create_dir_all(dir).map_err(|source| Error::Io {
        path: dir.to_path_buf(),
        source,
    })?;
    let path = dir.join("claude-settings.json");
    let body = serde_json::to_string_pretty(&settings_for_task(task_id, marver_bin, socket))
        .map_err(Error::Malformed)?;
    std::fs::write(&path, body).map_err(|source| Error::Io {
        path: path.clone(),
        source,
    })?;
    Ok(path)
}

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

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("valid timestamp")
    }

    fn store_with_task() -> (Store, i64) {
        let mut store = Store::open_in_memory().unwrap();
        let task = store
            .create_task("t", "do it", Path::new("/tmp/tasks"), &[], at(0))
            .unwrap();
        let id = task.id;
        (store, id)
    }

    fn payload(kind: &str, extra: Value) -> Payload {
        let mut raw = json!({
            "session_id": "abc123",
            "transcript_path": "/tmp/t.jsonl",
            "cwd": "/tmp/work",
            "permission_mode": "default",
            "hook_event_name": kind,
        });
        if let (Value::Object(base), Value::Object(more)) = (&mut raw, extra) {
            base.extend(more);
        }
        Payload::from_json(raw)
    }

    fn deliver(store: &mut Store, id: i64, p: Payload, secs: i64) -> Outcome {
        apply(
            store,
            &Delivery {
                task_id: id,
                payload: p,
            },
            at(secs),
        )
        .unwrap()
    }

    fn start(store: &mut Store, id: i64) {
        store
            .transition(id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();
    }

    #[test]
    fn parses_the_documented_common_fields() {
        let p = payload("Stop", json!({}));
        assert_eq!(p.kind, Kind::Stop);
        assert_eq!(p.session_id.as_deref(), Some("abc123"));
        assert_eq!(p.cwd.as_deref(), Some(Path::new("/tmp/work")));
    }

    /// Payloads captured from Claude Code 2.1.221, not invented.
    #[test]
    fn parses_payloads_observed_from_a_real_session() {
        let start = Payload::from_json(json!({
            "cwd": "/tmp/w", "hook_event_name": "SessionStart",
            "session_id": "s1", "source": "startup",
            "transcript_path": "/tmp/t.jsonl"
        }));
        assert_eq!(start.kind, Kind::SessionStart);
        // SessionStart carries no permission_mode; absence must not break it.
        assert_eq!(start.raw["source"], "startup");

        let stop = Payload::from_json(json!({
            "cwd": "/tmp/w", "hook_event_name": "Stop", "session_id": "s1",
            "permission_mode": "auto", "stop_hook_active": false,
            "last_assistant_message": "PONG", "stop_reason": "end_turn"
        }));
        assert_eq!(stop.kind, Kind::Stop);
        assert_eq!(stop.last_assistant_message.as_deref(), Some("PONG"));

        let end = Payload::from_json(json!({
            "cwd": "/tmp/w", "hook_event_name": "SessionEnd",
            "session_id": "s1", "reason": "other"
        }));
        assert_eq!(end.kind, Kind::SessionEnd);
        assert_eq!(end.reason.as_deref(), Some("other"));
    }

    #[test]
    fn an_unmodelled_event_is_kept_not_dropped() {
        let p = payload("PreToolUse", json!({"tool_name": "Bash"}));
        assert_eq!(p.kind, Kind::Other("PreToolUse".into()));
        assert_eq!(p.raw["tool_name"], "Bash");
    }

    #[test]
    fn stop_sends_a_running_task_to_review() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        let outcome = deliver(&mut store, id, payload("Stop", json!({})), 2);
        assert_eq!(
            outcome,
            Outcome::Moved {
                to: TaskState::AwaitingReview
            }
        );
        assert_eq!(store.get_task(id).unwrap().state, TaskState::AwaitingReview);
    }

    #[test]
    fn a_permission_prompt_blocks_with_the_right_kind() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(
            &mut store,
            id,
            payload(
                "Notification",
                json!({
                    "notification_type": "permission_prompt",
                    "message": "Claude needs permission to edit src/main.rs"
                }),
            ),
            2,
        );

        let task = store.get_task(id).unwrap();
        assert_eq!(task.state, TaskState::Blocked);
        assert_eq!(task.blocked_kind, Some(BlockedKind::PermissionPrompt));
        assert_eq!(
            task.blocked_reason.as_deref(),
            Some("Claude needs permission to edit src/main.rs")
        );
    }

    #[test]
    fn notification_types_map_to_the_right_blocked_kind() {
        for (notification, expected) in [
            ("permission_prompt", BlockedKind::PermissionPrompt),
            ("idle_prompt", BlockedKind::Silence),
            ("elicitation_dialog", BlockedKind::Question),
            ("agent_needs_input", BlockedKind::Question),
        ] {
            let (mut store, id) = store_with_task();
            start(&mut store, id);
            deliver(
                &mut store,
                id,
                payload("Notification", json!({ "notification_type": notification })),
                2,
            );
            let task = store.get_task(id).unwrap();
            assert_eq!(task.state, TaskState::Blocked, "for {notification}");
            assert_eq!(task.blocked_kind, Some(expected), "for {notification}");
        }
    }

    #[test]
    fn informational_notifications_do_not_block() {
        // The bug this guards: treating every Notification as blocking parks a
        // working task the moment it refreshes credentials.
        for notification in [
            "auth_success",
            "elicitation_complete",
            "elicitation_response",
            "agent_completed",
        ] {
            let (mut store, id) = store_with_task();
            start(&mut store, id);
            let outcome = deliver(
                &mut store,
                id,
                payload("Notification", json!({ "notification_type": notification })),
                2,
            );
            assert!(
                matches!(outcome, Outcome::Recorded { .. }),
                "{notification} should not block"
            );
            assert_eq!(
                store.get_task(id).unwrap().state,
                TaskState::Running,
                "{notification} should leave the task working"
            );
        }
    }

    #[test]
    fn a_task_that_hit_a_permission_prompt_still_reaches_review() {
        // The whole sequence, as it really arrives: the agent asks to run
        // something, the user approves it in the pane — which emits no hook —
        // and the agent then finishes. Nothing ever reports a return to
        // running, so `Stop` has to be legal from `blocked` or the work is lost.
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(
            &mut store,
            id,
            payload(
                "Notification",
                json!({"notification_type": "permission_prompt"}),
            ),
            2,
        );
        assert_eq!(store.get_task(id).unwrap().state, TaskState::Blocked);

        let outcome = deliver(&mut store, id, payload("Stop", json!({})), 3);
        assert_eq!(
            outcome,
            Outcome::Moved {
                to: TaskState::AwaitingReview
            },
            "a blocked agent that finishes must offer its diff, not strand"
        );
        let task = store.get_task(id).unwrap();
        assert_eq!(task.state, TaskState::AwaitingReview);
        assert_eq!(task.blocked_kind, None, "the block must be cleared");
    }

    #[test]
    fn an_idle_prompt_arriving_before_stop_does_not_trap_the_task() {
        // `idle_prompt` means "done, waiting for your next prompt", so it is
        // emitted alongside `Stop` at the end of an ordinary turn. They are two
        // separate connections with no ordering, and this is the losing race.
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(
            &mut store,
            id,
            payload("Notification", json!({"notification_type": "idle_prompt"})),
            2,
        );
        deliver(&mut store, id, payload("Stop", json!({})), 3);
        assert_eq!(
            store.get_task(id).unwrap().state,
            TaskState::AwaitingReview,
            "the ordinary end of every turn must not depend on hook ordering"
        );
    }

    #[test]
    fn an_unrecognised_notification_still_blocks() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(
            &mut store,
            id,
            payload(
                "Notification",
                json!({"notification_type": "something_new"}),
            ),
            2,
        );
        let task = store.get_task(id).unwrap();
        assert_eq!(
            task.state,
            TaskState::Blocked,
            "an unknown notification still means the agent wants the user"
        );
        assert_eq!(task.blocked_kind, Some(BlockedKind::Question));
    }

    #[test]
    fn stop_failure_fails_the_task_with_a_reason() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(
            &mut store,
            id,
            payload("StopFailure", json!({"message": "overloaded"})),
            2,
        );
        let task = store.get_task(id).unwrap();
        assert_eq!(task.state, TaskState::Failed);
        assert_eq!(task.failure_reason.as_deref(), Some("overloaded"));
    }

    #[test]
    fn stop_failure_without_a_message_still_records_one() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(&mut store, id, payload("StopFailure", json!({})), 2);
        // The schema requires a reason in the failed state.
        assert!(store.get_task(id).unwrap().failure_reason.is_some());
    }

    #[test]
    fn session_end_fails_a_task_that_was_still_working() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(&mut store, id, payload("SessionEnd", json!({})), 2);
        assert_eq!(store.get_task(id).unwrap().state, TaskState::Failed);
    }

    #[test]
    fn session_end_after_review_started_is_unremarkable() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(&mut store, id, payload("Stop", json!({})), 2);
        let outcome = deliver(&mut store, id, payload("SessionEnd", json!({})), 3);

        assert!(matches!(outcome, Outcome::Recorded { .. }));
        assert_eq!(
            store.get_task(id).unwrap().state,
            TaskState::AwaitingReview,
            "closing a finished session must not fail the task"
        );
    }

    #[test]
    fn blocking_then_resuming_round_trips() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(
            &mut store,
            id,
            payload(
                "Notification",
                json!({"notification_type": "permission_prompt"}),
            ),
            2,
        );
        // Answering the prompt puts the agent back to work.
        deliver(&mut store, id, payload("SessionStart", json!({})), 3);
        let task = store.get_task(id).unwrap();
        assert_eq!(task.state, TaskState::Running);
        assert_eq!(task.blocked_kind, None);
    }

    #[test]
    fn a_late_hook_cannot_resurrect_a_cancelled_task() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        store
            .transition(id, TaskState::Cancelled, Transition::Plain, at(2))
            .unwrap();

        let outcome = deliver(&mut store, id, payload("Stop", json!({})), 3);
        assert!(matches!(outcome, Outcome::Recorded { .. }));
        assert_eq!(store.get_task(id).unwrap().state, TaskState::Cancelled);
    }

    #[test]
    fn a_repeated_hook_is_not_an_error() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(&mut store, id, payload("Stop", json!({})), 2);
        let again = deliver(&mut store, id, payload("Stop", json!({})), 3);
        assert!(matches!(again, Outcome::Recorded { .. }));
    }

    #[test]
    fn every_hook_is_logged_even_when_it_changes_nothing() {
        let (mut store, id) = store_with_task();
        deliver(&mut store, id, payload("PreToolUse", json!({})), 2);
        let kinds: Vec<String> = store
            .list_events(id)
            .unwrap()
            .into_iter()
            .map(|e| e.kind)
            .collect();
        assert!(
            kinds.contains(&"hook.other.PreToolUse".to_string()),
            "got {kinds:?}"
        );
    }

    #[test]
    fn the_raw_payload_survives_into_the_log() {
        let (mut store, id) = store_with_task();
        start(&mut store, id);
        deliver(
            &mut store,
            id,
            payload("Stop", json!({"a_field_marver_ignores": 42})),
            2,
        );
        let events = store.list_events(id).unwrap();
        let hook = events.iter().find(|e| e.kind == "hook.stop").unwrap();
        assert_eq!(hook.payload["a_field_marver_ignores"], 42);
        assert_eq!(hook.payload["session_id"], "abc123");
    }

    // ---- transport ----

    #[test]
    fn a_delivery_survives_the_socket() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        let receiver = Receiver::bind(&socket).unwrap();

        let sent = Delivery {
            task_id: 42,
            payload: payload("Stop", json!({"extra": "kept"})),
        };
        let to_send = sent.clone();
        let path = socket.clone();
        let sender = std::thread::spawn(move || send(&path, &to_send).unwrap());

        let received = receiver.accept().unwrap();
        sender.join().unwrap();

        assert_eq!(received.task_id, 42);
        assert_eq!(received.payload.kind, Kind::Stop);
        assert_eq!(received.payload.raw["extra"], "kept");
    }

    /// Connect, write `body` verbatim, and go away.
    fn raw_send(path: &Path, body: &[u8]) {
        let mut stream = UnixStream::connect(path).unwrap();
        stream.write_all(body).unwrap();
    }

    #[test]
    fn one_bad_byte_does_not_stop_the_listener() {
        // `printf '\xff' | nc -U <socket>` used to end hook delivery for good:
        // the read failed as an io error, the daemon treated that as the
        // listener dying, and `Drop` then unlinked the socket file. Silently —
        // every later hook exits 0 and nobody reads its stderr.
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        let receiver = Receiver::bind(&socket).unwrap();

        let path = socket.clone();
        std::thread::spawn(move || raw_send(&path, &[0xff]));
        let err = receiver.accept().unwrap_err();
        assert!(
            matches!(err, Error::Rejected(_)),
            "a bad byte concerns that caller only, got {err:?}"
        );

        // And the listener is still good for the next, valid hook.
        let good = Delivery {
            task_id: 7,
            payload: payload("Stop", json!({})),
        };
        let to_send = good.clone();
        let path = socket.clone();
        std::thread::spawn(move || send(&path, &to_send).unwrap());
        assert_eq!(receiver.accept().unwrap().task_id, 7);
    }

    #[test]
    fn an_oversized_payload_is_rejected_rather_than_buffered() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        let receiver = Receiver::bind(&socket).unwrap();

        let path = socket.clone();
        std::thread::spawn(move || {
            // Any local process could otherwise drive the daemon to OOM.
            let _ = UnixStream::connect(&path).map(|mut s| s.write_all(&vec![b'x'; MAX_BODY * 2]));
        });
        assert!(matches!(receiver.accept(), Err(Error::Rejected(_))));
    }

    #[test]
    fn a_silent_client_does_not_wedge_the_listener() {
        // One `nc -U` left open used to freeze the daemon's entire event
        // intake: accept reads inline, single-threaded, with no timeout.
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        let receiver = Receiver::bind(&socket).unwrap();

        // Connect and hold it open without sending anything.
        let idle = UnixStream::connect(&socket).unwrap();
        let start = std::time::Instant::now();
        assert!(matches!(receiver.accept(), Err(Error::Rejected(_))));
        assert!(
            start.elapsed() < READ_TIMEOUT * 2,
            "the read must time out, not block forever"
        );
        drop(idle);

        let good = Delivery {
            task_id: 3,
            payload: payload("Stop", json!({})),
        };
        let to_send = good.clone();
        let path = socket.clone();
        std::thread::spawn(move || send(&path, &to_send).unwrap());
        assert_eq!(
            receiver.accept().unwrap().task_id,
            3,
            "hooks must flow again once the stalled client is dealt with"
        );
    }

    #[test]
    fn a_stale_socket_does_not_block_startup() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        {
            let _first = Receiver::bind(&socket).unwrap();
            // Leave the file behind as a crash would.
            std::fs::write(&socket, "").ok();
        }
        std::fs::write(&socket, "").ok();
        // A crashed daemon must not make marver permanently unstartable.
        let again = Receiver::bind(&socket);
        assert!(again.is_ok(), "{:?}", again.err());
    }

    #[test]
    fn a_live_socket_is_not_stolen_and_says_why() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        let _first = Receiver::bind(&socket).unwrap();

        let Err(err) = Receiver::bind(&socket) else {
            panic!("a second bind must fail");
        };

        // Not merely an error: the one failure here that is not a fault. Left as
        // a bare io error it reached the user as `Address already in use`, which
        // names a socket rather than the daemon they already have.
        assert!(matches!(err, Error::AlreadyRunning(_)), "got {err:?}");
        assert!(
            err.to_string().contains("already running"),
            "{}",
            err.to_string()
        );
    }

    #[test]
    fn listening_is_answered_by_connecting_not_by_the_file_existing() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        assert!(!is_listening(&socket), "nothing is bound yet");

        {
            let _receiver = Receiver::bind(&socket).unwrap();
            assert!(is_listening(&socket));
        }

        // A crash leaves the file behind. Its presence must not read as a
        // running daemon, or nothing would ever start one again.
        std::fs::write(&socket, "").ok();
        assert!(
            !is_listening(&socket),
            "a leftover socket file is not a daemon"
        );
    }

    #[test]
    fn a_probe_is_told_apart_from_a_broken_hook() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        let receiver = Receiver::bind(&socket).unwrap();

        let probe = std::thread::spawn(move || {
            // Exactly what `is_listening` does: connect, say nothing, close.
            let _ = UnixStream::connect(&socket);
        });
        let err = receiver.accept().expect_err("a probe carries no delivery");
        probe.join().unwrap();

        // Reported as its own kind so the daemon can stay silent. As
        // `Malformed` it would leave a complaint in the log on every status
        // check, and a log full of routine complaints stops being read.
        assert!(matches!(err, Error::Probe), "got {err:?}");
    }

    #[test]
    fn the_socket_is_removed_on_shutdown() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        {
            let _receiver = Receiver::bind(&socket).unwrap();
            assert!(socket.exists());
        }
        assert!(!socket.exists());
    }

    #[test]
    fn a_malformed_body_is_rejected_without_killing_the_listener() {
        let tmp = TempDir::new().unwrap();
        let socket = tmp.path().join("hooks.sock");
        let receiver = Receiver::bind(&socket).unwrap();

        let path = socket.clone();
        std::thread::spawn(move || {
            let mut s = UnixStream::connect(&path).unwrap();
            s.write_all(b"not json at all").ok();
        });
        assert!(matches!(receiver.accept(), Err(Error::Malformed(_))));

        // The listener still works afterwards.
        let good = Delivery {
            task_id: 1,
            payload: payload("Stop", json!({})),
        };
        let path = socket.clone();
        let to_send = good.clone();
        std::thread::spawn(move || send(&path, &to_send).unwrap());
        assert_eq!(receiver.accept().unwrap().task_id, 1);
    }

    // ---- settings ----

    #[test]
    fn generated_settings_subscribe_to_every_modelled_event() {
        let settings = settings_for_task(7, Path::new("/usr/local/bin/marver"), Path::new("/s"));
        let hooks = settings["hooks"].as_object().unwrap();
        for event in Kind::SUBSCRIBED {
            assert!(hooks.contains_key(*event), "{event} missing");
        }
        assert_eq!(hooks.len(), Kind::SUBSCRIBED.len());
    }

    #[test]
    fn the_task_id_is_fixed_in_the_argument_vector() {
        let settings = settings_for_task(7, Path::new("/bin/marver"), Path::new("/run/m.sock"));
        let args = &settings["hooks"]["Stop"][0]["hooks"][0]["args"];
        assert_eq!(
            args.as_array().unwrap(),
            &json!(["hook", "--task", "7", "--socket", "/run/m.sock"])
                .as_array()
                .unwrap()
                .clone(),
            "the id must not have to be inferred from cwd"
        );
        // Exec form: args present means no shell splits the path.
        assert_eq!(
            settings["hooks"]["Stop"][0]["hooks"][0]["command"],
            "/bin/marver"
        );
    }

    #[test]
    fn settings_are_written_where_claude_can_be_pointed_at_them() {
        let tmp = TempDir::new().unwrap();
        let path = write_settings(
            tmp.path(),
            3,
            Path::new("/bin/marver"),
            Path::new("/run/m.sock"),
        )
        .unwrap();

        assert!(path.exists());
        let parsed: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(
            parsed["hooks"]["Notification"][0]["hooks"][0]["args"][2],
            "3"
        );
    }
}