necro 0.1.0

File-board task manager for agents
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
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use rustix::fs::{FlockOperation, flock};

use futures::Stream;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tokio::io::AsyncReadExt;
use tokio::process::Command;

use crate::board;
use crate::error::Error;
use crate::task::{Lane, is_valid_id};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum WatchKind {
    Enter,
    Exit,
}

impl WatchKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Enter => "enter",
            Self::Exit => "exit",
        }
    }

    fn verb(self) -> &'static str {
        match self {
            Self::Enter => "entered",
            Self::Exit => "exited",
        }
    }

    pub fn parse_filter(value: &str) -> Result<&'static [WatchKind], Error> {
        match value {
            "enter" => Ok(&[WatchKind::Enter]),
            "exit" => Ok(&[WatchKind::Exit]),
            "all" => Ok(&[WatchKind::Enter, WatchKind::Exit]),
            other => Err(Error::InvalidEvent(other.to_string())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct WatchEvent {
    pub event: WatchKind,
    pub lane: Lane,
    pub id: String,
    pub path: String,
    pub agents_path: Option<String>,
    pub agents: Option<String>,
    pub exec_exit: Option<i32>,
    pub agent_output: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BoardSnapshot {
    lanes: BTreeMap<Lane, BTreeSet<String>>,
}

impl BoardSnapshot {
    pub fn lane(&self, lane: Lane) -> BTreeSet<String> {
        self.lanes.get(&lane).cloned().unwrap_or_default()
    }
}

#[derive(Debug, Clone)]
pub struct WatchFilter {
    pub lanes: Vec<Lane>,
    pub kinds: Vec<WatchKind>,
}

impl WatchFilter {
    pub fn matches(&self, event: &WatchEvent) -> bool {
        (self.lanes.is_empty() || self.lanes.contains(&event.lane))
            && self.kinds.contains(&event.event)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentKind {
    Grok,
    Claude,
}

impl AgentKind {
    pub fn parse(value: &str) -> Result<Self, Error> {
        match value {
            "grok" => Ok(Self::Grok),
            "claude" => Ok(Self::Claude),
            other => Err(Error::InvalidAgent(other.to_string())),
        }
    }

    pub fn program(self) -> &'static str {
        match self {
            Self::Grok => "grok",
            Self::Claude => "claude",
        }
    }

    pub fn args(self, prompt: &str) -> Vec<String> {
        match self {
            Self::Grok => vec![
                "-p".to_string(),
                prompt.to_string(),
                "--always-approve".to_string(),
                "--output-format".to_string(),
                "plain".to_string(),
            ],
            Self::Claude => vec![
                "-p".to_string(),
                prompt.to_string(),
                "--dangerously-skip-permissions".to_string(),
            ],
        }
    }
}

/// Exclusive lock for one `--agent` watcher per board.
#[derive(Debug)]
pub struct AgentWatchLock {
    _file: fs::File,
}

impl AgentWatchLock {
    pub fn path(root: &Path) -> PathBuf {
        board::board_dir(root).join("agent-watch.lock")
    }

    pub fn acquire(root: &Path) -> Result<Self, Error> {
        let file = fs::OpenOptions::new()
            .create(true)
            .write(true)
            .open(Self::path(root))?;
        match flock(&file, FlockOperation::NonBlockingLockExclusive) {
            Ok(()) => Ok(Self { _file: file }),
            Err(errno) => {
                let io_err = std::io::Error::from(errno);
                if io_err.kind() == ErrorKind::WouldBlock {
                    Err(Error::AgentWatcherLocked)
                } else {
                    Err(Error::Io(io_err))
                }
            }
        }
    }
}

pub fn agent_prompt(root: &Path, event: &WatchEvent) -> String {
    let task = fs::read_to_string(&event.path).unwrap_or_default();
    let agents = event.agents.as_deref().unwrap_or("(none)");
    let board_section = match board::load_board_agents(root) {
        Some(body) => format!("# Board AGENTS.md\n\n{body}\n\n"),
        None => String::new(),
    };
    format!(
        "A necro task {verb} the {lane} lane. Follow the lane instructions, then complete the task. Use necro to move the task when finished.\n\n\
Event: {event}\n\
Lane: {lane}\n\
Task ID: {id}\n\
Task path: {path}\n\n\
{board_section}\
# Lane AGENTS.md\n\n\
{agents}\n\n\
# Task\n\n\
{task}",
        verb = event.event.verb(),
        event = event.event.as_str(),
        lane = event.lane.as_str(),
        id = event.id,
        path = event.path,
        board_section = board_section,
        agents = agents,
        task = task,
    )
}

pub fn snapshot(root: &Path) -> Result<BoardSnapshot, Error> {
    let mut lanes = BTreeMap::new();
    for lane in Lane::all() {
        let mut ids = BTreeSet::new();
        let dir = board::lane_dir(root, *lane);
        for entry in fs::read_dir(dir)? {
            let path = entry?.path();
            if path.extension().and_then(|e| e.to_str()) != Some("md") {
                continue;
            }
            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
                continue;
            };
            if is_valid_id(stem) {
                ids.insert(stem.to_string());
            }
        }
        lanes.insert(*lane, ids);
    }
    Ok(BoardSnapshot { lanes })
}

pub fn diff(root: &Path, old: &BoardSnapshot, new: &BoardSnapshot) -> Vec<WatchEvent> {
    let mut events = Vec::new();
    for lane in Lane::all() {
        let before = old.lane(*lane);
        let after = new.lane(*lane);
        for id in before.difference(&after) {
            events.push(event(root, WatchKind::Exit, *lane, id));
        }
        for id in after.difference(&before) {
            events.push(event(root, WatchKind::Enter, *lane, id));
        }
    }
    events
}

pub fn existing_enters(root: &Path, snap: &BoardSnapshot) -> Vec<WatchEvent> {
    let empty = BoardSnapshot::default();
    diff(root, &empty, snap)
        .into_iter()
        .filter(|event| event.event == WatchKind::Enter)
        .collect()
}

fn event(root: &Path, kind: WatchKind, lane: Lane, id: &str) -> WatchEvent {
    let (agents_path, agents) = board::load_agents(root, lane);
    WatchEvent {
        event: kind,
        lane,
        id: id.to_string(),
        path: board::lane_dir(root, lane)
            .join(format!("{id}.md"))
            .to_string_lossy()
            .into_owned(),
        agents_path,
        agents,
        exec_exit: None,
        agent_output: None,
    }
}

pub async fn run_exec(root: &Path, script: &str, event: &mut WatchEvent) -> Result<(), Error> {
    let mut command = Command::new("sh");
    command
        .arg("-c")
        .arg(script)
        .env("NECRO_EVENT", event.event.as_str())
        .env("NECRO_LANE", event.lane.as_str())
        .env("NECRO_ID", &event.id)
        .env("NECRO_PATH", &event.path)
        .env("NECRO_ROOT", root.as_os_str())
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit());
    if let Some(path) = &event.agents_path {
        command.env("NECRO_AGENTS_PATH", path);
    }
    if let Some(body) = &event.agents {
        command.env("NECRO_AGENTS", body);
    }
    let status = command.status().await?;
    let code = status.code().unwrap_or(1);
    event.exec_exit = Some(code);
    if code != 0 {
        return Err(Error::ExecFailed {
            id: event.id.clone(),
            status: code,
        });
    }
    Ok(())
}

pub async fn run_agent(root: &Path, kind: AgentKind, event: &mut WatchEvent) -> Result<(), Error> {
    run_agent_bin(root, Path::new(kind.program()), kind, event).await
}

fn todo_task_path(root: &Path, id: &str) -> PathBuf {
    board::lane_dir(root, Lane::Todo).join(format!("{id}.md"))
}

fn task_still_in_todo(root: &Path, id: &str) -> bool {
    todo_task_path(root, id).is_file()
}

/// Claim a todo enter (`necro start`) before spawning. Returns `false` when the
/// task has left todo (started, done, or dropped) so the agent is not started.
async fn run_claimed_agent(
    root: &Path,
    program: &Path,
    kind: AgentKind,
    event: &mut WatchEvent,
) -> Result<bool, Error> {
    run_claimed_agent_between(root, program, kind, event, |_, _| {}).await
}

async fn run_claimed_agent_between(
    root: &Path,
    program: &Path,
    kind: AgentKind,
    event: &mut WatchEvent,
    between_detect_and_spawn: impl FnOnce(&Path, &str),
) -> Result<bool, Error> {
    if event.event == WatchKind::Enter && event.lane == Lane::Todo {
        between_detect_and_spawn(root, &event.id);
        if !task_still_in_todo(root, &event.id) {
            return Ok(false);
        }
        match crate::store::Store::open(root)?.claim(&event.id)? {
            Some(task) => event.path = task.path,
            None => return Ok(false),
        }
    }
    run_agent_bin(root, program, kind, event).await?;
    Ok(true)
}

async fn run_agent_bin(
    root: &Path,
    program: &Path,
    kind: AgentKind,
    event: &mut WatchEvent,
) -> Result<(), Error> {
    let prompt = agent_prompt(root, event);
    let mut command = Command::new(program);
    command
        .args(kind.args(&prompt))
        .current_dir(root)
        .env("NECRO_EVENT", event.event.as_str())
        .env("NECRO_LANE", event.lane.as_str())
        .env("NECRO_ID", &event.id)
        .env("NECRO_PATH", &event.path)
        .env("NECRO_ROOT", root.as_os_str())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit());
    if let Some(path) = &event.agents_path {
        command.env("NECRO_AGENTS_PATH", path);
    }
    if let Some(body) = &event.agents {
        command.env("NECRO_AGENTS", body);
    }
    let mut child = command.spawn()?;
    let mut stdout = child
        .stdout
        .take()
        .ok_or_else(|| std::io::Error::other("agent stdout was not piped"))?;
    stream_agent_stdout(root, event, &mut stdout).await?;
    let status = child.wait().await?;
    let code = status.code().unwrap_or(1);
    event.exec_exit = Some(code);
    Ok(())
}

async fn stream_agent_stdout(
    root: &Path,
    event: &mut WatchEvent,
    stdout: &mut (impl AsyncReadExt + Unpin),
) -> Result<(), Error> {
    let mut buf = [0u8; 4096];
    let mut captured = Vec::new();
    let mut started = false;
    loop {
        let n = stdout.read(&mut buf).await?;
        if n == 0 {
            break;
        }
        let chunk = &buf[..n];
        captured.extend_from_slice(chunk);
        let _ = std::io::Write::write_all(&mut std::io::stdout(), chunk);
        let store = crate::store::Store::open(root)?;
        if !started {
            store.append(&event.id, b"\n")?;
            started = true;
        } else if !captured[..captured.len() - n].ends_with(b"\n") && !chunk.starts_with(b"\n") {
            store.append(&event.id, b"\n")?;
        }
        store.append(&event.id, chunk)?;
    }
    if !captured.is_empty() && !captured.ends_with(b"\n") {
        let _ = crate::store::Store::open(root)?.append(&event.id, b"\n");
    }
    let text = String::from_utf8_lossy(&captured);
    let text = text.trim_end();
    if !text.is_empty() {
        event.agent_output = Some(text.to_string());
    }
    Ok(())
}

async fn apply_hooks(
    root: &Path,
    exec: &Option<String>,
    agent: Option<AgentKind>,
    event: &mut WatchEvent,
) -> Result<(), Error> {
    if let Some(script) = exec {
        run_exec(root, script, event).await?;
    }
    if let Some(kind) = agent {
        run_claimed_agent(root, Path::new(kind.program()), kind, event).await?;
    }
    Ok(())
}

pub async fn wait_once(
    root: PathBuf,
    filter: WatchFilter,
    existing: bool,
    interval: Duration,
    exec: Option<String>,
    agent: Option<AgentKind>,
) -> Result<WatchEvent, Error> {
    let mut snap = snapshot(&root)?;
    if existing {
        for mut event in existing_enters(&root, &snap) {
            if filter.matches(&event) {
                apply_hooks(&root, &exec, agent, &mut event).await?;
                return Ok(event);
            }
        }
    }
    loop {
        tokio::time::sleep(interval).await;
        let next = snapshot(&root)?;
        let events = diff(&root, &snap, &next);
        snap = next;
        for mut event in events {
            if !filter.matches(&event) {
                continue;
            }
            apply_hooks(&root, &exec, agent, &mut event).await?;
            return Ok(event);
        }
    }
}

pub fn watch_stream(
    root: PathBuf,
    filter: WatchFilter,
    existing: bool,
    interval: Duration,
    exec: Option<String>,
    agent: Option<AgentKind>,
    lock: Option<AgentWatchLock>,
) -> impl Stream<Item = serde_json::Value> {
    async_stream::stream! {
        let _lock = lock;
        let Ok(mut snap) = snapshot(&root) else {
            return;
        };
        if existing {
            for mut event in existing_enters(&root, &snap) {
                if !filter.matches(&event) {
                    continue;
                }
                let _ = apply_hooks(&root, &exec, agent, &mut event).await;
                if let Ok(value) = serde_json::to_value(&event) {
                    yield value;
                }
            }
        }
        loop {
            tokio::time::sleep(interval).await;
            let Ok(next) = snapshot(&root) else {
                continue;
            };
            let events = diff(&root, &snap, &next);
            snap = next;
            for mut event in events {
                if !filter.matches(&event) {
                    continue;
                }
                let _ = apply_hooks(&root, &exec, agent, &mut event).await;
                if let Ok(value) = serde_json::to_value(&event) {
                    yield value;
                }
            }
        }
    }
}

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

    fn primed() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        board::init(dir.path()).unwrap();
        let root = dir.path().canonicalize().unwrap();
        (dir, root)
    }

    #[test]
    fn agent_watch_lock_succeeds_when_free() {
        let (_dir, root) = primed();
        AgentWatchLock::acquire(&root).unwrap();
        assert!(AgentWatchLock::path(&root).is_file());
    }

    #[test]
    fn agent_watch_lock_released_on_drop() {
        let (_dir, root) = primed();
        let lock = AgentWatchLock::acquire(&root).unwrap();
        drop(lock);
        AgentWatchLock::acquire(&root).unwrap();
    }

    #[test]
    fn agent_watch_lock_fails_when_held() {
        let (_dir, root) = primed();
        if let Ok(hold) = std::env::var("NECRO_TEST_HOLD_AGENT_LOCK") {
            let _lock = AgentWatchLock::acquire(Path::new(&hold)).unwrap();
            println!("locked");
            std::thread::sleep(std::time::Duration::from_secs(30));
            return;
        }

        let exe = std::env::current_exe().unwrap();
        let mut child = std::process::Command::new(&exe)
            .args([
                "--exact",
                "watch::tests::agent_watch_lock_fails_when_held",
                "--nocapture",
            ])
            .env("NECRO_TEST_HOLD_AGENT_LOCK", &root)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .spawn()
            .unwrap();
        let stdout = child.stdout.take().unwrap();
        let mut reader = std::io::BufReader::new(stdout);
        let mut line = String::new();
        let start = std::time::Instant::now();
        loop {
            line.clear();
            if std::io::BufRead::read_line(&mut reader, &mut line).unwrap() == 0 {
                let _ = child.kill();
                let _ = child.wait();
                panic!("holder exited before locking");
            }
            if line.trim() == "locked" {
                break;
            }
            assert!(
                start.elapsed() < std::time::Duration::from_secs(5),
                "holder did not lock"
            );
        }
        let err = AgentWatchLock::acquire(&root).unwrap_err();
        assert_eq!(err.code(), "AGENT_WATCHER_LOCKED");
        let _ = child.kill();
        let _ = child.wait();
    }

    #[test]
    fn diff_rename_is_exit_then_enter() {
        let (_dir, root) = primed();
        fs::write(board::lane_dir(&root, Lane::Todo).join("alpha.md"), "# A\n").unwrap();
        let first = snapshot(&root).unwrap();
        fs::rename(
            board::lane_dir(&root, Lane::Todo).join("alpha.md"),
            board::lane_dir(&root, Lane::Doing).join("alpha.md"),
        )
        .unwrap();
        let second = snapshot(&root).unwrap();
        let events = diff(&root, &first, &second);
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].event, WatchKind::Exit);
        assert_eq!(events[0].lane, Lane::Todo);
        assert_eq!(events[0].id, "alpha");
        assert_eq!(events[1].event, WatchKind::Enter);
        assert_eq!(events[1].lane, Lane::Doing);
        assert_eq!(events[1].id, "alpha");
    }

    #[test]
    fn existing_enters_lists_current_todos() {
        let (_dir, root) = primed();
        fs::write(board::lane_dir(&root, Lane::Todo).join("beta.md"), "# B\n").unwrap();
        let snap = snapshot(&root).unwrap();
        let events = existing_enters(&root, &snap);
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event, WatchKind::Enter);
        assert_eq!(events[0].id, "beta");
    }

    #[test]
    fn filter_skips_other_lanes() {
        let event = WatchEvent {
            event: WatchKind::Enter,
            lane: Lane::Done,
            id: "x".into(),
            path: "x.md".into(),
            agents_path: None,
            agents: None,
            exec_exit: None,
            agent_output: None,
        };
        let filter = WatchFilter {
            lanes: vec![Lane::Todo],
            kinds: vec![WatchKind::Enter],
        };
        assert!(!filter.matches(&event));
    }

    #[test]
    fn grok_args_are_headless_yolo() {
        let args = AgentKind::Grok.args("do the task");
        assert_eq!(
            args,
            vec![
                "-p",
                "do the task",
                "--always-approve",
                "--output-format",
                "plain"
            ]
        );
    }

    #[test]
    fn agent_parse_accepts_claude() {
        let kind = AgentKind::parse("claude").expect("claude is a valid agent");
        assert_eq!(kind.program(), "claude");
    }

    #[test]
    fn agent_parse_rejects_unknown() {
        let err = AgentKind::parse("nope").unwrap_err();
        assert_eq!(err.code(), "INVALID_AGENT");
    }

    #[test]
    fn claude_args_are_headless_yolo() {
        let kind = AgentKind::parse("claude").expect("claude is a valid agent");
        assert_eq!(
            kind.args("do the task"),
            vec!["-p", "do the task", "--dangerously-skip-permissions"]
        );
    }

    #[test]
    fn agent_prompt_includes_lane_agents_and_task() {
        let (_dir, root) = primed();
        fs::write(
            board::agents_path(&root, Lane::Todo),
            "Start the task before editing.\n",
        )
        .unwrap();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let prompt = agent_prompt(&root, &event);
        assert!(prompt.contains("Start the task before editing."));
        assert!(prompt.contains("# Gamma\nDo the work.\n"));
        assert!(prompt.contains("gamma"));
        assert!(prompt.contains("entered"));
    }

    #[test]
    fn agent_prompt_includes_board_root_agents_md_when_present() {
        let (_dir, root) = primed();
        fs::write(
            root.join("AGENTS.md"),
            "ALWAYS USE NECRO TO IMPLEMENT ALL CHANGES.\n",
        )
        .unwrap();
        fs::write(
            board::agents_path(&root, Lane::Todo),
            "Start the task before editing.\n",
        )
        .unwrap();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let prompt = agent_prompt(&root, &event);
        assert!(prompt.contains("ALWAYS USE NECRO TO IMPLEMENT ALL CHANGES."));
        assert!(prompt.contains("Start the task before editing."));
        assert!(prompt.contains("# Gamma\nDo the work.\n"));
    }

    #[test]
    fn agent_prompt_succeeds_when_board_root_agents_md_is_missing() {
        let (_dir, root) = primed();
        assert!(!root.join("AGENTS.md").exists());
        fs::write(
            board::agents_path(&root, Lane::Todo),
            "Start the task before editing.\n",
        )
        .unwrap();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let prompt = agent_prompt(&root, &event);
        assert!(prompt.contains("Start the task before editing."));
        assert!(prompt.contains("# Gamma\nDo the work.\n"));
        assert!(!prompt.contains("# Board AGENTS.md"));
    }

    #[tokio::test]
    async fn run_agent_spawns_program_with_prompt() {
        let (dir, root) = primed();
        fs::write(
            board::agents_path(&root, Lane::Todo),
            "Start the task before editing.\n",
        )
        .unwrap();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");

        let stub = dir.path().join("fake-grok");
        fs::write(
            &stub,
            "#!/bin/sh\npwd > \"$NECRO_ROOT/agent-cwd.txt\"\ni=1\nfor arg in \"$@\"; do\n  printf '%s' \"$arg\" > \"$NECRO_ROOT/agent-arg-$i.txt\"\n  i=$((i+1))\ndone\n",
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&stub).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&stub, perms).unwrap();
        }

        run_agent_bin(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert_eq!(event.exec_exit, Some(0));
        let cwd = fs::read_to_string(root.join("agent-cwd.txt")).unwrap();
        assert_eq!(cwd.trim(), root.to_str().unwrap());
        assert_eq!(
            fs::read_to_string(root.join("agent-arg-1.txt")).unwrap(),
            "-p"
        );
        let prompt = fs::read_to_string(root.join("agent-arg-2.txt")).unwrap();
        assert!(prompt.contains("Start the task before editing."));
        assert!(prompt.contains("# Gamma\nDo the work.\n"));
        assert_eq!(
            fs::read_to_string(root.join("agent-arg-3.txt")).unwrap(),
            "--always-approve"
        );
        assert_eq!(event.agent_output, None);
        assert_eq!(
            fs::read_to_string(&task).unwrap(),
            "# Gamma\nDo the work.\n"
        );
    }

    #[tokio::test]
    async fn run_agent_spawns_claude_with_yolo_flag() {
        let (dir, root) = primed();
        fs::write(
            board::agents_path(&root, Lane::Todo),
            "Start the task before editing.\n",
        )
        .unwrap();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");

        let stub = dir.path().join("fake-claude");
        fs::write(
            &stub,
            "#!/bin/sh\npwd > \"$NECRO_ROOT/agent-cwd.txt\"\ni=1\nfor arg in \"$@\"; do\n  printf '%s' \"$arg\" > \"$NECRO_ROOT/agent-arg-$i.txt\"\n  i=$((i+1))\ndone\nprintf '%s\\n' 'hello from claude'\n",
        )
        .unwrap();
        chmod_exec(&stub);

        let kind = AgentKind::parse("claude").expect("claude is a valid agent");
        run_agent_bin(&root, &stub, kind, &mut event).await.unwrap();
        assert_eq!(event.exec_exit, Some(0));
        let cwd = fs::read_to_string(root.join("agent-cwd.txt")).unwrap();
        assert_eq!(cwd.trim(), root.to_str().unwrap());
        assert_eq!(
            fs::read_to_string(root.join("agent-arg-1.txt")).unwrap(),
            "-p"
        );
        let prompt = fs::read_to_string(root.join("agent-arg-2.txt")).unwrap();
        assert!(prompt.contains("Start the task before editing."));
        assert!(prompt.contains("# Gamma\nDo the work.\n"));
        assert_eq!(
            fs::read_to_string(root.join("agent-arg-3.txt")).unwrap(),
            "--dangerously-skip-permissions"
        );
        assert!(!root.join("agent-arg-4.txt").exists());
        assert_eq!(event.agent_output.as_deref(), Some("hello from claude"));
        let body = fs::read_to_string(&task).unwrap();
        assert!(body.contains("# Gamma\nDo the work.\n"));
        assert!(body.contains("hello from claude\n"));
        assert!(!body.contains("## Agent output"));
    }

    fn chmod_exec(path: &Path) {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(path).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(path, perms).unwrap();
        }
    }

    fn write_spawn_stub(dir: &Path) -> PathBuf {
        let stub = dir.join("fake-grok");
        fs::write(
            &stub,
            r#"#!/bin/sh
touch "$NECRO_ROOT/agent-ran"
if [ -f "$NECRO_ROOT/.necro/2-doing/$NECRO_ID.md" ] && [ ! -f "$NECRO_ROOT/.necro/1-todo/$NECRO_ID.md" ]; then
  touch "$NECRO_ROOT/claimed-before-spawn"
fi
printf '%s' "$1" > "$NECRO_ROOT/agent-arg-1.txt"
"#,
        )
        .unwrap();
        chmod_exec(&stub);
        stub
    }

    #[tokio::test]
    async fn todo_enter_claims_before_agent_spawn() {
        let (dir, root) = primed();
        let todo = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        let doing = board::lane_dir(&root, Lane::Doing).join("gamma.md");
        fs::write(&todo, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = write_spawn_stub(dir.path());

        let spawned = run_claimed_agent(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert!(spawned);
        assert!(!todo.exists());
        assert!(doing.is_file());
        assert!(root.join("agent-ran").is_file());
        assert!(root.join("claimed-before-spawn").is_file());
        assert_eq!(
            fs::read_to_string(root.join("agent-arg-1.txt")).unwrap(),
            "-p"
        );
        assert!(event.path.ends_with("/.necro/2-doing/gamma.md"));
    }

    #[tokio::test]
    async fn todo_enter_skips_agent_when_already_doing() {
        let (dir, root) = primed();
        let doing = board::lane_dir(&root, Lane::Doing).join("gamma.md");
        fs::write(&doing, "# Gamma\nAlready claimed.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = write_spawn_stub(dir.path());

        let spawned = run_claimed_agent(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert!(!spawned);
        assert!(!root.join("agent-ran").exists());
        assert!(!root.join("claimed-before-spawn").exists());
        assert!(doing.is_file());
        assert!(!board::lane_dir(&root, Lane::Todo).join("gamma.md").exists());
        assert_eq!(event.exec_exit, None);
        assert_eq!(
            fs::read_to_string(&doing).unwrap(),
            "# Gamma\nAlready claimed.\n"
        );
    }

    async fn assert_skips_spawn_after_leaving_todo(dest_lane: Lane) {
        let (dir, root) = primed();
        let todo = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        let dest_path = board::lane_dir(&root, dest_lane).join("gamma.md");
        fs::write(&todo, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = write_spawn_stub(dir.path());

        let spawned =
            run_claimed_agent_between(&root, &stub, AgentKind::Grok, &mut event, |root, id| {
                fs::rename(
                    todo_task_path(root, id),
                    board::lane_dir(root, dest_lane).join(format!("{id}.md")),
                )
                .unwrap();
            })
            .await
            .unwrap();
        assert!(
            !spawned,
            "agent spawned after todo file moved to {}",
            dest_lane.as_str()
        );
        assert!(
            !root.join("agent-ran").exists(),
            "agent binary ran after todo file moved to {}",
            dest_lane.as_str()
        );
        assert!(!todo.exists());
        assert!(dest_path.is_file());
        assert_eq!(event.exec_exit, None);
    }

    #[tokio::test]
    async fn todo_enter_skips_agent_when_task_left_todo() {
        for dest in [Lane::Doing, Lane::Done, Lane::Dropped] {
            assert_skips_spawn_after_leaving_todo(dest).await;
        }
    }

    #[tokio::test]
    async fn todo_enter_still_spawns_when_file_remains_in_todo() {
        let (dir, root) = primed();
        let todo = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&todo, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = write_spawn_stub(dir.path());
        assert!(todo.is_file());

        let spawned = run_claimed_agent(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert!(spawned);
        assert!(root.join("agent-ran").is_file());
        assert!(!todo.exists());
        assert!(
            board::lane_dir(&root, Lane::Doing)
                .join("gamma.md")
                .is_file()
        );
    }

    #[tokio::test]
    async fn run_agent_appends_stdout_to_task_file() {
        let (dir, root) = primed();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = dir.path().join("fake-grok");
        fs::write(&stub, "#!/bin/sh\nprintf '%s\\n' 'hello from grok'\n").unwrap();
        chmod_exec(&stub);

        run_agent_bin(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert_eq!(event.agent_output.as_deref(), Some("hello from grok"));
        let body = fs::read_to_string(&task).unwrap();
        assert!(body.contains("# Gamma\nDo the work.\n"));
        assert!(body.contains("hello from grok\n"));
        assert!(!body.contains("## Agent output"));
    }

    #[tokio::test]
    async fn run_agent_appends_stdout_before_process_exits() {
        let (dir, root) = primed();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = dir.path().join("fake-grok");
        fs::write(
            &stub,
            "#!/bin/sh\nprintf '%s\\n' 'first'\nsleep 0.4\nprintf '%s\\n' 'second'\n",
        )
        .unwrap();
        chmod_exec(&stub);

        let mut saw_partial = false;
        {
            let mut run = std::pin::pin!(run_agent_bin(&root, &stub, AgentKind::Grok, &mut event));
            loop {
                tokio::select! {
                    result = &mut run => {
                        result.unwrap();
                        break;
                    }
                    _ = tokio::time::sleep(Duration::from_millis(40)) => {
                        if let Ok(body) = fs::read_to_string(&task) {
                            if body.contains("first") && !body.contains("second") {
                                saw_partial = true;
                            }
                        }
                    }
                }
            }
        }
        assert!(
            saw_partial,
            "task file should contain the first stdout chunk before the agent process exits"
        );
        let body = fs::read_to_string(&task).unwrap();
        assert!(body.contains("first\nsecond\n"));
        assert_eq!(event.agent_output.as_deref(), Some("first\nsecond"));
    }

    #[tokio::test]
    async fn run_agent_notes_task_after_it_moves() {
        let (dir, root) = primed();
        let todo = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        let doing = board::lane_dir(&root, Lane::Doing).join("gamma.md");
        fs::write(&todo, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = dir.path().join("fake-grok");
        fs::write(
            &stub,
            "#!/bin/sh\nmv \"$NECRO_PATH\" \"$NECRO_ROOT/.necro/2-doing/gamma.md\"\nprintf '%s\\n' 'moved then spoke'\n",
        )
        .unwrap();
        chmod_exec(&stub);

        run_agent_bin(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert!(!todo.exists());
        let body = fs::read_to_string(&doing).unwrap();
        assert!(body.contains("moved then spoke"));
        assert_eq!(event.agent_output.as_deref(), Some("moved then spoke"));
    }

    fn assert_not_dropped(root: &Path, id: &str) {
        assert!(
            !board::lane_dir(root, Lane::Dropped)
                .join(format!("{id}.md"))
                .exists()
        );
    }

    #[tokio::test]
    async fn run_agent_records_stdout_on_nonzero_exit_without_dropping() {
        let (dir, root) = primed();
        let task = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        fs::write(&task, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = dir.path().join("fake-grok");
        fs::write(&stub, "#!/bin/sh\nprintf '%s\\n' 'agent crashed'\nexit 2\n").unwrap();
        chmod_exec(&stub);

        run_agent_bin(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert_eq!(event.exec_exit, Some(2));
        assert_eq!(event.agent_output.as_deref(), Some("agent crashed"));
        let body = fs::read_to_string(&task).unwrap();
        assert!(body.contains("# Gamma\nDo the work.\n"));
        assert!(body.contains("agent crashed\n"));
        assert!(!body.contains("## Agent output"));
        assert!(task.is_file());
        assert_not_dropped(&root, "gamma");
    }

    #[tokio::test]
    async fn claimed_agent_nonzero_exit_notes_doing_task_without_dropping() {
        let (dir, root) = primed();
        let todo = board::lane_dir(&root, Lane::Todo).join("gamma.md");
        let doing = board::lane_dir(&root, Lane::Doing).join("gamma.md");
        fs::write(&todo, "# Gamma\nDo the work.\n").unwrap();
        let mut event = event(&root, WatchKind::Enter, Lane::Todo, "gamma");
        let stub = dir.path().join("fake-grok");
        fs::write(
            &stub,
            "#!/bin/sh\nprintf '%s\\n' 'claimed then crashed'\nexit 3\n",
        )
        .unwrap();
        chmod_exec(&stub);

        let spawned = run_claimed_agent(&root, &stub, AgentKind::Grok, &mut event)
            .await
            .unwrap();
        assert!(spawned);
        assert!(!todo.exists());
        assert!(doing.is_file());
        assert_eq!(event.exec_exit, Some(3));
        assert_eq!(event.agent_output.as_deref(), Some("claimed then crashed"));
        let body = fs::read_to_string(&doing).unwrap();
        assert!(body.contains("claimed then crashed\n"));
        assert!(!body.contains("## Agent output"));
        assert_not_dropped(&root, "gamma");
    }
}