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