1use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18use std::path::{Component, Path, PathBuf};
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct Claim {
23 pub pattern: String,
25 pub session: String,
26 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub harness: Option<String>,
29 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub pid: Option<u32>,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub pid_start: Option<String>,
35 pub worktree: String,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub branch: Option<String>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub note: Option<String>,
41 pub claimed_at: String,
42 pub expires_at: String,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Standing {
48 Live,
49 Expired,
50 WorktreeGone,
51 SessionGone,
52}
53
54impl Standing {
55 pub fn name(self) -> &'static str {
56 match self {
57 Self::Live => "live",
58 Self::Expired => "expired",
59 Self::WorktreeGone => "worktree gone",
60 Self::SessionGone => "session gone",
61 }
62 }
63}
64
65impl Claim {
66 pub fn standing(&self, now: i64) -> Standing {
67 if jouet_output::time::parse_utc(&self.expires_at).is_none_or(|t| t <= now) {
68 return Standing::Expired;
69 }
70 if !Path::new(&self.worktree).join(".git").exists() {
71 return Standing::WorktreeGone;
72 }
73 if let Some(pid) = self.pid
74 && !agent::running(pid, self.pid_start.as_deref())
75 {
76 return Standing::SessionGone;
77 }
78 Standing::Live
79 }
80
81 pub fn who(&self) -> String {
84 let id: String = self.session.chars().take(8).collect();
85 match &self.harness {
86 Some(h) => format!("{h} session {id}"),
87 None => format!("session {id}"),
88 }
89 }
90
91 pub fn covers(&self, path: &str) -> bool {
93 covers(&self.pattern, path)
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct Holder {
100 pub session: String,
101 pub harness: Option<String>,
102 pub pid: Option<u32>,
103}
104
105impl Holder {
106 pub fn from_env() -> Option<Self> {
111 let var = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
112 let (session, harness) = [
113 ("JOUET_SESSION_ID", None),
114 ("CLAUDE_CODE_SESSION_ID", Some("claude")),
115 ("CODEX_THREAD_ID", Some("codex")),
116 ]
117 .into_iter()
118 .find_map(|(name, harness)| Some((var(name)?, harness.map(str::to_string))))?;
119 let pid = match harness.as_deref() {
120 Some("claude") => var("CLAUDE_PID").and_then(|p| p.parse().ok()),
121 Some("codex") => agent::ancestor("codex"),
122 _ => None,
123 };
124 Some(Self {
125 session,
126 harness,
127 pid,
128 })
129 }
130}
131
132pub struct Store {
134 dir: PathBuf,
135 root: PathBuf,
137}
138
139#[derive(Debug)]
141pub enum Refused {
142 Conflicts(Vec<Conflict>),
144 Io(String),
146}
147
148#[derive(Debug)]
150pub struct Conflict {
151 pub wanted: String,
152 pub held: Claim,
153}
154
155impl Store {
156 pub fn open(state: &Path, cwd: &Path) -> Option<Self> {
159 let root = jouet_output::paths::work_tree(cwd)?;
160 let common = common_dir(&root)?;
161 let digest = Sha256::digest(common.to_string_lossy().as_bytes());
162 let key: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
163 Some(Self {
164 dir: state.join(key),
165 root,
166 })
167 }
168
169 pub fn root(&self) -> &Path {
171 &self.root
172 }
173
174 pub fn all(&self, now: i64) -> Vec<(Claim, Standing)> {
176 let Ok(entries) = std::fs::read_dir(&self.dir) else {
177 return Vec::new();
178 };
179 let mut claims: Vec<(Claim, Standing)> = entries
180 .flatten()
181 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
182 .filter_map(|e| std::fs::read(e.path()).ok())
183 .filter_map(|bytes| serde_json::from_slice::<Claim>(&bytes).ok())
184 .map(|c| {
185 let standing = c.standing(now);
186 (c, standing)
187 })
188 .collect();
189 claims.sort_by(|a, b| (&a.0.pattern, &a.0.session).cmp(&(&b.0.pattern, &b.0.session)));
190 claims
191 }
192
193 pub fn live(&self, now: i64) -> Vec<Claim> {
195 self.all(now)
196 .into_iter()
197 .filter(|(_, s)| *s == Standing::Live)
198 .map(|(c, _)| c)
199 .collect()
200 }
201
202 pub fn prune(&self, now: i64) -> Vec<(Claim, Standing)> {
204 let dead: Vec<(Claim, Standing)> = self
205 .all(now)
206 .into_iter()
207 .filter(|(_, s)| *s != Standing::Live)
208 .collect();
209 for (claim, _) in &dead {
210 let _ = std::fs::remove_file(self.file(&claim.session, &claim.pattern));
211 }
212 dead
213 }
214
215 pub fn claim(
219 &self,
220 holder: &Holder,
221 patterns: &[String],
222 expires: i64,
223 note: Option<&str>,
224 now: i64,
225 ) -> Result<Vec<Claim>, Refused> {
226 let others: Vec<Claim> = self
227 .live(now)
228 .into_iter()
229 .filter(|c| c.session != holder.session)
230 .collect();
231 let conflicts: Vec<Conflict> = patterns
232 .iter()
233 .flat_map(|p| {
234 others
235 .iter()
236 .filter(|c| overlaps(p, &c.pattern))
237 .map(|c| Conflict {
238 wanted: p.clone(),
239 held: c.clone(),
240 })
241 })
242 .collect();
243 if !conflicts.is_empty() {
244 return Err(Refused::Conflicts(conflicts));
245 }
246 let worktree = self.root.to_string_lossy().into_owned();
247 let branch = branch(&self.root);
248 let pid_start = holder.pid.and_then(agent::start_time);
249 let claims: Vec<Claim> = patterns
250 .iter()
251 .map(|pattern| Claim {
252 pattern: pattern.clone(),
253 session: holder.session.clone(),
254 harness: holder.harness.clone(),
255 pid: holder.pid.filter(|_| pid_start.is_some()),
256 pid_start: pid_start.clone(),
257 worktree: worktree.clone(),
258 branch: branch.clone(),
259 note: note.map(str::to_string),
260 claimed_at: jouet_output::time::format_utc(now),
261 expires_at: jouet_output::time::format_utc(expires),
262 })
263 .collect();
264 for claim in &claims {
265 self.save(claim).map_err(Refused::Io)?;
266 }
267 Ok(claims)
268 }
269
270 fn save(&self, claim: &Claim) -> Result<(), String> {
271 std::fs::create_dir_all(&self.dir)
272 .map_err(|e| format!("creating {}: {e}", self.dir.display()))?;
273 let path = self.file(&claim.session, &claim.pattern);
274 let tmp = path.with_extension("tmp");
275 let json = serde_json::to_vec_pretty(claim).map_err(|e| e.to_string())?;
276 std::fs::write(&tmp, json).map_err(|e| format!("writing {}: {e}", tmp.display()))?;
277 std::fs::rename(&tmp, &path).map_err(|e| format!("writing {}: {e}", path.display()))
278 }
279
280 pub fn release(&self, session: &str, patterns: &[String], now: i64) -> Vec<Claim> {
283 let mine: Vec<Claim> = self
284 .all(now)
285 .into_iter()
286 .map(|(c, _)| c)
287 .filter(|c| c.session == session)
288 .filter(|c| patterns.is_empty() || patterns.contains(&c.pattern))
289 .collect();
290 for claim in &mine {
291 let _ = std::fs::remove_file(self.file(&claim.session, &claim.pattern));
292 }
293 mine
294 }
295
296 fn file(&self, session: &str, pattern: &str) -> PathBuf {
297 let digest = Sha256::digest(format!("{session}\0{pattern}").as_bytes());
298 let name: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
299 self.dir.join(format!("{name}.json"))
300 }
301
302 pub fn pattern(&self, cwd: &Path, arg: &str) -> Result<String, String> {
306 let glob = arg.contains(['*', '?', '[']);
307 let mut pattern = relative(&self.root, cwd, arg).ok_or_else(|| {
308 format!(
309 "`{arg}` is outside this repository ({})",
310 self.root.display()
311 )
312 })?;
313 if pattern.is_empty() {
314 return Err(format!(
315 "`{arg}` is the whole repository: claim the files or directories you work on"
316 ));
317 }
318 if !glob && (arg.ends_with('/') || cwd.join(arg).is_dir()) {
319 pattern.push('/');
320 }
321 Ok(pattern)
322 }
323}
324
325pub fn relative(root: &Path, cwd: &Path, path: &str) -> Option<String> {
329 let resolved = resolve(&cwd.join(path));
330 let holder = resolved
331 .ancestors()
332 .find(|dir| dir.exists())
333 .and_then(jouet_output::paths::work_tree)
334 .filter(|r| r.starts_with(root) && r != root)
335 .filter(|r| common_dir(r).is_some() && common_dir(r) == common_dir(root));
336 let rel = resolved
337 .strip_prefix(holder.as_deref().unwrap_or(root))
338 .ok()?;
339 Some(
340 rel.components()
341 .map(|c| c.as_os_str().to_string_lossy())
342 .collect::<Vec<_>>()
343 .join("/"),
344 )
345}
346
347fn resolve(path: &Path) -> PathBuf {
350 let mut clean = PathBuf::new();
351 for part in path.components() {
352 match part {
353 Component::ParentDir => {
354 clean.pop();
355 }
356 Component::CurDir => {}
357 other => clean.push(other),
358 }
359 }
360 let mut existing = clean.as_path();
361 let mut rest = Vec::new();
362 while !existing.exists() {
363 let (Some(parent), Some(name)) = (existing.parent(), existing.file_name()) else {
364 return clean;
365 };
366 rest.push(name.to_os_string());
367 existing = parent;
368 }
369 let mut out = existing.canonicalize().unwrap_or_else(|_| existing.into());
370 out.extend(rest.iter().rev());
371 out
372}
373
374pub fn common_dir(root: &Path) -> Option<PathBuf> {
378 let git = root.join(".git");
379 if git.is_dir() {
380 return git.canonicalize().ok();
381 }
382 let gitdir = git_dir(root)?;
383 let common = std::fs::read_to_string(gitdir.join("commondir")).ok();
384 let dir = match common {
385 Some(c) => gitdir.join(c.trim()),
386 None => gitdir,
387 };
388 dir.canonicalize().ok()
389}
390
391pub fn git_dir(root: &Path) -> Option<PathBuf> {
393 let git = root.join(".git");
394 if git.is_dir() {
395 return Some(git);
396 }
397 let text = std::fs::read_to_string(&git).ok()?;
398 let dir = text.lines().find_map(|l| l.strip_prefix("gitdir:"))?.trim();
399 Some(root.join(dir))
400}
401
402pub fn branch(root: &Path) -> Option<String> {
404 let head = std::fs::read_to_string(git_dir(root)?.join("HEAD")).ok()?;
405 head.trim()
406 .strip_prefix("ref: refs/heads/")
407 .map(str::to_string)
408}
409
410pub fn covers(pattern: &str, path: &str) -> bool {
412 let path = path.trim_end_matches('/');
413 if let Some(dir) = pattern.strip_suffix('/') {
414 return path == dir || path.starts_with(pattern);
415 }
416 if pattern.contains(['*', '?']) {
417 return wild(
418 &pattern.chars().collect::<Vec<_>>(),
419 &path.chars().collect::<Vec<_>>(),
420 );
421 }
422 pattern == path
423}
424
425pub fn overlaps(a: &str, b: &str) -> bool {
429 let literal = |p: &str| !p.contains(['*', '?']);
430 match (literal(a), literal(b)) {
431 (true, _) if covers(b, a) || covers(a, b) => true,
432 (_, true) if covers(a, b) || covers(b, a) => true,
433 (true, true) => {
434 a.ends_with('/') && b.starts_with(a) || b.ends_with('/') && a.starts_with(b)
436 }
437 (false, false) => {
438 let stem = |p: &str| p[..p.find(['*', '?']).unwrap_or(p.len())].to_string();
439 let (x, y) = (stem(a), stem(b));
440 x.starts_with(&y) || y.starts_with(&x)
441 }
442 (true, false) => a.ends_with('/') && b.starts_with(a),
444 (false, true) => b.ends_with('/') && a.starts_with(b),
445 }
446}
447
448fn wild(p: &[char], t: &[char]) -> bool {
451 match p.first() {
452 None => t.is_empty(),
453 Some('*') if p.get(1) == Some(&'*') => {
454 let rest = &p[2..];
455 let after_slash = rest.strip_prefix(&['/']).unwrap_or(rest);
456 (0..=t.len()).any(|i| wild(rest, &t[i..]))
457 || (rest.len() != after_slash.len() && wild(after_slash, t))
458 }
459 Some('*') => {
460 for i in 0..=t.len() {
461 if wild(&p[1..], &t[i..]) {
462 return true;
463 }
464 if t.get(i) == Some(&'/') {
465 return false;
466 }
467 }
468 false
469 }
470 Some('?') => t.first().is_some_and(|c| *c != '/') && wild(&p[1..], &t[1..]),
471 Some(c) => t.first() == Some(c) && wild(&p[1..], &t[1..]),
472 }
473}
474
475mod agent {
477 use std::process::{Command, Stdio};
478
479 pub(super) fn running(pid: u32, recorded: Option<&str>) -> bool {
483 if cfg!(windows) {
484 return true;
485 }
486 match (start_time(pid), recorded) {
487 (None, _) => false,
488 (Some(now), Some(then)) => now == then,
489 (Some(_), None) => true,
490 }
491 }
492
493 #[cfg(target_os = "linux")]
496 pub(super) fn start_time(pid: u32) -> Option<String> {
497 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
498 let (_, rest) = stat.rsplit_once(')')?;
499 let fields: Vec<&str> = rest.split_whitespace().collect();
500 if fields.first() == Some(&"Z") {
501 return None;
502 }
503 fields.get(19).map(|s| (*s).to_string())
505 }
506
507 #[cfg(not(target_os = "linux"))]
508 pub(super) fn start_time(pid: u32) -> Option<String> {
509 let out = Command::new("ps")
510 .args(["-o", "lstart=", "-p", &pid.to_string()])
511 .stdin(Stdio::null())
512 .stderr(Stdio::null())
513 .output()
514 .ok()?;
515 let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
516 (out.status.success() && !text.is_empty()).then_some(text)
517 }
518
519 pub(super) fn ancestor(name: &str) -> Option<u32> {
521 let (mut pid, _) = info(std::process::id())?;
522 for _ in 0..16 {
523 if pid <= 1 {
524 return None;
525 }
526 let (parent, comm) = info(pid)?;
527 if comm.starts_with(name) {
528 return Some(pid);
529 }
530 pid = parent;
531 }
532 None
533 }
534
535 fn info(pid: u32) -> Option<(u32, String)> {
537 let out = Command::new("ps")
538 .args(["-o", "ppid=,comm=", "-p", &pid.to_string()])
539 .stdin(Stdio::null())
540 .stderr(Stdio::null())
541 .output()
542 .ok()?;
543 let text = String::from_utf8_lossy(&out.stdout);
544 let mut fields = text.split_whitespace();
545 let ppid = fields.next()?.parse().ok()?;
546 let comm = fields.collect::<Vec<_>>().join(" ");
547 let base = comm.rsplit('/').next().unwrap_or(&comm).to_string();
548 Some((ppid, base))
549 }
550}
551
552#[cfg(test)]
553mod tests {
554 use super::*;
555
556 #[test]
557 fn patterns_cover_files_directories_and_globs() {
558 assert!(covers("src/a.rs", "src/a.rs"));
559 assert!(!covers("src/a.rs", "src/a.rsx"));
560 assert!(covers("src/", "src/deep/b.rs"));
561 assert!(covers("src/", "src"));
562 assert!(!covers("src/", "srcs/b.rs"));
563 assert!(covers("src/*.rs", "src/a.rs"));
564 assert!(!covers("src/*.rs", "src/deep/a.rs"));
565 assert!(covers("src/**/*.rs", "src/deep/a.rs"));
566 assert!(covers("src/**/*.rs", "src/a.rs"));
567 assert!(covers("docs/**", "docs/a/b.md"));
568 }
569
570 #[test]
571 fn overlap_is_symmetric_and_errs_toward_yes() {
572 for (a, b, want) in [
573 ("src/a.rs", "src/a.rs", true),
574 ("src/", "src/a.rs", true),
575 ("src/a.rs", "docs/", false),
576 ("src/*.rs", "src/a.rs", true),
577 ("src/*.rs", "docs/a.rs", false),
578 ("src/", "src/**/*.rs", true),
579 ("src/**", "src/cmd/*.rs", true),
580 ("docs/*.md", "src/*.rs", false),
581 ("src/cmd/", "src/", true),
582 ] {
583 assert_eq!(overlaps(a, b), want, "{a} vs {b}");
584 assert_eq!(overlaps(b, a), want, "{b} vs {a}");
585 }
586 }
587
588 fn holder(id: &str) -> Holder {
589 Holder {
590 session: id.into(),
591 harness: Some("claude".into()),
592 pid: None,
593 }
594 }
595
596 fn git(dir: &Path, args: &[&str]) {
597 let ok = std::process::Command::new("git")
598 .args(args)
599 .current_dir(dir)
600 .env("GIT_CONFIG_GLOBAL", "/dev/null")
601 .env("GIT_CONFIG_NOSYSTEM", "1")
602 .output()
603 .unwrap()
604 .status
605 .success();
606 assert!(ok, "git {args:?}");
607 }
608
609 #[test]
610 fn worktrees_of_one_repository_share_claims() {
611 let tmp = tempfile::tempdir().unwrap();
612 let main = tmp.path().join("main");
613 std::fs::create_dir_all(main.join("src")).unwrap();
614 git(&main, &["init", "-q", "-b", "main"]);
615 std::fs::write(main.join("src/a.rs"), "a").unwrap();
616 git(&main, &["add", "."]);
617 git(
618 &main,
619 &[
620 "-c",
621 "user.name=t",
622 "-c",
623 "user.email=t@t",
624 "commit",
625 "-qm",
626 "init",
627 ],
628 );
629 git(&main, &["worktree", "add", "-q", "-b", "other", "../wt"]);
630 let wt = tmp.path().join("wt");
631 let state = tmp.path().join("state");
632 let a = Store::open(&state, &main.join("src")).unwrap();
633 let b = Store::open(&state, &wt).unwrap();
634 assert_eq!(a.dir, b.dir);
635 assert_eq!(branch(&b.root).as_deref(), Some("other"));
636
637 let now = 1_000_000;
638 let pattern = a.pattern(&main.join("src"), "a.rs").unwrap();
639 assert_eq!(pattern, "src/a.rs");
640 assert_eq!(a.pattern(&main, "src").unwrap(), "src/");
641 assert!(a.pattern(&main, ".").is_err());
642 assert!(a.pattern(&main, "../elsewhere").is_err());
643 let claimed = a
644 .claim(&holder("s1"), &[pattern], now + 60, Some("fixing"), now)
645 .unwrap();
646 assert_eq!(claimed[0].branch.as_deref(), Some("main"));
647
648 let held = b.live(now);
651 assert_eq!(held.len(), 1);
652 assert_eq!(held[0].session, "s1");
653 let Err(Refused::Conflicts(conflicts)) =
654 b.claim(&holder("s2"), &["src/".into()], now + 60, None, now)
655 else {
656 panic!("an overlapping claim should be refused");
657 };
658 assert_eq!(conflicts[0].held.pattern, "src/a.rs");
659 a.claim(&holder("s1"), &["src/a.rs".into()], now + 120, None, now)
661 .unwrap();
662 assert_eq!(a.live(now).len(), 1);
663
664 assert!(a.live(now + 200).is_empty());
666 assert_eq!(a.prune(now + 200)[0].1, Standing::Expired);
667 assert!(a.all(now).is_empty());
668
669 b.claim(&holder("s2"), &["docs/".into()], now + 60, None, now)
671 .unwrap();
672 git(&main, &["worktree", "remove", "--force", "../wt"]);
673 assert_eq!(a.all(now)[0].1, Standing::WorktreeGone);
674
675 assert!(a.release("s9", &[], now).is_empty());
676 assert_eq!(a.release("s2", &[], now).len(), 1);
677 }
678
679 #[test]
680 fn a_claim_lapses_when_its_agent_exits() {
681 let mut child = std::process::Command::new("sleep")
682 .arg("30")
683 .spawn()
684 .unwrap();
685 let pid = child.id();
686 let start = agent::start_time(pid);
687 assert!(start.is_some());
688 assert!(agent::running(pid, start.as_deref()));
689 assert!(!agent::running(pid, Some("not-its-start")));
690 child.kill().unwrap();
691 child.wait().unwrap();
692 assert!(!agent::running(pid, start.as_deref()));
693 }
694}