Skip to content

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

JavaScript

Fix Claude user-scope hook installation (#986)

Paul Bakaus86adb04144d3
diff --git a/crates/common/src/fsx.rs b/crates/common/src/fsx.rs
new file mode 100644
index 000000000..7928a3671
--- /dev/null
+++ b/crates/common/src/fsx.rs
@@ -0,0 +1,164 @@
+//! Filesystem helpers shared by the verb crates.
+
+use std::path::{Path, PathBuf};
+
+/// Replace `path` with `bytes` atomically: write a sibling temp file, then
+/// rename it over the target, so a crash or a full disk never leaves a
+/// truncated file behind. A symlinked target (a dotfiles checkout of
+/// `~/.claude/settings.json`) is resolved first, so the link stays in place
+/// and the file it points at is the one replaced. An existing file's
+/// permissions carry over to the replacement.
+pub fn write_atomic(path: impl AsRef<Path>, bytes: &[u8]) -> std::io::Result<()> {
+ let path = path.as_ref();
+ let target = resolve_write_target(path);
+ let dir = match target.parent() {
+ Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(),
+ _ => PathBuf::from("."),
+ };
+ let name = target
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "file".into());
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.subsec_nanos())
+ .unwrap_or(0);
+ let temp = dir.join(format!(".{name}.{}.{nanos}.tmp", std::process::id()));
+ let result = (|| {
+ // A dangling link can point into a directory that does not exist yet
+ // (a first-time dotfiles checkout); callers only create the link's own
+ // parent.
+ std::fs::create_dir_all(&dir)?;
+ std::fs::write(&temp, bytes)?;
+ if let Ok(meta) = std::fs::metadata(&target) {
+ let _ = std::fs::set_permissions(&temp, meta.permissions());
+ }
+ std::fs::rename(&temp, &target)
+ })();
+ if result.is_err() {
+ let _ = std::fs::remove_file(&temp);
+ }
+ result
+}
+
+/// The file a write to `path` should land in. An existing target resolves
+/// through `canonicalize`. A symlink whose destination does not exist yet
+/// (a dotfiles link to a file not created) cannot be canonicalized, so its
+/// chain is followed with `read_link`, each relative hop resolved against the
+/// link's own directory, up to a bound that stops a cycle. Anything else is
+/// written in place.
+fn resolve_write_target(path: &Path) -> PathBuf {
+ if let Ok(real) = std::fs::canonicalize(path) {
+ return real;
+ }
+ const MAX_HOPS: usize = 40;
+ let mut current = path.to_path_buf();
+ for _ in 0..MAX_HOPS {
+ let is_link = std::fs::symlink_metadata(&current)
+ .map(|m| m.file_type().is_symlink())
+ .unwrap_or(false);
+ if !is_link {
+ return current;
+ }
+ let Ok(next) = std::fs::read_link(&current) else {
+ return current;
+ };
+ current = if next.is_absolute() {
+ next
+ } else {
+ current.parent().map(|p| p.join(&next)).unwrap_or(next)
+ };
+ }
+ // A cycle or an absurd chain: leave the link alone rather than guess.
+ path.to_path_buf()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tmp(tag: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!(
+ "impeccable-fsx-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ #[test]
+ fn writes_new_and_replaces_existing() {
+ let d = tmp("replace");
+ let f = d.join("a.json");
+ write_atomic(&f, b"one").unwrap();
+ write_atomic(&f, b"two").unwrap();
+ assert_eq!(std::fs::read_to_string(&f).unwrap(), "two");
+ let leftovers: Vec<_> = std::fs::read_dir(&d).unwrap().collect();
+ assert_eq!(leftovers.len(), 1, "temp file left behind");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn keeps_a_symlinked_target_linked() {
+ let d = tmp("symlink");
+ let real = d.join("real.json");
+ let link = d.join("link.json");
+ std::fs::write(&real, b"old").unwrap();
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+ write_atomic(&link, b"new").unwrap();
+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
+ assert_eq!(std::fs::read_to_string(&real).unwrap(), "new");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn creates_the_destination_of_a_dangling_link_chain() {
+ let d = tmp("dangling");
+ std::fs::create_dir_all(d.join("dotfiles")).unwrap();
+ let link = d.join("link.json");
+ let hop = d.join("dotfiles/hop.json");
+ // Relative hops: `link.json -> dotfiles/hop.json -> real.json`, the
+ // second resolved against `dotfiles/`, and `real.json` not created yet.
+ std::os::unix::fs::symlink("dotfiles/hop.json", &link).unwrap();
+ std::os::unix::fs::symlink("real.json", &hop).unwrap();
+ write_atomic(&link, b"new").unwrap();
+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
+ assert!(std::fs::symlink_metadata(&hop).unwrap().file_type().is_symlink());
+ assert_eq!(std::fs::read_to_string(d.join("dotfiles/real.json")).unwrap(), "new");
+ assert_eq!(std::fs::read_to_string(&link).unwrap(), "new");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn creates_the_missing_directory_of_a_dangling_link() {
+ let d = tmp("dangling-dir");
+ let link = d.join("settings.json");
+ // `settings.json -> dotfiles/claude/settings.json`, with `dotfiles/claude/` not created yet.
+ std::os::unix::fs::symlink("dotfiles/claude/settings.json", &link).unwrap();
+ write_atomic(&link, b"new").unwrap();
+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
+ assert_eq!(std::fs::read_to_string(d.join("dotfiles/claude/settings.json")).unwrap(), "new");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn leaves_a_symlink_cycle_alone() {
+ let d = tmp("cycle");
+ let a = d.join("a.json");
+ let b = d.join("b.json");
+ std::os::unix::fs::symlink(&b, &a).unwrap();
+ std::os::unix::fs::symlink(&a, &b).unwrap();
+ // Replaces the link itself rather than looping forever.
+ write_atomic(&a, b"x").unwrap();
+ assert_eq!(std::fs::read_to_string(&a).unwrap(), "x");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+}
diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs
index a9cdc6783..82519e2fc 100644
--- a/crates/common/src/lib.rs
+++ b/crates/common/src/lib.rs
@@ -6,6 +6,7 @@
//! `io.stdout` / `io.stderr`, reads `io.stdin()` lazily, and returns the exit
//! code. Only the `cli` binary calls `std::process::exit`.
+pub mod fsx;
pub mod git;
pub mod jsp;
pub mod proc;
diff --git a/crates/context/src/context_cli.rs b/crates/context/src/context_cli.rs
index 354411ff9..8bed3af19 100644
--- a/crates/context/src/context_cli.rs
+++ b/crates/context/src/context_cli.rs
@@ -102,6 +102,16 @@ pub fn automatic_hook_mode(ctx: &Ctx, cwd: &str, env: &Env, provider: &Provider)
}
}
}
+ if provider.id == "claude-code" {
+ let user_settings = jsp::join(&[&crate::util::homedir(env), ".claude", "settings.json"]);
+ if let Some(raw) = read_json(&user_settings) {
+ if let Some(hooks) = raw.get("hooks") {
+ if crate::staleness::js_truthy(hooks) && value_has_hook_marker(hooks) {
+ return "stop";
+ }
+ }
+ }
+ }
"none"
}
@@ -739,6 +749,83 @@ mod skill_version_tests {
}
}
+#[cfg(test)]
+mod user_scope_hook_tests {
+ use super::automatic_hook_mode;
+ use crate::context::Ctx;
+ use crate::provider::Provider;
+ use crate::util::Env;
+
+ #[test]
+ fn claude_user_settings_supply_automatic_hook_coverage() {
+ let root = std::env::temp_dir().join(format!(
+ "impeccable-user-hook-context-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
+ ));
+ let project = root.join("project");
+ let home = root.join("home");
+ std::fs::create_dir_all(project.join(".git")).unwrap();
+ let launcher = home.join(".claude/skills/impeccable/scripts/impeccable");
+ std::fs::create_dir_all(launcher.parent().unwrap()).unwrap();
+ std::fs::write(&launcher, "#!/bin/sh\n").unwrap();
+ let settings = home.join(".claude/settings.json");
+ std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
+ std::fs::write(
+ settings,
+ serde_json::json!({
+ "hooks": {
+ "PostToolUse": [{
+ "hooks": [{
+ "type": "command",
+ "command": format!("\"{}\" hook", launcher.to_string_lossy()),
+ }],
+ }],
+ },
+ })
+ .to_string(),
+ )
+ .unwrap();
+
+ let project = project.to_string_lossy().into_owned();
+ let home = home.to_string_lossy().into_owned();
+ let ctx = Ctx {
+ has_product: false,
+ product: None,
+ product_path: None,
+ has_design: false,
+ design: None,
+ design_path: None,
+ context_dir: project.clone(),
+ product_context_dir: None,
+ design_context_dir: None,
+ has_surface_brief: false,
+ surface_brief: None,
+ surface_brief_path: None,
+ surface_brief_reason: "none",
+ surface_brief_candidates: vec![],
+ has_visual_implementation: false,
+ platform: None,
+ project_root: project.clone(),
+ repo_root: project.clone(),
+ is_monorepo: false,
+ };
+ let provider = Provider {
+ id: "claude-code".to_string(),
+ command_prefix: "/".to_string(),
+ command: "/impeccable".to_string(),
+ skill_dir: None,
+ self_cmd: "impeccable".to_string(),
+ };
+ let mut env = Env::new();
+ env.insert("HOME".to_string(), home.clone());
+ env.insert("USERPROFILE".to_string(), home);
+
+ assert_eq!(automatic_hook_mode(&ctx, &project, &env, &provider), "stop");
+ let _ = std::fs::remove_dir_all(root);
+ }
+}
+
#[cfg(test)]
mod worktree_hook_tests {
use super::*;
diff --git a/crates/context/src/doctor.rs b/crates/context/src/doctor.rs
index b73f7e9d9..7f1da9344 100644
--- a/crates/context/src/doctor.rs
+++ b/crates/context/src/doctor.rs
@@ -97,7 +97,8 @@ fn collect(cwd: &str, target: &TargetOptions, env: &Env, provider_id: &str) -> R
findings.extend(boot.build_path);
findings.extend(check_detector_ignores(&project_root, known.as_deref()));
findings.extend(boot.surface_briefs);
- findings.extend(check_hook_installation(&project_root, Some(&ctx.repo_root), provider_id));
+ let home = crate::util::homedir(env);
+ findings.extend(check_hook_installation(&project_root, Some(&ctx.repo_root), provider_id, Some(&home)));
findings.extend(check_legacy_live_state(&project_root));
findings.extend(boot.project_roots);
findings.extend(ws_findings);
diff --git a/crates/context/src/staleness_deep.rs b/crates/context/src/staleness_deep.rs
index fb3ea4622..e1ef195d1 100644
--- a/crates/context/src/staleness_deep.rs
+++ b/crates/context/src/staleness_deep.rs
@@ -236,16 +236,37 @@ fn resolve_hook_script_path(token: &str, root: &str) -> Option<String> {
}
/// JS: checkHookInstallation
-pub fn check_hook_installation(project_root: &str, repo_root: Option<&str>, provider_id: &str) -> Vec<Finding> {
+pub fn check_hook_installation(
+ project_root: &str,
+ repo_root: Option<&str>,
+ provider_id: &str,
+ user_root: Option<&str>,
+) -> Vec<Finding> {
let mut out = Vec::new();
let manifests = crate::context_cli::hook_manifests_for(provider_id);
if manifests.is_empty() {
return out;
}
- let roots = unique_roots(project_root, repo_root);
+ let project_roots = unique_roots(project_root, repo_root);
+ let mut manifest_roots = project_roots.clone();
+ let mut user_manifest_root: Option<String> = None;
+ if provider_id == "claude-code" {
+ if let Some(root) = user_root.filter(|root| !root.is_empty()) {
+ let root = jsp::resolve(root, &[]);
+ if !manifest_roots.contains(&root) {
+ user_manifest_root = Some(root.clone());
+ manifest_roots.push(root);
+ }
+ }
+ }
let mut installed_at: Option<String> = None;
- for root in &roots {
- for rel in manifests {
+ for root in &manifest_roots {
+ let root_manifests: &[&str] = if user_manifest_root.as_deref() == Some(root.as_str()) {
+ &[".claude/settings.json"]
+ } else {
+ manifests
+ };
+ for rel in root_manifests {
let mp = jsp::join(&[root, rel]);
let Some(raw) = read_json(&mp) else { continue };
let Some(hooks) = raw.get("hooks") else { continue };
@@ -285,7 +306,7 @@ pub fn check_hook_installation(project_root: &str, repo_root: Option<&str>, prov
}
}
if let Some(ia) = installed_at {
- for root in &roots {
+ for root in &project_roots {
for name in ["config.json", "config.local.json"] {
let cp = jsp::join(&[root, ".impeccable", name]);
let Some(raw) = read_json(&cp) else { continue };
@@ -473,7 +494,7 @@ mod tests {
".claude/settings.local.json",
r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
);
- assert!(check_hook_installation(&root, None, "claude-code").is_empty());
+ assert!(check_hook_installation(&root, None, "claude-code", None).is_empty());
// Launcher form pointing at a missing launcher: reported.
write(
@@ -481,7 +502,7 @@ mod tests {
".claude/settings.local.json",
r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.other/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
);
- let f = check_hook_installation(&root, None, "claude-code");
+ let f = check_hook_installation(&root, None, "claude-code", None);
assert_eq!(f.len(), 1, "{f:?}");
assert_eq!(f[0].id, "hook-script-missing");
@@ -491,10 +512,54 @@ mod tests {
".claude/settings.local.json",
r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"node \"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs\""}]}]}}"#,
);
- let f = check_hook_installation(&root, None, "claude-code");
+ let f = check_hook_installation(&root, None, "claude-code", None);
assert_eq!(f.len(), 1, "{f:?}");
write(&root, ".claude/skills/impeccable/scripts/hook.mjs", "");
- assert!(check_hook_installation(&root, None, "claude-code").is_empty());
+ assert!(check_hook_installation(&root, None, "claude-code", None).is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn user_scope_claude_hook_is_checked_from_home() {
+ let root = tmp();
+ let project = crate::jsp::join(&[&root, "project"]);
+ let home = crate::jsp::join(&[&root, "home"]);
+ std::fs::create_dir_all(&project).unwrap();
+ let launcher = crate::jsp::join(&[
+ &home,
+ ".claude",
+ "skills",
+ "impeccable",
+ "scripts",
+ "impeccable",
+ ]);
+ write(&home, ".claude/skills/impeccable/scripts/impeccable", "#!/bin/sh\n");
+ write(
+ &home,
+ ".claude/settings.json",
+ &serde_json::json!({
+ "hooks": {
+ "PostToolUse": [{
+ "hooks": [{
+ "type": "command",
+ "command": format!("\"{launcher}\" hook"),
+ }],
+ }],
+ },
+ })
+ .to_string(),
+ );
+ write(
+ &home,
+ ".claude/settings.local.json",
+ r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"/missing/user-local/impeccable\" hook"}]}]}}"#,
+ );
+ assert!(check_hook_installation(&project, None, "claude-code", Some(&home)).is_empty());
+
+ std::fs::remove_file(&launcher).unwrap();
+ let findings = check_hook_installation(&project, None, "claude-code", Some(&home));
+ assert_eq!(findings.len(), 1, "{findings:?}");
+ assert_eq!(findings[0].id, "hook-script-missing");
let _ = std::fs::remove_dir_all(&root);
}
}
diff --git a/crates/hook/src/admin.rs b/crates/hook/src/admin.rs
index 4091593e7..fc6fa6f8e 100644
--- a/crates/hook/src/admin.rs
+++ b/crates/hook/src/admin.rs
@@ -110,8 +110,7 @@ struct ManifestTarget {
user_settings: bool,
}
-fn claude_manifest() -> Value {
- let cmd = CLAUDE_HOOK_COMMAND;
+fn claude_manifest_for_command(cmd: &str) -> Value {
obj(vec![
(
"description",
@@ -135,6 +134,23 @@ fn claude_manifest() -> Value {
])
}
+/// The guarded absolute-launcher command a user-scope install writes into
+/// `~/.claude/settings.json` (the `update --user` form): POSIX single quotes,
+/// double quotes on Windows.
+fn user_claude_hook_command(skill_root: &str, win32: bool) -> String {
+ let launcher = jsp::join(&[skill_root, "scripts", "impeccable"]);
+ let q = if win32 {
+ serde_json::to_string(&launcher).unwrap_or_default()
+ } else {
+ format!("'{}'", launcher.replace('\'', "'\\''"))
+ };
+ format!("[ ! -f {q} ] || {q} hook")
+}
+
+fn claude_manifest() -> Value {
+ claude_manifest_for_command(CLAUDE_HOOK_COMMAND)
+}
+
fn agents_manifest() -> Value {
let cmd = AGENTS_HOOK_COMMAND;
let win = &impeccable_context::hook_markers::windows_launcher_hook_command(".agents/skills/impeccable/scripts/impeccable", "hook");
@@ -685,7 +701,7 @@ fn set_enabled(rt: &Runtime, cwd: &str, value: bool) -> Result<String, String> {
let mut consent = Map::new();
consent.insert("consent".into(), Value::from("accepted"));
let local_target = write_hook_config(rt, cwd, &consent, true)?;
- let repaired = repair_hook_manifests(cwd)?;
+ let repaired = repair_hook_manifests(rt, cwd)?;
let mut parts = vec![
format!(
"Design hook enabled for this project (wrote {}).",
@@ -737,7 +753,7 @@ struct Repaired {
}
/// JS: repairHookManifests(cwd)
-fn repair_hook_manifests(cwd: &str) -> Result<Repaired, String> {
+fn repair_hook_manifests(rt: &Runtime, cwd: &str) -> Result<Repaired, String> {
let mut result = Repaired {
written: vec![],
already: vec![],
@@ -745,19 +761,51 @@ fn repair_hook_manifests(cwd: &str) -> Result<Repaired, String> {
skipped: vec![],
};
for target in HOOK_MANIFEST_TARGETS {
- if !exists(&jsp::join(&[cwd, target.skill_rel])) {
- continue;
- }
- let dest = jsp::join(&[cwd, target.dest_rel]);
+ let mut dest = jsp::join(&[cwd, target.dest_rel]);
let shared_dest = target.shared_dest_rel.map(|s| jsp::join(&[cwd, s]));
- if let Some(sd) = &shared_dest {
+ let project_skill = jsp::join(&[cwd, target.skill_rel]);
+ let user_skill = jsp::join(&[&rt.homedir(), target.skill_rel]);
+ let (skill_root, user_scoped) = if exists(&project_skill) {
+ (project_skill, false)
+ } else if target.provider == ".claude"
+ // The launcher itself, not just the skill folder: a user hook
+ // naming a missing launcher is a no-op, and switching to it would
+ // prune a project hook that may still run another installation.
+ && exists(&jsp::join(&[&user_skill, "scripts", "impeccable"]))
+ && (file_has_impeccable_hook_marker(&dest)
+ || shared_dest.as_ref().is_some_and(|path| file_has_impeccable_hook_marker(path)))
+ {
+ (user_skill, true)
+ } else {
+ continue;
+ };
+ let mut user_settings = target.user_settings;
+ // The project manifest to prune once the user-scope hook is confirmed.
+ let mut prune_after: Option<String> = None;
+ if user_scoped {
+ // A user-scope skill gets its hook where a user-scope install
+ // writes it: `~/.claude/settings.json`, with the absolute launcher.
+ // In the project only the gitignored `settings.local.json` loses
+ // its Impeccable entries, and only after the user hook is written
+ // or already present: an unreadable user file is skipped, and the
+ // project hook is then the only one the machine has. The committed
+ // `settings.json` belongs to the team and is never rewritten with
+ // a home path.
+ prune_after = Some(dest.clone());
+ dest = jsp::join(&[&rt.homedir(), ".claude", "settings.json"]);
+ user_settings = true;
+ } else if let Some(sd) = &shared_dest {
if file_has_impeccable_hook_marker(sd) {
prune_impeccable_hook_from_manifest(&dest)?;
result.already.push(target.provider.to_string());
continue;
}
}
- let fresh = (target.manifest)();
+ let fresh = if user_scoped {
+ claude_manifest_for_command(&user_claude_hook_command(&skill_root, rt.win32))
+ } else {
+ (target.manifest)()
+ };
let mut next = fresh.clone();
let mut had_comments = false;
if exists(&dest) {
@@ -767,8 +815,8 @@ fn repair_hook_manifests(cwd: &str) -> Result<Repaired, String> {
next = merge_hook_manifests(&existing, &fresh);
}
// The user's whole settings file: never replace it.
- None if target.user_settings => {
- result.skipped.push(target.dest_rel.to_string());
+ None if user_settings => {
+ result.skipped.push(if user_scoped { dest.clone() } else { target.dest_rel.to_string() });
continue;
}
None => {
@@ -785,12 +833,22 @@ fn repair_hook_manifests(cwd: &str) -> Result<Repaired, String> {
None
};
if current.as_deref() == Some(serialized.as_str()) {
+ if let Some(project_manifest) = &prune_after {
+ prune_impeccable_hook_from_manifest(project_manifest)?;
+ }
result.already.push(target.provider.to_string());
continue;
}
backup_commented(&dest, had_comments)?;
std::fs::create_dir_all(jsp::dirname(&dest)).map_err(|e| e.to_string())?;
- std::fs::write(&dest, serialized).map_err(|e| e.to_string())?;
+ if user_settings {
+ impeccable_common::fsx::write_atomic(&dest, serialized.as_bytes()).map_err(|e| e.to_string())?;
+ } else {
+ std::fs::write(&dest, serialized).map_err(|e| e.to_string())?;
+ }
+ if let Some(project_manifest) = &prune_after {
+ prune_impeccable_hook_from_manifest(project_manifest)?;
+ }
result.written.push(target.provider.to_string());
}
Ok(result)
diff --git a/crates/hook/tests/hook_tests.rs b/crates/hook/tests/hook_tests.rs
index ec6b4137e..b9eb762cb 100644
--- a/crates/hook/tests/hook_tests.rs
+++ b/crates/hook/tests/hook_tests.rs
@@ -2326,6 +2326,203 @@ fn admin_on_writes_launcher_manifests_for_every_harness() {
assert!(out.ends_with("Hook manifests already installed for: .claude, .agents, .cursor, .github.\n"), "{out}");
}
+fn expected_user_claude_hook_command(home: &str) -> String {
+ let launcher = jsp::join(&[home, ".claude", "skills", "impeccable", "scripts", "impeccable"]);
+ let q = if cfg!(windows) {
+ serde_json::to_string(&launcher).unwrap()
+ } else {
+ format!("'{}'", launcher.replace('\'', "'\\''"))
+ };
+ format!("[ ! -f {q} ] || {q} hook")
+}
+
+#[test]
+fn admin_on_repairs_project_manifest_from_user_scope_claude_skill() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let home = t.0.join("home");
+ std::fs::create_dir_all(home.join(".claude/skills/impeccable/scripts")).unwrap();
+ std::fs::write(home.join(".claude/skills/impeccable/scripts/impeccable"), "#!/bin/sh\n").unwrap();
+ std::fs::write(home.join(".claude/settings.json"), r#"{"model":"claude-sonnet-5"}"#).unwrap();
+ t.write(
+ ".claude/settings.local.json",
+ r#"{"permissions":{"allow":["Bash(ls)"]},"hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"node \"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs\""}]}]}}"#,
+ );
+ let home_text = home.to_string_lossy().to_string();
+ let r = rt_with(&cwd, env(&[("HOME", &home_text), ("USERPROFILE", &home_text)]));
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ assert!(out.contains("Installed or repaired hook manifests for: .claude."), "{out}");
+ let user: Value =
+ serde_json::from_str(&std::fs::read_to_string(home.join(".claude/settings.json")).unwrap()).unwrap();
+ assert_eq!(user["model"], "claude-sonnet-5");
+ let command = user["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str().unwrap();
+ assert_eq!(command, expected_user_claude_hook_command(&home_text));
+ let local: Value = serde_json::from_str(&t.read(".claude/settings.local.json")).unwrap();
+ assert!(local.get("hooks").is_none(), "stale project hook was not pruned: {local}");
+ assert_eq!(local["permissions"]["allow"], json!(["Bash(ls)"]));
+
+ // Once the project copy is gone, a second run leaves the user file alone.
+ let before = std::fs::read_to_string(home.join(".claude/settings.json")).unwrap();
+ let (again, _, code) = admin_run(&r, &["on"]);
+ assert_eq!(code, 0, "{again}");
+ assert_eq!(std::fs::read_to_string(home.join(".claude/settings.json")).unwrap(), before);
+}
+
+#[test]
+fn admin_on_repairs_shared_project_manifest_from_user_scope_claude_skill() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let home = t.0.join("home");
+ std::fs::create_dir_all(home.join(".claude/skills/impeccable/scripts")).unwrap();
+ std::fs::write(home.join(".claude/skills/impeccable/scripts/impeccable"), "#!/bin/sh\n").unwrap();
+ let shared_original = r#"{"model":"claude-sonnet-5","hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"node \"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs\""}]}]}}"#;
+ t.write(".claude/settings.json", shared_original);
+ t.write(
+ ".claude/settings.local.json",
+ r#"{"permissions":{"allow":["Bash(ls)"]},"hooks":{"Stop":[{"hooks":[{"type":"command","command":"node old/skills/impeccable/scripts/hook.mjs"}]}]}}"#,
+ );
+ let home_text = home.to_string_lossy().to_string();
+ let r = rt_with(&cwd, env(&[("HOME", &home_text), ("USERPROFILE", &home_text)]));
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ assert!(out.contains("Installed or repaired hook manifests for: .claude."), "{out}");
+ // The hook lands in the user's own settings, with the absolute launcher.
+ let user: Value =
+ serde_json::from_str(&std::fs::read_to_string(home.join(".claude/settings.json")).unwrap()).unwrap();
+ let command = user["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str().unwrap();
+ assert_eq!(command, expected_user_claude_hook_command(&home_text));
+ let local: Value = serde_json::from_str(&t.read(".claude/settings.local.json")).unwrap();
+ assert!(local.get("hooks").is_none(), "local duplicate was not pruned: {local}");
+ assert_eq!(local["permissions"]["allow"], json!(["Bash(ls)"]));
+}
+
+/// Regression: a user-scope repair must never write a home path into the
+/// committed, team-shared `.claude/settings.json`.
+#[test]
+fn admin_on_user_scope_repair_leaves_committed_settings_byte_unchanged() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let home = t.0.join("home");
+ std::fs::create_dir_all(home.join(".claude/skills/impeccable/scripts")).unwrap();
+ std::fs::write(home.join(".claude/skills/impeccable/scripts/impeccable"), "#!/bin/sh\n").unwrap();
+ let shared_original = "{\n \"hooks\": {\"PostToolUse\": [{\"matcher\": \"Edit\", \"hooks\": [{\"type\": \"command\", \"command\": \"\\\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\\\" hook\"}]}]}\n}\n";
+ t.write(".claude/settings.json", shared_original);
+ let home_text = home.to_string_lossy().to_string();
+ let r = rt_with(&cwd, env(&[("HOME", &home_text), ("USERPROFILE", &home_text)]));
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ let shared = t.read(".claude/settings.json");
+ assert_eq!(shared, shared_original);
+ assert!(!shared.contains(&home_text), "home path leaked into the committed manifest: {shared}");
+ assert!(std::fs::read_to_string(home.join(".claude/settings.json")).unwrap().contains("impeccable"));
+}
+
+/// Regression: an unreadable `~/.claude/settings.json` is skipped, so the
+/// project hook must survive; pruning it first would leave no hook at all.
+#[test]
+fn admin_on_user_scope_keeps_project_hook_when_user_settings_are_invalid() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let home = t.0.join("home");
+ std::fs::create_dir_all(home.join(".claude/skills/impeccable/scripts")).unwrap();
+ std::fs::write(home.join(".claude/skills/impeccable/scripts/impeccable"), "#!/bin/sh\n").unwrap();
+ let broken = "{ \"model\": \"claude-sonnet-5\",, }";
+ std::fs::write(home.join(".claude/settings.json"), broken).unwrap();
+ let local_original = r#"{"hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#;
+ t.write(".claude/settings.local.json", local_original);
+ let home_text = home.to_string_lossy().to_string();
+ let r = rt_with(&cwd, env(&[("HOME", &home_text), ("USERPROFILE", &home_text)]));
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ assert!(out.contains("Skipped "), "{out}");
+ assert!(out.contains("not valid JSON"), "{out}");
+ assert_eq!(std::fs::read_to_string(home.join(".claude/settings.json")).unwrap(), broken);
+ assert_eq!(t.read(".claude/settings.local.json"), local_original);
+}
+
+/// Regression (PR #986 review): a user skill folder without its launcher is not
+/// a user-scope install `hooks on` can switch to. The project hook may still run
+/// another installation, so it stays, and `~/.claude/settings.json` is not written.
+#[test]
+fn admin_on_user_scope_without_launcher_keeps_project_hook() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let home = t.0.join("home");
+ std::fs::create_dir_all(home.join(".claude/skills/impeccable")).unwrap();
+ let local_original = r#"{"hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#;
+ t.write(".claude/settings.local.json", local_original);
+ let home_text = home.to_string_lossy().to_string();
+ let r = rt_with(&cwd, env(&[("HOME", &home_text), ("USERPROFILE", &home_text)]));
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ assert_eq!(t.read(".claude/settings.local.json"), local_original);
+ assert!(!home.join(".claude/settings.json").exists(), "{out}");
+}
+
+/// Regression (PR #986 review): a legacy `hook.mjs` entry already in
+/// `~/.claude/settings.json` is not a current user hook. It is replaced with
+/// the launcher form, and only then is the project hook pruned.
+#[test]
+fn admin_on_replaces_legacy_user_hook_before_pruning_project_hook() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let home = t.0.join("home");
+ std::fs::create_dir_all(home.join(".claude/skills/impeccable/scripts")).unwrap();
+ std::fs::write(home.join(".claude/skills/impeccable/scripts/impeccable"), "#!/bin/sh\n").unwrap();
+ std::fs::write(
+ home.join(".claude/settings.json"),
+ r#"{"model":"claude-sonnet-5","hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"node \"~/.claude/skills/impeccable/scripts/hook.mjs\""}]}]}}"#,
+ )
+ .unwrap();
+ t.write(
+ ".claude/settings.local.json",
+ r#"{"permissions":{"allow":["Bash(ls)"]},"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
+ );
+ let home_text = home.to_string_lossy().to_string();
+ let r = rt_with(&cwd, env(&[("HOME", &home_text), ("USERPROFILE", &home_text)]));
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ let user_text = std::fs::read_to_string(home.join(".claude/settings.json")).unwrap();
+ assert!(!user_text.contains("hook.mjs"), "legacy user hook survived: {user_text}");
+ let user: Value = serde_json::from_str(&user_text).unwrap();
+ assert_eq!(user["model"], "claude-sonnet-5");
+ let command = user["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str().unwrap();
+ assert_eq!(command, expected_user_claude_hook_command(&home_text));
+ let local: Value = serde_json::from_str(&t.read(".claude/settings.local.json")).unwrap();
+ assert!(local.get("hooks").is_none(), "duplicate project hook survived: {local}");
+}
+
+#[test]
+fn admin_on_does_not_repair_project_manifests_from_other_user_scope_skills() {
+ let t = Tmp::new();
+ let cwd = t.path();
+ let home = t.0.join("home");
+ std::fs::create_dir_all(home.join(".cursor/skills/impeccable")).unwrap();
+ let original = r#"{"version":1,"hooks":{"preToolUse":[{"command":".cursor/skills/impeccable/scripts/impeccable hook-before-edit"}]}}"#;
+ t.write(".cursor/hooks.json", original);
+ let home_text = home.to_string_lossy().to_string();
+ let r = rt_with(&cwd, env(&[("HOME", &home_text), ("USERPROFILE", &home_text)]));
+
+ let (out, _, code) = admin_run(&r, &["on"]);
+
+ assert_eq!(code, 0, "{out}");
+ assert!(out.contains("No installed provider skill folders found to repair."), "{out}");
+ assert_eq!(t.read(".cursor/hooks.json"), original);
+}
+
#[test]
fn admin_on_repairs_legacy_mjs_manifests_to_the_launcher_form() {
let t = Tmp::new();
diff --git a/crates/skills/src/commands.rs b/crates/skills/src/commands.rs
index ae6eb10d0..93f92dc07 100644
--- a/crates/skills/src/commands.rs
+++ b/crates/skills/src/commands.rs
@@ -8,7 +8,7 @@ use serde_json::Value;
use crate::bundle::{self, download};
use crate::engine_binary::install_engine_binaries;
-use crate::hook_manifest::{self, copy_provider_hooks, hook_installed_for_provider, HOOK_EXPLAINER};
+use crate::hook_manifest::{self, copy_provider_hooks, hook_installed_for_provider, hook_installed_for_provider_at_scope, HOOK_EXPLAINER};
use crate::prompt::{CheckboxOption, Prompt, RadioOption};
use crate::providers::*;
use crate::util::{self, pad_end, utf16_len, utf16_prefix};
@@ -589,7 +589,14 @@ fn install(flags: &[String], io: &mut Io) -> R<()> {
}
let mut updated = 0usize;
let missing_hook_targets: Vec<&'static str> = if want_hooks {
- hook_targets.iter().copied().filter(|p| !hook_installed_for_provider(&hook_root, p)).collect()
+ hook_targets
+ .iter()
+ .copied()
+ .filter(|p| {
+ let manifest_root = if scope == Scope::User && *p == ".claude" { &install_root } else { &hook_root };
+ !hook_installed_for_provider_at_scope(manifest_root, p, scope == Scope::User)
+ })
+ .collect()
} else {
Vec::new()
};
@@ -640,13 +647,21 @@ fn install(flags: &[String], io: &mut Io) -> R<()> {
}
let written_hook_targets = if !missing_hook_targets.is_empty() {
- copy_provider_hooks(&sys, &bdir, &hook_root, &missing_hook_targets, false, Some(&install_root))?
+ copy_provider_hooks(&sys, &bdir, &hook_root, &missing_hook_targets, false, Some(&install_root), None)?
} else {
Vec::new()
};
if !written_hook_targets.is_empty() {
out(io, &format!("Installed hooks into: {}", written_hook_targets.join(", ")));
}
+ // A repeat user-scope install whose user hook is already current
+ // never sends Claude through copy_provider_hooks, so the
+ // duplicate-hook cleanup that function ends with runs here as well.
+ // A legacy or dangling user hook is not current: it was rewritten
+ // above, and the cleanup itself re-checks before pruning.
+ if want_hooks && scope == Scope::User && hook_targets.contains(&".claude") {
+ hook_manifest::prune_duplicate_claude_hooks(&sys, &install_root, &hook_root)?;
+ }
// Self-heal any pre-launcher (`node .../hook.mjs`) manifest left by a
// v3 install into a present provider dir (triage E8). Independent of
@@ -702,7 +717,7 @@ fn install(flags: &[String], io: &mut Io) -> R<()> {
let agents = bundle::copy_provider_agents(&sys, &bundle_dir, &install_root, &targets, scope_opt)?;
bundle::copy_provider_commands(&sys, &bundle_dir, &install_root, &targets, scope_opt);
let hooks = if want_hooks {
- copy_provider_hooks(&sys, &bundle_dir, &hook_root, &targets, force, Some(&install_root))?
+ copy_provider_hooks(&sys, &bundle_dir, &hook_root, &targets, force, Some(&install_root), None)?
} else {
Vec::new()
};
@@ -831,7 +846,7 @@ fn update(flags: &[String], io: &mut Io) -> R<()> {
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)?;
let hook_targets = if want_hooks {
- copy_provider_hooks(&sys, &tmp_dir, &root, &copy_providers, force, None).map_err(Flow::Throw)?
+ copy_provider_hooks(&sys, &tmp_dir, &root, &copy_providers, force, None, Some(&project_root)).map_err(Flow::Throw)?
} else {
Vec::new()
};
@@ -887,7 +902,7 @@ fn update(flags: &[String], io: &mut Io) -> R<()> {
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)?;
let hook_targets = if want_hooks {
- copy_provider_hooks(&sys, &tmp_dir, &root, &providers, force, None).map_err(Flow::Throw)?
+ copy_provider_hooks(&sys, &tmp_dir, &root, &providers, force, None, 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 3527d0c7d..112dd9636 100644
--- a/crates/skills/src/hook_manifest.rs
+++ b/crates/skills/src/hook_manifest.rs
@@ -68,6 +68,17 @@ pub fn hook_artifacts_for_provider(bundle_dir: &str, root: &str, provider: &str)
.collect()
}
+fn hook_artifacts_for_install(bundle_dir: &str, root: &str, provider: &str, user_scope: bool) -> Vec<HookArtifact> {
+ if provider == ".claude" && user_scope {
+ return vec![HookArtifact {
+ src: jsp::join(&[bundle_dir, ".claude", "settings.json"]),
+ dest: jsp::join(&[root, ".claude", "settings.json"]),
+ shared_dest: None,
+ }];
+ }
+ hook_artifacts_for_provider(bundle_dir, root, provider)
+}
+
/// JS: expectedHookDests(root, providers)
pub fn expected_hook_dests(root: &str, providers: &[&str]) -> Vec<String> {
providers
@@ -321,8 +332,8 @@ fn backup_commented(path: &str, had_comments: bool) -> Result<(), String> {
/// A provider whose hook manifest is the user's whole settings file (model,
/// auth, MCP servers), so an unreadable one is never replaced wholesale.
-fn manifest_is_user_settings(provider: &str) -> bool {
- provider == ".gemini"
+fn manifest_is_user_settings(provider: &str, user_scope: bool) -> bool {
+ provider == ".gemini" || (provider == ".claude" && user_scope)
}
/// JS: hookInstalledForProvider(root, provider)
@@ -340,6 +351,60 @@ pub fn hook_installed_for_provider(root: &str, provider: &str) -> bool {
})
}
+/// User-scoped Claude hooks are loaded only from `settings.json`; the
+/// project-only `settings.local.json` path must not satisfy a global install.
+/// For that file, "installed" means current (`user_claude_hook_is_current`),
+/// not merely marked: a legacy `hook.mjs` entry or one naming a launcher that
+/// no longer exists must be rewritten, not counted.
+pub fn hook_installed_for_provider_at_scope(root: &str, provider: &str, user_scope: bool) -> bool {
+ if user_scope && provider == ".claude" {
+ return user_claude_hook_is_current(root);
+ }
+ hook_installed_for_provider(root, provider)
+}
+
+/// The command a user-scope install writes into `<home>/.claude/settings.json`:
+/// the guarded absolute launcher under `<home>/.claude/skills/impeccable`.
+pub fn user_claude_hook_command(home_root: &str, win32: bool) -> Option<String> {
+ let quoted = quoted_launcher_path(home_root, ".claude", true)?;
+ Some(hook_command(&quoted, ".claude", win32))
+}
+
+fn collect_impeccable_hook_commands<'a>(value: &'a Value, out: &mut Vec<&'a str>) {
+ match value {
+ Value::String(s) if is_impeccable_hook_command(s) => out.push(s),
+ Value::Array(a) => a.iter().for_each(|v| collect_impeccable_hook_commands(v, out)),
+ Value::Object(o) => o.values().for_each(|v| collect_impeccable_hook_commands(v, out)),
+ _ => {}
+ }
+}
+
+/// True only when `<home>/.claude/settings.json` parses, its launcher exists,
+/// and every Impeccable hook command in it is exactly the form this engine
+/// writes for a user-scope install. An Impeccable marker alone is not enough:
+/// a legacy `node .../hook.mjs` entry, or one naming a launcher that is gone,
+/// is a dead hook, and counting it would skip the rewrite and let the
+/// duplicate-hook cleanup delete the project hook that still works.
+pub fn user_claude_hook_is_current(home_root: &str) -> bool {
+ user_claude_hook_is_current_for(home_root, cfg!(windows))
+}
+
+/// `user_claude_hook_is_current` with the platform made explicit.
+pub fn user_claude_hook_is_current_for(home_root: &str, win32: bool) -> bool {
+ let Some(expected) = user_claude_hook_command(home_root, win32) else { return false };
+ let Some(launcher) = launcher_path(home_root, ".claude") else { return false };
+ if !util::exists(&launcher) {
+ return false;
+ }
+ let Some((Value::Object(map), _)) = read_manifest(&jsp::join(&[home_root, ".claude", "settings.json"])) else {
+ return false;
+ };
+ let Some(hooks @ (Value::Object(_) | Value::Array(_))) = map.get("hooks") else { return false };
+ let mut commands = Vec::new();
+ collect_impeccable_hook_commands(hooks, &mut commands);
+ !commands.is_empty() && commands.iter().all(|c| *c == expected)
+}
+
fn marker_in(entry: &Map<String, Value>, key: &str) -> bool {
entry.get(key).map(value_has_impeccable_hook_marker).unwrap_or(false)
}
@@ -468,11 +533,13 @@ fn json_parse_message(e: &serde_json::Error) -> String {
/// JS: copyProviderHooks(bundleDir, root, providers, {force, skillRoot}).
/// Returns the providers whose manifest was written (deduplicated, in order).
-pub fn copy_provider_hooks(sys: &crate::providers::Sys, bundle_dir: &str, root: &str, providers: &[&'static str], force: bool, skill_root: Option<&str>) -> Result<Vec<&'static str>, String> {
+pub fn copy_provider_hooks(sys: &crate::providers::Sys, bundle_dir: &str, root: &str, providers: &[&'static str], force: bool, skill_root: Option<&str>, project_root: Option<&str>) -> Result<Vec<&'static str>, String> {
let skill_root = skill_root.unwrap_or(root);
+ let user_scope = sys.is_home_dir(skill_root);
let mut written: Vec<&'static str> = Vec::new();
for provider in providers {
- for artifact in hook_artifacts_for_provider(bundle_dir, root, provider) {
+ let manifest_root = if user_scope && *provider == ".claude" { skill_root } else { root };
+ for artifact in hook_artifacts_for_install(bundle_dir, manifest_root, provider, user_scope) {
if !util::exists(&artifact.src) {
continue;
}
@@ -492,7 +559,7 @@ pub fn copy_provider_hooks(sys: &crate::providers::Sys, bundle_dir: &str, root:
backup_commented(&artifact.dest, had_comments)?;
next = merge_hook_manifests(&existing, &fresh);
}
- None if manifest_is_user_settings(provider) => {
+ None if manifest_is_user_settings(provider, user_scope) => {
return Err(format!("Existing settings file is not valid JSON: {}. It holds your other settings too, so it is never replaced; fix it and re-run.", artifact.dest));
}
None => {
@@ -505,15 +572,36 @@ pub fn copy_provider_hooks(sys: &crate::providers::Sys, bundle_dir: &str, root:
}
}
util::mkdir_p(&jsp::dirname(&artifact.dest))?;
- util::write_bytes(&artifact.dest, format!("{}\n", util::json_pretty(&next)).as_bytes())?;
+ // 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))?;
if !written.contains(provider) {
written.push(provider);
}
}
+ if user_scope && *provider == ".claude" {
+ prune_duplicate_claude_hooks(sys, skill_root, project_root.unwrap_or(root))?;
+ }
}
Ok(written)
}
+/// Once a user-scope Claude hook is in `<home>/.claude/settings.json`, the
+/// Impeccable entries in `settings.local.json` (the home one Claude never
+/// loads, and the project's gitignored one) only make the hook fire twice.
+/// Prunes them, and only when the user hook is confirmed current: a legacy or
+/// dangling user entry does not count. Runs after a fresh hook write and on a
+/// repeat install whose user hook is already current.
+pub fn prune_duplicate_claude_hooks(sys: &crate::providers::Sys, home_root: &str, project_root: &str) -> Result<(), String> {
+ if !user_claude_hook_is_current(home_root) {
+ return Ok(());
+ }
+ prune_impeccable_hook_from_manifest(&jsp::join(&[home_root, ".claude", "settings.local.json"]))?;
+ if !sys.is_home_dir(project_root) {
+ prune_impeccable_hook_from_manifest(&jsp::join(&[project_root, ".claude", "settings.local.json"]))?;
+ }
+ Ok(())
+}
+
/// Self-heal for the v3 -> launcher upgrade (triage E8): a present provider
/// dir whose hook manifest still names `node .../hook.mjs` points at a script
/// the launcher-era skill no longer ships, so the editor fires a dead command
diff --git a/crates/skills/tests/drift_ports_tests.rs b/crates/skills/tests/drift_ports_tests.rs
index b00b6c526..c2850a19a 100644
--- a/crates/skills/tests/drift_ports_tests.rs
+++ b/crates/skills/tests/drift_ports_tests.rs
@@ -56,6 +56,9 @@ fn create_fake_universal_bundle(root: &str, providers: &[&str]) -> String {
&format!("---\nname: impeccable\nversion: 9.9.9-local\n---\n\nLocal deterministic bundle for {provider}.\n"),
);
write(&format!("{skill_dir}/scripts/context.mjs"), "console.log(\"local bundle context\");\n");
+ // Real bundles ship the launcher; a user-scope Claude hook counts as
+ // current only when the launcher it names exists.
+ write(&format!("{skill_dir}/scripts/impeccable"), "#!/bin/sh\n");
}
if providers.contains(&".claude") {
write(
@@ -675,7 +678,8 @@ fn global_install_rewrites_grok_project_hooks_to_the_global_skill_path() {
}
// Launcher-era adaptation: the JS asserted the rewritten hook.mjs path;
// the engine writes the launcher form pointing at the same global root.
- assert!(manifest_names_launcher(&format!("{tmp}/.claude/settings.local.json"), &home, ".claude"));
+ assert!(manifest_names_launcher(&format!("{home}/.claude/settings.json"), &home, ".claude"));
+ assert!(!std::path::Path::new(&format!("{home}/.claude/settings.local.json")).exists());
assert!(manifest_names_launcher(&format!("{tmp}/.codex/hooks.json"), &home, ".agents"));
assert!(manifest_names_launcher(&format!("{tmp}/.cursor/hooks.json"), &home, ".cursor"));
let grok_manifest = format!("{tmp}/.grok/hooks/impeccable.json");
@@ -691,7 +695,189 @@ fn global_install_rewrites_grok_project_hooks_to_the_global_skill_path() {
std::fs::remove_dir_all(&root).ok();
}
-// ─── Windows hook migration dedupe (665c51b9, #604) ──────────────────────────
+#[test]
+fn user_scope_update_writes_claude_user_settings() {
+ let root = temp_root("claude-user-settings");
+ 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}/.claude/skills/impeccable/SKILL.md"),
+ "---\nname: impeccable\nversion: 1.0.0\n---\n",
+ );
+ write(&format!("{home}/.claude/settings.json"), r#"{"model":"claude-sonnet-5"}"#);
+ write(
+ &format!("{home}/.claude/settings.local.json"),
+ r#"{"hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"node \"~/.claude/skills/impeccable/scripts/hook.mjs\""}]}]}}"#,
+ );
+ write(
+ &format!("{project}/.claude/settings.local.json"),
+ r#"{"hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"node \"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs\""}]}]}}"#,
+ );
+ let bundle = create_fake_universal_bundle(&project, &[".claude"]);
+ 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 settings = format!("{home}/.claude/settings.json");
+ assert!(
+ manifest_names_launcher(&settings, &home, ".claude"),
+ "user settings do not name the user-scope launcher: {}",
+ std::fs::read_to_string(&settings).unwrap_or_default()
+ );
+ let settings_json: Value = serde_json::from_str(&read(&settings)).unwrap();
+ assert_eq!(settings_json["model"], "claude-sonnet-5");
+ assert!(
+ !std::path::Path::new(&format!("{home}/.claude/settings.local.json")).exists(),
+ "Claude Code does not load settings.local.json from user scope"
+ );
+ assert!(!std::path::Path::new(&format!("{project}/.claude/settings.local.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");
+ 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();
+ let bundle = create_fake_universal_bundle(&project, &[".claude"]);
+ let env = base_env(&home, &tmpdir, &bundle);
+ let args = ["install", "-y", "--user", "--providers=claude"];
+
+ let first = run_cli(&args, &project, &env);
+ assert_eq!(first.code, 0, "{}\n{}", first.stdout, first.stderr);
+ std::fs::remove_file(format!("{home}/.claude/settings.json")).unwrap();
+ write(
+ &format!("{home}/.claude/settings.local.json"),
+ r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"~/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
+ );
+ write(
+ &format!("{project}/.claude/settings.local.json"),
+ r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
+ );
+
+ let second = run_cli(&args, &project, &env);
+ assert_eq!(second.code, 0, "{}\n{}", second.stdout, second.stderr);
+ assert!(manifest_names_launcher(&format!("{home}/.claude/settings.json"), &home, ".claude"));
+ assert!(!std::path::Path::new(&format!("{home}/.claude/settings.local.json")).exists());
+ assert!(!std::path::Path::new(&format!("{project}/.claude/settings.local.json")).exists());
+ std::fs::remove_dir_all(&root).ok();
+}
+
+#[test]
+fn repeat_user_install_prunes_duplicate_project_hook_when_user_hook_exists() {
+ let root = temp_root("claude-user-hook-repeat");
+ 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();
+ let bundle = create_fake_universal_bundle(&project, &[".claude"]);
+ let env = base_env(&home, &tmpdir, &bundle);
+ let args = ["install", "-y", "--user", "--providers=claude"];
+
+ let first = run_cli(&args, &project, &env);
+ assert_eq!(first.code, 0, "{}\n{}", first.stdout, first.stderr);
+ assert!(manifest_names_launcher(&format!("{home}/.claude/settings.json"), &home, ".claude"));
+ let project_local = format!("{project}/.claude/settings.local.json");
+ write(
+ &project_local,
+ r#"{"permissions":{"allow":["Bash(ls)"]},"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
+ );
+
+ let second = run_cli(&args, &project, &env);
+ assert_eq!(second.code, 0, "{}\n{}", second.stdout, second.stderr);
+ assert!(manifest_names_launcher(&format!("{home}/.claude/settings.json"), &home, ".claude"));
+ let local = read(&project_local);
+ assert!(!local.contains("impeccable"), "duplicate project hook survived a repeat install: {local}");
+ let local_json: Value = serde_json::from_str(&local).unwrap();
+ assert_eq!(local_json["permissions"]["allow"][0], "Bash(ls)");
+ std::fs::remove_dir_all(&root).ok();
+}
+
+/// Regression (PR #986 review): a user hook that is only marked, not current
+/// (a legacy `hook.mjs` entry), must be rewritten on a repeat install, and the
+/// project hook may be pruned only once the user hook is current.
+#[test]
+fn repeat_user_install_replaces_legacy_user_hook_before_pruning_project_hook() {
+ let root = temp_root("claude-user-hook-legacy");
+ 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();
+ let bundle = create_fake_universal_bundle(&project, &[".claude"]);
+ let env = base_env(&home, &tmpdir, &bundle);
+ let args = ["install", "-y", "--user", "--providers=claude"];
+
+ let first = run_cli(&args, &project, &env);
+ assert_eq!(first.code, 0, "{}\n{}", first.stdout, first.stderr);
+ let user_settings = format!("{home}/.claude/settings.json");
+ write(
+ &user_settings,
+ r#"{"model":"claude-sonnet-5","hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"node \"~/.claude/skills/impeccable/scripts/hook.mjs\""}]}]}}"#,
+ );
+ let project_local = format!("{project}/.claude/settings.local.json");
+ write(
+ &project_local,
+ r#"{"permissions":{"allow":["Bash(ls)"]},"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
+ );
+
+ let second = run_cli(&args, &project, &env);
+ assert_eq!(second.code, 0, "{}\n{}", second.stdout, second.stderr);
+ let user = read(&user_settings);
+ assert!(manifest_names_launcher(&user_settings, &home, ".claude"), "user hook was not made current: {user}");
+ assert!(!user.contains("hook.mjs"), "legacy user hook survived: {user}");
+ let user_json: Value = serde_json::from_str(&user).unwrap();
+ assert_eq!(user_json["model"], "claude-sonnet-5");
+ let local = read(&project_local);
+ assert!(!local.contains("impeccable"), "duplicate project hook survived: {local}");
+ std::fs::remove_dir_all(&root).ok();
+}
+
+/// A user hook naming a launcher that no longer exists is not current either:
+/// the project hook stays until a current user hook is written.
+#[test]
+fn user_hook_with_missing_launcher_is_not_current() {
+ let root = temp_root("claude-user-hook-dangling");
+ let home = format!("{root}/home");
+ let settings = format!("{home}/.claude/settings.json");
+ let command = impeccable_skills::hook_manifest::user_claude_hook_command(&home, false).unwrap();
+ write(
+ &settings,
+ &serde_json::json!({"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":command}]}]}}).to_string(),
+ );
+ assert!(!impeccable_skills::hook_manifest::user_claude_hook_is_current_for(&home, false));
+ write(&format!("{home}/.claude/skills/impeccable/scripts/impeccable"), "#!/bin/sh\n");
+ assert!(impeccable_skills::hook_manifest::user_claude_hook_is_current_for(&home, false));
+ // A legacy entry beside the current one still needs a rewrite.
+ write(
+ &settings,
+ &serde_json::json!({"hooks":{"PostToolUse":[
+ {"hooks":[{"type":"command","command":command}]},
+ {"hooks":[{"type":"command","command":"node \"~/.claude/skills/impeccable/scripts/hook.mjs\""}]}
+ ]}})
+ .to_string(),
+ );
+ assert!(!impeccable_skills::hook_manifest::user_claude_hook_is_current_for(&home, false));
+ std::fs::remove_dir_all(&root).ok();
+}
+
+// ─── Windows hook migration dedupe (665c51b9, #604)──────────────────────────
#[test]
fn merge_hook_manifests_replaces_legacy_windows_path_claude_hooks() {
diff --git a/crates/skills/tests/hook_manifest_tests.rs b/crates/skills/tests/hook_manifest_tests.rs
index d9ac1b6c5..bdf9f673e 100644
--- a/crates/skills/tests/hook_manifest_tests.rs
+++ b/crates/skills/tests/hook_manifest_tests.rs
@@ -598,7 +598,7 @@ fn gemini_install_merges_into_commented_settings_and_force_never_wipes() {
let original = "{\n // pick a model\n \"model\": {\"name\": \"gemini-3-pro\"},\n /* MCP */ \"mcpServers\": {\"x\": {\"url\": \"http://a//b\"}}\n}\n";
write(&settings, original);
let sys = sys_with_home("/nonexistent-home");
- copy_provider_hooks(&sys, &bundle, &project, &[".gemini"], false, None).unwrap();
+ copy_provider_hooks(&sys, &bundle, &project, &[".gemini"], false, None, None).unwrap();
let merged: Value = serde_json::from_str(&read(&settings)).unwrap();
assert_eq!(merged["model"]["name"], "gemini-3-pro");
assert_eq!(merged["mcpServers"]["x"]["url"], "http://a//b");
@@ -607,8 +607,39 @@ fn gemini_install_merges_into_commented_settings_and_force_never_wipes() {
// Truly malformed: refused without --force, and --force never replaces
// the user's whole settings file with a hooks-only manifest.
write(&settings, "{ \"model\": ");
- assert!(copy_provider_hooks(&sys, &bundle, &project, &[".gemini"], false, None).is_err());
- assert!(copy_provider_hooks(&sys, &bundle, &project, &[".gemini"], true, None).is_err());
+ assert!(copy_provider_hooks(&sys, &bundle, &project, &[".gemini"], false, None, None).is_err());
+ assert!(copy_provider_hooks(&sys, &bundle, &project, &[".gemini"], true, None, None).is_err());
assert_eq!(read(&settings), "{ \"model\": ");
let _ = std::fs::remove_dir_all(&dir);
}
+
+#[test]
+fn user_scope_keeps_project_hook_when_bundle_has_no_replacement() {
+ let dir = tmp_dir("claude-user-hook-missing-bundle-manifest");
+ let root = dir.to_string_lossy().into_owned();
+ let bundle = jsp::join(&[&root, "bundle"]);
+ let home = jsp::join(&[&root, "home"]);
+ let project = jsp::join(&[&root, "project"]);
+ let project_manifest = jsp::join(&[&project, ".claude", "settings.local.json"]);
+ write(
+ &project_manifest,
+ r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/impeccable\" hook"}]}]}}"#,
+ );
+ let sys = sys_with_home(&home);
+
+ let written = copy_provider_hooks(
+ &sys,
+ &bundle,
+ &project,
+ &[".claude"],
+ false,
+ Some(&home),
+ Some(&project),
+ )
+ .unwrap();
+
+ assert!(written.is_empty());
+ assert!(std::path::Path::new(&project_manifest).exists());
+ assert!(!std::path::Path::new(&jsp::join(&[&home, ".claude", "settings.json"])).exists());
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 3afe96a12..c21234479 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -424,7 +424,8 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI
- **Flag parsing** (`getFlagValue`): `--name=value` or `--name value` (next arg not starting with `-`). Boolean flags via `includes`.
- **install flags**: `--force`, `-y|--yes`, `--no-hooks`, `--providers=<list>`, scope: `--user|--home|--global` → user; `--project|--local` → project; `--scope=<v>`/`--install-scope=<v>` normalized (`u|user|home|global`→user, `p|project|local|repo`→project; unknown → error `Unknown install scope: ${v}. Use --scope=project or --scope=global.`). Project root = nearest ancestor with `.git`, else cwd. Detection: project harness dirs present in root, plus `GLOBAL_HARNESS_HINTS` under home (`.agent`, `.gemini/antigravity*`→`.agent`, `.claude`, `.codex`→`.agents`, `.cursor`, `.dsh` (resolved `$DSH_HOME`, fallback `~/.dsh`), `.gemini`, `.grok`, `.hermes`, `.kiro`, `.opencode`, opencode config dir, `.pi`, `.qoder`, `.rovodev`, `.vibe`). Targets: explicit list wins (invalid names → `Unknown provider(s): ...`); `-y` → detected project providers, else detected user providers, else DEFAULT_TARGETS; interactive → prints "Detected harnesses:" table then radio/checkbox prompts (raw-mode TTY) or line prompts (`Install target: [1] Detected only (...) [2] Customize [1]: `, `Select harnesses (comma-separated: ...)`). Scope: explicit; `-y` → project; interactive prompt `Install location` (Project/Global). Hooks: `decideHookInstall` reads `hook.consent` in config(.local).json; declined→false, accepted→true; all targets already have hook markers→true; `-y` or non-TTY→true; else prints HOOK_EXPLAINER and asks `Install the design hook? (Y/n) `, storing consent in `.impeccable/config.local.json`.
Bundle: `IMPECCABLE_BUNDLE_PATH` (dir or zip) else download `https://impeccable.style/api/download/bundle/universal` (https `get`, one redirect followed, non-200 → `HTTP ${status}`) to `${tmpdir}/impeccable-update-${Date.now()}.zip`, extracted with `fflate.unzipSync` into `${tmpdir}/impeccable-update-${Date.now()}` (zip-slip guarded: `Refusing to extract entry outside target dir: ${entry}`). Bundle layout `<bundle>/<provider>/skills/<skill>/...`, `<bundle>/<provider>/agents/*.md`, hook manifests `<bundle>/.claude/settings.json`, `.cursor/hooks.json`, `.codex/hooks.json`, `.github/hooks/impeccable.json`, `.grok/hooks/impeccable.json`.
- 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 (dest: `.claude/settings.local.json` [skips if `.claude/settings.json` already carries the marker and prunes the local copy], `.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). 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.
+ 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!`.
- **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.
@@ -658,6 +659,7 @@ followed by a single `\n`. Overwrites (one brief per slug).
- **CLI args / flags**: `--target <p>` / `-t <p>` / `--target=<p>` (strict; last wins). Missing value -> stderr `--target requires a path value.\n`, exit 1. Nothing else.
- **Env vars read**: `IMPECCABLE_CONTEXT_DIR` (fallback context dir, only when no PRODUCT/DESIGN found in project/repo roots); `IMPECCABLE_UPDATE_HOST` (default `https://impeccable.style`, trailing `/` stripped); `IMPECCABLE_UPDATE_CACHE` (default `~/.impeccable/update-check.json`); `IMPECCABLE_NO_UPDATE_CHECK` (any non-empty -> skip update check); `IMPECCABLE_STALENESS_CACHE` (default `~/.impeccable/staleness-check.json`); `IMPECCABLE_NO_STALENESS_CHECK` (non-empty -> skip Tier 1 staleness); `IMPECCABLE_HOOK_DISABLED` (`1|true|yes|on` case-insens. -> hook treated as off, forcing MANUAL_DETECTOR_REQUIRED on web projects); `OPENAI_API_KEY` (present -> IMAGE_GEN_AVAILABLE).
- **Inputs**: PRODUCT/DESIGN files per resolution above; `.impeccable/config.json` + `config.local.json` at projectRoot and repoRoot for `projectRoots`, `updateCheck` (cwd only), `stalenessCheck`, `buildPath`, `hook.enabled`; `package.json`, `pnpm-workspace.yaml`, `lerna.json`; hook manifests by provider ID: `claude-code`: `.claude/settings.local.json`, `.claude/settings.json`; `codex`/`agents`: `.codex/hooks.json`; `cursor`: `.cursor/hooks.json`; `github`: `.github/hooks/impeccable.json`; `grok`: `.grok/hooks/impeccable.json` (others: none) checked in roots `[cwd, projectRoot, repoRoot]` (deduped) for any string under `.hooks` containing `skills/impeccable/scripts/hook.mjs` or `skills/impeccable/scripts/hook-before-edit.mjs`; `../SKILL.md` frontmatter `^version:\s*(.+)$` (quotes stripped) for the local version; `../reference/ios.md`, `../reference/android.md`; `.impeccable/surfaces/*.md`; `.impeccable/design.json` etc. for staleness; `which`/`where` probes for `cwebp sips magick ffmpeg`.
+- **Claude user-scope hook coverage**: also checks `~/.claude/settings.json` for the launcher marker; `doctor` validates that manifest's launcher path alongside project/repo manifests.
- **Outputs** (stdout; parts joined by `'\n\n---\n\n'` and terminated by one `'\n'`; exit 0):
1. If `resolveTargetSelection` returns a selection (monorepo root, no --target, candidates exist): prints ONLY
```
@@ -1137,7 +1139,7 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill l
#### `hook.mjs` -> `impeccable hook`
- **Invoked from**:
- - **Claude Code** project settings (`.claude/settings.json` from the build; the CLI installer writes the same content to `.claude/settings.local.json`; `hook-admin on` writes `.claude/settings.local.json` with a simpler `node "${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs"` command). Manifest (build variant, verbatim):
+ - **Claude Code** settings (`.claude/settings.json` from the build; the CLI installer writes project-scope hooks to `.claude/settings.local.json` and user-scope hooks to `~/.claude/settings.json`; `hook-admin on` writes `.claude/settings.local.json` with the project launcher; when the project has no Claude skill but a user-scope one exists and a project manifest still carries an Impeccable hook, it writes the guarded absolute user launcher to `~/.claude/settings.json` instead). Manifest (build variant, verbatim):
```json
{
"description": "Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.",
@@ -1298,7 +1300,7 @@ DOM scans, design-system findings, co-scanned stylesheets without their own base
- `writeHookConfig(cwd, hookConfig, {local})`: target file; if local → `ensureHookGitExcludes` first; `next = { ...existing, hook: { ...existingHookMinusDetectorKeys, ...hookConfig } }`; legacy detector keys found under `hook` (`ignoreRules, ignoreFiles, ignoreValues, designSystem, advisoryRules`) are migrated into `detector` (merged with existing detector). `on`/`off` write `hook: { enabled, limits: { maxFindings, maxChars } }` merged over existing hook keys — NOTE this replaces the whole `limits` object, dropping a configured `maxFileBytes`; sibling keys (`quiet`, `auditLog`, `perEditRules`, `consent`) survive. `on` additionally writes `hook.consent: 'accepted'` into `config.local.json`.
- `writeDetectorConfig(cwd, detectorConfig, {local})`: `next.detector = { ...existingDetectorSection, ...merged }` where merged = `{ ignoreRules, ignoreFiles, ignoreValues, designSystem?, advisoryRules? }` (arrays deduped, ignoreValues normalized with key order rule,value,files,createdAt,reason); legacy detector keys are stripped out of `hook` (and `hook` deleted if then empty). Untouched `ignoreValues` entries stay byte-identical.
- `ignore-value` entry inserted: `{ rule, value, files?, createdAt: <ISO now>, reason? }`; if an entry with the same `rule\0value\0sortedFiles` key exists only its `reason` is updated (when given).
- - `repairHookManifests(cwd)` (`on` only): for each `HOOK_MANIFEST_TARGETS` whose `skillRel` dir exists:
+ - `repairHookManifests(cwd)` (`on` only): for each `HOOK_MANIFEST_TARGETS` whose project `skillRel` dir exists; Claude also accepts a user-scope skill (`~/.claude/skills/impeccable`) when no project skill exists and `.claude/settings.local.json` or `.claude/settings.json` already contains an Impeccable hook marker. That repair merges the hook (command `[ ! -f '<home>/.claude/skills/impeccable/scripts/impeccable' ] || '<home>/.claude/skills/impeccable/scripts/impeccable' hook`, the `update --user` form) into `~/.claude/settings.json` (written atomically through a temp file and rename, symlinks resolved; an invalid file is skipped, never replaced) and prunes Impeccable entries from the project's `.claude/settings.local.json`. The committed `.claude/settings.json` is never written, so no home path reaches the repository:
- `.claude` → dest `.claude/settings.local.json`; if `.claude/settings.json` already contains an impeccable hook marker in its `hooks` subtree, prune impeccable entries from `settings.local.json` and count as `already`. Manifest inserted:
```json
{ "description": "Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.",
diff --git a/skill/reference/hooks.md b/skill/reference/hooks.md
index 7e8b5cf24..8e71fe198 100644
--- a/skill/reference/hooks.md
+++ b/skill/reference/hooks.md
@@ -14,7 +14,7 @@ Declare server-side template extensions under **`detector.extensions`** when the
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
-Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `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.
+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.
@@ -105,7 +105,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 is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.local.json`, `.codex/hooks.json`, `.cursor/hooks.json`, `.github/hooks/impeccable.json`, and `.gemini/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.
+- 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