Skip to main content

cellix_agent/
lib.rs

1//! The local socket any agent can use to reach a running Cellix. One line in, one line
2//! out: `comments`, `take` (comments, then clear them), `threads`, `take-threads` (those an
3//! agent hasn't seen), `reply <id> <author>` then a tab and the text, or `open <path>`.
4//!
5//! It's a Unix socket where there are those, and elsewhere a port on 127.0.0.1 behind a token,
6//! as `loopback` describes. Agents call `cellix`, so only this crate tells the two apart.
7
8use std::env;
9use std::fs;
10use std::io::{self, BufRead, BufReader, ErrorKind, Write};
11#[cfg(unix)]
12use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
13#[cfg(unix)]
14use std::os::unix::net::{UnixListener, UnixStream};
15use std::path::{Path, PathBuf};
16use std::sync::mpsc::{Receiver, Sender, channel};
17use std::sync::{Arc, Mutex};
18use std::thread;
19use std::time::Duration;
20
21use cellix_review::Comment;
22use serde::{Deserialize, Serialize};
23
24pub mod context;
25pub mod hook;
26pub mod ide;
27mod loopback;
28
29/// How long a request waits on the app, which may be busy or gone. An agent's hook must never
30/// hang on it.
31const ANSWER_TIME: Duration = Duration::from_secs(2);
32/// How long a client waits for a reply: longer than the app is given, so a busy app's own
33/// answer arrives. A hook asks several things per prompt, so it's never much more.
34const REPLY_TIME: Duration = Duration::from_secs(5);
35/// How long a client waits for a Cellix to connect and prove itself.
36const PROOF_TIME: Duration = Duration::from_secs(2);
37
38/// Comments shared between the app and the socket thread.
39pub type SharedComments = Arc<Mutex<Vec<Comment>>>;
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
42pub enum AgentState {
43    Working,
44    NeedsYou,
45    Idle,
46    Ended,
47}
48
49/// What an agent is doing, as its hooks report it.
50#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub struct AgentEvent {
52    pub session: String,
53    pub agent: String,
54    pub state: AgentState,
55    pub detail: String,
56    pub folder: String,
57    /// The agent's process, so news from one that has since gone can be let go. Hooks from
58    /// before it was sent, and Windows, leave it out.
59    #[serde(default)]
60    pub pid: Option<u32>,
61    /// Where the agent keeps this session's transcript, when its hook says.
62    #[serde(default, skip_serializing_if = "String::is_empty")]
63    pub transcript: String,
64}
65
66/// A test command an agent ran.
67#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
68pub struct TestRun {
69    pub command: String,
70    pub passed: bool,
71    pub output: String,
72}
73
74/// The reviewer's answer to a plan.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub enum Decision {
77    /// With the plan's new text, if the reviewer edited it.
78    Approve(Option<String>),
79    SendBack(String),
80}
81
82/// Requests that need the app itself, drained on its next tick.
83#[derive(Debug)]
84pub enum Request {
85    Open(PathBuf),
86    /// The socket thread already emptied the shared list.
87    CommentsTaken,
88    Agent(AgentEvent),
89    Test(TestRun),
90    /// Input for a Cellix running as a pane, as the mod's JSON.
91    Pane(String),
92    /// An agent answering a comment.
93    Reply {
94        id: u32,
95        author: String,
96        text: String,
97        /// Whether that comment exists, so an answer can't vanish with a success.
98        found: Sender<bool>,
99    },
100    /// An agent suggesting a comment the reviewer didn't make. Answers with its number.
101    Suggest {
102        file: String,
103        line: usize,
104        kind: String,
105        quote: String,
106        text: String,
107        author: String,
108        made: Sender<u32>,
109    },
110    /// Wants the comments on the project, as JSON.
111    Threads(Sender<String>),
112    /// Wants the comments no agent has seen, as JSON, and marks them seen.
113    TakeThreads(Sender<String>),
114    /// A plan is waiting. The connection stays open until `reply` is answered or dropped.
115    Plan {
116        path: PathBuf,
117        reply: Sender<Decision>,
118    },
119}
120
121fn fnv(text: &str) -> u64 {
122    text.bytes().fold(0xcbf29ce484222325, |hash, byte| {
123        (hash ^ byte as u64).wrapping_mul(0x100000001b3)
124    })
125}
126
127/// How agents reach a Cellix.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum Transport {
130    /// A Unix socket at `socket_path`.
131    #[cfg(unix)]
132    Unix,
133    /// A port on 127.0.0.1, named with its token in a file at `socket_path`.
134    Loopback,
135}
136
137impl Transport {
138    /// What `start` and `request` use here.
139    #[cfg(unix)]
140    pub const NATIVE: Self = Self::Unix;
141    #[cfg(not(unix))]
142    pub const NATIVE: Self = Self::Loopback;
143}
144
145/// A token no one else can guess.
146pub(crate) fn new_token() -> io::Result<String> {
147    let mut bytes = [0u8; 16];
148    #[cfg(unix)]
149    io::Read::read_exact(&mut fs::File::open("/dev/urandom")?, &mut bytes)?;
150    #[cfg(not(unix))]
151    getrandom::fill(&mut bytes).map_err(io::Error::other)?;
152    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
153}
154
155/// The folder the sockets live in, which only this user can enter. On Unix it's named for
156/// the user in the shared temp folder, and made private.
157#[cfg(unix)]
158fn sockets_folder() -> PathBuf {
159    // SAFETY: getuid has no preconditions and cannot fail.
160    let uid = unsafe { libc::getuid() };
161    env::temp_dir().join(format!("cellix-{uid}"))
162}
163
164#[cfg(not(unix))]
165fn sockets_folder() -> PathBuf {
166    windows_sockets_folder(|name| env::var(name).ok())
167}
168
169/// The folder the sockets live in on Windows: the user's own local app data, which only they
170/// and administrators can read, wherever TEMP has been pointed.
171#[cfg_attr(unix, allow(dead_code))]
172fn windows_sockets_folder(var: impl Fn(&str) -> Option<String>) -> PathBuf {
173    let local = var("LOCALAPPDATA")
174        .filter(|v| !v.is_empty())
175        .map(PathBuf::from);
176    local
177        .or_else(|| {
178            Some(
179                PathBuf::from(var("USERPROFILE")?)
180                    .join("AppData")
181                    .join("Local"),
182            )
183        })
184        .unwrap_or_else(env::temp_dir)
185        .join("cellix")
186        .join("sockets")
187}
188
189/// One socket per workspace, in a directory only this user can enter.
190pub fn socket_path(root: &Path) -> PathBuf {
191    // `\\?\C:\x` and `C:\x` are one folder, so they share a socket. Unix paths are as they are.
192    let root = dunce::simplified(root);
193    sockets_folder().join(format!("{:016x}.sock", fnv(&root.to_string_lossy())))
194}
195
196/// A reply's text as `escape` sent it on one line: `\n` is a line break and `\\` a backslash.
197fn unescape(text: &str) -> String {
198    let mut out = String::with_capacity(text.len());
199    let mut chars = text.chars();
200    while let Some(c) = chars.next() {
201        match (c, chars.clone().next()) {
202            ('\\', Some('n')) => {
203                out.push('\n');
204                chars.next();
205            }
206            ('\\', Some('\\')) => {
207                out.push('\\');
208                chars.next();
209            }
210            (c, _) => out.push(c),
211        }
212    }
213    out
214}
215
216/// A reply's text on one line, for `reply`.
217pub fn escape(text: &str) -> String {
218    text.replace('\\', "\\\\").replace('\n', "\\n")
219}
220
221fn answer(line: &str, comments: &SharedComments, requests: &Sender<Request>) -> io::Result<String> {
222    let mut parts = line.trim().splitn(2, ' ');
223    let list = |clear: bool| -> io::Result<String> {
224        let mut shared = comments.lock().map_err(|_| io::Error::other("poisoned"))?;
225        let json = serde_json::to_string(&*shared)?;
226        if clear {
227            shared.clear();
228        }
229        Ok(json)
230    };
231    match (parts.next(), parts.next()) {
232        (Some("comments"), None) => list(false),
233        (Some("take"), None) => {
234            let json = list(true)?;
235            // The hook takes on every prompt, and an empty take isn't news.
236            if json != "[]" {
237                let _ = requests.send(Request::CommentsTaken);
238            }
239            Ok(json)
240        }
241        (Some("open"), Some(path)) => {
242            let _ = requests.send(Request::Open(PathBuf::from(path)));
243            Ok("ok".into())
244        }
245        (Some("threads"), None) => {
246            let (reply, threads) = channel();
247            let _ = requests.send(Request::Threads(reply));
248            Ok(threads
249                .recv_timeout(ANSWER_TIME)
250                .unwrap_or_else(|_| "[]".to_string()))
251        }
252        (Some("take-threads"), None) => {
253            let (reply, threads) = channel();
254            let _ = requests.send(Request::TakeThreads(reply));
255            Ok(threads
256                .recv_timeout(ANSWER_TIME)
257                .unwrap_or_else(|_| "[]".to_string()))
258        }
259        (Some("reply"), Some(rest)) => {
260            let Some((head, text)) = rest.split_once('\t') else {
261                return Ok("error: reply needs an id, an author and text".into());
262            };
263            let (id, author) = head.split_once(' ').unwrap_or((head, "Agent"));
264            let Ok(id) = id.parse() else {
265                return Ok("error: reply needs a comment's number".into());
266            };
267            // The reviewer's own replies come from Cellix, never over the socket: one that
268            // said it was theirs would be taken as their word, and passed to the next agent.
269            let author: String = author.chars().filter(|c| !c.is_control()).collect();
270            let author = author.trim();
271            if author.is_empty() || author.eq_ignore_ascii_case(cellix_review::YOU) {
272                return Ok(format!(
273                    "error: an agent can't reply as {}",
274                    cellix_review::YOU
275                ));
276            }
277            let (author, text) = (author.to_string(), unescape(text));
278            let (found, answer) = channel();
279            let _ = requests.send(Request::Reply {
280                id,
281                author,
282                text,
283                found,
284            });
285            Ok(match answer.recv_timeout(ANSWER_TIME) {
286                Ok(true) => "ok".to_string(),
287                _ => format!("error: there's no comment {id}"),
288            })
289        }
290        (Some("suggest"), Some(json)) => {
291            let value: serde_json::Value = serde_json::from_str(json)?;
292            let field = |name: &str| value[name].as_str().unwrap_or_default().to_string();
293            let (made, answer) = channel();
294            let _ = requests.send(Request::Suggest {
295                file: field("file"),
296                line: value["line"].as_u64().unwrap_or(1) as usize,
297                kind: field("kind"),
298                quote: field("quote"),
299                text: field("text"),
300                author: field("author"),
301                made,
302            });
303            Ok(match answer.recv_timeout(ANSWER_TIME) {
304                Ok(id) => format!("ok {id}"),
305                Err(_) => "error: Cellix didn't take the suggestion".to_string(),
306            })
307        }
308        (Some("pane"), Some(json)) => {
309            let _ = requests.send(Request::Pane(json.to_string()));
310            Ok("ok".into())
311        }
312        (Some("event"), Some(json)) => {
313            let _ = requests.send(Request::Agent(serde_json::from_str(json)?));
314            Ok("ok".into())
315        }
316        (Some("test"), Some(json)) => {
317            let _ = requests.send(Request::Test(serde_json::from_str(json)?));
318            Ok("ok".into())
319        }
320        (Some("plan"), Some(path)) => {
321            let (reply, decision) = channel();
322            let path = PathBuf::from(path);
323            let _ = requests.send(Request::Plan { path, reply });
324            // Quitting drops the sender, and the agent goes back to asking as usual.
325            Ok(match decision.recv() {
326                Ok(Decision::Approve(None)) => "approve".to_string(),
327                Ok(Decision::Approve(Some(text))) => {
328                    format!("approve {}", serde_json::to_string(&text)?)
329                }
330                Ok(Decision::SendBack(text)) => {
331                    format!("send-back {}", serde_json::to_string(&text)?)
332                }
333                Err(_) => "pass".to_string(),
334            })
335        }
336        _ => Ok("error: unknown request".into()),
337    }
338}
339
340fn serve(
341    mut reader: impl BufRead,
342    mut stream: impl Write,
343    comments: &SharedComments,
344    requests: &Sender<Request>,
345) -> io::Result<()> {
346    let mut line = String::new();
347    reader.read_line(&mut line)?;
348    writeln!(stream, "{}", answer(&line, comments, requests)?)
349}
350
351/// The running server. Dropping it removes the socket file, and the plans kept beside it.
352pub struct Server {
353    path: PathBuf,
354    owner: Owner,
355    pub requests: Receiver<Request>,
356}
357
358/// What tells this server's socket file from one a later Cellix put in its place.
359enum Owner {
360    /// The Unix socket's inode.
361    #[cfg(unix)]
362    Socket(u64),
363    Note(loopback::Note),
364}
365
366impl Server {
367    /// Whether the socket file is still this server's own.
368    fn owns_its_file(&self) -> bool {
369        match &self.owner {
370            #[cfg(unix)]
371            Owner::Socket(inode) => {
372                use std::os::unix::fs::MetadataExt;
373                fs::symlink_metadata(&self.path).is_ok_and(|m| m.ino() == *inode)
374            }
375            Owner::Note(note) => note.is_at(&self.path),
376        }
377    }
378}
379
380impl Drop for Server {
381    fn drop(&mut self) {
382        // Two starting at once can both find no one here, and the second's file replaces the
383        // first's. The first mustn't take it with it.
384        if self.owns_its_file() {
385            let _ = fs::remove_file(&self.path);
386            let _ = fs::remove_dir_all(self.path.with_extension(""));
387        }
388    }
389}
390
391/// Makes the folder the sockets live in, which only this user can enter.
392fn private_folder(dir: &Path) -> io::Result<()> {
393    #[cfg(unix)]
394    {
395        fs::DirBuilder::new()
396            .recursive(true)
397            .mode(0o700)
398            .create(dir)?;
399        fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
400        check_private(dir)
401    }
402    // Inside the user's own local app data, which only they and administrators can read.
403    #[cfg(not(unix))]
404    fs::DirBuilder::new().recursive(true).create(dir)
405}
406
407/// Refuses a sockets folder that isn't this user's own and closed to everyone else. It's in
408/// the shared temp folder, so on a machine with other users someone could make it first, put
409/// their own socket in it and answer an agent's hooks: hand it comments as the reviewer's, or
410/// approve its plans. Neither end uses such a folder.
411#[cfg(unix)]
412fn check_private(dir: &Path) -> io::Result<()> {
413    let meta = fs::symlink_metadata(dir)?;
414    // SAFETY: getuid has no preconditions and cannot fail.
415    let uid = unsafe { libc::getuid() };
416    if owned_privately(&meta, uid) {
417        Ok(())
418    } else {
419        Err(io::Error::new(
420            ErrorKind::PermissionDenied,
421            format!(
422                "{} belongs to someone else or others can enter it, so it isn't used",
423                dir.display()
424            ),
425        ))
426    }
427}
428
429/// Whether a folder is a real one, owned by `uid`, that only its owner can enter.
430#[cfg(unix)]
431fn owned_privately(meta: &fs::Metadata, uid: u32) -> bool {
432    use std::os::unix::fs::MetadataExt;
433    meta.file_type().is_dir() && meta.uid() == uid && meta.mode() & 0o077 == 0
434}
435
436/// Binds the workspace socket. Fails if another Cellix already serves this workspace.
437pub fn start(root: &Path, comments: SharedComments) -> io::Result<Server> {
438    start_with(root, comments, Transport::NATIVE)
439}
440
441/// `start`, over the transport given.
442pub fn start_with(
443    root: &Path,
444    comments: SharedComments,
445    transport: Transport,
446) -> io::Result<Server> {
447    let path = socket_path(root);
448    let dir = path.parent().ok_or_else(|| io::Error::other("no parent"))?;
449    private_folder(dir)?;
450    let (sender, requests) = channel();
451    let owner = match transport {
452        #[cfg(unix)]
453        Transport::Unix => {
454            if UnixStream::connect(&path).is_ok() {
455                return Err(io::Error::new(ErrorKind::AddrInUse, "already running"));
456            }
457            let _ = fs::remove_file(&path);
458            let listener = UnixListener::bind(&path)?;
459            let inode = std::os::unix::fs::MetadataExt::ino(&fs::symlink_metadata(&path)?);
460            thread::spawn(move || {
461                for stream in listener.incoming().flatten() {
462                    // One thread each, because a plan holds its connection open for as long as
463                    // the reviewer takes.
464                    let (comments, sender) = (comments.clone(), sender.clone());
465                    thread::spawn(move || {
466                        let reader = BufReader::new(stream.try_clone()?);
467                        serve(reader, stream, &comments, &sender)
468                    });
469                }
470            });
471            Owner::Socket(inode)
472        }
473        Transport::Loopback => {
474            if loopback::alive(&path) {
475                return Err(io::Error::new(ErrorKind::AddrInUse, "already running"));
476            }
477            let _ = fs::remove_file(&path);
478            let listener = Arc::new(loopback::bind(&path)?);
479            let note = listener.note.clone();
480            thread::spawn(move || {
481                for stream in listener.incoming() {
482                    let (comments, sender) = (comments.clone(), sender.clone());
483                    let listener = listener.clone();
484                    // Admitted on its own thread, so a stranger that never sends a token
485                    // holds up no one else.
486                    thread::spawn(move || {
487                        let (reader, stream) = listener.admit(stream)?;
488                        serve(reader, stream, &comments, &sender)
489                    });
490                }
491            });
492            Owner::Note(note)
493        }
494    };
495    Ok(Server {
496        path,
497        owner,
498        requests,
499    })
500}
501
502/// Sends one request to the Cellix serving `root`.
503pub fn request(root: &Path, line: &str) -> io::Result<String> {
504    request_with(root, line, Transport::NATIVE)
505}
506
507/// How long to wait for the reply to `line`. A plan waits for the reviewer, however long they
508/// take; anything else is answered at once or not at all, and a hook mustn't hang on it.
509fn patience(line: &str) -> Option<Duration> {
510    (!line.starts_with("plan ")).then_some(REPLY_TIME)
511}
512
513/// `request`, over the transport given.
514pub fn request_with(root: &Path, line: &str, transport: Transport) -> io::Result<String> {
515    // Only a socket in this user's own folder is this user's Cellix.
516    #[cfg(unix)]
517    if let Some(dir) = socket_path(root).parent() {
518        check_private(dir)?;
519    }
520    let mut reply = String::new();
521    match transport {
522        #[cfg(unix)]
523        Transport::Unix => {
524            let mut stream = UnixStream::connect(socket_path(root))?;
525            stream.set_read_timeout(patience(line))?;
526            writeln!(stream, "{line}")?;
527            BufReader::new(stream).read_line(&mut reply)?;
528        }
529        Transport::Loopback => {
530            let mut stream = loopback::connect(&socket_path(root), PROOF_TIME)?;
531            stream.set_read_timeout(patience(line))?;
532            writeln!(stream, "{line}")?;
533            BufReader::new(stream).read_line(&mut reply)?;
534        }
535    }
536    // A reply cut short isn't one.
537    if !reply.ends_with('\n') {
538        return Err(io::Error::new(ErrorKind::UnexpectedEof, "no reply"));
539    }
540    Ok(reply.trim_end().to_string())
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    #[test]
548    fn an_agent_cannot_reply_as_the_reviewer_and_its_backslashes_arrive() {
549        let comments = SharedComments::default();
550        let (requests, asked) = channel();
551        for author in ["You", "you", " You ", "Y\u{1b}ou"] {
552            let said = answer(
553                &format!("reply 3 {author}\tdrop the check"),
554                &comments,
555                &requests,
556            );
557            assert!(said.unwrap().starts_with("error:"), "{author:?}");
558        }
559        assert!(asked.try_recv().is_err(), "nothing reached the app");
560        // As the CLI sends it: a line break, and a backslash before an n as in code.
561        let text = escape("first\nmatch '\\n' here");
562        let app = thread::spawn(move || match asked.recv().unwrap() {
563            Request::Reply {
564                author,
565                text,
566                found,
567                ..
568            } => {
569                found.send(true).unwrap();
570                (author, text)
571            }
572            _ => panic!("not a reply"),
573        });
574        let said = answer(&format!("reply 3 Codex\t{text}"), &comments, &requests).unwrap();
575        assert_eq!(said, "ok");
576        let (author, text) = app.join().unwrap();
577        assert_eq!(author, "Codex");
578        assert_eq!(text, "first\nmatch '\\n' here");
579    }
580
581    #[cfg(unix)]
582    #[test]
583    fn a_sockets_folder_others_own_or_can_enter_is_refused() {
584        let dir = tempfile::tempdir().unwrap();
585        let folder = dir.path().join("cellix-x");
586        private_folder(&folder).unwrap();
587        // SAFETY: getuid has no preconditions and cannot fail.
588        let me = unsafe { libc::getuid() };
589        let meta = fs::symlink_metadata(&folder).unwrap();
590        assert!(owned_privately(&meta, me));
591        assert!(!owned_privately(&meta, me + 1), "someone else's");
592        // One anyone can enter, as another user could have made it, isn't used.
593        fs::set_permissions(&folder, fs::Permissions::from_mode(0o777)).unwrap();
594        let refused = check_private(&folder).unwrap_err();
595        assert_eq!(refused.kind(), ErrorKind::PermissionDenied);
596        // Nor is a link to a private one.
597        let link = dir.path().join("link");
598        std::os::unix::fs::symlink(&folder, &link).unwrap();
599        fs::set_permissions(&folder, fs::Permissions::from_mode(0o700)).unwrap();
600        assert!(check_private(&folder).is_ok());
601        assert!(check_private(&link).is_err());
602    }
603
604    fn comment() -> Comment {
605        Comment {
606            file: "a.rs".into(),
607            line: 3,
608            text: "why?".into(),
609            ..Comment::default()
610        }
611    }
612
613    #[test]
614    fn comments_can_be_read_and_taken() {
615        let dir = tempfile::tempdir().unwrap();
616        let shared: SharedComments = Arc::new(Mutex::new(vec![comment()]));
617        let server = start(dir.path(), shared.clone()).unwrap();
618        let json = request(dir.path(), "comments").unwrap();
619        let parsed: Vec<Comment> = serde_json::from_str(&json).unwrap();
620        assert_eq!(parsed, vec![comment()]);
621        assert_eq!(shared.lock().unwrap().len(), 1);
622        request(dir.path(), "take").unwrap();
623        assert!(shared.lock().unwrap().is_empty());
624        assert!(matches!(server.requests.recv(), Ok(Request::CommentsTaken)));
625    }
626
627    #[test]
628    fn open_reaches_the_app() {
629        let dir = tempfile::tempdir().unwrap();
630        let server = start(dir.path(), Arc::default()).unwrap();
631        assert_eq!(request(dir.path(), "open /tmp/x.rs").unwrap(), "ok");
632        assert!(matches!(
633            server.requests.recv(),
634            Ok(Request::Open(path)) if path == Path::new("/tmp/x.rs")
635        ));
636    }
637
638    #[test]
639    fn a_second_server_is_refused_and_stale_sockets_are_replaced() {
640        let dir = tempfile::tempdir().unwrap();
641        let server = start(dir.path(), Arc::default()).unwrap();
642        assert!(start(dir.path(), Arc::default()).is_err());
643        let path = server.path.clone();
644        std::mem::forget(server);
645        fs::remove_file(&path).unwrap();
646        fs::write(&path, "stale").unwrap();
647        assert!(start(dir.path(), Arc::default()).is_ok());
648    }
649
650    #[test]
651    fn a_closed_server_takes_its_plans_with_it() {
652        let dir = tempfile::tempdir().unwrap();
653        let server = start(dir.path(), Arc::default()).unwrap();
654        let plans = server.path.with_extension("").join("s1");
655        fs::create_dir_all(&plans).unwrap();
656        fs::write(plans.join("Plan.md"), "plan").unwrap();
657        let path = server.path.clone();
658        drop(server);
659        assert!(!path.exists());
660        assert!(!path.with_extension("").exists());
661    }
662
663    /// What Windows uses, proved on every platform.
664    #[test]
665    fn agents_reach_cellix_over_loopback_with_its_token() {
666        let dir = tempfile::tempdir().unwrap();
667        let shared: SharedComments = Arc::new(Mutex::new(vec![comment()]));
668        let over = Transport::Loopback;
669        let server = start_with(dir.path(), shared.clone(), over).unwrap();
670        // Where the socket would be, a note of the port, a token each way, and the process.
671        let note = fs::read_to_string(&server.path).unwrap();
672        let fields: Vec<&str> = note.split_whitespace().collect();
673        let port: u16 = fields[0].parse().unwrap();
674        assert_eq!((fields[1].len(), fields[2].len()), (32, 32));
675        assert_ne!(fields[1], fields[2]);
676        assert_eq!(fields[3], std::process::id().to_string());
677        #[cfg(unix)]
678        assert_eq!(
679            fs::metadata(&server.path).unwrap().permissions().mode() & 0o777,
680            0o600
681        );
682
683        let json = request_with(dir.path(), "comments", over).unwrap();
684        let parsed: Vec<Comment> = serde_json::from_str(&json).unwrap();
685        assert_eq!(parsed, vec![comment()]);
686        assert_eq!(
687            request_with(dir.path(), "open /tmp/x.rs", over).unwrap(),
688            "ok"
689        );
690        assert!(matches!(
691            server.requests.recv(),
692            Ok(Request::Open(path)) if path == Path::new("/tmp/x.rs")
693        ));
694        request_with(dir.path(), "take", over).unwrap();
695        assert!(shared.lock().unwrap().is_empty());
696        assert!(matches!(server.requests.recv(), Ok(Request::CommentsTaken)));
697
698        // Anything else that finds the port gets nothing without the token, even with a
699        // guess as long as it.
700        for guess in ["comments", &"0".repeat(32)] {
701            let mut stranger = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
702            writeln!(stranger, "{guess}\ncomments").unwrap();
703            let mut reply = String::new();
704            let _ = BufReader::new(stranger).read_line(&mut reply);
705            assert_eq!(reply, "");
706        }
707        shared.lock().unwrap().push(comment());
708        assert_ne!(request_with(dir.path(), "comments", over).unwrap(), "[]");
709
710        // A second Cellix here is refused while this one answers.
711        assert!(start_with(dir.path(), Arc::default(), over).is_err());
712        let path = server.path.clone();
713        drop(server);
714        assert!(!path.exists());
715    }
716
717    /// A note as a Cellix writes it, for a port and process of the test's choosing.
718    fn note_for(port: u16, pid: u32) -> String {
719        let tokens = (new_token().unwrap(), new_token().unwrap());
720        format!("{port} {} {} {pid}\n", tokens.0, tokens.1)
721    }
722
723    /// A port that refuses connections, as one whose Cellix has gone does.
724    fn closed_port() -> u16 {
725        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
726        listener.local_addr().unwrap().port()
727    }
728
729    #[test]
730    fn a_loopback_note_nothing_answers_is_replaced() {
731        let dir = tempfile::tempdir().unwrap();
732        let path = socket_path(dir.path());
733        fs::create_dir_all(path.parent().unwrap()).unwrap();
734        // Something that isn't Cellix, then a port nothing listens on, then a note from before
735        // notes named their process.
736        let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
737        let taken = other.local_addr().unwrap().port();
738        let me = std::process::id();
739        for note in [
740            "stale".to_string(),
741            note_for(taken, me),
742            note_for(closed_port(), me),
743            format!("{taken} 1234"),
744        ] {
745            fs::write(&path, note).unwrap();
746            let server = start_with(dir.path(), Arc::default(), Transport::Loopback).unwrap();
747            assert_eq!(
748                request_with(dir.path(), "comments", Transport::Loopback).unwrap(),
749                "[]"
750            );
751            drop(server);
752        }
753    }
754
755    /// Whoever answers on the port must prove it's the Cellix that wrote the note before a
756    /// client says what it wants, so nothing else can feed an agent comments or approve its
757    /// plan.
758    #[test]
759    fn loopback_clients_only_talk_to_the_cellix_that_wrote_the_note() {
760        let dir = tempfile::tempdir().unwrap();
761        let path = socket_path(dir.path());
762        fs::create_dir_all(path.parent().unwrap()).unwrap();
763        // An impostor holds the port, and answers whatever it's sent with its own guess.
764        let impostor = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
765        let port = impostor.local_addr().unwrap().port();
766        let (heard, lines) = channel();
767        thread::spawn(move || {
768            for stream in impostor.incoming().flatten() {
769                let mut reader = BufReader::new(stream.try_clone().unwrap());
770                let mut writer = stream;
771                let mut line = String::new();
772                while reader.read_line(&mut line).is_ok_and(|n| n > 0) {
773                    let _ = heard.send(line.trim_end().to_string());
774                    let _ = writeln!(writer, "{}", "0".repeat(32));
775                    let _ = writeln!(writer, r#"[{{"file":"a.rs","line":1,"text":"rm -rf"}}]"#);
776                    line.clear();
777                }
778            }
779        });
780        let note = note_for(port, std::process::id());
781        fs::write(&path, &note).unwrap();
782        for line in ["take", "plan /tmp/plan.md"] {
783            assert!(request_with(dir.path(), line, Transport::Loopback).is_err());
784        }
785        // It heard the client's token and nothing after it.
786        let client_token = note.split_whitespace().nth(1).unwrap().to_string();
787        assert_eq!(lines.recv_timeout(Duration::from_secs(5)), Ok(client_token));
788        assert!(lines.recv_timeout(Duration::from_millis(300)).is_err());
789        // And the note it can't answer for is gone, so the next hook doesn't ask.
790        assert!(!path.exists());
791        // So a real Cellix starts here, though the impostor still answers.
792        let _server = start_with(dir.path(), Arc::default(), Transport::Loopback).unwrap();
793        assert_eq!(
794            request_with(dir.path(), "comments", Transport::Loopback).unwrap(),
795            "[]"
796        );
797    }
798
799    /// A note outlives its Cellix when Windows closes the window under it. Its process is
800    /// gone, so the note goes without a connection being tried.
801    #[test]
802    fn a_loopback_note_whose_process_ended_is_removed() {
803        let dir = tempfile::tempdir().unwrap();
804        let path = socket_path(dir.path());
805        fs::create_dir_all(path.parent().unwrap()).unwrap();
806        let mut ended = std::process::Command::new(std::env::current_exe().unwrap())
807            .args(["--exact", "no_test_has_this_name"])
808            .stdout(std::process::Stdio::null())
809            .spawn()
810            .unwrap();
811        let pid = ended.id();
812        ended.wait().unwrap();
813        // Something listens there, and would be asked if the process weren't checked.
814        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
815        let port = listener.local_addr().unwrap().port();
816        fs::write(&path, note_for(port, pid)).unwrap();
817        let started = std::time::Instant::now();
818        let error = request_with(dir.path(), "take", Transport::Loopback).unwrap_err();
819        assert_eq!(error.kind(), ErrorKind::NotFound, "{error}");
820        assert!(started.elapsed() < Duration::from_secs(1));
821        assert!(!path.exists());
822        listener.set_nonblocking(true).unwrap();
823        assert!(listener.accept().is_err(), "it connected anyway");
824
825        // A refused port removes its note too, and quickly.
826        fs::write(&path, note_for(closed_port(), std::process::id())).unwrap();
827        let started = std::time::Instant::now();
828        assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
829        assert!(started.elapsed() < PROOF_TIME + Duration::from_secs(1));
830        assert!(!path.exists());
831    }
832
833    /// A Cellix that takes a connection and never answers holds a hook up for a few seconds
834    /// at most, whichever way it's reached. Only a plan waits on.
835    #[test]
836    fn a_silent_cellix_holds_no_hook_up() {
837        assert_eq!(patience("take"), Some(REPLY_TIME));
838        assert_eq!(patience("event {}"), Some(REPLY_TIME));
839        assert_eq!(patience("plan /tmp/p.md"), None);
840        let dir = tempfile::tempdir().unwrap();
841        let path = socket_path(dir.path());
842        fs::create_dir_all(path.parent().unwrap()).unwrap();
843
844        // Silent before proving itself.
845        let mute = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
846        fs::write(
847            &path,
848            note_for(mute.local_addr().unwrap().port(), std::process::id()),
849        )
850        .unwrap();
851        let started = std::time::Instant::now();
852        assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
853        let took = started.elapsed();
854        assert!(took < PROOF_TIME + Duration::from_secs(2), "{took:?}");
855        // A Cellix too slow to prove itself may only be busy, so its note stays.
856        assert!(path.exists());
857
858        // Proving itself, then silent: the reply time bounds it.
859        let listener = loopback::bind(&path).unwrap();
860        thread::spawn(move || {
861            for stream in listener.incoming() {
862                let admitted = listener.admit(stream);
863                thread::sleep(Duration::from_secs(30));
864                drop(admitted);
865            }
866        });
867        let started = std::time::Instant::now();
868        assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
869        let took = started.elapsed();
870        assert!(took >= REPLY_TIME / 2, "{took:?}");
871        assert!(took < REPLY_TIME + Duration::from_secs(2), "{took:?}");
872
873        #[cfg(unix)]
874        {
875            let _ = fs::remove_file(&path);
876            let socket = UnixListener::bind(&path).unwrap();
877            thread::spawn(move || {
878                let held: Vec<_> = socket.incoming().collect();
879                drop(held);
880            });
881            let started = std::time::Instant::now();
882            assert!(request_with(dir.path(), "take", Transport::Unix).is_err());
883            assert!(started.elapsed() < REPLY_TIME + Duration::from_secs(2));
884        }
885    }
886
887    /// Two starting at once can both find the place empty, and the second's file replaces the
888    /// first's. Closing the first leaves the second's alone.
889    #[test]
890    fn a_cellix_only_removes_its_own_socket_file() {
891        for transport in [Transport::NATIVE, Transport::Loopback] {
892            let dir = tempfile::tempdir().unwrap();
893            let first = start_with(dir.path(), Arc::default(), transport).unwrap();
894            let path = first.path.clone();
895            fs::remove_file(&path).unwrap();
896            let second = start_with(dir.path(), Arc::default(), transport).unwrap();
897            drop(first);
898            assert!(path.exists(), "{transport:?}");
899            assert_eq!(
900                request_with(dir.path(), "comments", transport).unwrap(),
901                "[]"
902            );
903            drop(second);
904            assert!(!path.exists(), "{transport:?}");
905        }
906    }
907
908    /// Windows keeps sockets in the user's local app data, not wherever TEMP points, and
909    /// doesn't name the folder for the user at all.
910    #[test]
911    fn windows_keeps_sockets_in_local_app_data() {
912        let var = |name: &str| match name {
913            "LOCALAPPDATA" => Some(r"C:\Users\Zoë\AppData\Local".to_string()),
914            "TEMP" => Some(r"D:\shared".to_string()),
915            _ => None,
916        };
917        let local = PathBuf::from(r"C:\Users\Zoë\AppData\Local");
918        assert_eq!(
919            windows_sockets_folder(var),
920            local.join("cellix").join("sockets")
921        );
922        let profile = |name: &str| (name == "USERPROFILE").then(|| r"C:\Users\Zoë".to_string());
923        let local = PathBuf::from(r"C:\Users\Zoë").join("AppData").join("Local");
924        assert_eq!(
925            windows_sockets_folder(profile),
926            local.join("cellix").join("sockets")
927        );
928        #[cfg(not(unix))]
929        assert_eq!(
930            socket_path(Path::new(r"C:\x")).parent(),
931            Some(windows_sockets_folder(|n| env::var(n).ok()).as_path())
932        );
933    }
934
935    #[test]
936    fn unknown_requests_get_an_error() {
937        let dir = tempfile::tempdir().unwrap();
938        let _server = start(dir.path(), Arc::default()).unwrap();
939        assert!(
940            request(dir.path(), "nonsense")
941                .unwrap()
942                .starts_with("error")
943        );
944    }
945}