1use crate::file_hooks::{AfterCellReport, AfterOutcome, CellChanges, FileWriteGuard, Verdict, inside};
13use loki::CheckError;
14use loki::run::Report;
15use serde_json::{Map, Value};
16use std::collections::{HashMap, HashSet};
17use std::path::{Path, PathBuf};
18use std::process::{Command, Stdio};
19use std::sync::Mutex;
20use std::sync::atomic::{AtomicBool, Ordering};
21
22const MAX_HOOK_FILES: usize = 40;
24
25fn count(n: usize, noun: &str) -> String {
26 format!("{n} {noun}{}", if n == 1 { "" } else { "s" })
27}
28
29fn loki_file_as_committed(root: &Path, relative: &str) -> bool {
33 if !relative.starts_with(".loki/") {
34 return false;
35 }
36 let git = |args: &[&str]| {
37 Command::new("git")
38 .arg("-C")
39 .arg(root)
40 .args(args)
41 .stdin(Stdio::null())
42 .stdout(Stdio::null())
43 .stderr(Stdio::null())
44 .status()
45 .is_ok_and(|status| status.success())
46 };
47 git(&["ls-files", "--error-unmatch", "--", relative]) && git(&["diff", "--quiet", "HEAD", "--", relative])
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum LokiMode {
52 On,
53 Advise,
54 Off,
55}
56
57const OFF_VALUES: [&str; 5] = ["off", "0", "false", "no", "none"];
58
59pub fn loki_timeout(value: Option<&str>) -> Option<std::time::Duration> {
63 let n: f64 = value?.trim().parse().ok()?;
65 (jsrt::number::is_safe_integer(n) && n > 0.0).then(|| std::time::Duration::from_millis(n as u64))
66}
67
68pub fn loki_mode(env: Option<&str>, settings: &Map<String, Value>) -> LokiMode {
70 let raw = env.map(|v| v.trim().to_lowercase()).filter(|v| !v.is_empty());
71 match raw.as_deref() {
72 Some(v) if OFF_VALUES.contains(&v) => LokiMode::Off,
73 Some("advise") => LokiMode::Advise,
74 Some(_) => LokiMode::On,
75 None => match settings.get("mode").and_then(Value::as_str) {
76 Some("off") => LokiMode::Off,
77 Some("advise") => LokiMode::Advise,
78 _ => LokiMode::On,
79 },
80 }
81}
82
83pub fn git_root(cwd: &Path) -> Option<PathBuf> {
85 let output = Command::new("git")
86 .args(["rev-parse", "--show-toplevel"])
87 .current_dir(cwd)
88 .env("GIT_OPTIONAL_LOCKS", "0")
89 .stdin(Stdio::null())
90 .stderr(Stdio::null())
91 .output()
92 .ok()?;
93 let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
94 (output.status.success() && !root.is_empty()).then(|| PathBuf::from(root))
95}
96
97pub struct LokiGuard {
98 root: PathBuf,
99 mode: LokiMode,
100 shown_notices: Mutex<Vec<String>>,
102 open: Mutex<HashMap<&'static str, HashMap<String, HashSet<String>>>>,
104 paused_shown: AtomicBool,
105 hook: HookRunner,
107 post_write: bool,
109 timeout: Option<std::time::Duration>,
111 hygiene: loki::hygiene::Level,
113}
114
115pub type HookRunner = std::sync::Arc<dyn Fn(&Path, &[String]) -> Result<Report, CheckError> + Send + Sync>;
117
118struct Unseen {
120 fresh: Vec<String>,
121 earlier: usize,
122 paths: Vec<String>,
123}
124
125impl LokiGuard {
126 pub fn new(root: impl Into<PathBuf>, mode: LokiMode) -> Self {
128 LokiGuard {
129 root: root.into(),
130 mode,
131 shown_notices: Mutex::new(Vec::new()),
132 open: Mutex::new(HashMap::new()),
133 paused_shown: AtomicBool::new(false),
134 hook: std::sync::Arc::new(|root: &Path, files: &[String]| loki::run::hook(root, files, None)),
135 post_write: true,
136 timeout: None,
137 hygiene: loki::hygiene::Level::Off,
138 }
139 }
140
141 pub fn with_hygiene(mut self, level: loki::hygiene::Level) -> Self {
143 self.hygiene = level;
144 self
145 }
146
147 pub fn with_timeout(mut self, timeout: Option<std::time::Duration>) -> Self {
149 self.timeout = timeout;
150 self
151 }
152
153 pub fn with_post_write(mut self, post_write: bool) -> Self {
156 self.post_write = post_write;
157 self
158 }
159
160 pub fn with_project_python(mut self, python: Option<String>) -> Self {
163 self.hook =
164 std::sync::Arc::new(move |root: &Path, files: &[String]| loki::run::hook(root, files, python.as_deref()));
165 self
166 }
167
168 pub fn with_hook(mut self, hook: HookRunner) -> Self {
170 self.hook = hook;
171 self
172 }
173
174 fn unseen(&self, tier: &'static str, lines: &[String], checked: &[String]) -> Unseen {
177 let mut open = self.open.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
178 let memory = open.entry(tier).or_default();
179 let mut now: Vec<(String, HashSet<String>)> = Vec::new();
180 let mut fresh = Vec::new();
181 let mut stale: Vec<String> = Vec::new();
182 for line in lines {
183 let (path, key) = loki::finding_key(&self.root, line);
184 if !path.is_empty() && memory.get(&path).is_some_and(|keys| keys.contains(&key)) {
185 if !stale.contains(&path) {
186 stale.push(path.clone());
187 }
188 } else {
189 fresh.push(line.clone());
190 }
191 if !path.is_empty() {
193 match now.iter_mut().find(|(p, _)| *p == path) {
194 Some((_, keys)) => {
195 keys.insert(key);
196 }
197 None => now.push((path, HashSet::from([key]))),
198 }
199 }
200 }
201 for path in checked {
202 memory.remove(path);
203 }
204 for (path, keys) in now {
205 memory.insert(path, keys);
206 }
207 Unseen {
208 earlier: lines.len() - fresh.len(),
209 fresh,
210 paths: stale,
211 }
212 }
213
214 fn notice(&self, lines: &[String]) -> Option<String> {
216 let mut shown = self
217 .shown_notices
218 .lock()
219 .unwrap_or_else(std::sync::PoisonError::into_inner);
220 let mut fresh = Vec::new();
221 for line in lines {
222 if !shown.contains(line) {
223 shown.push(line.clone());
224 fresh.push(
225 line.strip_prefix("NOT CHECKED")
226 .unwrap_or(line)
227 .trim_start()
228 .to_string(),
229 );
230 }
231 }
232 (!fresh.is_empty()).then(|| format!("not checked in this session (said once): {}", fresh.join("; ")))
233 }
234
235 fn refused(&self, reason: String, advise: &str) -> Verdict {
236 if self.mode == LokiMode::Advise {
237 Verdict::Allow(Some(format!("{advise}:\n{reason}")))
238 } else {
239 Verdict::Block(reason)
240 }
241 }
242}
243
244impl FileWriteGuard for LokiGuard {
245 fn name(&self) -> &str {
246 "Loki"
247 }
248
249 fn timeout(&self) -> Option<std::time::Duration> {
252 self.timeout
253 }
254
255 fn before_write(&self, path: &Path, content: &str, _cwd: &Path, _lane: &str) -> Result<Verdict, String> {
256 let (root, relative) = match inside(&self.root, path) {
258 Some(relative) => (self.root.clone(), relative),
259 None => {
260 let Some((root, relative)) = path
261 .ancestors()
262 .skip(1)
263 .find(|dir| dir.is_dir())
264 .and_then(git_root)
265 .filter(|root| root.join(".loki").is_dir())
266 .and_then(|root| inside(&root, path).map(|relative| (root, relative)))
267 else {
268 return Ok(Verdict::Allow(None));
269 };
270 (root, relative)
271 }
272 };
273 let report = match loki::run::protect_write(&root, &relative, content) {
274 Ok(report) => report,
275 Err(error) => {
276 return Ok(self.refused(
277 format!("loki: {}", error.describe()),
278 "would block this write (advise-only mode)",
279 ));
280 }
281 };
282 if report.blocked() {
283 return Ok(self.refused(
284 report.refusal_lines().join("\n"),
285 "would block this write (advise-only mode)",
286 ));
287 }
288 let not_checked: Vec<String> = report.not_checked().cloned().collect();
289 let mut lines: Vec<String> = report.advisory().cloned().collect();
290 lines.extend(self.notice(¬_checked));
291 Ok(Verdict::Allow((!lines.is_empty()).then(|| lines.join("\n"))))
292 }
293
294 fn watches_cells(&self) -> bool {
295 self.post_write && self.mode != LokiMode::Off
296 }
297
298 fn after_cell_changes(
300 &self,
301 changes: &CellChanges,
302 _cwd: &Path,
303 _lane: &str,
304 ) -> Result<Option<AfterCellReport>, String> {
305 let mut targets: Vec<String> = Vec::new();
306 for path in changes.files.iter().chain(&changes.checked) {
307 if let Some(relative) = inside(&self.root, path)
308 && !targets.contains(&relative)
309 && !loki_file_as_committed(&self.root, &relative)
310 {
311 targets.push(relative);
312 }
313 }
314 if targets.is_empty() {
315 return Ok(None);
316 }
317 let checked: Vec<String> = targets.iter().take(MAX_HOOK_FILES).cloned().collect();
318 let report = (self.hook)(&self.root, &checked).map_err(|error| error.describe())?;
319 if report.blocked_by_policy_changes() {
322 if self.paused_shown.swap(true, Ordering::SeqCst) {
323 return Ok(None);
324 }
325 return Ok(Some(AfterCellReport {
326 outcome: AfterOutcome::Clean,
327 message: Some("post-write checks are paused: .loki/ has uncommitted changes, and Loki checks against the committed policy. Before-write checks of edit() and write() still run. Commit .loki/ to resume them (git add .loki && git commit -m 'Add Loki guardrails' -- .loki).".into()),
328 }));
329 }
330 let mut report = report;
331 if !report.blocked() {
332 report
333 .warnings
334 .extend(loki::hygiene::written(&self.root, &checked, self.hygiene));
335 }
336 let advisory: Vec<String> = report.advisory().cloned().collect();
337 let not_checked: Vec<String> = report.not_checked().cloned().collect();
338 let blocking = self.unseen("blocking", &report.blocking, &checked);
339 let advisory = self.unseen("advisory", &advisory, &checked);
340 let mut sections = Vec::new();
341 if !blocking.fresh.is_empty() {
342 sections.push(format!(
343 "{} from this cell's changes; fix these:\n{}",
344 count(blocking.fresh.len(), "new finding"),
345 blocking.fresh.join("\n")
346 ));
347 }
348 if blocking.earlier > 0 {
349 sections.push(format!(
350 "{} reported earlier {} still open in {}.",
351 count(blocking.earlier, "finding"),
352 if blocking.earlier == 1 { "is" } else { "are" },
353 blocking.paths.join(", ")
354 ));
355 }
356 if !advisory.fresh.is_empty() {
357 sections.push(format!(
358 "FYI (advisory, not blocking; no change required):\n{}",
359 advisory.fresh.join("\n")
360 ));
361 }
362 sections.extend(self.notice(¬_checked));
363 if targets.len() > checked.len() {
364 sections.push(format!(
365 "({} more changed files were not checked)",
366 targets.len() - checked.len()
367 ));
368 }
369 let outcome = if !report.blocking.is_empty() {
370 AfterOutcome::Findings
371 } else if !advisory.fresh.is_empty() {
372 AfterOutcome::Advisory
373 } else {
374 AfterOutcome::Clean
375 };
376 Ok((!sections.is_empty()).then(|| AfterCellReport {
377 outcome,
378 message: Some(sections.join("\n")),
379 }))
380 }
381
382 fn before_shell(&self, command: &str, cwd: &Path) -> Result<Verdict, String> {
383 Ok(match loki::shell::command_refusal(&self.root, command, cwd) {
384 None => Verdict::Allow(None),
385 Some(reason) => self.refused(
386 reason.trim().to_string(),
387 "would refuse this command (advise-only mode)",
388 ),
389 })
390 }
391}