1use crate::Guard;
18use fancy_regex::Regex;
19use jsrt::sync;
20use serde_json::{Value, json};
21use std::collections::{BTreeMap, HashMap, HashSet};
22use std::path::{Component, Path, PathBuf};
23use std::sync::mpsc::{Sender, channel};
24use std::sync::{Arc, Condvar, LazyLock, Mutex, PoisonError};
25use std::time::Duration;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Verdict {
30 Block(String),
31 Allow(Option<String>),
32}
33
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct CellChanges {
37 pub files: Vec<PathBuf>,
39 pub checked: Vec<PathBuf>,
41 pub deleted: Vec<PathBuf>,
42 pub complete: bool,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum AfterOutcome {
49 Clean,
51 Advisory,
53 Findings,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct AfterCellReport {
60 pub message: Option<String>,
62 pub outcome: AfterOutcome,
63}
64
65pub trait FileWriteGuard: Send + Sync {
67 fn name(&self) -> &str;
69 fn enabled(&self) -> bool {
71 true
72 }
73 fn checks_writes(&self) -> bool {
76 true
77 }
78 fn checks_shell(&self) -> bool {
79 true
80 }
81 fn timeout(&self) -> Option<Duration> {
84 Some(DEFAULT_BEFORE_WRITE_TIMEOUT)
85 }
86 fn before_write(&self, _path: &Path, _content: &str, _cwd: &Path, _lane: &str) -> Result<Verdict, String> {
89 Ok(Verdict::Allow(None))
90 }
91 fn before_shell(&self, _command: &str, _cwd: &Path) -> Result<Verdict, String> {
93 Ok(Verdict::Allow(None))
94 }
95 fn watches_cells(&self) -> bool {
98 false
99 }
100 fn after_cell_changes(
102 &self,
103 _changes: &CellChanges,
104 _cwd: &Path,
105 _lane: &str,
106 ) -> Result<Option<AfterCellReport>, String> {
107 Ok(None)
108 }
109 fn after_timeout(&self) -> Duration {
111 DEFAULT_AFTER_CELL_TIMEOUT
112 }
113}
114
115pub trait CellObserver: Send + Sync {
118 fn enabled(&self) -> bool {
120 true
121 }
122 fn cell_changed(&self, changes: &CellChanges, cwd: &Path, lane: &str) -> Vec<String>;
124 fn before_shell(&self, _command: &str, _lane: &str) -> Option<String> {
126 None
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct Snapshot {
133 pub root: PathBuf,
134 pub entries: BTreeMap<String, String>,
135 pub complete: bool,
136}
137
138pub type Snapshotter = Arc<dyn Fn(&Path) -> Result<Snapshot, String> + Send + Sync>;
139
140pub const OUTSIDE_WAIT: Duration = Duration::from_secs(60);
143
144#[derive(Clone, Default)]
149pub struct OutsideChanges {
150 state: Arc<(Mutex<OutsideState>, Condvar)>,
151}
152
153#[derive(Default)]
154struct OutsideState {
155 running: usize,
156 after: HashMap<PathBuf, Option<String>>,
158}
159
160pub struct OutsideWork {
163 changes: OutsideChanges,
164}
165
166impl OutsideChanges {
167 pub fn begin(&self) -> OutsideWork {
169 sync::lock(&self.state.0).running += 1;
170 OutsideWork { changes: self.clone() }
171 }
172
173 fn wait(&self, limit: Duration) {
175 let (state, ended) = &*self.state;
176 let mut state = sync::lock(state);
177 let end = std::time::Instant::now() + limit;
178 while state.running > 0 {
179 let left = end.saturating_duration_since(std::time::Instant::now());
180 if left.is_zero() {
181 return;
182 }
183 state = ended
184 .wait_timeout(state, left)
185 .unwrap_or_else(PoisonError::into_inner)
186 .0;
187 }
188 }
189
190 fn explains(&self, path: &Path, signature: Option<&String>) -> bool {
192 sync::lock(&self.state.0)
193 .after
194 .get(path)
195 .is_some_and(|left| left.as_ref() == signature)
196 }
197}
198
199impl OutsideWork {
200 pub fn record<R>(self, root: &Path, snapshot: &Snapshotter, work: impl FnOnce() -> R) -> R {
204 let before = snapshot(root);
205 let result = work();
206 if let (Ok(before), Ok(after)) = (before, snapshot(root)) {
207 let (added, modified, deleted, _) = diff_snapshots(&before, &after);
208 let mut state = sync::lock(&self.changes.state.0);
209 for relative in added.iter().chain(&modified) {
210 let signature = after.entries.get(relative).cloned();
211 state.after.insert(resolve_lexical(&after.root, relative), signature);
212 }
213 for relative in &deleted {
214 state.after.insert(resolve_lexical(&after.root, relative), None);
215 }
216 }
217 result
218 }
219}
220
221impl Drop for OutsideWork {
222 fn drop(&mut self) {
223 let (state, ended) = &*self.changes.state;
224 let mut state = sync::lock(state);
225 state.running = state.running.saturating_sub(1);
226 ended.notify_all();
227 }
228}
229
230pub const DEFAULT_AFTER_CELL_TIMEOUT: Duration = Duration::from_secs(120);
231pub const DEFAULT_BEFORE_WRITE_TIMEOUT: Duration = Duration::from_millis(5_000);
232
233#[derive(Debug, Clone, Default, PartialEq, Eq)]
235pub struct GuardStats {
236 pub name: String,
237 pub checks: u64,
239 pub blocked: u64,
240 pub unchecked: u64,
241 pub after_checks: u64,
243 pub after_findings: u64,
244 pub total_ms: u64,
246 pub turn_ms: u64,
247}
248
249impl GuardStats {
250 pub fn to_json(&self) -> Value {
252 json!({
253 "name": self.name,
254 "checks": self.checks,
255 "blocked": self.blocked,
256 "unchecked": self.unchecked,
257 "afterChecks": self.after_checks,
258 "afterFindings": self.after_findings,
259 "totalMs": self.total_ms,
260 "turnMs": self.turn_ms,
261 })
262 }
263}
264
265#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct GuardRecord {
268 pub guard: String,
269 pub phase: &'static str,
271 pub outcome: &'static str,
273 pub ms: u64,
274 pub paths: Vec<String>,
275 pub lane: String,
276 pub detail: Option<String>,
277}
278
279impl GuardRecord {
280 pub fn to_json(&self) -> Value {
282 let mut record = json!({
283 "guard": self.guard,
284 "phase": self.phase,
285 "outcome": self.outcome,
286 "ms": self.ms,
287 "paths": self.paths,
288 "lane": self.lane,
289 });
290 if let Some(detail) = &self.detail {
291 record["detail"] = json!(detail);
292 }
293 record
294 }
295}
296
297pub type OnRecord = Arc<dyn Fn(&GuardRecord) + Send + Sync>;
298pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
300
301fn js_seconds(timeout: Duration) -> String {
303 jsrt::number::to_string(jsrt::number::round(timeout.as_millis() as f64 / 100.0) / 10.0)
304}
305
306enum Answer<T> {
308 Value(T),
309 Error(String),
310 TimedOut,
311}
312
313fn timed<T: Send + 'static>(
316 timeout: Option<Duration>,
317 call: impl FnOnce() -> Result<T, String> + Send + 'static,
318) -> Answer<T> {
319 let (sender, answer) = channel();
320 std::thread::spawn(move || {
321 let _ = sender.send(call());
322 });
323 let received = match timeout {
324 Some(timeout) => answer.recv_timeout(timeout).ok(),
325 None => answer.recv().ok(),
326 };
327 match received {
328 Some(Ok(value)) => Answer::Value(value),
329 Some(Err(error)) => Answer::Error(error),
330 None => Answer::TimedOut,
331 }
332}
333
334type Pending = std::sync::mpsc::Receiver<Answer<Verdict>>;
336
337#[derive(Clone)]
339struct Registered {
340 guard: Arc<dyn FileWriteGuard>,
341 stats: Arc<Mutex<GuardStats>>,
342}
343const MAX_PENDING_CHARS: usize = 6_000;
345
346fn re(pattern: &str) -> Regex {
347 Regex::new(pattern).expect("static pattern")
348}
349
350static DEV_NULL: LazyLock<Regex> = LazyLock::new(|| re(r"[0-9]*>>?\s*/dev/null(?![A-Za-z0-9_])"));
352static FD_DUP: LazyLock<Regex> = LazyLock::new(|| re(r"[0-9]*>&[0-9]+"));
353static WRITERS: LazyLock<[Regex; 5]> = LazyLock::new(|| {
354 [
355 re(r"(^|[^<>-])>{1,2}\|?(?!&)"),
356 re(r"(^|[\s;&|(])(tee|cp|mv|install)\s"),
357 re(r"(^|[\s;&|(])sed\s+(?:[^|;&]*\s)?(-i|--in-place)"),
358 re(r"(^|[\s;&|(])perl\s+(?:[^|;&]*\s)?-[a-zA-Z]*i"),
359 re(r"(^|[\s;&|(])dd\s[^|;&]*\bof="),
360 ]
361});
362
363pub fn may_write_files(command: &str) -> bool {
366 let text = DEV_NULL.replace_all(command, " ");
367 let text = FD_DUP.replace_all(&text, " ");
368 WRITERS
369 .iter()
370 .any(|pattern| pattern.is_match(text.as_ref()).unwrap_or(false))
371}
372
373pub fn resolve_lexical(cwd: &Path, path: &str) -> PathBuf {
375 let mut out = PathBuf::from("/");
376 for component in cwd.join(path).components() {
377 match component {
378 Component::ParentDir => {
379 out.pop();
380 }
381 Component::Normal(part) => out.push(part),
382 _ => {}
383 }
384 }
385 out
386}
387
388pub fn inside(from: &Path, to: &Path) -> Option<String> {
390 let relative = to.strip_prefix(from).ok()?.to_string_lossy().into_owned();
391 (!relative.is_empty() && !relative.starts_with("..")).then_some(relative)
392}
393
394#[derive(Clone)]
397pub struct FileHooks {
398 inner: Arc<Inner>,
399}
400
401struct Inner {
402 cwd: PathBuf,
403 guards: Mutex<Vec<Registered>>,
404 observers: Mutex<Vec<Arc<dyn CellObserver>>>,
405 on_record: Mutex<Option<OnRecord>>,
406 now: Mutex<Clock>,
407 snapshot: Option<Snapshotter>,
408 checked: Mutex<HashMap<PathBuf, String>>,
410 pending: Mutex<HashMap<String, Vec<String>>>,
412 latest: Mutex<Option<Snapshot>>,
414 baselines: Mutex<HashMap<String, Snapshot>>,
418 claimed: Mutex<HashMap<String, HashMap<String, Option<String>>>>,
422 live: Mutex<HashSet<String>>,
424 outside: Mutex<Option<OutsideChanges>>,
426 protected: Mutex<Vec<Protected>>,
428 queued: Mutex<usize>,
430 idle: Condvar,
431 worker: Mutex<Option<Sender<CellEvent>>>,
432}
433
434enum CellEvent {
436 Started(String, Option<Snapshot>),
439 Ended(String),
440}
441
442struct Protected {
445 path: PathBuf,
446 named: String,
447}
448
449const PROTECTOR: &str = "Ultron";
451
452pub fn diff_snapshots(before: &Snapshot, after: &Snapshot) -> (Vec<String>, Vec<String>, Vec<String>, bool) {
454 let mut added = Vec::new();
455 let mut modified = Vec::new();
456 for (path, value) in &after.entries {
457 match before.entries.get(path) {
458 None => added.push(path.clone()),
459 Some(previous) if previous != value => modified.push(path.clone()),
460 Some(_) => {}
461 }
462 }
463 let deleted = before
464 .entries
465 .keys()
466 .filter(|path| !after.entries.contains_key(*path))
467 .cloned()
468 .collect();
469 (added, modified, deleted, before.complete && after.complete)
470}
471
472fn js_cut(text: &str, limit: usize) -> (String, usize) {
474 let units: Vec<u16> = text.encode_utf16().collect();
475 if units.len() <= limit {
476 return (text.to_string(), units.len());
477 }
478 (String::from_utf16_lossy(&units[..limit]), units.len())
479}
480
481impl FileHooks {
482 pub fn new(cwd: impl Into<PathBuf>) -> Self {
483 FileHooks {
484 inner: Arc::new(Inner {
485 cwd: cwd.into(),
486 guards: Mutex::new(Vec::new()),
487 observers: Mutex::new(Vec::new()),
488 on_record: Mutex::new(None),
489 now: Mutex::new({
490 let started = std::time::Instant::now();
491 Arc::new(move || started.elapsed().as_millis() as u64)
492 }),
493 snapshot: None,
494 checked: Mutex::new(HashMap::new()),
495 pending: Mutex::new(HashMap::new()),
496 latest: Mutex::new(None),
497 baselines: Mutex::new(HashMap::new()),
498 claimed: Mutex::new(HashMap::new()),
499 live: Mutex::new(HashSet::new()),
500 outside: Mutex::new(None),
501 protected: Mutex::new(Vec::new()),
502 queued: Mutex::new(0),
503 idle: Condvar::new(),
504 worker: Mutex::new(None),
505 }),
506 }
507 }
508
509 pub fn with_snapshots(cwd: impl Into<PathBuf>, snapshot: Snapshotter) -> Self {
511 let mut hooks = FileHooks::new(cwd);
512 if let Some(inner) = Arc::get_mut(&mut hooks.inner) {
513 inner.snapshot = Some(snapshot);
514 }
515 hooks
516 }
517
518 pub fn add(&mut self, guard: Box<dyn FileWriteGuard>) {
519 let stats = GuardStats {
520 name: guard.name().to_string(),
521 ..GuardStats::default()
522 };
523 sync::lock(&self.inner.guards).push(Registered {
524 guard: Arc::from(guard),
525 stats: Arc::new(Mutex::new(stats)),
526 });
527 }
528
529 pub fn protect(&self, paths: Vec<PathBuf>, home: &Path) {
533 let mut protected = Vec::new();
534 for path in paths {
535 let named = path.strip_prefix(home).unwrap_or(&path).to_string_lossy().into_owned();
536 if let Ok(real) = std::fs::canonicalize(&path).or_else(|_| {
538 let parent = std::fs::canonicalize(path.parent().unwrap_or(&path))?;
539 Ok::<_, std::io::Error>(parent.join(path.file_name().unwrap_or_default()))
540 }) && real != path
541 {
542 protected.push(Protected {
543 path: real,
544 named: named.clone(),
545 });
546 }
547 protected.push(Protected { path, named });
548 }
549 *sync::lock(&self.inner.protected) = protected;
550 }
551
552 fn protected_by(&self, path: &Path) -> Option<PathBuf> {
554 let real = path
555 .ancestors()
556 .find_map(|existing| {
557 let resolved = std::fs::canonicalize(existing).ok()?;
558 Some(resolved.join(path.strip_prefix(existing).ok()?))
559 })
560 .unwrap_or_else(|| path.to_path_buf());
561 sync::lock(&self.inner.protected)
562 .iter()
563 .find(|p| {
564 [path, real.as_path()]
565 .iter()
566 .any(|candidate| candidate.starts_with(&p.path))
567 })
568 .map(|p| p.path.clone())
569 }
570
571 fn protected_in_command(&self, command: &str) -> Option<PathBuf> {
573 sync::lock(&self.inner.protected)
574 .iter()
575 .find(|p| command.contains(&p.named))
576 .map(|p| p.path.clone())
577 }
578
579 pub fn observe(&self, observer: Arc<dyn CellObserver>) {
581 sync::lock(&self.inner.observers).push(observer);
582 }
583
584 pub fn ignore_outside(&self, changes: OutsideChanges) {
587 *sync::lock(&self.inner.outside) = Some(changes);
588 }
589
590 pub fn on_record(&self, on_record: OnRecord) {
592 *sync::lock(&self.inner.on_record) = Some(on_record);
593 }
594
595 pub fn set_clock(&self, now: Clock) {
597 *sync::lock(&self.inner.now) = now;
598 }
599
600 pub fn begin_turn(&self) {
602 for registered in sync::lock(&self.inner.guards).iter() {
603 sync::lock(®istered.stats).turn_ms = 0;
604 }
605 }
606
607 pub fn stats(&self) -> Vec<GuardStats> {
609 sync::lock(&self.inner.guards)
610 .iter()
611 .map(|registered| sync::lock(®istered.stats).clone())
612 .collect()
613 }
614
615 pub fn watches_cells(&self) -> bool {
617 self.inner.watches_cells()
618 }
619
620 pub fn cell_started(&self, lane: &str) {
624 let inner = &self.inner;
625 if !inner.watches_cells() {
626 return;
627 }
628 let concurrent = {
629 let mut live = sync::lock(&inner.live);
630 live.insert(lane.to_string());
631 live.len() > 1
632 };
633 let picture = (concurrent || sync::lock(&inner.latest).is_none())
634 .then(|| inner.picture())
635 .flatten();
636 self.send(CellEvent::Started(lane.to_string(), picture));
637 }
638
639 pub fn cell_ended(&self, lane: &str) {
643 let inner = &self.inner;
644 let watched = sync::lock(&inner.live).remove(lane);
645 if !inner.watches_cells() {
646 return;
647 }
648 if !watched {
649 if sync::lock(&inner.latest).is_none() {
650 let picture = inner.picture();
653 let mut latest = sync::lock(&inner.latest);
654 if latest.is_none() {
655 *latest = picture;
656 }
657 return;
658 }
659 self.send(CellEvent::Started(lane.to_string(), None));
661 }
662 self.send(CellEvent::Ended(lane.to_string()));
663 }
664
665 fn send(&self, event: CellEvent) {
666 let inner = &self.inner;
667 *sync::lock(&inner.queued) += 1;
668 let mut worker = sync::lock(&inner.worker);
669 let sender = worker.get_or_insert_with(|| {
670 let (sender, events) = channel::<CellEvent>();
671 let inner = Arc::downgrade(&self.inner);
672 std::thread::spawn(move || {
673 for event in events {
674 let Some(inner) = inner.upgrade() else {
675 return;
676 };
677 match event {
678 CellEvent::Started(lane, picture) => inner.started(lane, picture),
679 CellEvent::Ended(lane) => inner.after_cell(&lane),
680 }
681 let mut queued = sync::lock(&inner.queued);
682 *queued -= 1;
683 inner.idle.notify_all();
684 }
685 });
686 sender
687 });
688 if sender.send(event).is_err() {
689 *sync::lock(&inner.queued) -= 1;
690 }
691 }
692
693 pub fn settled(&self) {
695 let mut queued = sync::lock(&self.inner.queued);
696 while *queued > 0 {
697 queued = self.inner.idle.wait(queued).unwrap_or_else(PoisonError::into_inner);
698 }
699 }
700
701 pub fn take_pending(&self, lane: &str) -> Option<String> {
703 let pending = sync::lock(&self.inner.pending).remove(lane)?;
704 if pending.is_empty() {
705 return None;
706 }
707 let text = pending.join("\n");
708 let (head, total) = js_cut(&text, MAX_PENDING_CHARS);
709 Some(if total > MAX_PENDING_CHARS {
710 format!("{head}\n… ({} more characters of findings)", total - MAX_PENDING_CHARS)
711 } else {
712 text
713 })
714 }
715
716 fn display(&self, path: &Path) -> String {
718 self.inner.display(path)
719 }
720
721 fn refuse_protected(&self, lane: &str, phase: &'static str, protected: &Path) -> String {
723 let reason = format!(
724 "[{PROTECTOR}] {} is the user's to change (the profile's settings, keys and skills): a cell may not write \
725 it. Ask the user to make the change.",
726 protected.display()
727 );
728 self.inner.record(GuardRecord {
729 guard: PROTECTOR.into(),
730 phase,
731 outcome: "blocked",
732 ms: 0,
733 paths: vec![protected.display().to_string()],
734 lane: lane.to_string(),
735 detail: Some(reason.clone()),
736 });
737 reason
738 }
739
740 fn guards(&self) -> Vec<Registered> {
741 sync::lock(&self.inner.guards).clone()
742 }
743}
744
745impl Inner {
746 fn watching(guard: &dyn FileWriteGuard) -> bool {
747 guard.enabled() && guard.watches_cells()
748 }
749
750 fn watches_cells(&self) -> bool {
751 self.snapshot.is_some()
752 && (sync::lock(&self.guards).iter().any(|r| Inner::watching(&*r.guard))
753 || sync::lock(&self.observers).iter().any(|observer| observer.enabled()))
754 }
755
756 fn now(&self) -> u64 {
757 let clock = sync::lock(&self.now).clone();
758 clock()
759 }
760
761 fn record(&self, record: GuardRecord) {
762 let on_record = sync::lock(&self.on_record).clone();
763 if let Some(on_record) = on_record {
764 on_record(&record);
765 }
766 }
767
768 fn display(&self, path: &Path) -> String {
770 inside(&self.cwd, path).unwrap_or_else(|| path.to_string_lossy().into_owned())
771 }
772
773 fn picture(&self) -> Option<Snapshot> {
774 self.snapshot.as_ref().and_then(|snapshot| snapshot(&self.cwd).ok())
775 }
776
777 fn started(&self, lane: String, picture: Option<Snapshot>) {
779 let mut latest = sync::lock(&self.latest);
780 let Some(baseline) = picture.or_else(|| latest.clone()) else {
781 return;
782 };
783 latest.get_or_insert_with(|| baseline.clone());
784 sync::lock(&self.claimed).remove(&lane);
785 sync::lock(&self.baselines).insert(lane, baseline);
786 }
787
788 fn after_cell(&self, lane: &str) {
791 let before = sync::lock(&self.baselines).remove(lane);
792 let outside = sync::lock(&self.outside).clone();
793 if let Some(outside) = &outside {
794 outside.wait(OUTSIDE_WAIT);
795 }
796 let after = self.picture();
797 if let Some(after) = &after {
798 *sync::lock(&self.latest) = Some(after.clone());
799 }
800 let (Some(before), Some(after)) = (before, after) else {
801 return;
802 };
803 if before.root != after.root {
804 return;
805 }
806 let (mut added, mut modified, mut deleted, complete) = diff_snapshots(&before, &after);
807 {
808 let mut claimed = sync::lock(&self.claimed);
809 if let Some(theirs) = claimed.remove(lane) {
810 let unchanged = |relative: &String| theirs.get(relative) == Some(&after.entries.get(relative).cloned());
811 added.retain(|relative| !unchanged(relative));
812 modified.retain(|relative| !unchanged(relative));
813 deleted.retain(|relative| !unchanged(relative));
814 }
815 for other in sync::lock(&self.baselines).keys() {
816 let theirs = claimed.entry(other.clone()).or_default();
817 for relative in added.iter().chain(&modified).chain(&deleted) {
818 theirs.insert(relative.clone(), after.entries.get(relative).cloned());
819 }
820 }
821 }
822 if let Some(outside) = &outside {
823 let theirs = |relative: &String| {
824 outside.explains(&resolve_lexical(&after.root, relative), after.entries.get(relative))
825 };
826 added.retain(|relative| !theirs(relative));
827 modified.retain(|relative| !theirs(relative));
828 deleted.retain(|relative| !theirs(relative));
829 }
830 let elsewhere: Vec<PathBuf> = {
832 let mut checked = sync::lock(&self.checked);
833 let outside: Vec<PathBuf> = checked
834 .keys()
835 .filter(|p| inside(&after.root, p).is_none())
836 .cloned()
837 .collect();
838 outside
839 .into_iter()
840 .filter(|path| {
841 let approved = checked.remove(path);
842 approved.is_some_and(|approved| {
843 std::fs::read(path).is_ok_and(|now| jsrt::hash::sha256_hex(&now) == approved)
844 })
845 })
846 .collect()
847 };
848 if added.is_empty() && modified.is_empty() && deleted.is_empty() && elsewhere.is_empty() {
849 return;
850 }
851 let mut changes = CellChanges {
852 complete,
853 checked: elsewhere,
854 ..CellChanges::default()
855 };
856 for relative in added.iter().chain(&modified) {
857 let path = resolve_lexical(&after.root, relative);
858 let approved = sync::lock(&self.checked).remove(&path);
859 if let Some(approved) = approved
860 && std::fs::read(&path).is_ok_and(|current| jsrt::hash::sha256_hex(¤t) == approved)
861 {
862 changes.checked.push(path);
863 continue;
864 }
865 changes.files.push(path);
866 }
867 for relative in &deleted {
868 let path = resolve_lexical(&after.root, relative);
869 sync::lock(&self.checked).remove(&path);
870 changes.deleted.push(path);
871 }
872 let guards: Vec<Registered> = sync::lock(&self.guards)
873 .iter()
874 .filter(|r| Inner::watching(&*r.guard))
875 .cloned()
876 .collect();
877 let paths: Vec<String> = changes
878 .files
879 .iter()
880 .chain(&changes.checked)
881 .map(|path| self.display(path))
882 .collect();
883 let changes = Arc::new(changes);
884 let calls: Vec<_> = guards
886 .into_iter()
887 .map(|registered| {
888 let started = self.now();
889 let (task, cwd, lane_name, checked) = (
890 registered.guard.clone(),
891 self.cwd.clone(),
892 lane.to_string(),
893 changes.clone(),
894 );
895 let limit = registered.guard.after_timeout();
896 let (sender, receiver) = channel();
897 std::thread::spawn(move || {
898 let _ = sender.send(timed(Some(limit), move || {
899 task.after_cell_changes(&checked, &cwd, &lane_name)
900 }));
901 });
902 (registered, started, receiver)
903 })
904 .collect();
905 let mut found = Vec::new();
906 for (registered, started, receiver) in calls {
907 let answer = receiver.recv().unwrap_or(Answer::TimedOut);
908 let ms = self.now().saturating_sub(started);
909 let name = registered.guard.name().to_string();
910 let (text, outcome) = match answer {
911 Answer::TimedOut => (
912 Some(format!("{name} did not finish checking the files this cell changed.")),
913 "unchecked",
914 ),
915 Answer::Error(error) => (
916 Some(format!("{name} could not check the files this cell changed: {error}")),
917 "unchecked",
918 ),
919 Answer::Value(None) => (None, "clean"),
920 Answer::Value(Some(report)) => (
921 report.message.filter(|m| !m.is_empty()),
922 match report.outcome {
923 AfterOutcome::Clean => "clean",
924 AfterOutcome::Advisory => "advisory",
925 AfterOutcome::Findings => "findings",
926 },
927 ),
928 };
929 {
930 let mut stats = sync::lock(®istered.stats);
931 stats.total_ms += ms;
932 stats.turn_ms += ms;
933 stats.after_checks += 1;
934 if matches!(outcome, "findings" | "unchecked") {
935 stats.after_findings += 1;
936 }
937 }
938 self.record(GuardRecord {
939 guard: name.clone(),
940 phase: "after_cell",
941 outcome,
942 ms,
943 paths: paths.clone(),
944 lane: lane.to_string(),
945 detail: text.clone(),
946 });
947 if let Some(text) = text {
948 found.push(format!("[{name}] {text}"));
949 }
950 }
951 let observers: Vec<Arc<dyn CellObserver>> = sync::lock(&self.observers)
952 .iter()
953 .filter(|observer| observer.enabled())
954 .cloned()
955 .collect();
956 for observer in observers {
957 found.extend(observer.cell_changed(&changes, &self.cwd, lane));
958 }
959 if !found.is_empty() {
960 sync::lock(&self.pending)
961 .entry(lane.to_string())
962 .or_default()
963 .extend(found);
964 }
965 }
966}
967
968impl Guard for FileHooks {
969 fn before_shell(&self, lane: &str, command: &str) -> Option<String> {
973 let observers: Vec<Arc<dyn CellObserver>> = sync::lock(&self.inner.observers)
974 .iter()
975 .filter(|observer| observer.enabled())
976 .cloned()
977 .collect();
978 if let Some(reason) = observers
979 .iter()
980 .find_map(|observer| observer.before_shell(command, lane))
981 {
982 return Some(reason);
983 }
984 if let Some(path) = may_write_files(command)
985 .then(|| self.protected_in_command(command))
986 .flatten()
987 {
988 return Some(self.refuse_protected(lane, "before_shell", &path));
989 }
990 let guards: Vec<Registered> = self
991 .guards()
992 .into_iter()
993 .filter(|r| r.guard.checks_shell() && r.guard.enabled())
994 .collect();
995 if guards.is_empty() || !may_write_files(command) {
996 return None;
997 }
998 let display = if command.encode_utf16().count() > 80 {
999 format!("{}...", js_cut(command, 77).0)
1000 } else {
1001 command.to_string()
1002 };
1003 let calls: Vec<(Registered, u64, Pending)> = guards
1004 .into_iter()
1005 .map(|registered| {
1006 let started = self.inner.now();
1007 let timeout = registered.guard.timeout();
1008 let (guard, command, cwd) = (registered.guard.clone(), command.to_string(), self.inner.cwd.clone());
1009 let (sender, receiver) = channel();
1010 std::thread::spawn(move || {
1011 let _ = sender.send(timed(timeout, move || guard.before_shell(&command, &cwd)));
1012 });
1013 (registered, started, receiver)
1014 })
1015 .collect();
1016 let mut reasons = Vec::new();
1017 for (registered, started, receiver) in calls {
1018 let answer = receiver.recv().unwrap_or(Answer::TimedOut);
1019 let ms = self.inner.now().saturating_sub(started);
1020 let name = registered.guard.name().to_string();
1021 let mut stats = sync::lock(®istered.stats);
1022 stats.total_ms += ms;
1023 stats.turn_ms += ms;
1024 stats.checks += 1;
1025 let (outcome, reason) = match answer {
1026 Answer::TimedOut | Answer::Error(_) => {
1027 stats.unchecked += 1;
1028 ("unchecked", None)
1029 }
1030 Answer::Value(Verdict::Block(reason)) => {
1031 stats.blocked += 1;
1032 ("blocked", Some(format!("[{name}] {reason}")))
1033 }
1034 Answer::Value(Verdict::Allow(_)) => ("allowed", None),
1035 };
1036 drop(stats);
1037 self.inner.record(GuardRecord {
1038 guard: name,
1039 phase: "before_shell",
1040 outcome,
1041 ms,
1042 paths: vec![display.clone()],
1043 lane: lane.to_string(),
1044 detail: reason.clone(),
1045 });
1046 reasons.extend(reason);
1047 }
1048 (!reasons.is_empty()).then(|| reasons.join("\n"))
1049 }
1050
1051 fn before_write(&self, lane: &str, path: &str, content: &str) -> Value {
1053 let path = resolve_lexical(&self.inner.cwd, path);
1054 if let Some(protected) = self.protected_by(&path) {
1055 let reason = self.refuse_protected(lane, "before_write", &protected);
1056 return json!({ "blocked": true, "reason": reason, "notes": [] });
1057 }
1058 let display = self.display(&path);
1059 let calls: Vec<(Registered, u64, Option<Duration>, Pending)> = self
1060 .guards()
1061 .into_iter()
1062 .filter(|r| r.guard.checks_writes() && r.guard.enabled())
1063 .map(|registered| {
1064 let started = self.inner.now();
1065 let timeout = registered.guard.timeout();
1066 let (guard, path, content, cwd, lane) = (
1067 registered.guard.clone(),
1068 path.clone(),
1069 content.to_string(),
1070 self.inner.cwd.clone(),
1071 lane.to_string(),
1072 );
1073 let (sender, receiver) = channel();
1075 std::thread::spawn(move || {
1076 let _ = sender.send(timed(timeout, move || guard.before_write(&path, &content, &cwd, &lane)));
1077 });
1078 (registered, started, timeout, receiver)
1079 })
1080 .collect();
1081 let mut reasons = Vec::new();
1082 let mut notes = Vec::new();
1083 for (registered, started, timeout, receiver) in calls {
1084 let answer = receiver.recv().unwrap_or(Answer::TimedOut);
1085 let ms = self.inner.now().saturating_sub(started);
1086 let name = registered.guard.name().to_string();
1087 let mut stats = sync::lock(®istered.stats);
1088 stats.total_ms += ms;
1089 stats.turn_ms += ms;
1090 stats.checks += 1;
1091 let (outcome, reason, note) = match answer {
1092 Answer::TimedOut => {
1093 stats.unchecked += 1;
1094 let limit = js_seconds(timeout.unwrap_or_default());
1095 let note = format!(
1096 "[{name}] {name} did not check this write to {display} (no answer within {limit} s); it was written unchecked."
1097 );
1098 ("unchecked", None, Some(note))
1099 }
1100 Answer::Error(error) => {
1101 stats.unchecked += 1;
1102 let note = format!(
1103 "[{name}] {name} did not check this write to {display} ({error}); it was written unchecked."
1104 );
1105 ("unchecked", None, Some(note))
1106 }
1107 Answer::Value(Verdict::Block(reason)) => {
1108 stats.blocked += 1;
1109 ("blocked", Some(format!("[{name}] {reason}")), None)
1110 }
1111 Answer::Value(Verdict::Allow(Some(message))) if !message.is_empty() => {
1112 ("allowed", None, Some(format!("[{name}] {message}")))
1113 }
1114 Answer::Value(Verdict::Allow(_)) => ("allowed", None, None),
1115 };
1116 drop(stats);
1117 self.inner.record(GuardRecord {
1118 guard: name,
1119 phase: "before_write",
1120 outcome,
1121 ms,
1122 paths: vec![display.clone()],
1123 lane: lane.to_string(),
1124 detail: reason.clone(),
1125 });
1126 reasons.extend(reason);
1127 notes.extend(note);
1128 }
1129 if reasons.is_empty() {
1130 sync::lock(&self.inner.checked).insert(path, jsrt::hash::sha256_hex(content.as_bytes()));
1132 json!({ "blocked": false, "notes": notes })
1133 } else {
1134 json!({ "blocked": true, "reason": reasons.join("\n"), "notes": notes })
1135 }
1136 }
1137
1138 fn guard_stats(&self) -> Vec<Value> {
1139 self.stats().iter().map(GuardStats::to_json).collect()
1140 }
1141
1142 fn begin_turn(&self) {
1143 FileHooks::begin_turn(self);
1144 }
1145
1146 fn cell_started(&self, lane: &str) {
1147 FileHooks::cell_started(self, lane);
1148 }
1149
1150 fn cell_ended(&self, lane: &str) {
1151 FileHooks::cell_ended(self, lane);
1152 }
1153
1154 fn take_pending(&self, lane: &str) -> Option<String> {
1155 FileHooks::take_pending(self, lane)
1156 }
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161 use super::*;
1162
1163 #[test]
1164 fn host_inside_matches_path_relative() {
1165 let root = Path::new("/r");
1166 assert_eq!(inside(root, Path::new("/r/a/b.txt")).as_deref(), Some("a/b.txt"));
1167 assert_eq!(inside(root, Path::new("/r")), None);
1168 assert_eq!(inside(root, Path::new("/rx/a")), None);
1169 assert_eq!(inside(root, Path::new("/r/..x")), None);
1170 assert_eq!(resolve_lexical(root, "a/../b/./c"), Path::new("/r/b/c"));
1171 assert_eq!(resolve_lexical(root, "/abs/../x"), Path::new("/x"));
1172 }
1173}