Skip to content

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

JavaScript

Ship every .cmd with CRLF, repair dangling Copilot hooks, use an idle download timeout (#1131)

Paul Bakaus1ea581e2399e
diff --git a/.gitattributes b/.gitattributes
index 2b013c336..be0228381 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,3 +1,11 @@
+# cmd.exe parses batch files by byte offset, and an LF-only `.cmd` breaks
+# `call :label` and `goto` (#1098). Every checkout and `git archive` writes
+# the source launcher and its tracked provider copies with CRLF; the build
+# also emits batch files with CRLF whatever the working tree holds
+# (scripts/lib/utils.js), and `bun run build` fails if any emitted copy has a
+# bare LF.
+*.cmd text eol=crlf
+
# The oracle replays goldens recorded from a POSIX checkout, and a finding's
# snippet carries the fixture's own bytes, so these files have to arrive with
# LF on every platform. `-text` disables end-of-line conversion outright, which
@@ -10,10 +18,6 @@ tests/oracle/** -text
ui/component-review/theme.css text eol=lf
crates/context/assets/component-review.js text eol=lf
-# cmd.exe can miss batch labels in LF-only scripts. Keep the launcher in CRLF
-# on every checkout so release bundles contain a native Windows batch file.
-skill/scripts/impeccable.cmd text eol=crlf
-
# Machine-written files that a line diff cannot usefully show. `-diff` makes
# `git diff`, `git show` and `git log -p` print "Binary files differ" instead
# of the content; `linguist-generated` collapses them in GitHub's PR view.
diff --git a/crates/skills/src/bundle.rs b/crates/skills/src/bundle.rs
index 8ace5eebb..25c95a562 100644
--- a/crates/skills/src/bundle.rs
+++ b/crates/skills/src/bundle.rs
@@ -44,21 +44,49 @@ const MAX_TOTAL_BYTES: u64 = 4 * 1024 * 1024 * 1024;
const MAX_COMPRESSION_RATIO: u64 = 200;
const RATIO_GUARD_FLOOR: u64 = 1024 * 1024;
+/// How long a download may wait to connect.
+const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
+
+/// How long a download may go without receiving (or sending) a byte before
+/// it is abandoned. There is deliberately no cap on the whole transfer: a
+/// slow but steady connection must finish (#1115, where a 120 s total cap
+/// failed the ~17 MB bundle below ~140 KB/s), and [`MAX_DOWNLOAD_BYTES`]
+/// already bounds what a response can send. ureq's `timeout()` would replace
+/// this per-read limit with a deadline for the whole request, so it is not
+/// set.
+const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
+
+fn download_agent(connect: std::time::Duration, idle: std::time::Duration) -> ureq::AgentBuilder {
+ impeccable_context::http::agent_builder()
+ .timeout_connect(connect)
+ .timeout_read(idle)
+ .timeout_write(idle)
+}
+
+/// A socket read or write timeout surfaces as `WouldBlock` on Unix and
+/// `TimedOut` on Windows; name it as the stall it is.
+fn describe_io_error(e: &std::io::Error, url: &str, idle: std::time::Duration) -> String {
+ match e.kind() {
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => {
+ format!("no data received for {} s downloading {url}; check the network and retry", idle.as_secs())
+ }
+ _ => e.to_string(),
+ }
+}
+
/// In-memory GET for the small payloads (`/api/commands`, the engine binary
/// and its sidecars). Non-2xx → `HTTP <status>`. The bundle itself goes
/// through `download_file`, which streams to disk. Reads are capped at
/// [`MAX_DOWNLOAD_BYTES`]; a longer response is an error, not a truncation.
pub fn download(url: &str) -> Result<Vec<u8>, String> {
- let agent = impeccable_context::http::agent_builder()
- .timeout_connect(std::time::Duration::from_secs(30))
- .build();
+ let agent = download_agent(CONNECT_TIMEOUT, IDLE_TIMEOUT).build();
match agent.get(url).call() {
Ok(res) => {
let mut body = Vec::new();
res.into_reader()
.take(MAX_DOWNLOAD_BYTES + 1)
.read_to_end(&mut body)
- .map_err(|e| e.to_string())?;
+ .map_err(|e| describe_io_error(&e, url, IDLE_TIMEOUT))?;
if body.len() as u64 > MAX_DOWNLOAD_BYTES {
return Err(format!("response too large downloading {url} (over {MAX_DOWNLOAD_BYTES} bytes)"));
}
@@ -79,16 +107,18 @@ pub struct FetchResponse {
}
fn ureq_fetch(url: &str) -> Result<FetchResponse, String> {
- let agent = impeccable_context::http::agent_builder()
- .timeout_connect(std::time::Duration::from_secs(30))
- .timeout(std::time::Duration::from_secs(120))
- .redirects(0)
- .build();
+ ureq_fetch_with(url, CONNECT_TIMEOUT, IDLE_TIMEOUT)
+}
+
+/// One transport hop with a connect timeout and an idle timeout, and no cap
+/// on the whole transfer (see [`IDLE_TIMEOUT`]).
+fn ureq_fetch_with(url: &str, connect: std::time::Duration, idle: std::time::Duration) -> Result<FetchResponse, String> {
+ let agent = download_agent(connect, idle).redirects(0).build();
match agent.get(url).call() {
Ok(res) => Ok(FetchResponse {
status: res.status(),
location: res.header("location").map(str::to_string),
- body: Box::new(res.into_reader()),
+ body: Box::new(IdleNamedReader { inner: res.into_reader(), url: url.to_string(), idle }),
}),
Err(ureq::Error::Status(code, res)) => Ok(FetchResponse {
status: code,
@@ -99,6 +129,25 @@ fn ureq_fetch(url: &str) -> Result<FetchResponse, String> {
}
}
+/// Names a read timeout as a stall (`describe_io_error`) while keeping the
+/// error an `io::Error`, so `download_file_capped`'s cleanup still runs.
+struct IdleNamedReader<R> {
+ inner: R,
+ url: String,
+ idle: std::time::Duration,
+}
+
+impl<R: Read> Read for IdleNamedReader<R> {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+ self.inner.read(buf).map_err(|e| match e.kind() {
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => {
+ std::io::Error::new(std::io::ErrorKind::TimedOut, describe_io_error(&e, &self.url, self.idle))
+ }
+ _ => e,
+ })
+ }
+}
+
/// JS: downloadFile(url, dest, { fetchImpl }) after #479 + af2e8b3a: manual
/// redirects (5 hops, relative Locations resolved against the current URL),
/// HTTPS only, the body streamed to `dest` opened `wx`. On failure the
@@ -873,6 +922,52 @@ pub fn link_provider_skills(io: &mut Io, bundle_root: &str, root: &str, targets:
mod tests {
use super::*;
+ /// A one-shot HTTP server on 127.0.0.1 that sends `chunks` pieces of a
+ /// `chunks * 1024`-byte body, sleeping `gap` before each.
+ fn slow_server(chunks: usize, gap: std::time::Duration) -> String {
+ use std::io::Write;
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ std::thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ let mut seen = Vec::new();
+ let mut byte = [0u8; 1];
+ while !seen.ends_with(b"\r\n\r\n") && stream.read(&mut byte).unwrap_or(0) == 1 {
+ seen.push(byte[0]);
+ }
+ let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", chunks * 1024);
+ let _ = stream.write_all(head.as_bytes());
+ for _ in 0..chunks {
+ std::thread::sleep(gap);
+ if stream.write_all(&[b'x'; 1024]).and_then(|_| stream.flush()).is_err() {
+ return;
+ }
+ }
+ });
+ format!("http://{addr}/bundle.zip")
+ }
+
+ #[test]
+ fn slow_steady_download_outlasts_the_idle_timeout() {
+ // #1115: the whole transfer takes ~3 s, three times the idle limit,
+ // and still completes because bytes keep arriving.
+ let url = slow_server(15, std::time::Duration::from_millis(200));
+ let res = ureq_fetch_with(&url, CONNECT_TIMEOUT, std::time::Duration::from_secs(1)).unwrap();
+ assert_eq!(res.status, 200);
+ let mut body = Vec::new();
+ res.body.take(MAX_DOWNLOAD_BYTES).read_to_end(&mut body).unwrap();
+ assert_eq!(body.len(), 15 * 1024);
+ }
+
+ #[test]
+ fn stalled_download_fails_with_an_idle_message() {
+ let url = slow_server(1, std::time::Duration::from_secs(3));
+ let res = ureq_fetch_with(&url, CONNECT_TIMEOUT, std::time::Duration::from_millis(500)).unwrap();
+ let mut body = Vec::new();
+ let err = res.body.take(MAX_DOWNLOAD_BYTES).read_to_end(&mut body).unwrap_err();
+ assert!(err.to_string().starts_with("no data received for 0 s downloading http://127.0.0.1:"), "{err}");
+ }
+
fn tmp_dir(tag: &str) -> String {
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
diff --git a/crates/skills/src/hook_manifest.rs b/crates/skills/src/hook_manifest.rs
index 0e02a5f70..8c2cdd17f 100644
--- a/crates/skills/src/hook_manifest.rs
+++ b/crates/skills/src/hook_manifest.rs
@@ -411,13 +411,51 @@ pub fn hook_installed_for_provider(root: &str, provider: &str) -> bool {
/// 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.
+///
+/// A user-scope Copilot install counts the project manifest only when it does
+/// not name the project's skill, or that skill is there: an older global
+/// install wrote the portable `$(git rev-parse ...)/.github/skills/...` form
+/// into a project with no Copilot skill of its own, a hook that never fires
+/// (#1098), so a repeat install must rewrite it rather than count it.
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);
}
+ if user_scope && provider == ".github" && github_manifest_names_missing_project_skill(root) {
+ return false;
+ }
hook_installed_for_provider(root, provider)
}
+/// The portable prefix of a project Copilot hook command.
+const GITHUB_PORTABLE_PREFIX: &str = "$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/impeccable";
+
+/// True when the project carries its own Copilot skill launcher.
+fn github_project_skill_exists(project_root: &str) -> bool {
+ util::exists(&jsp::join(&[project_root, ".github", "skills", "impeccable", "scripts", "impeccable"]))
+}
+
+/// True when `root` is a project (not the home dir) that ships its own
+/// Copilot skill: its committed manifest keeps the portable command.
+fn github_keeps_portable_form(sys: &Sys, root: &str) -> bool {
+ !sys.is_home_dir(root) && github_project_skill_exists(root)
+}
+
+/// True when `<root>/.github/hooks/impeccable.json` runs an Impeccable hook in
+/// the portable project form while `<root>` has no Copilot skill to run.
+fn github_manifest_names_missing_project_skill(root: &str) -> bool {
+ if github_project_skill_exists(root) {
+ return false;
+ }
+ let Some((Value::Object(map), _)) = read_manifest(&jsp::join(&[root, ".github", "hooks", "impeccable.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.iter().any(|c| c.contains(GITHUB_PORTABLE_PREFIX))
+}
+
/// 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> {
@@ -605,7 +643,10 @@ pub fn copy_provider_hooks(sys: &crate::providers::Sys, bundle_dir: &str, root:
}
}
let fresh_manifest = read_json_file(&artifact.src, "Bundled hook manifest")?;
- let absolute = skill_root != root || sys.is_home_dir(root);
+ // A project that ships its own Copilot skill keeps the portable,
+ // team-committed command even when the user installs globally.
+ let absolute = (skill_root != root || sys.is_home_dir(root))
+ && !(*provider == ".github" && github_keeps_portable_form(sys, root));
let fresh = rewrite_hook_commands_for_skill_root(&fresh_manifest, provider, skill_root, absolute);
let mut next = fresh.clone();
if util::exists(&artifact.dest) {
diff --git a/crates/skills/tests/hook_manifest_tests.rs b/crates/skills/tests/hook_manifest_tests.rs
index f06630802..73a800936 100644
--- a/crates/skills/tests/hook_manifest_tests.rs
+++ b/crates/skills/tests/hook_manifest_tests.rs
@@ -190,6 +190,12 @@ fn install_from_an_older_bundle_never_runs_the_post_edit_verb_before_the_edit()
let _ = std::fs::remove_dir_all(&dir);
}
+const GITHUB_PORTABLE: &str = "[ ! -f \"$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/impeccable\" ] || \"$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/impeccable\" hook";
+
+fn github_bundle_manifest() -> Value {
+ json!({ "version": 1, "hooks": { "postToolUse": [{ "type": "command", "matcher": "edit|create|apply_patch", "bash": GITHUB_PORTABLE, "timeoutSec": 5 }] } })
+}
+
#[test]
fn github_project_manifest_stays_portable_and_global_install_uses_home() {
// Project installs keep the committed `$(git rev-parse ...)` form.
@@ -707,3 +713,51 @@ fn user_scope_keeps_project_hook_when_bundle_has_no_replacement() {
assert!(!std::path::Path::new(&jsp::join(&[&home, ".claude", "settings.json"])).exists());
let _ = std::fs::remove_dir_all(&dir);
}
+
+#[test]
+fn github_user_scope_install_points_the_project_hook_at_the_home_skill() {
+ // #1098: a global install wrote the portable project form into the
+ // project's manifest, naming `.github/skills/...` in a project that has
+ // no Copilot skill, so the hook never fired.
+ let dir = tmp_dir("github-user-hook");
+ 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"]);
+ write(&jsp::join(&[&bundle, ".github", "hooks", "impeccable.json"]), &github_bundle_manifest().to_string());
+ write(&skill_launcher(&home, ".github"), "#!/bin/sh\n");
+ std::fs::create_dir_all(&project).unwrap();
+ let sys = sys_with_home(&home);
+ let manifest = jsp::join(&[&project, ".github", "hooks", "impeccable.json"]);
+
+ // An older global install left the portable form behind: not installed.
+ write(&manifest, &github_bundle_manifest().to_string());
+ assert!(hook_installed_for_provider(&project, ".github"));
+ assert!(!hook_installed_for_provider_at_scope(&project, ".github", true));
+ assert!(hook_installed_for_provider_at_scope(&project, ".github", false));
+
+ let written = copy_provider_hooks(&sys, &bundle, &project, &[".github"], false, Some(&home), Some(&project)).unwrap();
+ assert_eq!(written, [".github"]);
+ let after: Value = serde_json::from_str(&read(&manifest)).unwrap();
+ let gp = skill_launcher(&home, ".github");
+ let expected = if cfg!(windows) {
+ let w = gp.replace('\\', "/");
+ format!("[ ! -f '{w}' ] || '{w}' hook")
+ } else {
+ "[ ! -f \"$HOME/.github/skills/impeccable/scripts/impeccable\" ] || \"$HOME/.github/skills/impeccable/scripts/impeccable\" hook".to_string()
+ };
+ assert_eq!(after["hooks"]["postToolUse"].as_array().unwrap().len(), 1);
+ assert_eq!(after["hooks"]["postToolUse"][0]["bash"], Value::String(expected));
+ assert!(hook_installed_for_provider_at_scope(&project, ".github", true));
+
+ // A project that ships its own Copilot skill keeps the committed,
+ // portable manifest even when the user installs globally.
+ write(&skill_launcher(&project, ".github"), "#!/bin/sh\n");
+ write(&manifest, &github_bundle_manifest().to_string());
+ assert!(hook_installed_for_provider_at_scope(&project, ".github", true));
+ copy_provider_hooks(&sys, &bundle, &project, &[".github"], false, Some(&home), Some(&project)).unwrap();
+ let kept: Value = serde_json::from_str(&read(&manifest)).unwrap();
+ assert_eq!(kept["hooks"]["postToolUse"].as_array().unwrap().len(), 1);
+ assert_eq!(kept["hooks"]["postToolUse"][0]["bash"], GITHUB_PORTABLE);
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 0627bdb12..5926fe548 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -484,9 +484,11 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI
sorted by `id.localeCompare`.
- **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`.
+ Bundle: `IMPECCABLE_BUNDLE_PATH` (dir or zip) else download `https://impeccable.style/api/download/bundle/universal` (https only, up to 5 redirects, non-200 → `HTTP ${status}`; 30 s connect timeout and a 60 s idle timeout on every read, with no cap on the whole transfer, so a slow but steady connection finishes (#1115); a stall → `no data received for 60 s downloading <url>; check the network and retry`, under the `Could not verify skill bundle: ` prefix) 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 (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.
+ GitHub Copilot hook (`.github/hooks/impeccable.json` in the project, `bash` key): a project install keeps the bundle's portable `$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/impeccable` command; a user-scope install rewrites it to the home launcher (`$HOME/.github/skills/impeccable/scripts/impeccable` on POSIX, the resolved profile path with forward slashes on Windows), unless the project ships its own `.github/skills/impeccable/scripts/impeccable`, whose committed portable manifest is left as is. In user scope a project manifest that names the portable path while the project has no Copilot skill does not count as installed, so a repeat install rewrites it.
+ Every shipped `impeccable.cmd` (provider dirs, `plugin/`, `cursor-plugin/`, the dist zips) has CRLF line endings: `.gitattributes` sets `*.cmd text eol=crlf`, the build writes batch files with CRLF, and `bun run build` fails on any emitted `.cmd` with a bare LF (#1098).
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!`. Hook manifests follow install's placement: in user scope the Claude hook is `~/.claude/settings.json` and every other provider's manifest (`.cursor/hooks.json`, `.codex/hooks.json`, `.grok/hooks/impeccable.json`, ...) is the current project's, rewritten against the home skill. Hook consent is read from (and a prompt's answer written to) that same project root, so a project that declined hooks gets none from `update --user -y`. The stale-manifest repair (`repair_stale_hook_manifests`, including the retired Cursor gate) runs on those project manifests regardless of hook consent. An older `update --user` wrote non-Claude manifests under home instead; those are repaired in place too, never pruned, because a home manifest is global. When a home and a project hook (or a plugin and a project hook) both fire for one edit, the `hook` verb's event claim lets only one of them scan (see `hook`).
- **link**: `--source=<path>` (default `.impeccable`), `--providers`, `--force`, `-y`. Source must contain `dist/universal/` or provider `*/skills` dirs, else `Could not find compiled skills in ${src}. Expected dist/universal/ or provider skill folders.` Prompts `Link impeccable skills into N folder(s)? (Y/n) `; creates relative dir symlinks; existing non-link skipped with warning unless `--force`; output `Linked impeccable into: ... (N linked, N already linked, N skipped).` + submodule hint.
diff --git a/scripts/build.js b/scripts/build.js
index 84c4a2291..25591dcbf 100644
--- a/scripts/build.js
+++ b/scripts/build.js
@@ -19,7 +19,7 @@
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
-import { readSourceFiles, readPatterns, stashPerProjectArtifacts, restorePerProjectArtifacts } from './lib/utils.js';
+import { readSourceFiles, readPatterns, stashPerProjectArtifacts, restorePerProjectArtifacts, findBatchFilesWithBareLf } from './lib/utils.js';
import { syncRootCommands } from './lib/root-commands-sync.mjs';
import { createTransformer, PROVIDERS } from './lib/transformers/index.js';
import { hooksJsonFor, buildClaudePluginHooksManifest } from './lib/transformers/hooks.js';
@@ -486,6 +486,31 @@ function validateAskInstructionSites(rootDir) {
*
* Returns the number of validation errors. Build fails if > 0.
*/
+/**
+ * Every shipped `impeccable.cmd` must have CRLF line endings: cmd.exe cannot
+ * find `call :label` targets in an LF-only batch file (#1098). The build
+ * writes CRLF itself (readSkillScripts), so a failure here means that
+ * guarantee regressed. Checks dist/ (the release zips are packed from it)
+ * and, on a release build, the tracked harness dirs and plugin subtrees.
+ *
+ * Returns the number of validation errors. Build fails if > 0.
+ */
+function validateBatchLineEndings(rootDir, distDir, { syncRootOutputs }) {
+ const dirs = [distDir];
+ if (syncRootOutputs) {
+ for (const { configDir } of Object.values(PROVIDERS)) {
+ dirs.push(path.join(rootDir, configDir, 'skills', 'impeccable'));
+ }
+ dirs.push(path.join(rootDir, 'plugin'), path.join(rootDir, 'cursor-plugin'));
+ }
+ const bad = findBatchFilesWithBareLf([...new Set(dirs)]);
+ for (const file of bad) {
+ console.error(`❌ ${path.relative(rootDir, file)} has LF line endings; cmd.exe needs CRLF in a batch file (#1098).`);
+ }
+ if (bad.length === 0) console.log('✓ Batch launchers ship with CRLF line endings');
+ return bad.length;
+}
+
function copyDirSync(src, dest) {
fs.mkdirSync(dest, { recursive: true });
const entries = fs.readdirSync(src, { withFileTypes: true });
@@ -949,7 +974,10 @@ async function build() {
// guidance to every provider at once.
const askSiteErrors = validateAskInstructionSites(ROOT_DIR);
- if (countErrors > 0 || versionErrors > 0 || manifestShapeErrors > 0 || proseErrors > 0 || skillProseErrors > 0 || askSiteErrors > 0) {
+ // cmd.exe misparses an LF-only batch file, so every emitted .cmd is CRLF.
+ const batchEolErrors = validateBatchLineEndings(ROOT_DIR, DIST_DIR, BUILD_OPTIONS);
+
+ if (countErrors > 0 || versionErrors > 0 || manifestShapeErrors > 0 || proseErrors > 0 || skillProseErrors > 0 || askSiteErrors > 0 || batchEolErrors > 0) {
process.exit(1);
}
diff --git a/scripts/lib/utils.js b/scripts/lib/utils.js
index 0bd721bc3..7d0e8300e 100644
--- a/scripts/lib/utils.js
+++ b/scripts/lib/utils.js
@@ -45,6 +45,47 @@ export function restorePerProjectArtifacts(rootDir, stashed) {
}
}
+/**
+ * cmd.exe seeks by byte offset when it runs `call :label` or `goto`, so a
+ * batch file with LF-only line endings fails with "The system cannot find the
+ * batch label specified" (#1098). Every emitted `.cmd` is written with CRLF.
+ */
+export function isBatchFile(name) {
+ return /\.(cmd|bat)$/i.test(name);
+}
+
+export function toCrlf(text) {
+ return text.replace(/\r?\n/g, '\r\n');
+}
+
+/**
+ * Paths of every batch file under `dirs` that still holds a bare LF. Missing
+ * directories are skipped.
+ */
+export function findBatchFilesWithBareLf(dirs) {
+ const bad = [];
+ const walk = (dir) => {
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const entryPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ walk(entryPath);
+ } else if (entry.isFile() && isBatchFile(entry.name)) {
+ const text = fs.readFileSync(entryPath, 'latin1');
+ if (/(^|[^\r])\n/.test(text)) bad.push(entryPath);
+ }
+ }
+ };
+ for (const dir of dirs) walk(dir);
+ return bad;
+}
+
function readSkillScripts(scriptsDir) {
const scripts = [];
@@ -63,11 +104,13 @@ function readSkillScripts(scriptsDir) {
if (PER_PROJECT_SCRIPT_ARTIFACTS.has(entry.name)) continue;
const relPath = path.relative(scriptsDir, entryPath).split(path.sep).join('/');
+ const raw = fs.readFileSync(entryPath, 'utf-8');
// `mode` travels with the entry so the launcher keeps its executable
// bit in every provider copy (see writeScriptFile in the transformer).
+ // A batch file ships with CRLF whatever this checkout holds (#1098).
scripts.push({
name: relPath,
- content: fs.readFileSync(entryPath, 'utf-8'),
+ content: isBatchFile(relPath) ? toCrlf(raw) : raw,
filePath: entryPath,
mode: fs.statSync(entryPath).mode & 0o777,
});
diff --git a/tests/build.test.js b/tests/build.test.js
index d71d64105..d4c23241f 100644
--- a/tests/build.test.js
+++ b/tests/build.test.js
@@ -396,6 +396,14 @@ describe('skill scripts payload', () => {
}
});
+ test('ships the Windows launcher with CRLF line endings (#1098)', () => {
+ // cmd.exe cannot resolve `call :label` in an LF-only batch file, so the
+ // payload is CRLF whatever line endings this checkout holds.
+ const cmd = scripts.find((s) => s.name === 'impeccable.cmd');
+ expect(cmd.content).toContain('\r\n');
+ expect(cmd.content).not.toMatch(/(^|[^\r])\n/);
+ });
+
test('ships no engine entry points and no bundled detector', () => {
// The engine verbs live in the binary; the only Node scripts allowed in
// the payload are the comp-fidelity build pipeline and its libs, which
@@ -734,3 +742,22 @@ describe('agent bodies resolve placeholders on every surface that ships them', (
expect(codexToml).toMatch(/and ask \S+\./);
});
});
+
+describe('batch line endings', () => {
+ const dir = path.join(process.cwd(), 'test-tmp-batch-eol');
+
+ afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ test('toCrlf converts LF and leaves CRLF alone', () => {
+ expect(utils.toCrlf('a\nb\r\nc\n')).toBe('a\r\nb\r\nc\r\n');
+ });
+
+ test('findBatchFilesWithBareLf flags only batch files with a bare LF', () => {
+ fs.mkdirSync(path.join(dir, 'a', 'scripts'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'a', 'scripts', 'good.cmd'), '@echo off\r\ncall :x\r\n');
+ fs.writeFileSync(path.join(dir, 'a', 'scripts', 'bad.cmd'), '@echo off\r\ncall :x\n');
+ fs.writeFileSync(path.join(dir, 'a', 'scripts', 'impeccable'), '#!/bin/sh\nexit 0\n');
+ const bad = utils.findBatchFilesWithBareLf([dir, path.join(dir, 'missing')]);
+ expect(bad).toEqual([path.join(dir, 'a', 'scripts', 'bad.cmd')]);
+ });
+});