The design language that makes your AI harness better at design.
JavaScript
Fix: write git exclude blocks where a linked worktree reads them (#887) (#908)
Abdul Wahabcf4bfc213a33
diff --git a/crates/common/src/git.rs b/crates/common/src/git.rsnew file mode 100644index 000000000..b171c7c7e--- /dev/null+++ b/crates/common/src/git.rs@@ -0,0 +1,41 @@+//! Git repository layout, read from disk. Nothing here spawns `git`: the hook+//! runs on every edit, and git may not be installed.++use crate::jsp;++/// The `info/exclude` git reads for the repository whose gitdir is the+/// absolute path `git_dir`. A linked worktree's gitdir names the shared+/// directory in a `commondir` file, relative to itself, and git then ignores+/// the worktree's own `info`.+pub fn info_exclude(git_dir: &str) -> String {+ let common = match std::fs::read_to_string(jsp::join(&[git_dir, "commondir"])) {+ Ok(raw) => jsp::resolve(git_dir, &[raw.trim()]),+ Err(_) => git_dir.to_string(),+ };+ jsp::join(&[&common, "info", "exclude"])+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn info_exclude_follows_a_linked_worktrees_commondir() {+ let base = std::env::temp_dir().join(format!("impeccable-common-git-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ let tmp = base.to_string_lossy().into_owned();++ let plain = jsp::join(&[&tmp, "plain", ".git"]);+ assert_eq!(info_exclude(&plain), jsp::join(&[&plain, "info", "exclude"]));++ let worktree_git = jsp::join(&[&tmp, "repo", ".git", "worktrees", "wt"]);+ std::fs::create_dir_all(&worktree_git).unwrap();+ std::fs::write(jsp::join(&[&worktree_git, "commondir"]), "../..\n").unwrap();+ assert_eq!(+ info_exclude(&worktree_git),+ jsp::join(&[&tmp, "repo", ".git", "info", "exclude"])+ );++ let _ = std::fs::remove_dir_all(&base);+ }+}diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rsindex c699e39c6..9f9227de2 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 git;pub mod jsp;pub mod proc;diff --git a/crates/detect/src/config.rs b/crates/detect/src/config.rsindex 713a88742..8b0be6fd6 100644--- a/crates/detect/src/config.rs+++ b/crates/detect/src/config.rs@@ -1063,7 +1063,7 @@ pub fn ensure_config_git_exclude(root: &str) -> bool {let Some(git_dir) = resolve_git_dir(root) else {return false;};- let target = jsp::join(&[&git_dir, "info", "exclude"]);+ let target = impeccable_common::git::info_exclude(&git_dir);let existing = crate::util::read_text(&target).unwrap_or_default();let mut block_lines = vec![EXCLUDE_OPEN];block_lines.extend(EXCLUDE_PATTERNS);diff --git a/crates/hook/src/hook_lib.rs b/crates/hook/src/hook_lib.rsindex ed590e53b..83cbfc13d 100644--- a/crates/hook/src/hook_lib.rs+++ b/crates/hook/src/hook_lib.rs@@ -844,7 +844,7 @@ fn resolve_hook_git_exclude_target(rt: &Runtime, cwd: &str) -> Option<GitExcludelet git_dir = resolve_git_dir(rt, &dot_git, &dir)?;let rel_prefix = jsp::to_posix(&rt.relative(&dir, &start));return Some(GitExcludeTarget {- path: jsp::join(&[&git_dir, "info", "exclude"]),+ path: impeccable_common::git::info_exclude(&git_dir),pattern_prefix: if rel_prefix.is_empty() || rel_prefix == "." {String::new()} else {diff --git a/crates/hook/tests/hook_tests.rs b/crates/hook/tests/hook_tests.rsindex f8464e10c..98abd8b95 100644--- a/crates/hook/tests/hook_tests.rs+++ b/crates/hook/tests/hook_tests.rs@@ -1058,6 +1058,36 @@ fn git_excludes_land_in_info_exclude_not_gitignore() {);}+#[test]+fn git_excludes_in_a_linked_worktree_reach_the_exclude_file_git_reads() {+ let t = Tmp::new();+ let repo = jsp::join(&[&t.path(), "repo"]);+ let wt = jsp::join(&[&t.path(), "wt"]);+ std::fs::create_dir_all(jsp::join(&[&t.path(), "empty-hooks"])).unwrap();+ std::fs::create_dir_all(&repo).unwrap();+ let hooks = format!("core.hooksPath={}/empty-hooks", t.path());+ let git = |dir: &str, args: &[&str]| {+ std::process::Command::new("git").current_dir(dir)+ .args(["-c", "user.name=Test", "-c", "[email protected]",+ "-c", "commit.gpgsign=false", "-c", &hooks])+ .args(args).output().unwrap()+ };+ for args in [+ &["init", "--quiet"][..],+ &["commit", "--quiet", "--allow-empty", "-m", "init"],+ &["worktree", "add", "--quiet", "../wt"],+ ] {+ let out = git(&repo, args);+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ }+ // A linked worktree's `.git` is a file; git reads `info/exclude` from the+ // common dir, never from the per-worktree gitdir the file points at.+ assert!(impeccable_detect::config::ensure_config_git_exclude(&wt));+ assert!(git(&wt, &["check-ignore", "-q", ".impeccable/config.local.json"]).status.success());+ ensure_hook_git_excludes(&rt(&wt), &wt);+ assert!(git(&wt, &["check-ignore", "-q", ".impeccable/hook.cache.json"]).status.success());+}+// ── filtering ─────────────────────────────────────────────────────────────#[test]diff --git a/crates/live/src/gitignore.rs b/crates/live/src/gitignore.rsindex 5d69d8a60..605b5a132 100644--- a/crates/live/src/gitignore.rs+++ b/crates/live/src/gitignore.rs@@ -159,5 +159,35 @@ pub fn resolve_git_info_exclude_path(cwd: &str) -> Option<String> {} else {jsp::resolve(cwd, &[git_dir_raw])};- Some(jsp::join(&[&git_dir, "info", "exclude"]))+ Some(impeccable_common::git::info_exclude(&git_dir))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn linked_worktree_resolves_to_the_common_dir_exclude() {+ let base = std::env::temp_dir().join(format!(+ "impeccable-live-gitignore-{}-{:?}",+ std::process::id(),+ std::thread::current().id()+ ));+ let _ = std::fs::remove_dir_all(&base);+ let tmp = base.to_string_lossy().into_owned();++ let worktree_git = jsp::join(&[&tmp, "repo", ".git", "worktrees", "wt"]);+ std::fs::create_dir_all(&worktree_git).unwrap();+ std::fs::write(jsp::join(&[&worktree_git, "commondir"]), "../..\n").unwrap();+ let wt = jsp::join(&[&tmp, "wt"]);+ std::fs::create_dir_all(&wt).unwrap();+ std::fs::write(jsp::join(&[&wt, ".git"]), format!("gitdir: {worktree_git}\n")).unwrap();++ assert_eq!(+ resolve_git_info_exclude_path(&wt),+ Some(jsp::join(&[&tmp, "repo", ".git", "info", "exclude"]))+ );++ let _ = std::fs::remove_dir_all(&base);+ }}diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex 0a5223bef..96e799583 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -273,7 +273,7 @@ Optional keys added later by engines (appended after the above): `ignoreValue` (#### Config file (`cli/lib/impeccable-config.mjs`) — `.impeccable/config.json` + `.impeccable/config.local.json`-- Paths: `<root>/.impeccable/config.json` (shared) and `<root>/.impeccable/config.local.json` (per-dev; `writeDetectionConfig(...,{local:true})` also appends a block to `.git/info/exclude`: `# impeccable-config-ignore-start\n.impeccable/config.local.json\n# impeccable-config-ignore-end`, idempotent by marker regex, following `gitdir:` files for worktrees).+- Paths: `<root>/.impeccable/config.json` (shared) and `<root>/.impeccable/config.local.json` (per-dev; `writeDetectionConfig(...,{local:true})` also appends a block to `.git/info/exclude`: `# impeccable-config-ignore-start\n.impeccable/config.local.json\n# impeccable-config-ignore-end`, idempotent by marker regex, following `gitdir:` files, and a linked worktree's `commondir`, to the exclude file git reads).- Shape:```json{ "detector": { "ignoreRules": ["side-tab"], "ignoreFiles": ["src/legacy/**"],@@ -919,7 +919,7 @@ Shape (JSON, written with `JSON.stringify(cache)` — no pretty printing):- else `snippet = String(f.snippet||'').trim().slice(0,80)`; snippet ? `${antipattern}:0:${snippet}` : `${antipattern}:0`- Session flags consumed once per session: `designNoteShown`, `footerShown`; per-file: `cleanAcked`.-`ensureHookGitExcludes(cwd)`: walk up from `cwd` to find a `.git` (dir, or file `gitdir: <path>` → resolved). Target `<gitdir>/info/exclude`. `patternPrefix` = relative path from the repo dir to `cwd` (`''` if same). Block written:+`ensureHookGitExcludes(cwd)`: walk up from `cwd` to find a `.git` (dir, or file `gitdir: <path>` → resolved). Target `<gitdir>/info/exclude`, or `<commondir>/info/exclude` when the gitdir holds a `commondir` file (a linked worktree; git ignores the per-worktree `info`). `patternPrefix` = relative path from the repo dir to `cwd` (`''` if same). Block written:```# impeccable-hook-ignore-start <prefix or '.'><prefix/>.impeccable/hook.cache.json@@ -1135,7 +1135,7 @@ Candidates in order: `<scripts>/detector/detect-antipatterns.mjs` (built skill lTriage each finding, then state in your reply ... (full footer, 5 lines; short footer on later fires in the session)```optionally followed by `\n\n[impeccable@1] DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.` once per session.-- **Side effects**: writes `.impeccable/hook.cache.json` (rules in step 8/10 and Stop), `<gitdir>/info/exclude` block (via persistCache), audit NDJSON (env/config). `process.env.IMPECCABLE_HOOK_DEPTH='1'` exported to children. Audit entries: `{ts, event:'PostToolUse'|'Stop', harness, cwd, session, tool?, file?, ext?, editCount?, findings?, freshFindings?, deferred?, emitted?, kind?, pending?, chars?, freshFiles?, scannedFiles?, suppressed?, skipped?, bytes?, reentrant?, quiet?, error?, platform?, durationMs}`; on crash `{ts, event:'hook-error', error}`.+- **Side effects**: writes `.impeccable/hook.cache.json` (rules in step 8/10 and Stop), git `info/exclude` block (via persistCache), audit NDJSON (env/config). `process.env.IMPECCABLE_HOOK_DEPTH='1'` exported to children. Audit entries: `{ts, event:'PostToolUse'|'Stop', harness, cwd, session, tool?, file?, ext?, editCount?, findings?, freshFindings?, deferred?, emitted?, kind?, pending?, chars?, freshFiles?, scannedFiles?, suppressed?, skipped?, bytes?, reentrant?, quiet?, error?, platform?, durationMs}`; on crash `{ts, event:'hook-error', error}`.- **Detection performed**: `detectHtml(filePath, {designSystem?})` for html-engine targets; `detectText(content, filePath, {designSystem?})` otherwise. Findings capped in render at `limits.maxFindings` (5) total per emission and `limits.maxChars` (8000, floor 500) chars; deduped per session per file by `findingCacheKey`; per-edit shows only IMMEDIATE tier (unless `perEditRules:'all'` or cursor/github harness); advisory rules dropped unless `detector.advisoryRules:'include'`.- **Edge cases / gotchas**: generated/sensitive paths and any path containing `..` never scanned; native PRODUCT.md platform → whole scan skipped (audit `native-platform`); files > 128 KiB skipped; empty stdin is `stdin-malformed` (not `stdin-empty`); the 7th edit of a primary file in a session emits the suppression notice once and the file is silent thereafter (co-scanned stylesheets don't bump counts); umbrella-dir launches key `.impeccable/` to the edited file's nearest project root but the Stop pass uses the session cwd (so those sessions no-op on Stop); Windows: `path.sep` normalized to `/` for globs/display and command-arg quoting switches to double quotes; timeouts are the harness's (5 s per-edit, 30 s Stop) — the script has no internal timer; a detector throw leaves the cache untouched and yields `error:'detector-threw'` only if nothing else emitted; `hook.mjs` never returns exit 2, so no harness treats it as blocking.- **Tests covering it**: `tests/hook.test.mjs` — `truthy()`, `SENSITIVE_PATH / GENERATED_PATH`, `isScanTargetInsideProject()`, `readConfig()`, `readCache / persistCache / bumpEditCount`, `ensureHookGitExcludes()`, `matchesAnyGlob()`, `filterFindings()`, `renderTemplate()` (envelope, footer text, short footer, description dedupe, ignore hints, POSIX/Windows quoting #476/#533, clamp behaviour), `writeAuditLog()`, `payload()`, `runHook()` (≈40 cases: fresh→pending, GitHub edit/apply_patch end-to-end, clean ack, .ts/.js quiet, IMPECCABLE_HOOK_QUIET, config quiet, re-entrancy, kill switch, config-disabled, native platform, DESIGN.md gating, staleness note, sensitive/generated/traversal/outside-project/symlink, extension allowlist, ignoreFiles, suppression on 7th edit, MultiEdit/apply_patch shapes, detector throw, async HTML detector, inline impeccable-disable, malformed stdin, missing file), `runHook() — cache write gating`, `— oversized files`, `— session cache tracks current scan`, `— session-scoped notices`, `— clean-ack noise`, `resolveCacheCwd()`, `suppressionNotice()`, `ALLOWED_EXTS`, `matchConfiguredExtension()`, `renderCleanAck()/renderPendingAck()`, `parseApplyPatchPaths()`, `resolveTargetFiles()`, `resolveHarness()/normalizeHookEvent()`, `expandScanTargets()`, `runHook() — co-located stylesheet scan`, `— events without file_path`, `— configured template extensions (#316)`, `resolveProjectPlatform()/isNativePlatform()`, `runHook() — emission enrichment`, `— per-edit tiering`, `runStopHook()` (full rule set + dedupe, clamped grouped render, no touched files, out-of-project files, second Stop silent, ignoreRules, advisory, stop_hook_active true/false, kill switches). `tests/hook-build.test.mjs` — manifest builders for Claude/Codex/Cursor/GitHub/Grok, node-probe presence and cmd.exe-safe characters, generated root manifests match builders, plugin `hooks/hooks.json` uses `${CLAUDE_PLUGIN_ROOT}`, generated skill runtime can import bundled detector.@@ -1360,7 +1360,7 @@ plugins/impeccable-live.client.tsapp/plugins/impeccable-live.client.tssrc/plugins/impeccable-live.client.ts```-Ignore target: if `<cwd>/.git` is a directory → `.git/info/exclude`; if it is a file `gitdir: X` → `X/info/exclude`; else `<cwd>/.gitignore`. Existing marker block is replaced in place; otherwise appended (preceded by a blank line unless file empty/ends with blank line). Result object: `{ file, mode: 'git-info-exclude'|'gitignore', changed, patterns }`.+Ignore target: if `<cwd>/.git` is a directory → `.git/info/exclude`; if it is a file `gitdir: X` → `X/info/exclude`, or the `info/exclude` of the directory `X/commondir` names when that file exists (a linked worktree); else `<cwd>/.gitignore`. Existing marker block is replaced in place; otherwise appended (preceded by a blank line unless file empty/ends with blank line). Result object: `{ file, mode: 'git-info-exclude'|'gitignore', changed, patterns }`.#### 1. roots.json manifest and root resolution (`live/roots.mjs`)