The design language that makes your AI harness better at design.
JavaScript
Fix: Stop deep pass finds the session cache from a subfolder (#1088) (#1090)
Abdul Wahab374a0e179bb3
diff --git a/crates/hook/src/hook.rs b/crates/hook/src/hook.rsindex 251831976..a0e702e79 100644--- a/crates/hook/src/hook.rs+++ b/crates/hook/src/hook.rs@@ -657,16 +657,19 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {}}}- let project_cwd = rt.resolve(&[str_field(&event, "cwd").unwrap_or(&rt.proc_cwd)]);- audit.insert("cwd".into(), Value::String(project_cwd.clone()));let session_value = session_id_of(&event);let session_id = session_key(&session_value);+ // 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).+ let session_cwd = rt.resolve(&[str_field(&event, "cwd").unwrap_or(&rt.proc_cwd)]);+ audit.insert("cwd".into(), Value::String(session_cwd.clone()));audit.insert("session".into(),session_value.unwrap_or_else(|| Value::from("unknown")),);- let config = read_config(&project_cwd);+ let config = read_config(&session_cwd);if !config.enabled {return result(&audit,@@ -680,10 +683,10 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {// included. Resolving the platform reads PRODUCT.md, so it is paid only// when there is a build state to remind about or touched files to scan.let mut platform_memo: Option<Option<String>> = None;- let native_skip = |platform_memo: &mut Option<Option<String>>| -> Option<RunResult> {- let platform = platform_memo.get_or_insert_with(|| resolve_project_platform(rt, &project_cwd)).clone();+ let native_skip = |audit: &Map<String, Value>, cwd: &str, platform_memo: &mut Option<Option<String>>| -> Option<RunResult> {+ let platform = platform_memo.get_or_insert_with(|| resolve_project_platform(rt, cwd)).clone();is_native_platform(platform.as_deref()).then(|| result(- &audit,+ audit,vec![("skipped", Value::from("native-platform")),("platform", Value::String(platform.unwrap_or_default())),@@ -691,12 +694,12 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {],))};- if std::path::Path::new(&project_cwd).join(".impeccable/build/state.json").is_file() {- if let Some(skip) = native_skip(&mut platform_memo) { return skip; }+ if std::path::Path::new(&session_cwd).join(".impeccable/build/state.json").is_file() {+ if let Some(skip) = native_skip(&audit, &session_cwd, &mut platform_memo) { return skip; }}- let mut cache = read_cache(&project_cwd);+ let mut cache = read_cache(&session_cwd);if matches!(harness, "claude" | "codex" | "gemini") {- if let Some(message) = crate::build_completion::reminder(rt, &project_cwd, &session_id, stop_hook_active, &mut cache) {+ if let Some(message) = crate::build_completion::reminder(rt, &session_cwd, &session_id, stop_hook_active, &mut cache) {return RunResult {stdout: payload(&message, "Stop", harness),audit: with(&audit, vec![("kind", Value::from("build-completion")), ("emitted", Value::Bool(true)), ("durationMs", ms_since(started))]),@@ -709,6 +712,28 @@ 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)),+ ],+ );+ }+ 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(@@ -719,7 +744,7 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {],);}- if let Some(skip) = native_skip(&mut platform_memo) { return skip; }+ 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();@@ -865,7 +890,15 @@ pub fn run_stop_hook(rt: &Runtime, stdin: &str) -> RunResult {append_design_system_note_once(rt, &text, scan, &mut 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 text = match crate::build_completion::finished_build_note(rt, &project_cwd, &session_id, &mut cache) {+ 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); }+ 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,};diff --git a/crates/hook/src/hook_lib.rs b/crates/hook/src/hook_lib.rsindex effbafa24..b4b58f3c3 100644--- a/crates/hook/src/hook_lib.rs+++ b/crates/hook/src/hook_lib.rs@@ -338,6 +338,26 @@ pub fn resolve_cache_cwd(rt: &Runtime, primary_file: Option<&str>, session_cwd:}}+/// The Stop event names no file, so the per-edit pass may have keyed this+/// session's cache to a project root above the session cwd (#1088). Use the+/// nearest directory, from the session cwd up to (not including) the home+/// dir, whose cache lists files this session touched; else the session cwd.+pub fn resolve_stop_cwd(rt: &Runtime, session_cwd: &str, session_id: &str) -> String {+ let mut dir = session_cwd.to_string();+ let home = rt.resolve(&[&rt.homedir()]);+ while dir != home {+ if !touched_files(&read_cache(&dir), session_id).is_empty() {+ return dir;+ }+ let parent = jsp::dirname(&dir);+ if parent == dir {+ break;+ }+ dir = parent;+ }+ session_cwd.to_string()+}+/// JS: resolveProjectPlatform(cwd) — `extractPlatform(loadContext(cwd).product)`./// Only the platform is observable, so this reads PRODUCT.md through the same/// resolution and skips loadContext's surface-brief and visual-implementationdiff --git a/crates/hook/tests/hook_tests.rs b/crates/hook/tests/hook_tests.rsindex b9eb762cb..f4ceb76b8 100644--- a/crates/hook/tests/hook_tests.rs+++ b/crates/hook/tests/hook_tests.rs@@ -181,7 +181,12 @@ fn unfinished_comp_stop_is_owned_bounded_and_does_not_reopen_on_unrelated_turn()/// A comp build this session recorded as shipped, the way `finish` leaves it.fn shipped_build(t: &Tmp) {- t.write("index.html", "<main>Shipped</main>");+ shipped_build_in(t, "");+}++/// `shipped_build` under `dir` (empty or ending in `/`), where `build-phase` ran.+fn shipped_build_in(t: &Tmp, dir: &str) {+ t.write(&format!("{dir}index.html"), "<main>Shipped</main>");let mut state = json!({"tool":"build-phase", "version":2, "startedAt":"build-one", "phase":"review","sessionId":"owner", "artifact":"index.html", "capturePolicy":"native-html-v1", "phases":{}@@ -189,10 +194,10 @@ fn shipped_build(t: &Tmp) {for phase in ["comps", "spec", "plates", "hero", "sections", "motion", "responsive", "review"] {state["phases"][phase] = json!({"status":"closed"});}- let hash = impeccable_comp_verbs::completion::artifact_hash(std::path::Path::new(&t.path()), &state).unwrap();+ let hash = impeccable_comp_verbs::completion::artifact_hash(&t.0.join(dir), &state).unwrap();state["finish"] = json!({"disposition":"ship", "phaseAtFinish":"review", "artifactSha256":hash,"captureInputs":[{"path":"index.html","sha256":hash}]});- t.write(".impeccable/build/state.json", &state.to_string());+ t.write(&format!("{dir}.impeccable/build/state.json"), &state.to_string());}#[test]@@ -2683,6 +2688,78 @@ fn stop_cache_syncs_after_clean_scan_so_reintroductions_fire() {assert!(again.stdout.contains("[side-tab]"), "{}", again.stdout);}+#[test]+fn stop_from_a_subfolder_finds_the_root_cache() {+ // #1088: the per-edit pass keys the cache to the project root; Stop from a+ // subfolder, even one with its own `.impeccable/`, must still find it.+ let t = Tmp::new();+ t.write("package.json", "{}");+ let cwd = t.path();+ let css = t.write("src/a.css", SIDE_TAB_CSS);+ let docs = jsp::join(&[&cwd, "docs"]);+ t.write("docs/readme.txt", "x");+ let app = jsp::join(&[&cwd, "app"]);+ t.write("app/.impeccable/live/roots.json", "{}");+ for (session, sub) in [("s1", &docs), ("s2", &app)] {+ hook::run_hook(&rt(&cwd), &edit_event(&cwd, &css, session));+ let res = hook::run_stop_hook(&rt(sub), &stop_event(sub, session));+ assert!(res.stdout.contains("[side-tab]"), "{session}: {}", res.stdout);+ assert_eq!(audit_str(&res.audit, "cwd"), Some(cwd.as_str()));+ }+}++#[test]+fn stop_from_a_subfolder_build_keeps_its_reminder_and_scans_the_root_cache() {+ // #1088: `build-phase` keeps its state under its own cwd, so the reminder+ // and its config stay there, while the scan still finds root edits.+ let t = Tmp::new();+ t.write("package.json", "{}");+ let cwd = t.path();+ let css = t.write("src/a.css", SIDE_TAB_CSS);+ t.write("app/index.html", "<main>In progress</main>");+ let build = |owner: &str| t.write("app/.impeccable/build/state.json", &json!({+ "tool":"build-phase", "version":2, "startedAt":"build-one",+ "sessionId":owner, "artifact":"index.html", "finish":null,+ "phases":{"hero":{"status":"open"}}+ }).to_string());+ let app = jsp::join(&[&cwd, "app"]);+ hook::run_hook(&rt(&cwd), &edit_event(&cwd, &css, "owner"));+ build("other");+ let res = hook::run_stop_hook(&rt(&app), &stop_event(&app, "owner"));+ assert!(res.stdout.contains("[side-tab]"), "{}", res.stdout);+ build("owner");+ let res = hook::run_stop_hook(&rt(&app), &stop_event(&app, "owner"));+ assert!(res.stdout.contains("Comp build"), "{}", res.stdout);+ t.write("app/.impeccable/config.json", r#"{"hook":{"enabled":false}}"#);+ let res = hook::run_stop_hook(&rt(&app), &stop_event(&app, "owner"));+ assert_eq!(audit_str(&res.audit, "skipped"), Some("config-disabled"));+ // The root's own config gates the scan of root edits.+ t.write("app/.impeccable/config.json", "{}");+ t.write("app/.impeccable/build/state.json", "{}");+ t.write(".impeccable/config.json", r#"{"hook":{"enabled":false}}"#);+ let res = hook::run_stop_hook(&rt(&app), &stop_event(&app, "owner"));+ assert_eq!(audit_str(&res.audit, "skipped"), Some("config-disabled"));+ assert_eq!(audit_str(&res.audit, "cwd"), Some(cwd.as_str()));+}++#[test]+fn stop_from_a_subfolder_shipped_build_marks_the_build_folder_cache() {+ // #1088: findings from a root edit over a build shipped in the subfolder+ // carry the finish note, and its marker lands where the reminder reads it.+ let t = Tmp::new();+ t.write("package.json", "{}");+ let cwd = t.path();+ shipped_build_in(&t, "app/");+ let css = t.write("src/a.css", SIDE_TAB_CSS);+ hook::run_hook(&rt(&cwd), &edit_event(&cwd, &css, "owner"));+ let app = jsp::join(&[&cwd, "app"]);+ let res = hook::run_stop_hook(&rt(&app), &stop_event(&app, "owner"));+ assert!(res.stdout.contains("[side-tab]"), "{}", res.stdout);+ assert!(res.stdout.contains("finish --disposition ship recorded"), "{}", res.stdout);+ assert!(t.read("app/.impeccable/hook.cache.json").contains("findingsAfterFinish"));+ assert!(!t.read(".impeccable/hook.cache.json").contains("findingsAfterFinish"));+}+#[test]fn codex_stop_emits_decision_block() {// #603: Codex Stop rejects Claude's hookSpecificOutput shape; findingsdiff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex 2baa64c35..ae35dc1a3 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -1238,7 +1238,7 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill l9. 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).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). `projectCwd = resolve(event.cwd || cwd)` (no file-based re-keying); `sessionId = event.session_id || 'unknown'`; 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 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}`.- **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.@@ -1254,7 +1254,7 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill loptionally 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}`.- **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 uses the session cwd (so those sessions 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 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.- **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.---