Skip to main content

jouet_git/
session.rs

1//! The last test, lint and build runs of an agent session, as `jouet
2//! setup`'s hooks record them in `$XDG_STATE_HOME/jouet/sessions/ID.json`,
3//! by the work tree each ran in:
4//! `{"trees": {"/src/app": {"runs": {"test": {"command": "cargo test", "exit_code": 0}}}}}`.
5//!
6//! Reading is best effort: no session ID, no file, or a file in a shape
7//! this build does not know all mean nothing was recorded.
8
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct CheckRun {
15    /// `test`, `lint` or `build`.
16    pub kind: String,
17    pub command: String,
18    pub exit_code: i32,
19}
20
21#[derive(Deserialize)]
22struct State {
23    #[serde(default)]
24    trees: BTreeMap<String, Tree>,
25}
26
27#[derive(Deserialize)]
28struct Tree {
29    #[serde(default)]
30    runs: BTreeMap<String, Run>,
31}
32
33#[derive(Deserialize)]
34struct Run {
35    command: String,
36    exit_code: i32,
37}
38
39/// The session ID to read: `JOUET_SESSION_ID`, else Claude Code's
40/// `CLAUDE_CODE_SESSION_ID`.
41pub fn id_from_env() -> Option<String> {
42    ["JOUET_SESSION_ID", "CLAUDE_CODE_SESSION_ID"]
43        .iter()
44        .filter_map(|name| std::env::var(name).ok())
45        .find(|v| !v.trim().is_empty())
46}
47
48/// The file the hooks keep for a session, named the way they name it.
49fn path(dir: &Path, id: &str) -> Option<PathBuf> {
50    let safe: String = id
51        .chars()
52        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
53        .take(128)
54        .collect();
55    (!safe.is_empty()).then(|| dir.join(format!("{safe}.json")))
56}
57
58/// The session's latest run of each kind of check in the work tree at
59/// `worktree`, or `None` when nothing was recorded there.
60pub fn last_checks(dir: &Path, id: &str, worktree: &Path) -> Option<Vec<CheckRun>> {
61    let bytes = std::fs::read(path(dir, id)?).ok()?;
62    let mut state: State = serde_json::from_slice(&bytes).ok()?;
63    // Keyed as the hooks key it: the root with symlinks resolved.
64    let root = worktree
65        .canonicalize()
66        .unwrap_or_else(|_| worktree.to_path_buf());
67    let tree = state.trees.remove(root.to_string_lossy().as_ref())?;
68    let runs: Vec<CheckRun> = tree
69        .runs
70        .into_iter()
71        .map(|(kind, run)| CheckRun {
72            kind,
73            command: run.command,
74            exit_code: run.exit_code,
75        })
76        .collect();
77    (!runs.is_empty()).then_some(runs)
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn reads_what_the_hooks_record() {
86        let dir = tempfile::tempdir().unwrap();
87        std::fs::write(
88            dir.path().join("abc-123.json"),
89            r#"{"trees":{"/src/app":{"runs":{"test":{"command":"cargo test","exit_code":101},"lint":{"command":"mise run lint","exit_code":0}}},"/src/other":{"runs":{"build":{"command":"cargo build","exit_code":0}}}}}"#,
90        )
91        .unwrap();
92        let app = Path::new("/src/app");
93        let runs = last_checks(dir.path(), "abc-123", app).unwrap();
94        assert_eq!(
95            runs,
96            [
97                CheckRun {
98                    kind: "lint".into(),
99                    command: "mise run lint".into(),
100                    exit_code: 0
101                },
102                CheckRun {
103                    kind: "test".into(),
104                    command: "cargo test".into(),
105                    exit_code: 101
106                },
107            ]
108        );
109        // Another work tree's runs are not this one's.
110        assert_eq!(
111            last_checks(dir.path(), "abc-123", Path::new("/src/elsewhere")),
112            None
113        );
114        assert_eq!(last_checks(dir.path(), "other", app), None);
115        assert_eq!(last_checks(dir.path(), "../../etc", app), None);
116        std::fs::write(dir.path().join("bad.json"), "not json").unwrap();
117        assert_eq!(last_checks(dir.path(), "bad", app), None);
118        std::fs::write(
119            dir.path().join("empty.json"),
120            r#"{"trees":{"/src/app":{"runs":{}}}}"#,
121        )
122        .unwrap();
123        assert_eq!(last_checks(dir.path(), "empty", app), None);
124    }
125}