Skip to content

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

JavaScript

Fix: doctor checks the launcher in Codex user-level hooks (#1111) (#1121)

Abdul Wahabe07dc019a75e
diff --git a/crates/context/src/context_cli.rs b/crates/context/src/context_cli.rs
index 9f3b39e3c..e218762a1 100644
--- a/crates/context/src/context_cli.rs
+++ b/crates/context/src/context_cli.rs
@@ -30,6 +30,21 @@ pub fn hook_manifests_for(provider_id: &str) -> &'static [&'static str] {
}
}
+/// The user-level manifest a user-scope install writes for this provider:
+/// Claude's `~/.claude/settings.json`; Codex and agents `$CODEX_HOME/hooks.json`
+/// (relative to cwd), or `~/.codex/hooks.json` when CODEX_HOME is unset or
+/// empty. A non-empty CODEX_HOME is exclusive.
+pub fn user_hook_manifest(provider_id: &str, cwd: &str, env: &Env) -> Option<String> {
+ match provider_id {
+ "claude-code" => Some(jsp::join(&[&crate::util::homedir(env), ".claude", "settings.json"])),
+ "codex" | "agents" => Some(match env_nonempty(env, "CODEX_HOME") {
+ Some(root) => std::path::Path::new(cwd).join(root).join("hooks.json").to_string_lossy().into_owned(),
+ None => jsp::join(&[&crate::util::homedir(env), ".codex", "hooks.json"]),
+ }),
+ _ => None,
+ }
+}
+
const STOP_REVIEW_PROVIDERS: [&str; 4] = ["claude-code", "codex", "agents", "grok"];
// Only the launcher-era design hook counts as an active automatic hook. A
@@ -104,15 +119,7 @@ pub fn automatic_hook_mode(ctx: &Ctx, cwd: &str, env: &Env, provider: &Provider)
}
}
}
- let user_manifest = match provider.id.as_str() {
- "claude-code" => Some(jsp::join(&[&crate::util::homedir(env), ".claude", "settings.json"])),
- "codex" | "agents" => Some(match env_nonempty(env, "CODEX_HOME") {
- Some(root) => std::path::Path::new(cwd).join(root).join("hooks.json").to_string_lossy().into_owned(),
- None => jsp::join(&[&crate::util::homedir(env), ".codex", "hooks.json"]),
- }),
- _ => None,
- };
- if let Some(path) = user_manifest {
+ if let Some(path) = user_hook_manifest(&provider.id, cwd, env) {
if let Some(raw) = read_json(&path) {
if let Some(hooks) = raw.get("hooks") {
if crate::staleness::js_truthy(hooks) && value_has_hook_marker(hooks) {
diff --git a/crates/context/src/doctor.rs b/crates/context/src/doctor.rs
index 7c3811a38..f916be045 100644
--- a/crates/context/src/doctor.rs
+++ b/crates/context/src/doctor.rs
@@ -97,8 +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);
- let home = crate::util::homedir(env);
- findings.extend(check_hook_installation(&project_root, Some(&ctx.repo_root), provider_id, Some(&home)));
+ let user_manifest = crate::context_cli::user_hook_manifest(provider_id, cwd, env);
+ findings.extend(check_hook_installation(&project_root, Some(&ctx.repo_root), provider_id, user_manifest.as_deref()));
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 e1ef195d1..b56218757 100644
--- a/crates/context/src/staleness_deep.rs
+++ b/crates/context/src/staleness_deep.rs
@@ -240,7 +240,7 @@ pub fn check_hook_installation(
project_root: &str,
repo_root: Option<&str>,
provider_id: &str,
- user_root: Option<&str>,
+ user_manifest: Option<&str>,
) -> Vec<Finding> {
let mut out = Vec::new();
let manifests = crate::context_cli::hook_manifests_for(provider_id);
@@ -248,61 +248,59 @@ pub fn check_hook_installation(
return out;
}
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 entries: Vec<(&str, String, bool)> = Vec::new();
+ for root in &project_roots {
+ for rel in manifests {
+ entries.push((root, jsp::join(&[root, rel]), false));
+ }
+ }
+ if let Some(mp) = user_manifest {
+ let mp = jsp::resolve(mp, &[]);
+ if !entries.iter().any(|(_, existing, _)| *existing == mp) {
+ entries.push((project_root, mp, true));
}
}
let mut installed_at: Option<String> = None;
- 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 };
- if !js_truthy(hooks) {
- continue;
- }
- let mut commands = Vec::new();
- collect_hook_commands(hooks, &mut commands);
- if commands.is_empty() {
- continue;
- }
- let base = if project_root.is_empty() { root.as_str() } else { project_root };
- installed_at = to_relative(Some(&mp), base);
- let broken: Vec<&String> = commands
- .iter()
- .filter(|c| {
- let Some(token) = hook_script_token_from(c) else { return false };
- let Some(abs) = resolve_hook_script_path(&token, root) else { return false };
- !exists(&abs)
- })
- .collect();
- if !broken.is_empty() {
- let ia = installed_at.clone().unwrap();
- out.push(finding(
- "hook-script-missing",
- "hook manifest",
- Some(ia.clone()),
- "mention",
- format!(
- "{} installs the design hook, but its script path does not exist: {}. The hook runs as a no-op, so UI edits have been going unscanned while the project looks covered.",
- ia,
- broken.iter().map(|c| format!("`{}`", c)).collect::<Vec<_>>().join(", ")
- ),
- "Reinstall with `impeccable hooks on`, which rewrites the manifest against the skill's current location.".to_string(),
- ));
- }
+ for (root, mp, is_user) in &entries {
+ let Some(raw) = read_json(mp) else { continue };
+ let Some(hooks) = raw.get("hooks") else { continue };
+ if !js_truthy(hooks) {
+ continue;
+ }
+ let mut commands = Vec::new();
+ collect_hook_commands(hooks, &mut commands);
+ if commands.is_empty() {
+ continue;
+ }
+ let base = if project_root.is_empty() { *root } else { project_root };
+ installed_at = to_relative(Some(mp), base);
+ let broken: Vec<&String> = commands
+ .iter()
+ .filter(|c| {
+ let Some(token) = hook_script_token_from(c) else { return false };
+ let Some(abs) = resolve_hook_script_path(&token, root) else { return false };
+ !exists(&abs)
+ })
+ .collect();
+ if !broken.is_empty() {
+ let ia = installed_at.clone().unwrap();
+ out.push(finding(
+ "hook-script-missing",
+ "hook manifest",
+ Some(ia.clone()),
+ "mention",
+ format!(
+ "{} installs the design hook, but its script path does not exist: {}. The hook runs as a no-op, so UI edits have been going unscanned while the project looks covered.",
+ ia,
+ broken.iter().map(|c| format!("`{}`", c)).collect::<Vec<_>>().join(", ")
+ ),
+ if *is_user {
+ "Repoint this user-level manifest at the installed skill: `impeccable update --user` rewrites `~/.claude/settings.json` and `~/.codex/hooks.json`, but a hooks file under a custom `CODEX_HOME` has to be edited by hand."
+ } else {
+ "Reinstall with `impeccable hooks on`, which rewrites the manifest against the skill's current location."
+ }
+ .to_string(),
+ ));
}
}
if let Some(ia) = installed_at {
@@ -533,6 +531,7 @@ mod tests {
"scripts",
"impeccable",
]);
+ let manifest = crate::jsp::join(&[&home, ".claude", "settings.json"]);
write(&home, ".claude/skills/impeccable/scripts/impeccable", "#!/bin/sh\n");
write(
&home,
@@ -554,12 +553,47 @@ mod tests {
".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());
+ assert!(check_hook_installation(&project, None, "claude-code", Some(&manifest)).is_empty());
+
+ std::fs::remove_file(&launcher).unwrap();
+ let findings = check_hook_installation(&project, None, "claude-code", Some(&manifest));
+ assert_eq!(findings.len(), 1, "{findings:?}");
+ assert_eq!(findings[0].id, "hook-script-missing");
+ assert!(findings[0].fix.contains("update --user"), "{:?}", findings[0].fix);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn user_scope_codex_hook_is_checked_from_codex_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, ".agents", "skills", "impeccable", "scripts", "impeccable"]);
+ let manifest = crate::jsp::join(&[&root, "codex-home", "hooks.json"]);
+ write(&home, ".agents/skills/impeccable/scripts/impeccable", "#!/bin/sh\n");
+ write(
+ &root,
+ "codex-home/hooks.json",
+ &serde_json::json!({
+ "hooks": {
+ "Stop": [{
+ "hooks": [{
+ "type": "command",
+ "command": format!("[ ! -f '{launcher}' ] || '{launcher}' hook"),
+ }],
+ }],
+ },
+ })
+ .to_string(),
+ );
+ assert!(check_hook_installation(&project, None, "codex", Some(&manifest)).is_empty());
std::fs::remove_file(&launcher).unwrap();
- let findings = check_hook_installation(&project, None, "claude-code", Some(&home));
+ let findings = check_hook_installation(&project, None, "codex", Some(&manifest));
assert_eq!(findings.len(), 1, "{findings:?}");
assert_eq!(findings[0].id, "hook-script-missing");
+ assert!(findings[0].fix.contains("update --user"), "{:?}", findings[0].fix);
let _ = std::fs::remove_dir_all(&root);
}
}
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 0dc5e4321..1e63d6ec0 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -790,7 +790,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).
+- `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.
- `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.
diff --git a/tests/oracle/cases/context.mjs b/tests/oracle/cases/context.mjs
index 543cd6d3a..e3aa79d02 100644
--- a/tests/oracle/cases/context.mjs
+++ b/tests/oracle/cases/context.mjs
@@ -484,6 +484,8 @@ const cases = [
{ id: 'doctor-config-malformed', verb: 'doctor', workspace: 'ctx-product-only', setup: (ws) => write(ws, '.impeccable/config.json', '{not json'), env: env() },
{ id: 'doctor-config-array', verb: 'doctor', workspace: 'ctx-product-only', setup: (ws) => write(ws, '.impeccable/config.json', '[1,2]\n'), env: env() },
{ id: 'doctor-hook-script-missing', verb: 'doctor', workspace: 'ctx-product-only', setup: (ws) => write(ws, '.claude/settings.json', JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'node "${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs"' }] }] } }, null, 2) + '\n'), args: ['--json'], env: env() },
+ { id: 'doctor-codex-user-hook-script-missing', verb: 'doctor', workspace: 'ctx-product-only', setup: (ws) => codexUserHook(ws, '.oracle-home/.codex'), args: ['--json'], env: env({ IMPECCABLE_PROVIDER_ID: 'codex' }) },
+ { id: 'doctor-codex-home-hook-script-missing', verb: 'doctor', workspace: 'ctx-product-only', setup: (ws) => codexUserHook(ws, 'codex-home'), args: ['--json'], env: env({ IMPECCABLE_PROVIDER_ID: 'codex', CODEX_HOME: `${WS}/codex-home` }) },
{ id: 'doctor-hook-script-present', verb: 'doctor', workspace: 'ctx-product-only', setup: (ws) => { write(ws, '.claude/settings.json', JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'node .claude/skills/impeccable/scripts/hook.mjs' }] }] } }, null, 2) + '\n'); write(ws, '.claude/skills/impeccable/scripts/hook.mjs', '// present\n'); }, args: ['--json'], env: env() },
{
id: 'doctor-design-drift', verb: 'doctor', workspace: 'ctx-signals',
diff --git a/tests/oracle/golden/doctor-codex-home-hook-script-missing.json b/tests/oracle/golden/doctor-codex-home-hook-script-missing.json
new file mode 100644
index 000000000..d5b1e7abf
--- /dev/null
+++ b/tests/oracle/golden/doctor-codex-home-hook-script-missing.json
@@ -0,0 +1,7 @@
+{
+ "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\": \"hook-script-missing\",\n \"artifact\": \"hook manifest\",\n \"path\": \"codex-home/hooks.json\",\n \"severity\": \"mention\",\n \"summary\": \"codex-home/hooks.json installs the design hook, but its script path does not exist: `[ ! -f '/u/.agents/skills/impeccable/scripts/impeccable' ] || '/u/.agents/skills/impeccable/scripts/impeccable' hook`. The hook runs as a no-op, so UI edits have been going unscanned while the project looks covered.\",\n \"fix\": \"Repoint this user-level manifest at the installed skill: `impeccable update --user` rewrites `~/.claude/settings.json` and `~/.codex/hooks.json`, but a hooks file under a custom `CODEX_HOME` has to be edited by hand.\"\n }\n ],\n \"workspaces\": []\n}\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {}
+}
diff --git a/tests/oracle/golden/doctor-codex-user-hook-script-missing.json b/tests/oracle/golden/doctor-codex-user-hook-script-missing.json
new file mode 100644
index 000000000..cc85f64cf
--- /dev/null
+++ b/tests/oracle/golden/doctor-codex-user-hook-script-missing.json
@@ -0,0 +1,7 @@
+{
+ "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\": \"hook-script-missing\",\n \"artifact\": \"hook manifest\",\n \"path\": \".oracle-home/.codex/hooks.json\",\n \"severity\": \"mention\",\n \"summary\": \".oracle-home/.codex/hooks.json installs the design hook, but its script path does not exist: `[ ! -f '/u/.agents/skills/impeccable/scripts/impeccable' ] || '/u/.agents/skills/impeccable/scripts/impeccable' hook`. The hook runs as a no-op, so UI edits have been going unscanned while the project looks covered.\",\n \"fix\": \"Repoint this user-level manifest at the installed skill: `impeccable update --user` rewrites `~/.claude/settings.json` and `~/.codex/hooks.json`, but a hooks file under a custom `CODEX_HOME` has to be edited by hand.\"\n }\n ],\n \"workspaces\": []\n}\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {}
+}