The design language that makes your AI harness better at design.
JavaScript
Find projects below the session cwd on Stop (fixes #1101) (#1130)
Paul Bakausc51e529c42ee
diff --git a/crates/hook/src/hook.rs b/crates/hook/src/hook.rsindex a7dbeddb0..23bc86e1c 100644--- a/crates/hook/src/hook.rs+++ b/crates/hook/src/hook.rs@@ -67,6 +67,16 @@ fn session_key(v: &Option<Value>) -> String {}}+/// Records the root whose cache this edit just wrote, so a Stop from a+/// session cwd above it finds it (#1101). Only for a named session, and only+/// for harnesses that run a Stop pass: Cursor and GitHub Copilot install none.+fn record_session_root(rt: &Runtime, harness: &str, session_value: &Option<Value>, project_cwd: &str) {+ if session_value.is_none() || matches!(harness, "cursor" | "github") {+ return;+ }+ crate::hook_sessions::record_root(rt, &session_key(session_value), project_cwd);+}+/// JS: runHook({ stdinJson, env, cwd })pub fn run_hook(rt: &Runtime, stdin: &str) -> RunResult {let mut audit: Map<String, Value> = Map::new();@@ -427,7 +437,9 @@ pub fn run_hook(rt: &Runtime, stdin: &str) -> RunResult {let text =append_design_system_note_once(rt, &rendered, scan, &mut cache, &session_id, &config);commit_footer_shown(rt, &mut cache, &session_id, &text);- persist_cache(rt, &project_cwd, &cache);+ if persist_cache(rt, &project_cwd, &cache) {+ record_session_root(rt, harness, &session_value, &project_cwd);+ }let all: usize = fresh_groups.iter().map(|g| g.findings.len()).sum();return RunResult {stdout: payload(&text, "PostToolUse", harness),@@ -491,11 +503,11 @@ pub fn run_hook(rt: &Runtime, stdin: &str) -> RunResult {// this, clean-edit editCount bumps would stop persisting the moment// state relocates. Under stock paths the cache sits inside// `.impeccable/`, so the extra check changes nothing there.- if deferred_total > 0+ let wants_persist = deferred_total > 0|| (cache_dirty- && (exists(&jsp::join(&[&project_cwd, ".impeccable"])) || exists(&get_cache_path(&project_cwd))))- {- persist_cache(rt, &project_cwd, &cache);+ && (exists(&jsp::join(&[&project_cwd, ".impeccable"])) || exists(&get_cache_path(&project_cwd))));+ if wants_persist && persist_cache(rt, &project_cwd, &cache) {+ record_session_root(rt, harness, &session_value, &project_cwd);}if detector_threw_any && pending_winner.is_none() && clean_winner.is_none() {@@ -678,6 +690,7 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {}let session_value = session_id_of(&event);let session_id = session_key(&session_value);+ let named_session = session_value.is_some();// The build-completion stage keeps the session cwd: `build-phase` writes// its state under its own cwd. Only the touched-file scan moves to the// root the per-edit pass keyed this session's cache to (#1088).@@ -731,121 +744,154 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {if truthy(rt.env("IMPECCABLE_HOOK_COMPLETION_ONLY")) {return result(&audit, vec![("skipped", Value::from("no-build-continuation")), ("durationMs", ms_since(started))]);}- let project_cwd = resolve_stop_cwd(rt, &session_cwd, &session_id);- // At another root the scan runs under that root's config and cache, as- // the per-edit pass did; the session cwd's cache keeps the build marker.- let mut build_cache = None;- let config = if project_cwd == session_cwd {- config- } else {- audit.insert("cwd".into(), Value::String(project_cwd.clone()));- let config = read_config(&project_cwd);- if !config.enabled {- return result(- &audit,- vec![- ("skipped", Value::from("config-disabled")),- ("durationMs", ms_since(started)),- ],- );+ // The roots to scan: the nearest one from the session cwd up whose cache+ // this session touched (#1088), then every root the per-edit pass+ // recorded for this session (#1101), which finds projects below a session+ // cwd that sits above them. Without a recorded root this is the walk up+ // alone, as before.+ let mut roots = vec![resolve_stop_cwd(rt, &session_cwd, &session_id)];+ if named_session {+ for root in crate::hook_sessions::recorded_roots(rt, &session_id) {+ if !roots.contains(&root) {+ roots.push(root);+ }}- platform_memo = None;- build_cache = Some(std::mem::replace(&mut cache, read_cache(&project_cwd)));- config- };- let touched = touched_files(&cache, &session_id);- if touched.is_empty() {- return result(- &audit,- vec![- ("skipped", Value::from("no-touched-files")),- ("durationMs", ms_since(started)),- ],- );}- if let Some(skip) = native_skip(&audit, &project_cwd, &mut platform_memo) { return skip; }- let mut scans = HashMap::new();- let mut fresh_groups: Vec<Group> = Vec::new();+ // Each root is scanned under its own config and cache, as the per-edit+ // pass did. The session cwd's cache keeps the build marker.+ struct RootPass {+ cwd: String,+ config: HookConfig,+ cache: Cache,+ groups: Vec<Group>,+ scans: HashMap<String, HookScanOptions>,+ dirty: bool,+ }+ let mut passes: Vec<RootPass> = Vec::new();+ let mut first_skip: Option<RunResult> = None;let mut scanned = 0usize;- let mut cache_dirty = false;let mut pre_existing = 0usize;let mut new_findings = 0usize;let mut unknown = 0usize;- for file_path in &touched {- if scanned >= STOP_MAX_FILES {- break;- }- if has_path_traversal(file_path)- || is_sensitive_path(file_path)- || is_generated_path(file_path)- {- continue;- }- let ext = js::to_lower_case(&jsp::extname(file_path));- let configured = match_configured_extension(file_path, &config.extensions);- if !ALLOWED_EXTS.contains(&ext.as_str()) && configured.is_none() {- continue;+ for root in &roots {+ let mut root_audit = audit.clone();+ if *root != session_cwd {+ root_audit.insert("cwd".into(), Value::String(root.clone()));}- if is_ignored_file(&rt.proc_cwd, file_path, &project_cwd, &config.ignore_files) {+ let at_session_cwd = *root == session_cwd;+ let root_config = if at_session_cwd { config.clone() } else { read_config(root) };+ if !root_config.enabled {+ first_skip.get_or_insert_with(|| result(+ &root_audit,+ vec![("skipped", Value::from("config-disabled")), ("durationMs", ms_since(started))],+ ));continue;}- if !exists(file_path) || !is_scan_target_inside_project(rt, file_path, &project_cwd) {+ let mut root_cache = if at_session_cwd { cache.clone() } else { read_cache(root) };+ let touched = touched_files(&root_cache, &session_id);+ if touched.is_empty() {+ first_skip.get_or_insert_with(|| result(+ &root_audit,+ vec![("skipped", Value::from("no-touched-files")), ("durationMs", ms_since(started))],+ ));continue;}- scanned += 1;- let content = match std::fs::read(file_path) {- Ok(b) => String::from_utf8_lossy(&b).into_owned(),- Err(_) => continue,- };- if crate::hook_lib::has_live_preview_markers(&content) {+ let mut root_memo = if at_session_cwd { platform_memo.clone() } else { None };+ if let Some(skip) = native_skip(&root_audit, root, &mut root_memo) {+ first_skip.get_or_insert(skip);continue;}- let use_html_engine = uses_html_engine(file_path, &config.extensions);- let scan = scans.entry(file_path.clone()).or_insert_with(|| {- design_system_options_for_file(rt, &config, &project_cwd, file_path)- });- // JS: a detector failure tells us nothing about the file. Leave- // whatever was remembered alone rather than recording an empty scan- // as truth. (detectText cannot throw here: the Rust engine returns- // findings directly.)- let findings = if use_html_engine {- match detector_detect_html(rt, file_path, scan) {- Ok(f) => f,+ let mut scans = HashMap::new();+ let mut groups: Vec<Group> = Vec::new();+ let mut dirty = false;+ for file_path in &touched {+ if scanned >= STOP_MAX_FILES {+ break;+ }+ if has_path_traversal(file_path)+ || is_sensitive_path(file_path)+ || is_generated_path(file_path)+ {+ continue;+ }+ let ext = js::to_lower_case(&jsp::extname(file_path));+ let configured = match_configured_extension(file_path, &root_config.extensions);+ if !ALLOWED_EXTS.contains(&ext.as_str()) && configured.is_none() {+ continue;+ }+ if is_ignored_file(&rt.proc_cwd, file_path, root, &root_config.ignore_files) {+ continue;+ }+ if !exists(file_path) || !is_scan_target_inside_project(rt, file_path, root) {+ continue;+ }+ scanned += 1;+ let content = match std::fs::read(file_path) {+ Ok(b) => String::from_utf8_lossy(&b).into_owned(),Err(_) => continue,+ };+ if crate::hook_lib::has_live_preview_markers(&content) {+ continue;}- } else {- detector_detect_text(&content, file_path, scan)- };- if !use_html_engine {- stop_baseline::reconcile(&mut cache, &session_id, file_path, &findings);- }- let filtered = filter_findings(findings, &config);- let classified = stop_baseline::classify(&cache, &session_id, file_path, use_html_engine, filtered.clone());- pre_existing += classified.pre_existing;- new_findings += classified.new;- unknown += classified.unknown;- let fresh = dedupe_against_cache(&classified.findings, &mut cache, &session_id, file_path);- // JS: sync to the live scan, including empty. Remembering only- // `fresh` (or skipping the write on a clean Stop) left stale keys in- // place, so a finding that was fixed and later reintroduced never- // fired again.- remember_findings(&mut cache, &session_id, file_path, &filtered);- cache_dirty = true;- if !fresh.is_empty() {- fresh_groups.push(Group {- file_path: file_path.clone(),- findings: fresh,+ let use_html_engine = uses_html_engine(file_path, &root_config.extensions);+ let scan = scans.entry(file_path.clone()).or_insert_with(|| {+ design_system_options_for_file(rt, &root_config, root, file_path)});+ // JS: a detector failure tells us nothing about the file. Leave+ // whatever was remembered alone rather than recording an empty scan+ // as truth. (detectText cannot throw here: the Rust engine returns+ // findings directly.)+ let findings = if use_html_engine {+ match detector_detect_html(rt, file_path, scan) {+ Ok(f) => f,+ Err(_) => continue,+ }+ } else {+ detector_detect_text(&content, file_path, scan)+ };+ if !use_html_engine {+ stop_baseline::reconcile(&mut root_cache, &session_id, file_path, &findings);+ }+ let filtered = filter_findings(findings, &root_config);+ let classified = stop_baseline::classify(&root_cache, &session_id, file_path, use_html_engine, filtered.clone());+ pre_existing += classified.pre_existing;+ new_findings += classified.new;+ unknown += classified.unknown;+ let fresh = dedupe_against_cache(&classified.findings, &mut root_cache, &session_id, file_path);+ // JS: sync to the live scan, including empty. Remembering only+ // `fresh` (or skipping the write on a clean Stop) left stale keys in+ // place, so a finding that was fixed and later reintroduced never+ // fired again.+ remember_findings(&mut root_cache, &session_id, file_path, &filtered);+ dirty = true;+ if !fresh.is_empty() {+ groups.push(Group {+ file_path: file_path.clone(),+ findings: fresh,+ });+ }}+ passes.push(RootPass { cwd: root.clone(), config: root_config, cache: root_cache, groups, scans, dirty });+ }+ if passes.is_empty() {+ // Every root fell out at a gate: report the first, as a single root did.+ return first_skip.expect("at least one root");+ }+ if passes[0].cwd != session_cwd {+ audit.insert("cwd".into(), Value::String(passes[0].cwd.clone()));+ }+ if passes.len() > 1 {+ audit.insert("roots".into(), Value::from(passes.len()));}audit.insert("scannedFiles".into(), Value::from(scanned));audit.insert("preExistingFindings".into(), Value::from(pre_existing));audit.insert("newFindings".into(), Value::from(new_findings));audit.insert("unknownFindings".into(), Value::from(unknown));- if fresh_groups.is_empty() {- if cache_dirty {- persist_cache(rt, &project_cwd, &cache);+ let emitting: Vec<usize> = (0..passes.len()).filter(|&i| !passes[i].groups.is_empty()).collect();+ if emitting.is_empty() {+ for pass in passes.iter().filter(|p| p.dirty) {+ persist_cache(rt, &pass.cwd, &pass.cache);}return result(&audit,@@ -856,8 +902,16 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {],);}- let scan = &scans[&fresh_groups[0].file_path];- let short = footer_mode_short(&mut cache, &session_id);+ // The first root with findings leads: its config sets the render caps, and+ // its cache carries the footer mode and the design-system note. Findings+ // from several roots render as one grouped list, root by root, with paths+ // relative to the session cwd so each names its project.+ let lead = emitting[0];+ let fresh_groups: Vec<Group> = emitting.iter().flat_map(|&i| std::mem::take(&mut passes[i].groups)).collect();+ let display_cwd = if emitting.len() == 1 { passes[lead].cwd.clone() } else { session_cwd.clone() };+ let config = passes[lead].config.clone();+ let scan = passes[lead].scans[&fresh_groups[0].file_path].clone();+ let short = footer_mode_short(&mut passes[lead].cache, &session_id);let first_unknown = fresh_groups.iter().flat_map(|group| &group.findings).position(|f| f.name.starts_with("[attribution unknown]"));let mut attribution_note = if first_unknown.is_some() {@@ -872,7 +926,7 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {&fresh_groups,render_config,&RenderOpts {- cwd: Some(project_cwd.clone()),+ cwd: Some(display_cwd.clone()),short_footer: short,reserve_chars: if note.is_empty() { 0.0 } else { (utf16_len(note) + 2) as f64 },},@@ -903,23 +957,31 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {}let text = if shows_unknown { format!("{attribution_note}\n\n{rendered}") } else { rendered };let text =- append_design_system_note_once(rt, &text, scan, &mut cache, &session_id, &config);+ append_design_system_note_once(rt, &text, &scan, &mut passes[lead].cache, &session_id, &config);// Findings shown over a comp build already recorded as shipped: a fix voids// that finish, so say so with the findings, not after the agent stops.- let note = match build_cache.as_mut() {- Some(build_cache) => {- let note = crate::build_completion::finished_build_note(rt, &session_cwd, &session_id, build_cache);- if note.is_some() { persist_cache(rt, &session_cwd, build_cache); }+ let note = match passes.iter().position(|p| p.cwd == session_cwd) {+ Some(i) => {+ passes[i].dirty = true;+ crate::build_completion::finished_build_note(rt, &session_cwd, &session_id, &mut passes[i].cache)+ }+ None => {+ let note = crate::build_completion::finished_build_note(rt, &session_cwd, &session_id, &mut cache);+ if note.is_some() { persist_cache(rt, &session_cwd, &cache); }note}- None => crate::build_completion::finished_build_note(rt, &session_cwd, &session_id, &mut cache),};let text = match note {Some(note) => format!("{text}\n\n{note}"),None => text,};- commit_footer_shown(rt, &mut cache, &session_id, &text);- persist_cache(rt, &project_cwd, &cache);+ for &i in &emitting {+ commit_footer_shown(rt, &mut passes[i].cache, &session_id, &text);+ passes[i].dirty = true;+ }+ for pass in passes.iter().filter(|p| p.dirty) {+ persist_cache(rt, &pass.cwd, &pass.cache);+ }let all: usize = fresh_groups.iter().map(|g| g.findings.len()).sum();RunResult {stdout: payload(&text, "Stop", harness),diff --git a/crates/hook/src/hook_claim.rs b/crates/hook/src/hook_claim.rsindex 69c9e20ef..832fa1a72 100644--- a/crates/hook/src/hook_claim.rs+++ b/crates/hook/src/hook_claim.rs@@ -88,12 +88,25 @@ pub fn event_key(event: &Map<String, Value>, project_cwd: &str, files: &[String]/// home read from the hook's own environment (`HOME`, then `USERPROFILE`;/// the other way round on Windows). `None` without a home: no claim.fn claim_root(rt: &Runtime) -> Option<PathBuf> {- if let Some(dir) = rt.env("IMPECCABLE_HOOK_CLAIM_DIR").filter(|s| !s.is_empty()) {+ user_dir(rt, "IMPECCABLE_HOOK_CLAIM_DIR", "hook-claims")+}++/// `$<override_env>` when set, else `<home>/.impeccable/<name>`, with home+/// read from the hook's own environment (`HOME`, then `USERPROFILE`; the+/// other way round on Windows). `None` without a home.+pub(crate) fn user_dir(rt: &Runtime, override_env: &str, name: &str) -> Option<PathBuf> {+ if let Some(dir) = rt.env(override_env).filter(|s| !s.is_empty()) {return Some(PathBuf::from(dir));}let order: [&str; 2] = if cfg!(windows) { ["USERPROFILE", "HOME"] } else { ["HOME", "USERPROFILE"] };let home = order.iter().find_map(|k| rt.env(k).filter(|s| !s.is_empty()))?;- Some(Path::new(home).join(".impeccable").join("hook-claims"))+ Some(Path::new(home).join(".impeccable").join(name))+}++/// Lowercase hex SHA-256 of `s`: a 64-character name that is safe on every+/// file system.+pub(crate) fn sha256_hex(s: &str) -> String {+ Sha256::digest(s.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()}fn now_bucket() -> Option<u64> {@@ -111,7 +124,7 @@ fn current_uid() -> u32 {/// A directory this invocation may create in and delete from: a real/// directory (the metadata is `lstat`'s, so a symlink is never one), and on/// Unix owned by the current user with no group or other write bit.-fn is_safe_dir(meta: &std::fs::Metadata) -> bool {+pub(crate) fn is_safe_dir(meta: &std::fs::Metadata) -> bool {if !meta.file_type().is_dir() {return false;}@@ -126,7 +139,7 @@ fn is_safe_dir(meta: &std::fs::Metadata) -> bool {}/// Creates one directory level, private to the user on Unix. Not recursive.-fn create_private_dir(path: &Path) -> std::io::Result<()> {+pub(crate) fn create_private_dir(path: &Path) -> std::io::Result<()> {let mut b = std::fs::DirBuilder::new();#[cfg(unix)]{@@ -136,9 +149,20 @@ fn create_private_dir(path: &Path) -> std::io::Result<()> {b.create(path)}+/// Makes a file `opts` creates private to the user on Unix.+pub(crate) fn private_file_mode(opts: &mut std::fs::OpenOptions) {+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ opts.mode(0o600);+ }+ #[cfg(not(unix))]+ let _ = opts;+}+/// `Some(created)` when `path` is (now) a safe directory, `None` when it is/// missing and could not be made, or is unsafe.-fn ensure_safe_dir(path: &Path) -> Option<bool> {+pub(crate) fn ensure_safe_dir(path: &Path) -> Option<bool> {let created = match create_private_dir(path) {Ok(()) => true,Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => false,@@ -151,7 +175,12 @@ fn ensure_safe_dir(path: &Path) -> Option<bool> {/// The claim root, created when missing (with its `.impeccable` parent, a/// plain user dir) and checked; `None` when it is unusable or unsafe.fn safe_root(rt: &Runtime) -> Option<PathBuf> {- let root = claim_root(rt)?;+ safe_user_dir(claim_root(rt)?)+}++/// `root`, created when missing (with its `.impeccable` parent, a plain user+/// dir) and checked; `None` when it is unusable or unsafe.+pub(crate) fn safe_user_dir(root: PathBuf) -> Option<PathBuf> {if std::fs::symlink_metadata(&root).is_err() {if let Some(parent) = root.parent() {// Two hooks of one first edit race to make it: losing that race@@ -171,7 +200,7 @@ fn is_bucket_name(name: &str) -> bool {!name.is_empty() && name.len() <= 20 && name.bytes().all(|b| b.is_ascii_digit())}-fn is_claim_name(name: &str) -> bool {+pub(crate) fn is_claim_name(name: &str) -> bool {name.len() == 64 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))}diff --git a/crates/hook/src/hook_sessions.rs b/crates/hook/src/hook_sessions.rsnew file mode 100644index 000000000..c397b1cb4--- /dev/null+++ b/crates/hook/src/hook_sessions.rs@@ -0,0 +1,162 @@+//! Which project roots a session's per-edit pass wrote a hook cache in, so+//! the Stop pass can find them from a session cwd above the projects (#1101).+//!+//! The per-edit pass keys its cache to the edited file's nearest project root.+//! A Stop event names no file, and walking up from the session cwd misses a+//! project below it: a session started in `~/code` that edits `~/code/app`.+//! So the first time a session writes a root's cache, the per-edit pass also+//! records that root here:+//!+//! `~/.impeccable/hook-sessions/<sha256(session id)>/<sha256(root)>`+//!+//! The file holds the root path. One file per (session, root) means writers+//! never read-modify-write a shared list, so parallel first edits each land+//! once (`create_new`, and losing that race is success). The Stop pass lists+//! the session's dir and keeps an entry only when its content hashes back to+//! its name, which drops partial writes and anything that is not ours.+//!+//! The directories get the same checks as the claim dirs (`hook_claim`): a+//! real directory, not a symlink, owned by the current user with no group or+//! other write bit on Unix, created 0700 one level at a time. Every failure+//! fails open: nothing is recorded, and Stop falls back to the walk up.+//!+//! Cost per edit: two hashes and one `lstat` once the root is recorded. The+//! first edit of a root in a session adds a few `lstat`s, a `create_dir` and+//! a `create_new`. A new session's first record sweeps session dirs untouched+//! for [`EXPIRE_SECONDS`]: it reads the root once, looks at no more than+//! [`SWEEP_SCAN_LIMIT`] entries and removes no more than+//! [`SWEEP_REMOVE_LIMIT`] dirs. It removes only `<64 hex>` dirs, and in them+//! only `<64 hex>` regular files, then the dir if that left it empty.++use std::io::{Read, Write};+use std::path::{Path, PathBuf};+use std::time::{Duration, SystemTime};++use crate::hook_claim::{private_file_mode, ensure_safe_dir, is_claim_name, is_safe_dir, safe_user_dir, sha256_hex, user_dir};+use crate::hook_lib::Runtime;++const OVERRIDE_ENV: &str = "IMPECCABLE_HOOK_SESSION_DIR";+const DIR_NAME: &str = "hook-sessions";++/// A session dir no edit has added a root to for this long is removed. A+/// live session can run for days, so this is generous; a session past it+/// that edits a new root records again, and Stop's walk up still runs.+pub const EXPIRE_SECONDS: u64 = 30 * 24 * 60 * 60;+/// Entries one sweep looks at, and session dirs one sweep removes.+pub const SWEEP_SCAN_LIMIT: usize = 256;+pub const SWEEP_REMOVE_LIMIT: usize = 16;+/// Roots one Stop pass reads from the index.+pub const MAX_ROOTS: usize = 16;+/// A recorded path longer than this is not ours.+const MAX_ENTRY_BYTES: u64 = 4096;++fn index_dir(rt: &Runtime) -> Option<PathBuf> {+ user_dir(rt, OVERRIDE_ENV, DIR_NAME)+}++/// Records that `session`'s per-edit pass wrote the hook cache under `root`.+/// A no-op once recorded, and on any failure.+pub fn record_root(rt: &Runtime, session: &str, root: &str) {+ if session.is_empty() || root.is_empty() || !Path::new(root).is_absolute() {+ return;+ }+ let Some(base) = index_dir(rt) else { return };+ let session_name = sha256_hex(session);+ let file = base.join(&session_name).join(sha256_hex(root));+ // Recorded on an earlier edit: the common case, one lstat.+ if std::fs::symlink_metadata(&file).is_ok() {+ return;+ }+ let Some(base) = safe_user_dir(base) else { return };+ let dir = base.join(&session_name);+ let Some(created) = ensure_safe_dir(&dir) else { return };+ if created {+ sweep_expired(&base, &session_name);+ }+ // `create_new` is O_CREAT|O_EXCL: it never follows a symlink at the path,+ // and a parallel first edit that got there first has already recorded it.+ let mut opts = std::fs::OpenOptions::new();+ opts.write(true).create_new(true);+ private_file_mode(&mut opts);+ if let Ok(mut f) = opts.open(&file) {+ if f.write_all(root.as_bytes()).is_err() {+ // Ours, and unreadable as a record: remove it so the next edit retries.+ drop(f);+ let _ = std::fs::remove_file(&file);+ }+ }+}++/// The roots recorded for `session`, sorted, at most [`MAX_ROOTS`]. Empty+/// when there is no index, or it is not a safe directory.+pub fn recorded_roots(rt: &Runtime, session: &str) -> Vec<String> {+ if session.is_empty() {+ return vec![];+ }+ let Some(base) = index_dir(rt) else { return vec![] };+ let dir = base.join(sha256_hex(session));+ for d in [&base, &dir] {+ match std::fs::symlink_metadata(d) {+ Ok(meta) if is_safe_dir(&meta) => {}+ _ => return vec![],+ }+ }+ let Ok(entries) = std::fs::read_dir(&dir) else { return vec![] };+ let mut roots: Vec<String> = Vec::new();+ for entry in entries.flatten().take(SWEEP_SCAN_LIMIT) {+ let name = entry.file_name();+ let Some(name) = name.to_str().filter(|n| is_claim_name(n)) else { continue };+ // `DirEntry::file_type` does not follow symlinks.+ if !entry.file_type().is_ok_and(|t| t.is_file()) {+ continue;+ }+ let Some(root) = read_entry(&entry.path()) else { continue };+ // A root that is gone (a deleted project, a test's temp dir) never+ // takes one of the [`MAX_ROOTS`] places.+ if sha256_hex(&root) == name && Path::new(&root).is_absolute() && Path::new(&root).is_dir() && !roots.contains(&root) {+ roots.push(root);+ }+ }+ roots.sort();+ roots.truncate(MAX_ROOTS);+ roots+}++fn read_entry(path: &Path) -> Option<String> {+ let f = std::fs::File::open(path).ok()?;+ let mut buf = String::new();+ f.take(MAX_ENTRY_BYTES + 1).read_to_string(&mut buf).ok()?;+ (!buf.is_empty() && buf.len() as u64 <= MAX_ENTRY_BYTES).then_some(buf)+}++/// Removes session dirs whose mtime is older than [`EXPIRE_SECONDS`]. Runs+/// only when this invocation created a session dir, so it is paid once per+/// session. Only safe `<64 hex>` dirs are touched, and in them only+/// `<64 hex>` regular files; a dir holding anything else is left in place.+fn sweep_expired(base: &Path, keep: &str) {+ let Some(cutoff) = SystemTime::now().checked_sub(Duration::from_secs(EXPIRE_SECONDS)) else { return };+ let Ok(entries) = std::fs::read_dir(base) else { return };+ let mut removed = 0usize;+ for entry in entries.flatten().take(SWEEP_SCAN_LIMIT) {+ if removed >= SWEEP_REMOVE_LIMIT {+ break;+ }+ let name = entry.file_name();+ let Some(name) = name.to_str().filter(|n| is_claim_name(n) && *n != keep) else { continue };+ let dir = base.join(name);+ let Ok(meta) = std::fs::symlink_metadata(&dir) else { continue };+ if !is_safe_dir(&meta) || meta.modified().map_or(true, |m| m > cutoff) {+ continue;+ }+ let Ok(files) = std::fs::read_dir(&dir) else { continue };+ for file in files.flatten().take(SWEEP_SCAN_LIMIT) {+ let ok_name = file.file_name().to_str().is_some_and(is_claim_name);+ if ok_name && file.file_type().is_ok_and(|t| t.is_file()) {+ let _ = std::fs::remove_file(file.path());+ }+ }+ if std::fs::remove_dir(&dir).is_ok() {+ removed += 1;+ }+ }+}diff --git a/crates/hook/src/lib.rs b/crates/hook/src/lib.rsindex e926c11a0..0bae326bb 100644--- a/crates/hook/src/lib.rs+++ b/crates/hook/src/lib.rs@@ -15,6 +15,7 @@ pub mod before_edit;pub mod hook;pub mod hook_claim;pub mod hook_lib;+pub mod hook_sessions;mod build_completion;mod stop_baseline;pub mod util;diff --git a/crates/hook/tests/hook_tests.rs b/crates/hook/tests/hook_tests.rsindex da6c22fe6..e9c1d2b47 100644--- a/crates/hook/tests/hook_tests.rs+++ b/crates/hook/tests/hook_tests.rs@@ -3251,3 +3251,298 @@ fn concurrent_first_edits_in_a_fresh_home_scan_once() {assert_eq!(scans, 1, "round {round}");}}++// ─── Session root index: Stop from a cwd above the project (#1101) ───────────++/// A temp HOME under the fixture, so the index never touches the real one.+fn home_env(t: &Tmp) -> HashMap<String, String> {+ let home = jsp::join(&[&t.path(), "home"]);+ std::fs::create_dir_all(&home).unwrap();+ env(&[("HOME", &home), ("USERPROFILE", &home)])+}++fn index_dir(t: &Tmp) -> String {+ jsp::join(&[&t.path(), "home", ".impeccable", "hook-sessions"])+}++fn names_in(dir: &str) -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir(dir)+ .map(|it| it.map(|e| e.unwrap().file_name().into_string().unwrap()).collect())+ .unwrap_or_default();+ names.sort();+ names+}++fn umbrella(t: &Tmp, projects: &[(&str, &str)]) -> (String, Vec<String>) {+ let files = projects+ .iter()+ .map(|(name, css)| {+ t.write(&format!("work/{name}/package.json"), "{}");+ t.write(&format!("work/{name}/src/a.css"), css)+ })+ .collect();+ (jsp::join(&[&t.path(), "work"]), files)+}++#[test]+fn stop_from_an_umbrella_cwd_finds_the_project_below_it() {+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("site", SIDE_TAB_CSS)]);+ let edit = hook::run_hook(&rt_with(&work, e.clone()), &edit_event(&work, &files[0], "p1"));+ let site = jsp::join(&[&work, "site"]);+ assert_eq!(audit_str(&edit.audit, "cwd"), Some(site.as_str()));+ let stop = hook::run_stop_hook(&rt_with(&work, e.clone()), &stop_event(&work, "p1"));+ assert!(stop.stdout.contains("[side-tab]"), "{} {:?}", stop.stdout, stop.audit);+ assert_eq!(audit_str(&stop.audit, "cwd"), Some(site.as_str()));+ assert!(stop.audit.get("roots").is_none(), "{:?}", stop.audit);+ // Nothing lands in the umbrella folder itself (#346).+ assert!(!t.exists("work/.impeccable"));+ // The second Stop has nothing new to say.+ let again = hook::run_stop_hook(&rt_with(&work, e.clone()), &stop_event(&work, "p1"));+ assert_eq!(again.stdout, "", "{:?}", again.audit);+ assert_eq!(audit_str(&again.audit, "skipped"), Some("stop-clean"));+ // Another session's Stop does not see this session's roots.+ let other = hook::run_stop_hook(&rt_with(&work, e), &stop_event(&work, "p2"));+ assert_eq!(audit_str(&other.audit, "skipped"), Some("no-touched-files"));+}++#[test]+fn stop_reports_every_project_the_session_edited_within_the_caps() {+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("app", SIDE_TAB_CSS), ("site", SIDE_TAB_CSS)]);+ for file in &files {+ hook::run_hook(&rt_with(&work, e.clone()), &edit_event(&work, file, "p1"));+ }+ let stop = hook::run_stop_hook(&rt_with(&work, e.clone()), &stop_event(&work, "p1"));+ assert!(stop.stdout.contains("app/src/a.css"), "{}", stop.stdout);+ assert!(stop.stdout.contains("site/src/a.css"), "{}", stop.stdout);+ assert_eq!(stop.audit["roots"], 2);+ assert_eq!(stop.audit["freshFiles"], 2);+ assert!(!t.exists("work/.impeccable"));+ let again = hook::run_stop_hook(&rt_with(&work, e.clone()), &stop_event(&work, "p1"));+ assert_eq!(again.stdout, "", "{:?}", again.audit);++ // The lead project's caps bound the combined output.+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("app", SIDE_TAB_CSS), ("site", SIDE_TAB_CSS)]);+ t.write("work/app/.impeccable/config.json", r#"{"hook":{"limits":{"maxFindings":1}}}"#);+ for file in &files {+ hook::run_hook(&rt_with(&work, e.clone()), &edit_event(&work, file, "p1"));+ }+ let stop = hook::run_stop_hook(&rt_with(&work, e.clone()), &stop_event(&work, "p1"));+ let finding_lines = stop.stdout.matches("[side-tab]").count();+ assert_eq!(finding_lines, 1, "{}", stop.stdout);+ assert!(stop.stdout.contains("more in site/src/a.css"), "{}", stop.stdout);+ // Both projects remembered what this Stop saw: the next is silent.+ let again = hook::run_stop_hook(&rt_with(&work, e), &stop_event(&work, "p1"));+ assert_eq!(again.stdout, "", "{:?}", again.audit);+}++#[test]+fn a_disabled_or_native_project_drops_out_and_the_other_still_reports() {+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("app", SIDE_TAB_CSS), ("site", SIDE_TAB_CSS)]);+ for file in &files {+ hook::run_hook(&rt_with(&work, e.clone()), &edit_event(&work, file, "p1"));+ }+ t.write("work/app/.impeccable/config.json", r#"{"hook":{"enabled":false}}"#);+ let stop = hook::run_stop_hook(&rt_with(&work, e.clone()), &stop_event(&work, "p1"));+ assert!(stop.stdout.contains("[side-tab]"), "{}", stop.stdout);+ assert!(!stop.stdout.contains("app/src"), "{}", stop.stdout);+ assert_eq!(audit_str(&stop.audit, "cwd"), Some(jsp::join(&[&work, "site"]).as_str()));+}++#[test]+fn without_a_session_id_stop_walks_up_as_before_and_records_nothing() {+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("site", SIDE_TAB_CSS)]);+ let edit = json!({ "cwd": work, "hook_event_name": "PostToolUse", "tool_name": "Edit",+ "tool_input": { "file_path": files[0] } }).to_string();+ hook::run_hook(&rt_with(&work, e.clone()), &edit);+ assert!(!std::path::Path::new(&index_dir(&t)).exists());+ let stop = json!({ "cwd": work, "hook_event_name": "Stop", "stop_hook_active": false }).to_string();+ let res = hook::run_stop_hook(&rt_with(&work, e.clone()), &stop);+ assert_eq!(audit_str(&res.audit, "skipped"), Some("no-touched-files"));+ // From the project itself the walk still finds it.+ let site = jsp::join(&[&work, "site"]);+ let stop = json!({ "cwd": site, "hook_event_name": "Stop", "stop_hook_active": false }).to_string();+ let res = hook::run_stop_hook(&rt_with(&site, e), &stop);+ assert!(res.stdout.contains("[side-tab]"), "{:?}", res.audit);+}++#[test]+fn without_a_usable_home_stop_walks_up_as_before() {+ let t = Tmp::new();+ let (work, files) = umbrella(&t, &[("site", SIDE_TAB_CSS)]);+ hook::run_hook(&rt(&work), &edit_event(&work, &files[0], "p1"));+ let res = hook::run_stop_hook(&rt(&work), &stop_event(&work, "p1"));+ assert_eq!(audit_str(&res.audit, "skipped"), Some("no-touched-files"));+}++/// An index root that is a symlink is never followed: nothing is created or+/// removed behind it, and Stop falls back to the walk up.+#[test]+#[cfg(unix)]+fn a_symlinked_index_root_is_never_followed() {+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("site", SIDE_TAB_CSS)]);+ let victim = jsp::join(&[&t.path(), "victim"]);+ t.write(&format!("victim/{OLD_CLAIM}/{OLD_CLAIM}"), &work);+ t.write("home/.impeccable/keep.txt", "");+ std::os::unix::fs::symlink(&victim, index_dir(&t)).unwrap();+ hook::run_hook(&rt_with(&work, e.clone()), &edit_event(&work, &files[0], "p1"));+ let res = hook::run_stop_hook(&rt_with(&work, e), &stop_event(&work, "p1"));+ assert_eq!(audit_str(&res.audit, "skipped"), Some("no-touched-files"));+ assert_eq!(names_in(&victim), vec![OLD_CLAIM.to_string()]);+ assert_eq!(names_in(&jsp::join(&[&victim, OLD_CLAIM])), vec![OLD_CLAIM.to_string()]);+}++/// A root other users can write to is not trusted, for writing or reading.+#[test]+#[cfg(unix)]+fn a_group_or_world_writable_index_root_is_not_used() {+ use std::os::unix::fs::PermissionsExt;+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("site", SIDE_TAB_CSS)]);+ let root = index_dir(&t);+ std::fs::create_dir_all(&root).unwrap();+ std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o777)).unwrap();+ hook::run_hook(&rt_with(&work, e.clone()), &edit_event(&work, &files[0], "p1"));+ assert!(names_in(&root).is_empty());+ // A record planted under it is not read either.+ let site = jsp::join(&[&work, "site"]);+ let planted = jsp::join(&[&root, &sha256("p1"), &sha256(&site)]);+ std::fs::create_dir_all(std::path::Path::new(&planted).parent().unwrap()).unwrap();+ std::fs::write(&planted, &site).unwrap();+ let res = hook::run_stop_hook(&rt_with(&work, e), &stop_event(&work, "p1"));+ assert_eq!(audit_str(&res.audit, "skipped"), Some("no-touched-files"));+}++fn sha256(s: &str) -> String {+ use sha2::Digest;+ sha2::Sha256::digest(s.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()+}++/// A record whose content does not hash to its name (a partial write, or a+/// file that is not ours) is ignored.+#[test]+#[cfg(unix)]+fn a_record_that_does_not_hash_to_its_name_is_ignored() {+ let t = Tmp::new();+ let e = home_env(&t);+ let (work, files) = umbrella(&t, &[("site", SIDE_TAB_CSS)]);+ hook::run_hook(&rt_with(&work, e.clone()), &edit_event(&work, &files[0], "p1"));+ let session_dir = jsp::join(&[&index_dir(&t), &sha256("p1")]);+ let site = jsp::join(&[&work, "site"]);+ let record = jsp::join(&[&session_dir, &sha256(&site)]);+ assert_eq!(std::fs::read_to_string(&record).unwrap(), site);+ std::fs::write(&record, "/elsewhere").unwrap();+ let res = hook::run_stop_hook(&rt_with(&work, e), &stop_event(&work, "p1"));+ assert_eq!(audit_str(&res.audit, "skipped"), Some("no-touched-files"));+}++#[test]+fn parallel_first_edits_record_each_root_once() {+ let t = Tmp::new();+ let e = home_env(&t);+ let roots = [jsp::join(&[&t.path(), "work", "a"]), jsp::join(&[&t.path(), "work", "b"])];+ std::thread::scope(|s| {+ for i in 0..16 {+ let (e, root) = (e.clone(), roots[i % 2].clone());+ let cwd = t.path();+ s.spawn(move || impeccable_hook::hook_sessions::record_root(&rt_with(&cwd, e), "p1", &root));+ }+ });+ for root in &roots {+ std::fs::create_dir_all(root).unwrap();+ }+ let session_dir = jsp::join(&[&index_dir(&t), &sha256("p1")]);+ let mut expected: Vec<String> = roots.iter().map(|r| sha256(r)).collect();+ expected.sort();+ assert_eq!(names_in(&session_dir), expected);+ let r = rt_with(&t.path(), e);+ let mut recorded = impeccable_hook::hook_sessions::recorded_roots(&r, "p1");+ recorded.sort();+ assert_eq!(recorded, roots.to_vec());+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ for dir in [index_dir(&t), session_dir.clone()] {+ assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700, "{dir}");+ }+ let file = jsp::join(&[&session_dir, &sha256(&roots[0])]);+ assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);+ }+}++/// Session ids and roots become 64-hex names whatever characters they hold,+/// so a Windows path or an id with `:` or `/` is a valid file name.+#[test]+fn index_names_are_safe_on_every_file_system() {+ let t = Tmp::new();+ let e = home_env(&t);+ let r = rt_with(&t.path(), e);+ let root = jsp::join(&[&t.path(), "proj"]);+ std::fs::create_dir_all(&root).unwrap();+ let session = r"a/b:c*?<>|\d";+ impeccable_hook::hook_sessions::record_root(&r, session, &root);+ // A recorded root that no longer exists is not returned.+ impeccable_hook::hook_sessions::record_root(&r, session, &jsp::join(&[&t.path(), "gone"]));+ let sessions = names_in(&index_dir(&t));+ assert_eq!(sessions.len(), 1);+ let records = names_in(&jsp::join(&[&index_dir(&t), &sessions[0]]));+ for name in sessions.iter().chain(&records) {+ assert!(name.len() == 64 && name.bytes().all(|b| b.is_ascii_hexdigit()), "{name}");+ }+ assert_eq!(impeccable_hook::hook_sessions::recorded_roots(&r, session), vec![root]);+ // A relative root is not recorded.+ impeccable_hook::hook_sessions::record_root(&r, "p2", "relative/dir");+ assert_eq!(names_in(&index_dir(&t)).len(), 1);+}++/// A new session sweeps session dirs untouched for the expiry window. It+/// removes only `<64 hex>` dirs and `<64 hex>` files in them: foreign names,+/// foreign files, fresh sessions and symlinks stay.+#[test]+#[cfg(unix)]+fn expiry_removes_only_old_session_dirs_of_ours() {+ use std::os::unix::fs::PermissionsExt;+ let t = Tmp::new();+ let e = home_env(&t);+ let root = index_dir(&t);+ let old_a = "a".repeat(64);+ let old_b = "b".repeat(64);+ let fresh = "c".repeat(64);+ let linked = "d".repeat(64);+ t.write(&format!("home/.impeccable/hook-sessions/{old_a}/{OLD_CLAIM}"), "/x");+ t.write(&format!("home/.impeccable/hook-sessions/{old_b}/{OLD_CLAIM}"), "/x");+ t.write(&format!("home/.impeccable/hook-sessions/{old_b}/notes.txt"), "not ours");+ t.write(&format!("home/.impeccable/hook-sessions/{fresh}/{OLD_CLAIM}"), "/x");+ t.write("home/.impeccable/hook-sessions/keep-me/x", "not ours");+ t.write(&format!("outside/{OLD_CLAIM}"), "/x");+ std::os::unix::fs::symlink(jsp::join(&[&t.path(), "outside"]), jsp::join(&[&root, &linked])).unwrap();+ for d in [root.clone(), jsp::join(&[&root, &old_a]), jsp::join(&[&root, &old_b]), jsp::join(&[&root, &fresh]), jsp::join(&[&root, "keep-me"])] {+ std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)).unwrap();+ }+ let long_ago = std::time::SystemTime::now()+ - std::time::Duration::from_secs(impeccable_hook::hook_sessions::EXPIRE_SECONDS + 3600);+ for d in [&old_a, &old_b, &"keep-me".to_string()] {+ std::fs::File::open(jsp::join(&[&root, d])).unwrap().set_modified(long_ago).unwrap();+ }+ impeccable_hook::hook_sessions::record_root(&rt_with(&t.path(), e), "new-session", &jsp::join(&[&t.path(), "p"]));+ let names = names_in(&root);+ assert!(!names.contains(&old_a), "{names:?}");+ assert!(names.contains(&old_b) && names.contains(&fresh) && names.contains(&linked), "{names:?}");+ assert!(names.contains(&"keep-me".to_string()) && names.contains(&sha256("new-session")), "{names:?}");+ assert_eq!(names_in(&jsp::join(&[&root, &old_b])), vec!["notes.txt".to_string()]);+ assert_eq!(names_in(&jsp::join(&[&root, &fresh])), vec![OLD_CLAIM.to_string()]);+ assert!(t.exists(&format!("outside/{OLD_CLAIM}")));+ assert!(t.exists("home/.impeccable/hook-sessions/keep-me/x"));+}diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex f233e314a..0627bdb12 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -1264,9 +1264,9 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill l7. For each target file (audit.file updated each iteration): skip with `lastSkip` = `'sensitive'` (contains `..` or SENSITIVE_PATH), `'generated'`, `'extension'` (not ALLOWED and not configured), `'config-ignore-file'` (`matchesAnyGlob(relativized)` or `(absolute)` vs `config.ignoreFiles`), `'file-missing'`, `'outside-project'`, `'too-large'` (records `skippedBytes`), and, once the content is read, `'live-preview'` (LIVE_PREVIEW_MARKERS; when the marked file is the edited PRIMARY, the whole event returns `{emitted:false, skipped:'live-preview'}` with `file` = that primary, co-scanned stylesheets included). If the file is a PRIMARY (not co-scanned): `editCount = bumpEditCount(...)`; if `editCount > 6` → if `=== 7` and no suppression winner yet → `suppressionWinner={filePath}`; `lastSkip='suppressed'`, `suppressedHit=true`, continue. Read content, run detector (throw → `findings=[]`, `detectorThrew=true`). `filtered = filterFindings(...)`; if tiered split into immediate/deferred else all immediate. If deferred non-empty → `touchFile`, `deferredTotal += n`. `fresh = dedupeAgainstCache(immediate, ...)`. `audit.findings = raw count`, `audit.freshFindings = fresh.length`, `audit.deferred = deferredTotal` (if >0). If detectorThrew → `detectorThrewAny=true`, continue (cache untouched for that file). `rememberFindings(cache, sid, file, immediate)` (replace). If fresh>0 → push `{filePath, findings: fresh}` to `freshGroups`, continue. Else if immediate>0 and no pendingWinner → `pendingWinner={filePath, known: immediate.map(findingCacheKey)}`; else if immediate==0 and no cleanWinner: if quiet or not ack-eligible → `cleanWinner={filePath}` (without consuming `cleanAcked`); else if `fileEntry.cleanAcked` → `cleanAckDeduped=true` (keep scanning); else set `cleanAcked=true`, `cleanWinner={filePath}`, `cleanAckDeduped=false`.8. If `freshGroups` non-empty: `text = appendDesignSystemNoteOnce(renderGroupedTemplate(freshGroups, config, {cwd:projectCwd, footer: footerModeForSession, reserveChars: designNoteReserve}), ...)`; `commitFooterShown`; **`persistCache` always** (creates `.impeccable/` if needed); return `stdout = payload(text,'PostToolUse',harness)`, audit `{..., file: firstGroup.filePath, emitted:true, freshFiles, freshFindings(total), chars, durationMs}`, `emission:{kind:'fresh', file, findings, groups}`.9. Else compute `ack`: not quiet AND pendingWinner AND ack-eligible → `{kind:'pending', text: appendDesignSystemNoteOnce(renderPendingAck(...))}`; else not quiet AND no suppressionWinner AND cleanWinner AND !cleanAckDeduped AND ack-eligible → `{kind:'clean', text: appendDesignSystemNoteOnce(renderCleanAck(...))}`.- 10. Persist cache only if `deferredTotal > 0 || (cacheDirty && exists(<projectCwd>/.impeccable))` (a clean edit in a project with no `.impeccable/` footprint writes nothing to disk).+ 10. Persist cache only if `deferredTotal > 0 || (cacheDirty && exists(<projectCwd>/.impeccable))` (a clean edit in a project with no `.impeccable/` footprint writes nothing to disk). After a persist, a named session records the project root in the session index (#1101, below).11. Return precedence: `detectorThrewAny && !pendingWinner && !cleanWinner` → audit `{emitted:false, error:'detector-threw'}`; quiet → `{emitted:false, quiet:true}`; pending ack → stdout payload, audit `{file, emitted:true, kind:'pending', pending:<n>, chars}`; suppressionWinner → stdout `payload(suppressionNotice(relativize(file)))`, audit `{file, suppressed:true, emitted:true}`; clean ack → stdout payload, audit `{file, emitted:true, kind:'clean', chars}`; pendingWinner (non-UI) → `{emitted:false, skipped:'non-ui-ack'}`; cleanWinner → same `'non-ui-ack'`; cleanAckDeduped → `skipped:'clean-ack-deduped'`; suppressedHit → `{suppressed:true, emitted:false}`; else `{skipped:lastSkip, bytes?:skippedBytes (only when 'too-large')}`. Any exception → `{exitCode:0, stdout:'', audit:{..., error}}`.-- **Stop algorithm (`runStopHook`)**: re-entrancy/disabled/malformed/empty as above; `event.stop_hook_active === true` → `skipped:'stop-hook-active'` (no scan, no output; prevents Claude Code re-invocation loops, issue #400). `sessionId = event.session_id || 'unknown'`; the config gate, build-completion reminder and shipped-build note use `resolve(event.cwd || cwd)` (`build-phase` writes its state under its own cwd); the touched-file scan then uses `projectCwd` = the nearest directory from there up to (not including) the home dir whose cache lists files touched by this session, else the same cwd, and a `projectCwd` elsewhere must also pass its own config gate (#1088); config disabled → `'config-disabled'`; `touched = keys(cache.sessions[sid].files)`; empty → `'no-touched-files'`; native → `'native-platform'`; detector missing → `'detector-missing'`. Iterate touched files (max 20 scanned): same skips (sensitive/generated/extension/ignoreFiles/missing/outside-project) silently; read (unreadable → skip; LIVE_PREVIEW_MARKERS in the content → skip); detect with full rule set (no tiering); `filtered = filterFindings`; `fresh = dedupeAgainstCache`; if fresh → `rememberFindings(cache, sid, file, fresh)` (NOTE: replaces the file's remembered set with only the fresh ones), push group. `audit.scannedFiles`. No groups → `{emitted:false, skipped:'stop-clean'}`. Else render grouped with footer mode + reserve, `appendDesignSystemNoteOnce`, `commitFooterShown`, `persistCache`, stdout `payload(text,'Stop',harness)`, audit `{emitted:true, freshFiles, freshFindings, chars, durationMs}`, `emission:{kind:'stop-deep-pass', groups}`.+- **Stop algorithm (`runStopHook`)**: re-entrancy/disabled/malformed/empty as above; `event.stop_hook_active === true` → `skipped:'stop-hook-active'` (no scan, no output; prevents Claude Code re-invocation loops, issue #400). `sessionId = event.session_id || 'unknown'`; the config gate, build-completion reminder and shipped-build note use `resolve(event.cwd || cwd)` (`build-phase` writes its state under its own cwd); the touched-file scan then runs over a list of roots: first the nearest directory from there up to (not including) the home dir whose cache lists files touched by this session, else the same cwd (#1088), then every root the session index records for a named session (#1101, below), deduped and sorted. Each root is scanned under its own config, cache and platform; a root other than the session cwd must pass its own config gate. Per root: config disabled → `'config-disabled'`; `touched = keys(cache.sessions[sid].files)`; empty → `'no-touched-files'`; native → `'native-platform'`; a root that stops at one of these adds nothing, and only when every root stopped is the first root's skip returned (so a single root behaves as before); detector missing → `'detector-missing'`. Iterate touched files (max 20 scanned): same skips (sensitive/generated/extension/ignoreFiles/missing/outside-project) silently; read (unreadable → skip; LIVE_PREVIEW_MARKERS in the content → skip); detect with full rule set (no tiering); `filtered = filterFindings`; `fresh = dedupeAgainstCache`; if fresh → `rememberFindings(cache, sid, file, fresh)` (NOTE: replaces the file's remembered set with only the fresh ones), push group. `audit.scannedFiles`. No groups → `{emitted:false, skipped:'stop-clean'}`. Else render grouped with footer mode + reserve, `appendDesignSystemNoteOnce`, `commitFooterShown`, `persistCache`, stdout `payload(text,'Stop',harness)`, audit `{emitted:true, freshFiles, freshFindings, chars, durationMs}`, `emission:{kind:'stop-deep-pass', groups}`.- **Outputs**:- stdout: exactly one JSON document (no trailing newline) when something is emitted, else nothing. Claude/Codex/Grok: `{"hookSpecificOutput":{"hookEventName":"PostToolUse"|"Stop","additionalContext":"<text>"}}`. Cursor-shaped: `{"additional_context":"<text>"}`. GitHub: `{"additionalContext":"<text>"}`.- stderr: only `[impeccable-hook] <err>` when `IMPECCABLE_HOOK_DEBUG` and an unexpected top-level error.@@ -1280,9 +1280,9 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill lTriage each finding, then state in your reply ... (full footer, 5 lines; short footer on later fires in the session)```optionally followed by `\n\n[impeccable@1] DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.` once per session.-- **Side effects**: writes `.impeccable/hook.cache.json` (rules in step 8/10 and Stop), git `info/exclude` block (via persistCache), audit NDJSON (env/config). `process.env.IMPECCABLE_HOOK_DEPTH='1'` exported to children. Audit entries: `{ts, event:'PostToolUse'|'Stop', harness, cwd, session, tool?, file?, ext?, editCount?, findings?, freshFindings?, deferred?, emitted?, kind?, pending?, chars?, freshFiles?, scannedFiles?, suppressed?, skipped?, bytes?, reentrant?, quiet?, error?, platform?, durationMs}`; on crash `{ts, event:'hook-error', error}`.+- **Side effects**: writes `.impeccable/hook.cache.json` (rules in step 8/10 and Stop), git `info/exclude` block (via persistCache), the session index under `~/.impeccable/hook-sessions/` (below), audit NDJSON (env/config). `process.env.IMPECCABLE_HOOK_DEPTH='1'` exported to children. Audit entries: `{ts, event:'PostToolUse'|'Stop', harness, cwd, session, tool?, file?, ext?, editCount?, findings?, freshFindings?, deferred?, emitted?, kind?, pending?, chars?, freshFiles?, scannedFiles?, roots?, suppressed?, skipped?, bytes?, reentrant?, quiet?, error?, platform?, durationMs}`; on crash `{ts, event:'hook-error', error}`.- **Detection performed**: `detectHtml(filePath, {designSystem?})` for html-engine targets; `detectText(content, filePath, {designSystem?})` otherwise. Findings capped in render at `limits.maxFindings` (5) total per emission and `limits.maxChars` (8000, floor 500) chars; deduped per session per file by `findingCacheKey`; per-edit shows only IMMEDIATE tier (unless `perEditRules:'all'` or cursor/github harness); advisory rules dropped unless `detector.advisoryRules:'include'`.-- **Edge cases / gotchas**: generated/sensitive paths and any path containing `..` never scanned; native PRODUCT.md platform → whole scan skipped (audit `native-platform`); files > 128 KiB skipped; empty stdin is `stdin-malformed` (not `stdin-empty`); the 7th edit of a primary file in a session emits the suppression notice once and the file is silent thereafter (co-scanned stylesheets don't bump counts); umbrella-dir launches key `.impeccable/` to the edited file's nearest project root but the Stop pass searches the session cwd and its ancestors (so umbrella-dir sessions, with the cwd above the project, still no-op on Stop); Windows: `path.sep` normalized to `/` for globs/display and command-arg quoting switches to double quotes; timeouts are the harness's (5 s per-edit, 30 s Stop) — the script has no internal timer; a detector throw leaves the cache untouched and yields `error:'detector-threw'` only if nothing else emitted; `hook.mjs` never returns exit 2, so no harness treats it as blocking.+- **Edge cases / gotchas**: generated/sensitive paths and any path containing `..` never scanned; native PRODUCT.md platform → whole scan skipped (audit `native-platform`); files > 128 KiB skipped; empty stdin is `stdin-malformed` (not `stdin-empty`); the 7th edit of a primary file in a session emits the suppression notice once and the file is silent thereafter (co-scanned stylesheets don't bump counts); umbrella-dir launches key `.impeccable/` to the edited file's nearest project root; the Stop pass searches the session cwd and its ancestors, and reaches projects below the session cwd through the session index, so an umbrella-dir session (the cwd above the projects) reports on Stop when it has a session id and a usable home dir, and still no-ops without one; Windows: `path.sep` normalized to `/` for globs/display and command-arg quoting switches to double quotes; timeouts are the harness's (5 s per-edit, 30 s Stop) — the script has no internal timer; a detector throw leaves the cache untouched and yields `error:'detector-threw'` only if nothing else emitted; `hook.mjs` never returns exit 2, so no harness treats it as blocking.- **Tests covering it**: `tests/hook.test.mjs` — `truthy()`, `SENSITIVE_PATH / GENERATED_PATH`, `isScanTargetInsideProject()`, `readConfig()`, `readCache / persistCache / bumpEditCount`, `ensureHookGitExcludes()`, `matchesAnyGlob()`, `filterFindings()`, `renderTemplate()` (envelope, footer text, short footer, description dedupe, ignore hints, POSIX/Windows quoting #476/#533, clamp behaviour), `writeAuditLog()`, `payload()`, `runHook()` (≈40 cases: fresh→pending, GitHub edit/apply_patch end-to-end, clean ack, .ts/.js quiet, IMPECCABLE_HOOK_QUIET, config quiet, re-entrancy, kill switch, config-disabled, native platform, DESIGN.md gating, staleness note, sensitive/generated/traversal/outside-project/symlink, extension allowlist, ignoreFiles, suppression on 7th edit, MultiEdit/apply_patch shapes, detector throw, async HTML detector, inline impeccable-disable, malformed stdin, missing file), `runHook() — cache write gating`, `— oversized files`, `— session cache tracks current scan`, `— session-scoped notices`, `— clean-ack noise`, `resolveCacheCwd()`, `suppressionNotice()`, `ALLOWED_EXTS`, `matchConfiguredExtension()`, `renderCleanAck()/renderPendingAck()`, `parseApplyPatchPaths()`, `resolveTargetFiles()`, `resolveHarness()/normalizeHookEvent()`, `expandScanTargets()`, `runHook() — co-located stylesheet scan`, `— events without file_path`, `— configured template extensions (#316)`, `resolveProjectPlatform()/isNativePlatform()`, `runHook() — emission enrichment`, `— per-edit tiering`, `runStopHook()` (full rule set + dedupe, clamped grouped render, no touched files, out-of-project files, second Stop silent, ignoreRules, advisory, stop_hook_active true/false, kill switches). `tests/hook-build.test.mjs` — manifest builders for Claude/Codex/Cursor/GitHub/Grok, node-probe presence and cmd.exe-safe characters, generated root manifests match builders, plugin `hooks/hooks.json` uses `${CLAUDE_PLUGIN_ROOT}`, generated skill runtime can import bundled detector.---@@ -1291,6 +1291,15 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill lWhen the Stop pass shows findings while the session's own comp build has a `finish --disposition ship` that still covers the page (`build-phase completion` status `complete`, same session), it appends one line after the findings: `[impeccable@1] The comp build for <artifact> has finish --disposition ship recorded. A fix after it voids that finish: once the fixes are in, run <self> build-phase finish --disposition ship again so the final check covers the current files.` It also records the build under the session cache's `findingsAfterFinish`. The build-completion reminder normally stands down on a `stop_hook_active` Stop with no reminder issued yet, so it never takes over another hook's continuation; a continuation this pass started with those findings is its own, so the reminder may fire there. The marker grants that one continuation: the first `stop_hook_active` Stop removes it whether or not the reminder fires. The reminder's "unchanged since the last reminder" check fingerprints the entry and every recorded capture input, so a stylesheet-only edit after a reminder earns another (cache field `boundSha256`, which replaced `artifactSha256`). When a bound file changed after the finish, the reminder reads `Comp build for <artifact> is unfinished. A file the recorded finish bound changed after it (<changed paths>), so that ship no longer covers the build. Run <self> build-phase finish --disposition ship again before you stop: it rechecks the current files and must pass the responsive gate again. If it refuses, follow what it prints. If work is blocked, report what remains unresolved. This is completion pass N of 3; existing fidelity gates still apply.` The three-pass bound is unchanged.+#### Session index: Stop from a folder above the projects (#1101)++A Stop event names no file, so the walk up from the session cwd cannot see a project below it, such as a session started in `~/code` that edits `~/code/app`. The per-edit pass therefore records each project root it writes a cache in, per session, in a per-user index: `~/.impeccable/hook-sessions/<sha256(session id)>/<sha256(root)>`, a file holding the root path (`IMPECCABLE_HOOK_SESSION_DIR` overrides the directory; home is `HOME`, then `USERPROFILE`, the other way round on Windows, read from the hook's environment).++- **When it is written**: after the per-edit pass persists a project's cache, for an event with a `session_id`, on harnesses that run a Stop pass (not Cursor or GitHub Copilot). The cache persists only after a file passed the sensitive, generated, extension, ignore, missing and outside-project checks; native-platform projects and duplicate events return before it. A root already recorded for the session costs one `lstat`. One file per (session, root) means parallel first edits never rewrite a shared list: the record is `create_new`, and losing that race is success.+- **Safety**: the index root and each session dir must be a real directory (never a symlink) that, on Unix, the current user owns with no group or other write bit; they are created 0700 one level at a time, and records 0600. Any failure, or an unsafe directory, records nothing and is never an error.+- **Expiry**: when a session creates its dir, the pass removes session dirs whose mtime is older than 30 days. It looks at no more than 256 entries and removes no more than 16 dirs; it removes only `<64 hex>` dirs, and in them only `<64 hex>` regular files, then the dir if that left it empty. Symlinks are never followed.+- **Stop**: lists the session's dir (same safety checks; a missing or unsafe index means no recorded roots) and keeps a record only when its content is the absolute path of an existing directory whose SHA-256 is the record's name, at most 16 roots. These roots follow the walk-up root in the scan list. Each root keeps its own dedupe, so a second Stop with nothing new is silent per root. Files scanned across all roots share the 20-file cap. When findings come from one root, the output is exactly the single-root output. When they come from several, they render as one grouped list, root by root, with paths relative to the session cwd (so each path names its project); the first root with findings leads, and its config sets `maxFindings` and `maxChars` for the whole list, its cache supplies the footer mode and the design-system note, and every root that showed findings records the footer. The audit `cwd` is the first scanned root, and `roots` counts the scanned roots when there are more than one.+#### Stop finding attribution (#522)The Rust Stop pass still scans whole touched files; it does not infer causation from changed line ranges. It suppresses confirmed pre-existing text findings and marks remaining findings `[new]` or `[attribution unknown]`. Unknown findings remain visible, with a reminder not to treat them as regressions or broaden the task without asking. Explicit `detect` scans and per-edit/pre-edit output are unchanged.diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.mdindex edf8e8947..19c200c15 100644--- a/tests/oracle/DELTAS.md+++ b/tests/oracle/DELTAS.md@@ -7192,3 +7192,7 @@ Merged again with main (#1105, #1110): the three directory sweeps re-recorded frMerged again with main (#1059, #1106, #1112): the three directory sweeps re-recorded from the binary and reviewed by hand differ from main only by the four `hard-offset-shadow` advisories, advisory notes 174 to 178, failures and exit codes unchanged.Review round, 2026-10-22 (#998 review threads): a zero length now counts as zero in any CSS length unit, so a `0em` blur reports like `0px`, while a non-zero non-`px` length stays unresolved. `colors.html` gains two should-flag rows (`4px 4px 0 black`, `4px 4px 0em black`) and three should-pass rows (`rgba(0,0,0,0)` and `hsla(0,0%,0%,0)` paint, a `1em` blur). Re-recorded from the binary and reviewed by hand: `detect-hard-offset-shadow-colors-advisory` goes from four advisories to six, the two new rows; the pass rows are quiet; exit 0. `detect-hard-offset-shadow-colors-no-advisory` and every other golden did not move.++## Recorded 2026-10-22: Stop from a folder above the projects (#1101)++The per-edit pass now records each project root it writes a cache in under a per-user session index, `~/.impeccable/hook-sessions/` (`docs/CLI-CONTRACT.md`, "Session index"), and the Stop pass scans those roots after the walk-up root. New case `hook-stop-umbrella-cwd` on the new workspace `hook-umbrella` (a plain folder holding `site/` and `app/`, each with a `package.json`), recorded from a release build of the binary and reviewed by hand: an edit in each project from the umbrella cwd, then a Stop that reports both files in one grouped list with project-relative paths (`app/src/b.css`, `site/src/a.css`, short footer because the per-edit pass already showed the full one in `app`), then a silent second Stop. The index lives in the case's isolated HOME, so the golden snapshots only the two project caches, and no `.impeccable/` appears in the umbrella folder. No existing golden moved: without a recorded root the Stop pass is the walk up alone.diff --git a/tests/oracle/cases/hooks.mjs b/tests/oracle/cases/hooks.mjsindex 9acf2b2ed..df6a3263d 100644--- a/tests/oracle/cases/hooks.mjs+++ b/tests/oracle/cases/hooks.mjs@@ -1,8 +1,9 @@/*** `impeccable hook`, `hook-before-edit`, `hook-admin` corpus.* Workspace: hook-project (package.json, PRODUCT.md web, UI files with and- * without findings). Multi-step cases share one staged workspace so the- * session cache carries between steps.+ * without findings); hook-umbrella (a plain folder holding the projects+ * site/ and app/, for Stop from a cwd above them). Multi-step cases share+ * one staged workspace so the session cache carries between steps.*/import fs from 'node:fs';@@ -220,6 +221,22 @@ export default [],},+ // Umbrella session (#1101): the session cwd is a plain folder holding the+ // projects, so the per-edit pass keys each cache to the project root below+ // it. Stop finds them through the per-user session index (in the case's+ // isolated HOME), reports both projects, and writes nothing in the+ // umbrella folder. The second Stop is silent.+ {+ id: 'hook-stop-umbrella-cwd', verb: 'hook', workspace: 'hook-umbrella',+ files: ['.impeccable/**', 'site/.impeccable/**', 'app/.impeccable/**'],+ steps: [+ { stdin: claudeEdit('site/src/a.css', { session_id: 'u1' }) },+ { stdin: claudeEdit('app/src/b.css', { session_id: 'u1' }) },+ { stdin: stop({ session_id: 'u1' }) },+ { stdin: stop({ session_id: 'u1' }) },+ ],+ },+// --- hook-before-edit.mjs (Cursor) ---{ id: 'hbe-write-with-findings', verb: 'hook-before-edit', workspace: 'hook-project', stdin: { hook_event_name: 'preToolUse', conversation_id: 'cv1', workspace_roots: [WS], tool_name: 'Write', tool_input: { path: 'src/new.css', content: '.t { background: linear-gradient(90deg,#f00,#00f); -webkit-background-clip: text; color: transparent; }\n' } }, files: CACHE_FILES },{ id: 'hbe-write-clean', verb: 'hook-before-edit', workspace: 'hook-project', stdin: { hook_event_name: 'preToolUse', conversation_id: 'cv1', workspace_roots: [WS], tool_name: 'Write', tool_input: { path: 'src/new.css', content: '.t { color: #111; }\n' } }, files: CACHE_FILES },diff --git a/tests/oracle/golden/hook-stop-umbrella-cwd.json b/tests/oracle/golden/hook-stop-umbrella-cwd.jsonnew file mode 100644index 000000000..1a15487b3--- /dev/null+++ b/tests/oracle/golden/hook-stop-umbrella-cwd.json@@ -0,0 +1,32 @@+{+ "steps": [+ {+ "stdout": "{\"hookSpecificOutput\":{\"hookEventName\":\"PostToolUse\",\"additionalContext\":\"[impeccable@1] Design hook scanned src/a.css. No deterministic design-quality issues found. That does not mean the design is good: keep following the project design system and the impeccable skill guidance.\"}}",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "{\"hookSpecificOutput\":{\"hookEventName\":\"PostToolUse\",\"additionalContext\":\"[impeccable@1] Design hook findings requiring review in src/b.css (1 issue(s)):\\n- L1 [gradient-text] Gradient text. Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.\\n\\nTriage each finding, then state in your reply what you fixed, what you suppressed, and what you left standing:\\n- Real design problem: fix it. Keep intentional design as designed.\\n- Confident false positive or sanctioned exception (an intentional demo or fixture, documentation of bad design, literal or domain-appropriate motion, a choice the user confirmed): persist the narrowest ignore yourself and disclose it. Run `<HOOK_ADMIN_CMD> ignore-value <rule> \\\"<value>\\\" --reason \\\"<who decided: evidence>\\\"` with the pair shown on the finding line, or value \\\"*\\\" plus `--file <path>` when the line shows none. Write \\\"user confirmed\\\" in a reason only when the user did.\\n- Unsure: leave it as is and ask the user in one line.\\nSelf-serve ends at ignore-value: `ignore-file` and `ignore-rule` need the user's explicit approval, and never add an ignore to push a blocked write through. Full suppression ladder: /impeccable hooks.\"}}",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "{\"hookSpecificOutput\":{\"hookEventName\":\"Stop\",\"additionalContext\":\"[impeccable@1] Findings marked attribution unknown may predate this session; do not treat them as regressions or broaden the task without asking.\\n\\n[impeccable@1] Design hook findings requiring review across 2 files (2 issue(s)):\\napp/src/b.css (1 issue(s)):\\n- L2 [side-tab] [attribution unknown] Side-tab accent border. Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.\\nsite/src/a.css (1 issue(s)):\\n- L1 [side-tab] [attribution unknown] Side-tab accent border.\\n\\nTriage per the session policy: fix real problems; persist confident false-positive or sanctioned-exception ignores via `impeccable hooks ignore-value` and disclose them in your reply; unsure, ask in one line.\"}}",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "",+ "stderr": "",+ "exit": 0,+ "signal": null+ }+ ],+ "files": {+ "app/.impeccable/hook.cache.json": "{\"version\":1,\"sessions\":{\"u1\":{\"updatedAt\": <EPOCH>,\"files\":{\"<WS>/app/src/b.css\":{\"editCount\":1,\"findings\":[\"side-tab:2\",\"gradient-text:1\"]}},\"footerShown\":true}}}",+ "site/.impeccable/hook.cache.json": "{\"version\":1,\"sessions\":{\"u1\":{\"updatedAt\": <EPOCH>,\"files\":{\"<WS>/site/src/a.css\":{\"editCount\":1,\"findings\":[\"side-tab:1\"],\"cleanAcked\":true}}}}}"+ }+}diff --git a/tests/oracle/workspaces/hook-umbrella/app/package.json b/tests/oracle/workspaces/hook-umbrella/app/package.jsonnew file mode 100644index 000000000..8a42307b7--- /dev/null+++ b/tests/oracle/workspaces/hook-umbrella/app/package.json@@ -0,0 +1 @@+{ "name": "app" }diff --git a/tests/oracle/workspaces/hook-umbrella/app/src/b.css b/tests/oracle/workspaces/hook-umbrella/app/src/b.cssnew file mode 100644index 000000000..273fda525--- /dev/null+++ b/tests/oracle/workspaces/hook-umbrella/app/src/b.css@@ -0,0 +1,2 @@+.title { background: linear-gradient(90deg, #f472b6, #a78bfa); -webkit-background-clip: text; color: transparent; }+.card { border-left: 4px solid #6366f1; border-radius: 8px; }diff --git a/tests/oracle/workspaces/hook-umbrella/site/package.json b/tests/oracle/workspaces/hook-umbrella/site/package.jsonnew file mode 100644index 000000000..c85902e32--- /dev/null+++ b/tests/oracle/workspaces/hook-umbrella/site/package.json@@ -0,0 +1 @@+{ "name": "site" }diff --git a/tests/oracle/workspaces/hook-umbrella/site/src/a.css b/tests/oracle/workspaces/hook-umbrella/site/src/a.cssnew file mode 100644index 000000000..a427891db--- /dev/null+++ b/tests/oracle/workspaces/hook-umbrella/site/src/a.css@@ -0,0 +1 @@+.card { border-left: 4px solid #6366f1; border-radius: 8px; }