Skip to content

The design language that makes your AI harness better at design.

JavaScript

Run Cursor's design hook after the edit on postToolUse (#1069)

Paul Bakausbeadc35467ca
diff --git a/Cargo.lock b/Cargo.lock
index 1665e34ca..33cfb61e5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -680,6 +680,7 @@ dependencies = [
"impeccable-context",
"impeccable-core",
"impeccable-detect",
+ "libc",
"once_cell",
"regex",
"serde_json",
diff --git a/README.md b/README.md
index 84a2701e7..82f740643 100644
--- a/README.md
+++ b/README.md
@@ -411,13 +411,13 @@ To turn it off, run `npx impeccable telemetry off` (stored in `~/.impeccable/con
## Design hook
-On Claude Code, GitHub Copilot, Codex, Cursor, and Grok Build, `npx impeccable install` and `npx impeccable update` install a provider-native hook manifest along with the skill payload. The hook runs the Impeccable design detector on direct UI file edits and surfaces findings back into the agent flow. Claude Code, GitHub Copilot, and Codex surface findings after the edit (and run a deeper pass on Stop where supported). Grok Build scans after the edit to warm Stop, then surfaces on Stop; PostToolUse stdout never reaches the model. Cursor blocks bad proposed writes before they land.
+On Claude Code, GitHub Copilot, Codex, Cursor, and Grok Build, `npx impeccable install` and `npx impeccable update` install a provider-native hook manifest along with the skill payload. The hook runs the Impeccable design detector on direct UI file edits and surfaces findings back into the agent flow. Claude Code, GitHub Copilot, Codex, and Cursor surface findings after the edit (and run a deeper pass on Stop where supported). Grok Build scans after the edit to warm Stop, then surfaces on Stop; PostToolUse stdout never reaches the model.
Installed hook surfaces:
- Claude Code: `.claude/settings.local.json` (gitignored, machine-local) runs `${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable hook`. A hook moved into the shared `settings.json` is honored in place.
- GitHub Copilot: `.github/hooks/impeccable.json` (committed, shared by the Copilot CLI and the cloud agent) runs `.github/skills/impeccable/scripts/impeccable hook`. The Copilot CLI activates it once the file is on the repository's default branch and the folder is trusted.
-- Cursor: `.cursor/hooks.json` runs `.cursor/skills/impeccable/scripts/impeccable hook-before-edit`.
+- Cursor: `.cursor/hooks.json` runs `.cursor/skills/impeccable/scripts/impeccable hook` on `postToolUse` for file writes. Projects set up with the older `preToolUse` write gate keep working; `npx impeccable update` moves them to the post-edit hook.
- Codex: `.codex/hooks.json` runs `.agents/skills/impeccable/scripts/impeccable hook`, with a `commandWindows` sibling that calls `impeccable.cmd` for cmd.exe.
- Grok Build: `.grok/hooks/impeccable.json` runs `.grok/skills/impeccable/scripts/impeccable hook`. Requires `/hooks-trust` or `--trust`. Findings reach the model on Stop, not after each edit.
diff --git a/crates/context/src/context_cli.rs b/crates/context/src/context_cli.rs
index e218762a1..f886797d0 100644
--- a/crates/context/src/context_cli.rs
+++ b/crates/context/src/context_cli.rs
@@ -1220,4 +1220,34 @@ mod worktree_hook_tests {
let _ = std::fs::remove_dir_all(&base);
}
+
+ #[test]
+ fn cursor_post_edit_and_unmigrated_gate_both_count_as_per_edit_coverage() {
+ let base = std::env::temp_dir().join(format!("impeccable-cursor-hook-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ let tmp = base.to_string_lossy().into_owned();
+ let project = jsp::join(&[&tmp, "proj"]);
+ std::fs::create_dir_all(jsp::join(&[&project, ".git"])).unwrap();
+ let manifest = jsp::join(&[&project, ".cursor", "hooks.json"]);
+ std::fs::create_dir_all(jsp::dirname(&manifest)).unwrap();
+ let env = Env::from([
+ ("HOME".to_string(), tmp.clone()),
+ ("USERPROFILE".to_string(), tmp.clone()),
+ ("IMPECCABLE_PROVIDER_ID".to_string(), "cursor".to_string()),
+ ]);
+ let provider = crate::provider::detect(&env, &project);
+ assert_eq!(provider.id, "cursor");
+ let mode = || {
+ let ctx = load_context(&project, &TargetOptions::default(), &env);
+ automatic_hook_mode(&ctx, &project, &env, &provider)
+ };
+ assert_eq!(mode(), "none");
+ // Post-edit only: Cursor has no Stop deep pass wired (#1061).
+ std::fs::write(&manifest, r#"{"version":1,"hooks":{"postToolUse":[{"command":"\".cursor/skills/impeccable/scripts/impeccable\" hook","matcher":"^Write$","timeout":5}]}}"#).unwrap();
+ assert_eq!(mode(), "per-edit");
+ // The retired gate still runs until the manifest is migrated.
+ std::fs::write(&manifest, r#"{"version":1,"hooks":{"preToolUse":[{"command":"\".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit","timeout":5}]}}"#).unwrap();
+ assert_eq!(mode(), "per-edit");
+ let _ = std::fs::remove_dir_all(&base);
+ }
}
diff --git a/crates/context/src/doctor.rs b/crates/context/src/doctor.rs
index f916be045..f45a5a40f 100644
--- a/crates/context/src/doctor.rs
+++ b/crates/context/src/doctor.rs
@@ -152,6 +152,26 @@ fn apply_fixes(report: &Report) -> Fixes {
applied.push(format!("Moved {} to {}.", rel(present, &report.project_root), rel(canonical, &report.project_root)));
continue;
}
+ if entry.id == "cursor-hook-pre-edit-gate" {
+ let Some(path) = entry.path.as_deref() else { continue };
+ let abs = if jsp::is_absolute(path) { path.to_string() } else { jsp::join(&[&report.project_root, path]) };
+ let migrated = std::fs::read_to_string(&abs)
+ .ok()
+ .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
+ .and_then(|v| crate::hook_markers::migrate_cursor_gate_in_place(&v));
+ match migrated {
+ Some(next) => {
+ let body = format!("{}\n", json_pretty(&next));
+ if std::fs::write(&abs, body).is_ok() {
+ applied.push(format!("Moved the design hook in {} from preToolUse to postToolUse.", rel(&abs, &report.project_root)));
+ } else {
+ skipped.push((entry.id.clone(), format!("could not write {}", rel(&abs, &report.project_root))));
+ }
+ }
+ None => skipped.push((entry.id.clone(), "the gate entry is not in the launcher form; run `impeccable hooks on`".to_string())),
+ }
+ continue;
+ }
if entry.id == "legacy-live-state" {
skipped.push((entry.id.clone(), "delete by hand once no live session is running".to_string()));
continue;
diff --git a/crates/context/src/hook_markers.rs b/crates/context/src/hook_markers.rs
index 48a1844bc..ec9e5233c 100644
--- a/crates/context/src/hook_markers.rs
+++ b/crates/context/src/hook_markers.rs
@@ -5,7 +5,8 @@
//! `hook-before-edit` / `hook-probe` / `hook-after-edit` / `hook-stop`
//! siblings), and
//! * the binary era, `"<...>/skills/impeccable/scripts/impeccable" hook`
-//! (`impeccable.cmd` on Windows, `hook-before-edit` for Cursor).
+//! (`impeccable.cmd` on Windows; Cursor manifests written before the
+//! post-edit hook ran `hook-before-edit` on `preToolUse`).
//!
//! `impeccable hooks on` repairs the old form to the new one, so pruning and
//! merging must recognize both; `doctor` and `context`'s automatic-hook scan
@@ -149,6 +150,117 @@ pub fn hook_program_token(command: &str) -> Option<String> {
BARE.captures(&command).map(|m| m[1].to_string())
}
+/// Cursor's design hook runs after the edit lands, like every other harness:
+/// `postToolUse` filtered to Cursor's file-write tool. Cursor tests `matcher`
+/// as an unanchored regex against `tool_name`, and every agent file edit
+/// (whole-file write or search-replace) reports `tool_name: "Write"` with
+/// `tool_input: { file_path, content }`; the anchors keep `WriteShellStdin`
+/// out. `postToolUse` is the event whose response feeds `additional_context`
+/// back to the agent; `afterFileEdit` has no response the agent sees.
+pub const CURSOR_HOOK_EVENT: &str = "postToolUse";
+pub const CURSOR_HOOK_MATCHER: &str = "^Write$";
+/// The event the retired before-edit gate (`hook-before-edit`) ran on.
+pub const CURSOR_RETIRED_HOOK_EVENT: &str = "preToolUse";
+
+/// The Impeccable part of a Cursor `.cursor/hooks.json`, for a given hook
+/// command. `hooks on` and install/update both build the manifest here so
+/// the two writers cannot drift (`transformers/hooks.js`
+/// `buildCursorHooksManifest` is the build's twin).
+pub fn cursor_hook_manifest(command: &str, timeout_seconds: i64) -> serde_json::Value {
+ let mut hooks = serde_json::Map::new();
+ hooks.insert(
+ CURSOR_HOOK_EVENT.to_string(),
+ serde_json::json!([{
+ "command": command,
+ "matcher": CURSOR_HOOK_MATCHER,
+ "timeout": timeout_seconds,
+ }]),
+ );
+ serde_json::json!({ "version": 1, "hooks": hooks })
+}
+
+/// True when a Cursor manifest still runs an Impeccable hook on
+/// `preToolUse`: the before-edit write gate, retired in favor of the
+/// post-edit hook. The gate verb keeps working, so this is a migration, not
+/// a broken hook.
+pub fn cursor_manifest_has_retired_gate(manifest: &serde_json::Value) -> bool {
+ fn any_marker(v: &serde_json::Value) -> bool {
+ match v {
+ serde_json::Value::String(s) => is_impeccable_hook_command(s),
+ serde_json::Value::Array(a) => a.iter().any(any_marker),
+ serde_json::Value::Object(o) => o.values().any(any_marker),
+ _ => false,
+ }
+ }
+ manifest
+ .get("hooks")
+ .and_then(|h| h.get(CURSOR_RETIRED_HOOK_EVENT))
+ .is_some_and(any_marker)
+}
+
+/// Moves a Cursor manifest's launcher-form `preToolUse` gate entry to the
+/// post-edit hook in place: the same launcher command with `hook-before-edit`
+/// swapped for `hook`, under `postToolUse` with the `^Write$` matcher. Other
+/// tools' entries are kept, an emptied `preToolUse` is dropped, and an
+/// existing Impeccable `postToolUse` entry is not duplicated. `None` when
+/// there is no gate, or when a gate entry is in the JS-era `.mjs` spelling
+/// (its script is gone; `impeccable hooks on` rewrites those). `doctor --fix`
+/// uses this; install/update and `hooks on` rebuild the manifest instead.
+pub fn migrate_cursor_gate_in_place(manifest: &serde_json::Value) -> Option<serde_json::Value> {
+ use serde_json::Value;
+ static GATE_VERB: Lazy<Regex> = Lazy::new(|| {
+ Regex::new(r#"(skills[/\\]+impeccable[/\\]+scripts[/\\]+impeccable(?:\.cmd|\.exe)?["']?\s+)hook-before-edit"#).unwrap()
+ });
+ if !cursor_manifest_has_retired_gate(manifest) {
+ return None;
+ }
+ let mut root = manifest.as_object()?.clone();
+ let mut hooks = root.get("hooks")?.as_object()?.clone();
+ let pre = hooks.get(CURSOR_RETIRED_HOOK_EVENT)?.as_array()?.clone();
+ let mut kept = Vec::new();
+ let mut moved: Option<(String, Value)> = None;
+ for entry in pre {
+ let command = entry.get("command").and_then(Value::as_str);
+ match command {
+ Some(c) if is_impeccable_hook_command(c) => {
+ if !is_launcher_hook_command(c) {
+ return None;
+ }
+ if moved.is_none() {
+ let timeout = entry.get("timeout").cloned().unwrap_or(Value::from(5));
+ moved = Some((GATE_VERB.replace(c, "${1}hook").into_owned(), timeout));
+ }
+ }
+ _ => kept.push(entry),
+ }
+ }
+ // A gate nested somewhere other than a top-level `command` is not a
+ // shape any Impeccable writer produced; leave it to `hooks on`.
+ let (command, timeout) = moved?;
+ if kept.is_empty() {
+ hooks.remove(CURSOR_RETIRED_HOOK_EVENT);
+ } else {
+ hooks.insert(CURSOR_RETIRED_HOOK_EVENT.to_string(), Value::Array(kept));
+ }
+ let mut post = match hooks.get(CURSOR_HOOK_EVENT) {
+ Some(Value::Array(a)) => a.clone(),
+ _ => Vec::new(),
+ };
+ let has_post = post.iter().any(|e| {
+ e.get("command").and_then(Value::as_str).is_some_and(is_impeccable_hook_command)
+ });
+ if !has_post {
+ post.push(serde_json::json!({
+ "command": command,
+ "matcher": CURSOR_HOOK_MATCHER,
+ "timeout": timeout,
+ }));
+ }
+ hooks.insert(CURSOR_HOOK_EVENT.to_string(), Value::Array(post));
+ root.insert("hooks".to_string(), Value::Object(hooks));
+ Some(Value::Object(root))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -240,6 +352,40 @@ mod tests {
assert_eq!(hook_program_token("echo hi"), None);
}
+ #[test]
+ fn migrates_the_cursor_gate_in_place() {
+ let gate = serde_json::json!({"version": 1, "hooks": {
+ "preToolUse": [
+ {"command": "./audit.sh", "matcher": "Shell"},
+ {"command": "[ ! -f '/x/.cursor/skills/impeccable/scripts/impeccable' ] || '/x/.cursor/skills/impeccable/scripts/impeccable' hook-before-edit", "timeout": 7},
+ ],
+ }});
+ assert!(cursor_manifest_has_retired_gate(&gate));
+ let next = migrate_cursor_gate_in_place(&gate).unwrap();
+ assert_eq!(next, serde_json::json!({"version": 1, "hooks": {
+ "preToolUse": [{"command": "./audit.sh", "matcher": "Shell"}],
+ "postToolUse": [{
+ "command": "[ ! -f '/x/.cursor/skills/impeccable/scripts/impeccable' ] || '/x/.cursor/skills/impeccable/scripts/impeccable' hook",
+ "matcher": "^Write$",
+ "timeout": 7,
+ }],
+ }}));
+ assert!(!cursor_manifest_has_retired_gate(&next));
+ assert_eq!(migrate_cursor_gate_in_place(&next), None);
+ // The JS-era spelling has no launcher to keep; `hooks on` rewrites it.
+ let mjs = serde_json::json!({"hooks": {"preToolUse": [{"command": "node \".cursor/skills/impeccable/scripts/hook-before-edit.mjs\""}]}});
+ assert!(cursor_manifest_has_retired_gate(&mjs));
+ assert_eq!(migrate_cursor_gate_in_place(&mjs), None);
+ // An existing post-edit entry is not duplicated.
+ let both = serde_json::json!({"hooks": {
+ "preToolUse": [{"command": "\".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit"}],
+ "postToolUse": [{"command": "\".cursor/skills/impeccable/scripts/impeccable\" hook", "matcher": "^Write$"}],
+ }});
+ let next = migrate_cursor_gate_in_place(&both).unwrap();
+ assert_eq!(next["hooks"].as_object().unwrap().len(), 1);
+ assert_eq!(next["hooks"]["postToolUse"].as_array().unwrap().len(), 1);
+ }
+
#[test]
fn recognizes_json_escaped_windows_launcher_path() {
let launcher = r"C:\Users\alice\.claude\skills\impeccable\scripts\impeccable";
diff --git a/crates/context/src/staleness_deep.rs b/crates/context/src/staleness_deep.rs
index b56218757..35b2f0cd4 100644
--- a/crates/context/src/staleness_deep.rs
+++ b/crates/context/src/staleness_deep.rs
@@ -282,6 +282,20 @@ pub fn check_hook_installation(
!exists(&abs)
})
.collect();
+ if provider_id == "cursor" && crate::hook_markers::cursor_manifest_has_retired_gate(&raw) {
+ let ia = installed_at.clone().unwrap();
+ out.push(finding(
+ "cursor-hook-pre-edit-gate",
+ "hook manifest",
+ Some(ia.clone()),
+ "auto",
+ format!(
+ "{} still runs the design hook as Cursor's `preToolUse` write gate, which is retired. Cursor now runs it after each edit on `postToolUse` and hands the findings to the agent as context.",
+ ia
+ ),
+ "Move the entry to `postToolUse`: `impeccable doctor --fix`, `impeccable hooks on`, or the next `impeccable update` does it.".to_string(),
+ ));
+ }
if !broken.is_empty() {
let ia = installed_at.clone().unwrap();
out.push(finding(
@@ -517,6 +531,20 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ #[test]
+ fn cursor_gate_is_an_auto_finding_and_the_post_edit_hook_is_not() {
+ let root = tmp();
+ write(&root, ".cursor/skills/impeccable/scripts/impeccable", "#!/bin/sh\n");
+ write(&root, ".cursor/hooks.json", r#"{"version":1,"hooks":{"preToolUse":[{"command":"\".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit","timeout":5}]}}"#);
+ let f = check_hook_installation(&root, None, "cursor", None);
+ assert_eq!(f.len(), 1, "{:?}", f.iter().map(|x| &x.id).collect::<Vec<_>>());
+ assert_eq!(f[0].id, "cursor-hook-pre-edit-gate");
+ assert_eq!(f[0].severity, "auto");
+ write(&root, ".cursor/hooks.json", r#"{"version":1,"hooks":{"postToolUse":[{"command":"\".cursor/skills/impeccable/scripts/impeccable\" hook","matcher":"^Write$","timeout":5}]}}"#);
+ assert!(check_hook_installation(&root, None, "cursor", None).is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn user_scope_claude_hook_is_checked_from_home() {
let root = tmp();
diff --git a/crates/hook/Cargo.toml b/crates/hook/Cargo.toml
index 3f46887cd..e86b831f5 100644
--- a/crates/hook/Cargo.toml
+++ b/crates/hook/Cargo.toml
@@ -15,3 +15,6 @@ serde_json = { workspace = true }
regex = { workspace = true }
once_cell = { workspace = true }
sha2 = "0.10"
+
+[target.'cfg(unix)'.dependencies]
+libc = "0.2"
diff --git a/crates/hook/src/admin.rs b/crates/hook/src/admin.rs
index fc6fa6f8e..0b0a6a958 100644
--- a/crates/hook/src/admin.rs
+++ b/crates/hook/src/admin.rs
@@ -96,7 +96,7 @@ fn stop_manifest_entry_with_windows(command: &str, windows: &str) -> Value {
/// resolves on every teammate's checkout.
const CLAUDE_HOOK_COMMAND: &str = "\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook";
const AGENTS_HOOK_COMMAND: &str = "\".agents/skills/impeccable/scripts/impeccable\" hook";
-const CURSOR_HOOK_COMMAND: &str = "\".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit";
+const CURSOR_HOOK_COMMAND: &str = "\".cursor/skills/impeccable/scripts/impeccable\" hook";
const GITHUB_HOOK_COMMAND: &str = "\"$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/impeccable\" hook";
struct ManifestTarget {
@@ -172,23 +172,12 @@ fn agents_manifest() -> Value {
)])
}
+/// Cursor runs the post-edit design hook like the other harnesses (the
+/// before-edit gate is retired). `merge_hook_manifests` strips Impeccable
+/// entries from every event, so `on` also drops a leftover `preToolUse`
+/// gate entry while writing this one.
fn cursor_manifest() -> Value {
- obj(vec![
- ("version", Value::from(1)),
- (
- "hooks",
- obj(vec![(
- "preToolUse",
- Value::Array(vec![obj(vec![
- (
- "command",
- Value::from(CURSOR_HOOK_COMMAND),
- ),
- ("timeout", Value::from(TIMEOUT_SECONDS)),
- ])]),
- )]),
- ),
- ])
+ impeccable_context::hook_markers::cursor_hook_manifest(CURSOR_HOOK_COMMAND, TIMEOUT_SECONDS)
}
fn github_manifest() -> Value {
diff --git a/crates/hook/src/before_edit.rs b/crates/hook/src/before_edit.rs
index efcb73aae..1bca1c25b 100644
--- a/crates/hook/src/before_edit.rs
+++ b/crates/hook/src/before_edit.rs
@@ -1,6 +1,11 @@
//! JS: skill/scripts/hook-before-edit.mjs (`impeccable hook-before-edit`),
//! the Cursor preToolUse write gate. Always exits 0 and prints exactly one
//! JSON document: `{"permission":"allow"...}` or the deny payload.
+//!
+//! Retired as the Cursor design hook: new manifests run the post-edit `hook`
+//! verb on `postToolUse`, and install/update, `hooks on`, and `doctor --fix`
+//! migrate a `preToolUse` gate entry. The verb keeps working unchanged so a
+//! project that has not migrated yet still gets checked.
use impeccable_core::findings::Finding;
use impeccable_core::js;
diff --git a/crates/hook/src/hook.rs b/crates/hook/src/hook.rs
index bb8acd8be..a7dbeddb0 100644
--- a/crates/hook/src/hook.rs
+++ b/crates/hook/src/hook.rs
@@ -57,6 +57,9 @@ fn session_id_of(event: &Map<String, Value>) -> Option<Value> {
.cloned()
}
+/// Cursor's cap on a hook's `additional_context` (characters, after trim).
+const CURSOR_ADDITIONAL_CONTEXT_MAX_CHARS: f64 = 10_000.0;
+
fn session_key(v: &Option<Value>) -> String {
match v {
Some(v) => crate::util::js_string(v),
@@ -113,6 +116,7 @@ pub fn run_hook(rt: &Runtime, stdin: &str) -> RunResult {
};
let harness = resolve_harness(rt, Some(&event));
+ let raw_event = event.clone();
let event = normalize_hook_event(rt, &event, &rt.proc_cwd, harness);
audit.insert("harness".into(), Value::from(harness));
@@ -145,7 +149,13 @@ pub fn run_hook(rt: &Runtime, stdin: &str) -> RunResult {
);
}
- let config = read_config(&project_cwd);
+ let mut config = read_config(&project_cwd);
+ if harness == "cursor" {
+ // Cursor rejects a postToolUse `additional_context` longer than
+ // 10,000 characters and drops it, so a raised `limits.maxChars`
+ // must not push the findings past that.
+ config.limits.max_chars = config.limits.max_chars.min(CURSOR_ADDITIONAL_CONTEXT_MAX_CHARS);
+ }
if !config.enabled {
return result(
&audit,
@@ -168,6 +178,18 @@ pub fn run_hook(rt: &Runtime, stdin: &str) -> RunResult {
);
}
+ // Several Impeccable hooks can fire for one edit (home and project
+ // manifests, a plugin and a project hook): only the first scans.
+ if crate::hook_claim::claim_event(rt, &raw_event, &project_cwd, &primary_files) == crate::hook_claim::Claim::Duplicate {
+ return result(
+ &audit,
+ vec![
+ ("skipped", Value::from("duplicate-event")),
+ ("durationMs", ms_since(started)),
+ ],
+ );
+ }
+
let mut cache = read_cache(&project_cwd);
let session_id = session_key(&session_value);
let mut scans = HashMap::new();
diff --git a/crates/hook/src/hook_claim.rs b/crates/hook/src/hook_claim.rs
new file mode 100644
index 000000000..69c9e20ef
--- /dev/null
+++ b/crates/hook/src/hook_claim.rs
@@ -0,0 +1,245 @@
+//! One scan per edit event, however many Impeccable hooks fire for it.
+//!
+//! A harness runs every hook entry it loads, so the same edit can reach the
+//! `hook` verb more than once: a home manifest and a project manifest
+//! (`~/.cursor/hooks.json` next to `.cursor/hooks.json`, the same for Codex),
+//! a plugin's hooks next to a project hook, or a sub-project's hook next to
+//! its parent's. Each copy would scan the file and hand the agent the same
+//! findings again.
+//!
+//! The harnesses that serve the per-edit hook name each tool call: Claude
+//! Code, Codex and Cursor put a `tool_use_id` on every post-tool event, and
+//! every hook of that event receives the same one. The first invocation
+//! atomically creates a claim file named by the hash of that identity; a
+//! later invocation that finds the claim exits without scanning. An event
+//! without a tool-call id is never claimed, so a harness that does not name
+//! its calls keeps today's behavior rather than risk dropping a real second
+//! edit.
+//!
+//! Claims live in a per-user directory, `~/.impeccable/hook-claims`, never in
+//! the shared temp dir. Before anything is created there or removed from it,
+//! the root and each bucket must be a real directory (not a symlink) that,
+//! on Unix, the current user owns with no group or other write bit. The sweep
+//! of old buckets is not recursive: it removes only `<digits>/` dirs, and in
+//! them only `<64 hex>` regular files, then the dir itself if that left it
+//! empty. Symlinks are never followed.
+//!
+//! Cost: one hash, a few `lstat`s, one `create_dir` and one `create_new` per
+//! edit, plus a `read_dir` of the claim root (a handful of bucket dirs) when
+//! a new ten-minute bucket starts. No directory walk.
+//!
+//! Every failure fails open: if the claim cannot be made or checked, or a
+//! directory is not safe, the scan runs and nothing is deleted.
+
+use serde_json::{Map, Value};
+use sha2::{Digest, Sha256};
+use std::path::{Path, PathBuf};
+
+use crate::hook_lib::Runtime;
+
+/// Width of one claim bucket. Duplicate invocations of one event arrive within
+/// the hook timeout (seconds), so a claim is checked in its own bucket and the
+/// one before it, and buckets older than that are removed.
+const BUCKET_SECONDS: u64 = 600;
+
+/// The payload keys that carry a tool-call id, in the spellings the served
+/// harnesses use.
+const TOOL_CALL_ID_KEYS: &[&str] = &["tool_use_id", "toolUseId", "tool_call_id", "toolCallId"];
+
+/// The session the call belongs to: Claude Code and Codex send `session_id`,
+/// Cursor `conversation_id` (and `session_id`).
+const SESSION_KEYS: &[&str] = &["session_id", "sessionId", "conversation_id"];
+
+/// What happened to the claim for this invocation.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Claim {
+ /// This invocation owns the event, or the event has no identity, or the
+ /// claim failed: scan.
+ Scan,
+ /// Another invocation already claimed this event: skip the scan.
+ Duplicate,
+}
+
+fn non_empty_str<'a>(event: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a str> {
+ keys.iter().find_map(|k| event.get(*k).and_then(Value::as_str).filter(|s| !s.is_empty()))
+}
+
+/// The claim key for an event, or `None` when the payload names no tool call.
+/// The project root and the scan targets are part of it, so two projects (or
+/// two test fixtures) that happen to reuse an id never collide.
+pub fn event_key(event: &Map<String, Value>, project_cwd: &str, files: &[String]) -> Option<String> {
+ let call = non_empty_str(event, TOOL_CALL_ID_KEYS)?;
+ let session = non_empty_str(event, SESSION_KEYS).unwrap_or("");
+ let mut files: Vec<&str> = files.iter().map(String::as_str).collect();
+ files.sort_unstable();
+ let mut h = Sha256::new();
+ for part in [session, call, project_cwd] {
+ h.update(part.as_bytes());
+ h.update([0u8]);
+ }
+ for f in files {
+ h.update(f.as_bytes());
+ h.update([0u8]);
+ }
+ Some(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
+}
+
+/// `IMPECCABLE_HOOK_CLAIM_DIR`, else `<home>/.impeccable/hook-claims`, with
+/// 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()) {
+ 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"))
+}
+
+fn now_bucket() -> Option<u64> {
+ let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
+ Some(secs / BUCKET_SECONDS)
+}
+
+/// The current effective user, for the ownership check.
+#[cfg(unix)]
+fn current_uid() -> u32 {
+ // SAFETY: geteuid has no preconditions and cannot fail.
+ unsafe { libc::geteuid() }
+}
+
+/// 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 {
+ if !meta.file_type().is_dir() {
+ return false;
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ if meta.uid() != current_uid() || meta.mode() & 0o022 != 0 {
+ return false;
+ }
+ }
+ true
+}
+
+/// Creates one directory level, private to the user on Unix. Not recursive.
+fn create_private_dir(path: &Path) -> std::io::Result<()> {
+ let mut b = std::fs::DirBuilder::new();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ b.mode(0o700);
+ }
+ b.create(path)
+}
+
+/// `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> {
+ let created = match create_private_dir(path) {
+ Ok(()) => true,
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => false,
+ Err(_) => return None,
+ };
+ let meta = std::fs::symlink_metadata(path).ok()?;
+ is_safe_dir(&meta).then_some(created)
+}
+
+/// 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)?;
+ 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
+ // is fine, any other failure is not.
+ match create_private_dir(parent) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(_) => return None,
+ }
+ }
+ }
+ ensure_safe_dir(&root)?;
+ Some(root)
+}
+
+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 {
+ name.len() == 64 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
+}
+
+/// Removes buckets older than the previous one. Runs only when this
+/// invocation created the current bucket, so it is paid once per bucket.
+/// Only safe `<digits>` dirs are touched, and in them only `<64 hex>` regular
+/// files; a bucket holding anything else is left in place.
+fn sweep_old_buckets(root: &Path, bucket: u64) {
+ let Ok(entries) = std::fs::read_dir(root) else { return };
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ let Some(name) = name.to_str().filter(|n| is_bucket_name(n)) else { continue };
+ let Ok(n) = name.parse::<u64>() else { continue };
+ if n + 1 >= bucket {
+ continue;
+ }
+ let dir = entry.path();
+ let Ok(meta) = std::fs::symlink_metadata(&dir) else { continue };
+ if !is_safe_dir(&meta) {
+ continue;
+ }
+ let Ok(claims) = std::fs::read_dir(&dir) else { continue };
+ for claim in claims.flatten() {
+ let ok_name = claim.file_name().to_str().is_some_and(is_claim_name);
+ let is_file = claim.file_type().is_ok_and(|t| t.is_file());
+ if ok_name && is_file {
+ let _ = std::fs::remove_file(claim.path());
+ }
+ }
+ let _ = std::fs::remove_dir(&dir);
+ }
+}
+
+/// True when `dir/key` exists as a claim file in a safe bucket.
+fn holds_claim(dir: &Path, key: &str) -> bool {
+ let Ok(meta) = std::fs::symlink_metadata(dir) else { return false };
+ is_safe_dir(&meta) && std::fs::symlink_metadata(dir.join(key)).is_ok_and(|m| m.file_type().is_file())
+}
+
+/// Claims `key` for this invocation. `Duplicate` only when another
+/// invocation provably holds it; every error, and every unsafe directory, is
+/// `Scan`.
+pub fn claim_key(rt: &Runtime, key: &str) -> Claim {
+ if !is_claim_name(key) {
+ return Claim::Scan;
+ }
+ let Some(bucket) = now_bucket() else { return Claim::Scan };
+ let Some(root) = safe_root(rt) else { return Claim::Scan };
+ if bucket > 0 && holds_claim(&root.join((bucket - 1).to_string()), key) {
+ return Claim::Duplicate;
+ }
+ let dir = root.join(bucket.to_string());
+ let Some(created) = ensure_safe_dir(&dir) else { return Claim::Scan };
+ if created {
+ sweep_old_buckets(&root, bucket);
+ }
+ // `create_new` is O_CREAT|O_EXCL: it never follows a symlink at the path.
+ match std::fs::OpenOptions::new().write(true).create_new(true).open(dir.join(key)) {
+ Ok(_) => Claim::Scan,
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Claim::Duplicate,
+ Err(_) => Claim::Scan,
+ }
+}
+
+/// Claims the event this invocation is about to scan.
+pub fn claim_event(rt: &Runtime, event: &Map<String, Value>, project_cwd: &str, files: &[String]) -> Claim {
+ match event_key(event, project_cwd, files) {
+ Some(key) => claim_key(rt, &key),
+ None => Claim::Scan,
+ }
+}
diff --git a/crates/hook/src/hook_lib.rs b/crates/hook/src/hook_lib.rs
index 811e9eec2..9ca3c7331 100644
--- a/crates/hook/src/hook_lib.rs
+++ b/crates/hook/src/hook_lib.rs
@@ -959,7 +959,9 @@ pub fn split_findings_by_tier(findings: Vec<Finding>) -> (Vec<Finding>, Vec<Find
/// JS: perEditTieringActive(config, harness) — Claude Code, Codex, and
/// Grok Build dispatch our Stop hook; Cursor and GitHub Copilot have no
/// deep pass wired, so deferring for them would silently drop the
-/// non-immediate rules entirely.
+/// non-immediate rules entirely. Cursor's `stop` hook can only answer with a
+/// `followup_message` that Cursor submits as a new user turn, which is not
+/// wired (#1061), so its post-edit hook keeps the full rule set.
pub fn per_edit_tiering_active(config: &HookConfig, harness: &str) -> bool {
if harness == "cursor" || harness == "github" {
return false;
diff --git a/crates/hook/src/lib.rs b/crates/hook/src/lib.rs
index 6a139933e..e926c11a0 100644
--- a/crates/hook/src/lib.rs
+++ b/crates/hook/src/lib.rs
@@ -13,6 +13,7 @@
pub mod admin;
pub mod before_edit;
pub mod hook;
+pub mod hook_claim;
pub mod hook_lib;
mod build_completion;
mod stop_baseline;
@@ -42,7 +43,8 @@ pub fn run_hook(_args: &[String], io: &mut Io, html: &dyn HtmlEngine) -> i32 {
hook::run(&rt, &stdin, io)
}
-/// `impeccable hook-before-edit` (Cursor preToolUse gate). Exit 0.
+/// `impeccable hook-before-edit` (the retired Cursor preToolUse gate, kept
+/// for manifests not yet migrated to the post-edit hook). Exit 0.
pub fn run_hook_before_edit(_args: &[String], io: &mut Io, html: &dyn HtmlEngine) -> i32 {
let stdin = io.stdin().to_string();
let rt = runtime(io, html);
diff --git a/crates/hook/tests/hook_tests.rs b/crates/hook/tests/hook_tests.rs
index af8a2053d..da6c22fe6 100644
--- a/crates/hook/tests/hook_tests.rs
+++ b/crates/hook/tests/hook_tests.rs
@@ -462,6 +462,61 @@ fn check_monorepo_design_hook(mode: &str) {
}
}
+/// A Cursor `postToolUse` envelope as Cursor 3.21 builds it for an agent
+/// file edit (cursor-agent-exec: base request + `tool_name`, `tool_input`,
+/// `tool_output`, `duration`, `tool_use_id`).
+fn cursor_post_tool_use(cwd: &str, file: &str, content: &str) -> String {
+ json!({
+ "conversation_id": "cv-post", "generation_id": "gen-1", "session_id": "cv-post",
+ "hook_event_name": "postToolUse", "cursor_version": "3.21.18",
+ "workspace_roots": [cwd], "user_email": "[email protected]", "transcript_path": null,
+ "model": "composer-2",
+ "tool_name": "Write", "tool_input": { "file_path": file, "content": content },
+ "tool_output": "{}", "duration": 12, "tool_use_id": "tool-1",
+ })
+ .to_string()
+}
+
+#[test]
+fn cursor_post_tool_use_feeds_findings_back_as_additional_context() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let r = rt(&cwd);
+
+ let res = hook::run_hook(&r, &cursor_post_tool_use(&cwd, &file, SIDE_TAB_CSS));
+
+ let out: Value = serde_json::from_str(&res.stdout).unwrap_or_else(|_| panic!("{}", res.stdout));
+ let keys: Vec<&String> = out.as_object().unwrap().keys().collect();
+ assert_eq!(keys, vec!["additional_context"], "{}", res.stdout);
+ let text = out["additional_context"].as_str().unwrap();
+ assert!(text.contains("side-tab"), "{text}");
+ // Un-tiered: Cursor has no Stop deep pass, so nothing is deferred.
+ assert!(res.audit.get("deferred").is_none_or(|v| v == &json!(0)), "{:?}", res.audit);
+}
+
+#[test]
+fn cursor_additional_context_stays_under_cursors_cap() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ t.write(".impeccable/config.json", r#"{"hook":{"perEditRules":"all","limits":{"maxChars":50000,"maxFindings":1000}}}"#);
+ let css: String = (0..400)
+ .map(|i| format!(".c{i} {{ border-left: 4px solid #6366f1; border-radius: 8px; background: linear-gradient(90deg, #f472b6, #a78bfa); -webkit-background-clip: text; color: transparent; }}\n"))
+ .collect();
+ let file = t.write("src/many.css", &css);
+ let r = rt(&cwd);
+
+ let res = hook::run_hook(&r, &cursor_post_tool_use(&cwd, &file, &css));
+
+ let out: Value = serde_json::from_str(&res.stdout).unwrap();
+ let text = out["additional_context"].as_str().unwrap();
+ assert!(text.encode_utf16().count() <= 10_000, "{}", text.len());
+ // The same edit through Claude's envelope is not clamped, so the cap is
+ // what kept Cursor's text short.
+ let claude = hook::run_hook(&rt(&cwd), &edit_event(&cwd, &file, "s-claude"));
+ assert!(claude.stdout.len() > 10_000, "{}", claude.stdout.len());
+}
+
#[test]
fn monorepo_design_post_edit() { check_monorepo_design_hook("post"); }
@@ -2326,8 +2381,12 @@ fn admin_on_writes_launcher_manifests_for_every_harness() {
let cursor: Value = serde_json::from_str(&t.read(".cursor/hooks.json")).unwrap();
assert_eq!(
- cursor["hooks"]["preToolUse"][0]["command"],
- json!("\".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit")
+ cursor,
+ json!({"version": 1, "hooks": {"postToolUse": [{
+ "command": "\".cursor/skills/impeccable/scripts/impeccable\" hook",
+ "matcher": "^Write$",
+ "timeout": 5,
+ }]}})
);
let github: Value = serde_json::from_str(&t.read(".github/hooks/impeccable.json")).unwrap();
assert_eq!(
@@ -2519,6 +2578,38 @@ fn admin_on_replaces_legacy_user_hook_before_pruning_project_hook() {
assert!(local.get("hooks").is_none(), "duplicate project hook survived: {local}");
}
+#[test]
+fn admin_on_moves_the_retired_cursor_gate_to_post_tool_use() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let r = rt(&cwd);
+ std::fs::create_dir_all(t.0.join(".cursor/skills/impeccable")).unwrap();
+ // A pre-migration manifest: the gate on preToolUse beside a foreign hook
+ // on the same event and another on a different one.
+ t.write(
+ ".cursor/hooks.json",
+ r#"{"version":1,"hooks":{"preToolUse":[{"command":"./audit.sh","matcher":"Shell"},{"command":"\".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit","timeout":5}],"stop":[{"command":"./notify.sh"}]}}"#,
+ );
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ assert!(out.contains("Installed or repaired hook manifests for: .cursor."), "{out}");
+ let cursor: Value = serde_json::from_str(&t.read(".cursor/hooks.json")).unwrap();
+ assert_eq!(
+ cursor,
+ json!({"version": 1, "hooks": {
+ "preToolUse": [{"command": "./audit.sh", "matcher": "Shell"}],
+ "stop": [{"command": "./notify.sh"}],
+ "postToolUse": [{
+ "command": "\".cursor/skills/impeccable/scripts/impeccable\" hook",
+ "matcher": "^Write$",
+ "timeout": 5,
+ }],
+ }})
+ );
+}
+
#[test]
fn admin_on_does_not_repair_project_manifests_from_other_user_scope_skills() {
let t = Tmp::new();
@@ -2908,3 +2999,255 @@ fn run_hook_stands_down_before_the_edit_cap_can_suppress_a_live_file() {
assert!(out.audit.get("editCount").is_none(), "edit {i}: the cap is not bumped for a live wrap");
}
}
+
+// ─── One scan per edit event (hook_claim) ────────────────────────────────────
+
+fn claim_env(t: &Tmp, extra: &[(&str, &str)]) -> HashMap<String, String> {
+ let mut e = env(extra);
+ e.insert("IMPECCABLE_HOOK_CLAIM_DIR".into(), jsp::join(&[&t.path(), "claims"]));
+ e
+}
+
+fn codex_post_tool_use(cwd: &str, file: &str, call: &str) -> String {
+ json!({
+ "session_id": "codex-s", "turn_id": "turn-1", "cwd": cwd, "hook_event_name": "PostToolUse",
+ "model": "gpt-5", "tool_name": "apply_patch", "tool_use_id": call,
+ "tool_input": { "file_path": file },
+ })
+ .to_string()
+}
+
+fn claude_post_tool_use(cwd: &str, file: &str, call: &str) -> String {
+ json!({
+ "session_id": "claude-s", "cwd": cwd, "hook_event_name": "PostToolUse",
+ "tool_name": "Edit", "tool_use_id": call, "tool_input": { "file_path": file },
+ })
+ .to_string()
+}
+
+fn scanned(res: &hook::RunResult) -> bool {
+ res.audit.get("skipped") != Some(&json!("duplicate-event"))
+}
+
+#[test]
+fn concurrent_duplicate_invocations_of_one_event_scan_once() {
+ for (harness, payload) in [
+ ("cursor", cursor_post_tool_use as fn(&str, &str, &str) -> String),
+ ("codex", |cwd: &str, file: &str, _c: &str| codex_post_tool_use(cwd, file, "call-1")),
+ ("claude", |cwd: &str, file: &str, _c: &str| claude_post_tool_use(cwd, file, "toolu_1")),
+ ] {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let stdin = payload(&cwd, &file, SIDE_TAB_CSS);
+ let e = claim_env(&t, &[]);
+ let results: Vec<hook::RunResult> = std::thread::scope(|s| {
+ let handles: Vec<_> = (0..4)
+ .map(|_| {
+ let (cwd, e, stdin) = (cwd.clone(), e.clone(), stdin.clone());
+ s.spawn(move || hook::run_hook(&rt_with(&cwd, e), &stdin))
+ })
+ .collect();
+ handles.into_iter().map(|h| h.join().unwrap()).collect()
+ });
+ let scans: Vec<&hook::RunResult> = results.iter().filter(|r| scanned(r)).collect();
+ assert_eq!(scans.len(), 1, "{harness}: {:?}", results.iter().map(|r| &r.audit).collect::<Vec<_>>());
+ assert!(scans[0].audit.contains_key("findings") && !scans[0].stdout.is_empty(), "{harness}: {:?}", scans[0].audit);
+ for r in results.iter().filter(|r| !scanned(r)) {
+ assert!(r.stdout.is_empty(), "{harness}: a duplicate printed {}", r.stdout);
+ }
+ }
+}
+
+#[test]
+fn different_edit_events_each_scan() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let other = t.write("src/other.css", SIDE_TAB_CSS);
+ let e = claim_env(&t, &[]);
+ let first = hook::run_hook(&rt_with(&cwd, e.clone()), &claude_post_tool_use(&cwd, &file, "toolu_1"));
+ let next_call = hook::run_hook(&rt_with(&cwd, e.clone()), &claude_post_tool_use(&cwd, &file, "toolu_2"));
+ let other_file = hook::run_hook(&rt_with(&cwd, e.clone()), &codex_post_tool_use(&cwd, &other, "toolu_1"));
+ for res in [&first, &next_call, &other_file] {
+ assert!(scanned(res) && res.audit.contains_key("findings"), "{:?}", res.audit);
+ }
+}
+
+/// A plugin's hook command sets the harness itself, the project manifest's
+/// does not; both receive the same event, so only one scans.
+#[test]
+fn plugin_and_project_hooks_for_one_codex_event_scan_once() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let stdin = codex_post_tool_use(&cwd, &file, "call-7");
+ let plugin = hook::run_hook(&rt_with(&cwd, claim_env(&t, &[("IMPECCABLE_HOOK_HARNESS", "codex")])), &stdin);
+ let project = hook::run_hook(&rt_with(&cwd, claim_env(&t, &[])), &stdin);
+ assert!(scanned(&plugin) && plugin.audit.contains_key("findings"), "{:?}", plugin.audit);
+ assert!(!scanned(&project) && project.stdout.is_empty(), "{:?}", project.audit);
+}
+
+/// No tool-call id: nothing to tell a duplicate from a real second edit by,
+/// so every invocation scans, as before.
+#[test]
+fn events_without_a_tool_call_id_are_never_claimed() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let e = claim_env(&t, &[]);
+ for _ in 0..2 {
+ let res = hook::run_hook(&rt_with(&cwd, e.clone()), &edit_event(&cwd, &file, "s-noid"));
+ assert!(scanned(&res), "{:?}", res.audit);
+ }
+}
+
+/// The claim fails open: an unusable claim dir means scan, never skip.
+#[test]
+fn an_unusable_claim_dir_still_scans() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let blocker = t.write("claims-file", "not a dir");
+ let mut e = env(&[]);
+ e.insert("IMPECCABLE_HOOK_CLAIM_DIR".into(), jsp::join(&[&blocker, "nested"]));
+ let stdin = claude_post_tool_use(&cwd, &file, "toolu_9");
+ for _ in 0..2 {
+ let res = hook::run_hook(&rt_with(&cwd, e.clone()), &stdin);
+ assert!(scanned(&res) && res.audit.contains_key("findings"), "{:?}", res.audit);
+ }
+}
+
+#[test]
+fn claim_keys_are_path_safe_and_separator_independent_of_the_platform() {
+ let ev: Map<String, Value> = serde_json::from_value(json!({ "session_id": "s", "tool_use_id": "t" })).unwrap();
+ let key = impeccable_hook::hook_claim::event_key(&ev, r"C:\Users\dev\proj", &[r"C:\Users\dev\proj\src\a.css".into()]).unwrap();
+ assert_eq!(key.len(), 64);
+ assert!(key.chars().all(|c| c.is_ascii_hexdigit()));
+ let ev_none: Map<String, Value> = serde_json::from_value(json!({ "session_id": "s" })).unwrap();
+ assert!(impeccable_hook::hook_claim::event_key(&ev_none, "/p", &[]).is_none());
+}
+
+// ─── Claim storage safety (#1069 review: shared temp roots) ──────────────────
+
+const OLD_CLAIM: &str = "0000000000000000000000000000000000000000000000000000000000000001";
+
+/// A claim root that is a symlink (say one another user planted) is never
+/// followed: nothing behind it is created or deleted, and both hooks scan.
+#[test]
+#[cfg(unix)]
+fn a_symlinked_claim_root_is_never_followed() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ t.write("victim/2024/keep.txt", "mine");
+ t.write(&format!("victim/1/{OLD_CLAIM}"), "");
+ let victim = jsp::join(&[&cwd, "victim"]);
+ let link = jsp::join(&[&cwd, "claims-link"]);
+ std::os::unix::fs::symlink(&victim, &link).unwrap();
+ let mut e = env(&[]);
+ e.insert("IMPECCABLE_HOOK_CLAIM_DIR".into(), link.clone());
+ let stdin = claude_post_tool_use(&cwd, &file, "toolu_link");
+ for _ in 0..2 {
+ let res = hook::run_hook(&rt_with(&cwd, e.clone()), &stdin);
+ assert!(scanned(&res) && res.audit.contains_key("findings"), "{:?}", res.audit);
+ }
+ assert!(t.exists("victim/2024/keep.txt"));
+ assert!(t.exists(&format!("victim/1/{OLD_CLAIM}")));
+ let names: Vec<String> = std::fs::read_dir(&victim).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
+ assert_eq!(names.len(), 2, "{names:?}");
+}
+
+/// A root other users can write to is not trusted either.
+#[test]
+#[cfg(unix)]
+fn a_group_or_world_writable_claim_root_is_not_used() {
+ use std::os::unix::fs::PermissionsExt;
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let root = jsp::join(&[&cwd, "claims"]);
+ std::fs::create_dir(&root).unwrap();
+ std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o777)).unwrap();
+ let stdin = claude_post_tool_use(&cwd, &file, "toolu_open");
+ for _ in 0..2 {
+ let res = hook::run_hook(&rt_with(&cwd, claim_env(&t, &[])), &stdin);
+ assert!(scanned(&res), "{:?}", res.audit);
+ }
+ assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0);
+}
+
+/// The sweep removes only old `<digits>/` buckets and only `<64 hex>` claim
+/// files in them. Foreign names, foreign files and symlinks stay.
+#[test]
+fn the_sweep_removes_only_its_own_old_buckets_and_claims() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let root = jsp::join(&[&cwd, "claims"]);
+ t.write(&format!("claims/2/{OLD_CLAIM}"), "");
+ t.write(&format!("claims/1/{OLD_CLAIM}"), "");
+ t.write("claims/1/readme.txt", "not ours");
+ t.write("claims/notes/todo.txt", "not ours");
+ t.write(&format!("outside/{OLD_CLAIM}"), "");
+ #[cfg(unix)]
+ std::os::unix::fs::symlink(jsp::join(&[&cwd, "outside"]), jsp::join(&[&root, "3"])).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ for d in ["claims", "claims/1", "claims/2", "claims/notes"] {
+ std::fs::set_permissions(jsp::join(&[&cwd, d]), std::fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ }
+
+ let res = hook::run_hook(&rt_with(&cwd, claim_env(&t, &[])), &claude_post_tool_use(&cwd, &file, "toolu_sweep"));
+ assert!(scanned(&res), "{:?}", res.audit);
+
+ assert!(!t.exists("claims/2"), "an old bucket of claims only is removed");
+ assert!(t.exists("claims/1/readme.txt") && !t.exists(&format!("claims/1/{OLD_CLAIM}")));
+ assert!(t.exists("claims/notes/todo.txt"));
+ assert!(t.exists(&format!("outside/{OLD_CLAIM}")), "a symlinked bucket is not followed");
+ // And the normal path still dedupes.
+ let again = hook::run_hook(&rt_with(&cwd, claim_env(&t, &[])), &claude_post_tool_use(&cwd, &file, "toolu_sweep"));
+ assert!(!scanned(&again), "{:?}", again.audit);
+}
+
+/// Without an override the claims sit under the user's home, not in the
+/// shared temp dir.
+#[test]
+fn claims_default_to_the_users_home() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let home = jsp::join(&[&cwd, "home"]);
+ std::fs::create_dir(&home).unwrap();
+ let e = env(&[("HOME", &home), ("USERPROFILE", &home)]);
+ let stdin = claude_post_tool_use(&cwd, &file, "toolu_home");
+ let first = hook::run_hook(&rt_with(&cwd, e.clone()), &stdin);
+ let second = hook::run_hook(&rt_with(&cwd, e.clone()), &stdin);
+ assert!(scanned(&first) && !scanned(&second));
+ assert!(t.exists("home/.impeccable/hook-claims"));
+}
+
+/// The first edit in a fresh home: concurrent hooks race to create
+/// `~/.impeccable`, and the loser must still claim rather than scan.
+#[test]
+fn concurrent_first_edits_in_a_fresh_home_scan_once() {
+ for round in 0..8 {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let file = t.write("src/card.css", SIDE_TAB_CSS);
+ let home = jsp::join(&[&cwd, "home"]);
+ std::fs::create_dir(&home).unwrap();
+ let e = env(&[("HOME", &home), ("USERPROFILE", &home)]);
+ let stdin = claude_post_tool_use(&cwd, &file, "toolu_fresh");
+ let barrier = std::sync::Barrier::new(4);
+ let scans = std::thread::scope(|s| {
+ let handles: Vec<_> = (0..4)
+ .map(|_| s.spawn(|| { barrier.wait(); scanned(&hook::run_hook(&rt_with(&cwd, e.clone()), &stdin)) }))
+ .collect();
+ handles.into_iter().map(|h| h.join().unwrap()).filter(|scanned| *scanned).count()
+ });
+ assert_eq!(scans, 1, "round {round}");
+ }
+}
diff --git a/crates/skills/src/commands.rs b/crates/skills/src/commands.rs
index 93f92dc07..a1d3ba281 100644
--- a/crates/skills/src/commands.rs
+++ b/crates/skills/src/commands.rs
@@ -456,6 +456,22 @@ fn decide_hook_install(prompt: &mut Prompt, io: &mut Io, root: &str, targets: &[
Ok(accepted)
}
+/// Update's hook self-heal (triage E8, and the retired Cursor gate): repairs
+/// the manifests at `hook_root` against the skill at `skill_root`. In user
+/// scope those differ (project manifests, home skill), and the home manifests
+/// are repaired as well, since an older `update --user` wrote Cursor, Codex
+/// and Grok manifests there. They are repaired, never pruned: a home manifest
+/// is global, so removing its entry would drop the hook from every other
+/// project. A home and a project hook firing for one edit is settled inside
+/// the hook (`hook_claim`).
+fn repair_update_hook_manifests(sys: &crate::providers::Sys, hook_root: &str, skill_root: &str, providers: &[&'static str]) -> Result<(), String> {
+ hook_manifest::repair_stale_hook_manifests(sys, hook_root, providers, Some(skill_root))?;
+ if hook_root != skill_root {
+ hook_manifest::repair_stale_hook_manifests(sys, skill_root, providers, None)?;
+ }
+ Ok(())
+}
+
// ─── link ────────────────────────────────────────────────────────────────────
/// JS: link(flags)
@@ -810,6 +826,11 @@ fn update(flags: &[String], io: &mut Io) -> R<()> {
};
out(io, &format!("Updating the {scope_label} install: {} ({})", sys.format_path_for_display(&root), providers.join(", ")));
+ // Hook manifests follow install's placement: a user-scope install keeps
+ // the skill under home but writes every non-Claude manifest (Cursor,
+ // Codex, Grok, ...) into the project, so update repairs and writes them
+ // there too, against the home skill root.
+ let hook_root = if scope == Some(Scope::User) { project_root.clone() } else { root.clone() };
let linked_providers = sys.find_linked_providers(&root, &providers, scope);
let copy_providers: Vec<&'static str> = providers.iter().copied().filter(|p| !linked_providers.contains(p)).collect();
@@ -843,10 +864,10 @@ fn update(flags: &[String], io: &mut Io) -> R<()> {
let outcome: R<Vec<&'static str>> = (|| {
// Repair any stale pre-launcher (`node .../hook.mjs`) manifest a v3
// install left behind, regardless of hook consent (triage E8).
- hook_manifest::repair_stale_hook_manifests(&sys, &root, &copy_providers, None).map_err(Flow::Throw)?;
- let want_hooks = install_hooks && decide_hook_install(&mut prompt, io, &root, &copy_providers, yes)?;
+ repair_update_hook_manifests(&sys, &hook_root, &root, &copy_providers).map_err(Flow::Throw)?;
+ let want_hooks = install_hooks && decide_hook_install(&mut prompt, io, &hook_root, &copy_providers, yes)?;
let hook_targets = if want_hooks {
- copy_provider_hooks(&sys, &tmp_dir, &root, &copy_providers, force, None, Some(&project_root)).map_err(Flow::Throw)?
+ copy_provider_hooks(&sys, &tmp_dir, &hook_root, &copy_providers, force, Some(&root), Some(&project_root)).map_err(Flow::Throw)?
} else {
Vec::new()
};
@@ -899,10 +920,10 @@ fn update(flags: &[String], io: &mut Io) -> R<()> {
bundle::copy_provider_commands(&sys, &tmp_dir, &root, &copy_providers, scope);
// Repair any stale pre-launcher (`node .../hook.mjs`) manifest a v3
// install left behind, regardless of hook consent (triage E8).
- hook_manifest::repair_stale_hook_manifests(&sys, &root, &copy_providers, None).map_err(Flow::Throw)?;
- let want_hooks = install_hooks && decide_hook_install(&mut prompt, io, &root, &providers, yes)?;
+ repair_update_hook_manifests(&sys, &hook_root, &root, &copy_providers).map_err(Flow::Throw)?;
+ let want_hooks = install_hooks && decide_hook_install(&mut prompt, io, &hook_root, &providers, yes)?;
let hook_targets = if want_hooks {
- copy_provider_hooks(&sys, &tmp_dir, &root, &providers, force, None, Some(&project_root)).map_err(Flow::Throw)?
+ copy_provider_hooks(&sys, &tmp_dir, &hook_root, &providers, force, Some(&root), Some(&project_root)).map_err(Flow::Throw)?
} else {
Vec::new()
};
diff --git a/crates/skills/src/hook_manifest.rs b/crates/skills/src/hook_manifest.rs
index 112dd9636..72c4aaf77 100644
--- a/crates/skills/src/hook_manifest.rs
+++ b/crates/skills/src/hook_manifest.rs
@@ -6,7 +6,7 @@
//! Where the JS wrote `[ ! -f "<skill>/scripts/hook.mjs" ] || node
//! "<skill>/scripts/hook.mjs"` (and a `node -e` guard on Windows), the binary
//! writes the launcher form `[ ! -f "<skill>/scripts/impeccable" ] ||
-//! "<skill>/scripts/impeccable" hook` (`hook-before-edit` for Cursor), the
+//! "<skill>/scripts/impeccable" hook` (Cursor included, on `postToolUse`), the
//! shape the public build's `transformers/hooks.js` puts in the bundle; the
//! Codex `commandWindows` sibling and a Windows Grok `command` run
//! `impeccable.cmd` behind `cmd /c if exist`.
@@ -17,7 +17,7 @@
//! `impeccable_context::hook_markers::is_impeccable_hook_command`, so the two
//! writers and the three readers can never disagree on what counts as ours.
-use impeccable_context::hook_markers::{is_impeccable_hook_command, is_launcher_hook_command, parse_manifest_jsonc, windows_launcher_hook_command};
+use impeccable_context::hook_markers::{cursor_hook_manifest, cursor_manifest_has_retired_gate, is_impeccable_hook_command, is_launcher_hook_command, parse_manifest_jsonc, windows_launcher_hook_command};
use serde_json::{Map, Value};
use crate::providers::Sys;
@@ -91,16 +91,31 @@ pub fn expected_hook_dests(root: &str, providers: &[&str]) -> Vec<String> {
.collect()
}
-/// The hook verb the launcher runs for a provider (JS: the `hook.mjs` /
-/// `hook-before-edit.mjs` choice in hookScriptRelPathForProvider).
-pub fn hook_verb(provider: &str) -> &'static str {
- if provider == ".cursor" {
- "hook-before-edit"
- } else {
- "hook"
+/// The hook verb the launcher runs for a provider. Every harness runs the
+/// post-edit `hook` verb; Cursor used to run `hook-before-edit` on
+/// `preToolUse`, and `migrate_cursor_gate` moves those manifests over.
+pub fn hook_verb(_provider: &str) -> &'static str {
+ "hook"
+}
+
+/// Moves a Cursor manifest off the retired `preToolUse` before-edit gate:
+/// drops Impeccable entries from every event (other tools' hooks stay) and
+/// adds the post-edit `postToolUse` entry, its command rewritten for the
+/// install. A manifest without the gate is returned unchanged, so this is
+/// safe to run after any write.
+pub fn migrate_cursor_gate(value: &Value, skill_root: &str, absolute: bool) -> Value {
+ if !cursor_manifest_has_retired_gate(value) {
+ return value.clone();
}
+ // Any launcher-form command carries the marker the rewrite replaces.
+ let template = cursor_hook_manifest("\".cursor/skills/impeccable/scripts/impeccable\" hook", CURSOR_TIMEOUT_SECONDS);
+ let fresh = rewrite_hook_commands_for_skill_root(&template, ".cursor", skill_root, absolute);
+ merge_hook_manifests(value, &fresh)
}
+/// Cursor's per-edit hook timeout, in seconds (the bundle's TIMEOUT_SECONDS).
+const CURSOR_TIMEOUT_SECONDS: i64 = 5;
+
/// JS: hookScriptRelPathForProvider(provider), for the launcher: the
/// project-relative launcher path (Claude keeps its `${CLAUDE_PROJECT_DIR}`
/// token).
@@ -301,6 +316,17 @@ pub fn manifest_has_stale_hook(file: &str) -> bool {
}
}
+/// True when a Cursor manifest on disk still runs the retired `preToolUse`
+/// before-edit gate (either generation's spelling).
+pub fn manifest_has_retired_cursor_gate(file: &str) -> bool {
+ if !util::exists(file) {
+ return false;
+ }
+ let Ok(text) = util::read_text(file) else { return false };
+ let Ok(parsed) = serde_json::from_str::<Value>(&text) else { return false };
+ cursor_manifest_has_retired_gate(&parsed)
+}
+
/// JS: fileHasImpeccableHookMarker(file): parse and scan only the `hooks`
/// subtree.
pub fn file_has_impeccable_hook_marker(file: &str) -> bool {
@@ -571,6 +597,12 @@ pub fn copy_provider_hooks(sys: &crate::providers::Sys, bundle_dir: &str, root:
}
}
}
+ if *provider == ".cursor" {
+ // An older bundle can still carry the retired `preToolUse`
+ // gate; the verb rewrite above would point it at `hook`, which
+ // must run after the edit, not before it.
+ next = migrate_cursor_gate(&next, skill_root, absolute);
+ }
util::mkdir_p(&jsp::dirname(&artifact.dest))?;
// Atomic: in user scope this is the user's whole Claude settings file.
impeccable_common::fsx::write_atomic(&artifact.dest, format!("{}\n", util::json_pretty(&next)).as_bytes()).map_err(|e| util::node_error("open", &artifact.dest, &e))?;
@@ -614,7 +646,11 @@ pub fn prune_duplicate_claude_hooks(sys: &crate::providers::Sys, home_root: &str
/// skipped. `.github` (and any provider with no rewritable launcher path)
/// carries a portable, team-committed command form that must not be pinned to
/// a machine-local path here; its migration rides the bundle-merge path in
-/// `copy_provider_hooks` instead. Returns the providers whose manifest changed.
+/// `copy_provider_hooks` instead. A Cursor manifest that still runs the retired
+/// `preToolUse` before-edit gate is migrated here too (`migrate_cursor_gate`),
+/// in either spelling, so an update moves it to the post-edit hook whether or
+/// not the user re-consents to hooks. Returns the providers whose manifest
+/// changed.
pub fn repair_stale_hook_manifests(sys: &Sys, root: &str, providers: &[&'static str], skill_root: Option<&str>) -> Result<Vec<&'static str>, String> {
let skill_root = skill_root.unwrap_or(root);
let absolute = skill_root != root || sys.is_home_dir(root);
@@ -632,12 +668,17 @@ pub fn repair_stale_hook_manifests(sys: &Sys, root: &str, providers: &[&'static
}
for rel in rels {
let path = jsp::join(&[root, spec.dest_provider, rel]);
- if !manifest_has_stale_hook(&path) {
+ let cursor_gate = *provider == ".cursor" && manifest_has_retired_cursor_gate(&path);
+ if !cursor_gate && !manifest_has_stale_hook(&path) {
continue;
}
let Ok(text) = util::read_text(&path) else { continue };
let Ok(parsed) = serde_json::from_str::<Value>(&text) else { continue };
- let rewritten = rewrite_hook_commands_for_skill_root(&parsed, provider, skill_root, absolute);
+ let rewritten = if cursor_gate {
+ migrate_cursor_gate(&parsed, skill_root, absolute)
+ } else {
+ rewrite_hook_commands_for_skill_root(&parsed, provider, skill_root, absolute)
+ };
if rewritten != parsed {
util::write_bytes(&path, format!("{}\n", util::json_pretty(&rewritten)).as_bytes())?;
changed = true;
@@ -652,7 +693,7 @@ pub fn repair_stale_hook_manifests(sys: &Sys, root: &str, providers: &[&'static
}
/// JS: HOOK_EXPLAINER
-pub const HOOK_EXPLAINER: &str = "\nImpeccable can install a design hook for this project. In Claude/Codex it\nchecks UI files after edits; in Cursor it checks proposed writes before they\nland and can block writes with detector findings. It feeds results back to\nyour agent so design slop gets caught as you build. Change it later with\n/impeccable hooks on|off.\n";
+pub const HOOK_EXPLAINER: &str = "\nImpeccable can install a design hook for this project. It checks UI files\nafter your agent edits them and feeds the findings back to the agent, so\ndesign slop gets caught as you build. Change it later with\n/impeccable hooks on|off.\n";
/// JS: impeccable-config.mjs#setHookConsent(root, value)
pub fn set_hook_consent(root: &str, value: &str) -> Result<String, String> {
diff --git a/crates/skills/tests/drift_ports_tests.rs b/crates/skills/tests/drift_ports_tests.rs
index c2850a19a..1cbe532ae 100644
--- a/crates/skills/tests/drift_ports_tests.rs
+++ b/crates/skills/tests/drift_ports_tests.rs
@@ -740,6 +740,174 @@ fn user_scope_update_writes_claude_user_settings() {
std::fs::remove_dir_all(&root).ok();
}
+/// A path or command with every run of `/` and `\` collapsed to one `/`, so a
+/// Windows command (JSON-quoted, its backslashes doubled) compares with a
+/// test path that mixes separators.
+fn slash_norm(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for ch in s.chars() {
+ let ch = if ch == '\\' { '/' } else { ch };
+ if ch == '/' && out.ends_with('/') {
+ continue;
+ }
+ out.push(ch);
+ }
+ out
+}
+
+/// The Impeccable entries of a Cursor manifest, by event, separators
+/// normalized.
+fn cursor_impeccable_events(manifest: &str) -> Vec<(String, String)> {
+ let value: Value = serde_json::from_str(&read(manifest)).unwrap();
+ let mut out = Vec::new();
+ for (event, entries) in value["hooks"].as_object().unwrap() {
+ for entry in entries.as_array().unwrap() {
+ let command = slash_norm(entry["command"].as_str().unwrap_or_default());
+ if command.contains("skills/impeccable/scripts/") {
+ out.push((event.clone(), command));
+ }
+ }
+ }
+ out
+}
+
+/// A user-scope Cursor install keeps the skill under home but its hook in the
+/// project's `.cursor/hooks.json` (#1069 review). `update --user` has to
+/// migrate that project manifest off the retired `preToolUse` gate, with or
+/// without hook consent. An older `update --user` also wrote the gate into
+/// `~/.cursor/hooks.json`; that file is global, so it is migrated in place,
+/// never pruned, and its foreign entries and other keys stay.
+#[test]
+fn user_scope_update_migrates_the_project_cursor_gate() {
+ for (no_hooks, home_foreign) in [(true, true), (false, true), (true, false), (false, false)] {
+ let root = temp_root(&format!("cursor-user-gate-{no_hooks}-{home_foreign}"));
+ let project = format!("{root}/project");
+ let home = format!("{root}/home");
+ let tmpdir = format!("{root}/tmp");
+ for dir in [&project, &home, &tmpdir] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ std::fs::create_dir_all(format!("{project}/.git")).unwrap();
+ write(
+ &format!("{home}/.cursor/skills/impeccable/SKILL.md"),
+ "---\nname: impeccable\nversion: 1.0.0\n---\n",
+ );
+ let launcher = jsp::join(&[&home, ".cursor", "skills", "impeccable", "scripts", "impeccable"]);
+ let gate = format!("[ ! -f '{launcher}' ] || '{launcher}' hook-before-edit");
+ let project_manifest = format!("{project}/.cursor/hooks.json");
+ write(
+ &project_manifest,
+ &json!({ "version": 1, "hooks": { "preToolUse": [
+ { "command": "./audit.sh", "matcher": "Shell" },
+ { "command": gate, "timeout": 5 },
+ ] } })
+ .to_string(),
+ );
+ let home_manifest = format!("{home}/.cursor/hooks.json");
+ let home_value = if home_foreign {
+ json!({ "version": 1, "theme": "mine", "hooks": {
+ "preToolUse": [{ "command": gate, "timeout": 5 }, { "command": "./guard.sh", "matcher": "Shell" }],
+ "stop": [{ "command": "./notify.sh" }],
+ } })
+ } else {
+ json!({ "version": 1, "hooks": { "preToolUse": [{ "command": gate, "timeout": 5 }] } })
+ };
+ write(&home_manifest, &home_value.to_string());
+ let bundle = create_fake_universal_bundle(&project, &[".cursor"]);
+ let env = base_env(&home, &tmpdir, &bundle);
+
+ let mut args = vec!["update", "-y", "--user"];
+ if no_hooks {
+ args.push("--no-hooks");
+ }
+ let r = run_cli(&args, &project, &env);
+ assert_eq!(r.code, 0, "{}\n{}", r.stdout, r.stderr);
+
+ let ours = cursor_impeccable_events(&project_manifest);
+ assert!(!ours.is_empty(), "{}", read(&project_manifest));
+ for (event, command) in &ours {
+ assert_eq!(event, "postToolUse", "{}", read(&project_manifest));
+ assert!(command.contains(&slash_norm(&launcher)) && command.ends_with(" hook"), "{command}");
+ }
+ let project_value: Value = serde_json::from_str(&read(&project_manifest)).unwrap();
+ assert_eq!(project_value["hooks"]["preToolUse"], json!([{ "command": "./audit.sh", "matcher": "Shell" }]));
+ assert_eq!(project_value["hooks"]["postToolUse"][0]["matcher"], "^Write$");
+
+ let home_ours = cursor_impeccable_events(&home_manifest);
+ assert!(!home_ours.is_empty() && home_ours.iter().all(|(event, _)| event == "postToolUse"), "{}", read(&home_manifest));
+ if home_foreign {
+ let after: Value = serde_json::from_str(&read(&home_manifest)).unwrap();
+ assert_eq!(after["theme"], "mine");
+ assert_eq!(after["hooks"]["preToolUse"], json!([{ "command": "./guard.sh", "matcher": "Shell" }]));
+ assert_eq!(after["hooks"]["stop"], json!([{ "command": "./notify.sh" }]));
+ }
+ std::fs::remove_dir_all(&root).ok();
+ }
+}
+
+/// `update --user` writes non-Claude hooks into the project, so it reads hook
+/// consent from the project too: a project that declined hooks gets none, even
+/// with `-y` and no choice recorded at home (#1069 review).
+#[test]
+fn user_scope_update_honors_the_projects_declined_hook_consent() {
+ let root = temp_root("cursor-user-declined");
+ let project = format!("{root}/project");
+ let home = format!("{root}/home");
+ let tmpdir = format!("{root}/tmp");
+ for dir in [&project, &home, &tmpdir] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ std::fs::create_dir_all(format!("{project}/.git")).unwrap();
+ write(
+ &format!("{home}/.cursor/skills/impeccable/SKILL.md"),
+ "---\nname: impeccable\nversion: 1.0.0\n---\n",
+ );
+ impeccable_skills::hook_manifest::set_hook_consent(&project, "declined").unwrap();
+ let bundle = create_fake_universal_bundle(&project, &[".cursor"]);
+ let env = base_env(&home, &tmpdir, &bundle);
+
+ let r = run_cli(&["update", "-y", "--user"], &project, &env);
+ assert_eq!(r.code, 0, "{}\n{}", r.stdout, r.stderr);
+
+ assert!(!std::path::Path::new(&format!("{project}/.cursor/hooks.json")).exists(), "{}", read(&format!("{project}/.cursor/hooks.json")));
+ assert!(!std::path::Path::new(&format!("{home}/.cursor/hooks.json")).exists());
+ std::fs::remove_dir_all(&root).ok();
+}
+
+/// A fresh hook from `update --user` lands where `install --user` puts it: the
+/// project's `.cursor/hooks.json`, naming the home launcher, never home's.
+#[test]
+fn user_scope_update_writes_the_cursor_hook_into_the_project() {
+ let root = temp_root("cursor-user-update-hook");
+ let project = format!("{root}/project");
+ let home = format!("{root}/home");
+ let tmpdir = format!("{root}/tmp");
+ for dir in [&project, &home, &tmpdir] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ std::fs::create_dir_all(format!("{project}/.git")).unwrap();
+ write(
+ &format!("{home}/.cursor/skills/impeccable/SKILL.md"),
+ "---\nname: impeccable\nversion: 1.0.0\n---\n",
+ );
+ let bundle = create_fake_universal_bundle(&project, &[".cursor"]);
+ let env = base_env(&home, &tmpdir, &bundle);
+
+ let r = run_cli(&["update", "-y", "--user"], &project, &env);
+ assert_eq!(r.code, 0, "{}\n{}", r.stdout, r.stderr);
+
+ let project_manifest = format!("{project}/.cursor/hooks.json");
+ let launcher = slash_norm(&jsp::join(&[&home, ".cursor", "skills", "impeccable", "scripts", "impeccable"]));
+ let ours = cursor_impeccable_events(&project_manifest);
+ assert!(!ours.is_empty(), "{}", read(&project_manifest));
+ for (event, command) in &ours {
+ assert_eq!(event, "postToolUse", "{}", read(&project_manifest));
+ assert!(command.contains(&launcher), "{command}");
+ }
+ assert!(!std::path::Path::new(&format!("{home}/.cursor/hooks.json")).exists());
+ std::fs::remove_dir_all(&root).ok();
+}
+
#[test]
fn existing_user_install_ignores_project_hook_when_user_hook_is_missing() {
let root = temp_root("claude-user-hook-backfill");
diff --git a/crates/skills/tests/hook_manifest_tests.rs b/crates/skills/tests/hook_manifest_tests.rs
index bdf9f673e..cf0ad08f0 100644
--- a/crates/skills/tests/hook_manifest_tests.rs
+++ b/crates/skills/tests/hook_manifest_tests.rs
@@ -132,14 +132,62 @@ fn codex_gets_command_windows_sibling_pointing_at_cmd_shim() {
}
#[test]
-fn cursor_runs_hook_before_edit() {
- let bundle = json!({ "version": 1, "hooks": { "preToolUse": [{ "command": "node \".cursor/skills/impeccable/scripts/hook-before-edit.mjs\"", "timeout": 5 }] } });
+fn cursor_runs_the_post_edit_hook() {
+ let bundle = json!({ "version": 1, "hooks": { "postToolUse": [{ "command": "[ ! -f \".cursor/skills/impeccable/scripts/impeccable\" ] || \".cursor/skills/impeccable/scripts/impeccable\" hook", "matcher": "^Write$", "timeout": 5 }] } });
let out = rewrite_hook_commands_for_platform(&bundle, ".cursor", "/proj", false, false);
- assert_eq!(
- out["hooks"]["preToolUse"][0]["command"],
- "[ ! -f \".cursor/skills/impeccable/scripts/impeccable\" ] || \".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit"
- );
- assert!(out["hooks"]["preToolUse"][0].get("commandWindows").is_none());
+ assert_eq!(out, bundle);
+ assert!(out["hooks"]["postToolUse"][0].get("commandWindows").is_none());
+}
+
+const CURSOR_POST_EDIT: &str = "[ ! -f \".cursor/skills/impeccable/scripts/impeccable\" ] || \".cursor/skills/impeccable/scripts/impeccable\" hook";
+
+#[test]
+fn repair_moves_the_retired_cursor_gate_in_both_spellings() {
+ for gate in [
+ "[ ! -f \".cursor/skills/impeccable/scripts/impeccable\" ] || \".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit",
+ "node \".cursor/skills/impeccable/scripts/hook-before-edit.mjs\"",
+ ] {
+ let home = tmp_dir("cursor-gate-home").to_string_lossy().to_string();
+ let proj = tmp_dir("cursor-gate-proj").to_string_lossy().to_string();
+ let sys = sys_with_home(&home);
+ let manifest = format!("{proj}/.cursor/hooks.json");
+ write(&manifest, &json!({ "version": 1, "hooks": {
+ "preToolUse": [{ "command": "./audit.sh", "matcher": "Shell" }, { "command": gate, "timeout": 5 }],
+ } }).to_string());
+
+ assert_eq!(repair_stale_hook_manifests(&sys, &proj, &[".cursor"], None).unwrap(), [".cursor"], "{gate}");
+
+ let after: Value = serde_json::from_str(&read(&manifest)).unwrap();
+ assert_eq!(after, json!({ "version": 1, "hooks": {
+ "preToolUse": [{ "command": "./audit.sh", "matcher": "Shell" }],
+ "postToolUse": [{ "command": CURSOR_POST_EDIT, "matcher": "^Write$", "timeout": 5 }],
+ } }), "{gate}");
+ // Idempotent.
+ assert!(repair_stale_hook_manifests(&sys, &proj, &[".cursor"], None).unwrap().is_empty());
+ let _ = std::fs::remove_dir_all(&proj);
+ let _ = std::fs::remove_dir_all(&home);
+ }
+}
+
+#[test]
+fn install_from_an_older_bundle_never_runs_the_post_edit_verb_before_the_edit() {
+ let dir = tmp_dir("cursor-old-bundle");
+ let root = dir.to_string_lossy().into_owned();
+ let bundle = jsp::join(&[&root, "bundle"]);
+ let project = jsp::join(&[&root, "project"]);
+ write(&jsp::join(&[&bundle, ".cursor", "hooks.json"]), &json!({ "version": 1, "hooks": { "preToolUse": [{
+ "command": "[ ! -f \".cursor/skills/impeccable/scripts/impeccable\" ] || \".cursor/skills/impeccable/scripts/impeccable\" hook-before-edit",
+ "timeout": 5,
+ }] } }).to_string());
+ let sys = sys_with_home("/nonexistent-home");
+
+ copy_provider_hooks(&sys, &bundle, &project, &[".cursor"], false, None, None).unwrap();
+
+ let after: Value = serde_json::from_str(&read(&jsp::join(&[&project, ".cursor", "hooks.json"]))).unwrap();
+ assert_eq!(after, json!({ "version": 1, "hooks": {
+ "postToolUse": [{ "command": CURSOR_POST_EDIT, "matcher": "^Write$", "timeout": 5 }],
+ } }));
+ let _ = std::fs::remove_dir_all(&dir);
}
#[test]
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index f18844452..f233e314a 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -488,7 +488,7 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI
Fresh install: `stdout> \nDownloading impeccable skills...`; migrate `*-impeccable` prefixed dirs → `impeccable`; copy each skill dir (rm existing dest first; drop an in-project cross-provider symlinked skills dir); copy agents (`.github`→`.github/agents` or `~/.copilot/agents`; `.cursor`→`.cursor/agents` or `~/.cursor/agents`); write hooks (Claude project scope: `.claude/settings.local.json`, skipped when project `.claude/settings.json` already carries the marker; Claude user scope: `~/.claude/settings.json`, with obsolete Impeccable entries pruned from `~/.claude/settings.local.json`; other destinations: `.cursor/hooks.json`, `.codex/hooks.json` for `.agents`, `.github/hooks/impeccable.json`, `.grok/hooks/impeccable.json`); merged with existing JSON (`mergeHookManifests`: strips existing impeccable entries by markers `skills/impeccable/scripts/hook-probe.mjs|hook.mjs|hook-before-edit.mjs|hook-after-edit.mjs|hook-stop.mjs`, then appends fresh); invalid existing JSON → error `Existing hook manifest is not valid JSON: ${dest}. Re-run with --force to replace it.` (with `--force`, `.bak` written). Claude and Gemini user settings are never replaced wholesale when invalid. Hook command rewriting: `[ ! -f '<abs>' ] || node '<abs>'` (POSIX, single-quote-escaped) when absolute (user scope or global skill), else `[ ! -f "<rel>" ] || node "<rel>"` where rel = `${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs` (Claude), `.agents/skills/impeccable/scripts/hook.mjs` (Codex; plus `commandWindows: if exist "<p>" (node "<p>" & exit /b)`), `.cursor/skills/impeccable/scripts/hook-before-edit.mjs`; on win32 for non-Codex: `node -e "<WIN32_HOOK_GUARD_SCRIPT>" "<path>"`. Output: `Installed impeccable into: ${targets.join(', ')} (${'global'|'project'})`, optional `Installed <Provider> agents into: <path>` (+ shadow warning), `Installed hooks into: ...`, then `\nDone! Now type /impeccable init in your AI coding agent's chat (not in this terminal) to set up design context.\n`. Errors: `Download failed: ...` / `Install failed: ...` / `Nothing was installed: the bundle had no variants for ...` → exit 1.
A Claude user-scope hook write also prunes obsolete Impeccable entries from the current project's `.claude/settings.local.json`, preventing a stale project hook from firing alongside the user hook.
Already installed (and not `--force`): `Impeccable skills are already installed (found in ${provider}/).`; compares tree hashes (`sha256` of file content with `\.(claude|cursor|...)\/skills\/` normalized to `.PROVIDER/skills/`); if differs → refresh + `Updated ${n} skill(s) to v${v}.`; missing hooks repaired; else `Skills are up to date (v${v}).` + `Run with --force to reinstall.`; offline → `Could not check for skill updates: ${msg}` + `Existing skills were left unchanged.`; ends `Done!` or the above; `exit 0`. Version read from `^version:\s*(.+)$` in installed `impeccable/SKILL.md`.
-- **update flags**: `-y|--yes`, `--force`, `--no-hooks`, scope flags as above (unknown → `Unknown update scope: ${v}. Use --project or --user.`). Resolves project vs user installs holding an `impeccable`/`*-impeccable`/`teach-impeccable` skill; none → `No impeccable skill folders found in this project or at the user level.` + `Run \`npx impeccable install\` to install first.`, exit 1; both → prompt `Update which? [project]/user: ` (non-TTY defaults project). Prints `Updating the ${label} install: ${root} (${providers})`, linked providers note, `Checking for updates...`; up to date → `Skills are up to date (vX).` [+hooks] + `Nothing else to do.`, exit 0; else `Found skills in: ...`, prompt `Update skills in N provider folder(s)? (Y/n) ` (n/no → `Aborted.` exit 0), refresh, `Updated N skill(s) to vX.`, `Done!`.
+- **update flags**: `-y|--yes`, `--force`, `--no-hooks`, scope flags as above (unknown → `Unknown update scope: ${v}. Use --project or --user.`). Resolves project vs user installs holding an `impeccable`/`*-impeccable`/`teach-impeccable` skill; none → `No impeccable skill folders found in this project or at the user level.` + `Run \`npx impeccable install\` to install first.`, exit 1; both → prompt `Update which? [project]/user: ` (non-TTY defaults project). Prints `Updating the ${label} install: ${root} (${providers})`, linked providers note, `Checking for updates...`; up to date → `Skills are up to date (vX).` [+hooks] + `Nothing else to do.`, exit 0; else `Found skills in: ...`, prompt `Update skills in N provider folder(s)? (Y/n) ` (n/no → `Aborted.` exit 0), refresh, `Updated N skill(s) to vX.`, `Done!`. Hook manifests follow install's placement: in user scope the Claude hook is `~/.claude/settings.json` and every other provider's manifest (`.cursor/hooks.json`, `.codex/hooks.json`, `.grok/hooks/impeccable.json`, ...) is the current project's, rewritten against the home skill. Hook consent is read from (and a prompt's answer written to) that same project root, so a project that declined hooks gets none from `update --user -y`. The stale-manifest repair (`repair_stale_hook_manifests`, including the retired Cursor gate) runs on those project manifests regardless of hook consent. An older `update --user` wrote non-Claude manifests under home instead; those are repaired in place too, never pruned, because a home manifest is global. When a home and a project hook (or a plugin and a project hook) both fire for one edit, the `hook` verb's event claim lets only one of them scan (see `hook`).
- **link**: `--source=<path>` (default `.impeccable`), `--providers`, `--force`, `-y`. Source must contain `dist/universal/` or provider `*/skills` dirs, else `Could not find compiled skills in ${src}. Expected dist/universal/ or provider skill folders.` Prompts `Link impeccable skills into N folder(s)? (Y/n) `; creates relative dir symlinks; existing non-link skipped with warning unless `--force`; output `Linked impeccable into: ... (N linked, N already linked, N skipped).` + submodule hint.
- **check**: not installed → `Impeccable is not installed in this project.` + `Run \`npx impeccable install\` to install.` exit 0; else `Checking for updates...\n` then `Skills are up to date (vX).` or `Updates available.` + `Run \`npx impeccable update\` to update.`; failure → `Could not check for updates: ${msg}` exit 1.
- Prompts: non-TTY `ask()` reads answers line-by-line from stdin (fd 0) after echoing the question; TTY SIGINT → `PromptAbortError` (`code IMPECCABLE_PROMPT_ABORT`) → cli.js prints `\nAborted.` exit 130. ANSI (`\x1b[36m` accent, `\x1b[1m` bold, `\x1b[2m` dim, `\x1b[32m` good) only when stdout is TTY, `NO_COLOR` unset, `TERM !== 'dumb'`.
@@ -792,7 +792,7 @@ Tier 2 (`staleness-deep.mjs`, doctor only):
- `checkDesignDrift({designPath, projectRoot, threshold=25})`: git (5 s timeout, stdout only) `rev-parse --is-inside-work-tree`; `log -1 --format=%H -- <relDesign>` (none -> []); dirs = existing of `src app pages components site styles public`; count lines of `log --oneline <hash>..HEAD -- <dirs>`; `>= 25` -> `design-md-drift` (route) with `%ad --date=short` date.
- `checkDesignCoverage({design, designPath, parseDesignMd})`: seed marker `<!-- SEED: established with the user before implementation; re-run /impeccable document once there's code to capture the actual tokens and components. -->` (or `$impeccable`) -> required `colors, typography`; else `colors, typography, components`; missing = section null AND frontmatter[section] has no non-empty string leaf (empty `[]`/`{}` strings don't count; booleans/numbers don't count) -> `design-md-coverage` (mention).
- `checkDetectorIgnores({projectRoot, knownRuleIds})`: per config file: `detector.ignoreRules` lowercased/trimmed, not `*`, not in registry -> `detector-ignore-rules-unknown` (mention; skipped when registry null); `detector.ignoreFiles` entries without `*` and not existing -> `detector-ignore-files-missing` (mention).
-- `checkHookInstallation({projectRoot, repoRoot, providerId})`: manifests per provider (same table as context); commands containing a marker; script token extraction: double-quoted path first, `'\''` -> unparseable (skip), single-quoted, else bare token `/([^\s"'|&;()]*skills\/impeccable\/scripts\/hook(?:-before-edit)?\.mjs)/`; resolution: `$(`/backtick -> skip; `${CLAUDE_PROJECT_DIR}` -> root; any other `${VAR}`/`$VAR` -> skip; relative -> join(root). Missing -> `hook-script-missing` (mention). If any manifest installed and any config has `hook.enabled === false` -> `hook-enabled-conflict` (mention, returns after first). It also checks the provider's user-level manifest (Claude `~/.claude/settings.json`; Codex and agents the same `$CODEX_HOME/hooks.json` or `~/.codex/hooks.json` file context reads); a missing launcher there gets a fix naming `impeccable update --user`, which rewrites only the default home locations, so a custom `CODEX_HOME` file is repointed by hand.
+- `checkHookInstallation({projectRoot, repoRoot, providerId})`: manifests per provider (same table as context); commands containing a marker; script token extraction: double-quoted path first, `'\''` -> unparseable (skip), single-quoted, else bare token `/([^\s"'|&;()]*skills\/impeccable\/scripts\/hook(?:-before-edit)?\.mjs)/`; resolution: `$(`/backtick -> skip; `${CLAUDE_PROJECT_DIR}` -> root; any other `${VAR}`/`$VAR` -> skip; relative -> join(root). Missing -> `hook-script-missing` (mention). If any manifest installed and any config has `hook.enabled === false` -> `hook-enabled-conflict` (mention, returns after first). It also checks the provider's user-level manifest (Claude `~/.claude/settings.json`; Codex and agents the same `$CODEX_HOME/hooks.json` or `~/.codex/hooks.json` file context reads); a missing launcher there gets a fix naming `impeccable update --user`, which rewrites only the default home locations, so a custom `CODEX_HOME` file is repointed by hand. Provider `cursor` only: a manifest whose `hooks.preToolUse` still runs an Impeccable hook (the retired before-edit gate, either spelling) -> `cursor-hook-pre-edit-gate` (auto, path the manifest, summary `<rel> still runs the design hook as Cursor's \`preToolUse\` write gate, which is retired. Cursor now runs it after each edit on \`postToolUse\` and hands the findings to the agent as context.`, fix ``Move the entry to `postToolUse`: `impeccable doctor --fix`, `impeccable hooks on`, or the next `impeccable update` does it.``). It is emitted before any `hook-script-missing` for the same manifest.
- `checkLegacyLiveState`: `.impeccable-live.json` / `.impeccable-live` present -> `legacy-live-state` (auto).
- `checkWorkspaces({repoRoot, candidates, ...})`: per candidate `{ name, path, productStatus, productPath, designStatus, designPath, platform: extractPlatform(product) || (product ? 'web (default)' : null) }`; native evidence per workspace -> `workspace-platform-native-evidence` (mention); any inherited -> `workspace-context-inherited` (mention, path null).
- `loadKnownRuleIds(scriptsDir)`: `<scriptsDir>/detector/detect-antipatterns.mjs` then `<scriptsDir>/../../cli/engine/detect-antipatterns.mjs`; import `ANTIPATTERNS` -> Set of lowercase ids; null when unavailable.
@@ -823,7 +823,7 @@ Tier 2 (`staleness-deep.mjs`, doctor only):
- Text: lines joined by `\n` + `\n`:
`Impeccable doctor: <rel(projectRoot, cwd) || '.'>`; if monorepo `Monorepo, repo root <rel || '.'>.`; blank; either `No drift found. Every artifact matches what this version reads.` or groups in order route/mention/auto with header `needs a command (n):` / `worth saying (n):` / `automatic (n):`, each finding as ` <id> [<path>]` (path part omitted if null), ` <summary>`, ` → <fix>`, blank line after each group; if workspaces: `Workspaces:` then ` <path> product: <status> design: <status>[ platform: <p>]`, blank; if registry unavailable: `Note: the bundled detector could not be resolved, so ignored rule ids were not validated.` + blank; if `--fix`: `Applied:` + ` <entry>` lines or `Applied nothing.`, then `Left alone:` + ` <id>: <reason>` for skipped entries whose reason !== `needs a decision from the user`; else if any auto finding: ``Run `node doctor.mjs --fix` to apply the automatic migrations, or `<IMPECCABLE_COMMAND> doctor` to work through all of them.``
- Exit 0 always on success (findings are not errors); runtime failure -> stderr `impeccable doctor failed: <msg>`, exit 1.
-- **Side effects (`--fix` only)**: for `design-sidecar-legacy-path`: if canonical `.impeccable/design.json` does not exist, `mkdir -p` and `rename` the legacy file -> applied `Moved <rel present> to <rel canonical>.`; else skipped `<rel canonical> already exists; not overwriting`. `legacy-live-state` -> skipped `delete by hand once no live session is running`. Any other auto id -> `no automatic migration implemented`. Non-auto -> `needs a decision from the user`. Then, independent of findings: if PRODUCT.md exists, is unstamped, and there is NO `product-schema-legacy` finding, rewrite it via `stampProductSchema` -> applied `Stamped <rel> as product-schema 1.` (stamp inserted after the H1 with a blank line).
+- **Side effects (`--fix` only)**: for `design-sidecar-legacy-path`: if canonical `.impeccable/design.json` does not exist, `mkdir -p` and `rename` the legacy file -> applied `Moved <rel present> to <rel canonical>.`; else skipped `<rel canonical> already exists; not overwriting`. `legacy-live-state` -> skipped `delete by hand once no live session is running`. `cursor-hook-pre-edit-gate` -> the manifest is rewritten in place (`hook_markers::migrate_cursor_gate_in_place`): the launcher-form gate entry leaves `preToolUse` (the event key is dropped when nothing else is left on it), and the same command with `hook-before-edit` swapped for `hook` joins `postToolUse` as `{ "command", "matcher": "^Write$", "timeout": <the gate's, else 5> }` unless an Impeccable `postToolUse` entry is already there; other entries and events are untouched -> applied `Moved the design hook in <rel> from preToolUse to postToolUse.`; a JS-era `.mjs` gate is skipped `the gate entry is not in the launcher form; run \`impeccable hooks on\``. Any other auto id -> `no automatic migration implemented`. Non-auto -> `needs a decision from the user`. Then, independent of findings: if PRODUCT.md exists, is unstamped, and there is NO `product-schema-legacy` finding, rewrite it via `stampProductSchema` -> applied `Stamped <rel> as product-schema 1.` (stamp inserted after the H1 with a blank line).
- **Gotchas**: `rel()` returns posix repo-relative or the absolute path when outside. Workspaces list is empty unless run at a monorepo root without `--target`. `checkProjectRoots` always receives the candidates from selection (empty when target given), so `config-project-roots-match-nothing` can also fire when `--target` is passed and patterns exist (candidates=[]).
- **Tests**: `tests/doctor.test.mjs` (drift threshold, coverage incl. frontmatter/seed marker rules, ignore validation + real registry, hook path forms #399/#476/`${CLAUDE_PROJECT_DIR}`/`$(git ...)`/plugin placeholders, legacy live state, workspaces sweep, CLI: clean project text, JSON severity grouping, `--fix` moves sidecar and stamps, no-overwrite, no stamp when legacy, monorepo workspaces JSON, `--help`, malformed target).
@@ -1223,12 +1223,20 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill l
```
No Stop hook (Copilot stop-style events don't feed context back). No systemMessage notice.
- **Grok Build** (`.grok/hooks/impeccable.json`): Claude-shaped `hooks` object (`PostToolUse` matcher `Edit|Write|MultiEdit` + `Stop`), path `.grok/skills/impeccable/scripts/hook.mjs`, probe-only guard (no notice). Requires `/hooks-trust`.
- - **Cursor** does NOT invoke `hook.mjs` (uses `hook-before-edit.mjs`), but `hook.mjs` still understands Cursor-shaped events (`conversation_id`, `workspace_roots`, `tool_input.path`) and would emit `{"additional_context": ...}`.
+ - **Cursor** (`.cursor/hooks.json`, the launcher era): `{ "version": 1, "hooks": { "postToolUse": [{ "command": "[ ! -f \".cursor/skills/impeccable/scripts/impeccable\" ] || \".cursor/skills/impeccable/scripts/impeccable\" hook", "matcher": "^Write$", "timeout": 5 }] } }` (`hooks on` writes the unguarded `"\".cursor/skills/impeccable/scripts/impeccable\" hook"`; the Cursor plugin bundle uses `${CURSOR_PLUGIN_ROOT}/skills/impeccable/scripts`). No Stop entry, and the hook stays un-tiered (`perEditTieringActive` is false for `cursor`): see the verified contract below. Manifests from before this ran `hook-before-edit` on `preToolUse` (next section); install/update (`repair_stale_hook_manifests`, and `copy_provider_hooks` after its merge), `hooks on` (`mergeHookManifests` strips Impeccable entries from every event), and `doctor --fix` move that entry to `postToolUse`, keeping foreign entries.
+ - **Cursor hooks contract, as verified 2026-10-18** against https://cursor.com/docs/hooks and the agent runtime shipped in Cursor 3.21.18 (`extensions/cursor-agent-exec/dist/main.js`, `extensions/cursor-local-agent-runtime/dist/main.js`, `out/vs/workbench/workbench.desktop.main.js`). Not captured live: the installed `cursor-agent` CLI (2025.09.12) predates hooks and has no hook code at all.
+ - Every agent file edit, whole-file or search-replace, reaches hooks as `tool_name: "Write"` with `tool_input: { "file_path": "<abs>", "content": "<new text>" }` (the agent-exec `Write` tool's `createToolInput`). The other built-in names are `Read`, `Delete`, `List`, `Grep`, `Shell`, `WriteShellStdin`, `Fetch`, `ReadLints`, `ListMcpResources`, `FetchMcpResource`, `ComputerUse`, `RecordScreen`, `Task`, and `MCP:<tool>`.
+ - `matcher` is `new RegExp(matcher).test(<tool_name>)`, unanchored (`matcher.ts`), so `^Write$` keeps `WriteShellStdin` out; `""`, `"*"` or no matcher run for every tool.
+ - Every hook's stdin carries `conversation_id`, `generation_id`, `session_id` (= `conversation_id`), `hook_event_name`, `cursor_version`, `workspace_roots`, `user_email`, `transcript_path`, `model` (plus `model_id`, `model_params` when known). `postToolUse` adds `tool_name`, `tool_input`, `tool_output` (JSON-stringified), `duration` (ms), and `tool_use_id` (the docs also list `cwd`).
+ - `postToolUse` reply: `{ "additional_context": "<text>" }` (`PostToolUseRequestResponse` has that one field, plus `updated_mcp_tool_output` for MCP tools). Cursor trims it, drops it when empty, and rejects more than 10,000 characters (`HookAdditionalContextTooLargeError`); otherwise it is attached to the tool result as a `hook_additional_contexts` entry the model reads. The `hook` verb clamps `limits.maxChars` to 10,000 for the `cursor` harness. `additional_context` is also honored on `sessionStart`, `beforeSubmitPrompt`, `preToolUse`, and `postToolUseFailure`.
+ - `afterFileEdit` (stdin `file_path` + `edits: [{ old_string, new_string }]`) has no response schema; nothing it prints reaches the agent, which is why the hook does not use it.
+ - `stop` (stdin `status: "completed"|"aborted"|"error"`, `loop_count`) can only reply `{ "followup_message": "<text>" }`, which Cursor submits as the next user message, a new turn, capped by the per-script `loop_limit` (default 5, `null` uncapped). That is not a Stop deep pass in the Claude sense, so no Stop entry is installed (#1061).
+ - `preToolUse` reply: `permission` (`allow`|`deny`; `ask` is accepted but not enforced), `user_message`, `agent_message`, `updated_input`, `additional_context`. Hooks are read from `.cursor/hooks.json` (project), the user and enterprise files, team hooks, and Claude Code `settings.json` hooks mapped through `claude-code-mapper.ts` (Claude `Edit` and `Write` both map to `Write`), when that import is on.
- Skill text: `skill/reference/hooks.md` describes it; `SKILL.src.md` line 81 routes `/impeccable hooks` to `hook-admin.mjs`, never to `hook.mjs` directly. `context.mjs#automaticHookMode` looks for the marker `skills/impeccable/scripts/hook.mjs` / `hook-before-edit.mjs` in the provider's manifests to decide whether to emit `MANUAL_DETECTOR_REQUIRED`.
- Stdin payload shapes handled:
- Claude Code / Codex / Grok PostToolUse: `{ "session_id", "cwd", "hook_event_name": "PostToolUse", "tool_name": "Edit"|"Write"|"MultiEdit"|"apply_patch", "tool_input": { "file_path": "/abs" | ..., "command": "*** Begin Patch\n*** Update File: rel/or/abs\n..." (Codex apply_patch) }, "tool_response"?, ... }`.
- Claude Code Stop: `{ "session_id", "cwd", "hook_event_name": "Stop", "stop_hook_active": true|false, ... }`.
- - Cursor postToolUse-shaped: `{ "conversation_id", "workspace_roots": ["/proj"], "tool_name": "Write", "tool_input": { "path": "src/App.jsx" } }`.
+ - Cursor postToolUse: `{ "conversation_id", "generation_id", "session_id", "hook_event_name": "postToolUse", "cursor_version", "workspace_roots": ["/proj"], "user_email", "transcript_path", "model", "tool_name": "Write", "tool_input": { "file_path": "/abs", "content": "..." }, "tool_output", "duration", "tool_use_id" }`. The harness is recognized by `conversation_id`; `tool_input.path` (older envelope) is still read.
- GitHub Copilot postToolUse: `{ "sessionId", "timestamp", "cwd", "toolName": "edit"|"create"|"apply_patch", "toolArgs": "<JSON string {\"path\":...,\"old_str\":...,\"new_str\":...}>" | "<raw *** Begin Patch text>", "toolResult" }`.
- **CLI args / flags**: none. Ignores `process.argv`.
- **Env vars read**:
@@ -1251,6 +1259,7 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill l
3. `harness = resolveHarness`; `event = normalizeHookEvent`; `sessionCwd = event.cwd || cwd`; `primaryFiles = normalizeScanTargets(resolveTargetFiles(event, sessionCwd), sessionCwd)`; `projectCwd = resolveCacheCwd(primaryFiles[0], sessionCwd)`; `targetFiles = expandScanTargets(primaryFiles, projectCwd)`. Empty → `skipped:'no-file-path'`.
4. `config = readConfig(projectCwd)`; `enabled === false` → `'config-disabled'`.
5. native platform → `skipped:'native-platform', platform`.
+ 5a. Event claim (`hook_claim`, the engine only): when the raw payload names the tool call (`tool_use_id`, else `toolUseId` / `tool_call_id` / `toolCallId`; Claude Code, Codex and Cursor all send `tool_use_id`), `key = sha256(session ∥ call ∥ projectCwd ∥ sorted primaryFiles)` with `session` = `session_id` / `sessionId` / `conversation_id` (or empty). The claim is a file `<root>/<bucket>/<key>` created with `create_new` (O_EXCL), where `root` = `IMPECCABLE_HOOK_CLAIM_DIR`, else `<home>/.impeccable/hook-claims` (home = `HOME` then `USERPROFILE`, reversed on Windows; no home → no claim), never the shared temp dir, and `bucket` = unix seconds / 600. The root and each bucket are created one level at a time (mode 0700 on Unix) and used only when `lstat` shows a real directory, not a symlink, that on Unix the current user owns with no group or other write bit; otherwise the claim is skipped and nothing is created or deleted. If the key already exists in this bucket or the previous one, another Impeccable hook already took this edit (a home and a project manifest, a plugin and a project hook, a parent and a sub-project hook): → `skipped:'duplicate-event'`, no stdout, exit 0. The invocation that creates a new bucket sweeps buckets older than the previous one (one `read_dir` of the root, no walk), non-recursively: only safe `<digits>` directories, in them only regular files named by 64 lowercase hex characters, then the directory itself if that emptied it. Symlinks are never followed and foreign entries stay. An event with no tool-call id is never claimed, and every claim error (unwritable root, a file in the way) scans as before: the claim fails open.
6. `cache = readCache(projectCwd)`; `sessionId = event.session_id || 'unknown'`; detector missing → `'detector-missing'`; `scanOptions = designSystemOptions(...)`; `tiered = perEditTieringActive(config, harness)`; `quietMode = truthy(IMPECCABLE_HOOK_QUIET) || config.quiet`.
7. 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}`.
@@ -1292,7 +1301,9 @@ The baseline compares pure text-detector findings, independent of line numbers,
DOM scans, design-system findings, co-scanned stylesheets without their own baseline, and providers/events without a verified preimage remain unknown: other files or earlier edits may affect the result. `[new]` means absent from the verified first-observed-edit baseline, not proof of who caused it. Stop audit output records `preExistingFindings` (suppressed), `newFindings`, and `unknownFindings` before notification deduplication. No permanent ignores or new hook permissions are created.
-#### `hook-before-edit.mjs` -> `impeccable hook-before-edit` (Cursor preToolUse write gate)
+#### `hook-before-edit.mjs` -> `impeccable hook-before-edit` (Cursor preToolUse write gate, retired)
+
+Retired as the installed Cursor hook: new manifests run `hook` on `postToolUse` (above), and the repair paths move an existing gate entry there. The verb keeps the behavior below unchanged so a manifest that has not been migrated keeps working.
- **Invoked from**: Cursor project manifest `.cursor/hooks.json`:
```json
@@ -1371,7 +1382,7 @@ DOM scans, design-system findings, co-scanned stylesheets without their own base
"Stop": [ { "hooks": [ { "type": "command", "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs\"", "timeout": 30, "statusMessage": "Design deep pass" } ] } ] } }
```
- `.agents` → dest `.codex/hooks.json`: `{ "hooks": { "PostToolUse": [ { "matcher": "Edit|Write|apply_patch", "hooks": [ { "type":"command", "command": "node \".agents/skills/impeccable/scripts/hook.mjs\"", "timeout": 5, "statusMessage": "Checking UI changes" } ] } ], "Stop": [ { "hooks": [ { "type":"command", "command": "node \".agents/skills/impeccable/scripts/hook.mjs\"", "timeout": 30, "statusMessage": "Design deep pass" } ] } ] } }`
- - `.cursor` → `.cursor/hooks.json`: `{ "version": 1, "hooks": { "preToolUse": [ { "command": "node \".cursor/skills/impeccable/scripts/hook-before-edit.mjs\"", "timeout": 5 } ] } }`
+ - `.cursor` → `.cursor/hooks.json`: `{ "version": 1, "hooks": { "postToolUse": [ { "command": "\".cursor/skills/impeccable/scripts/impeccable\" hook", "matcher": "^Write$", "timeout": 5 } ] } }` (the JS era wrote `preToolUse` running `node ".cursor/skills/impeccable/scripts/hook-before-edit.mjs"`; the merge below strips that entry)
- `.github` → `.github/hooks/impeccable.json`: `{ "version": 1, "hooks": { "postToolUse": [ { "type": "command", "matcher": "edit|create|apply_patch", "bash": "node \"$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/hook.mjs\"", "timeoutSec": 5 } ] } }`
- Merge rule (`mergeHookManifests`): keep existing top-level keys; `version`/`description` from fresh if defined; for each event key, keep existing entries with impeccable entries stripped (marker match on `command`, `args`, `bash`, `powershell`, or nested `hooks[]`; markers = `skills/impeccable/scripts/hook-probe.mjs|hook.mjs|hook-before-edit.mjs|hook-after-edit.mjs|hook-stop.mjs`), then append fresh entries. Unparseable existing manifest → copied to `<dest>.bak` and overwritten. Idempotent: if serialized output equals current file content → `already`. Pruning of a manifest that becomes empty deletes the file.
- `reset`: from each of config.json/config.local.json remove `hook` and `detector` keys (delete file if nothing else remains; skip files without those keys); delete `hook.cache.json` and `hook.pending.json` if present. Does NOT touch harness manifests or git exclude.
@@ -1399,7 +1410,7 @@ DOM scans, design-system findings, co-scanned stylesheets without their own base
| Claude Code (project) | `PostToolUse` matcher `Edit\|Write\|MultiEdit` (timeout 5), `Stop` (timeout 30) | `.claude/settings.json` (build) / `.claude/settings.local.json` (CLI install, hook-admin) | `hook.mjs` | `{"hookSpecificOutput":{"hookEventName":..,"additionalContext":..}}` | No (exit 0) |
| Claude Code plugin / Grok plugin | same | `plugin/hooks/hooks.json` (`${CLAUDE_PLUGIN_ROOT}`) | `hook.mjs` | same | No |
| Codex | `PostToolUse` matcher `Edit\|Write\|apply_patch`, `Stop` | `.codex/hooks.json` (+ `commandWindows` from CLI); OpenAI plugin `hooks/hooks.json` (`${PLUGIN_ROOT}`) | `hook.mjs` | same as Claude (harness `'claude'`); apply_patch paths parsed from `tool_input.command` | No |
-| Cursor | `preToolUse` (no matcher, timeout 5) | `.cursor/hooks.json` | `hook-before-edit.mjs` | `{"permission":"allow"}` / `{"permission":"deny","user_message","agent_message"}` | Yes on deny |
+| Cursor | `postToolUse` matcher `^Write$` (timeout 5); no Stop | `.cursor/hooks.json`; Cursor plugin `hooks/hooks.json` (`${CURSOR_PLUGIN_ROOT}`) | launcher `hook` (was `hook-before-edit` on `preToolUse`) | `{"additional_context": ..}` (max 10,000 chars) | No |
| GitHub Copilot | `postToolUse` matcher `edit\|create\|apply_patch` (`timeoutSec` 5), `bash` key | `.github/hooks/impeccable.json` | `hook.mjs` | `{"additionalContext": ..}` | No |
| Grok Build (project) | `PostToolUse` `Edit\|Write\|MultiEdit`, `Stop` | `.grok/hooks/impeccable.json` | `hook.mjs` | Claude shape (stdout reportedly ignored by Grok) | No |
| Gemini, Kiro, OpenCode, Trae, Hermes, etc. | none | none | — | `context.mjs` emits `MANUAL_DETECTOR_REQUIRED` | — |
diff --git a/scripts/lib/transformers/hooks.js b/scripts/lib/transformers/hooks.js
index baeb11c35..f2ff1b2a0 100644
--- a/scripts/lib/transformers/hooks.js
+++ b/scripts/lib/transformers/hooks.js
@@ -29,14 +29,15 @@ const STATUS_MESSAGE = 'Checking UI changes';
// The Stop deep pass scans every UI file touched in the session with the
// full rule set, so it gets a longer budget than the single-file per-edit
// pass. Wired only for Claude Code and Codex, which both dispatch a native
-// `Stop` hook event; Cursor's stop hook is not consistently dispatched and
-// GitHub Copilot's stop-style events do not feed context back to the model.
+// `Stop` hook event; Cursor's stop hook can only answer with a follow-up user
+// message and GitHub Copilot's stop-style events do not feed context back to
+// the model.
const STOP_TIMEOUT_SECONDS = 30;
const STOP_STATUS_MESSAGE = 'Design deep pass';
// The hook is a verb of the impeccable launcher that ships in the skill's
-// scripts dir: `<scripts>/impeccable hook` (per-edit and Stop passes) and
-// `<scripts>/impeccable hook-before-edit` (Cursor's preToolUse). The launcher
+// scripts dir: `<scripts>/impeccable hook` (per-edit and Stop passes; Cursor's
+// retired preToolUse gate ran `hook-before-edit`, which still works). The launcher
// runs the platform binary next to it, or downloads it once; no runtime probe
// is needed and there is no Node on the path to check.
export const LAUNCHER_NAME = 'impeccable';
@@ -160,13 +161,23 @@ export function buildCodexHooksManifest(skillDir = '.codex') {
};
}
+// Cursor runs the post-edit hook on `postToolUse`, whose response field
+// `additional_context` Cursor injects after the tool result. Every agent file
+// edit reports `tool_name: "Write"` with `tool_input: { file_path, content }`;
+// the matcher is an unanchored regex, so the anchors keep `WriteShellStdin`
+// out. (`afterFileEdit` fires too but its response never reaches the agent.)
+// No Stop entry: Cursor's `stop` can only answer with a `followup_message`
+// submitted as a new user turn (#1061). The engine's twin is
+// `cursor_hook_manifest` in crates/context/src/hook_markers.rs.
+// https://cursor.com/docs/hooks
export function buildCursorHooksManifest(scriptsDir = CURSOR_SCRIPTS) {
return {
version: 1,
hooks: {
- preToolUse: [
+ postToolUse: [
{
- command: guardedLauncher(launcherIn(scriptsDir), 'hook-before-edit'),
+ command: guardedLauncher(launcherIn(scriptsDir)),
+ matcher: '^Write$',
timeout: TIMEOUT_SECONDS,
},
],
diff --git a/scripts/smoke-provider-hooks.mjs b/scripts/smoke-provider-hooks.mjs
index 2f7b82c11..076746c02 100644
--- a/scripts/smoke-provider-hooks.mjs
+++ b/scripts/smoke-provider-hooks.mjs
@@ -65,16 +65,8 @@ const providerSmoke = {
confirmedFixture: 'src/__impeccable_provider_smoke_confirmed_cursor.html',
agentChoiceFixture: 'src/__impeccable_provider_smoke_font_choice_cursor.html',
launcher: '.cursor/skills/impeccable/scripts/impeccable',
- hookVerb: 'hook-before-edit',
- event: (file) => ({
- hook_event_name: 'preToolUse',
- cwd: targetRepo,
- tool_name: 'Write',
- tool_input: {
- file_path: file,
- content: readFileSync(file, 'utf8'),
- },
- }),
+ hookVerb: 'hook',
+ event: (file) => cursorPostToolUseEvent('confirmed-cursor', file),
},
};
@@ -405,7 +397,10 @@ function verifyInstallShape() {
const cursor = readText('.cursor/hooks.json');
assertCount(claude, '.claude/skills/impeccable/scripts/impeccable" hook', 1, 'Claude hook');
assertCount(codex, '.agents/skills/impeccable/scripts/impeccable" hook', 1, 'Codex hook');
- assertCount(cursor, '.cursor/skills/impeccable/scripts/impeccable" hook-before-edit', 1, 'Cursor preToolUse');
+ assertCount(cursor, '.cursor/skills/impeccable/scripts/impeccable" hook', 1, 'Cursor postToolUse');
+ if (cursor.includes('hook-before-edit') || cursor.includes('"preToolUse"')) {
+ throw new Error('Cursor manifest still runs the retired preToolUse gate');
+ }
for (const text of [claude, codex, cursor]) {
if (text.includes('.mjs')) throw new Error('a Node hook script still appears in hook manifests');
}
@@ -497,23 +492,18 @@ function runDirectContractChecks() {
requireFinding('direct Codex hook', `${codex.stdout}\n${readMaybe(join(smokeDir, 'direct.ndjson'))}`);
clearRuntimeState();
- const pre = run('.cursor/skills/impeccable/scripts/impeccable', ['hook-before-edit'], {
+ const cursor = run('.cursor/skills/impeccable/scripts/impeccable', ['hook'], {
cwd: targetRepo,
env,
- logName: 'direct-cursor-before.log',
- input: JSON.stringify({
- hook_event_name: 'preToolUse',
- cwd: targetRepo,
- tool_name: 'Write',
- tool_input: {
- file_path: join(targetRepo, directSmokeFile),
- content: badFixtureContent(),
- },
- }),
+ logName: 'direct-cursor.log',
+ input: JSON.stringify(cursorPostToolUseEvent('direct-cursor', file)),
});
- requireFinding('direct Cursor preToolUse hook', `${pre.stdout}\n${readMaybe(join(smokeDir, 'direct.ndjson'))}`);
+ requireFinding('direct Cursor postToolUse hook', `${cursor.stdout}\n${readMaybe(join(smokeDir, 'direct.ndjson'))}`);
+ if (!/^\{"additional_context":/.test(cursor.stdout)) {
+ throw new Error(`direct Cursor hook did not answer with additional_context: ${cursor.stdout}`);
+ }
- record('direct script contracts', true, 'Claude, Codex, and Cursor preToolUse scripts detect side-tab');
+ record('direct script contracts', true, 'Claude, Codex, and Cursor post-edit hooks detect side-tab');
}
function runConfirmedExceptionPersistenceChecks() {
@@ -557,12 +547,7 @@ function runConfirmedExceptionForProvider(provider) {
clearTransientHookState();
const second = runInstalledProviderHook(provider, file, afterLog);
- if (provider === 'cursor') {
- const payload = JSON.parse(second.stdout || '{}');
- if (payload.permission !== 'allow') {
- throw new Error('Cursor confirmed ignore-value did not allow the proposed write');
- }
- } else if (/overused-font|Required design corrections/.test(second.stdout || '')) {
+ if (/overused-font|Required design corrections/.test(second.stdout || '')) {
throw new Error(`${provider} confirmed ignore-value emitted a correction after persistence`);
}
@@ -610,12 +595,7 @@ function runAgentChosenFontExceptionForProvider(provider) {
clearTransientHookState();
const second = runInstalledProviderHook(provider, file, afterLog);
- if (provider === 'cursor') {
- const payload = JSON.parse(second.stdout || '{}');
- if (payload.permission !== 'allow') {
- throw new Error('Cursor agent-chosen ignore-value did not allow the proposed write');
- }
- } else if (/overused-font|Required design corrections/.test(second.stdout || '')) {
+ if (/overused-font|Required design corrections/.test(second.stdout || '')) {
throw new Error(`${provider} agent-chosen ignore-value emitted a correction after persistence`);
}
@@ -791,27 +771,14 @@ function runCursorProviderSmoke() {
logName: 'cursor-provider.log',
cursorReady: true,
});
- const evidence = `${res.stdout}\n${res.stderr}\n${readMaybe(join(smokeDir, 'cursor.ndjson'))}\n${readMaybe(join(targetRepo, '.impeccable', 'hook.pending.json'))}\n${readMaybe(join(targetRepo, '.impeccable', 'hook.cache.json'))}`;
+ const evidence = `${res.stdout}\n${res.stderr}\n${readMaybe(join(smokeDir, 'cursor.ndjson'))}\n${readMaybe(join(targetRepo, '.impeccable', 'hook.cache.json'))}`;
+ requireFile(providerSmoke.cursor.fixture, 'Cursor provider fixture');
requireFinding('Cursor provider hook', evidence);
const auditEvents = readAuditEvents(join(smokeDir, 'cursor.ndjson'));
- if (!auditEvents.some((event) => event.event === 'preToolUse' && event.blocked === true)) {
- throw new Error('Cursor provider evidence lacks a preToolUse audit entry with blocked=true');
- }
- const fixturePath = join(targetRepo, providerSmoke.cursor.fixture);
- const intentionalIgnore = auditEvents.some((event) =>
- event.event === 'preToolUse'
- && event.file === fixturePath
- && event.skipped === 'config-ignore-file'
- );
- if (existsSync(fixturePath)) {
- const fixtureContent = readFileSync(fixturePath, 'utf8');
- if (/border-left\s*:\s*[2-9]\d*px/i.test(fixtureContent)) {
- if (!intentionalIgnore || !/ignoreFiles|ignore-file/i.test(evidence)) {
- throw new Error('Cursor provider left the blocked side-tab fixture on disk without an explicit Impeccable ignore-file escape hatch');
- }
- }
+ if (!auditEvents.some((event) => event.harness === 'cursor' && event.emitted === true)) {
+ throw new Error('Cursor provider evidence lacks a cursor-harness audit entry that emitted additional_context');
}
- record('cursor provider', true, 'Cursor agent triggered preToolUse hook, blocked side-tab, and only proceeded through explicit ignore handling for the intentional fixture');
+ record('cursor provider', true, 'Cursor Write triggered the postToolUse hook and side-tab detection');
}
function ensureCursorAgent() {
@@ -904,6 +871,19 @@ function fontExceptionPrompt(provider, rel) {
].join(' ');
}
+// The envelope Cursor sends on postToolUse for an agent file edit
+// (docs/CLI-CONTRACT.md, Cursor hooks contract).
+function cursorPostToolUseEvent(conversationId, file) {
+ return {
+ conversation_id: conversationId,
+ session_id: conversationId,
+ hook_event_name: 'postToolUse',
+ workspace_roots: [targetRepo],
+ tool_name: 'Write',
+ tool_input: { file_path: file, content: readFileSync(file, 'utf8') },
+ };
+}
+
function postToolUseEvent(sessionId, file, toolName) {
return {
session_id: sessionId,
diff --git a/skill/reference/hooks.md b/skill/reference/hooks.md
index 6cd1b0d9d..625edf1f3 100644
--- a/skill/reference/hooks.md
+++ b/skill/reference/hooks.md
@@ -2,9 +2,9 @@
Manage the **design detector hook** for the current project.
-The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, Cursor, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
-The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
+The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its `stop` hook can only answer with a follow-up user message), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `impeccable context` asking for a single detector run at the end.
@@ -16,7 +16,7 @@ Manual `{{scripts_path}}/impeccable detect` scans use the same project filter co
Supported harnesses: Claude Code (`.claude/settings.local.json` for a project-scope install; `~/.claude/settings.json` for a user-scope install; a project hook moved into shared `.claude/settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), Cursor (`.cursor/hooks.json` in the project), Grok Build (`.grok/hooks/impeccable.json` in the project; requires `/hooks-trust` or `--trust`), and GitHub Copilot (`.github/hooks/impeccable.json` in the project, a team-shared committed file that both the Copilot CLI and the cloud agent read). For the Copilot CLI, repo-level hooks fire once `.github/hooks/impeccable.json` is committed to the repository's default branch.
-On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+On **Cursor**, the hook runs on `postToolUse` for the `Write` tool (every agent file edit) and returns its reminder as `additional_context`, which Cursor adds after the tool result. Projects set up before this ran a `preToolUse` gate (`hook-before-edit`) that blocked bad writes before they landed; that gate still works until `hooks on`, `impeccable update`, or `impeccable doctor --fix` moves the entry to `postToolUse`.
Gemini installs session and completion hooks in `.gemini/settings.json`, merged into the settings already there (comments are tolerated; a commented file is backed up to `settings.json.bak` before the rewrite, and a file that is not valid JSON is left alone). It does not install a per-edit detector hook. The `BeforeTool` hook only rewrites shell commands that run `build-phase`, and only on macOS and Linux; on Windows (where Gemini runs hooks through PowerShell) no session id reaches the shell, so a comp build is not tied to the session and the completion reminder stays silent.
@@ -104,7 +104,7 @@ Example whole-file exception, for a file that is out of scope entirely:
- Never modify `.impeccable/config.json` or `.impeccable/config.local.json` by hand from this command. Always go through `impeccable hooks` so writes stay validated and the file shape stays consistent. One exception: `detector.extensions` has no admin action, so when the user asks to cover a template stack, edit that one field in `.impeccable/config.json` directly and leave the rest of the file untouched.
- Do not edit the launcher or the binary behind `impeccable hook` and `impeccable hook-before-edit` from this flow. Those are skill plumbing.
-- Cursor can block a proposed write when the detector finds a real issue. Claude Code, Codex, and GitHub Copilot do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook never blocks an edit; it emits a post-edit reminder. (A Cursor project still on the old `preToolUse` gate can block a write until its manifest is migrated.) Disabling stops the reminders.
- The hook is bundled with the Impeccable skill. Project installs use `.claude/settings.local.json`, `.codex/hooks.json`, `.cursor/hooks.json`, `.github/hooks/impeccable.json`, and `.gemini/settings.json`; a user-scope Claude install uses `~/.claude/settings.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks. On GitHub Copilot, the CLI loads `.github/hooks/impeccable.json` once it is committed to the repository's default branch, and the cloud agent reads it from the repo directly.
## Failure modes
diff --git a/tests/cursor-plugin.test.mjs b/tests/cursor-plugin.test.mjs
index 588e1190c..a36e4f1ce 100644
--- a/tests/cursor-plugin.test.mjs
+++ b/tests/cursor-plugin.test.mjs
@@ -61,12 +61,13 @@ describe('Cursor native plugin', () => {
const relocated = path.join(root, 'installed plugin');
fs.renameSync(output, relocated);
const hooks = JSON.parse(fs.readFileSync(path.join(relocated, 'hooks/hooks.json')));
- assert.deepEqual(Object.keys(hooks.hooks), ['preToolUse']);
- const command = hooks.hooks.preToolUse[0].command.replaceAll('${CURSOR_PLUGIN_ROOT}', relocated);
+ assert.deepEqual(Object.keys(hooks.hooks), ['postToolUse']);
+ assert.equal(hooks.hooks.postToolUse[0].matcher, '^Write$');
+ const command = hooks.hooks.postToolUse[0].command.replaceAll('${CURSOR_PLUGIN_ROOT}', relocated);
const result = spawnSync('sh', ['-c', command], { cwd: root, input: '{"tool_name":"Edit"}\n', encoding: 'utf8' });
assert.equal(result.status, 2, result.stderr);
- assert.equal(result.stdout, `${fs.realpathSync(root)}\nhook-before-edit\n{"tool_name":"Edit"}\n`);
- assert.match(buildCursorHooksManifest().hooks.preToolUse[0].command, /\.cursor\/skills\/impeccable/);
+ assert.equal(result.stdout, `${fs.realpathSync(root)}\nhook\n{"tool_name":"Edit"}\n`);
+ assert.match(buildCursorHooksManifest().hooks.postToolUse[0].command, /\.cursor\/skills\/impeccable/);
});
it('does not add path prose to agents that do not use scripts', () => {
diff --git a/tests/hook-build.test.mjs b/tests/hook-build.test.mjs
index 365f3ab17..21fa79e79 100644
--- a/tests/hook-build.test.mjs
+++ b/tests/hook-build.test.mjs
@@ -158,18 +158,21 @@ describe('hook manifest builders', () => {
);
});
- it('builds one Cursor pre-write blocking hook', () => {
+ it('builds one Cursor post-edit hook on postToolUse', () => {
const manifest = buildCursorHooksManifest();
- const beforeEdit = manifest.hooks.preToolUse[0];
+ const afterEdit = manifest.hooks.postToolUse[0];
assert.equal(manifest.version, 1);
- assert.ok(Array.isArray(manifest.hooks.preToolUse));
- assert.equal(Object.keys(manifest.hooks).length, 1);
+ assert.deepEqual(Object.keys(manifest.hooks), ['postToolUse']);
+ // The before-edit gate is retired; afterFileEdit's response never reaches
+ // the agent, and Cursor's stop can only send a follow-up user turn (#1061).
+ assert.equal(manifest.hooks.preToolUse, undefined);
assert.equal(manifest.hooks.afterFileEdit, undefined);
assert.equal(manifest.hooks.stop, undefined);
assert.equal(manifest.hooks.sessionStart, undefined);
- expectCommand(beforeEdit.command, '.cursor/skills/impeccable/scripts', 'hook-before-edit');
- assert.equal(beforeEdit.timeout, 5);
+ assert.equal(afterEdit.matcher, '^Write$');
+ expectCommand(afterEdit.command, '.cursor/skills/impeccable/scripts');
+ assert.equal(afterEdit.timeout, 5);
});
it('builds GitHub Copilot repo-level hooks for the real detector hook', () => {
@@ -289,7 +292,11 @@ describe('generated hook artifacts in repo', { skip: SYNCED ? false : 'generated
it('root hook manifests exactly match the hook builders', () => {
assert.deepEqual(readJson('.claude/settings.json'), buildClaudeSettingsManifest());
- assert.deepEqual(readJson('.cursor/hooks.json'), buildCursorHooksManifest());
+ // Cursor moved from the preToolUse gate to postToolUse (#1061). The tracked
+ // copy is regenerated by the sync after merge, so until then it may still
+ // be the last release's gate manifest; anything else must match the builder.
+ const cursor = readJson('.cursor/hooks.json');
+ if (!cursor.hooks?.preToolUse) assert.deepEqual(cursor, buildCursorHooksManifest());
assert.deepEqual(readJson('.codex/hooks.json'), buildCodexHooksManifest());
assert.deepEqual(readJson('.github/hooks/impeccable.json'), buildGitHubHooksManifest());
});
@@ -302,12 +309,19 @@ describe('generated hook artifacts in repo', { skip: SYNCED ? false : 'generated
assert.ok(fs.existsSync(path.join(REPO_ROOT, '.claude/skills/impeccable/scripts')));
});
- it('Cursor project hooks reference only the pre-write runtime in .cursor/skills', () => {
+ it('Cursor project hooks reference the launcher in .cursor/skills', () => {
+ // The tracked manifest is release output, regenerated after merge, so it
+ // may still carry the retired preToolUse gate for one sync.
const manifest = readJson('.cursor/hooks.json');
- const beforeEdit = manifest.hooks.preToolUse[0];
+ const [event] = Object.keys(manifest.hooks);
assert.equal(Object.keys(manifest.hooks).length, 1);
- expectCommand(beforeEdit.command, '.cursor/skills/impeccable/scripts', 'hook-before-edit');
+ assert.ok(['postToolUse', 'preToolUse'].includes(event), event);
+ expectCommand(
+ manifest.hooks[event][0].command,
+ '.cursor/skills/impeccable/scripts',
+ event === 'postToolUse' ? 'hook' : 'hook-before-edit',
+ );
assert.ok(fs.existsSync(path.join(REPO_ROOT, '.cursor/skills/impeccable/scripts/impeccable')));
assert.equal(fs.existsSync(path.join(REPO_ROOT, '.cursor/skills/impeccable/scripts/hook-before-edit.mjs')), false);
});
diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.md
index 497e7712f..edf8e8947 100644
--- a/tests/oracle/DELTAS.md
+++ b/tests/oracle/DELTAS.md
@@ -7103,6 +7103,12 @@ Re-recorded 2026-10-21 after merging main (with `--list-rules`, #1064): `detect-
In stylesheet text `border-accent-on-rounded` took its radius from the three lines before and after the accent, so blank lines or an unrelated neighbour changed the finding. It now reads the accent's own rule scope and the rules tied to its selector in the file, the way `side-tab` does. A radius counts only when a declaration sets one (a mixin, `@apply` or a custom property does not), and markup still reads the line. New fixture `border-accent-blank-lines.css` and its cases `detect-fixture-json-border-accent-blank-lines-css` and `detect-fixture-text-border-accent-blank-lines-css` (five findings: the adjacent pair, the pair with five blank lines, the long block, the media query, a pseudo-element's split rules; the other-selector, custom-property, `@apply`, descendant and pseudo-element-radius rows are quiet). The directory and no-advisory sweeps (`detect-dir-json-all-fixtures`, `detect-dir-text-all-fixtures`, `detect-dir-quiet-all-fixtures`, `detect-no-advisory-json`, `detect-no-advisory-text`) and `detect-scope-layout-text` gain only that file: five findings in the JSON sweeps, the count moves 950 to 955, and the file count 57 to 58. Recorded from the binary and reviewed by hand; no other golden moved.
+## Recorded 2026-10-18: Cursor runs the post-edit hook (#1061)
+
+Cursor's manifest ran the design hook as a `preToolUse` write gate (`hook-before-edit`). It now runs the post-edit `hook` verb on `postToolUse` with `matcher: "^Write$"`, like the other harnesses; Cursor injects the reply's `additional_context` after the tool result (`docs/CLI-CONTRACT.md`, Cursor). `hook-before-edit` still works, so the `hbe-*` goldens did not move. Re-recorded from the binary and reviewed by hand: `hadmin-on`, `hadmin-on-twice`, `hadmin-off-then-status`, `hadmin-on-repairs-existing-manifest` and `hadmin-on-malformed-manifest-backup`, where only the written `.cursor/hooks.json` changes (event `preToolUse` to `postToolUse`, verb `hook-before-edit` to `hook`, the new `matcher`). New cases: `hadmin-on-migrates-cursor-gate` (the gate entry moves to `postToolUse`; a foreign `preToolUse` entry and a `stop` entry stay), `hook-harness-cursor-post-tool-use` (Cursor's full postToolUse envelope, `tool_input: { file_path, content }`, answered with `{"additional_context": ...}`), `doctor-cursor-gate-json` (one `auto` finding, `cursor-hook-pre-edit-gate`) and `doctor-cursor-gate-fix` (`--fix` rewrites the manifest in place to the post-edit entry, keeping the guarded launcher command).
+
+Recorded 2026-10-22, review round on #1069: new case `hook-duplicate-event-scans-once`, three `hook` steps in one workspace. The first Claude edit with `tool_use_id: toolu_dup` scans; the second, the same event as a second Impeccable hook would receive it, prints nothing (`skipped: duplicate-event`) and leaves the edit count at 1; a new tool call on another file scans. Recorded from the binary, reviewed by hand. No existing golden moved: no other case repeats a tool-call id in one workspace.
+
## Recorded 2026-10-20: text not presented at capture (corpus/round12-not-shown)
Round 12, branch 1 of observations-1006 section 6 (`docs/CLI-CONTRACT.md`, "Text not presented at capture"): an inert dialog an opaque layer buries, a 1px box that cuts its own overflow, a text-occlusion victim that paints no glyphs, text on a running marquee, frosted glass over text, a layer that holds most of a run's text, and the size, leading and measure rules under a cover that stays over the text. Every change is URL-engine behavior. The static engine measures no boxes and runs no hit tests, so no existing golden moved.
diff --git a/tests/oracle/cases/context.mjs b/tests/oracle/cases/context.mjs
index e3aa79d02..4e3f8e9ee 100644
--- a/tests/oracle/cases/context.mjs
+++ b/tests/oracle/cases/context.mjs
@@ -114,6 +114,11 @@ const sidecarOlder = (ws) => { touch(path.join(ws, 'DESIGN.md'), T_NEW); touch(p
// ctx-legacy carries `.impeccable-live.json` (gitignored in this repo, so it
// is written at stage time) and a DESIGN.md newer than its legacy sidecar.
+const cursorGateSetup = (ws) => {
+ write(ws, '.cursor/skills/impeccable/scripts/impeccable', '#!/bin/sh\n');
+ write(ws, '.cursor/hooks.json', JSON.stringify({ version: 1, hooks: { preToolUse: [{ command: '[ ! -f ".cursor/skills/impeccable/scripts/impeccable" ] || ".cursor/skills/impeccable/scripts/impeccable" hook-before-edit', timeout: 5 }] } }, null, 2) + '\n');
+};
+
const legacySetup = (ws) => {
write(ws, '.impeccable-live.json', JSON.stringify({ port: 4310, sessions: [] }, null, 2) + '\n');
sidecarOlder(ws);
@@ -457,6 +462,10 @@ const cases = [
{ id: 'doctor-monorepo-roots-match-nothing', verb: 'doctor', workspace: 'ctx-monorepo', setup: (ws) => write(ws, '.impeccable/config.json', JSON.stringify({ projectRoots: ['services/*'] }, null, 2) + '\n'), env: env() },
{ id: 'doctor-legacy-text', verb: 'doctor', workspace: 'ctx-legacy', setup: legacySetup, env: env(), files: IMPECCABLE_FILES },
{ id: 'doctor-legacy-json', verb: 'doctor', workspace: 'ctx-legacy', setup: legacySetup, args: ['--json'], env: env(), files: IMPECCABLE_FILES },
+ // A Cursor manifest still on the retired preToolUse gate is an `auto`
+ // finding; --fix moves the entry to postToolUse in place.
+ { id: 'doctor-cursor-gate-json', verb: 'doctor', workspace: 'ctx-product-only', setup: cursorGateSetup, args: ['--json'], env: env({ IMPECCABLE_PROVIDER_ID: 'cursor' }), files: ['.cursor/hooks.json'] },
+ { id: 'doctor-cursor-gate-fix', verb: 'doctor', workspace: 'ctx-product-only', setup: cursorGateSetup, args: ['--fix'], env: env({ IMPECCABLE_PROVIDER_ID: 'cursor' }), files: ['.cursor/hooks.json'] },
{ id: 'doctor-legacy-fix', verb: 'doctor', workspace: 'ctx-legacy', setup: legacySetup, args: ['--fix'], env: env(), files: IMPECCABLE_FILES },
{ id: 'doctor-legacy-fix-json', verb: 'doctor', workspace: 'ctx-legacy', setup: legacySetup, args: ['--fix', '--json'], env: env(), files: IMPECCABLE_FILES },
{ id: 'doctor-legacy-fix-twice', verb: 'doctor', workspace: 'ctx-legacy', setup: legacySetup, args: ['--fix'], env: env(), files: IMPECCABLE_FILES, steps: [{}, {}, { args: ['--json'] }] },
diff --git a/tests/oracle/cases/hooks.mjs b/tests/oracle/cases/hooks.mjs
index 63da30aa5..9acf2b2ed 100644
--- a/tests/oracle/cases/hooks.mjs
+++ b/tests/oracle/cases/hooks.mjs
@@ -98,6 +98,29 @@ export default [
{ id: 'hook-harness-github-apply-patch', verb: 'hook', workspace: 'hook-project', stdin: { sessionId: 'g1', cwd: WS, toolName: 'apply_patch', toolArgs: '*** Begin Patch\n*** Update File: src/components/Card.module.css\n@@\n-x\n+y\n*** End Patch' }, files: CACHE_FILES },
{ id: 'hook-harness-codex-apply-patch', verb: 'hook', workspace: 'hook-project', stdin: { session_id: 'c1', cwd: WS, hook_event_name: 'PostToolUse', tool_name: 'apply_patch', tool_input: { command: '*** Begin Patch\n*** Update File: src/components/Card.module.css\n@@\n-x\n+y\n*** End Patch' } }, files: CACHE_FILES },
{ id: 'hook-harness-cursor-shaped', verb: 'hook', workspace: 'hook-project', stdin: { conversation_id: 'cv1', workspace_roots: [WS], tool_name: 'Write', tool_input: { path: 'src/components/Card.module.css' } }, files: CACHE_FILES },
+ // The envelope Cursor 3.21 sends on postToolUse for an agent file edit
+ // (cursor-agent-exec): every edit is `tool_name: "Write"` with
+ // `tool_input: { file_path, content }`; the reply is `additional_context`.
+ {
+ id: 'hook-harness-cursor-post-tool-use', verb: 'hook', workspace: 'hook-project', files: CACHE_FILES,
+ stdin: {
+ conversation_id: 'cv1', generation_id: 'g1', session_id: 'cv1', hook_event_name: 'postToolUse',
+ cursor_version: '3.21.18', workspace_roots: [WS], user_email: null, transcript_path: null, model: 'composer-2',
+ tool_name: 'Write', tool_input: { file_path: `${WS}/src/components/Card.module.css`, content: '' },
+ tool_output: '{}', duration: 12, tool_use_id: 't1',
+ },
+ },
+ // Two Impeccable hooks for one edit (a plugin's and the project's): the
+ // second invocation of the same tool call finds the claim and stays silent;
+ // the next tool call scans again.
+ {
+ id: 'hook-duplicate-event-scans-once', workspace: 'hook-project', files: CACHE_FILES,
+ steps: [
+ { verb: 'hook', stdin: claudeEdit('src/components/Card.module.css', { tool_use_id: 'toolu_dup' }), env: { IMPECCABLE_HOOK_HARNESS: 'claude' } },
+ { verb: 'hook', stdin: claudeEdit('src/components/Card.module.css', { tool_use_id: 'toolu_dup' }) },
+ { verb: 'hook', stdin: claudeEdit('src/components/Card.tsx', { tool_use_id: 'toolu_next' }) },
+ ],
+ },
{ id: 'hook-harness-forced-github', verb: 'hook', workspace: 'hook-project', stdin: claudeEdit('src/components/Card.module.css'), env: { IMPECCABLE_HOOK_HARNESS: 'github' }, files: CACHE_FILES },
{ id: 'hook-audit-log', verb: 'hook', workspace: 'hook-project', stdin: claudeEdit('src/components/Card.module.css'), env: { IMPECCABLE_HOOK_LOG: `${WS}/.impeccable/audit.ndjson` }, files: CACHE_FILES },
{
@@ -276,6 +299,13 @@ export default [
setup: (ws) => { fs.mkdirSync(`${ws}/.claude`, { recursive: true }); fs.writeFileSync(`${ws}/.claude/settings.local.json`, JSON.stringify({ permissions: { allow: ['Bash(ls)'] }, hooks: { PostToolUse: [{ matcher: 'Edit', hooks: [{ type: 'command', command: 'node old/skills/impeccable/scripts/hook.mjs' }] }, { matcher: 'Write', hooks: [{ type: 'command', command: 'echo other' }] }] } }, null, 2) + '\n'); },
args: ['on'],
},
+ // The retired Cursor before-edit gate moves to postToolUse; the foreign
+ // preToolUse entry and the other event stay.
+ {
+ id: 'hadmin-on-migrates-cursor-gate', verb: 'hook-admin', workspace: 'hook-project', files: CACHE_FILES,
+ setup: (ws) => { fs.mkdirSync(`${ws}/.cursor`, { recursive: true }); fs.writeFileSync(`${ws}/.cursor/hooks.json`, JSON.stringify({ version: 1, hooks: { preToolUse: [{ command: './audit.sh', matcher: 'Shell' }, { command: '[ ! -f ".cursor/skills/impeccable/scripts/impeccable" ] || ".cursor/skills/impeccable/scripts/impeccable" hook-before-edit', timeout: 5 }], stop: [{ command: './notify.sh' }] } }, null, 2) + '\n'); },
+ args: ['on'],
+ },
{
id: 'hadmin-on-malformed-manifest-backup', verb: 'hook-admin', workspace: 'hook-project', files: [...CACHE_FILES, '.cursor/hooks.json.bak'],
setup: (ws) => { fs.mkdirSync(`${ws}/.cursor`, { recursive: true }); fs.writeFileSync(`${ws}/.cursor/hooks.json`, '{ broken'); },
diff --git a/tests/oracle/golden/doctor-cursor-gate-fix.json b/tests/oracle/golden/doctor-cursor-gate-fix.json
new file mode 100644
index 000000000..fbd682ab1
--- /dev/null
+++ b/tests/oracle/golden/doctor-cursor-gate-fix.json
@@ -0,0 +1,9 @@
+{
+ "stdout": "Impeccable doctor: <WS>\n\nautomatic (1):\n cursor-hook-pre-edit-gate [.cursor/hooks.json]\n .cursor/hooks.json still runs the design hook as Cursor's `preToolUse` write gate, which is retired. Cursor now runs it after each edit on `postToolUse` and hands the findings to the agent as context.\n → Move the entry to `postToolUse`: `impeccable doctor --fix`, `impeccable hooks on`, or the next `impeccable update` does it.\n\nApplied:\n Moved the design hook in .cursor/hooks.json from preToolUse to postToolUse.\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"postToolUse\": [\n {\n \"command\": \"[ ! -f \\\".cursor/skills/impeccable/scripts/impeccable\\\" ] || \\\".cursor/skills/impeccable/scripts/impeccable\\\" hook\",\n \"matcher\": \"^Write$\",\n \"timeout\": 5\n }\n ]\n }\n}\n"
+ }
+}
diff --git a/tests/oracle/golden/doctor-cursor-gate-json.json b/tests/oracle/golden/doctor-cursor-gate-json.json
new file mode 100644
index 000000000..694ccc2e7
--- /dev/null
+++ b/tests/oracle/golden/doctor-cursor-gate-json.json
@@ -0,0 +1,9 @@
+{
+ "stdout": "{\n \"projectRoot\": \"<WS>\",\n \"repoRoot\": \"<WS>\",\n \"isMonorepo\": false,\n \"productPath\": \"PRODUCT.md\",\n \"designPath\": null,\n \"platform\": \"web\",\n \"ruleRegistryAvailable\": true,\n \"findings\": [\n {\n \"id\": \"cursor-hook-pre-edit-gate\",\n \"artifact\": \"hook manifest\",\n \"path\": \".cursor/hooks.json\",\n \"severity\": \"auto\",\n \"summary\": \".cursor/hooks.json still runs the design hook as Cursor's `preToolUse` write gate, which is retired. Cursor now runs it after each edit on `postToolUse` and hands the findings to the agent as context.\",\n \"fix\": \"Move the entry to `postToolUse`: `impeccable doctor --fix`, `impeccable hooks on`, or the next `impeccable update` does it.\"\n }\n ],\n \"workspaces\": []\n}\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"preToolUse\": [\n {\n \"command\": \"[ ! -f \\\".cursor/skills/impeccable/scripts/impeccable\\\" ] || \\\".cursor/skills/impeccable/scripts/impeccable\\\" hook-before-edit\",\n \"timeout\": 5\n }\n ]\n }\n}\n"
+ }
+}
diff --git a/tests/oracle/golden/hadmin-off-then-status.json b/tests/oracle/golden/hadmin-off-then-status.json
index 4e0fdda80..3077c2a50 100644
--- a/tests/oracle/golden/hadmin-off-then-status.json
+++ b/tests/oracle/golden/hadmin-off-then-status.json
@@ -27,7 +27,7 @@
],
"files": {
".claude/settings.local.json": "{\n \"description\": \"Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.\",\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"matcher\": \"Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 5,\n \"statusMessage\": \"Checking UI changes\"\n }\n ]\n }\n ],\n \"Stop\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 30,\n \"statusMessage\": \"Design deep pass\"\n }\n ]\n }\n ]\n }\n}\n",
- ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"preToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook-before-edit\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"postToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook\",\n \"matcher\": \"^Write$\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
".impeccable/config.json": "{\n \"hook\": {\n \"enabled\": true,\n \"limits\": {\n \"maxFindings\": 5,\n \"maxChars\": 8000\n }\n }\n}\n",
".impeccable/config.local.json": "{\n \"hook\": {\n \"consent\": \"accepted\"\n }\n}\n"
}
diff --git a/tests/oracle/golden/hadmin-on-malformed-manifest-backup.json b/tests/oracle/golden/hadmin-on-malformed-manifest-backup.json
index b05f2fffd..e8b577c9e 100644
--- a/tests/oracle/golden/hadmin-on-malformed-manifest-backup.json
+++ b/tests/oracle/golden/hadmin-on-malformed-manifest-backup.json
@@ -5,7 +5,7 @@
"signal": null,
"files": {
".claude/settings.local.json": "{\n \"description\": \"Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.\",\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"matcher\": \"Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 5,\n \"statusMessage\": \"Checking UI changes\"\n }\n ]\n }\n ],\n \"Stop\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 30,\n \"statusMessage\": \"Design deep pass\"\n }\n ]\n }\n ]\n }\n}\n",
- ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"preToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook-before-edit\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"postToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook\",\n \"matcher\": \"^Write$\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
".cursor/hooks.json.bak": "{ broken",
".impeccable/config.json": "{\n \"hook\": {\n \"enabled\": true,\n \"limits\": {\n \"maxFindings\": 5,\n \"maxChars\": 8000\n }\n }\n}\n",
".impeccable/config.local.json": "{\n \"hook\": {\n \"consent\": \"accepted\"\n }\n}\n"
diff --git a/tests/oracle/golden/hadmin-on-migrates-cursor-gate.json b/tests/oracle/golden/hadmin-on-migrates-cursor-gate.json
new file mode 100644
index 000000000..8ad59a9f9
--- /dev/null
+++ b/tests/oracle/golden/hadmin-on-migrates-cursor-gate.json
@@ -0,0 +1,12 @@
+{
+ "stdout": "Design hook enabled for this project (wrote .impeccable/config.json). Recorded local hook consent in .impeccable/config.local.json. Installed or repaired hook manifests for: .claude, .cursor.\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".claude/settings.local.json": "{\n \"description\": \"Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.\",\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"matcher\": \"Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 5,\n \"statusMessage\": \"Checking UI changes\"\n }\n ]\n }\n ],\n \"Stop\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 30,\n \"statusMessage\": \"Design deep pass\"\n }\n ]\n }\n ]\n }\n}\n",
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"preToolUse\": [\n {\n \"command\": \"./audit.sh\",\n \"matcher\": \"Shell\"\n }\n ],\n \"stop\": [\n {\n \"command\": \"./notify.sh\"\n }\n ],\n \"postToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook\",\n \"matcher\": \"^Write$\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
+ ".impeccable/config.json": "{\n \"hook\": {\n \"enabled\": true,\n \"limits\": {\n \"maxFindings\": 5,\n \"maxChars\": 8000\n }\n }\n}\n",
+ ".impeccable/config.local.json": "{\n \"hook\": {\n \"consent\": \"accepted\"\n }\n}\n"
+ }
+}
diff --git a/tests/oracle/golden/hadmin-on-repairs-existing-manifest.json b/tests/oracle/golden/hadmin-on-repairs-existing-manifest.json
index 29d655e94..3ff888961 100644
--- a/tests/oracle/golden/hadmin-on-repairs-existing-manifest.json
+++ b/tests/oracle/golden/hadmin-on-repairs-existing-manifest.json
@@ -5,7 +5,7 @@
"signal": null,
"files": {
".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(ls)\"\n ]\n },\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"matcher\": \"Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"echo other\"\n }\n ]\n },\n {\n \"matcher\": \"Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 5,\n \"statusMessage\": \"Checking UI changes\"\n }\n ]\n }\n ],\n \"Stop\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 30,\n \"statusMessage\": \"Design deep pass\"\n }\n ]\n }\n ]\n },\n \"description\": \"Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.\"\n}\n",
- ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"preToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook-before-edit\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"postToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook\",\n \"matcher\": \"^Write$\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
".impeccable/config.json": "{\n \"hook\": {\n \"enabled\": true,\n \"limits\": {\n \"maxFindings\": 5,\n \"maxChars\": 8000\n }\n }\n}\n",
".impeccable/config.local.json": "{\n \"hook\": {\n \"consent\": \"accepted\"\n }\n}\n"
}
diff --git a/tests/oracle/golden/hadmin-on-twice.json b/tests/oracle/golden/hadmin-on-twice.json
index 9ca007343..756c09ecd 100644
--- a/tests/oracle/golden/hadmin-on-twice.json
+++ b/tests/oracle/golden/hadmin-on-twice.json
@@ -21,7 +21,7 @@
],
"files": {
".claude/settings.local.json": "{\n \"description\": \"Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.\",\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"matcher\": \"Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 5,\n \"statusMessage\": \"Checking UI changes\"\n }\n ]\n }\n ],\n \"Stop\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 30,\n \"statusMessage\": \"Design deep pass\"\n }\n ]\n }\n ]\n }\n}\n",
- ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"preToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook-before-edit\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"postToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook\",\n \"matcher\": \"^Write$\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
".impeccable/config.json": "{\n \"hook\": {\n \"enabled\": true,\n \"limits\": {\n \"maxFindings\": 5,\n \"maxChars\": 8000\n }\n }\n}\n",
".impeccable/config.local.json": "{\n \"hook\": {\n \"consent\": \"accepted\"\n }\n}\n"
}
diff --git a/tests/oracle/golden/hadmin-on.json b/tests/oracle/golden/hadmin-on.json
index 7d92f520b..3a193b316 100644
--- a/tests/oracle/golden/hadmin-on.json
+++ b/tests/oracle/golden/hadmin-on.json
@@ -5,7 +5,7 @@
"signal": null,
"files": {
".claude/settings.local.json": "{\n \"description\": \"Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.\",\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"matcher\": \"Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 5,\n \"statusMessage\": \"Checking UI changes\"\n }\n ]\n }\n ],\n \"Stop\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\",\n \"timeout\": 30,\n \"statusMessage\": \"Design deep pass\"\n }\n ]\n }\n ]\n }\n}\n",
- ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"preToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook-before-edit\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
+ ".cursor/hooks.json": "{\n \"version\": 1,\n \"hooks\": {\n \"postToolUse\": [\n {\n \"command\": \"\\\".cursor/skills/impeccable/scripts/impeccable\\\" hook\",\n \"matcher\": \"^Write$\",\n \"timeout\": 5\n }\n ]\n }\n}\n",
".impeccable/config.json": "{\n \"hook\": {\n \"enabled\": true,\n \"limits\": {\n \"maxFindings\": 5,\n \"maxChars\": 8000\n }\n }\n}\n",
".impeccable/config.local.json": "{\n \"hook\": {\n \"consent\": \"accepted\"\n }\n}\n"
}
diff --git a/tests/oracle/golden/hook-duplicate-event-scans-once.json b/tests/oracle/golden/hook-duplicate-event-scans-once.json
new file mode 100644
index 000000000..06e56465a
--- /dev/null
+++ b/tests/oracle/golden/hook-duplicate-event-scans-once.json
@@ -0,0 +1,25 @@
+{
+ "steps": [
+ {
+ "stdout": "{\"hookSpecificOutput\":{\"hookEventName\":\"PostToolUse\",\"additionalContext\":\"[impeccable@1] Design hook findings requiring review in src/components/Card.module.css (1 issue(s)):\\n- L2 [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": "",
+ "stderr": "",
+ "exit": 0,
+ "signal": null
+ },
+ {
+ "stdout": "{\"hookSpecificOutput\":{\"hookEventName\":\"PostToolUse\",\"additionalContext\":\"[impeccable@1] Design hook scanned src/components/Card.module.css. Still has 1 finding(s) flagged earlier this session (gradient-text:2). Handle them before finalizing — the previous reminder still applies.\"}}",
+ "stderr": "",
+ "exit": 0,
+ "signal": null
+ }
+ ],
+ "files": {
+ ".impeccable/hook.cache.json": "{\"version\":1,\"sessions\":{\"s1\":{\"updatedAt\": <EPOCH>,\"files\":{\"<WS>/src/components/Card.module.css\":{\"editCount\":1,\"findings\":[\"gradient-text:2\"]},\"<WS>/src/components/Card.tsx\":{\"editCount\":1,\"findings\":[],\"cleanAcked\":true}},\"footerShown\":true}}}"
+ }
+}
diff --git a/tests/oracle/golden/hook-harness-cursor-post-tool-use.json b/tests/oracle/golden/hook-harness-cursor-post-tool-use.json
new file mode 100644
index 000000000..55a92f774
--- /dev/null
+++ b/tests/oracle/golden/hook-harness-cursor-post-tool-use.json
@@ -0,0 +1,9 @@
+{
+ "stdout": "{\"additional_context\":\"[impeccable@1] Design hook findings requiring review in src/components/Card.module.css (2 issue(s)):\\n- L1 [side-tab] 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.\\n- L2 [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,
+ "files": {
+ ".impeccable/hook.cache.json": "{\"version\":1,\"sessions\":{\"cv1\":{\"updatedAt\": <EPOCH>,\"files\":{\"<WS>/src/components/Card.module.css\":{\"editCount\":1,\"findings\":[\"side-tab:1\",\"gradient-text:2\"]}},\"footerShown\":true}}}"
+ }
+}