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