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