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