Skip to main content

host/
file_hooks.rs

1//! Generic file-write hooks for the RLM REPL (ultron/file-hooks.ts):
2//!
3//! 1. Before a write (blocking): the kernel's `edit()`/`write()` send each proposed write to the host before touching
4//!    the file (`files.before_write`). A guard that blocks makes `write()` raise ValueError with its diagnostic
5//!    (runtime.py `_check_write`); a guard that fails lets the write proceed with a visible note: it fails open,
6//!    never silently.
7//!    Before any guard, a write into a protected path ([`FileHooks::protect`]: the profile's settings, keys and
8//!    skills, which are the user's to change) is blocked, and so is a shell command that may write files and names
9//!    one.
10//! 2. After a cell (advisory): files a cell changed by other means (`bash('sed -i ...')`, `Path.write_text`) are found
11//!    by comparing workspace snapshots taken between cells, minus the checked writes whose content is unchanged.
12//!    Guards' `after_cell_changes` run in the background, so a cell returns as fast as before, and what they report
13//!    reaches the model with the lane's next cell result ([`FileHooks::take_pending`]).
14//! 3. Before a shell command (blocking): commands that may write a file go to the guards before they run; a guard
15//!    that blocks makes the host refuse the command ("bash command was not run: ...").
16
17use 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/// A guard's answer: block with a reason, or allow with an optional note.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Verdict {
30    Block(String),
31    Allow(Option<String>),
32}
33
34/// Files one cell changed (absolute paths).
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct CellChanges {
37    /// Added or modified files no before-write check saw (or whose checked content was changed again).
38    pub files: Vec<PathBuf>,
39    /// Files written through a checked `edit()`/`write()` whose content is what was checked.
40    pub checked: Vec<PathBuf>,
41    pub deleted: Vec<PathBuf>,
42    /// False when a snapshot hit its size bound, so some changes may be missing.
43    pub complete: bool,
44}
45
46/// Whether an after-cell report holds something to fix.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum AfterOutcome {
49    /// Nothing, or only a note.
50    Clean,
51    /// Only for-your-information lines.
52    Advisory,
53    /// Something to fix.
54    Findings,
55}
56
57/// What an after-cell check has to say (`AfterCellReport`).
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct AfterCellReport {
60    /// Text for the model, delivered with the lane's next cell result.
61    pub message: Option<String>,
62    pub outcome: AfterOutcome,
63}
64
65/// One registered guard (Loki). `Err` means the guard could not check (the write proceeds unchecked).
66pub trait FileWriteGuard: Send + Sync {
67    /// Shown in notes and statistics ("Loki").
68    fn name(&self) -> &str;
69    /// False while the guard has nothing to do (checked per call; file-hooks.ts `enabled`).
70    fn enabled(&self) -> bool {
71        true
72    }
73    /// Whether the guard checks proposed writes / shell commands at all (TS: whether `beforeWrite` / `beforeShell`
74    /// is defined); only those calls are counted in its statistics.
75    fn checks_writes(&self) -> bool {
76        true
77    }
78    fn checks_shell(&self) -> bool {
79        true
80    }
81    /// Per-call time limit of `before_write` and `before_shell` (default 5 s); `None` waits for the answer. A guard
82    /// that does not answer in time lets the write (or command) proceed with a note.
83    fn timeout(&self) -> Option<Duration> {
84        Some(DEFAULT_BEFORE_WRITE_TIMEOUT)
85    }
86    /// A proposed write of the cell on `lane`: the absolute, normalized path and the complete new text; `cwd` is the
87    /// lane's directory.
88    fn before_write(&self, _path: &Path, _content: &str, _cwd: &Path, _lane: &str) -> Result<Verdict, String> {
89        Ok(Verdict::Allow(None))
90    }
91    /// A shell command that may write files ([`may_write_files`]), before it runs in `cwd`.
92    fn before_shell(&self, _command: &str, _cwd: &Path) -> Result<Verdict, String> {
93        Ok(Verdict::Allow(None))
94    }
95    /// Whether the guard wants the files each cell changed (snapshots are taken only while one does); checked per
96    /// cell.
97    fn watches_cells(&self) -> bool {
98        false
99    }
100    /// The files a cell on `lane` (working in `cwd`) changed by other means than checked writes.
101    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    /// How long `after_cell_changes` may take (default 120 s).
110    fn after_timeout(&self) -> Duration {
111        DEFAULT_AFTER_CELL_TIMEOUT
112    }
113}
114
115/// Something that wants the files each cell changed without being a guard: no verdicts, no statistics, no records.
116/// Its lines are delivered verbatim with the lane's next cell result (memory pointers, `kernel_apis::memory_pointers`).
117pub trait CellObserver: Send + Sync {
118    /// False while the observer has nothing to do (checked per cell, like a guard's `watches_cells`).
119    fn enabled(&self) -> bool {
120        true
121    }
122    /// The files a cell on `lane` (working in `cwd`) changed, checked writes included; lines for the model.
123    fn cell_changed(&self, changes: &CellChanges, cwd: &Path, lane: &str) -> Vec<String>;
124    /// A shell command a cell on `lane` is about to run: `Some(reason)` refuses it, with the reason for the model.
125    fn before_shell(&self, _command: &str, _lane: &str) -> Option<String> {
126        None
127    }
128}
129
130/// A picture of a working directory: relative path (with `/`) to a metadata signature (workspace-snapshot.ts).
131#[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
140/// How long an after-cell check waits for work outside the cells still running (Loki's setup commit: 30 s for
141/// the commit and its hooks, then a picture of the repository).
142pub const OUTSIDE_WAIT: Duration = Duration::from_secs(60);
143
144/// Files the session's own work changed outside the cells: Loki's setup commit, whose pre-commit hooks may rewrite
145/// files (a formatter rewrote `.loki/loki.json`, which the next after-cell check then reported as that cell's
146/// `protected file`). An after-cell check waits for such work and leaves out the files it changed, unless the cell
147/// changed them again.
148#[derive(Clone, Default)]
149pub struct OutsideChanges {
150    state: Arc<(Mutex<OutsideState>, Condvar)>,
151}
152
153#[derive(Default)]
154struct OutsideState {
155    running: usize,
156    /// Absolute path -> its signature once the work finished (None: the work deleted it).
157    after: HashMap<PathBuf, Option<String>>,
158}
159
160/// Work outside the cells that has begun ([`OutsideChanges::begin`]); dropping it without [`Self::record`] ends it
161/// with nothing recorded.
162pub struct OutsideWork {
163    changes: OutsideChanges,
164}
165
166impl OutsideChanges {
167    /// Work outside the cells begins now: after-cell checks wait for it from this moment.
168    pub fn begin(&self) -> OutsideWork {
169        sync::lock(&self.state.0).running += 1;
170        OutsideWork { changes: self.clone() }
171    }
172
173    /// Wait (at most `limit`) for the work that has begun to end.
174    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    /// Whether `path` (absolute) with `signature` (None: missing) is as the work outside the cells left it.
191    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    /// Run `work`, recording what it changed between pictures of `root` taken by `snapshot` before and after it.
201    /// Picture only what the work changes (Loki's setup: `.loki/`): a cell's own write elsewhere in that time
202    /// would otherwise be taken for the work's and go unchecked.
203    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/// One guard's time and outcomes, for the RLM pane and diagnostics (`GuardStats`).
234#[derive(Debug, Clone, Default, PartialEq, Eq)]
235pub struct GuardStats {
236    pub name: String,
237    /// Before-write (and before-shell) checks run, those that blocked, those that timed out or failed.
238    pub checks: u64,
239    pub blocked: u64,
240    pub unchecked: u64,
241    /// After-cell checks run, and how many reported findings to fix (or could not check).
242    pub after_checks: u64,
243    pub after_findings: u64,
244    /// Time spent in the guard: in all, and since the current root turn began.
245    pub total_ms: u64,
246    pub turn_ms: u64,
247}
248
249impl GuardStats {
250    /// The TS object (`fileHooks.stats()` entries).
251    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/// Every guard outcome, for logs (`GuardRecord`, ULTRON_LOKI_LOG).
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct GuardRecord {
268    pub guard: String,
269    /// `before_write`, `before_shell` or `after_cell`.
270    pub phase: &'static str,
271    /// `allowed`, `blocked`, `unchecked`, `clean`, `advisory` or `findings`.
272    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    /// The record as TS writes it (`detail` left out when unset).
281    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>;
298/// Milliseconds on some clock (TS `now`, default `Date.now`): only differences are used.
299pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
300
301/// `Math.round(ms / 100) / 10` as JavaScript prints it ("5", "0.2").
302fn js_seconds(timeout: Duration) -> String {
303    jsrt::number::to_string(jsrt::number::round(timeout.as_millis() as f64 / 100.0) / 10.0)
304}
305
306/// How one timed guard call ended.
307enum Answer<T> {
308    Value(T),
309    Error(String),
310    TimedOut,
311}
312
313/// Run `call` on its own thread and wait at most `timeout` (file-hooks.ts `#timed`): a call that does not answer in
314/// time is left to finish on its own.
315fn 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
334/// A guard call's answer, once it comes (or its time is up).
335type Pending = std::sync::mpsc::Receiver<Answer<Verdict>>;
336
337/// A registered guard and its statistics.
338#[derive(Clone)]
339struct Registered {
340    guard: Arc<dyn FileWriteGuard>,
341    stats: Arc<Mutex<GuardStats>>,
342}
343/// Findings delivered with one cell result are capped; the rest are summarized.
344const MAX_PENDING_CHARS: usize = 6_000;
345
346fn re(pattern: &str) -> Regex {
347    Regex::new(pattern).expect("static pattern")
348}
349
350// JavaScript's `\b` after `null` is "no ASCII word character next"; `\d` is ASCII.
351static 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
363/// `mayWriteFiles`: whether a command may write a file, cheaply and generously (a redirect, `tee`, `sed -i`,
364/// `perl -i`, `cp`/`mv`/`install`, `dd of=`). Redirects to `/dev/null` and fd duplications do not count.
365pub 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
373/// `path.resolve(cwd, path)`: lexical, `..` and `.` removed.
374pub 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
388/// `path.relative(from, to)` when `to` is inside `from`, as a `/` path; None for `from` itself or outside it.
389pub 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/// The guards of one working directory (the session's, or a worktree subagent's), answering the host's
395/// `files.before_write` and shell checks, and checking what each cell changed (`FileHooks`).
396#[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 writes since the last after-cell snapshot: absolute path -> sha256 of the checked content.
409    checked: Mutex<HashMap<PathBuf, String>>,
410    /// Findings not yet shown, per lane.
411    pending: Mutex<HashMap<String, Vec<String>>>,
412    /// The last snapshot of the directory (taken before the first watched cell, then after each).
413    latest: Mutex<Option<Snapshot>>,
414    /// Each lane's picture from the start of its running cell, which the cell's end is compared with: a lane is
415    /// told only what changed while its own cell ran, and another lane's end does not absorb its changes. Changed
416    /// only by the after-cell worker, in the order the cells started and ended.
417    baselines: Mutex<HashMap<String, Snapshot>>,
418    /// Changes another lane's cell end was given while this lane's cell ran (relative path -> its picture entry then,
419    /// `None` for a deletion): a change goes to the first cell that ends after it, and another lane's running cell
420    /// gets it only if that cell changes the file again.
421    claimed: Mutex<HashMap<String, HashMap<String, Option<String>>>>,
422    /// Lanes whose watched cell runs now.
423    live: Mutex<HashSet<String>>,
424    /// Files changed outside the cells, left out of their changes ([`FileHooks::ignore_outside`]).
425    outside: Mutex<Option<OutsideChanges>>,
426    /// Paths no cell may write ([`FileHooks::protect`]), and how a shell command names each.
427    protected: Mutex<Vec<Protected>>,
428    /// Cell starts and ends queued or being handled, and the worker that handles them one at a time.
429    queued: Mutex<usize>,
430    idle: Condvar,
431    worker: Mutex<Option<Sender<CellEvent>>>,
432}
433
434/// A watched cell's start or end, handled by the after-cell worker in order.
435enum CellEvent {
436    /// Its picture when one was taken as it started (another lane's cell was running, or there was none yet);
437    /// otherwise the latest picture is its baseline.
438    Started(String, Option<Snapshot>),
439    Ended(String),
440}
441
442/// A protected file or directory: its absolute path, and the text a shell command names it by (its path from the
443/// home directory when it is inside it, which `~/`, `$HOME/` and absolute forms all contain).
444struct Protected {
445    path: PathBuf,
446    named: String,
447}
448
449/// Who blocks a write into a protected path, in its reason and guard records.
450const PROTECTOR: &str = "Ultron";
451
452/// `diffSnapshots`: added, modified and deleted paths (each sorted), and whether both pictures were complete.
453pub 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
472/// The first `limit` UTF-16 code units of `text` (JavaScript's `slice(0, limit)`), and how many there were in all.
473fn 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    /// Hooks that also check what each cell changed, picturing the directory with `snapshot`.
510    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    /// No cell writes `paths` (files, or directories with everything in them) through `write()`/`edit()` or a
530    /// shell command that names one: they are the user's to change (the profile's settings, keys and skills).
531    /// `home` is the home directory a command may name them from.
532    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            // Through a symlinked home or profile, too.
537            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    /// The protected path `path` is in, if any (as written, and with its existing part's symlinks resolved).
553    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    /// The protected path a shell command that may write files names, if any.
572    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    /// `observer` sees what each cell changed (after the guards); its lines go with the lane's next cell result.
580    pub fn observe(&self, observer: Arc<dyn CellObserver>) {
581        sync::lock(&self.inner.observers).push(observer);
582    }
583
584    /// Files `changes` records as changed outside the cells are not a cell's changes (unless it changed them
585    /// again), and an after-cell check waits for that work to end first.
586    pub fn ignore_outside(&self, changes: OutsideChanges) {
587        *sync::lock(&self.inner.outside) = Some(changes);
588    }
589
590    /// Every guard outcome goes to `on_record` (ULTRON_LOKI_LOG).
591    pub fn on_record(&self, on_record: OnRecord) {
592        *sync::lock(&self.inner.on_record) = Some(on_record);
593    }
594
595    /// The clock guard times are measured with (tests).
596    pub fn set_clock(&self, now: Clock) {
597        *sync::lock(&self.inner.now) = now;
598    }
599
600    /// A new root turn began: per-turn times start from zero.
601    pub fn begin_turn(&self) {
602        for registered in sync::lock(&self.inner.guards).iter() {
603            sync::lock(&registered.stats).turn_ms = 0;
604        }
605    }
606
607    /// Each guard's statistics, in registration order.
608    pub fn stats(&self) -> Vec<GuardStats> {
609        sync::lock(&self.inner.guards)
610            .iter()
611            .map(|registered| sync::lock(&registered.stats).clone())
612            .collect()
613    }
614
615    /// True when some guard wants to see changes after each cell (snapshots are taken only then).
616    pub fn watches_cells(&self) -> bool {
617        self.inner.watches_cells()
618    }
619
620    /// A cell is starting on `lane`: the directory as it is now is what its end is compared with. While no other
621    /// lane's cell runs that is the latest picture (taken after the previous cell); otherwise a picture is taken now,
622    /// so the other lane's changes made before this start are not this lane's.
623    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    /// A cell on `lane` ended: in the background, diff the directory against the lane's picture from the cell's
640    /// start and give the guards the files changed by other means than checked writes. Returns at once;
641    /// [`Self::settled`] waits.
642    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                // No picture yet (a guard became interested mid-session): this cell's changes cannot be told apart;
651                // the next cell's are.
652                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            // Its start was not seen: compared with the latest picture.
660            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    /// Wait for the after-cell checks already started.
694    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    /// Findings from after-cell checks not yet shown to `lane`, as one block of text (and forget them).
702    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    /// A path for notes: relative to the session directory when inside it.
717    fn display(&self, path: &Path) -> String {
718        self.inner.display(path)
719    }
720
721    /// The refusal of a write into `protected` (recorded like a guard's block).
722    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    /// A path for records: relative to the session directory when inside it.
769    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    /// A lane's cell started: its baseline is the picture taken then, else the latest one.
778    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    /// `#afterCell`: diff against the lane's picture from its cell's start, then ask every watching guard (each
789    /// within its time limit).
790    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        // Checked writes outside the session directory (a sibling worktree) are in no snapshot; they are changes too.
831        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(&current) == 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        // Every watching guard starts at once; each is awaited with its own limit.
885        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(&registered.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    /// `beforeShell` of a command on `lane`: commands that may write no file, or with no shell guard, are allowed
970    /// at once. `Some(reasons)` blocks it. Notes (a guard that could not check, advise-only refusals) are not shown
971    /// for shell commands.
972    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(&registered.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    /// `beforeWrite` of one proposed write on `lane`: every enabled guard, in parallel, each within its time limit.
1052    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                // Started together; each answer is awaited below with its own limit.
1074                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(&registered.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            // The write will happen with this content; an after-cell diff need not report it again.
1131            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}