Skip to content

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

JavaScript

Fix launcher probe exit status, `**/` ignore boundaries, denied storage, and unsafe DESIGN.md links (#1116)

Sjors Robroek03ea58d89963
diff --git a/crates/detect/src/config.rs b/crates/detect/src/config.rs
index a4ab306e1..e3f1291ca 100644
--- a/crates/detect/src/config.rs
+++ b/crates/detect/src/config.rs
@@ -746,11 +746,13 @@ fn glob_to_regex(glob: &str) -> Option<Regex> {
let c = chars[i];
if c == '*' {
if chars.get(i + 1) == Some(&'*') {
- re.push_str(DOT);
- re.push('*');
i += 2;
if chars.get(i) == Some(&'/') {
+ re.push_str(&format!("(?:{DOT}*/)?"));
i += 1;
+ } else {
+ re.push_str(DOT);
+ re.push('*');
}
} else {
re.push_str("[^/]*");
@@ -1187,6 +1189,18 @@ mod tests {
assert!(matches_any_glob("a.scss", &["*.{css,scss}".to_string()]));
}
+ #[test]
+ fn globstar_slash_keeps_the_directory_boundary() {
+ let nested = ["src/**/a.html".to_string()];
+ assert!(matches_any_glob("src/a.html", &nested));
+ assert!(matches_any_glob("src/pages/a.html", &nested));
+ assert!(!matches_any_glob("src/xa.html", &nested));
+ let leading = ["**/foo.html".to_string()];
+ assert!(matches_any_glob("foo.html", &leading));
+ assert!(matches_any_glob("bar/foo.html", &leading));
+ assert!(!matches_any_glob("barfoo.html", &leading));
+ }
+
#[test]
fn colors() {
assert_eq!(color_ignore_key("#fff"), "255,255,255,255");
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 45f3a2205..cae76e65e 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -324,7 +324,7 @@ Optional keys added later by engines (appended after the above): `ignoreValue` (
- `readDetectionConfig(root)`: start `{ignoreRules:[],ignoreFiles:[],ignoreValues:[],designSystem:{enabled:true},extensions:[]}`; for shared then local: apply legacy `raw.hook.*` section then `raw.detector.*`. Arrays are unioned (`uniqueStrings`, String-coerced); ignoreValues merged by key `rule\0value\0sortedFiles.join('\x1f')` (later wins); `designSystem.enabled` false only when literally `false`; `advisoryRules` copied only if `'include'|'exclude'`; `extensions` merges normalized `detector.extensions` entries by ext, later source wins (string → engine `html`; `{ext, engine}` → `text` only when engine is literally `"text"`). Invalid/non-array `extensions` skipped. Invalid JSON / non-object files are ignored silently. **No validation errors are ever raised by the CLI**; the only validation of ignore lists lives in `skill/scripts/lib/staleness-deep.mjs checkDetectorIgnores` (doctor): unknown `ignoreRules` ids vs live `ANTIPATTERNS` → finding `detector-ignore-rules-unknown` (severity `mention`); non-glob `ignoreFiles` entries that don't exist → `detector-ignore-files-missing`.
- `normalizeIgnoreValue(v)`: trim, strip one leading/trailing quote, `+`→space, collapse whitespace, lowercase. Rules lowercased/trimmed.
- `normalizeIgnoreValueEntries`: keeps `{rule, value, [files], [createdAt], [reason]}` in **that key order**; `file` (string) and `files` merged, trimmed, deduped.
-- Glob → regex: `**` → `.*` (swallowing a following `/`), `*` → `[^/]*`, `?` → `[^/]`, `{a,b}` → `(?:a|b)`, regex specials escaped; anchored `^...$`. `matchesAnyGlob` tests the `/`-normalized path and its basename.
+- Glob → regex: `**/` → `(?:.*/)?` (zero or more whole directories, so `src/**/a.html` matches `src/a.html` and `src/pages/a.html` but not `src/xa.html`), any other `**` → `.*`, `*` → `[^/]*`, `?` → `[^/]`, `{a,b}` → `(?:a|b)`, regex specials escaped; anchored `^...$`. `matchesAnyGlob` tests the `/`-normalized path and its basename.
- `shouldIgnoreDetectionFile(filePath, root, config)`: raw path, absolute path, and root-relative path (if inside root) tested against `ignoreFiles`.
- `filterDetectionFindings`: drop when `ignoreRules` has the rule, or an `ignoreValues` entry matches: same rule; entry.value `*` (wildcard) OR extracted value equals (with color-key equality for `design-system-color`: rgb/hex/hsl parsed to `r,g,b,round(a*255)`); if entry has `files`, `finding.file` (or any `/`-suffix of it) must glob-match; a wildcard with no files never matches (unscoped `*` disallowed).
- `extractFindingIgnoreValue`: only for `overused-font, bounce-easing, design-system-font, design-system-color, design-system-radius, design-system-font-size`; source `finding.ignoreValue || finding.value`, else parse `detail`/`snippet`: bounce → `animate-bounce`, `cubic-bezier(...)`, or animation token matching `/bounce|elastic|wobble|jiggle|spring/i`; fonts → `Primary font:`, `Google Fonts:`, `font-family:` value, or `family=` URL param (decoded).
@@ -1119,7 +1119,7 @@ If markers already exist (regex `open[\s\S]*?close`), the block is replaced in p
`splitFindingsByTier(findings)` → `{immediate, deferred}` by `IMMEDIATE_TIER_RULES`.
`perEditTieringActive(config, harness)` = `false` for `'cursor'`/`'github'`; else `config.perEditRules !== 'all'`.
-`matchesAnyGlob(filePath, globs)`: path separators normalized to `/`; each glob → regex `^...$` where `**`→`.*` (a following `/` consumed), `*`→`[^/]*`, `?`→`[^/]`, `{a,b}`→`(?:a|b)`, regex specials escaped; tested against full path AND basename.
+`matchesAnyGlob(filePath, globs)`: path separators normalized to `/`; each glob → regex `^...$` where `**/`→`(?:.*/)?` (zero or more whole directories), any other `**`→`.*`, `*`→`[^/]*`, `?`→`[^/]`, `{a,b}`→`(?:a|b)`, regex specials escaped; tested against full path AND basename.
#### 0.7 Rendering
diff --git a/skill/scripts/impeccable b/skill/scripts/impeccable
index 224028c79..8832f3d0f 100755
--- a/skill/scripts/impeccable
+++ b/skill/scripts/impeccable
@@ -18,7 +18,8 @@ set -eu
# then skips its own probes and refuses to download, so probing stays cheap
# and can never loop.
probe_ok() {
- case "$(IMPECCABLE_LAUNCHER_PROBE=1 "$1" engine-probe 2>/dev/null || true)" in
+ probe_out=$(IMPECCABLE_LAUNCHER_PROBE=1 "$1" engine-probe 2>/dev/null) || return 1
+ case "$probe_out" in
impeccable-engine*) return 0 ;;
esac
return 1
diff --git a/skill/scripts/live-browser-ignores.js b/skill/scripts/live-browser-ignores.js
index 1c8514c7b..1a2912e57 100644
--- a/skill/scripts/live-browser-ignores.js
+++ b/skill/scripts/live-browser-ignores.js
@@ -63,9 +63,13 @@
const c = glob[i];
if (c === '*') {
if (glob[i + 1] === '*') {
- re += '.*';
i += 2;
- if (glob[i] === '/') i += 1;
+ if (glob[i] === '/') {
+ re += '(?:.*/)?';
+ i += 1;
+ } else {
+ re += '.*';
+ }
} else {
re += '[^/]*';
i += 1;
diff --git a/skill/scripts/live-browser-session.js b/skill/scripts/live-browser-session.js
index 388d2c2f9..687177072 100644
--- a/skill/scripts/live-browser-session.js
+++ b/skill/scripts/live-browser-session.js
@@ -42,7 +42,10 @@
function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
+ let store = storage;
+ if (!store) {
+ try { store = root.localStorage; } catch { store = null; /* storage denied */ }
+ }
const makeId = idFactory || function () { return randomId8(); };
const sessionKey = prefix + '-session';
const handledKey = sessionKey + '-handled';
diff --git a/skill/scripts/live-browser.js b/skill/scripts/live-browser.js
index a63f1abe2..ac5ab80e3 100644
--- a/skill/scripts/live-browser.js
+++ b/skill/scripts/live-browser.js
@@ -13,13 +13,17 @@
'use strict';
if (typeof window === 'undefined') return;
+ // Take the helper token out of the global before anything else, including
+ // on the double-init return below: each served copy re-prepends it.
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ try { delete window.__IMPECCABLE_TOKEN__; } catch { /* non-configurable */ }
+
// Guard against double-init. Bun's HTML loader may process the <script> tag
// and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
+ // Check BEFORE reading port to catch all cases.
if (window.__IMPECCABLE_LIVE_INIT__) return;
window.__IMPECCABLE_LIVE_INIT__ = true;
- const TOKEN = window.__IMPECCABLE_TOKEN__;
const PORT = window.__IMPECCABLE_PORT__;
const APP_ROOT = window.__IMPECCABLE_APP_ROOT__ || null;
if (!TOKEN || !PORT) {
@@ -63,11 +67,13 @@
const MANUAL_APPLY_STATE_TTL_MS = 15 * 60 * 1000;
// No idFactory: the session helper's default works on plain-HTTP origins,
// where the secure-context-only randomUUID does not exist (issue #1055).
+ let liveStorage = null;
+ try { liveStorage = window.localStorage; } catch { /* storage denied */ }
let sessionState = null;
try {
sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
prefix: PREFIX,
- storage: localStorage,
+ storage: liveStorage,
});
} catch (err) {
console.error('[impeccable] Live mode could not create its session state.', err);
@@ -13469,7 +13475,9 @@ void main() {
// Code spans
s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
// Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
+ s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => (
+ isSafeHref(u) ? `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>` : t
+ ));
// Bold
s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
// Italic (only single *…*, skip if inside bold already handled)
@@ -13477,6 +13485,14 @@ void main() {
return s;
}
+ function isSafeHref(url) {
+ // Browsers drop ASCII whitespace and C0 controls inside a scheme, so
+ // "java\tscript:" still runs; strip them before reading the scheme.
+ const probe = String(url).replace(/[\u0000-\u0020\u007f]/g, '');
+ const scheme = probe.match(/^([a-z][a-z0-9+.-]*):/i);
+ return !scheme || ['http', 'https', 'mailto'].includes(scheme[1].toLowerCase());
+ }
+
function highlightBold(text) {
return inlineMd(text);
}
diff --git a/tests/launcher-download.test.mjs b/tests/launcher-download.test.mjs
index 690d831d9..93d42b13b 100644
--- a/tests/launcher-download.test.mjs
+++ b/tests/launcher-download.test.mjs
@@ -254,6 +254,56 @@ test('cmd launcher forwards engine exit code through cmd /c', { skip: WINDOWS ?
}
});
+for (const [probeStatus, trusted] of [[0, true], [1, false]]) {
+ test(`sh launcher ${trusted ? 'runs' : 'skips'} a home binary whose engine-probe exits ${probeStatus}`, { skip: WINDOWS ? 'POSIX launcher probe' : false }, async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-launcher-probe-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const scripts = path.join(root, 'scripts');
+ const home = path.join(root, 'home');
+ const homeBin = path.join(home, '.impeccable', 'bin');
+ fs.mkdirSync(scripts);
+ fs.mkdirSync(homeBin, { recursive: true });
+ fs.writeFileSync(path.join(scripts, 'VERSION'), '0.0.0-test\n');
+ const launcher = path.join(scripts, 'impeccable');
+ fs.copyFileSync(path.join(ROOT, 'skill/scripts/impeccable'), launcher);
+ // Prints the handshake marker either way; only the exit status differs.
+ fs.writeFileSync(path.join(homeBin, 'impeccable'),
+ `#!/bin/sh\nif [ "$1" = engine-probe ]; then echo impeccable-engine 0.0.0-test; exit ${probeStatus}; fi\necho home-engine-ran\n`,
+ { mode: 0o755 });
+ const requests = [];
+ const server = http.createServer((req, res) => {
+ requests.push(req.url);
+ res.writeHead(404);
+ res.end();
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ t.after(() => new Promise(resolve => server.close(resolve)));
+ const env = {
+ PATH: '/usr/bin:/bin',
+ HOME: home,
+ IMPECCABLE_HOME: path.join(root, 'cache'),
+ IMPECCABLE_DOWNLOAD_BASE: `http://127.0.0.1:${server.address().port}`,
+ };
+ const result = await new Promise((resolve, reject) => {
+ const child = spawn('/bin/sh', [launcher, 'detect'], { env, cwd: root, timeout: 20000 });
+ let stdout = '';
+ child.stdout.on('data', data => { stdout += data; });
+ child.on('error', reject);
+ child.on('close', (status, signal) => resolve({ status, signal, stdout }));
+ });
+ assert.equal(result.signal, null, JSON.stringify(result));
+ if (trusted) {
+ assert.equal(result.status, 0, JSON.stringify(result));
+ assert.match(result.stdout, /home-engine-ran/);
+ assert.equal(requests.length, 0, 'a trusted home binary needs no download');
+ } else {
+ assert.equal(result.status, 127, JSON.stringify(result));
+ assert.doesNotMatch(result.stdout, /home-engine-ran/);
+ assert.equal(requests.length, 1, 'a failed probe falls through to the pinned download');
+ }
+ });
+}
+
for (const scenario of ['removed', 'emptied', 'empty-download', 'no-sidecar', 'empty-sidecar', 'mismatch', 'hash-failure', 'removed-during-hash', 'removed-before-move', 'removed-after-move', 'emptied-after-move', 'move-failure']) {
test(`launcher refuses ${scenario} with an accurate diagnostic`, async t => {
const result = await exercise(t, scenario);
diff --git a/tests/live-browser-ignores.test.mjs b/tests/live-browser-ignores.test.mjs
index 46745fa3e..f72e549ac 100644
--- a/tests/live-browser-ignores.test.mjs
+++ b/tests/live-browser-ignores.test.mjs
@@ -296,6 +296,16 @@ describe('live-browser-ignores resolver', () => {
assert.equal(out.skipScan, true);
});
+ it('keeps the directory boundary after `**/`', () => {
+ const ignores = { ignoreFiles: ['public/**/index.html'], roots: ['public/'] };
+ assert.equal(resolve({ ignores, pathname: '/safeindex.html' }).skipScan, false);
+ assert.equal(resolve({ ignores, pathname: '/index.html' }).skipScan, true);
+ assert.equal(resolve({ ignores, pathname: '/docs/index.html' }).skipScan, true);
+ const leading = { ignoreFiles: ['**/foo.html'] };
+ assert.equal(resolve({ ignores: leading, pathname: '/barfoo.html' }).skipScan, false);
+ assert.equal(resolve({ ignores: leading, pathname: '/bar/foo.html' }).skipScan, true);
+ });
+
it('treats a malformed ignoreFiles value as no waiver at all', () => {
const out = resolve({
ignores: { ignoreFiles: 'prototype/**', roots: [] },
diff --git a/tests/live-browser-session.test.mjs b/tests/live-browser-session.test.mjs
index 678c43488..ced79119c 100644
--- a/tests/live-browser-session.test.mjs
+++ b/tests/live-browser-session.test.mjs
@@ -86,4 +86,18 @@ describe('live-browser-session state helper', () => {
const session = loadSession({ crypto: { randomUUID() { throw new TypeError('not allowed'); } } });
assert.match(session.randomUUID(), UUID_V4);
});
+ it('starts with no persistence when reading localStorage is denied', () => {
+ const context = vm.createContext({});
+ // Defined from inside the realm: an accessor set on the sandbox object
+ // from outside is not invoked for in-realm global reads.
+ vm.runInContext(
+ "Object.defineProperty(globalThis, 'localStorage', { get() { throw new Error('SecurityError: storage denied'); } });",
+ context,
+ );
+ vm.runInContext(readFileSync(SCRIPT, 'utf-8'), context);
+ const state = context.__IMPECCABLE_LIVE_SESSION__.createLiveBrowserSessionState({ prefix: 'impeccable-live' });
+ state.saveSession({ id: 'session-a' });
+ assert.equal(state.loadSession(), null);
+ assert.equal(state.nextCheckpointRevision(), 1);
+ });
});
diff --git a/tests/live-browser-source.test.mjs b/tests/live-browser-source.test.mjs
index b2294201b..7a7e3db65 100644
--- a/tests/live-browser-source.test.mjs
+++ b/tests/live-browser-source.test.mjs
@@ -1285,6 +1285,36 @@ describe('live-browser source contracts', () => {
assert.equal(lines?.length, 2, 'both configure rows skip auto-focus on touch');
assert.match(SOURCE, /if \(keepExpanded && touchPrimary\(\)\) preparePageChatInputForTyping\(\);/);
});
+ it('renders DESIGN.md links only for safe schemes', () => {
+ const fn = (name) => SOURCE.match(new RegExp(`\\n function ${name}\\([^)]*\\) \\{[\\s\\S]*?\\n \\}`))?.[0];
+ const sources = ['inlineMd', 'isSafeHref', 'escapeHtml'].map(fn);
+ for (const source of sources) assert.ok(source);
+ const inlineMd = runInNewContext(`${sources.join('\n')}\ninlineMd`, {});
+ // Payloads avoid `)`: the link pattern ends the URL at the first one.
+ for (const href of ['javascript:void 0', 'JavaScript:void 0', 'java\tscript:void 0', ' javascript:void 0', 'data:text/html,x', 'vbscript:x']) {
+ const html = inlineMd(`[docs](${href})`);
+ assert.doesNotMatch(html, /<a /, href);
+ assert.equal(html, 'docs', href);
+ }
+ for (const href of ['https://example.com/a', 'http://localhost:3000', 'mailto:[email protected]', '/docs/x', '#tokens', 'guide.md']) {
+ assert.match(inlineMd(`[docs](${href})`), /^<a href="/, href);
+ }
+ });
+
+ it('removes the helper token from window on every run, including a double-init', () => {
+ for (const alreadyInit of [false, true]) {
+ const window = { __IMPECCABLE_TOKEN__: 'secret', __IMPECCABLE_LIVE_INIT__: alreadyInit };
+ // No port: a fresh run returns right after reading it, before any DOM work.
+ runInNewContext(SOURCE, { window, console });
+ assert.equal('__IMPECCABLE_TOKEN__' in window, false, `alreadyInit=${alreadyInit}`);
+ }
+ });
+ it('reads localStorage for the session helper inside a try', () => {
+ // A denied store throws on the property read itself; unguarded, init
+ // aborts with __IMPECCABLE_LIVE_INIT__ still true and never retries.
+ assert.doesNotMatch(SOURCE, /storage: localStorage,/);
+ assert.match(SOURCE, /try \{ liveStorage = window\.localStorage; \} catch/);
+ });
});
// Exercise Tune's real control listeners and open/close lifecycle without a server.
diff --git a/tests/oracle/cases/detect.mjs b/tests/oracle/cases/detect.mjs
index 608337a79..2e4c2e35c 100644
--- a/tests/oracle/cases/detect.mjs
+++ b/tests/oracle/cases/detect.mjs
@@ -294,6 +294,25 @@ function Thumb({ url }: { url?: string }) {
args: ['--json', target],
})),
+ // `**/` must match root and nested paths without swallowing adjacent names.
+ {
+ id: 'detect-ignore-globstar-directory-boundary-json', verb: 'detect',
+ setup: (ws) => {
+ fs.writeFileSync(path.join(ws, 'package.json'), '{"name":"globstar-ignore"}\n');
+ fs.mkdirSync(path.join(ws, 'docs'), { recursive: true });
+ fs.mkdirSync(path.join(ws, '.impeccable'));
+ fs.writeFileSync(
+ path.join(ws, '.impeccable', 'config.json'),
+ JSON.stringify({ detector: { ignoreFiles: ['**/index.html'] } }) + '\n',
+ );
+ const html = '<style>.card { border-left: 4px solid #ff0000; border-radius: 10px; }</style>\n<div class="card">Card</div>\n';
+ for (const file of ['index.html', 'docs/index.html', 'safeindex.html', 'docs/safeindex.html']) {
+ fs.writeFileSync(path.join(ws, file), html);
+ }
+ },
+ args: ['--json', '.'],
+ },
+
// A DESIGN.md that declares a purple switches ai-color-palette's
// purple/violet forms off for its project, in the static and the regex
// engines alike, and text mode says so; a DESIGN.md without one changes
diff --git a/tests/oracle/golden/detect-ignore-globstar-directory-boundary-json.json b/tests/oracle/golden/detect-ignore-globstar-directory-boundary-json.json
new file mode 100644
index 000000000..63c8e3615
--- /dev/null
+++ b/tests/oracle/golden/detect-ignore-globstar-directory-boundary-json.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "[\n {\n \"antipattern\": \"side-tab\",\n \"name\": \"Side-tab accent border\",\n \"description\": \"Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.\",\n \"severity\": \"warning\",\n \"category\": \"slop\",\n \"file\": \"<WS>/docs/safeindex.html\",\n \"line\": 0,\n \"snippet\": \"border-left: 4px + border-radius: 10px\"\n },\n {\n \"antipattern\": \"side-tab\",\n \"name\": \"Side-tab accent border\",\n \"description\": \"Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.\",\n \"severity\": \"warning\",\n \"category\": \"slop\",\n \"file\": \"<WS>/safeindex.html\",\n \"line\": 0,\n \"snippet\": \"border-left: 4px + border-radius: 10px\"\n }\n]\n",
+ "stderr": "",
+ "exit": 2,
+ "signal": null,
+ "files": {}
+}