mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-11 21:57:14 +03:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2064b0696f | ||
|
|
c3ea1c79f5 | ||
|
|
f849d610f3 | ||
|
|
bfe634e254 | ||
|
|
3c442af7ad | ||
|
|
c0b1ec6fef | ||
|
|
35ae07339b | ||
|
|
c9e7cd8a64 | ||
|
|
c39b6425fa | ||
|
|
2c39c39f16 | ||
|
|
c87e460f5e | ||
|
|
b40982a967 | ||
|
|
82cb738f46 | ||
|
|
49571365a8 | ||
|
|
8056422d87 | ||
|
|
a735bc55cd | ||
|
|
01e5112127 | ||
|
|
2e8f8dfdae | ||
|
|
313d0748f2 | ||
|
|
26bb3d3af5 | ||
|
|
d07edadafb | ||
|
|
1a7ee36324 | ||
|
|
8e3926a3aa | ||
|
|
8522ce7e25 | ||
|
|
809976638d | ||
|
|
9a7d0fbc50 | ||
|
|
ba873f7599 | ||
|
|
7ddcd533a4 | ||
|
|
7426af446e | ||
|
|
a236137bc6 | ||
|
|
ddb609936a | ||
|
|
5444031942 | ||
|
|
067665cc7e | ||
|
|
869c887372 | ||
|
|
8347d77f54 | ||
|
|
bda7411acd | ||
|
|
1b7da15b56 | ||
|
|
d008dd98c3 | ||
|
|
56f44523f7 | ||
|
|
5d4418e2dc | ||
|
|
abba4012ff | ||
|
|
e0a9d8e7d9 | ||
|
|
fccd91c6ac | ||
|
|
e5abceedc4 | ||
|
|
c29f30fa34 | ||
|
|
6360b27823 | ||
|
|
a66aefba80 | ||
|
|
77dd327080 | ||
|
|
ff1f15c7ad | ||
|
|
d2a9efb90f | ||
|
|
16a218e632 | ||
|
|
7b94585653 | ||
|
|
93dce3d62e | ||
|
|
478325a2dd | ||
|
|
8d62b135fe | ||
|
|
611147a333 | ||
|
|
7d5c60d291 | ||
|
|
1f2c3f9d6b | ||
|
|
cf8f295dc3 | ||
|
|
665c51b903 |
@@ -2,9 +2,9 @@
|
||||
|
||||
Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
|
||||
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code and Codex, which both dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit.
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
|
||||
|
||||
Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `context.mjs` asking for a single detector run at the end.
|
||||
|
||||
@@ -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), 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` 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -44,7 +44,7 @@ The first argument is the action. Defaults to `status`.
|
||||
```
|
||||
|
||||
3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `$impeccable hooks on`."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write on a UI file."
|
||||
5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/config.json`; add `--local` only when the user explicitly asks for a private exception.
|
||||
6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
|
||||
|
||||
|
||||
@@ -626,7 +626,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -688,7 +688,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -985,7 +985,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -1115,7 +1115,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -773,14 +773,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
@@ -1955,20 +1963,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -1985,13 +1992,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -3986,7 +3990,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
@@ -7281,7 +7285,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -7343,7 +7347,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -7640,7 +7644,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -7770,7 +7774,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -42,6 +42,7 @@ function shouldRunPageAnalyzers(content, filePath) {
|
||||
}
|
||||
|
||||
const JS_SOURCE_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']);
|
||||
const STYLESHEET_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
const REGEX_PREFIX_KEYWORDS = new Set(['await', 'case', 'default', 'delete', 'do', 'else', 'in', 'instanceof', 'new', 'of', 'return', 'throw', 'typeof', 'void', 'yield']);
|
||||
const BLOCK_BRACE_PREFIX_KEYWORDS = new Set(['do', 'else', 'finally', 'try']);
|
||||
|
||||
@@ -256,6 +257,153 @@ function stripCssComments(content) {
|
||||
return content.replace(/\/\*[\s\S]*?\*\//g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankHtmlComments(text) {
|
||||
return text.replace(/<!--[\s\S]*?-->/g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankCssLineCommentsInStyleBlocks(text) {
|
||||
const re = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
const inner = match[1];
|
||||
const openLength = match[0].length - inner.length - '</style>'.length;
|
||||
output += text.slice(lastIndex, match.index);
|
||||
output += match[0].slice(0, openLength);
|
||||
output += blankCssLineComments(inner);
|
||||
output += match[0].slice(openLength + inner.length);
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + text.slice(lastIndex);
|
||||
}
|
||||
|
||||
function blankHtmlAndCssCommentsOutsideScripts(text) {
|
||||
const re = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
output += blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex, match.index))));
|
||||
output += match[0];
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex))));
|
||||
}
|
||||
|
||||
function blankCssLineComments(text) {
|
||||
let output = '';
|
||||
let state = 'code';
|
||||
let urlDepth = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
const next = text[i + 1];
|
||||
if (state === 'line') {
|
||||
if (char === '\n') {
|
||||
output += '\n';
|
||||
state = 'code';
|
||||
} else {
|
||||
output += ' ';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state === 'single' || state === 'double') {
|
||||
output += char;
|
||||
if (char === '\\' && next) {
|
||||
output += next;
|
||||
i++;
|
||||
} else if ((state === 'single' && char === "'") || (state === 'double' && char === '"')) {
|
||||
state = 'code';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const prev = output.length ? output[output.length - 1] : '';
|
||||
if (char === '/' && next === '/' && urlDepth === 0 && prev !== ':' && prev !== '(' && prev !== '\\') {
|
||||
output += ' ';
|
||||
i++;
|
||||
state = 'line';
|
||||
continue;
|
||||
}
|
||||
if (char === "'") state = 'single';
|
||||
else if (char === '"') state = 'double';
|
||||
if (char === '(') {
|
||||
const behind = output.replace(/\s+$/, '');
|
||||
if (urlDepth > 0 || /url$/i.test(behind)) urlDepth++;
|
||||
} else if (char === ')' && urlDepth) {
|
||||
urlDepth--;
|
||||
}
|
||||
output += char;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function findAstroFrontmatterClose(text) {
|
||||
if (!text.startsWith('---')) return -1;
|
||||
let cursor = text.indexOf('\n');
|
||||
if (cursor === -1) return -1;
|
||||
cursor += 1;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor - 1] === '\n' && text.startsWith('---', cursor)) {
|
||||
let end = cursor + 3;
|
||||
while (text[end] === ' ' || text[end] === '\t') end++;
|
||||
if (end >= text.length || text[end] === '\n' || text[end] === '\r') return cursor - 1;
|
||||
}
|
||||
const char = text[cursor];
|
||||
const next = text[cursor + 1];
|
||||
if (char === "'" || char === '"') {
|
||||
const close = findQuotedStringEnd(text, cursor, char);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '`') {
|
||||
const close = findTemplateLiteralEnd(text, cursor);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '/') {
|
||||
const lineEnd = text.indexOf('\n', cursor);
|
||||
if (lineEnd === -1) return -1;
|
||||
cursor = lineEnd;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '*') {
|
||||
const commentEnd = text.indexOf('*/', cursor + 2);
|
||||
if (commentEnd === -1) return -1;
|
||||
cursor = commentEnd + 2;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next !== '/' && next !== '*') {
|
||||
const close = findRegexLiteralEnd(text, cursor);
|
||||
if (close !== -1) {
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cursor++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function blankAstroFrontmatterComments(text) {
|
||||
const close = findAstroFrontmatterClose(text);
|
||||
if (close === -1) return text;
|
||||
return stripJsComments(text.slice(0, close)) + text.slice(close);
|
||||
}
|
||||
|
||||
function blankCommentsForMatchers(text, ext) {
|
||||
if (PAGE_ANALYZER_EXTS.has(ext)) {
|
||||
const withFrontmatter = ext === '.astro' ? blankAstroFrontmatterComments(text) : text;
|
||||
return blankHtmlAndCssCommentsOutsideScripts(withFrontmatter);
|
||||
}
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
const withoutBlocks = stripCssComments(text);
|
||||
return ext === '.css' ? withoutBlocks : blankCssLineComments(withoutBlocks);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function firstOverusedGoogleFont(text) {
|
||||
return extractGoogleFontFamilies(text).find(f => OVERUSED_FONTS.has(f)) || '';
|
||||
}
|
||||
@@ -1028,14 +1176,13 @@ function detectText(content, filePath, options = {}) {
|
||||
const ext = extFromFilePath(filePath);
|
||||
const commentStrippedSource = JS_SOURCE_EXTS.has(ext) ? stripJsComments(content, {
|
||||
jsx: ext === '.js' || ext === '.jsx' || ext === '.tsx',
|
||||
}) : content;
|
||||
}) : blankCommentsForMatchers(content, ext);
|
||||
const source = stripCssInJsComments(commentStrippedSource, ext);
|
||||
const lines = source.split('\n');
|
||||
|
||||
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
|
||||
// Enable block context for CSS files where related properties span multiple lines
|
||||
const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, STYLESHEET_EXTS.has(ext) || null, {
|
||||
profile,
|
||||
phase: 'source',
|
||||
}));
|
||||
@@ -1050,7 +1197,7 @@ function detectText(content, filePath, options = {}) {
|
||||
scanCssTextForPseudoStripe(text).map(hit =>
|
||||
finding(hit.id, filePath, hit.snippet, lineOffset + text.slice(0, hit.index).split('\n').length));
|
||||
|
||||
if (cssLike.has(ext)) {
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
findings.push(...scanInsetStripeCss(content, filePath));
|
||||
findings.push(...pseudoStripeFindings(content, 0));
|
||||
}
|
||||
@@ -1078,7 +1225,8 @@ function detectText(content, filePath, options = {}) {
|
||||
}, () => extractStyleBlocks(content, ext))
|
||||
: extractStyleBlocks(content, ext);
|
||||
for (const block of styleBlocks) {
|
||||
const blockLines = block.content.split('\n');
|
||||
const blockContent = blankCssLineComments(stripCssComments(block.content));
|
||||
const blockLines = blockContent.split('\n');
|
||||
findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
|
||||
profile,
|
||||
phase: 'style-block',
|
||||
@@ -1089,8 +1237,8 @@ function detectText(content, filePath, options = {}) {
|
||||
// 1-based, so the offset is startLine - 2; startLine - 1 double-counted and
|
||||
// reported every selector one line low. runRegexMatchers keeps startLine - 1
|
||||
// because it indexes its split lines from zero.
|
||||
findings.push(...scanInsetStripeCss(block.content, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(block.content, block.startLine - 2));
|
||||
findings.push(...scanInsetStripeCss(blockContent, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(blockContent, block.startLine - 2));
|
||||
}
|
||||
|
||||
// Extract and scan CSS-in-JS template literals
|
||||
|
||||
@@ -721,20 +721,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -751,13 +750,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -2752,7 +2748,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
|
||||
@@ -103,14 +103,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
|
||||
@@ -33,13 +33,8 @@ import {
|
||||
stampProductSchema,
|
||||
} from './lib/artifact-schema.mjs';
|
||||
import {
|
||||
checkBuildPathUnset,
|
||||
checkConfig,
|
||||
checkDesignSidecar,
|
||||
collectBootFindingGroups,
|
||||
checkNativePlatformEvidence,
|
||||
checkProduct,
|
||||
checkProjectRoots,
|
||||
checkSurfaceBriefs,
|
||||
designSidecarCandidatesFor,
|
||||
} from './lib/staleness.mjs';
|
||||
import {
|
||||
@@ -106,34 +101,30 @@ async function collect(cwd, targetOptions) {
|
||||
extractPlatform,
|
||||
readFile: safeRead,
|
||||
});
|
||||
const bootFindings = collectBootFindingGroups(ctx, {
|
||||
absDesignPath,
|
||||
sidecarCandidates,
|
||||
projectRootPatterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
targetCandidates: workspaceCandidates,
|
||||
});
|
||||
|
||||
const findings = [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
...(ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({ designPath: absDesignPath, sidecarCandidates, projectRoot }),
|
||||
...bootFindings.product,
|
||||
...bootFindings.nativePlatform,
|
||||
...bootFindings.designSidecar,
|
||||
...checkDesignDrift({ designPath: absDesignPath, projectRoot }),
|
||||
...checkDesignCoverage({ design: ctx.design, designPath: ctx.designPath, parseDesignMd }),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...bootFindings.config,
|
||||
...bootFindings.buildPath,
|
||||
...checkDetectorIgnores({ projectRoot, knownRuleIds }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...bootFindings.surfaceBriefs,
|
||||
...checkHookInstallation({
|
||||
projectRoot,
|
||||
repoRoot: ctx.repoRoot,
|
||||
providerId: IMPECCABLE_PROVIDER_ID,
|
||||
}),
|
||||
...checkLegacyLiveState({ projectRoot }),
|
||||
...checkProjectRoots({
|
||||
patterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
candidates: workspaceCandidates,
|
||||
}),
|
||||
...bootFindings.projectRoots,
|
||||
...workspaceResult.findings,
|
||||
];
|
||||
|
||||
|
||||
@@ -75,11 +75,11 @@ const HOOK_MANIFEST_TARGETS = [
|
||||
destRel: '.claude/settings.local.json',
|
||||
sharedDestRel: '.claude/settings.json',
|
||||
manifest: () => ({
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.',
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.',
|
||||
hooks: {
|
||||
PostToolUse: [
|
||||
{
|
||||
matcher: 'Edit|Write|MultiEdit',
|
||||
matcher: 'Edit|Write',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
|
||||
@@ -816,9 +816,9 @@ export function splitFindingsByTier(findings) {
|
||||
}
|
||||
|
||||
// Whether the per-edit pass for this harness should defer non-immediate
|
||||
// findings to a Stop deep pass. Only Claude Code and Codex dispatch our Stop
|
||||
// hook; Cursor and GitHub Copilot have no deep pass wired, so deferring for
|
||||
// them would silently drop the non-immediate rules entirely.
|
||||
// findings to a Stop deep pass. Claude Code, Codex, and Grok Build dispatch
|
||||
// our Stop hook; Cursor and GitHub Copilot have no deep pass wired, so
|
||||
// deferring for them would silently drop the non-immediate rules entirely.
|
||||
export function perEditTieringActive(config, harness) {
|
||||
if (harness === 'cursor' || harness === 'github') return false;
|
||||
return (config?.perEditRules || DEFAULT_CONFIG.perEditRules) !== 'all';
|
||||
@@ -1251,9 +1251,14 @@ export function resolveHarness(env = {}, event = null) {
|
||||
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
|
||||
if (explicit === 'cursor') return 'cursor';
|
||||
if (explicit === 'github') return 'github';
|
||||
if (explicit === 'grok') return 'grok';
|
||||
if (explicit === 'claude' || explicit === 'codex') return 'claude';
|
||||
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
|
||||
// has no `tool_name`/`tool_input`. That shape is the discriminator.
|
||||
// Grok Build sends camelCase `toolName`/`toolInput`/`hookEventName` and no
|
||||
// snake_case pair. GitHub Copilot sends camelCase `toolName`/`toolArgs`.
|
||||
// Check Grok first: the old GitHub heuristic (`toolName` and no
|
||||
// `tool_input`) also matches Grok, which is how live PostToolUse was
|
||||
// classified as Copilot and then skipped with no-file-path (#646).
|
||||
if (looksLikeGrokEnvelope(event)) return 'grok';
|
||||
if (event && typeof event === 'object'
|
||||
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
|
||||
&& event.tool_name === undefined && event.tool_input === undefined) {
|
||||
@@ -1263,6 +1268,27 @@ export function resolveHarness(env = {}, event = null) {
|
||||
return 'claude';
|
||||
}
|
||||
|
||||
function looksLikeGrokEnvelope(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
if (event.hook_event_name !== undefined
|
||||
|| event.tool_name !== undefined
|
||||
|| event.tool_input !== undefined) {
|
||||
return false;
|
||||
}
|
||||
if (event.toolArgs !== undefined) return false;
|
||||
if (typeof event.hookEventName === 'string') return true;
|
||||
return typeof event.toolName === 'string' && event.toolInput !== undefined;
|
||||
}
|
||||
|
||||
// Stop arrives as Claude's `hook_event_name: "Stop"` or Grok Build's
|
||||
// `hookEventName: "stop"`. hook.mjs routes on the raw stdin, before any
|
||||
// normalize, so both casings must match here.
|
||||
export function isStopEvent(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const name = event.hook_event_name || event.hookEventName;
|
||||
return typeof name === 'string' && name.toLowerCase() === 'stop';
|
||||
}
|
||||
|
||||
// GitHub Copilot's postToolUse payload is
|
||||
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
|
||||
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
|
||||
@@ -1354,9 +1380,36 @@ function normalizeGitHubEvent(event, projectCwd) {
|
||||
};
|
||||
}
|
||||
|
||||
// Grok Build 1.0.5 (captured 2026-08-24) sends camelCase `toolName` /
|
||||
// `toolInput` / `sessionId` / `stopHookActive`, plus `cwd` alongside a
|
||||
// trailing-slashed `workspaceRoot` (every consumer path.resolve()s, so no
|
||||
// stripping here). Only the fields the hook reads are copied; the event
|
||||
// name stays camelCase because routing already happened on the raw stdin
|
||||
// (isStopEvent) and nothing downstream reads `hook_event_name`.
|
||||
function normalizeGrokEvent(event, projectCwd) {
|
||||
const cwd = event.cwd || event.workspaceRoot || envProjectDir(projectCwd) || projectCwd;
|
||||
const sessionId = event.sessionId || event.session_id || 'unknown';
|
||||
const rawInput = event.toolInput ?? event.tool_input;
|
||||
const toolInput = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
|
||||
? { ...rawInput }
|
||||
: {};
|
||||
const out = {
|
||||
...event,
|
||||
cwd,
|
||||
session_id: sessionId,
|
||||
tool_name: event.toolName || event.tool_name || null,
|
||||
tool_input: toolInput,
|
||||
};
|
||||
if (event.stopHookActive !== undefined && event.stop_hook_active === undefined) {
|
||||
out.stop_hook_active = event.stopHookActive;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
|
||||
if (!event || typeof event !== 'object') return event;
|
||||
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
|
||||
if (harness === 'grok') return normalizeGrokEvent(event, projectCwd);
|
||||
if (harness !== 'cursor') return event;
|
||||
|
||||
const cwd = event.cwd
|
||||
@@ -1959,7 +2012,15 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// findings stop being remembered and a reintroduced one reads as fresh.
|
||||
// Only the immediate tier is remembered: a deferred finding the per-edit
|
||||
// pass never reported must still read as fresh to the Stop deep pass.
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
//
|
||||
// Grok ignores PostToolUse stdout, so Stop is the user-visible pass.
|
||||
// Remembering here would dedupe those findings out of Stop. Touch the
|
||||
// file so Stop has it, and leave the finding list empty.
|
||||
if (harness === 'grok') {
|
||||
touchFile(cache, sessionId, filePath);
|
||||
} else {
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
}
|
||||
cacheDirty = true;
|
||||
|
||||
if (fresh.length > 0) {
|
||||
@@ -2191,22 +2252,32 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
event = normalizeHookEvent(event, cwd, harness);
|
||||
|
||||
// Claude Code's Stop-hook contract: `stop_hook_active` is true when this
|
||||
// hook is being re-invoked only because a prior invocation kept the turn
|
||||
// alive (here, via hookSpecificOutput.additionalContext). Re-scanning and
|
||||
// re-blocking now would loop until Claude Code's consecutive-block cap
|
||||
// force-ends the turn (issue #400). The prior fire already surfaced the
|
||||
// findings; whether to act on them is the agent's call. Exit fast with no
|
||||
// output before any scan. Only Claude Code sends this field; other
|
||||
// harnesses omit it, so the strict `=== true` is a no-op for them. This
|
||||
// guard makes the loop impossible regardless of the finding cache key's
|
||||
// line-number sensitivity (out of scope here; see findingCacheKey).
|
||||
// output before any scan. Claude sends `stop_hook_active`; Grok sends
|
||||
// `stopHookActive`, copied onto the snake_case field above. The strict
|
||||
// `=== true` is a no-op when the field is absent. This guard makes the
|
||||
// loop impossible regardless of the finding cache key's line-number
|
||||
// sensitivity (out of scope here; see findingCacheKey).
|
||||
if (event.stop_hook_active === true) {
|
||||
return result({ skipped: 'stop-hook-active', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
// Grok fires Stop twice: `end_turn` (the gate that can inject
|
||||
// additionalContext) then an observe-only `shutdown`. A second deep
|
||||
// pass would re-emit the same findings. Claude omits `reason`; only
|
||||
// skip when Grok named a reason that is not end_turn.
|
||||
if (harness === 'grok' && typeof event.reason === 'string' && event.reason !== 'end_turn') {
|
||||
return result({ skipped: 'stop-reason', reason: event.reason, durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
// A Stop event carries no file, so the session cwd is the project.
|
||||
// Umbrella-dir launches keyed their per-edit cache to the edited file's
|
||||
@@ -2241,6 +2312,7 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
|
||||
const freshGroups = [];
|
||||
let scanned = 0;
|
||||
let cacheDirty = false;
|
||||
for (const filePath of touched) {
|
||||
if (scanned >= STOP_MAX_FILES) break;
|
||||
if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) continue;
|
||||
@@ -2261,29 +2333,39 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
|
||||
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
const useHtmlEngine = configuredExt
|
||||
? configuredExt.engine === 'html'
|
||||
: (ext === '.html' || ext === '.htm');
|
||||
|
||||
if (useHtmlEngine && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
// A detector failure tells us nothing about the file. Leave whatever
|
||||
// was remembered alone rather than recording an empty scan as truth.
|
||||
if (detectorThrew) continue;
|
||||
|
||||
// Full rule set: no tier split here. Config/inline ignores still apply,
|
||||
// and the session dedupe drops everything the per-edit pass (or an
|
||||
// earlier Stop pass) already surfaced.
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
|
||||
// Sync to the live scan, including empty. Remembering only `fresh`
|
||||
// (or skipping the write on a clean Stop) left stale keys in place, so
|
||||
// a finding that was fixed and later reintroduced never fired again.
|
||||
rememberFindings(cache, sessionId, filePath, filtered);
|
||||
cacheDirty = true;
|
||||
if (fresh.length > 0) {
|
||||
rememberFindings(cache, sessionId, filePath, fresh);
|
||||
freshGroups.push({ filePath, findings: fresh });
|
||||
}
|
||||
}
|
||||
audit.scannedFiles = scanned;
|
||||
|
||||
if (freshGroups.length === 0) {
|
||||
if (cacheDirty) persistCache(projectCwd, cache);
|
||||
return result({ emitted: false, skipped: 'stop-clean', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
@@ -2300,8 +2382,8 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
);
|
||||
commitFooterShown(cache, sessionId, text);
|
||||
|
||||
// Fresh findings earn the cache write so the next Stop fire is silent
|
||||
// unless new issues appear; the notice flags ride along.
|
||||
// Persist the live finding set so the next Stop fire is silent unless
|
||||
// new issues appear; the notice flags ride along.
|
||||
persistCache(projectCwd, cache);
|
||||
return {
|
||||
exitCode: 0,
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
/**
|
||||
* Impeccable design hook — PostToolUse + Stop entry point.
|
||||
*
|
||||
* Reads the Claude Code / Codex / Cursor hook event from stdin and routes by
|
||||
* `hook_event_name`:
|
||||
* Reads the Claude Code / Codex / Cursor / Grok Build hook event from stdin
|
||||
* and routes by Stop vs everything else. Claude uses `hook_event_name:
|
||||
* "Stop"`; Grok uses `hookEventName: "stop"`.
|
||||
*
|
||||
* - PostToolUse: runs the immediate-tier detector rules against the touched
|
||||
* file and emits a system reminder via
|
||||
* `hookSpecificOutput.additionalContext` when findings exist.
|
||||
* `hookSpecificOutput.additionalContext` when findings exist. Grok
|
||||
* discards that stdout; the scan still warms the session cache for Stop.
|
||||
* - Stop: runs the FULL detector rule set over every UI file touched this
|
||||
* session (the deep pass), deduped against what the per-edit pass already
|
||||
* surfaced, and emits once via the Stop additionalContext channel.
|
||||
@@ -19,7 +21,7 @@
|
||||
* subprocess. This file is the thin stdin/stdout adapter.
|
||||
*/
|
||||
|
||||
import { runHook, runStopHook, writeAuditLog } from './hook-lib.mjs';
|
||||
import { runHook, runStopHook, writeAuditLog, isStopEvent } from './hook-lib.mjs';
|
||||
|
||||
async function readStdin() {
|
||||
if (process.stdin.isTTY) return '';
|
||||
@@ -28,10 +30,9 @@ async function readStdin() {
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
function isStopEvent(stdinJson) {
|
||||
function stdinIsStop(stdinJson) {
|
||||
try {
|
||||
const event = JSON.parse(stdinJson);
|
||||
return event && typeof event === 'object' && event.hook_event_name === 'Stop';
|
||||
return isStopEvent(JSON.parse(stdinJson));
|
||||
} catch {
|
||||
// Malformed stdin falls through to runHook, which audits the skip.
|
||||
return false;
|
||||
@@ -48,7 +49,7 @@ async function main() {
|
||||
let stdinJson = '';
|
||||
try { stdinJson = await readStdin(); } catch { /* fall through */ }
|
||||
|
||||
const run = isStopEvent(stdinJson) ? runStopHook : runHook;
|
||||
const run = stdinIsStop(stdinJson) ? runStopHook : runHook;
|
||||
const result = await run({
|
||||
stdinJson,
|
||||
env: inheritedEnv,
|
||||
|
||||
@@ -196,9 +196,6 @@ function parseScalar(raw) {
|
||||
|
||||
const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
|
||||
const OKLCH_RE = /oklch\([^)]+\)/gi;
|
||||
const RGBA_RE = /rgba?\([^)]+\)/gi;
|
||||
const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
|
||||
const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
|
||||
|
||||
// ---------- Section splitting ----------
|
||||
|
||||
@@ -550,36 +547,6 @@ function detectFormat(v) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function scanInlineColors(lines) {
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '');
|
||||
const color = parseColorBullet(trimmed);
|
||||
if (color) out.push(color);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseStitchInlineGroups(lines) {
|
||||
// Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
|
||||
// Each bullet IS its own role. Group them under the spoken role name.
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
|
||||
const m = trimmed.match(
|
||||
/^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
|
||||
);
|
||||
if (m) {
|
||||
const role = m[1];
|
||||
const color = buildColor(role, m[2], m[3]);
|
||||
out.push({ role, colors: [color] });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractTypography(section) {
|
||||
if (!section) return null;
|
||||
const text = section.lines.join('\n');
|
||||
|
||||
@@ -488,41 +488,46 @@ export function describeWorkspaceContext(candidates = []) {
|
||||
// ─── Tier 1 orchestration ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Everything a boot can afford. `ctx` is the loadContext result; `extras`
|
||||
* carries values the caller already computed so nothing is recomputed here.
|
||||
* Everything a boot can afford, grouped by artifact so deeper reports can
|
||||
* interleave their own checks without rebuilding this policy. `ctx` is the
|
||||
* loadContext result; `extras` carries values the caller already computed so
|
||||
* nothing is recomputed here.
|
||||
*/
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
if (!ctx) return [];
|
||||
export function collectBootFindingGroups(ctx, extras = {}) {
|
||||
if (!ctx) return {};
|
||||
const projectRoot = ctx.projectRoot || process.cwd();
|
||||
const absProductPath = extras.absProductPath || null;
|
||||
const absDesignPath = extras.absDesignPath || null;
|
||||
|
||||
return [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
return {
|
||||
product: checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
// Only checked once a PRODUCT.md exists. Without one the boot already
|
||||
// emits NO_PRODUCT_MD and routes into init, which asks for the platform
|
||||
// directly; a second signal saying the same thing is noise.
|
||||
...(ctx.product
|
||||
nativePlatform: ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({
|
||||
: [],
|
||||
designSidecar: checkDesignSidecar({
|
||||
designPath: absDesignPath,
|
||||
sidecarCandidates: extras.sidecarCandidates || [],
|
||||
projectRoot,
|
||||
}),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...(extras.projectRootPatterns
|
||||
config: checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
buildPath: checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
surfaceBriefs: checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
projectRoots: extras.projectRootPatterns
|
||||
? checkProjectRoots({
|
||||
patterns: extras.projectRootPatterns,
|
||||
candidates: extras.targetCandidates || [],
|
||||
})
|
||||
: []),
|
||||
];
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
return Object.values(collectBootFindingGroups(ctx, extras)).flat();
|
||||
}
|
||||
|
||||
@@ -4902,6 +4902,13 @@
|
||||
saveSession();
|
||||
}
|
||||
|
||||
function completeParameterGenerationIfReady() {
|
||||
if (expectedVariants <= 0 || arrivedVariants < expectedVariants) return;
|
||||
if (parameterGenerationState === 'pending' || parameterGenerationState === 'loading') {
|
||||
completeParameterPublication();
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTunePopover() {
|
||||
if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }
|
||||
if (tuneOpen) { closeTunePopover(); return; }
|
||||
@@ -5796,7 +5803,7 @@
|
||||
setLiveState('CYCLING');
|
||||
showOrUpdateCyclingBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5884,7 +5891,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');
|
||||
} catch (err) {
|
||||
console.error('[impeccable] Failed to mount component-preview variants:', err);
|
||||
@@ -6329,7 +6336,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
|
||||
})
|
||||
.catch(err => {
|
||||
@@ -6836,6 +6843,7 @@
|
||||
|
||||
const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
|
||||
if (expected > 0) expectedVariants = expected;
|
||||
completeParameterGenerationIfReady();
|
||||
|
||||
if (arrivedVariants > 0) {
|
||||
setLiveState('CYCLING');
|
||||
|
||||
@@ -944,8 +944,42 @@ export async function commitManualEdits({
|
||||
};
|
||||
}
|
||||
|
||||
const repairContext = {
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
};
|
||||
|
||||
const baseRollbackScope = collectApplyOwnedFiles(batch, cwd);
|
||||
const rollbackSnapshot = snapshotRollbackFiles(cwd, baseRollbackScope);
|
||||
const failWithRollback = ({
|
||||
scope = baseRollbackScope,
|
||||
extraFiles = [],
|
||||
failed,
|
||||
files = [],
|
||||
details = {},
|
||||
}) => {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, extraFiles, scope);
|
||||
return {
|
||||
applied: [],
|
||||
failed,
|
||||
files,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
...details,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
result = repairOnly
|
||||
@@ -965,42 +999,27 @@ export async function commitManualEdits({
|
||||
chatAvailable,
|
||||
});
|
||||
} catch (err) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, [], baseRollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
failed: batch.entries.map((entry) => ({
|
||||
id: entry.id,
|
||||
reason: err.message || String(err),
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
})),
|
||||
files: [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'error') {
|
||||
const rollbackScope = collectApplyOwnedFiles(batch, cwd, result.files || []);
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const failed = normalizeFailedEntries(batch, result, result.message || 'AI copy edit failed');
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: failed.length > 0
|
||||
? failed
|
||||
: verificationFailuresForEntries(batch, batch.entries, result.message || 'AI copy edit failed'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedIds = uniqueStrings(result.appliedEntryIds || []);
|
||||
@@ -1013,72 +1032,44 @@ export async function commitManualEdits({
|
||||
const conflictingAppliedIds = reportedAppliedIds.filter((id) => failedIds.has(id));
|
||||
|
||||
if (conflictingAppliedIds.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const conflictingEntries = batch.entries.filter((entry) => conflictingAppliedIds.includes(entry.id));
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...verificationFailuresForEntries(batch, conflictingEntries, 'conflicting_apply_result'),
|
||||
...aiFailed.filter((item) => !conflictingAppliedIds.includes(item.id)),
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const unreportedFiles = unreportedChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
if (unreportedFiles.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], [...rollbackScope, ...unreportedFiles]);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: [...rollbackScope, ...unreportedFiles],
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'unreported_source_changes', { files: unreportedFiles }),
|
||||
files: result.files || [],
|
||||
unreportedFiles,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { unreportedFiles, notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'done' && reportedAppliedIds.length === 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'missing_applied_entry_ids'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedEntries = batch.entries.filter((entry) => reportedAppliedIds.includes(entry.id));
|
||||
if (reportedAppliedIds.length > 0 && reportedFiles.length === 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: aiFailed,
|
||||
@@ -1089,21 +1080,10 @@ export async function commitManualEdits({
|
||||
});
|
||||
}
|
||||
|
||||
const verifiedAppliedIds = [];
|
||||
const verificationFailed = [];
|
||||
for (const entry of reportedAppliedEntries) {
|
||||
const failures = verifyAppliedEntry({ batch, entry, reportedFiles, cwd });
|
||||
if (failures.length === 0) {
|
||||
verifiedAppliedIds.push(entry.id);
|
||||
} else {
|
||||
verificationFailed.push({
|
||||
id: entry.id,
|
||||
reason: 'source_verification_failed',
|
||||
failures,
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
const {
|
||||
verifiedIds: verifiedAppliedIds,
|
||||
failed: verificationFailed,
|
||||
} = verifyEntriesAfterRepair({ batch, appliedEntryIds: reportedAppliedIds, files: reportedFiles, cwd });
|
||||
const unreportedEntries = result.status === 'done' || result.status === 'partial'
|
||||
? batch.entries.filter((entry) => !reportedAppliedIds.includes(entry.id) && !aiFailed.some((item) => item.id === entry.id))
|
||||
: [];
|
||||
@@ -1133,37 +1113,22 @@ export async function commitManualEdits({
|
||||
reason: 'rolled_back_due_to_failed_entry_source_changed',
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
}));
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...leakedUnapplied,
|
||||
...failed.filter((item) => !leakedIds.has(item.id)),
|
||||
...rolledBackVerified,
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
notes: result.notes || [],
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (verificationFailed.length > 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: nonRepairFailed,
|
||||
@@ -1180,16 +1145,7 @@ export async function commitManualEdits({
|
||||
? reportedAppliedEntries.filter((entry) => verifiedAppliedIds.includes(entry.id))
|
||||
: batch.entries;
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: verifiedAppliedIds.length > 0
|
||||
? verifiedAppliedIds
|
||||
: postCheckEntries.map((entry) => entry.id).filter(Boolean),
|
||||
|
||||
@@ -238,10 +238,9 @@ export async function completeAcceptHandling(event, base, token) {
|
||||
});
|
||||
} catch (err) {
|
||||
event._completionAck = { ok: false, error: err.message };
|
||||
return event;
|
||||
}
|
||||
if (!event._completionAck) {
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
}
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -269,9 +268,11 @@ export function printPollEvent(event) {
|
||||
// Situational plumbing rides with the event itself: `_instructions` is the
|
||||
// authoritative next step, with real ids and paths substituted, so the
|
||||
// reference doc can stay lean and can never drift from script behavior.
|
||||
if (event && typeof event === 'object' && !event._instructions) {
|
||||
// A wire-supplied value must never win over the locally generated one.
|
||||
if (event && typeof event === 'object') {
|
||||
const instructions = instructionsForEvent(event, { scriptsPath: SELF_DIR });
|
||||
if (instructions) event._instructions = instructions;
|
||||
else delete event._instructions;
|
||||
}
|
||||
console.log(JSON.stringify(event));
|
||||
}
|
||||
|
||||
@@ -181,8 +181,16 @@ function chatAgentLikelyActive() {
|
||||
// cap at 10 MB to guard against runaway writes from a misbehaving client.
|
||||
const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
const POLLER_OWNED_EVENT_FIELDS = ['_instructions', '_completionAck', '_acceptResult'];
|
||||
|
||||
function stripPollerOwnedEventFields(event) {
|
||||
if (!event || typeof event !== 'object') return;
|
||||
for (const key of POLLER_OWNED_EVENT_FIELDS) delete event[key];
|
||||
}
|
||||
|
||||
function enqueueEvent(event) {
|
||||
if (!event) return;
|
||||
stripPollerOwnedEventFields(event);
|
||||
// Dedupe by (session, type), except mount failures, which are per-variant:
|
||||
// variant 2 failing must not be swallowed because variant 1's failure is
|
||||
// still queued.
|
||||
@@ -936,15 +944,23 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
const filePath = url.searchParams.get('path');
|
||||
if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
|
||||
const absPath = path.resolve(process.cwd(), filePath);
|
||||
// Confine to the project root. A bare `startsWith(cwd)` string check lets a
|
||||
// sibling dir whose name extends the root name (projeto -> projeto-backup)
|
||||
// slip through; compare on the relative path instead (same pattern as
|
||||
// sessionFileMetadataFromPollReply below). An empty rel means the request
|
||||
// resolved to the root directory itself, which this file route never serves.
|
||||
const rel = path.relative(process.cwd(), absPath);
|
||||
let realRoot, realTarget;
|
||||
try {
|
||||
realRoot = fs.realpathSync(process.cwd());
|
||||
realTarget = fs.realpathSync(absPath);
|
||||
} catch {
|
||||
res.writeHead(404); res.end('File not found'); return;
|
||||
}
|
||||
// Confine to the project root after symlink resolution. A bare
|
||||
// `startsWith(cwd)` string check lets a sibling dir whose name extends the
|
||||
// root name (projeto -> projeto-backup) slip through; compare on the
|
||||
// relative path instead (same pattern as sessionFileMetadataFromPollReply
|
||||
// below). An empty rel means the request resolved to the root directory
|
||||
// itself, which this file route never serves.
|
||||
const rel = path.relative(realRoot, realTarget);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { res.writeHead(403); res.end('Forbidden'); return; }
|
||||
let content;
|
||||
try { content = fs.readFileSync(absPath, 'utf-8'); }
|
||||
try { content = fs.readFileSync(realTarget, 'utf-8'); }
|
||||
catch { res.writeHead(404); res.end('File not found'); return; }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(content);
|
||||
@@ -1026,6 +1042,7 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
res.end(JSON.stringify({ error }));
|
||||
return;
|
||||
}
|
||||
stripPollerOwnedEventFields(msg);
|
||||
if (msg.type === 'agent_phase') {
|
||||
recordAgentPhase(msg.id, msg.phase, {
|
||||
...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),
|
||||
|
||||
@@ -11,6 +11,8 @@ import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
|
||||
export const SVELTE_LIVE_ROOT_COMPONENT = 'src/lib/impeccable/ImpeccableLiveRoot.svelte';
|
||||
export const SVELTE_LAYOUT_MARKER_OPEN = '<!-- impeccable-live-svelte-start -->';
|
||||
export const SVELTE_LAYOUT_MARKER_CLOSE = '<!-- impeccable-live-svelte-end -->';
|
||||
@@ -45,11 +47,17 @@ export function detectSvelteKitProject(cwd = process.cwd(), config = null) {
|
||||
&& fileIncludes(path.join(cwd, appHtml), '%sveltekit.head%');
|
||||
if (!hasTemplateMarkers) return null;
|
||||
|
||||
const hasSvelteConfig = fs.existsSync(path.join(cwd, 'svelte.config.js'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.mjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.cjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.ts'));
|
||||
const hasKitPackage = packageHasSvelteKit(cwd);
|
||||
const hasSvelteConfig = Boolean(firstExistingFile(cwd, [
|
||||
'svelte.config.js',
|
||||
'svelte.config.mjs',
|
||||
'svelte.config.cjs',
|
||||
'svelte.config.ts',
|
||||
]));
|
||||
const hasKitPackage = hasAnyDependency(cwd, [
|
||||
'@sveltejs/kit',
|
||||
'@sveltejs/vite-plugin-svelte',
|
||||
'svelte',
|
||||
]);
|
||||
if (!hasSvelteConfig && !hasKitPackage) return null;
|
||||
|
||||
return {
|
||||
@@ -260,36 +268,16 @@ function findSvelteKitAppHtml(cwd, config) {
|
||||
}
|
||||
|
||||
function findSvelteKitLayout(cwd) {
|
||||
const candidates = [
|
||||
return firstExistingFile(cwd, [
|
||||
'src/routes/+layout.svelte',
|
||||
'src/routes/(app)/+layout.svelte',
|
||||
];
|
||||
for (const rel of candidates) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return 'src/routes/+layout.svelte';
|
||||
]) || 'src/routes/+layout.svelte';
|
||||
}
|
||||
|
||||
function defaultSvelteLayout() {
|
||||
return `<script>\n let { children } = $props();\n</script>\n\n{@render children?.()}\n`;
|
||||
}
|
||||
|
||||
function packageHasSvelteKit(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fileIncludes(file, text) {
|
||||
try {
|
||||
return fs.readFileSync(file, 'utf-8').includes(text);
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
import { buildLiveScriptSrc } from './frameworks/script-src.mjs';
|
||||
|
||||
export const TANSTACK_MARKER_OPEN = '{/* impeccable-live-tanstack-start */}';
|
||||
@@ -42,8 +44,8 @@ const START_PACKAGES = [
|
||||
];
|
||||
|
||||
export function detectTanStackStartProject(cwd = process.cwd()) {
|
||||
if (!packageHasTanStackStart(cwd)) return null;
|
||||
const rootRoute = findRootRouteFile(cwd);
|
||||
if (!hasAnyDependency(cwd, START_PACKAGES)) return null;
|
||||
const rootRoute = firstExistingFile(cwd, ROOT_ROUTE_CANDIDATES);
|
||||
if (!rootRoute) return null;
|
||||
|
||||
const ext = path.extname(rootRoute);
|
||||
@@ -218,29 +220,6 @@ function isManagedComponent(content) {
|
||||
return String(content || '').includes('impeccable-live-tanstack');
|
||||
}
|
||||
|
||||
function findRootRouteFile(cwd) {
|
||||
for (const rel of ROOT_ROUTE_CANDIDATES) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function packageHasTanStackStart(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return START_PACKAGES.some((name) => Boolean(deps[name]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function relativeImportSpecifier(fromFile, toFile) {
|
||||
const rel = path.posix.relative(
|
||||
path.posix.dirname(fromFile.split(path.sep).join('/')),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"description": "Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.",
|
||||
"description": "Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.",
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write|MultiEdit",
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
|
||||
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code and Codex, which both dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit.
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
|
||||
|
||||
Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `context.mjs` asking for a single detector run at the end.
|
||||
|
||||
@@ -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), 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` 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -44,7 +44,7 @@ The first argument is the action. Defaults to `status`.
|
||||
```
|
||||
|
||||
3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write on a UI file."
|
||||
5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/config.json`; add `--local` only when the user explicitly asks for a private exception.
|
||||
6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
|
||||
|
||||
|
||||
@@ -626,7 +626,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -688,7 +688,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -985,7 +985,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -1115,7 +1115,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -773,14 +773,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
@@ -1955,20 +1963,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -1985,13 +1992,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -3986,7 +3990,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
@@ -7281,7 +7285,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -7343,7 +7347,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -7640,7 +7644,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -7770,7 +7774,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -42,6 +42,7 @@ function shouldRunPageAnalyzers(content, filePath) {
|
||||
}
|
||||
|
||||
const JS_SOURCE_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']);
|
||||
const STYLESHEET_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
const REGEX_PREFIX_KEYWORDS = new Set(['await', 'case', 'default', 'delete', 'do', 'else', 'in', 'instanceof', 'new', 'of', 'return', 'throw', 'typeof', 'void', 'yield']);
|
||||
const BLOCK_BRACE_PREFIX_KEYWORDS = new Set(['do', 'else', 'finally', 'try']);
|
||||
|
||||
@@ -256,6 +257,153 @@ function stripCssComments(content) {
|
||||
return content.replace(/\/\*[\s\S]*?\*\//g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankHtmlComments(text) {
|
||||
return text.replace(/<!--[\s\S]*?-->/g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankCssLineCommentsInStyleBlocks(text) {
|
||||
const re = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
const inner = match[1];
|
||||
const openLength = match[0].length - inner.length - '</style>'.length;
|
||||
output += text.slice(lastIndex, match.index);
|
||||
output += match[0].slice(0, openLength);
|
||||
output += blankCssLineComments(inner);
|
||||
output += match[0].slice(openLength + inner.length);
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + text.slice(lastIndex);
|
||||
}
|
||||
|
||||
function blankHtmlAndCssCommentsOutsideScripts(text) {
|
||||
const re = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
output += blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex, match.index))));
|
||||
output += match[0];
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex))));
|
||||
}
|
||||
|
||||
function blankCssLineComments(text) {
|
||||
let output = '';
|
||||
let state = 'code';
|
||||
let urlDepth = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
const next = text[i + 1];
|
||||
if (state === 'line') {
|
||||
if (char === '\n') {
|
||||
output += '\n';
|
||||
state = 'code';
|
||||
} else {
|
||||
output += ' ';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state === 'single' || state === 'double') {
|
||||
output += char;
|
||||
if (char === '\\' && next) {
|
||||
output += next;
|
||||
i++;
|
||||
} else if ((state === 'single' && char === "'") || (state === 'double' && char === '"')) {
|
||||
state = 'code';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const prev = output.length ? output[output.length - 1] : '';
|
||||
if (char === '/' && next === '/' && urlDepth === 0 && prev !== ':' && prev !== '(' && prev !== '\\') {
|
||||
output += ' ';
|
||||
i++;
|
||||
state = 'line';
|
||||
continue;
|
||||
}
|
||||
if (char === "'") state = 'single';
|
||||
else if (char === '"') state = 'double';
|
||||
if (char === '(') {
|
||||
const behind = output.replace(/\s+$/, '');
|
||||
if (urlDepth > 0 || /url$/i.test(behind)) urlDepth++;
|
||||
} else if (char === ')' && urlDepth) {
|
||||
urlDepth--;
|
||||
}
|
||||
output += char;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function findAstroFrontmatterClose(text) {
|
||||
if (!text.startsWith('---')) return -1;
|
||||
let cursor = text.indexOf('\n');
|
||||
if (cursor === -1) return -1;
|
||||
cursor += 1;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor - 1] === '\n' && text.startsWith('---', cursor)) {
|
||||
let end = cursor + 3;
|
||||
while (text[end] === ' ' || text[end] === '\t') end++;
|
||||
if (end >= text.length || text[end] === '\n' || text[end] === '\r') return cursor - 1;
|
||||
}
|
||||
const char = text[cursor];
|
||||
const next = text[cursor + 1];
|
||||
if (char === "'" || char === '"') {
|
||||
const close = findQuotedStringEnd(text, cursor, char);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '`') {
|
||||
const close = findTemplateLiteralEnd(text, cursor);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '/') {
|
||||
const lineEnd = text.indexOf('\n', cursor);
|
||||
if (lineEnd === -1) return -1;
|
||||
cursor = lineEnd;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '*') {
|
||||
const commentEnd = text.indexOf('*/', cursor + 2);
|
||||
if (commentEnd === -1) return -1;
|
||||
cursor = commentEnd + 2;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next !== '/' && next !== '*') {
|
||||
const close = findRegexLiteralEnd(text, cursor);
|
||||
if (close !== -1) {
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cursor++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function blankAstroFrontmatterComments(text) {
|
||||
const close = findAstroFrontmatterClose(text);
|
||||
if (close === -1) return text;
|
||||
return stripJsComments(text.slice(0, close)) + text.slice(close);
|
||||
}
|
||||
|
||||
function blankCommentsForMatchers(text, ext) {
|
||||
if (PAGE_ANALYZER_EXTS.has(ext)) {
|
||||
const withFrontmatter = ext === '.astro' ? blankAstroFrontmatterComments(text) : text;
|
||||
return blankHtmlAndCssCommentsOutsideScripts(withFrontmatter);
|
||||
}
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
const withoutBlocks = stripCssComments(text);
|
||||
return ext === '.css' ? withoutBlocks : blankCssLineComments(withoutBlocks);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function firstOverusedGoogleFont(text) {
|
||||
return extractGoogleFontFamilies(text).find(f => OVERUSED_FONTS.has(f)) || '';
|
||||
}
|
||||
@@ -1028,14 +1176,13 @@ function detectText(content, filePath, options = {}) {
|
||||
const ext = extFromFilePath(filePath);
|
||||
const commentStrippedSource = JS_SOURCE_EXTS.has(ext) ? stripJsComments(content, {
|
||||
jsx: ext === '.js' || ext === '.jsx' || ext === '.tsx',
|
||||
}) : content;
|
||||
}) : blankCommentsForMatchers(content, ext);
|
||||
const source = stripCssInJsComments(commentStrippedSource, ext);
|
||||
const lines = source.split('\n');
|
||||
|
||||
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
|
||||
// Enable block context for CSS files where related properties span multiple lines
|
||||
const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, STYLESHEET_EXTS.has(ext) || null, {
|
||||
profile,
|
||||
phase: 'source',
|
||||
}));
|
||||
@@ -1050,7 +1197,7 @@ function detectText(content, filePath, options = {}) {
|
||||
scanCssTextForPseudoStripe(text).map(hit =>
|
||||
finding(hit.id, filePath, hit.snippet, lineOffset + text.slice(0, hit.index).split('\n').length));
|
||||
|
||||
if (cssLike.has(ext)) {
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
findings.push(...scanInsetStripeCss(content, filePath));
|
||||
findings.push(...pseudoStripeFindings(content, 0));
|
||||
}
|
||||
@@ -1078,7 +1225,8 @@ function detectText(content, filePath, options = {}) {
|
||||
}, () => extractStyleBlocks(content, ext))
|
||||
: extractStyleBlocks(content, ext);
|
||||
for (const block of styleBlocks) {
|
||||
const blockLines = block.content.split('\n');
|
||||
const blockContent = blankCssLineComments(stripCssComments(block.content));
|
||||
const blockLines = blockContent.split('\n');
|
||||
findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
|
||||
profile,
|
||||
phase: 'style-block',
|
||||
@@ -1089,8 +1237,8 @@ function detectText(content, filePath, options = {}) {
|
||||
// 1-based, so the offset is startLine - 2; startLine - 1 double-counted and
|
||||
// reported every selector one line low. runRegexMatchers keeps startLine - 1
|
||||
// because it indexes its split lines from zero.
|
||||
findings.push(...scanInsetStripeCss(block.content, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(block.content, block.startLine - 2));
|
||||
findings.push(...scanInsetStripeCss(blockContent, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(blockContent, block.startLine - 2));
|
||||
}
|
||||
|
||||
// Extract and scan CSS-in-JS template literals
|
||||
|
||||
@@ -721,20 +721,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -751,13 +750,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -2752,7 +2748,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
|
||||
@@ -103,14 +103,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
|
||||
@@ -33,13 +33,8 @@ import {
|
||||
stampProductSchema,
|
||||
} from './lib/artifact-schema.mjs';
|
||||
import {
|
||||
checkBuildPathUnset,
|
||||
checkConfig,
|
||||
checkDesignSidecar,
|
||||
collectBootFindingGroups,
|
||||
checkNativePlatformEvidence,
|
||||
checkProduct,
|
||||
checkProjectRoots,
|
||||
checkSurfaceBriefs,
|
||||
designSidecarCandidatesFor,
|
||||
} from './lib/staleness.mjs';
|
||||
import {
|
||||
@@ -106,34 +101,30 @@ async function collect(cwd, targetOptions) {
|
||||
extractPlatform,
|
||||
readFile: safeRead,
|
||||
});
|
||||
const bootFindings = collectBootFindingGroups(ctx, {
|
||||
absDesignPath,
|
||||
sidecarCandidates,
|
||||
projectRootPatterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
targetCandidates: workspaceCandidates,
|
||||
});
|
||||
|
||||
const findings = [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
...(ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({ designPath: absDesignPath, sidecarCandidates, projectRoot }),
|
||||
...bootFindings.product,
|
||||
...bootFindings.nativePlatform,
|
||||
...bootFindings.designSidecar,
|
||||
...checkDesignDrift({ designPath: absDesignPath, projectRoot }),
|
||||
...checkDesignCoverage({ design: ctx.design, designPath: ctx.designPath, parseDesignMd }),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...bootFindings.config,
|
||||
...bootFindings.buildPath,
|
||||
...checkDetectorIgnores({ projectRoot, knownRuleIds }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...bootFindings.surfaceBriefs,
|
||||
...checkHookInstallation({
|
||||
projectRoot,
|
||||
repoRoot: ctx.repoRoot,
|
||||
providerId: IMPECCABLE_PROVIDER_ID,
|
||||
}),
|
||||
...checkLegacyLiveState({ projectRoot }),
|
||||
...checkProjectRoots({
|
||||
patterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
candidates: workspaceCandidates,
|
||||
}),
|
||||
...bootFindings.projectRoots,
|
||||
...workspaceResult.findings,
|
||||
];
|
||||
|
||||
|
||||
@@ -75,11 +75,11 @@ const HOOK_MANIFEST_TARGETS = [
|
||||
destRel: '.claude/settings.local.json',
|
||||
sharedDestRel: '.claude/settings.json',
|
||||
manifest: () => ({
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.',
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.',
|
||||
hooks: {
|
||||
PostToolUse: [
|
||||
{
|
||||
matcher: 'Edit|Write|MultiEdit',
|
||||
matcher: 'Edit|Write',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
|
||||
@@ -816,9 +816,9 @@ export function splitFindingsByTier(findings) {
|
||||
}
|
||||
|
||||
// Whether the per-edit pass for this harness should defer non-immediate
|
||||
// findings to a Stop deep pass. Only Claude Code and Codex dispatch our Stop
|
||||
// hook; Cursor and GitHub Copilot have no deep pass wired, so deferring for
|
||||
// them would silently drop the non-immediate rules entirely.
|
||||
// findings to a Stop deep pass. Claude Code, Codex, and Grok Build dispatch
|
||||
// our Stop hook; Cursor and GitHub Copilot have no deep pass wired, so
|
||||
// deferring for them would silently drop the non-immediate rules entirely.
|
||||
export function perEditTieringActive(config, harness) {
|
||||
if (harness === 'cursor' || harness === 'github') return false;
|
||||
return (config?.perEditRules || DEFAULT_CONFIG.perEditRules) !== 'all';
|
||||
@@ -1251,9 +1251,14 @@ export function resolveHarness(env = {}, event = null) {
|
||||
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
|
||||
if (explicit === 'cursor') return 'cursor';
|
||||
if (explicit === 'github') return 'github';
|
||||
if (explicit === 'grok') return 'grok';
|
||||
if (explicit === 'claude' || explicit === 'codex') return 'claude';
|
||||
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
|
||||
// has no `tool_name`/`tool_input`. That shape is the discriminator.
|
||||
// Grok Build sends camelCase `toolName`/`toolInput`/`hookEventName` and no
|
||||
// snake_case pair. GitHub Copilot sends camelCase `toolName`/`toolArgs`.
|
||||
// Check Grok first: the old GitHub heuristic (`toolName` and no
|
||||
// `tool_input`) also matches Grok, which is how live PostToolUse was
|
||||
// classified as Copilot and then skipped with no-file-path (#646).
|
||||
if (looksLikeGrokEnvelope(event)) return 'grok';
|
||||
if (event && typeof event === 'object'
|
||||
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
|
||||
&& event.tool_name === undefined && event.tool_input === undefined) {
|
||||
@@ -1263,6 +1268,27 @@ export function resolveHarness(env = {}, event = null) {
|
||||
return 'claude';
|
||||
}
|
||||
|
||||
function looksLikeGrokEnvelope(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
if (event.hook_event_name !== undefined
|
||||
|| event.tool_name !== undefined
|
||||
|| event.tool_input !== undefined) {
|
||||
return false;
|
||||
}
|
||||
if (event.toolArgs !== undefined) return false;
|
||||
if (typeof event.hookEventName === 'string') return true;
|
||||
return typeof event.toolName === 'string' && event.toolInput !== undefined;
|
||||
}
|
||||
|
||||
// Stop arrives as Claude's `hook_event_name: "Stop"` or Grok Build's
|
||||
// `hookEventName: "stop"`. hook.mjs routes on the raw stdin, before any
|
||||
// normalize, so both casings must match here.
|
||||
export function isStopEvent(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const name = event.hook_event_name || event.hookEventName;
|
||||
return typeof name === 'string' && name.toLowerCase() === 'stop';
|
||||
}
|
||||
|
||||
// GitHub Copilot's postToolUse payload is
|
||||
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
|
||||
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
|
||||
@@ -1354,9 +1380,36 @@ function normalizeGitHubEvent(event, projectCwd) {
|
||||
};
|
||||
}
|
||||
|
||||
// Grok Build 1.0.5 (captured 2026-08-24) sends camelCase `toolName` /
|
||||
// `toolInput` / `sessionId` / `stopHookActive`, plus `cwd` alongside a
|
||||
// trailing-slashed `workspaceRoot` (every consumer path.resolve()s, so no
|
||||
// stripping here). Only the fields the hook reads are copied; the event
|
||||
// name stays camelCase because routing already happened on the raw stdin
|
||||
// (isStopEvent) and nothing downstream reads `hook_event_name`.
|
||||
function normalizeGrokEvent(event, projectCwd) {
|
||||
const cwd = event.cwd || event.workspaceRoot || envProjectDir(projectCwd) || projectCwd;
|
||||
const sessionId = event.sessionId || event.session_id || 'unknown';
|
||||
const rawInput = event.toolInput ?? event.tool_input;
|
||||
const toolInput = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
|
||||
? { ...rawInput }
|
||||
: {};
|
||||
const out = {
|
||||
...event,
|
||||
cwd,
|
||||
session_id: sessionId,
|
||||
tool_name: event.toolName || event.tool_name || null,
|
||||
tool_input: toolInput,
|
||||
};
|
||||
if (event.stopHookActive !== undefined && event.stop_hook_active === undefined) {
|
||||
out.stop_hook_active = event.stopHookActive;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
|
||||
if (!event || typeof event !== 'object') return event;
|
||||
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
|
||||
if (harness === 'grok') return normalizeGrokEvent(event, projectCwd);
|
||||
if (harness !== 'cursor') return event;
|
||||
|
||||
const cwd = event.cwd
|
||||
@@ -1959,7 +2012,15 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// findings stop being remembered and a reintroduced one reads as fresh.
|
||||
// Only the immediate tier is remembered: a deferred finding the per-edit
|
||||
// pass never reported must still read as fresh to the Stop deep pass.
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
//
|
||||
// Grok ignores PostToolUse stdout, so Stop is the user-visible pass.
|
||||
// Remembering here would dedupe those findings out of Stop. Touch the
|
||||
// file so Stop has it, and leave the finding list empty.
|
||||
if (harness === 'grok') {
|
||||
touchFile(cache, sessionId, filePath);
|
||||
} else {
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
}
|
||||
cacheDirty = true;
|
||||
|
||||
if (fresh.length > 0) {
|
||||
@@ -2191,22 +2252,32 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
event = normalizeHookEvent(event, cwd, harness);
|
||||
|
||||
// Claude Code's Stop-hook contract: `stop_hook_active` is true when this
|
||||
// hook is being re-invoked only because a prior invocation kept the turn
|
||||
// alive (here, via hookSpecificOutput.additionalContext). Re-scanning and
|
||||
// re-blocking now would loop until Claude Code's consecutive-block cap
|
||||
// force-ends the turn (issue #400). The prior fire already surfaced the
|
||||
// findings; whether to act on them is the agent's call. Exit fast with no
|
||||
// output before any scan. Only Claude Code sends this field; other
|
||||
// harnesses omit it, so the strict `=== true` is a no-op for them. This
|
||||
// guard makes the loop impossible regardless of the finding cache key's
|
||||
// line-number sensitivity (out of scope here; see findingCacheKey).
|
||||
// output before any scan. Claude sends `stop_hook_active`; Grok sends
|
||||
// `stopHookActive`, copied onto the snake_case field above. The strict
|
||||
// `=== true` is a no-op when the field is absent. This guard makes the
|
||||
// loop impossible regardless of the finding cache key's line-number
|
||||
// sensitivity (out of scope here; see findingCacheKey).
|
||||
if (event.stop_hook_active === true) {
|
||||
return result({ skipped: 'stop-hook-active', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
// Grok fires Stop twice: `end_turn` (the gate that can inject
|
||||
// additionalContext) then an observe-only `shutdown`. A second deep
|
||||
// pass would re-emit the same findings. Claude omits `reason`; only
|
||||
// skip when Grok named a reason that is not end_turn.
|
||||
if (harness === 'grok' && typeof event.reason === 'string' && event.reason !== 'end_turn') {
|
||||
return result({ skipped: 'stop-reason', reason: event.reason, durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
// A Stop event carries no file, so the session cwd is the project.
|
||||
// Umbrella-dir launches keyed their per-edit cache to the edited file's
|
||||
@@ -2241,6 +2312,7 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
|
||||
const freshGroups = [];
|
||||
let scanned = 0;
|
||||
let cacheDirty = false;
|
||||
for (const filePath of touched) {
|
||||
if (scanned >= STOP_MAX_FILES) break;
|
||||
if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) continue;
|
||||
@@ -2261,29 +2333,39 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
|
||||
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
const useHtmlEngine = configuredExt
|
||||
? configuredExt.engine === 'html'
|
||||
: (ext === '.html' || ext === '.htm');
|
||||
|
||||
if (useHtmlEngine && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
// A detector failure tells us nothing about the file. Leave whatever
|
||||
// was remembered alone rather than recording an empty scan as truth.
|
||||
if (detectorThrew) continue;
|
||||
|
||||
// Full rule set: no tier split here. Config/inline ignores still apply,
|
||||
// and the session dedupe drops everything the per-edit pass (or an
|
||||
// earlier Stop pass) already surfaced.
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
|
||||
// Sync to the live scan, including empty. Remembering only `fresh`
|
||||
// (or skipping the write on a clean Stop) left stale keys in place, so
|
||||
// a finding that was fixed and later reintroduced never fired again.
|
||||
rememberFindings(cache, sessionId, filePath, filtered);
|
||||
cacheDirty = true;
|
||||
if (fresh.length > 0) {
|
||||
rememberFindings(cache, sessionId, filePath, fresh);
|
||||
freshGroups.push({ filePath, findings: fresh });
|
||||
}
|
||||
}
|
||||
audit.scannedFiles = scanned;
|
||||
|
||||
if (freshGroups.length === 0) {
|
||||
if (cacheDirty) persistCache(projectCwd, cache);
|
||||
return result({ emitted: false, skipped: 'stop-clean', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
@@ -2300,8 +2382,8 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
);
|
||||
commitFooterShown(cache, sessionId, text);
|
||||
|
||||
// Fresh findings earn the cache write so the next Stop fire is silent
|
||||
// unless new issues appear; the notice flags ride along.
|
||||
// Persist the live finding set so the next Stop fire is silent unless
|
||||
// new issues appear; the notice flags ride along.
|
||||
persistCache(projectCwd, cache);
|
||||
return {
|
||||
exitCode: 0,
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
/**
|
||||
* Impeccable design hook — PostToolUse + Stop entry point.
|
||||
*
|
||||
* Reads the Claude Code / Codex / Cursor hook event from stdin and routes by
|
||||
* `hook_event_name`:
|
||||
* Reads the Claude Code / Codex / Cursor / Grok Build hook event from stdin
|
||||
* and routes by Stop vs everything else. Claude uses `hook_event_name:
|
||||
* "Stop"`; Grok uses `hookEventName: "stop"`.
|
||||
*
|
||||
* - PostToolUse: runs the immediate-tier detector rules against the touched
|
||||
* file and emits a system reminder via
|
||||
* `hookSpecificOutput.additionalContext` when findings exist.
|
||||
* `hookSpecificOutput.additionalContext` when findings exist. Grok
|
||||
* discards that stdout; the scan still warms the session cache for Stop.
|
||||
* - Stop: runs the FULL detector rule set over every UI file touched this
|
||||
* session (the deep pass), deduped against what the per-edit pass already
|
||||
* surfaced, and emits once via the Stop additionalContext channel.
|
||||
@@ -19,7 +21,7 @@
|
||||
* subprocess. This file is the thin stdin/stdout adapter.
|
||||
*/
|
||||
|
||||
import { runHook, runStopHook, writeAuditLog } from './hook-lib.mjs';
|
||||
import { runHook, runStopHook, writeAuditLog, isStopEvent } from './hook-lib.mjs';
|
||||
|
||||
async function readStdin() {
|
||||
if (process.stdin.isTTY) return '';
|
||||
@@ -28,10 +30,9 @@ async function readStdin() {
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
function isStopEvent(stdinJson) {
|
||||
function stdinIsStop(stdinJson) {
|
||||
try {
|
||||
const event = JSON.parse(stdinJson);
|
||||
return event && typeof event === 'object' && event.hook_event_name === 'Stop';
|
||||
return isStopEvent(JSON.parse(stdinJson));
|
||||
} catch {
|
||||
// Malformed stdin falls through to runHook, which audits the skip.
|
||||
return false;
|
||||
@@ -48,7 +49,7 @@ async function main() {
|
||||
let stdinJson = '';
|
||||
try { stdinJson = await readStdin(); } catch { /* fall through */ }
|
||||
|
||||
const run = isStopEvent(stdinJson) ? runStopHook : runHook;
|
||||
const run = stdinIsStop(stdinJson) ? runStopHook : runHook;
|
||||
const result = await run({
|
||||
stdinJson,
|
||||
env: inheritedEnv,
|
||||
|
||||
@@ -196,9 +196,6 @@ function parseScalar(raw) {
|
||||
|
||||
const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
|
||||
const OKLCH_RE = /oklch\([^)]+\)/gi;
|
||||
const RGBA_RE = /rgba?\([^)]+\)/gi;
|
||||
const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
|
||||
const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
|
||||
|
||||
// ---------- Section splitting ----------
|
||||
|
||||
@@ -550,36 +547,6 @@ function detectFormat(v) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function scanInlineColors(lines) {
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '');
|
||||
const color = parseColorBullet(trimmed);
|
||||
if (color) out.push(color);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseStitchInlineGroups(lines) {
|
||||
// Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
|
||||
// Each bullet IS its own role. Group them under the spoken role name.
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
|
||||
const m = trimmed.match(
|
||||
/^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
|
||||
);
|
||||
if (m) {
|
||||
const role = m[1];
|
||||
const color = buildColor(role, m[2], m[3]);
|
||||
out.push({ role, colors: [color] });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractTypography(section) {
|
||||
if (!section) return null;
|
||||
const text = section.lines.join('\n');
|
||||
|
||||
@@ -488,41 +488,46 @@ export function describeWorkspaceContext(candidates = []) {
|
||||
// ─── Tier 1 orchestration ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Everything a boot can afford. `ctx` is the loadContext result; `extras`
|
||||
* carries values the caller already computed so nothing is recomputed here.
|
||||
* Everything a boot can afford, grouped by artifact so deeper reports can
|
||||
* interleave their own checks without rebuilding this policy. `ctx` is the
|
||||
* loadContext result; `extras` carries values the caller already computed so
|
||||
* nothing is recomputed here.
|
||||
*/
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
if (!ctx) return [];
|
||||
export function collectBootFindingGroups(ctx, extras = {}) {
|
||||
if (!ctx) return {};
|
||||
const projectRoot = ctx.projectRoot || process.cwd();
|
||||
const absProductPath = extras.absProductPath || null;
|
||||
const absDesignPath = extras.absDesignPath || null;
|
||||
|
||||
return [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
return {
|
||||
product: checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
// Only checked once a PRODUCT.md exists. Without one the boot already
|
||||
// emits NO_PRODUCT_MD and routes into init, which asks for the platform
|
||||
// directly; a second signal saying the same thing is noise.
|
||||
...(ctx.product
|
||||
nativePlatform: ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({
|
||||
: [],
|
||||
designSidecar: checkDesignSidecar({
|
||||
designPath: absDesignPath,
|
||||
sidecarCandidates: extras.sidecarCandidates || [],
|
||||
projectRoot,
|
||||
}),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...(extras.projectRootPatterns
|
||||
config: checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
buildPath: checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
surfaceBriefs: checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
projectRoots: extras.projectRootPatterns
|
||||
? checkProjectRoots({
|
||||
patterns: extras.projectRootPatterns,
|
||||
candidates: extras.targetCandidates || [],
|
||||
})
|
||||
: []),
|
||||
];
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
return Object.values(collectBootFindingGroups(ctx, extras)).flat();
|
||||
}
|
||||
|
||||
@@ -4902,6 +4902,13 @@
|
||||
saveSession();
|
||||
}
|
||||
|
||||
function completeParameterGenerationIfReady() {
|
||||
if (expectedVariants <= 0 || arrivedVariants < expectedVariants) return;
|
||||
if (parameterGenerationState === 'pending' || parameterGenerationState === 'loading') {
|
||||
completeParameterPublication();
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTunePopover() {
|
||||
if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }
|
||||
if (tuneOpen) { closeTunePopover(); return; }
|
||||
@@ -5796,7 +5803,7 @@
|
||||
setLiveState('CYCLING');
|
||||
showOrUpdateCyclingBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5884,7 +5891,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');
|
||||
} catch (err) {
|
||||
console.error('[impeccable] Failed to mount component-preview variants:', err);
|
||||
@@ -6329,7 +6336,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
|
||||
})
|
||||
.catch(err => {
|
||||
@@ -6836,6 +6843,7 @@
|
||||
|
||||
const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
|
||||
if (expected > 0) expectedVariants = expected;
|
||||
completeParameterGenerationIfReady();
|
||||
|
||||
if (arrivedVariants > 0) {
|
||||
setLiveState('CYCLING');
|
||||
|
||||
@@ -944,8 +944,42 @@ export async function commitManualEdits({
|
||||
};
|
||||
}
|
||||
|
||||
const repairContext = {
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
};
|
||||
|
||||
const baseRollbackScope = collectApplyOwnedFiles(batch, cwd);
|
||||
const rollbackSnapshot = snapshotRollbackFiles(cwd, baseRollbackScope);
|
||||
const failWithRollback = ({
|
||||
scope = baseRollbackScope,
|
||||
extraFiles = [],
|
||||
failed,
|
||||
files = [],
|
||||
details = {},
|
||||
}) => {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, extraFiles, scope);
|
||||
return {
|
||||
applied: [],
|
||||
failed,
|
||||
files,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
...details,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
result = repairOnly
|
||||
@@ -965,42 +999,27 @@ export async function commitManualEdits({
|
||||
chatAvailable,
|
||||
});
|
||||
} catch (err) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, [], baseRollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
failed: batch.entries.map((entry) => ({
|
||||
id: entry.id,
|
||||
reason: err.message || String(err),
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
})),
|
||||
files: [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'error') {
|
||||
const rollbackScope = collectApplyOwnedFiles(batch, cwd, result.files || []);
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const failed = normalizeFailedEntries(batch, result, result.message || 'AI copy edit failed');
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: failed.length > 0
|
||||
? failed
|
||||
: verificationFailuresForEntries(batch, batch.entries, result.message || 'AI copy edit failed'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedIds = uniqueStrings(result.appliedEntryIds || []);
|
||||
@@ -1013,72 +1032,44 @@ export async function commitManualEdits({
|
||||
const conflictingAppliedIds = reportedAppliedIds.filter((id) => failedIds.has(id));
|
||||
|
||||
if (conflictingAppliedIds.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const conflictingEntries = batch.entries.filter((entry) => conflictingAppliedIds.includes(entry.id));
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...verificationFailuresForEntries(batch, conflictingEntries, 'conflicting_apply_result'),
|
||||
...aiFailed.filter((item) => !conflictingAppliedIds.includes(item.id)),
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const unreportedFiles = unreportedChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
if (unreportedFiles.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], [...rollbackScope, ...unreportedFiles]);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: [...rollbackScope, ...unreportedFiles],
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'unreported_source_changes', { files: unreportedFiles }),
|
||||
files: result.files || [],
|
||||
unreportedFiles,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { unreportedFiles, notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'done' && reportedAppliedIds.length === 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'missing_applied_entry_ids'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedEntries = batch.entries.filter((entry) => reportedAppliedIds.includes(entry.id));
|
||||
if (reportedAppliedIds.length > 0 && reportedFiles.length === 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: aiFailed,
|
||||
@@ -1089,21 +1080,10 @@ export async function commitManualEdits({
|
||||
});
|
||||
}
|
||||
|
||||
const verifiedAppliedIds = [];
|
||||
const verificationFailed = [];
|
||||
for (const entry of reportedAppliedEntries) {
|
||||
const failures = verifyAppliedEntry({ batch, entry, reportedFiles, cwd });
|
||||
if (failures.length === 0) {
|
||||
verifiedAppliedIds.push(entry.id);
|
||||
} else {
|
||||
verificationFailed.push({
|
||||
id: entry.id,
|
||||
reason: 'source_verification_failed',
|
||||
failures,
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
const {
|
||||
verifiedIds: verifiedAppliedIds,
|
||||
failed: verificationFailed,
|
||||
} = verifyEntriesAfterRepair({ batch, appliedEntryIds: reportedAppliedIds, files: reportedFiles, cwd });
|
||||
const unreportedEntries = result.status === 'done' || result.status === 'partial'
|
||||
? batch.entries.filter((entry) => !reportedAppliedIds.includes(entry.id) && !aiFailed.some((item) => item.id === entry.id))
|
||||
: [];
|
||||
@@ -1133,37 +1113,22 @@ export async function commitManualEdits({
|
||||
reason: 'rolled_back_due_to_failed_entry_source_changed',
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
}));
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...leakedUnapplied,
|
||||
...failed.filter((item) => !leakedIds.has(item.id)),
|
||||
...rolledBackVerified,
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
notes: result.notes || [],
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (verificationFailed.length > 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: nonRepairFailed,
|
||||
@@ -1180,16 +1145,7 @@ export async function commitManualEdits({
|
||||
? reportedAppliedEntries.filter((entry) => verifiedAppliedIds.includes(entry.id))
|
||||
: batch.entries;
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: verifiedAppliedIds.length > 0
|
||||
? verifiedAppliedIds
|
||||
: postCheckEntries.map((entry) => entry.id).filter(Boolean),
|
||||
|
||||
@@ -238,10 +238,9 @@ export async function completeAcceptHandling(event, base, token) {
|
||||
});
|
||||
} catch (err) {
|
||||
event._completionAck = { ok: false, error: err.message };
|
||||
return event;
|
||||
}
|
||||
if (!event._completionAck) {
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
}
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -269,9 +268,11 @@ export function printPollEvent(event) {
|
||||
// Situational plumbing rides with the event itself: `_instructions` is the
|
||||
// authoritative next step, with real ids and paths substituted, so the
|
||||
// reference doc can stay lean and can never drift from script behavior.
|
||||
if (event && typeof event === 'object' && !event._instructions) {
|
||||
// A wire-supplied value must never win over the locally generated one.
|
||||
if (event && typeof event === 'object') {
|
||||
const instructions = instructionsForEvent(event, { scriptsPath: SELF_DIR });
|
||||
if (instructions) event._instructions = instructions;
|
||||
else delete event._instructions;
|
||||
}
|
||||
console.log(JSON.stringify(event));
|
||||
}
|
||||
|
||||
@@ -181,8 +181,16 @@ function chatAgentLikelyActive() {
|
||||
// cap at 10 MB to guard against runaway writes from a misbehaving client.
|
||||
const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
const POLLER_OWNED_EVENT_FIELDS = ['_instructions', '_completionAck', '_acceptResult'];
|
||||
|
||||
function stripPollerOwnedEventFields(event) {
|
||||
if (!event || typeof event !== 'object') return;
|
||||
for (const key of POLLER_OWNED_EVENT_FIELDS) delete event[key];
|
||||
}
|
||||
|
||||
function enqueueEvent(event) {
|
||||
if (!event) return;
|
||||
stripPollerOwnedEventFields(event);
|
||||
// Dedupe by (session, type), except mount failures, which are per-variant:
|
||||
// variant 2 failing must not be swallowed because variant 1's failure is
|
||||
// still queued.
|
||||
@@ -936,15 +944,23 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
const filePath = url.searchParams.get('path');
|
||||
if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
|
||||
const absPath = path.resolve(process.cwd(), filePath);
|
||||
// Confine to the project root. A bare `startsWith(cwd)` string check lets a
|
||||
// sibling dir whose name extends the root name (projeto -> projeto-backup)
|
||||
// slip through; compare on the relative path instead (same pattern as
|
||||
// sessionFileMetadataFromPollReply below). An empty rel means the request
|
||||
// resolved to the root directory itself, which this file route never serves.
|
||||
const rel = path.relative(process.cwd(), absPath);
|
||||
let realRoot, realTarget;
|
||||
try {
|
||||
realRoot = fs.realpathSync(process.cwd());
|
||||
realTarget = fs.realpathSync(absPath);
|
||||
} catch {
|
||||
res.writeHead(404); res.end('File not found'); return;
|
||||
}
|
||||
// Confine to the project root after symlink resolution. A bare
|
||||
// `startsWith(cwd)` string check lets a sibling dir whose name extends the
|
||||
// root name (projeto -> projeto-backup) slip through; compare on the
|
||||
// relative path instead (same pattern as sessionFileMetadataFromPollReply
|
||||
// below). An empty rel means the request resolved to the root directory
|
||||
// itself, which this file route never serves.
|
||||
const rel = path.relative(realRoot, realTarget);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { res.writeHead(403); res.end('Forbidden'); return; }
|
||||
let content;
|
||||
try { content = fs.readFileSync(absPath, 'utf-8'); }
|
||||
try { content = fs.readFileSync(realTarget, 'utf-8'); }
|
||||
catch { res.writeHead(404); res.end('File not found'); return; }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(content);
|
||||
@@ -1026,6 +1042,7 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
res.end(JSON.stringify({ error }));
|
||||
return;
|
||||
}
|
||||
stripPollerOwnedEventFields(msg);
|
||||
if (msg.type === 'agent_phase') {
|
||||
recordAgentPhase(msg.id, msg.phase, {
|
||||
...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),
|
||||
|
||||
@@ -11,6 +11,8 @@ import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
|
||||
export const SVELTE_LIVE_ROOT_COMPONENT = 'src/lib/impeccable/ImpeccableLiveRoot.svelte';
|
||||
export const SVELTE_LAYOUT_MARKER_OPEN = '<!-- impeccable-live-svelte-start -->';
|
||||
export const SVELTE_LAYOUT_MARKER_CLOSE = '<!-- impeccable-live-svelte-end -->';
|
||||
@@ -45,11 +47,17 @@ export function detectSvelteKitProject(cwd = process.cwd(), config = null) {
|
||||
&& fileIncludes(path.join(cwd, appHtml), '%sveltekit.head%');
|
||||
if (!hasTemplateMarkers) return null;
|
||||
|
||||
const hasSvelteConfig = fs.existsSync(path.join(cwd, 'svelte.config.js'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.mjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.cjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.ts'));
|
||||
const hasKitPackage = packageHasSvelteKit(cwd);
|
||||
const hasSvelteConfig = Boolean(firstExistingFile(cwd, [
|
||||
'svelte.config.js',
|
||||
'svelte.config.mjs',
|
||||
'svelte.config.cjs',
|
||||
'svelte.config.ts',
|
||||
]));
|
||||
const hasKitPackage = hasAnyDependency(cwd, [
|
||||
'@sveltejs/kit',
|
||||
'@sveltejs/vite-plugin-svelte',
|
||||
'svelte',
|
||||
]);
|
||||
if (!hasSvelteConfig && !hasKitPackage) return null;
|
||||
|
||||
return {
|
||||
@@ -260,36 +268,16 @@ function findSvelteKitAppHtml(cwd, config) {
|
||||
}
|
||||
|
||||
function findSvelteKitLayout(cwd) {
|
||||
const candidates = [
|
||||
return firstExistingFile(cwd, [
|
||||
'src/routes/+layout.svelte',
|
||||
'src/routes/(app)/+layout.svelte',
|
||||
];
|
||||
for (const rel of candidates) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return 'src/routes/+layout.svelte';
|
||||
]) || 'src/routes/+layout.svelte';
|
||||
}
|
||||
|
||||
function defaultSvelteLayout() {
|
||||
return `<script>\n let { children } = $props();\n</script>\n\n{@render children?.()}\n`;
|
||||
}
|
||||
|
||||
function packageHasSvelteKit(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fileIncludes(file, text) {
|
||||
try {
|
||||
return fs.readFileSync(file, 'utf-8').includes(text);
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
import { buildLiveScriptSrc } from './frameworks/script-src.mjs';
|
||||
|
||||
export const TANSTACK_MARKER_OPEN = '{/* impeccable-live-tanstack-start */}';
|
||||
@@ -42,8 +44,8 @@ const START_PACKAGES = [
|
||||
];
|
||||
|
||||
export function detectTanStackStartProject(cwd = process.cwd()) {
|
||||
if (!packageHasTanStackStart(cwd)) return null;
|
||||
const rootRoute = findRootRouteFile(cwd);
|
||||
if (!hasAnyDependency(cwd, START_PACKAGES)) return null;
|
||||
const rootRoute = firstExistingFile(cwd, ROOT_ROUTE_CANDIDATES);
|
||||
if (!rootRoute) return null;
|
||||
|
||||
const ext = path.extname(rootRoute);
|
||||
@@ -218,29 +220,6 @@ function isManagedComponent(content) {
|
||||
return String(content || '').includes('impeccable-live-tanstack');
|
||||
}
|
||||
|
||||
function findRootRouteFile(cwd) {
|
||||
for (const rel of ROOT_ROUTE_CANDIDATES) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function packageHasTanStackStart(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return START_PACKAGES.some((name) => Boolean(deps[name]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function relativeImportSpecifier(fromFile, toFile) {
|
||||
const rel = path.posix.relative(
|
||||
path.posix.dirname(fromFile.split(path.sep).join('/')),
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
|
||||
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code and Codex, which both dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit.
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
|
||||
|
||||
Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `context.mjs` asking for a single detector run at the end.
|
||||
|
||||
@@ -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), 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` 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -44,7 +44,7 @@ The first argument is the action. Defaults to `status`.
|
||||
```
|
||||
|
||||
3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write on a UI file."
|
||||
5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/config.json`; add `--local` only when the user explicitly asks for a private exception.
|
||||
6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
|
||||
|
||||
|
||||
@@ -626,7 +626,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -688,7 +688,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -985,7 +985,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -1115,7 +1115,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -773,14 +773,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
@@ -1955,20 +1963,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -1985,13 +1992,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -3986,7 +3990,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
@@ -7281,7 +7285,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -7343,7 +7347,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -7640,7 +7644,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -7770,7 +7774,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -42,6 +42,7 @@ function shouldRunPageAnalyzers(content, filePath) {
|
||||
}
|
||||
|
||||
const JS_SOURCE_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']);
|
||||
const STYLESHEET_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
const REGEX_PREFIX_KEYWORDS = new Set(['await', 'case', 'default', 'delete', 'do', 'else', 'in', 'instanceof', 'new', 'of', 'return', 'throw', 'typeof', 'void', 'yield']);
|
||||
const BLOCK_BRACE_PREFIX_KEYWORDS = new Set(['do', 'else', 'finally', 'try']);
|
||||
|
||||
@@ -256,6 +257,153 @@ function stripCssComments(content) {
|
||||
return content.replace(/\/\*[\s\S]*?\*\//g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankHtmlComments(text) {
|
||||
return text.replace(/<!--[\s\S]*?-->/g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankCssLineCommentsInStyleBlocks(text) {
|
||||
const re = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
const inner = match[1];
|
||||
const openLength = match[0].length - inner.length - '</style>'.length;
|
||||
output += text.slice(lastIndex, match.index);
|
||||
output += match[0].slice(0, openLength);
|
||||
output += blankCssLineComments(inner);
|
||||
output += match[0].slice(openLength + inner.length);
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + text.slice(lastIndex);
|
||||
}
|
||||
|
||||
function blankHtmlAndCssCommentsOutsideScripts(text) {
|
||||
const re = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
output += blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex, match.index))));
|
||||
output += match[0];
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex))));
|
||||
}
|
||||
|
||||
function blankCssLineComments(text) {
|
||||
let output = '';
|
||||
let state = 'code';
|
||||
let urlDepth = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
const next = text[i + 1];
|
||||
if (state === 'line') {
|
||||
if (char === '\n') {
|
||||
output += '\n';
|
||||
state = 'code';
|
||||
} else {
|
||||
output += ' ';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state === 'single' || state === 'double') {
|
||||
output += char;
|
||||
if (char === '\\' && next) {
|
||||
output += next;
|
||||
i++;
|
||||
} else if ((state === 'single' && char === "'") || (state === 'double' && char === '"')) {
|
||||
state = 'code';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const prev = output.length ? output[output.length - 1] : '';
|
||||
if (char === '/' && next === '/' && urlDepth === 0 && prev !== ':' && prev !== '(' && prev !== '\\') {
|
||||
output += ' ';
|
||||
i++;
|
||||
state = 'line';
|
||||
continue;
|
||||
}
|
||||
if (char === "'") state = 'single';
|
||||
else if (char === '"') state = 'double';
|
||||
if (char === '(') {
|
||||
const behind = output.replace(/\s+$/, '');
|
||||
if (urlDepth > 0 || /url$/i.test(behind)) urlDepth++;
|
||||
} else if (char === ')' && urlDepth) {
|
||||
urlDepth--;
|
||||
}
|
||||
output += char;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function findAstroFrontmatterClose(text) {
|
||||
if (!text.startsWith('---')) return -1;
|
||||
let cursor = text.indexOf('\n');
|
||||
if (cursor === -1) return -1;
|
||||
cursor += 1;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor - 1] === '\n' && text.startsWith('---', cursor)) {
|
||||
let end = cursor + 3;
|
||||
while (text[end] === ' ' || text[end] === '\t') end++;
|
||||
if (end >= text.length || text[end] === '\n' || text[end] === '\r') return cursor - 1;
|
||||
}
|
||||
const char = text[cursor];
|
||||
const next = text[cursor + 1];
|
||||
if (char === "'" || char === '"') {
|
||||
const close = findQuotedStringEnd(text, cursor, char);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '`') {
|
||||
const close = findTemplateLiteralEnd(text, cursor);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '/') {
|
||||
const lineEnd = text.indexOf('\n', cursor);
|
||||
if (lineEnd === -1) return -1;
|
||||
cursor = lineEnd;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '*') {
|
||||
const commentEnd = text.indexOf('*/', cursor + 2);
|
||||
if (commentEnd === -1) return -1;
|
||||
cursor = commentEnd + 2;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next !== '/' && next !== '*') {
|
||||
const close = findRegexLiteralEnd(text, cursor);
|
||||
if (close !== -1) {
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cursor++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function blankAstroFrontmatterComments(text) {
|
||||
const close = findAstroFrontmatterClose(text);
|
||||
if (close === -1) return text;
|
||||
return stripJsComments(text.slice(0, close)) + text.slice(close);
|
||||
}
|
||||
|
||||
function blankCommentsForMatchers(text, ext) {
|
||||
if (PAGE_ANALYZER_EXTS.has(ext)) {
|
||||
const withFrontmatter = ext === '.astro' ? blankAstroFrontmatterComments(text) : text;
|
||||
return blankHtmlAndCssCommentsOutsideScripts(withFrontmatter);
|
||||
}
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
const withoutBlocks = stripCssComments(text);
|
||||
return ext === '.css' ? withoutBlocks : blankCssLineComments(withoutBlocks);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function firstOverusedGoogleFont(text) {
|
||||
return extractGoogleFontFamilies(text).find(f => OVERUSED_FONTS.has(f)) || '';
|
||||
}
|
||||
@@ -1028,14 +1176,13 @@ function detectText(content, filePath, options = {}) {
|
||||
const ext = extFromFilePath(filePath);
|
||||
const commentStrippedSource = JS_SOURCE_EXTS.has(ext) ? stripJsComments(content, {
|
||||
jsx: ext === '.js' || ext === '.jsx' || ext === '.tsx',
|
||||
}) : content;
|
||||
}) : blankCommentsForMatchers(content, ext);
|
||||
const source = stripCssInJsComments(commentStrippedSource, ext);
|
||||
const lines = source.split('\n');
|
||||
|
||||
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
|
||||
// Enable block context for CSS files where related properties span multiple lines
|
||||
const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, STYLESHEET_EXTS.has(ext) || null, {
|
||||
profile,
|
||||
phase: 'source',
|
||||
}));
|
||||
@@ -1050,7 +1197,7 @@ function detectText(content, filePath, options = {}) {
|
||||
scanCssTextForPseudoStripe(text).map(hit =>
|
||||
finding(hit.id, filePath, hit.snippet, lineOffset + text.slice(0, hit.index).split('\n').length));
|
||||
|
||||
if (cssLike.has(ext)) {
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
findings.push(...scanInsetStripeCss(content, filePath));
|
||||
findings.push(...pseudoStripeFindings(content, 0));
|
||||
}
|
||||
@@ -1078,7 +1225,8 @@ function detectText(content, filePath, options = {}) {
|
||||
}, () => extractStyleBlocks(content, ext))
|
||||
: extractStyleBlocks(content, ext);
|
||||
for (const block of styleBlocks) {
|
||||
const blockLines = block.content.split('\n');
|
||||
const blockContent = blankCssLineComments(stripCssComments(block.content));
|
||||
const blockLines = blockContent.split('\n');
|
||||
findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
|
||||
profile,
|
||||
phase: 'style-block',
|
||||
@@ -1089,8 +1237,8 @@ function detectText(content, filePath, options = {}) {
|
||||
// 1-based, so the offset is startLine - 2; startLine - 1 double-counted and
|
||||
// reported every selector one line low. runRegexMatchers keeps startLine - 1
|
||||
// because it indexes its split lines from zero.
|
||||
findings.push(...scanInsetStripeCss(block.content, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(block.content, block.startLine - 2));
|
||||
findings.push(...scanInsetStripeCss(blockContent, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(blockContent, block.startLine - 2));
|
||||
}
|
||||
|
||||
// Extract and scan CSS-in-JS template literals
|
||||
|
||||
@@ -721,20 +721,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -751,13 +750,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -2752,7 +2748,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
|
||||
@@ -103,14 +103,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
|
||||
@@ -33,13 +33,8 @@ import {
|
||||
stampProductSchema,
|
||||
} from './lib/artifact-schema.mjs';
|
||||
import {
|
||||
checkBuildPathUnset,
|
||||
checkConfig,
|
||||
checkDesignSidecar,
|
||||
collectBootFindingGroups,
|
||||
checkNativePlatformEvidence,
|
||||
checkProduct,
|
||||
checkProjectRoots,
|
||||
checkSurfaceBriefs,
|
||||
designSidecarCandidatesFor,
|
||||
} from './lib/staleness.mjs';
|
||||
import {
|
||||
@@ -106,34 +101,30 @@ async function collect(cwd, targetOptions) {
|
||||
extractPlatform,
|
||||
readFile: safeRead,
|
||||
});
|
||||
const bootFindings = collectBootFindingGroups(ctx, {
|
||||
absDesignPath,
|
||||
sidecarCandidates,
|
||||
projectRootPatterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
targetCandidates: workspaceCandidates,
|
||||
});
|
||||
|
||||
const findings = [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
...(ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({ designPath: absDesignPath, sidecarCandidates, projectRoot }),
|
||||
...bootFindings.product,
|
||||
...bootFindings.nativePlatform,
|
||||
...bootFindings.designSidecar,
|
||||
...checkDesignDrift({ designPath: absDesignPath, projectRoot }),
|
||||
...checkDesignCoverage({ design: ctx.design, designPath: ctx.designPath, parseDesignMd }),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...bootFindings.config,
|
||||
...bootFindings.buildPath,
|
||||
...checkDetectorIgnores({ projectRoot, knownRuleIds }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...bootFindings.surfaceBriefs,
|
||||
...checkHookInstallation({
|
||||
projectRoot,
|
||||
repoRoot: ctx.repoRoot,
|
||||
providerId: IMPECCABLE_PROVIDER_ID,
|
||||
}),
|
||||
...checkLegacyLiveState({ projectRoot }),
|
||||
...checkProjectRoots({
|
||||
patterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
candidates: workspaceCandidates,
|
||||
}),
|
||||
...bootFindings.projectRoots,
|
||||
...workspaceResult.findings,
|
||||
];
|
||||
|
||||
|
||||
@@ -75,11 +75,11 @@ const HOOK_MANIFEST_TARGETS = [
|
||||
destRel: '.claude/settings.local.json',
|
||||
sharedDestRel: '.claude/settings.json',
|
||||
manifest: () => ({
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.',
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.',
|
||||
hooks: {
|
||||
PostToolUse: [
|
||||
{
|
||||
matcher: 'Edit|Write|MultiEdit',
|
||||
matcher: 'Edit|Write',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
|
||||
@@ -816,9 +816,9 @@ export function splitFindingsByTier(findings) {
|
||||
}
|
||||
|
||||
// Whether the per-edit pass for this harness should defer non-immediate
|
||||
// findings to a Stop deep pass. Only Claude Code and Codex dispatch our Stop
|
||||
// hook; Cursor and GitHub Copilot have no deep pass wired, so deferring for
|
||||
// them would silently drop the non-immediate rules entirely.
|
||||
// findings to a Stop deep pass. Claude Code, Codex, and Grok Build dispatch
|
||||
// our Stop hook; Cursor and GitHub Copilot have no deep pass wired, so
|
||||
// deferring for them would silently drop the non-immediate rules entirely.
|
||||
export function perEditTieringActive(config, harness) {
|
||||
if (harness === 'cursor' || harness === 'github') return false;
|
||||
return (config?.perEditRules || DEFAULT_CONFIG.perEditRules) !== 'all';
|
||||
@@ -1251,9 +1251,14 @@ export function resolveHarness(env = {}, event = null) {
|
||||
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
|
||||
if (explicit === 'cursor') return 'cursor';
|
||||
if (explicit === 'github') return 'github';
|
||||
if (explicit === 'grok') return 'grok';
|
||||
if (explicit === 'claude' || explicit === 'codex') return 'claude';
|
||||
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
|
||||
// has no `tool_name`/`tool_input`. That shape is the discriminator.
|
||||
// Grok Build sends camelCase `toolName`/`toolInput`/`hookEventName` and no
|
||||
// snake_case pair. GitHub Copilot sends camelCase `toolName`/`toolArgs`.
|
||||
// Check Grok first: the old GitHub heuristic (`toolName` and no
|
||||
// `tool_input`) also matches Grok, which is how live PostToolUse was
|
||||
// classified as Copilot and then skipped with no-file-path (#646).
|
||||
if (looksLikeGrokEnvelope(event)) return 'grok';
|
||||
if (event && typeof event === 'object'
|
||||
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
|
||||
&& event.tool_name === undefined && event.tool_input === undefined) {
|
||||
@@ -1263,6 +1268,27 @@ export function resolveHarness(env = {}, event = null) {
|
||||
return 'claude';
|
||||
}
|
||||
|
||||
function looksLikeGrokEnvelope(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
if (event.hook_event_name !== undefined
|
||||
|| event.tool_name !== undefined
|
||||
|| event.tool_input !== undefined) {
|
||||
return false;
|
||||
}
|
||||
if (event.toolArgs !== undefined) return false;
|
||||
if (typeof event.hookEventName === 'string') return true;
|
||||
return typeof event.toolName === 'string' && event.toolInput !== undefined;
|
||||
}
|
||||
|
||||
// Stop arrives as Claude's `hook_event_name: "Stop"` or Grok Build's
|
||||
// `hookEventName: "stop"`. hook.mjs routes on the raw stdin, before any
|
||||
// normalize, so both casings must match here.
|
||||
export function isStopEvent(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const name = event.hook_event_name || event.hookEventName;
|
||||
return typeof name === 'string' && name.toLowerCase() === 'stop';
|
||||
}
|
||||
|
||||
// GitHub Copilot's postToolUse payload is
|
||||
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
|
||||
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
|
||||
@@ -1354,9 +1380,36 @@ function normalizeGitHubEvent(event, projectCwd) {
|
||||
};
|
||||
}
|
||||
|
||||
// Grok Build 1.0.5 (captured 2026-08-24) sends camelCase `toolName` /
|
||||
// `toolInput` / `sessionId` / `stopHookActive`, plus `cwd` alongside a
|
||||
// trailing-slashed `workspaceRoot` (every consumer path.resolve()s, so no
|
||||
// stripping here). Only the fields the hook reads are copied; the event
|
||||
// name stays camelCase because routing already happened on the raw stdin
|
||||
// (isStopEvent) and nothing downstream reads `hook_event_name`.
|
||||
function normalizeGrokEvent(event, projectCwd) {
|
||||
const cwd = event.cwd || event.workspaceRoot || envProjectDir(projectCwd) || projectCwd;
|
||||
const sessionId = event.sessionId || event.session_id || 'unknown';
|
||||
const rawInput = event.toolInput ?? event.tool_input;
|
||||
const toolInput = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
|
||||
? { ...rawInput }
|
||||
: {};
|
||||
const out = {
|
||||
...event,
|
||||
cwd,
|
||||
session_id: sessionId,
|
||||
tool_name: event.toolName || event.tool_name || null,
|
||||
tool_input: toolInput,
|
||||
};
|
||||
if (event.stopHookActive !== undefined && event.stop_hook_active === undefined) {
|
||||
out.stop_hook_active = event.stopHookActive;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
|
||||
if (!event || typeof event !== 'object') return event;
|
||||
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
|
||||
if (harness === 'grok') return normalizeGrokEvent(event, projectCwd);
|
||||
if (harness !== 'cursor') return event;
|
||||
|
||||
const cwd = event.cwd
|
||||
@@ -1959,7 +2012,15 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// findings stop being remembered and a reintroduced one reads as fresh.
|
||||
// Only the immediate tier is remembered: a deferred finding the per-edit
|
||||
// pass never reported must still read as fresh to the Stop deep pass.
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
//
|
||||
// Grok ignores PostToolUse stdout, so Stop is the user-visible pass.
|
||||
// Remembering here would dedupe those findings out of Stop. Touch the
|
||||
// file so Stop has it, and leave the finding list empty.
|
||||
if (harness === 'grok') {
|
||||
touchFile(cache, sessionId, filePath);
|
||||
} else {
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
}
|
||||
cacheDirty = true;
|
||||
|
||||
if (fresh.length > 0) {
|
||||
@@ -2191,22 +2252,32 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
event = normalizeHookEvent(event, cwd, harness);
|
||||
|
||||
// Claude Code's Stop-hook contract: `stop_hook_active` is true when this
|
||||
// hook is being re-invoked only because a prior invocation kept the turn
|
||||
// alive (here, via hookSpecificOutput.additionalContext). Re-scanning and
|
||||
// re-blocking now would loop until Claude Code's consecutive-block cap
|
||||
// force-ends the turn (issue #400). The prior fire already surfaced the
|
||||
// findings; whether to act on them is the agent's call. Exit fast with no
|
||||
// output before any scan. Only Claude Code sends this field; other
|
||||
// harnesses omit it, so the strict `=== true` is a no-op for them. This
|
||||
// guard makes the loop impossible regardless of the finding cache key's
|
||||
// line-number sensitivity (out of scope here; see findingCacheKey).
|
||||
// output before any scan. Claude sends `stop_hook_active`; Grok sends
|
||||
// `stopHookActive`, copied onto the snake_case field above. The strict
|
||||
// `=== true` is a no-op when the field is absent. This guard makes the
|
||||
// loop impossible regardless of the finding cache key's line-number
|
||||
// sensitivity (out of scope here; see findingCacheKey).
|
||||
if (event.stop_hook_active === true) {
|
||||
return result({ skipped: 'stop-hook-active', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
// Grok fires Stop twice: `end_turn` (the gate that can inject
|
||||
// additionalContext) then an observe-only `shutdown`. A second deep
|
||||
// pass would re-emit the same findings. Claude omits `reason`; only
|
||||
// skip when Grok named a reason that is not end_turn.
|
||||
if (harness === 'grok' && typeof event.reason === 'string' && event.reason !== 'end_turn') {
|
||||
return result({ skipped: 'stop-reason', reason: event.reason, durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
// A Stop event carries no file, so the session cwd is the project.
|
||||
// Umbrella-dir launches keyed their per-edit cache to the edited file's
|
||||
@@ -2241,6 +2312,7 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
|
||||
const freshGroups = [];
|
||||
let scanned = 0;
|
||||
let cacheDirty = false;
|
||||
for (const filePath of touched) {
|
||||
if (scanned >= STOP_MAX_FILES) break;
|
||||
if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) continue;
|
||||
@@ -2261,29 +2333,39 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
|
||||
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
const useHtmlEngine = configuredExt
|
||||
? configuredExt.engine === 'html'
|
||||
: (ext === '.html' || ext === '.htm');
|
||||
|
||||
if (useHtmlEngine && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
// A detector failure tells us nothing about the file. Leave whatever
|
||||
// was remembered alone rather than recording an empty scan as truth.
|
||||
if (detectorThrew) continue;
|
||||
|
||||
// Full rule set: no tier split here. Config/inline ignores still apply,
|
||||
// and the session dedupe drops everything the per-edit pass (or an
|
||||
// earlier Stop pass) already surfaced.
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
|
||||
// Sync to the live scan, including empty. Remembering only `fresh`
|
||||
// (or skipping the write on a clean Stop) left stale keys in place, so
|
||||
// a finding that was fixed and later reintroduced never fired again.
|
||||
rememberFindings(cache, sessionId, filePath, filtered);
|
||||
cacheDirty = true;
|
||||
if (fresh.length > 0) {
|
||||
rememberFindings(cache, sessionId, filePath, fresh);
|
||||
freshGroups.push({ filePath, findings: fresh });
|
||||
}
|
||||
}
|
||||
audit.scannedFiles = scanned;
|
||||
|
||||
if (freshGroups.length === 0) {
|
||||
if (cacheDirty) persistCache(projectCwd, cache);
|
||||
return result({ emitted: false, skipped: 'stop-clean', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
@@ -2300,8 +2382,8 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
);
|
||||
commitFooterShown(cache, sessionId, text);
|
||||
|
||||
// Fresh findings earn the cache write so the next Stop fire is silent
|
||||
// unless new issues appear; the notice flags ride along.
|
||||
// Persist the live finding set so the next Stop fire is silent unless
|
||||
// new issues appear; the notice flags ride along.
|
||||
persistCache(projectCwd, cache);
|
||||
return {
|
||||
exitCode: 0,
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
/**
|
||||
* Impeccable design hook — PostToolUse + Stop entry point.
|
||||
*
|
||||
* Reads the Claude Code / Codex / Cursor hook event from stdin and routes by
|
||||
* `hook_event_name`:
|
||||
* Reads the Claude Code / Codex / Cursor / Grok Build hook event from stdin
|
||||
* and routes by Stop vs everything else. Claude uses `hook_event_name:
|
||||
* "Stop"`; Grok uses `hookEventName: "stop"`.
|
||||
*
|
||||
* - PostToolUse: runs the immediate-tier detector rules against the touched
|
||||
* file and emits a system reminder via
|
||||
* `hookSpecificOutput.additionalContext` when findings exist.
|
||||
* `hookSpecificOutput.additionalContext` when findings exist. Grok
|
||||
* discards that stdout; the scan still warms the session cache for Stop.
|
||||
* - Stop: runs the FULL detector rule set over every UI file touched this
|
||||
* session (the deep pass), deduped against what the per-edit pass already
|
||||
* surfaced, and emits once via the Stop additionalContext channel.
|
||||
@@ -19,7 +21,7 @@
|
||||
* subprocess. This file is the thin stdin/stdout adapter.
|
||||
*/
|
||||
|
||||
import { runHook, runStopHook, writeAuditLog } from './hook-lib.mjs';
|
||||
import { runHook, runStopHook, writeAuditLog, isStopEvent } from './hook-lib.mjs';
|
||||
|
||||
async function readStdin() {
|
||||
if (process.stdin.isTTY) return '';
|
||||
@@ -28,10 +30,9 @@ async function readStdin() {
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
function isStopEvent(stdinJson) {
|
||||
function stdinIsStop(stdinJson) {
|
||||
try {
|
||||
const event = JSON.parse(stdinJson);
|
||||
return event && typeof event === 'object' && event.hook_event_name === 'Stop';
|
||||
return isStopEvent(JSON.parse(stdinJson));
|
||||
} catch {
|
||||
// Malformed stdin falls through to runHook, which audits the skip.
|
||||
return false;
|
||||
@@ -48,7 +49,7 @@ async function main() {
|
||||
let stdinJson = '';
|
||||
try { stdinJson = await readStdin(); } catch { /* fall through */ }
|
||||
|
||||
const run = isStopEvent(stdinJson) ? runStopHook : runHook;
|
||||
const run = stdinIsStop(stdinJson) ? runStopHook : runHook;
|
||||
const result = await run({
|
||||
stdinJson,
|
||||
env: inheritedEnv,
|
||||
|
||||
@@ -196,9 +196,6 @@ function parseScalar(raw) {
|
||||
|
||||
const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
|
||||
const OKLCH_RE = /oklch\([^)]+\)/gi;
|
||||
const RGBA_RE = /rgba?\([^)]+\)/gi;
|
||||
const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
|
||||
const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
|
||||
|
||||
// ---------- Section splitting ----------
|
||||
|
||||
@@ -550,36 +547,6 @@ function detectFormat(v) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function scanInlineColors(lines) {
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '');
|
||||
const color = parseColorBullet(trimmed);
|
||||
if (color) out.push(color);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseStitchInlineGroups(lines) {
|
||||
// Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
|
||||
// Each bullet IS its own role. Group them under the spoken role name.
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
|
||||
const m = trimmed.match(
|
||||
/^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
|
||||
);
|
||||
if (m) {
|
||||
const role = m[1];
|
||||
const color = buildColor(role, m[2], m[3]);
|
||||
out.push({ role, colors: [color] });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractTypography(section) {
|
||||
if (!section) return null;
|
||||
const text = section.lines.join('\n');
|
||||
|
||||
@@ -488,41 +488,46 @@ export function describeWorkspaceContext(candidates = []) {
|
||||
// ─── Tier 1 orchestration ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Everything a boot can afford. `ctx` is the loadContext result; `extras`
|
||||
* carries values the caller already computed so nothing is recomputed here.
|
||||
* Everything a boot can afford, grouped by artifact so deeper reports can
|
||||
* interleave their own checks without rebuilding this policy. `ctx` is the
|
||||
* loadContext result; `extras` carries values the caller already computed so
|
||||
* nothing is recomputed here.
|
||||
*/
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
if (!ctx) return [];
|
||||
export function collectBootFindingGroups(ctx, extras = {}) {
|
||||
if (!ctx) return {};
|
||||
const projectRoot = ctx.projectRoot || process.cwd();
|
||||
const absProductPath = extras.absProductPath || null;
|
||||
const absDesignPath = extras.absDesignPath || null;
|
||||
|
||||
return [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
return {
|
||||
product: checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
// Only checked once a PRODUCT.md exists. Without one the boot already
|
||||
// emits NO_PRODUCT_MD and routes into init, which asks for the platform
|
||||
// directly; a second signal saying the same thing is noise.
|
||||
...(ctx.product
|
||||
nativePlatform: ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({
|
||||
: [],
|
||||
designSidecar: checkDesignSidecar({
|
||||
designPath: absDesignPath,
|
||||
sidecarCandidates: extras.sidecarCandidates || [],
|
||||
projectRoot,
|
||||
}),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...(extras.projectRootPatterns
|
||||
config: checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
buildPath: checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
surfaceBriefs: checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
projectRoots: extras.projectRootPatterns
|
||||
? checkProjectRoots({
|
||||
patterns: extras.projectRootPatterns,
|
||||
candidates: extras.targetCandidates || [],
|
||||
})
|
||||
: []),
|
||||
];
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
return Object.values(collectBootFindingGroups(ctx, extras)).flat();
|
||||
}
|
||||
|
||||
@@ -4902,6 +4902,13 @@
|
||||
saveSession();
|
||||
}
|
||||
|
||||
function completeParameterGenerationIfReady() {
|
||||
if (expectedVariants <= 0 || arrivedVariants < expectedVariants) return;
|
||||
if (parameterGenerationState === 'pending' || parameterGenerationState === 'loading') {
|
||||
completeParameterPublication();
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTunePopover() {
|
||||
if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }
|
||||
if (tuneOpen) { closeTunePopover(); return; }
|
||||
@@ -5796,7 +5803,7 @@
|
||||
setLiveState('CYCLING');
|
||||
showOrUpdateCyclingBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5884,7 +5891,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');
|
||||
} catch (err) {
|
||||
console.error('[impeccable] Failed to mount component-preview variants:', err);
|
||||
@@ -6329,7 +6336,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
|
||||
})
|
||||
.catch(err => {
|
||||
@@ -6836,6 +6843,7 @@
|
||||
|
||||
const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
|
||||
if (expected > 0) expectedVariants = expected;
|
||||
completeParameterGenerationIfReady();
|
||||
|
||||
if (arrivedVariants > 0) {
|
||||
setLiveState('CYCLING');
|
||||
|
||||
@@ -944,8 +944,42 @@ export async function commitManualEdits({
|
||||
};
|
||||
}
|
||||
|
||||
const repairContext = {
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
};
|
||||
|
||||
const baseRollbackScope = collectApplyOwnedFiles(batch, cwd);
|
||||
const rollbackSnapshot = snapshotRollbackFiles(cwd, baseRollbackScope);
|
||||
const failWithRollback = ({
|
||||
scope = baseRollbackScope,
|
||||
extraFiles = [],
|
||||
failed,
|
||||
files = [],
|
||||
details = {},
|
||||
}) => {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, extraFiles, scope);
|
||||
return {
|
||||
applied: [],
|
||||
failed,
|
||||
files,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
...details,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
result = repairOnly
|
||||
@@ -965,42 +999,27 @@ export async function commitManualEdits({
|
||||
chatAvailable,
|
||||
});
|
||||
} catch (err) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, [], baseRollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
failed: batch.entries.map((entry) => ({
|
||||
id: entry.id,
|
||||
reason: err.message || String(err),
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
})),
|
||||
files: [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'error') {
|
||||
const rollbackScope = collectApplyOwnedFiles(batch, cwd, result.files || []);
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const failed = normalizeFailedEntries(batch, result, result.message || 'AI copy edit failed');
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: failed.length > 0
|
||||
? failed
|
||||
: verificationFailuresForEntries(batch, batch.entries, result.message || 'AI copy edit failed'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedIds = uniqueStrings(result.appliedEntryIds || []);
|
||||
@@ -1013,72 +1032,44 @@ export async function commitManualEdits({
|
||||
const conflictingAppliedIds = reportedAppliedIds.filter((id) => failedIds.has(id));
|
||||
|
||||
if (conflictingAppliedIds.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const conflictingEntries = batch.entries.filter((entry) => conflictingAppliedIds.includes(entry.id));
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...verificationFailuresForEntries(batch, conflictingEntries, 'conflicting_apply_result'),
|
||||
...aiFailed.filter((item) => !conflictingAppliedIds.includes(item.id)),
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const unreportedFiles = unreportedChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
if (unreportedFiles.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], [...rollbackScope, ...unreportedFiles]);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: [...rollbackScope, ...unreportedFiles],
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'unreported_source_changes', { files: unreportedFiles }),
|
||||
files: result.files || [],
|
||||
unreportedFiles,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { unreportedFiles, notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'done' && reportedAppliedIds.length === 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'missing_applied_entry_ids'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedEntries = batch.entries.filter((entry) => reportedAppliedIds.includes(entry.id));
|
||||
if (reportedAppliedIds.length > 0 && reportedFiles.length === 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: aiFailed,
|
||||
@@ -1089,21 +1080,10 @@ export async function commitManualEdits({
|
||||
});
|
||||
}
|
||||
|
||||
const verifiedAppliedIds = [];
|
||||
const verificationFailed = [];
|
||||
for (const entry of reportedAppliedEntries) {
|
||||
const failures = verifyAppliedEntry({ batch, entry, reportedFiles, cwd });
|
||||
if (failures.length === 0) {
|
||||
verifiedAppliedIds.push(entry.id);
|
||||
} else {
|
||||
verificationFailed.push({
|
||||
id: entry.id,
|
||||
reason: 'source_verification_failed',
|
||||
failures,
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
const {
|
||||
verifiedIds: verifiedAppliedIds,
|
||||
failed: verificationFailed,
|
||||
} = verifyEntriesAfterRepair({ batch, appliedEntryIds: reportedAppliedIds, files: reportedFiles, cwd });
|
||||
const unreportedEntries = result.status === 'done' || result.status === 'partial'
|
||||
? batch.entries.filter((entry) => !reportedAppliedIds.includes(entry.id) && !aiFailed.some((item) => item.id === entry.id))
|
||||
: [];
|
||||
@@ -1133,37 +1113,22 @@ export async function commitManualEdits({
|
||||
reason: 'rolled_back_due_to_failed_entry_source_changed',
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
}));
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...leakedUnapplied,
|
||||
...failed.filter((item) => !leakedIds.has(item.id)),
|
||||
...rolledBackVerified,
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
notes: result.notes || [],
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (verificationFailed.length > 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: nonRepairFailed,
|
||||
@@ -1180,16 +1145,7 @@ export async function commitManualEdits({
|
||||
? reportedAppliedEntries.filter((entry) => verifiedAppliedIds.includes(entry.id))
|
||||
: batch.entries;
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: verifiedAppliedIds.length > 0
|
||||
? verifiedAppliedIds
|
||||
: postCheckEntries.map((entry) => entry.id).filter(Boolean),
|
||||
|
||||
@@ -238,10 +238,9 @@ export async function completeAcceptHandling(event, base, token) {
|
||||
});
|
||||
} catch (err) {
|
||||
event._completionAck = { ok: false, error: err.message };
|
||||
return event;
|
||||
}
|
||||
if (!event._completionAck) {
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
}
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -269,9 +268,11 @@ export function printPollEvent(event) {
|
||||
// Situational plumbing rides with the event itself: `_instructions` is the
|
||||
// authoritative next step, with real ids and paths substituted, so the
|
||||
// reference doc can stay lean and can never drift from script behavior.
|
||||
if (event && typeof event === 'object' && !event._instructions) {
|
||||
// A wire-supplied value must never win over the locally generated one.
|
||||
if (event && typeof event === 'object') {
|
||||
const instructions = instructionsForEvent(event, { scriptsPath: SELF_DIR });
|
||||
if (instructions) event._instructions = instructions;
|
||||
else delete event._instructions;
|
||||
}
|
||||
console.log(JSON.stringify(event));
|
||||
}
|
||||
|
||||
@@ -181,8 +181,16 @@ function chatAgentLikelyActive() {
|
||||
// cap at 10 MB to guard against runaway writes from a misbehaving client.
|
||||
const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
const POLLER_OWNED_EVENT_FIELDS = ['_instructions', '_completionAck', '_acceptResult'];
|
||||
|
||||
function stripPollerOwnedEventFields(event) {
|
||||
if (!event || typeof event !== 'object') return;
|
||||
for (const key of POLLER_OWNED_EVENT_FIELDS) delete event[key];
|
||||
}
|
||||
|
||||
function enqueueEvent(event) {
|
||||
if (!event) return;
|
||||
stripPollerOwnedEventFields(event);
|
||||
// Dedupe by (session, type), except mount failures, which are per-variant:
|
||||
// variant 2 failing must not be swallowed because variant 1's failure is
|
||||
// still queued.
|
||||
@@ -936,15 +944,23 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
const filePath = url.searchParams.get('path');
|
||||
if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
|
||||
const absPath = path.resolve(process.cwd(), filePath);
|
||||
// Confine to the project root. A bare `startsWith(cwd)` string check lets a
|
||||
// sibling dir whose name extends the root name (projeto -> projeto-backup)
|
||||
// slip through; compare on the relative path instead (same pattern as
|
||||
// sessionFileMetadataFromPollReply below). An empty rel means the request
|
||||
// resolved to the root directory itself, which this file route never serves.
|
||||
const rel = path.relative(process.cwd(), absPath);
|
||||
let realRoot, realTarget;
|
||||
try {
|
||||
realRoot = fs.realpathSync(process.cwd());
|
||||
realTarget = fs.realpathSync(absPath);
|
||||
} catch {
|
||||
res.writeHead(404); res.end('File not found'); return;
|
||||
}
|
||||
// Confine to the project root after symlink resolution. A bare
|
||||
// `startsWith(cwd)` string check lets a sibling dir whose name extends the
|
||||
// root name (projeto -> projeto-backup) slip through; compare on the
|
||||
// relative path instead (same pattern as sessionFileMetadataFromPollReply
|
||||
// below). An empty rel means the request resolved to the root directory
|
||||
// itself, which this file route never serves.
|
||||
const rel = path.relative(realRoot, realTarget);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { res.writeHead(403); res.end('Forbidden'); return; }
|
||||
let content;
|
||||
try { content = fs.readFileSync(absPath, 'utf-8'); }
|
||||
try { content = fs.readFileSync(realTarget, 'utf-8'); }
|
||||
catch { res.writeHead(404); res.end('File not found'); return; }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(content);
|
||||
@@ -1026,6 +1042,7 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
res.end(JSON.stringify({ error }));
|
||||
return;
|
||||
}
|
||||
stripPollerOwnedEventFields(msg);
|
||||
if (msg.type === 'agent_phase') {
|
||||
recordAgentPhase(msg.id, msg.phase, {
|
||||
...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),
|
||||
|
||||
@@ -11,6 +11,8 @@ import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
|
||||
export const SVELTE_LIVE_ROOT_COMPONENT = 'src/lib/impeccable/ImpeccableLiveRoot.svelte';
|
||||
export const SVELTE_LAYOUT_MARKER_OPEN = '<!-- impeccable-live-svelte-start -->';
|
||||
export const SVELTE_LAYOUT_MARKER_CLOSE = '<!-- impeccable-live-svelte-end -->';
|
||||
@@ -45,11 +47,17 @@ export function detectSvelteKitProject(cwd = process.cwd(), config = null) {
|
||||
&& fileIncludes(path.join(cwd, appHtml), '%sveltekit.head%');
|
||||
if (!hasTemplateMarkers) return null;
|
||||
|
||||
const hasSvelteConfig = fs.existsSync(path.join(cwd, 'svelte.config.js'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.mjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.cjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.ts'));
|
||||
const hasKitPackage = packageHasSvelteKit(cwd);
|
||||
const hasSvelteConfig = Boolean(firstExistingFile(cwd, [
|
||||
'svelte.config.js',
|
||||
'svelte.config.mjs',
|
||||
'svelte.config.cjs',
|
||||
'svelte.config.ts',
|
||||
]));
|
||||
const hasKitPackage = hasAnyDependency(cwd, [
|
||||
'@sveltejs/kit',
|
||||
'@sveltejs/vite-plugin-svelte',
|
||||
'svelte',
|
||||
]);
|
||||
if (!hasSvelteConfig && !hasKitPackage) return null;
|
||||
|
||||
return {
|
||||
@@ -260,36 +268,16 @@ function findSvelteKitAppHtml(cwd, config) {
|
||||
}
|
||||
|
||||
function findSvelteKitLayout(cwd) {
|
||||
const candidates = [
|
||||
return firstExistingFile(cwd, [
|
||||
'src/routes/+layout.svelte',
|
||||
'src/routes/(app)/+layout.svelte',
|
||||
];
|
||||
for (const rel of candidates) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return 'src/routes/+layout.svelte';
|
||||
]) || 'src/routes/+layout.svelte';
|
||||
}
|
||||
|
||||
function defaultSvelteLayout() {
|
||||
return `<script>\n let { children } = $props();\n</script>\n\n{@render children?.()}\n`;
|
||||
}
|
||||
|
||||
function packageHasSvelteKit(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fileIncludes(file, text) {
|
||||
try {
|
||||
return fs.readFileSync(file, 'utf-8').includes(text);
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
import { buildLiveScriptSrc } from './frameworks/script-src.mjs';
|
||||
|
||||
export const TANSTACK_MARKER_OPEN = '{/* impeccable-live-tanstack-start */}';
|
||||
@@ -42,8 +44,8 @@ const START_PACKAGES = [
|
||||
];
|
||||
|
||||
export function detectTanStackStartProject(cwd = process.cwd()) {
|
||||
if (!packageHasTanStackStart(cwd)) return null;
|
||||
const rootRoute = findRootRouteFile(cwd);
|
||||
if (!hasAnyDependency(cwd, START_PACKAGES)) return null;
|
||||
const rootRoute = firstExistingFile(cwd, ROOT_ROUTE_CANDIDATES);
|
||||
if (!rootRoute) return null;
|
||||
|
||||
const ext = path.extname(rootRoute);
|
||||
@@ -218,29 +220,6 @@ function isManagedComponent(content) {
|
||||
return String(content || '').includes('impeccable-live-tanstack');
|
||||
}
|
||||
|
||||
function findRootRouteFile(cwd) {
|
||||
for (const rel of ROOT_ROUTE_CANDIDATES) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function packageHasTanStackStart(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return START_PACKAGES.some((name) => Boolean(deps[name]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function relativeImportSpecifier(fromFile, toFile) {
|
||||
const rel = path.posix.relative(
|
||||
path.posix.dirname(fromFile.split(path.sep).join('/')),
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
|
||||
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code and Codex, which both dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit.
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
|
||||
|
||||
Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `context.mjs` asking for a single detector run at the end.
|
||||
|
||||
@@ -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), 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` 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -44,7 +44,7 @@ The first argument is the action. Defaults to `status`.
|
||||
```
|
||||
|
||||
3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write on a UI file."
|
||||
5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/config.json`; add `--local` only when the user explicitly asks for a private exception.
|
||||
6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
|
||||
|
||||
|
||||
@@ -626,7 +626,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -688,7 +688,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -985,7 +985,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -1115,7 +1115,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -773,14 +773,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
@@ -1955,20 +1963,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -1985,13 +1992,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -3986,7 +3990,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
@@ -7281,7 +7285,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -7343,7 +7347,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -7640,7 +7644,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -7770,7 +7774,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -42,6 +42,7 @@ function shouldRunPageAnalyzers(content, filePath) {
|
||||
}
|
||||
|
||||
const JS_SOURCE_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']);
|
||||
const STYLESHEET_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
const REGEX_PREFIX_KEYWORDS = new Set(['await', 'case', 'default', 'delete', 'do', 'else', 'in', 'instanceof', 'new', 'of', 'return', 'throw', 'typeof', 'void', 'yield']);
|
||||
const BLOCK_BRACE_PREFIX_KEYWORDS = new Set(['do', 'else', 'finally', 'try']);
|
||||
|
||||
@@ -256,6 +257,153 @@ function stripCssComments(content) {
|
||||
return content.replace(/\/\*[\s\S]*?\*\//g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankHtmlComments(text) {
|
||||
return text.replace(/<!--[\s\S]*?-->/g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankCssLineCommentsInStyleBlocks(text) {
|
||||
const re = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
const inner = match[1];
|
||||
const openLength = match[0].length - inner.length - '</style>'.length;
|
||||
output += text.slice(lastIndex, match.index);
|
||||
output += match[0].slice(0, openLength);
|
||||
output += blankCssLineComments(inner);
|
||||
output += match[0].slice(openLength + inner.length);
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + text.slice(lastIndex);
|
||||
}
|
||||
|
||||
function blankHtmlAndCssCommentsOutsideScripts(text) {
|
||||
const re = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
output += blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex, match.index))));
|
||||
output += match[0];
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex))));
|
||||
}
|
||||
|
||||
function blankCssLineComments(text) {
|
||||
let output = '';
|
||||
let state = 'code';
|
||||
let urlDepth = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
const next = text[i + 1];
|
||||
if (state === 'line') {
|
||||
if (char === '\n') {
|
||||
output += '\n';
|
||||
state = 'code';
|
||||
} else {
|
||||
output += ' ';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state === 'single' || state === 'double') {
|
||||
output += char;
|
||||
if (char === '\\' && next) {
|
||||
output += next;
|
||||
i++;
|
||||
} else if ((state === 'single' && char === "'") || (state === 'double' && char === '"')) {
|
||||
state = 'code';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const prev = output.length ? output[output.length - 1] : '';
|
||||
if (char === '/' && next === '/' && urlDepth === 0 && prev !== ':' && prev !== '(' && prev !== '\\') {
|
||||
output += ' ';
|
||||
i++;
|
||||
state = 'line';
|
||||
continue;
|
||||
}
|
||||
if (char === "'") state = 'single';
|
||||
else if (char === '"') state = 'double';
|
||||
if (char === '(') {
|
||||
const behind = output.replace(/\s+$/, '');
|
||||
if (urlDepth > 0 || /url$/i.test(behind)) urlDepth++;
|
||||
} else if (char === ')' && urlDepth) {
|
||||
urlDepth--;
|
||||
}
|
||||
output += char;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function findAstroFrontmatterClose(text) {
|
||||
if (!text.startsWith('---')) return -1;
|
||||
let cursor = text.indexOf('\n');
|
||||
if (cursor === -1) return -1;
|
||||
cursor += 1;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor - 1] === '\n' && text.startsWith('---', cursor)) {
|
||||
let end = cursor + 3;
|
||||
while (text[end] === ' ' || text[end] === '\t') end++;
|
||||
if (end >= text.length || text[end] === '\n' || text[end] === '\r') return cursor - 1;
|
||||
}
|
||||
const char = text[cursor];
|
||||
const next = text[cursor + 1];
|
||||
if (char === "'" || char === '"') {
|
||||
const close = findQuotedStringEnd(text, cursor, char);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '`') {
|
||||
const close = findTemplateLiteralEnd(text, cursor);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '/') {
|
||||
const lineEnd = text.indexOf('\n', cursor);
|
||||
if (lineEnd === -1) return -1;
|
||||
cursor = lineEnd;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '*') {
|
||||
const commentEnd = text.indexOf('*/', cursor + 2);
|
||||
if (commentEnd === -1) return -1;
|
||||
cursor = commentEnd + 2;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next !== '/' && next !== '*') {
|
||||
const close = findRegexLiteralEnd(text, cursor);
|
||||
if (close !== -1) {
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cursor++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function blankAstroFrontmatterComments(text) {
|
||||
const close = findAstroFrontmatterClose(text);
|
||||
if (close === -1) return text;
|
||||
return stripJsComments(text.slice(0, close)) + text.slice(close);
|
||||
}
|
||||
|
||||
function blankCommentsForMatchers(text, ext) {
|
||||
if (PAGE_ANALYZER_EXTS.has(ext)) {
|
||||
const withFrontmatter = ext === '.astro' ? blankAstroFrontmatterComments(text) : text;
|
||||
return blankHtmlAndCssCommentsOutsideScripts(withFrontmatter);
|
||||
}
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
const withoutBlocks = stripCssComments(text);
|
||||
return ext === '.css' ? withoutBlocks : blankCssLineComments(withoutBlocks);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function firstOverusedGoogleFont(text) {
|
||||
return extractGoogleFontFamilies(text).find(f => OVERUSED_FONTS.has(f)) || '';
|
||||
}
|
||||
@@ -1028,14 +1176,13 @@ function detectText(content, filePath, options = {}) {
|
||||
const ext = extFromFilePath(filePath);
|
||||
const commentStrippedSource = JS_SOURCE_EXTS.has(ext) ? stripJsComments(content, {
|
||||
jsx: ext === '.js' || ext === '.jsx' || ext === '.tsx',
|
||||
}) : content;
|
||||
}) : blankCommentsForMatchers(content, ext);
|
||||
const source = stripCssInJsComments(commentStrippedSource, ext);
|
||||
const lines = source.split('\n');
|
||||
|
||||
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
|
||||
// Enable block context for CSS files where related properties span multiple lines
|
||||
const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, STYLESHEET_EXTS.has(ext) || null, {
|
||||
profile,
|
||||
phase: 'source',
|
||||
}));
|
||||
@@ -1050,7 +1197,7 @@ function detectText(content, filePath, options = {}) {
|
||||
scanCssTextForPseudoStripe(text).map(hit =>
|
||||
finding(hit.id, filePath, hit.snippet, lineOffset + text.slice(0, hit.index).split('\n').length));
|
||||
|
||||
if (cssLike.has(ext)) {
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
findings.push(...scanInsetStripeCss(content, filePath));
|
||||
findings.push(...pseudoStripeFindings(content, 0));
|
||||
}
|
||||
@@ -1078,7 +1225,8 @@ function detectText(content, filePath, options = {}) {
|
||||
}, () => extractStyleBlocks(content, ext))
|
||||
: extractStyleBlocks(content, ext);
|
||||
for (const block of styleBlocks) {
|
||||
const blockLines = block.content.split('\n');
|
||||
const blockContent = blankCssLineComments(stripCssComments(block.content));
|
||||
const blockLines = blockContent.split('\n');
|
||||
findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
|
||||
profile,
|
||||
phase: 'style-block',
|
||||
@@ -1089,8 +1237,8 @@ function detectText(content, filePath, options = {}) {
|
||||
// 1-based, so the offset is startLine - 2; startLine - 1 double-counted and
|
||||
// reported every selector one line low. runRegexMatchers keeps startLine - 1
|
||||
// because it indexes its split lines from zero.
|
||||
findings.push(...scanInsetStripeCss(block.content, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(block.content, block.startLine - 2));
|
||||
findings.push(...scanInsetStripeCss(blockContent, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(blockContent, block.startLine - 2));
|
||||
}
|
||||
|
||||
// Extract and scan CSS-in-JS template literals
|
||||
|
||||
@@ -721,20 +721,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -751,13 +750,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -2752,7 +2748,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
|
||||
@@ -103,14 +103,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
|
||||
@@ -33,13 +33,8 @@ import {
|
||||
stampProductSchema,
|
||||
} from './lib/artifact-schema.mjs';
|
||||
import {
|
||||
checkBuildPathUnset,
|
||||
checkConfig,
|
||||
checkDesignSidecar,
|
||||
collectBootFindingGroups,
|
||||
checkNativePlatformEvidence,
|
||||
checkProduct,
|
||||
checkProjectRoots,
|
||||
checkSurfaceBriefs,
|
||||
designSidecarCandidatesFor,
|
||||
} from './lib/staleness.mjs';
|
||||
import {
|
||||
@@ -106,34 +101,30 @@ async function collect(cwd, targetOptions) {
|
||||
extractPlatform,
|
||||
readFile: safeRead,
|
||||
});
|
||||
const bootFindings = collectBootFindingGroups(ctx, {
|
||||
absDesignPath,
|
||||
sidecarCandidates,
|
||||
projectRootPatterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
targetCandidates: workspaceCandidates,
|
||||
});
|
||||
|
||||
const findings = [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
...(ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({ designPath: absDesignPath, sidecarCandidates, projectRoot }),
|
||||
...bootFindings.product,
|
||||
...bootFindings.nativePlatform,
|
||||
...bootFindings.designSidecar,
|
||||
...checkDesignDrift({ designPath: absDesignPath, projectRoot }),
|
||||
...checkDesignCoverage({ design: ctx.design, designPath: ctx.designPath, parseDesignMd }),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...bootFindings.config,
|
||||
...bootFindings.buildPath,
|
||||
...checkDetectorIgnores({ projectRoot, knownRuleIds }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...bootFindings.surfaceBriefs,
|
||||
...checkHookInstallation({
|
||||
projectRoot,
|
||||
repoRoot: ctx.repoRoot,
|
||||
providerId: IMPECCABLE_PROVIDER_ID,
|
||||
}),
|
||||
...checkLegacyLiveState({ projectRoot }),
|
||||
...checkProjectRoots({
|
||||
patterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
candidates: workspaceCandidates,
|
||||
}),
|
||||
...bootFindings.projectRoots,
|
||||
...workspaceResult.findings,
|
||||
];
|
||||
|
||||
|
||||
@@ -75,11 +75,11 @@ const HOOK_MANIFEST_TARGETS = [
|
||||
destRel: '.claude/settings.local.json',
|
||||
sharedDestRel: '.claude/settings.json',
|
||||
manifest: () => ({
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.',
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.',
|
||||
hooks: {
|
||||
PostToolUse: [
|
||||
{
|
||||
matcher: 'Edit|Write|MultiEdit',
|
||||
matcher: 'Edit|Write',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
|
||||
@@ -816,9 +816,9 @@ export function splitFindingsByTier(findings) {
|
||||
}
|
||||
|
||||
// Whether the per-edit pass for this harness should defer non-immediate
|
||||
// findings to a Stop deep pass. Only Claude Code and Codex dispatch our Stop
|
||||
// hook; Cursor and GitHub Copilot have no deep pass wired, so deferring for
|
||||
// them would silently drop the non-immediate rules entirely.
|
||||
// findings to a Stop deep pass. Claude Code, Codex, and Grok Build dispatch
|
||||
// our Stop hook; Cursor and GitHub Copilot have no deep pass wired, so
|
||||
// deferring for them would silently drop the non-immediate rules entirely.
|
||||
export function perEditTieringActive(config, harness) {
|
||||
if (harness === 'cursor' || harness === 'github') return false;
|
||||
return (config?.perEditRules || DEFAULT_CONFIG.perEditRules) !== 'all';
|
||||
@@ -1251,9 +1251,14 @@ export function resolveHarness(env = {}, event = null) {
|
||||
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
|
||||
if (explicit === 'cursor') return 'cursor';
|
||||
if (explicit === 'github') return 'github';
|
||||
if (explicit === 'grok') return 'grok';
|
||||
if (explicit === 'claude' || explicit === 'codex') return 'claude';
|
||||
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
|
||||
// has no `tool_name`/`tool_input`. That shape is the discriminator.
|
||||
// Grok Build sends camelCase `toolName`/`toolInput`/`hookEventName` and no
|
||||
// snake_case pair. GitHub Copilot sends camelCase `toolName`/`toolArgs`.
|
||||
// Check Grok first: the old GitHub heuristic (`toolName` and no
|
||||
// `tool_input`) also matches Grok, which is how live PostToolUse was
|
||||
// classified as Copilot and then skipped with no-file-path (#646).
|
||||
if (looksLikeGrokEnvelope(event)) return 'grok';
|
||||
if (event && typeof event === 'object'
|
||||
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
|
||||
&& event.tool_name === undefined && event.tool_input === undefined) {
|
||||
@@ -1263,6 +1268,27 @@ export function resolveHarness(env = {}, event = null) {
|
||||
return 'claude';
|
||||
}
|
||||
|
||||
function looksLikeGrokEnvelope(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
if (event.hook_event_name !== undefined
|
||||
|| event.tool_name !== undefined
|
||||
|| event.tool_input !== undefined) {
|
||||
return false;
|
||||
}
|
||||
if (event.toolArgs !== undefined) return false;
|
||||
if (typeof event.hookEventName === 'string') return true;
|
||||
return typeof event.toolName === 'string' && event.toolInput !== undefined;
|
||||
}
|
||||
|
||||
// Stop arrives as Claude's `hook_event_name: "Stop"` or Grok Build's
|
||||
// `hookEventName: "stop"`. hook.mjs routes on the raw stdin, before any
|
||||
// normalize, so both casings must match here.
|
||||
export function isStopEvent(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const name = event.hook_event_name || event.hookEventName;
|
||||
return typeof name === 'string' && name.toLowerCase() === 'stop';
|
||||
}
|
||||
|
||||
// GitHub Copilot's postToolUse payload is
|
||||
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
|
||||
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
|
||||
@@ -1354,9 +1380,36 @@ function normalizeGitHubEvent(event, projectCwd) {
|
||||
};
|
||||
}
|
||||
|
||||
// Grok Build 1.0.5 (captured 2026-08-24) sends camelCase `toolName` /
|
||||
// `toolInput` / `sessionId` / `stopHookActive`, plus `cwd` alongside a
|
||||
// trailing-slashed `workspaceRoot` (every consumer path.resolve()s, so no
|
||||
// stripping here). Only the fields the hook reads are copied; the event
|
||||
// name stays camelCase because routing already happened on the raw stdin
|
||||
// (isStopEvent) and nothing downstream reads `hook_event_name`.
|
||||
function normalizeGrokEvent(event, projectCwd) {
|
||||
const cwd = event.cwd || event.workspaceRoot || envProjectDir(projectCwd) || projectCwd;
|
||||
const sessionId = event.sessionId || event.session_id || 'unknown';
|
||||
const rawInput = event.toolInput ?? event.tool_input;
|
||||
const toolInput = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
|
||||
? { ...rawInput }
|
||||
: {};
|
||||
const out = {
|
||||
...event,
|
||||
cwd,
|
||||
session_id: sessionId,
|
||||
tool_name: event.toolName || event.tool_name || null,
|
||||
tool_input: toolInput,
|
||||
};
|
||||
if (event.stopHookActive !== undefined && event.stop_hook_active === undefined) {
|
||||
out.stop_hook_active = event.stopHookActive;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
|
||||
if (!event || typeof event !== 'object') return event;
|
||||
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
|
||||
if (harness === 'grok') return normalizeGrokEvent(event, projectCwd);
|
||||
if (harness !== 'cursor') return event;
|
||||
|
||||
const cwd = event.cwd
|
||||
@@ -1959,7 +2012,15 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// findings stop being remembered and a reintroduced one reads as fresh.
|
||||
// Only the immediate tier is remembered: a deferred finding the per-edit
|
||||
// pass never reported must still read as fresh to the Stop deep pass.
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
//
|
||||
// Grok ignores PostToolUse stdout, so Stop is the user-visible pass.
|
||||
// Remembering here would dedupe those findings out of Stop. Touch the
|
||||
// file so Stop has it, and leave the finding list empty.
|
||||
if (harness === 'grok') {
|
||||
touchFile(cache, sessionId, filePath);
|
||||
} else {
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
}
|
||||
cacheDirty = true;
|
||||
|
||||
if (fresh.length > 0) {
|
||||
@@ -2191,22 +2252,32 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
event = normalizeHookEvent(event, cwd, harness);
|
||||
|
||||
// Claude Code's Stop-hook contract: `stop_hook_active` is true when this
|
||||
// hook is being re-invoked only because a prior invocation kept the turn
|
||||
// alive (here, via hookSpecificOutput.additionalContext). Re-scanning and
|
||||
// re-blocking now would loop until Claude Code's consecutive-block cap
|
||||
// force-ends the turn (issue #400). The prior fire already surfaced the
|
||||
// findings; whether to act on them is the agent's call. Exit fast with no
|
||||
// output before any scan. Only Claude Code sends this field; other
|
||||
// harnesses omit it, so the strict `=== true` is a no-op for them. This
|
||||
// guard makes the loop impossible regardless of the finding cache key's
|
||||
// line-number sensitivity (out of scope here; see findingCacheKey).
|
||||
// output before any scan. Claude sends `stop_hook_active`; Grok sends
|
||||
// `stopHookActive`, copied onto the snake_case field above. The strict
|
||||
// `=== true` is a no-op when the field is absent. This guard makes the
|
||||
// loop impossible regardless of the finding cache key's line-number
|
||||
// sensitivity (out of scope here; see findingCacheKey).
|
||||
if (event.stop_hook_active === true) {
|
||||
return result({ skipped: 'stop-hook-active', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
// Grok fires Stop twice: `end_turn` (the gate that can inject
|
||||
// additionalContext) then an observe-only `shutdown`. A second deep
|
||||
// pass would re-emit the same findings. Claude omits `reason`; only
|
||||
// skip when Grok named a reason that is not end_turn.
|
||||
if (harness === 'grok' && typeof event.reason === 'string' && event.reason !== 'end_turn') {
|
||||
return result({ skipped: 'stop-reason', reason: event.reason, durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
// A Stop event carries no file, so the session cwd is the project.
|
||||
// Umbrella-dir launches keyed their per-edit cache to the edited file's
|
||||
@@ -2241,6 +2312,7 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
|
||||
const freshGroups = [];
|
||||
let scanned = 0;
|
||||
let cacheDirty = false;
|
||||
for (const filePath of touched) {
|
||||
if (scanned >= STOP_MAX_FILES) break;
|
||||
if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) continue;
|
||||
@@ -2261,29 +2333,39 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
|
||||
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
const useHtmlEngine = configuredExt
|
||||
? configuredExt.engine === 'html'
|
||||
: (ext === '.html' || ext === '.htm');
|
||||
|
||||
if (useHtmlEngine && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
// A detector failure tells us nothing about the file. Leave whatever
|
||||
// was remembered alone rather than recording an empty scan as truth.
|
||||
if (detectorThrew) continue;
|
||||
|
||||
// Full rule set: no tier split here. Config/inline ignores still apply,
|
||||
// and the session dedupe drops everything the per-edit pass (or an
|
||||
// earlier Stop pass) already surfaced.
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
|
||||
// Sync to the live scan, including empty. Remembering only `fresh`
|
||||
// (or skipping the write on a clean Stop) left stale keys in place, so
|
||||
// a finding that was fixed and later reintroduced never fired again.
|
||||
rememberFindings(cache, sessionId, filePath, filtered);
|
||||
cacheDirty = true;
|
||||
if (fresh.length > 0) {
|
||||
rememberFindings(cache, sessionId, filePath, fresh);
|
||||
freshGroups.push({ filePath, findings: fresh });
|
||||
}
|
||||
}
|
||||
audit.scannedFiles = scanned;
|
||||
|
||||
if (freshGroups.length === 0) {
|
||||
if (cacheDirty) persistCache(projectCwd, cache);
|
||||
return result({ emitted: false, skipped: 'stop-clean', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
@@ -2300,8 +2382,8 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
);
|
||||
commitFooterShown(cache, sessionId, text);
|
||||
|
||||
// Fresh findings earn the cache write so the next Stop fire is silent
|
||||
// unless new issues appear; the notice flags ride along.
|
||||
// Persist the live finding set so the next Stop fire is silent unless
|
||||
// new issues appear; the notice flags ride along.
|
||||
persistCache(projectCwd, cache);
|
||||
return {
|
||||
exitCode: 0,
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
/**
|
||||
* Impeccable design hook — PostToolUse + Stop entry point.
|
||||
*
|
||||
* Reads the Claude Code / Codex / Cursor hook event from stdin and routes by
|
||||
* `hook_event_name`:
|
||||
* Reads the Claude Code / Codex / Cursor / Grok Build hook event from stdin
|
||||
* and routes by Stop vs everything else. Claude uses `hook_event_name:
|
||||
* "Stop"`; Grok uses `hookEventName: "stop"`.
|
||||
*
|
||||
* - PostToolUse: runs the immediate-tier detector rules against the touched
|
||||
* file and emits a system reminder via
|
||||
* `hookSpecificOutput.additionalContext` when findings exist.
|
||||
* `hookSpecificOutput.additionalContext` when findings exist. Grok
|
||||
* discards that stdout; the scan still warms the session cache for Stop.
|
||||
* - Stop: runs the FULL detector rule set over every UI file touched this
|
||||
* session (the deep pass), deduped against what the per-edit pass already
|
||||
* surfaced, and emits once via the Stop additionalContext channel.
|
||||
@@ -19,7 +21,7 @@
|
||||
* subprocess. This file is the thin stdin/stdout adapter.
|
||||
*/
|
||||
|
||||
import { runHook, runStopHook, writeAuditLog } from './hook-lib.mjs';
|
||||
import { runHook, runStopHook, writeAuditLog, isStopEvent } from './hook-lib.mjs';
|
||||
|
||||
async function readStdin() {
|
||||
if (process.stdin.isTTY) return '';
|
||||
@@ -28,10 +30,9 @@ async function readStdin() {
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
function isStopEvent(stdinJson) {
|
||||
function stdinIsStop(stdinJson) {
|
||||
try {
|
||||
const event = JSON.parse(stdinJson);
|
||||
return event && typeof event === 'object' && event.hook_event_name === 'Stop';
|
||||
return isStopEvent(JSON.parse(stdinJson));
|
||||
} catch {
|
||||
// Malformed stdin falls through to runHook, which audits the skip.
|
||||
return false;
|
||||
@@ -48,7 +49,7 @@ async function main() {
|
||||
let stdinJson = '';
|
||||
try { stdinJson = await readStdin(); } catch { /* fall through */ }
|
||||
|
||||
const run = isStopEvent(stdinJson) ? runStopHook : runHook;
|
||||
const run = stdinIsStop(stdinJson) ? runStopHook : runHook;
|
||||
const result = await run({
|
||||
stdinJson,
|
||||
env: inheritedEnv,
|
||||
|
||||
@@ -196,9 +196,6 @@ function parseScalar(raw) {
|
||||
|
||||
const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
|
||||
const OKLCH_RE = /oklch\([^)]+\)/gi;
|
||||
const RGBA_RE = /rgba?\([^)]+\)/gi;
|
||||
const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
|
||||
const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
|
||||
|
||||
// ---------- Section splitting ----------
|
||||
|
||||
@@ -550,36 +547,6 @@ function detectFormat(v) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function scanInlineColors(lines) {
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '');
|
||||
const color = parseColorBullet(trimmed);
|
||||
if (color) out.push(color);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseStitchInlineGroups(lines) {
|
||||
// Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
|
||||
// Each bullet IS its own role. Group them under the spoken role name.
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
|
||||
const m = trimmed.match(
|
||||
/^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
|
||||
);
|
||||
if (m) {
|
||||
const role = m[1];
|
||||
const color = buildColor(role, m[2], m[3]);
|
||||
out.push({ role, colors: [color] });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractTypography(section) {
|
||||
if (!section) return null;
|
||||
const text = section.lines.join('\n');
|
||||
|
||||
@@ -488,41 +488,46 @@ export function describeWorkspaceContext(candidates = []) {
|
||||
// ─── Tier 1 orchestration ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Everything a boot can afford. `ctx` is the loadContext result; `extras`
|
||||
* carries values the caller already computed so nothing is recomputed here.
|
||||
* Everything a boot can afford, grouped by artifact so deeper reports can
|
||||
* interleave their own checks without rebuilding this policy. `ctx` is the
|
||||
* loadContext result; `extras` carries values the caller already computed so
|
||||
* nothing is recomputed here.
|
||||
*/
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
if (!ctx) return [];
|
||||
export function collectBootFindingGroups(ctx, extras = {}) {
|
||||
if (!ctx) return {};
|
||||
const projectRoot = ctx.projectRoot || process.cwd();
|
||||
const absProductPath = extras.absProductPath || null;
|
||||
const absDesignPath = extras.absDesignPath || null;
|
||||
|
||||
return [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
return {
|
||||
product: checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
// Only checked once a PRODUCT.md exists. Without one the boot already
|
||||
// emits NO_PRODUCT_MD and routes into init, which asks for the platform
|
||||
// directly; a second signal saying the same thing is noise.
|
||||
...(ctx.product
|
||||
nativePlatform: ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({
|
||||
: [],
|
||||
designSidecar: checkDesignSidecar({
|
||||
designPath: absDesignPath,
|
||||
sidecarCandidates: extras.sidecarCandidates || [],
|
||||
projectRoot,
|
||||
}),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...(extras.projectRootPatterns
|
||||
config: checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
buildPath: checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
surfaceBriefs: checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
projectRoots: extras.projectRootPatterns
|
||||
? checkProjectRoots({
|
||||
patterns: extras.projectRootPatterns,
|
||||
candidates: extras.targetCandidates || [],
|
||||
})
|
||||
: []),
|
||||
];
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
return Object.values(collectBootFindingGroups(ctx, extras)).flat();
|
||||
}
|
||||
|
||||
@@ -4902,6 +4902,13 @@
|
||||
saveSession();
|
||||
}
|
||||
|
||||
function completeParameterGenerationIfReady() {
|
||||
if (expectedVariants <= 0 || arrivedVariants < expectedVariants) return;
|
||||
if (parameterGenerationState === 'pending' || parameterGenerationState === 'loading') {
|
||||
completeParameterPublication();
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTunePopover() {
|
||||
if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }
|
||||
if (tuneOpen) { closeTunePopover(); return; }
|
||||
@@ -5796,7 +5803,7 @@
|
||||
setLiveState('CYCLING');
|
||||
showOrUpdateCyclingBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5884,7 +5891,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');
|
||||
} catch (err) {
|
||||
console.error('[impeccable] Failed to mount component-preview variants:', err);
|
||||
@@ -6329,7 +6336,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
|
||||
})
|
||||
.catch(err => {
|
||||
@@ -6836,6 +6843,7 @@
|
||||
|
||||
const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
|
||||
if (expected > 0) expectedVariants = expected;
|
||||
completeParameterGenerationIfReady();
|
||||
|
||||
if (arrivedVariants > 0) {
|
||||
setLiveState('CYCLING');
|
||||
|
||||
@@ -944,8 +944,42 @@ export async function commitManualEdits({
|
||||
};
|
||||
}
|
||||
|
||||
const repairContext = {
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
};
|
||||
|
||||
const baseRollbackScope = collectApplyOwnedFiles(batch, cwd);
|
||||
const rollbackSnapshot = snapshotRollbackFiles(cwd, baseRollbackScope);
|
||||
const failWithRollback = ({
|
||||
scope = baseRollbackScope,
|
||||
extraFiles = [],
|
||||
failed,
|
||||
files = [],
|
||||
details = {},
|
||||
}) => {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, extraFiles, scope);
|
||||
return {
|
||||
applied: [],
|
||||
failed,
|
||||
files,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
...details,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
result = repairOnly
|
||||
@@ -965,42 +999,27 @@ export async function commitManualEdits({
|
||||
chatAvailable,
|
||||
});
|
||||
} catch (err) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, [], baseRollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
failed: batch.entries.map((entry) => ({
|
||||
id: entry.id,
|
||||
reason: err.message || String(err),
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
})),
|
||||
files: [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'error') {
|
||||
const rollbackScope = collectApplyOwnedFiles(batch, cwd, result.files || []);
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const failed = normalizeFailedEntries(batch, result, result.message || 'AI copy edit failed');
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: failed.length > 0
|
||||
? failed
|
||||
: verificationFailuresForEntries(batch, batch.entries, result.message || 'AI copy edit failed'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedIds = uniqueStrings(result.appliedEntryIds || []);
|
||||
@@ -1013,72 +1032,44 @@ export async function commitManualEdits({
|
||||
const conflictingAppliedIds = reportedAppliedIds.filter((id) => failedIds.has(id));
|
||||
|
||||
if (conflictingAppliedIds.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const conflictingEntries = batch.entries.filter((entry) => conflictingAppliedIds.includes(entry.id));
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...verificationFailuresForEntries(batch, conflictingEntries, 'conflicting_apply_result'),
|
||||
...aiFailed.filter((item) => !conflictingAppliedIds.includes(item.id)),
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const unreportedFiles = unreportedChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
if (unreportedFiles.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], [...rollbackScope, ...unreportedFiles]);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: [...rollbackScope, ...unreportedFiles],
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'unreported_source_changes', { files: unreportedFiles }),
|
||||
files: result.files || [],
|
||||
unreportedFiles,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { unreportedFiles, notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'done' && reportedAppliedIds.length === 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'missing_applied_entry_ids'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedEntries = batch.entries.filter((entry) => reportedAppliedIds.includes(entry.id));
|
||||
if (reportedAppliedIds.length > 0 && reportedFiles.length === 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: aiFailed,
|
||||
@@ -1089,21 +1080,10 @@ export async function commitManualEdits({
|
||||
});
|
||||
}
|
||||
|
||||
const verifiedAppliedIds = [];
|
||||
const verificationFailed = [];
|
||||
for (const entry of reportedAppliedEntries) {
|
||||
const failures = verifyAppliedEntry({ batch, entry, reportedFiles, cwd });
|
||||
if (failures.length === 0) {
|
||||
verifiedAppliedIds.push(entry.id);
|
||||
} else {
|
||||
verificationFailed.push({
|
||||
id: entry.id,
|
||||
reason: 'source_verification_failed',
|
||||
failures,
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
const {
|
||||
verifiedIds: verifiedAppliedIds,
|
||||
failed: verificationFailed,
|
||||
} = verifyEntriesAfterRepair({ batch, appliedEntryIds: reportedAppliedIds, files: reportedFiles, cwd });
|
||||
const unreportedEntries = result.status === 'done' || result.status === 'partial'
|
||||
? batch.entries.filter((entry) => !reportedAppliedIds.includes(entry.id) && !aiFailed.some((item) => item.id === entry.id))
|
||||
: [];
|
||||
@@ -1133,37 +1113,22 @@ export async function commitManualEdits({
|
||||
reason: 'rolled_back_due_to_failed_entry_source_changed',
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
}));
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...leakedUnapplied,
|
||||
...failed.filter((item) => !leakedIds.has(item.id)),
|
||||
...rolledBackVerified,
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
notes: result.notes || [],
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (verificationFailed.length > 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: nonRepairFailed,
|
||||
@@ -1180,16 +1145,7 @@ export async function commitManualEdits({
|
||||
? reportedAppliedEntries.filter((entry) => verifiedAppliedIds.includes(entry.id))
|
||||
: batch.entries;
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: verifiedAppliedIds.length > 0
|
||||
? verifiedAppliedIds
|
||||
: postCheckEntries.map((entry) => entry.id).filter(Boolean),
|
||||
|
||||
@@ -238,10 +238,9 @@ export async function completeAcceptHandling(event, base, token) {
|
||||
});
|
||||
} catch (err) {
|
||||
event._completionAck = { ok: false, error: err.message };
|
||||
return event;
|
||||
}
|
||||
if (!event._completionAck) {
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
}
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -269,9 +268,11 @@ export function printPollEvent(event) {
|
||||
// Situational plumbing rides with the event itself: `_instructions` is the
|
||||
// authoritative next step, with real ids and paths substituted, so the
|
||||
// reference doc can stay lean and can never drift from script behavior.
|
||||
if (event && typeof event === 'object' && !event._instructions) {
|
||||
// A wire-supplied value must never win over the locally generated one.
|
||||
if (event && typeof event === 'object') {
|
||||
const instructions = instructionsForEvent(event, { scriptsPath: SELF_DIR });
|
||||
if (instructions) event._instructions = instructions;
|
||||
else delete event._instructions;
|
||||
}
|
||||
console.log(JSON.stringify(event));
|
||||
}
|
||||
|
||||
@@ -181,8 +181,16 @@ function chatAgentLikelyActive() {
|
||||
// cap at 10 MB to guard against runaway writes from a misbehaving client.
|
||||
const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
const POLLER_OWNED_EVENT_FIELDS = ['_instructions', '_completionAck', '_acceptResult'];
|
||||
|
||||
function stripPollerOwnedEventFields(event) {
|
||||
if (!event || typeof event !== 'object') return;
|
||||
for (const key of POLLER_OWNED_EVENT_FIELDS) delete event[key];
|
||||
}
|
||||
|
||||
function enqueueEvent(event) {
|
||||
if (!event) return;
|
||||
stripPollerOwnedEventFields(event);
|
||||
// Dedupe by (session, type), except mount failures, which are per-variant:
|
||||
// variant 2 failing must not be swallowed because variant 1's failure is
|
||||
// still queued.
|
||||
@@ -936,15 +944,23 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
const filePath = url.searchParams.get('path');
|
||||
if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
|
||||
const absPath = path.resolve(process.cwd(), filePath);
|
||||
// Confine to the project root. A bare `startsWith(cwd)` string check lets a
|
||||
// sibling dir whose name extends the root name (projeto -> projeto-backup)
|
||||
// slip through; compare on the relative path instead (same pattern as
|
||||
// sessionFileMetadataFromPollReply below). An empty rel means the request
|
||||
// resolved to the root directory itself, which this file route never serves.
|
||||
const rel = path.relative(process.cwd(), absPath);
|
||||
let realRoot, realTarget;
|
||||
try {
|
||||
realRoot = fs.realpathSync(process.cwd());
|
||||
realTarget = fs.realpathSync(absPath);
|
||||
} catch {
|
||||
res.writeHead(404); res.end('File not found'); return;
|
||||
}
|
||||
// Confine to the project root after symlink resolution. A bare
|
||||
// `startsWith(cwd)` string check lets a sibling dir whose name extends the
|
||||
// root name (projeto -> projeto-backup) slip through; compare on the
|
||||
// relative path instead (same pattern as sessionFileMetadataFromPollReply
|
||||
// below). An empty rel means the request resolved to the root directory
|
||||
// itself, which this file route never serves.
|
||||
const rel = path.relative(realRoot, realTarget);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { res.writeHead(403); res.end('Forbidden'); return; }
|
||||
let content;
|
||||
try { content = fs.readFileSync(absPath, 'utf-8'); }
|
||||
try { content = fs.readFileSync(realTarget, 'utf-8'); }
|
||||
catch { res.writeHead(404); res.end('File not found'); return; }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(content);
|
||||
@@ -1026,6 +1042,7 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
res.end(JSON.stringify({ error }));
|
||||
return;
|
||||
}
|
||||
stripPollerOwnedEventFields(msg);
|
||||
if (msg.type === 'agent_phase') {
|
||||
recordAgentPhase(msg.id, msg.phase, {
|
||||
...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),
|
||||
|
||||
@@ -11,6 +11,8 @@ import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
|
||||
export const SVELTE_LIVE_ROOT_COMPONENT = 'src/lib/impeccable/ImpeccableLiveRoot.svelte';
|
||||
export const SVELTE_LAYOUT_MARKER_OPEN = '<!-- impeccable-live-svelte-start -->';
|
||||
export const SVELTE_LAYOUT_MARKER_CLOSE = '<!-- impeccable-live-svelte-end -->';
|
||||
@@ -45,11 +47,17 @@ export function detectSvelteKitProject(cwd = process.cwd(), config = null) {
|
||||
&& fileIncludes(path.join(cwd, appHtml), '%sveltekit.head%');
|
||||
if (!hasTemplateMarkers) return null;
|
||||
|
||||
const hasSvelteConfig = fs.existsSync(path.join(cwd, 'svelte.config.js'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.mjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.cjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.ts'));
|
||||
const hasKitPackage = packageHasSvelteKit(cwd);
|
||||
const hasSvelteConfig = Boolean(firstExistingFile(cwd, [
|
||||
'svelte.config.js',
|
||||
'svelte.config.mjs',
|
||||
'svelte.config.cjs',
|
||||
'svelte.config.ts',
|
||||
]));
|
||||
const hasKitPackage = hasAnyDependency(cwd, [
|
||||
'@sveltejs/kit',
|
||||
'@sveltejs/vite-plugin-svelte',
|
||||
'svelte',
|
||||
]);
|
||||
if (!hasSvelteConfig && !hasKitPackage) return null;
|
||||
|
||||
return {
|
||||
@@ -260,36 +268,16 @@ function findSvelteKitAppHtml(cwd, config) {
|
||||
}
|
||||
|
||||
function findSvelteKitLayout(cwd) {
|
||||
const candidates = [
|
||||
return firstExistingFile(cwd, [
|
||||
'src/routes/+layout.svelte',
|
||||
'src/routes/(app)/+layout.svelte',
|
||||
];
|
||||
for (const rel of candidates) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return 'src/routes/+layout.svelte';
|
||||
]) || 'src/routes/+layout.svelte';
|
||||
}
|
||||
|
||||
function defaultSvelteLayout() {
|
||||
return `<script>\n let { children } = $props();\n</script>\n\n{@render children?.()}\n`;
|
||||
}
|
||||
|
||||
function packageHasSvelteKit(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fileIncludes(file, text) {
|
||||
try {
|
||||
return fs.readFileSync(file, 'utf-8').includes(text);
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
import { buildLiveScriptSrc } from './frameworks/script-src.mjs';
|
||||
|
||||
export const TANSTACK_MARKER_OPEN = '{/* impeccable-live-tanstack-start */}';
|
||||
@@ -42,8 +44,8 @@ const START_PACKAGES = [
|
||||
];
|
||||
|
||||
export function detectTanStackStartProject(cwd = process.cwd()) {
|
||||
if (!packageHasTanStackStart(cwd)) return null;
|
||||
const rootRoute = findRootRouteFile(cwd);
|
||||
if (!hasAnyDependency(cwd, START_PACKAGES)) return null;
|
||||
const rootRoute = firstExistingFile(cwd, ROOT_ROUTE_CANDIDATES);
|
||||
if (!rootRoute) return null;
|
||||
|
||||
const ext = path.extname(rootRoute);
|
||||
@@ -218,29 +220,6 @@ function isManagedComponent(content) {
|
||||
return String(content || '').includes('impeccable-live-tanstack');
|
||||
}
|
||||
|
||||
function findRootRouteFile(cwd) {
|
||||
for (const rel of ROOT_ROUTE_CANDIDATES) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function packageHasTanStackStart(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return START_PACKAGES.some((name) => Boolean(deps[name]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function relativeImportSpecifier(fromFile, toFile) {
|
||||
const rel = path.posix.relative(
|
||||
path.posix.dirname(fromFile.split(path.sep).join('/')),
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
|
||||
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code and Codex, which both dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit.
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
|
||||
|
||||
Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `context.mjs` asking for a single detector run at the end.
|
||||
|
||||
@@ -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), 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` 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -44,7 +44,7 @@ The first argument is the action. Defaults to `status`.
|
||||
```
|
||||
|
||||
3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write on a UI file."
|
||||
5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/config.json`; add `--local` only when the user explicitly asks for a private exception.
|
||||
6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
|
||||
|
||||
|
||||
@@ -626,7 +626,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -688,7 +688,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -985,7 +985,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -1115,7 +1115,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -773,14 +773,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
@@ -1955,20 +1963,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -1985,13 +1992,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -3986,7 +3990,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
@@ -7281,7 +7285,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -7343,7 +7347,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -7640,7 +7644,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -7770,7 +7774,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -42,6 +42,7 @@ function shouldRunPageAnalyzers(content, filePath) {
|
||||
}
|
||||
|
||||
const JS_SOURCE_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']);
|
||||
const STYLESHEET_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
const REGEX_PREFIX_KEYWORDS = new Set(['await', 'case', 'default', 'delete', 'do', 'else', 'in', 'instanceof', 'new', 'of', 'return', 'throw', 'typeof', 'void', 'yield']);
|
||||
const BLOCK_BRACE_PREFIX_KEYWORDS = new Set(['do', 'else', 'finally', 'try']);
|
||||
|
||||
@@ -256,6 +257,153 @@ function stripCssComments(content) {
|
||||
return content.replace(/\/\*[\s\S]*?\*\//g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankHtmlComments(text) {
|
||||
return text.replace(/<!--[\s\S]*?-->/g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankCssLineCommentsInStyleBlocks(text) {
|
||||
const re = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
const inner = match[1];
|
||||
const openLength = match[0].length - inner.length - '</style>'.length;
|
||||
output += text.slice(lastIndex, match.index);
|
||||
output += match[0].slice(0, openLength);
|
||||
output += blankCssLineComments(inner);
|
||||
output += match[0].slice(openLength + inner.length);
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + text.slice(lastIndex);
|
||||
}
|
||||
|
||||
function blankHtmlAndCssCommentsOutsideScripts(text) {
|
||||
const re = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
output += blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex, match.index))));
|
||||
output += match[0];
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex))));
|
||||
}
|
||||
|
||||
function blankCssLineComments(text) {
|
||||
let output = '';
|
||||
let state = 'code';
|
||||
let urlDepth = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
const next = text[i + 1];
|
||||
if (state === 'line') {
|
||||
if (char === '\n') {
|
||||
output += '\n';
|
||||
state = 'code';
|
||||
} else {
|
||||
output += ' ';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state === 'single' || state === 'double') {
|
||||
output += char;
|
||||
if (char === '\\' && next) {
|
||||
output += next;
|
||||
i++;
|
||||
} else if ((state === 'single' && char === "'") || (state === 'double' && char === '"')) {
|
||||
state = 'code';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const prev = output.length ? output[output.length - 1] : '';
|
||||
if (char === '/' && next === '/' && urlDepth === 0 && prev !== ':' && prev !== '(' && prev !== '\\') {
|
||||
output += ' ';
|
||||
i++;
|
||||
state = 'line';
|
||||
continue;
|
||||
}
|
||||
if (char === "'") state = 'single';
|
||||
else if (char === '"') state = 'double';
|
||||
if (char === '(') {
|
||||
const behind = output.replace(/\s+$/, '');
|
||||
if (urlDepth > 0 || /url$/i.test(behind)) urlDepth++;
|
||||
} else if (char === ')' && urlDepth) {
|
||||
urlDepth--;
|
||||
}
|
||||
output += char;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function findAstroFrontmatterClose(text) {
|
||||
if (!text.startsWith('---')) return -1;
|
||||
let cursor = text.indexOf('\n');
|
||||
if (cursor === -1) return -1;
|
||||
cursor += 1;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor - 1] === '\n' && text.startsWith('---', cursor)) {
|
||||
let end = cursor + 3;
|
||||
while (text[end] === ' ' || text[end] === '\t') end++;
|
||||
if (end >= text.length || text[end] === '\n' || text[end] === '\r') return cursor - 1;
|
||||
}
|
||||
const char = text[cursor];
|
||||
const next = text[cursor + 1];
|
||||
if (char === "'" || char === '"') {
|
||||
const close = findQuotedStringEnd(text, cursor, char);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '`') {
|
||||
const close = findTemplateLiteralEnd(text, cursor);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '/') {
|
||||
const lineEnd = text.indexOf('\n', cursor);
|
||||
if (lineEnd === -1) return -1;
|
||||
cursor = lineEnd;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '*') {
|
||||
const commentEnd = text.indexOf('*/', cursor + 2);
|
||||
if (commentEnd === -1) return -1;
|
||||
cursor = commentEnd + 2;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next !== '/' && next !== '*') {
|
||||
const close = findRegexLiteralEnd(text, cursor);
|
||||
if (close !== -1) {
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cursor++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function blankAstroFrontmatterComments(text) {
|
||||
const close = findAstroFrontmatterClose(text);
|
||||
if (close === -1) return text;
|
||||
return stripJsComments(text.slice(0, close)) + text.slice(close);
|
||||
}
|
||||
|
||||
function blankCommentsForMatchers(text, ext) {
|
||||
if (PAGE_ANALYZER_EXTS.has(ext)) {
|
||||
const withFrontmatter = ext === '.astro' ? blankAstroFrontmatterComments(text) : text;
|
||||
return blankHtmlAndCssCommentsOutsideScripts(withFrontmatter);
|
||||
}
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
const withoutBlocks = stripCssComments(text);
|
||||
return ext === '.css' ? withoutBlocks : blankCssLineComments(withoutBlocks);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function firstOverusedGoogleFont(text) {
|
||||
return extractGoogleFontFamilies(text).find(f => OVERUSED_FONTS.has(f)) || '';
|
||||
}
|
||||
@@ -1028,14 +1176,13 @@ function detectText(content, filePath, options = {}) {
|
||||
const ext = extFromFilePath(filePath);
|
||||
const commentStrippedSource = JS_SOURCE_EXTS.has(ext) ? stripJsComments(content, {
|
||||
jsx: ext === '.js' || ext === '.jsx' || ext === '.tsx',
|
||||
}) : content;
|
||||
}) : blankCommentsForMatchers(content, ext);
|
||||
const source = stripCssInJsComments(commentStrippedSource, ext);
|
||||
const lines = source.split('\n');
|
||||
|
||||
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
|
||||
// Enable block context for CSS files where related properties span multiple lines
|
||||
const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, STYLESHEET_EXTS.has(ext) || null, {
|
||||
profile,
|
||||
phase: 'source',
|
||||
}));
|
||||
@@ -1050,7 +1197,7 @@ function detectText(content, filePath, options = {}) {
|
||||
scanCssTextForPseudoStripe(text).map(hit =>
|
||||
finding(hit.id, filePath, hit.snippet, lineOffset + text.slice(0, hit.index).split('\n').length));
|
||||
|
||||
if (cssLike.has(ext)) {
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
findings.push(...scanInsetStripeCss(content, filePath));
|
||||
findings.push(...pseudoStripeFindings(content, 0));
|
||||
}
|
||||
@@ -1078,7 +1225,8 @@ function detectText(content, filePath, options = {}) {
|
||||
}, () => extractStyleBlocks(content, ext))
|
||||
: extractStyleBlocks(content, ext);
|
||||
for (const block of styleBlocks) {
|
||||
const blockLines = block.content.split('\n');
|
||||
const blockContent = blankCssLineComments(stripCssComments(block.content));
|
||||
const blockLines = blockContent.split('\n');
|
||||
findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
|
||||
profile,
|
||||
phase: 'style-block',
|
||||
@@ -1089,8 +1237,8 @@ function detectText(content, filePath, options = {}) {
|
||||
// 1-based, so the offset is startLine - 2; startLine - 1 double-counted and
|
||||
// reported every selector one line low. runRegexMatchers keeps startLine - 1
|
||||
// because it indexes its split lines from zero.
|
||||
findings.push(...scanInsetStripeCss(block.content, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(block.content, block.startLine - 2));
|
||||
findings.push(...scanInsetStripeCss(blockContent, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(blockContent, block.startLine - 2));
|
||||
}
|
||||
|
||||
// Extract and scan CSS-in-JS template literals
|
||||
|
||||
@@ -721,20 +721,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -751,13 +750,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -2752,7 +2748,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
|
||||
@@ -103,14 +103,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
|
||||
@@ -33,13 +33,8 @@ import {
|
||||
stampProductSchema,
|
||||
} from './lib/artifact-schema.mjs';
|
||||
import {
|
||||
checkBuildPathUnset,
|
||||
checkConfig,
|
||||
checkDesignSidecar,
|
||||
collectBootFindingGroups,
|
||||
checkNativePlatformEvidence,
|
||||
checkProduct,
|
||||
checkProjectRoots,
|
||||
checkSurfaceBriefs,
|
||||
designSidecarCandidatesFor,
|
||||
} from './lib/staleness.mjs';
|
||||
import {
|
||||
@@ -106,34 +101,30 @@ async function collect(cwd, targetOptions) {
|
||||
extractPlatform,
|
||||
readFile: safeRead,
|
||||
});
|
||||
const bootFindings = collectBootFindingGroups(ctx, {
|
||||
absDesignPath,
|
||||
sidecarCandidates,
|
||||
projectRootPatterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
targetCandidates: workspaceCandidates,
|
||||
});
|
||||
|
||||
const findings = [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
...(ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({ designPath: absDesignPath, sidecarCandidates, projectRoot }),
|
||||
...bootFindings.product,
|
||||
...bootFindings.nativePlatform,
|
||||
...bootFindings.designSidecar,
|
||||
...checkDesignDrift({ designPath: absDesignPath, projectRoot }),
|
||||
...checkDesignCoverage({ design: ctx.design, designPath: ctx.designPath, parseDesignMd }),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...bootFindings.config,
|
||||
...bootFindings.buildPath,
|
||||
...checkDetectorIgnores({ projectRoot, knownRuleIds }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...bootFindings.surfaceBriefs,
|
||||
...checkHookInstallation({
|
||||
projectRoot,
|
||||
repoRoot: ctx.repoRoot,
|
||||
providerId: IMPECCABLE_PROVIDER_ID,
|
||||
}),
|
||||
...checkLegacyLiveState({ projectRoot }),
|
||||
...checkProjectRoots({
|
||||
patterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
candidates: workspaceCandidates,
|
||||
}),
|
||||
...bootFindings.projectRoots,
|
||||
...workspaceResult.findings,
|
||||
];
|
||||
|
||||
|
||||
@@ -75,11 +75,11 @@ const HOOK_MANIFEST_TARGETS = [
|
||||
destRel: '.claude/settings.local.json',
|
||||
sharedDestRel: '.claude/settings.json',
|
||||
manifest: () => ({
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.',
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.',
|
||||
hooks: {
|
||||
PostToolUse: [
|
||||
{
|
||||
matcher: 'Edit|Write|MultiEdit',
|
||||
matcher: 'Edit|Write',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
|
||||
@@ -816,9 +816,9 @@ export function splitFindingsByTier(findings) {
|
||||
}
|
||||
|
||||
// Whether the per-edit pass for this harness should defer non-immediate
|
||||
// findings to a Stop deep pass. Only Claude Code and Codex dispatch our Stop
|
||||
// hook; Cursor and GitHub Copilot have no deep pass wired, so deferring for
|
||||
// them would silently drop the non-immediate rules entirely.
|
||||
// findings to a Stop deep pass. Claude Code, Codex, and Grok Build dispatch
|
||||
// our Stop hook; Cursor and GitHub Copilot have no deep pass wired, so
|
||||
// deferring for them would silently drop the non-immediate rules entirely.
|
||||
export function perEditTieringActive(config, harness) {
|
||||
if (harness === 'cursor' || harness === 'github') return false;
|
||||
return (config?.perEditRules || DEFAULT_CONFIG.perEditRules) !== 'all';
|
||||
@@ -1251,9 +1251,14 @@ export function resolveHarness(env = {}, event = null) {
|
||||
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
|
||||
if (explicit === 'cursor') return 'cursor';
|
||||
if (explicit === 'github') return 'github';
|
||||
if (explicit === 'grok') return 'grok';
|
||||
if (explicit === 'claude' || explicit === 'codex') return 'claude';
|
||||
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
|
||||
// has no `tool_name`/`tool_input`. That shape is the discriminator.
|
||||
// Grok Build sends camelCase `toolName`/`toolInput`/`hookEventName` and no
|
||||
// snake_case pair. GitHub Copilot sends camelCase `toolName`/`toolArgs`.
|
||||
// Check Grok first: the old GitHub heuristic (`toolName` and no
|
||||
// `tool_input`) also matches Grok, which is how live PostToolUse was
|
||||
// classified as Copilot and then skipped with no-file-path (#646).
|
||||
if (looksLikeGrokEnvelope(event)) return 'grok';
|
||||
if (event && typeof event === 'object'
|
||||
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
|
||||
&& event.tool_name === undefined && event.tool_input === undefined) {
|
||||
@@ -1263,6 +1268,27 @@ export function resolveHarness(env = {}, event = null) {
|
||||
return 'claude';
|
||||
}
|
||||
|
||||
function looksLikeGrokEnvelope(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
if (event.hook_event_name !== undefined
|
||||
|| event.tool_name !== undefined
|
||||
|| event.tool_input !== undefined) {
|
||||
return false;
|
||||
}
|
||||
if (event.toolArgs !== undefined) return false;
|
||||
if (typeof event.hookEventName === 'string') return true;
|
||||
return typeof event.toolName === 'string' && event.toolInput !== undefined;
|
||||
}
|
||||
|
||||
// Stop arrives as Claude's `hook_event_name: "Stop"` or Grok Build's
|
||||
// `hookEventName: "stop"`. hook.mjs routes on the raw stdin, before any
|
||||
// normalize, so both casings must match here.
|
||||
export function isStopEvent(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const name = event.hook_event_name || event.hookEventName;
|
||||
return typeof name === 'string' && name.toLowerCase() === 'stop';
|
||||
}
|
||||
|
||||
// GitHub Copilot's postToolUse payload is
|
||||
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
|
||||
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
|
||||
@@ -1354,9 +1380,36 @@ function normalizeGitHubEvent(event, projectCwd) {
|
||||
};
|
||||
}
|
||||
|
||||
// Grok Build 1.0.5 (captured 2026-08-24) sends camelCase `toolName` /
|
||||
// `toolInput` / `sessionId` / `stopHookActive`, plus `cwd` alongside a
|
||||
// trailing-slashed `workspaceRoot` (every consumer path.resolve()s, so no
|
||||
// stripping here). Only the fields the hook reads are copied; the event
|
||||
// name stays camelCase because routing already happened on the raw stdin
|
||||
// (isStopEvent) and nothing downstream reads `hook_event_name`.
|
||||
function normalizeGrokEvent(event, projectCwd) {
|
||||
const cwd = event.cwd || event.workspaceRoot || envProjectDir(projectCwd) || projectCwd;
|
||||
const sessionId = event.sessionId || event.session_id || 'unknown';
|
||||
const rawInput = event.toolInput ?? event.tool_input;
|
||||
const toolInput = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
|
||||
? { ...rawInput }
|
||||
: {};
|
||||
const out = {
|
||||
...event,
|
||||
cwd,
|
||||
session_id: sessionId,
|
||||
tool_name: event.toolName || event.tool_name || null,
|
||||
tool_input: toolInput,
|
||||
};
|
||||
if (event.stopHookActive !== undefined && event.stop_hook_active === undefined) {
|
||||
out.stop_hook_active = event.stopHookActive;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
|
||||
if (!event || typeof event !== 'object') return event;
|
||||
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
|
||||
if (harness === 'grok') return normalizeGrokEvent(event, projectCwd);
|
||||
if (harness !== 'cursor') return event;
|
||||
|
||||
const cwd = event.cwd
|
||||
@@ -1959,7 +2012,15 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// findings stop being remembered and a reintroduced one reads as fresh.
|
||||
// Only the immediate tier is remembered: a deferred finding the per-edit
|
||||
// pass never reported must still read as fresh to the Stop deep pass.
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
//
|
||||
// Grok ignores PostToolUse stdout, so Stop is the user-visible pass.
|
||||
// Remembering here would dedupe those findings out of Stop. Touch the
|
||||
// file so Stop has it, and leave the finding list empty.
|
||||
if (harness === 'grok') {
|
||||
touchFile(cache, sessionId, filePath);
|
||||
} else {
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
}
|
||||
cacheDirty = true;
|
||||
|
||||
if (fresh.length > 0) {
|
||||
@@ -2191,22 +2252,32 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
event = normalizeHookEvent(event, cwd, harness);
|
||||
|
||||
// Claude Code's Stop-hook contract: `stop_hook_active` is true when this
|
||||
// hook is being re-invoked only because a prior invocation kept the turn
|
||||
// alive (here, via hookSpecificOutput.additionalContext). Re-scanning and
|
||||
// re-blocking now would loop until Claude Code's consecutive-block cap
|
||||
// force-ends the turn (issue #400). The prior fire already surfaced the
|
||||
// findings; whether to act on them is the agent's call. Exit fast with no
|
||||
// output before any scan. Only Claude Code sends this field; other
|
||||
// harnesses omit it, so the strict `=== true` is a no-op for them. This
|
||||
// guard makes the loop impossible regardless of the finding cache key's
|
||||
// line-number sensitivity (out of scope here; see findingCacheKey).
|
||||
// output before any scan. Claude sends `stop_hook_active`; Grok sends
|
||||
// `stopHookActive`, copied onto the snake_case field above. The strict
|
||||
// `=== true` is a no-op when the field is absent. This guard makes the
|
||||
// loop impossible regardless of the finding cache key's line-number
|
||||
// sensitivity (out of scope here; see findingCacheKey).
|
||||
if (event.stop_hook_active === true) {
|
||||
return result({ skipped: 'stop-hook-active', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
// Grok fires Stop twice: `end_turn` (the gate that can inject
|
||||
// additionalContext) then an observe-only `shutdown`. A second deep
|
||||
// pass would re-emit the same findings. Claude omits `reason`; only
|
||||
// skip when Grok named a reason that is not end_turn.
|
||||
if (harness === 'grok' && typeof event.reason === 'string' && event.reason !== 'end_turn') {
|
||||
return result({ skipped: 'stop-reason', reason: event.reason, durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
// A Stop event carries no file, so the session cwd is the project.
|
||||
// Umbrella-dir launches keyed their per-edit cache to the edited file's
|
||||
@@ -2241,6 +2312,7 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
|
||||
const freshGroups = [];
|
||||
let scanned = 0;
|
||||
let cacheDirty = false;
|
||||
for (const filePath of touched) {
|
||||
if (scanned >= STOP_MAX_FILES) break;
|
||||
if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) continue;
|
||||
@@ -2261,29 +2333,39 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
|
||||
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
const useHtmlEngine = configuredExt
|
||||
? configuredExt.engine === 'html'
|
||||
: (ext === '.html' || ext === '.htm');
|
||||
|
||||
if (useHtmlEngine && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
// A detector failure tells us nothing about the file. Leave whatever
|
||||
// was remembered alone rather than recording an empty scan as truth.
|
||||
if (detectorThrew) continue;
|
||||
|
||||
// Full rule set: no tier split here. Config/inline ignores still apply,
|
||||
// and the session dedupe drops everything the per-edit pass (or an
|
||||
// earlier Stop pass) already surfaced.
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
|
||||
// Sync to the live scan, including empty. Remembering only `fresh`
|
||||
// (or skipping the write on a clean Stop) left stale keys in place, so
|
||||
// a finding that was fixed and later reintroduced never fired again.
|
||||
rememberFindings(cache, sessionId, filePath, filtered);
|
||||
cacheDirty = true;
|
||||
if (fresh.length > 0) {
|
||||
rememberFindings(cache, sessionId, filePath, fresh);
|
||||
freshGroups.push({ filePath, findings: fresh });
|
||||
}
|
||||
}
|
||||
audit.scannedFiles = scanned;
|
||||
|
||||
if (freshGroups.length === 0) {
|
||||
if (cacheDirty) persistCache(projectCwd, cache);
|
||||
return result({ emitted: false, skipped: 'stop-clean', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
@@ -2300,8 +2382,8 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
);
|
||||
commitFooterShown(cache, sessionId, text);
|
||||
|
||||
// Fresh findings earn the cache write so the next Stop fire is silent
|
||||
// unless new issues appear; the notice flags ride along.
|
||||
// Persist the live finding set so the next Stop fire is silent unless
|
||||
// new issues appear; the notice flags ride along.
|
||||
persistCache(projectCwd, cache);
|
||||
return {
|
||||
exitCode: 0,
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
/**
|
||||
* Impeccable design hook — PostToolUse + Stop entry point.
|
||||
*
|
||||
* Reads the Claude Code / Codex / Cursor hook event from stdin and routes by
|
||||
* `hook_event_name`:
|
||||
* Reads the Claude Code / Codex / Cursor / Grok Build hook event from stdin
|
||||
* and routes by Stop vs everything else. Claude uses `hook_event_name:
|
||||
* "Stop"`; Grok uses `hookEventName: "stop"`.
|
||||
*
|
||||
* - PostToolUse: runs the immediate-tier detector rules against the touched
|
||||
* file and emits a system reminder via
|
||||
* `hookSpecificOutput.additionalContext` when findings exist.
|
||||
* `hookSpecificOutput.additionalContext` when findings exist. Grok
|
||||
* discards that stdout; the scan still warms the session cache for Stop.
|
||||
* - Stop: runs the FULL detector rule set over every UI file touched this
|
||||
* session (the deep pass), deduped against what the per-edit pass already
|
||||
* surfaced, and emits once via the Stop additionalContext channel.
|
||||
@@ -19,7 +21,7 @@
|
||||
* subprocess. This file is the thin stdin/stdout adapter.
|
||||
*/
|
||||
|
||||
import { runHook, runStopHook, writeAuditLog } from './hook-lib.mjs';
|
||||
import { runHook, runStopHook, writeAuditLog, isStopEvent } from './hook-lib.mjs';
|
||||
|
||||
async function readStdin() {
|
||||
if (process.stdin.isTTY) return '';
|
||||
@@ -28,10 +30,9 @@ async function readStdin() {
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
function isStopEvent(stdinJson) {
|
||||
function stdinIsStop(stdinJson) {
|
||||
try {
|
||||
const event = JSON.parse(stdinJson);
|
||||
return event && typeof event === 'object' && event.hook_event_name === 'Stop';
|
||||
return isStopEvent(JSON.parse(stdinJson));
|
||||
} catch {
|
||||
// Malformed stdin falls through to runHook, which audits the skip.
|
||||
return false;
|
||||
@@ -48,7 +49,7 @@ async function main() {
|
||||
let stdinJson = '';
|
||||
try { stdinJson = await readStdin(); } catch { /* fall through */ }
|
||||
|
||||
const run = isStopEvent(stdinJson) ? runStopHook : runHook;
|
||||
const run = stdinIsStop(stdinJson) ? runStopHook : runHook;
|
||||
const result = await run({
|
||||
stdinJson,
|
||||
env: inheritedEnv,
|
||||
|
||||
@@ -196,9 +196,6 @@ function parseScalar(raw) {
|
||||
|
||||
const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
|
||||
const OKLCH_RE = /oklch\([^)]+\)/gi;
|
||||
const RGBA_RE = /rgba?\([^)]+\)/gi;
|
||||
const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
|
||||
const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
|
||||
|
||||
// ---------- Section splitting ----------
|
||||
|
||||
@@ -550,36 +547,6 @@ function detectFormat(v) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function scanInlineColors(lines) {
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '');
|
||||
const color = parseColorBullet(trimmed);
|
||||
if (color) out.push(color);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseStitchInlineGroups(lines) {
|
||||
// Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
|
||||
// Each bullet IS its own role. Group them under the spoken role name.
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
|
||||
const m = trimmed.match(
|
||||
/^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
|
||||
);
|
||||
if (m) {
|
||||
const role = m[1];
|
||||
const color = buildColor(role, m[2], m[3]);
|
||||
out.push({ role, colors: [color] });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractTypography(section) {
|
||||
if (!section) return null;
|
||||
const text = section.lines.join('\n');
|
||||
|
||||
@@ -488,41 +488,46 @@ export function describeWorkspaceContext(candidates = []) {
|
||||
// ─── Tier 1 orchestration ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Everything a boot can afford. `ctx` is the loadContext result; `extras`
|
||||
* carries values the caller already computed so nothing is recomputed here.
|
||||
* Everything a boot can afford, grouped by artifact so deeper reports can
|
||||
* interleave their own checks without rebuilding this policy. `ctx` is the
|
||||
* loadContext result; `extras` carries values the caller already computed so
|
||||
* nothing is recomputed here.
|
||||
*/
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
if (!ctx) return [];
|
||||
export function collectBootFindingGroups(ctx, extras = {}) {
|
||||
if (!ctx) return {};
|
||||
const projectRoot = ctx.projectRoot || process.cwd();
|
||||
const absProductPath = extras.absProductPath || null;
|
||||
const absDesignPath = extras.absDesignPath || null;
|
||||
|
||||
return [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
return {
|
||||
product: checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
// Only checked once a PRODUCT.md exists. Without one the boot already
|
||||
// emits NO_PRODUCT_MD and routes into init, which asks for the platform
|
||||
// directly; a second signal saying the same thing is noise.
|
||||
...(ctx.product
|
||||
nativePlatform: ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({
|
||||
: [],
|
||||
designSidecar: checkDesignSidecar({
|
||||
designPath: absDesignPath,
|
||||
sidecarCandidates: extras.sidecarCandidates || [],
|
||||
projectRoot,
|
||||
}),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...(extras.projectRootPatterns
|
||||
config: checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
buildPath: checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
surfaceBriefs: checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
projectRoots: extras.projectRootPatterns
|
||||
? checkProjectRoots({
|
||||
patterns: extras.projectRootPatterns,
|
||||
candidates: extras.targetCandidates || [],
|
||||
})
|
||||
: []),
|
||||
];
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function collectBootFindings(ctx, extras = {}) {
|
||||
return Object.values(collectBootFindingGroups(ctx, extras)).flat();
|
||||
}
|
||||
|
||||
@@ -4902,6 +4902,13 @@
|
||||
saveSession();
|
||||
}
|
||||
|
||||
function completeParameterGenerationIfReady() {
|
||||
if (expectedVariants <= 0 || arrivedVariants < expectedVariants) return;
|
||||
if (parameterGenerationState === 'pending' || parameterGenerationState === 'loading') {
|
||||
completeParameterPublication();
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTunePopover() {
|
||||
if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }
|
||||
if (tuneOpen) { closeTunePopover(); return; }
|
||||
@@ -5796,7 +5803,7 @@
|
||||
setLiveState('CYCLING');
|
||||
showOrUpdateCyclingBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5884,7 +5891,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');
|
||||
} catch (err) {
|
||||
console.error('[impeccable] Failed to mount component-preview variants:', err);
|
||||
@@ -6329,7 +6336,7 @@
|
||||
refreshParamsPanel();
|
||||
positionBar();
|
||||
saveSession();
|
||||
if (parameterGenerationState === 'loading') completeParameterPublication();
|
||||
completeParameterGenerationIfReady();
|
||||
console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
|
||||
})
|
||||
.catch(err => {
|
||||
@@ -6836,6 +6843,7 @@
|
||||
|
||||
const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
|
||||
if (expected > 0) expectedVariants = expected;
|
||||
completeParameterGenerationIfReady();
|
||||
|
||||
if (arrivedVariants > 0) {
|
||||
setLiveState('CYCLING');
|
||||
|
||||
@@ -944,8 +944,42 @@ export async function commitManualEdits({
|
||||
};
|
||||
}
|
||||
|
||||
const repairContext = {
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
};
|
||||
|
||||
const baseRollbackScope = collectApplyOwnedFiles(batch, cwd);
|
||||
const rollbackSnapshot = snapshotRollbackFiles(cwd, baseRollbackScope);
|
||||
const failWithRollback = ({
|
||||
scope = baseRollbackScope,
|
||||
extraFiles = [],
|
||||
failed,
|
||||
files = [],
|
||||
details = {},
|
||||
}) => {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, extraFiles, scope);
|
||||
return {
|
||||
applied: [],
|
||||
failed,
|
||||
files,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
...details,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
result = repairOnly
|
||||
@@ -965,42 +999,27 @@ export async function commitManualEdits({
|
||||
chatAvailable,
|
||||
});
|
||||
} catch (err) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, [], baseRollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
failed: batch.entries.map((entry) => ({
|
||||
id: entry.id,
|
||||
reason: err.message || String(err),
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
})),
|
||||
files: [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'error') {
|
||||
const rollbackScope = collectApplyOwnedFiles(batch, cwd, result.files || []);
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const failed = normalizeFailedEntries(batch, result, result.message || 'AI copy edit failed');
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: failed.length > 0
|
||||
? failed
|
||||
: verificationFailuresForEntries(batch, batch.entries, result.message || 'AI copy edit failed'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedIds = uniqueStrings(result.appliedEntryIds || []);
|
||||
@@ -1013,72 +1032,44 @@ export async function commitManualEdits({
|
||||
const conflictingAppliedIds = reportedAppliedIds.filter((id) => failedIds.has(id));
|
||||
|
||||
if (conflictingAppliedIds.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
const conflictingEntries = batch.entries.filter((entry) => conflictingAppliedIds.includes(entry.id));
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...verificationFailuresForEntries(batch, conflictingEntries, 'conflicting_apply_result'),
|
||||
...aiFailed.filter((item) => !conflictingAppliedIds.includes(item.id)),
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const unreportedFiles = unreportedChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
if (unreportedFiles.length > 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], [...rollbackScope, ...unreportedFiles]);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: [...rollbackScope, ...unreportedFiles],
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'unreported_source_changes', { files: unreportedFiles }),
|
||||
files: result.files || [],
|
||||
unreportedFiles,
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { unreportedFiles, notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status === 'done' && reportedAppliedIds.length === 0) {
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: verificationFailuresForEntries(batch, batch.entries, 'missing_applied_entry_ids'),
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
notes: result.notes || [],
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
const reportedAppliedEntries = batch.entries.filter((entry) => reportedAppliedIds.includes(entry.id));
|
||||
if (reportedAppliedIds.length > 0 && reportedFiles.length === 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: aiFailed,
|
||||
@@ -1089,21 +1080,10 @@ export async function commitManualEdits({
|
||||
});
|
||||
}
|
||||
|
||||
const verifiedAppliedIds = [];
|
||||
const verificationFailed = [];
|
||||
for (const entry of reportedAppliedEntries) {
|
||||
const failures = verifyAppliedEntry({ batch, entry, reportedFiles, cwd });
|
||||
if (failures.length === 0) {
|
||||
verifiedAppliedIds.push(entry.id);
|
||||
} else {
|
||||
verificationFailed.push({
|
||||
id: entry.id,
|
||||
reason: 'source_verification_failed',
|
||||
failures,
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
const {
|
||||
verifiedIds: verifiedAppliedIds,
|
||||
failed: verificationFailed,
|
||||
} = verifyEntriesAfterRepair({ batch, appliedEntryIds: reportedAppliedIds, files: reportedFiles, cwd });
|
||||
const unreportedEntries = result.status === 'done' || result.status === 'partial'
|
||||
? batch.entries.filter((entry) => !reportedAppliedIds.includes(entry.id) && !aiFailed.some((item) => item.id === entry.id))
|
||||
: [];
|
||||
@@ -1133,37 +1113,22 @@ export async function commitManualEdits({
|
||||
reason: 'rolled_back_due_to_failed_entry_source_changed',
|
||||
candidates: candidatesForEntry(batch, entry.id),
|
||||
}));
|
||||
const rollback = rollbackChangedFiles(cwd, rollbackSnapshot, result.files || [], rollbackScope);
|
||||
return {
|
||||
applied: [],
|
||||
return failWithRollback({
|
||||
scope: rollbackScope,
|
||||
extraFiles: result.files || [],
|
||||
failed: [
|
||||
...leakedUnapplied,
|
||||
...failed.filter((item) => !leakedIds.has(item.id)),
|
||||
...rolledBackVerified,
|
||||
],
|
||||
files: result.files || [],
|
||||
cleared: 0,
|
||||
count,
|
||||
pageUrl,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
notes: result.notes || [],
|
||||
...countByPage(cwd),
|
||||
};
|
||||
details: { notes: result.notes || [] },
|
||||
});
|
||||
}
|
||||
|
||||
if (verificationFailed.length > 0) {
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: reportedAppliedIds,
|
||||
files: result.files || [],
|
||||
failed: nonRepairFailed,
|
||||
@@ -1180,16 +1145,7 @@ export async function commitManualEdits({
|
||||
? reportedAppliedEntries.filter((entry) => verifiedAppliedIds.includes(entry.id))
|
||||
: batch.entries;
|
||||
return repairPostApplyValidation({
|
||||
batch,
|
||||
cwd,
|
||||
pageUrl,
|
||||
count,
|
||||
provider,
|
||||
env,
|
||||
timeoutMs,
|
||||
applyBatchToSource,
|
||||
chatAvailable,
|
||||
transactionId,
|
||||
...repairContext,
|
||||
appliedEntryIds: verifiedAppliedIds.length > 0
|
||||
? verifiedAppliedIds
|
||||
: postCheckEntries.map((entry) => entry.id).filter(Boolean),
|
||||
|
||||
@@ -238,10 +238,9 @@ export async function completeAcceptHandling(event, base, token) {
|
||||
});
|
||||
} catch (err) {
|
||||
event._completionAck = { ok: false, error: err.message };
|
||||
return event;
|
||||
}
|
||||
if (!event._completionAck) {
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
}
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -269,9 +268,11 @@ export function printPollEvent(event) {
|
||||
// Situational plumbing rides with the event itself: `_instructions` is the
|
||||
// authoritative next step, with real ids and paths substituted, so the
|
||||
// reference doc can stay lean and can never drift from script behavior.
|
||||
if (event && typeof event === 'object' && !event._instructions) {
|
||||
// A wire-supplied value must never win over the locally generated one.
|
||||
if (event && typeof event === 'object') {
|
||||
const instructions = instructionsForEvent(event, { scriptsPath: SELF_DIR });
|
||||
if (instructions) event._instructions = instructions;
|
||||
else delete event._instructions;
|
||||
}
|
||||
console.log(JSON.stringify(event));
|
||||
}
|
||||
|
||||
@@ -181,8 +181,16 @@ function chatAgentLikelyActive() {
|
||||
// cap at 10 MB to guard against runaway writes from a misbehaving client.
|
||||
const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
const POLLER_OWNED_EVENT_FIELDS = ['_instructions', '_completionAck', '_acceptResult'];
|
||||
|
||||
function stripPollerOwnedEventFields(event) {
|
||||
if (!event || typeof event !== 'object') return;
|
||||
for (const key of POLLER_OWNED_EVENT_FIELDS) delete event[key];
|
||||
}
|
||||
|
||||
function enqueueEvent(event) {
|
||||
if (!event) return;
|
||||
stripPollerOwnedEventFields(event);
|
||||
// Dedupe by (session, type), except mount failures, which are per-variant:
|
||||
// variant 2 failing must not be swallowed because variant 1's failure is
|
||||
// still queued.
|
||||
@@ -936,15 +944,23 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
const filePath = url.searchParams.get('path');
|
||||
if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
|
||||
const absPath = path.resolve(process.cwd(), filePath);
|
||||
// Confine to the project root. A bare `startsWith(cwd)` string check lets a
|
||||
// sibling dir whose name extends the root name (projeto -> projeto-backup)
|
||||
// slip through; compare on the relative path instead (same pattern as
|
||||
// sessionFileMetadataFromPollReply below). An empty rel means the request
|
||||
// resolved to the root directory itself, which this file route never serves.
|
||||
const rel = path.relative(process.cwd(), absPath);
|
||||
let realRoot, realTarget;
|
||||
try {
|
||||
realRoot = fs.realpathSync(process.cwd());
|
||||
realTarget = fs.realpathSync(absPath);
|
||||
} catch {
|
||||
res.writeHead(404); res.end('File not found'); return;
|
||||
}
|
||||
// Confine to the project root after symlink resolution. A bare
|
||||
// `startsWith(cwd)` string check lets a sibling dir whose name extends the
|
||||
// root name (projeto -> projeto-backup) slip through; compare on the
|
||||
// relative path instead (same pattern as sessionFileMetadataFromPollReply
|
||||
// below). An empty rel means the request resolved to the root directory
|
||||
// itself, which this file route never serves.
|
||||
const rel = path.relative(realRoot, realTarget);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { res.writeHead(403); res.end('Forbidden'); return; }
|
||||
let content;
|
||||
try { content = fs.readFileSync(absPath, 'utf-8'); }
|
||||
try { content = fs.readFileSync(realTarget, 'utf-8'); }
|
||||
catch { res.writeHead(404); res.end('File not found'); return; }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(content);
|
||||
@@ -1026,6 +1042,7 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
res.end(JSON.stringify({ error }));
|
||||
return;
|
||||
}
|
||||
stripPollerOwnedEventFields(msg);
|
||||
if (msg.type === 'agent_phase') {
|
||||
recordAgentPhase(msg.id, msg.phase, {
|
||||
...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),
|
||||
|
||||
@@ -11,6 +11,8 @@ import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
|
||||
export const SVELTE_LIVE_ROOT_COMPONENT = 'src/lib/impeccable/ImpeccableLiveRoot.svelte';
|
||||
export const SVELTE_LAYOUT_MARKER_OPEN = '<!-- impeccable-live-svelte-start -->';
|
||||
export const SVELTE_LAYOUT_MARKER_CLOSE = '<!-- impeccable-live-svelte-end -->';
|
||||
@@ -45,11 +47,17 @@ export function detectSvelteKitProject(cwd = process.cwd(), config = null) {
|
||||
&& fileIncludes(path.join(cwd, appHtml), '%sveltekit.head%');
|
||||
if (!hasTemplateMarkers) return null;
|
||||
|
||||
const hasSvelteConfig = fs.existsSync(path.join(cwd, 'svelte.config.js'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.mjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.cjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.ts'));
|
||||
const hasKitPackage = packageHasSvelteKit(cwd);
|
||||
const hasSvelteConfig = Boolean(firstExistingFile(cwd, [
|
||||
'svelte.config.js',
|
||||
'svelte.config.mjs',
|
||||
'svelte.config.cjs',
|
||||
'svelte.config.ts',
|
||||
]));
|
||||
const hasKitPackage = hasAnyDependency(cwd, [
|
||||
'@sveltejs/kit',
|
||||
'@sveltejs/vite-plugin-svelte',
|
||||
'svelte',
|
||||
]);
|
||||
if (!hasSvelteConfig && !hasKitPackage) return null;
|
||||
|
||||
return {
|
||||
@@ -260,36 +268,16 @@ function findSvelteKitAppHtml(cwd, config) {
|
||||
}
|
||||
|
||||
function findSvelteKitLayout(cwd) {
|
||||
const candidates = [
|
||||
return firstExistingFile(cwd, [
|
||||
'src/routes/+layout.svelte',
|
||||
'src/routes/(app)/+layout.svelte',
|
||||
];
|
||||
for (const rel of candidates) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return 'src/routes/+layout.svelte';
|
||||
]) || 'src/routes/+layout.svelte';
|
||||
}
|
||||
|
||||
function defaultSvelteLayout() {
|
||||
return `<script>\n let { children } = $props();\n</script>\n\n{@render children?.()}\n`;
|
||||
}
|
||||
|
||||
function packageHasSvelteKit(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fileIncludes(file, text) {
|
||||
try {
|
||||
return fs.readFileSync(file, 'utf-8').includes(text);
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { firstExistingFile, hasAnyDependency } from './frameworks/detect-utils.mjs';
|
||||
import { buildLiveScriptSrc } from './frameworks/script-src.mjs';
|
||||
|
||||
export const TANSTACK_MARKER_OPEN = '{/* impeccable-live-tanstack-start */}';
|
||||
@@ -42,8 +44,8 @@ const START_PACKAGES = [
|
||||
];
|
||||
|
||||
export function detectTanStackStartProject(cwd = process.cwd()) {
|
||||
if (!packageHasTanStackStart(cwd)) return null;
|
||||
const rootRoute = findRootRouteFile(cwd);
|
||||
if (!hasAnyDependency(cwd, START_PACKAGES)) return null;
|
||||
const rootRoute = firstExistingFile(cwd, ROOT_ROUTE_CANDIDATES);
|
||||
if (!rootRoute) return null;
|
||||
|
||||
const ext = path.extname(rootRoute);
|
||||
@@ -218,29 +220,6 @@ function isManagedComponent(content) {
|
||||
return String(content || '').includes('impeccable-live-tanstack');
|
||||
}
|
||||
|
||||
function findRootRouteFile(cwd) {
|
||||
for (const rel of ROOT_ROUTE_CANDIDATES) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function packageHasTanStackStart(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return START_PACKAGES.some((name) => Boolean(deps[name]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function relativeImportSpecifier(fromFile, toFile) {
|
||||
const rel = path.posix.relative(
|
||||
path.posix.dirname(fromFile.split(path.sep).join('/')),
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Manage the **design detector hook** for the current project.
|
||||
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
|
||||
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. Grok Build fires the same PostToolUse scan to mark touched files, then surfaces findings on Stop `additionalContext`. Do not expect a Grok per-edit reminder: Grok discards that stdout.
|
||||
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code and Codex, which both dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit.
|
||||
The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code, Codex, and Grok Build, which dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. Grok also fires an observe-only Stop with `reason: "shutdown"` after `end_turn`; skip that one, scan only `end_turn`.
|
||||
|
||||
Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `context.mjs` asking for a single detector run at the end.
|
||||
|
||||
@@ -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), 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` 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -44,7 +44,7 @@ The first argument is the action. Defaults to `status`.
|
||||
```
|
||||
|
||||
3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
|
||||
4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write on a UI file."
|
||||
5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/config.json`; add `--local` only when the user explicitly asks for a private exception.
|
||||
6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
|
||||
|
||||
|
||||
@@ -626,7 +626,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -688,7 +688,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -985,7 +985,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -1115,7 +1115,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -773,14 +773,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
@@ -1955,20 +1963,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -1985,13 +1992,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -3986,7 +3990,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
@@ -7281,7 +7285,7 @@ if (IS_BROWSER) {
|
||||
if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
|
||||
if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
|
||||
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor);
|
||||
const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
|
||||
if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
|
||||
current = current.parentElement;
|
||||
}
|
||||
@@ -7343,7 +7347,7 @@ if (IS_BROWSER) {
|
||||
// starve the url()-backed texts this mode exists to sample.
|
||||
if (options.imageOnly && !reasons.includes('image background')) continue;
|
||||
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
const fontSize = parseFloat(style.fontSize) || 16;
|
||||
const fontWeight = parseInt(style.fontWeight) || 400;
|
||||
const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
|
||||
@@ -7640,7 +7644,7 @@ if (IS_BROWSER) {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
const bg = parseRgb(style.backgroundColor);
|
||||
const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
|
||||
if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
|
||||
return { status: 'unresolved', reason: 'no readable background' };
|
||||
}
|
||||
@@ -7770,7 +7774,7 @@ if (IS_BROWSER) {
|
||||
}
|
||||
|
||||
const style = getComputedStyle(el);
|
||||
const textColor = parseRgb(style.color) || candidate.textColor;
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
|
||||
if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
|
||||
|
||||
const rect = getDirectTextRect(el) || el.getBoundingClientRect();
|
||||
|
||||
@@ -42,6 +42,7 @@ function shouldRunPageAnalyzers(content, filePath) {
|
||||
}
|
||||
|
||||
const JS_SOURCE_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']);
|
||||
const STYLESHEET_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
const REGEX_PREFIX_KEYWORDS = new Set(['await', 'case', 'default', 'delete', 'do', 'else', 'in', 'instanceof', 'new', 'of', 'return', 'throw', 'typeof', 'void', 'yield']);
|
||||
const BLOCK_BRACE_PREFIX_KEYWORDS = new Set(['do', 'else', 'finally', 'try']);
|
||||
|
||||
@@ -256,6 +257,153 @@ function stripCssComments(content) {
|
||||
return content.replace(/\/\*[\s\S]*?\*\//g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankHtmlComments(text) {
|
||||
return text.replace(/<!--[\s\S]*?-->/g, comment => comment.replace(/[^\n]/g, ' '));
|
||||
}
|
||||
|
||||
function blankCssLineCommentsInStyleBlocks(text) {
|
||||
const re = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
const inner = match[1];
|
||||
const openLength = match[0].length - inner.length - '</style>'.length;
|
||||
output += text.slice(lastIndex, match.index);
|
||||
output += match[0].slice(0, openLength);
|
||||
output += blankCssLineComments(inner);
|
||||
output += match[0].slice(openLength + inner.length);
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + text.slice(lastIndex);
|
||||
}
|
||||
|
||||
function blankHtmlAndCssCommentsOutsideScripts(text) {
|
||||
const re = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
|
||||
let output = '';
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
output += blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex, match.index))));
|
||||
output += match[0];
|
||||
lastIndex = re.lastIndex;
|
||||
}
|
||||
return output + blankCssLineCommentsInStyleBlocks(stripCssComments(blankHtmlComments(text.slice(lastIndex))));
|
||||
}
|
||||
|
||||
function blankCssLineComments(text) {
|
||||
let output = '';
|
||||
let state = 'code';
|
||||
let urlDepth = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
const next = text[i + 1];
|
||||
if (state === 'line') {
|
||||
if (char === '\n') {
|
||||
output += '\n';
|
||||
state = 'code';
|
||||
} else {
|
||||
output += ' ';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state === 'single' || state === 'double') {
|
||||
output += char;
|
||||
if (char === '\\' && next) {
|
||||
output += next;
|
||||
i++;
|
||||
} else if ((state === 'single' && char === "'") || (state === 'double' && char === '"')) {
|
||||
state = 'code';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const prev = output.length ? output[output.length - 1] : '';
|
||||
if (char === '/' && next === '/' && urlDepth === 0 && prev !== ':' && prev !== '(' && prev !== '\\') {
|
||||
output += ' ';
|
||||
i++;
|
||||
state = 'line';
|
||||
continue;
|
||||
}
|
||||
if (char === "'") state = 'single';
|
||||
else if (char === '"') state = 'double';
|
||||
if (char === '(') {
|
||||
const behind = output.replace(/\s+$/, '');
|
||||
if (urlDepth > 0 || /url$/i.test(behind)) urlDepth++;
|
||||
} else if (char === ')' && urlDepth) {
|
||||
urlDepth--;
|
||||
}
|
||||
output += char;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function findAstroFrontmatterClose(text) {
|
||||
if (!text.startsWith('---')) return -1;
|
||||
let cursor = text.indexOf('\n');
|
||||
if (cursor === -1) return -1;
|
||||
cursor += 1;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor - 1] === '\n' && text.startsWith('---', cursor)) {
|
||||
let end = cursor + 3;
|
||||
while (text[end] === ' ' || text[end] === '\t') end++;
|
||||
if (end >= text.length || text[end] === '\n' || text[end] === '\r') return cursor - 1;
|
||||
}
|
||||
const char = text[cursor];
|
||||
const next = text[cursor + 1];
|
||||
if (char === "'" || char === '"') {
|
||||
const close = findQuotedStringEnd(text, cursor, char);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '`') {
|
||||
const close = findTemplateLiteralEnd(text, cursor);
|
||||
if (close === -1) return -1;
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '/') {
|
||||
const lineEnd = text.indexOf('\n', cursor);
|
||||
if (lineEnd === -1) return -1;
|
||||
cursor = lineEnd;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next === '*') {
|
||||
const commentEnd = text.indexOf('*/', cursor + 2);
|
||||
if (commentEnd === -1) return -1;
|
||||
cursor = commentEnd + 2;
|
||||
continue;
|
||||
}
|
||||
if (char === '/' && next !== '/' && next !== '*') {
|
||||
const close = findRegexLiteralEnd(text, cursor);
|
||||
if (close !== -1) {
|
||||
cursor = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cursor++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function blankAstroFrontmatterComments(text) {
|
||||
const close = findAstroFrontmatterClose(text);
|
||||
if (close === -1) return text;
|
||||
return stripJsComments(text.slice(0, close)) + text.slice(close);
|
||||
}
|
||||
|
||||
function blankCommentsForMatchers(text, ext) {
|
||||
if (PAGE_ANALYZER_EXTS.has(ext)) {
|
||||
const withFrontmatter = ext === '.astro' ? blankAstroFrontmatterComments(text) : text;
|
||||
return blankHtmlAndCssCommentsOutsideScripts(withFrontmatter);
|
||||
}
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
const withoutBlocks = stripCssComments(text);
|
||||
return ext === '.css' ? withoutBlocks : blankCssLineComments(withoutBlocks);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function firstOverusedGoogleFont(text) {
|
||||
return extractGoogleFontFamilies(text).find(f => OVERUSED_FONTS.has(f)) || '';
|
||||
}
|
||||
@@ -1028,14 +1176,13 @@ function detectText(content, filePath, options = {}) {
|
||||
const ext = extFromFilePath(filePath);
|
||||
const commentStrippedSource = JS_SOURCE_EXTS.has(ext) ? stripJsComments(content, {
|
||||
jsx: ext === '.js' || ext === '.jsx' || ext === '.tsx',
|
||||
}) : content;
|
||||
}) : blankCommentsForMatchers(content, ext);
|
||||
const source = stripCssInJsComments(commentStrippedSource, ext);
|
||||
const lines = source.split('\n');
|
||||
|
||||
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
|
||||
// Enable block context for CSS files where related properties span multiple lines
|
||||
const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
|
||||
findings.push(...runRegexMatchers(lines, filePath, 0, STYLESHEET_EXTS.has(ext) || null, {
|
||||
profile,
|
||||
phase: 'source',
|
||||
}));
|
||||
@@ -1050,7 +1197,7 @@ function detectText(content, filePath, options = {}) {
|
||||
scanCssTextForPseudoStripe(text).map(hit =>
|
||||
finding(hit.id, filePath, hit.snippet, lineOffset + text.slice(0, hit.index).split('\n').length));
|
||||
|
||||
if (cssLike.has(ext)) {
|
||||
if (STYLESHEET_EXTS.has(ext)) {
|
||||
findings.push(...scanInsetStripeCss(content, filePath));
|
||||
findings.push(...pseudoStripeFindings(content, 0));
|
||||
}
|
||||
@@ -1078,7 +1225,8 @@ function detectText(content, filePath, options = {}) {
|
||||
}, () => extractStyleBlocks(content, ext))
|
||||
: extractStyleBlocks(content, ext);
|
||||
for (const block of styleBlocks) {
|
||||
const blockLines = block.content.split('\n');
|
||||
const blockContent = blankCssLineComments(stripCssComments(block.content));
|
||||
const blockLines = blockContent.split('\n');
|
||||
findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
|
||||
profile,
|
||||
phase: 'style-block',
|
||||
@@ -1089,8 +1237,8 @@ function detectText(content, filePath, options = {}) {
|
||||
// 1-based, so the offset is startLine - 2; startLine - 1 double-counted and
|
||||
// reported every selector one line low. runRegexMatchers keeps startLine - 1
|
||||
// because it indexes its split lines from zero.
|
||||
findings.push(...scanInsetStripeCss(block.content, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(block.content, block.startLine - 2));
|
||||
findings.push(...scanInsetStripeCss(blockContent, filePath, block.startLine - 2));
|
||||
findings.push(...pseudoStripeFindings(blockContent, block.startLine - 2));
|
||||
}
|
||||
|
||||
// Extract and scan CSS-in-JS template literals
|
||||
|
||||
@@ -721,20 +721,19 @@ function scanCssTextForGlow(content) {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Decorative grid or line-field backgrounds drawn with hairline
|
||||
// Decorative two-axis grid backgrounds drawn with hairline
|
||||
// linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
|
||||
// pattern pass and the regex source engine so standalone CSS, component
|
||||
// styles, and inline styles receive the same coverage. Both signals must
|
||||
// co-occur in one declaration block; unrelated rules must not add up across
|
||||
// the file. Returns [{ index, snippet }], capped at one finding per source to
|
||||
// match the page-level HTML check's existing behavior.
|
||||
// the file. A single hairline is a line, divider, or rail, not a grid, even
|
||||
// when tiled by a 2D px cell. Returns [{ index, snippet }], capped at one
|
||||
// finding per source to match the page-level HTML check's existing behavior.
|
||||
function scanCssTextForGridBackground(content) {
|
||||
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
|
||||
const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
|
||||
const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
|
||||
const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
|
||||
const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
|
||||
const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
|
||||
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
|
||||
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
|
||||
let blk;
|
||||
@@ -751,13 +750,10 @@ function scanCssTextForGridBackground(content) {
|
||||
}
|
||||
if (hairlineCount === 0) continue;
|
||||
const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
|
||||
const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
|
||||
if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
|
||||
if (hairlineCount >= 2 && hasPxCell) {
|
||||
return [{
|
||||
index: blk.index,
|
||||
snippet: hairlineCount >= 2
|
||||
? 'two-axis grid-line gradient background'
|
||||
: 'px-tiled hairline line-field background',
|
||||
snippet: 'two-axis grid-line gradient background',
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -2752,7 +2748,7 @@ function checkElementAIPaletteDOM(el) {
|
||||
}
|
||||
|
||||
// Check for neon text (vivid cyan/purple color on dark background)
|
||||
const textColor = parseRgb(style.color);
|
||||
const textColor = parseRgb(style.color) || parseAnyColor(style.color);
|
||||
if (textColor && hasChroma(textColor, 80)) {
|
||||
const hue = getHue(textColor);
|
||||
const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
|
||||
|
||||
@@ -103,14 +103,22 @@ function extractColorFunctionTokens(value) {
|
||||
function parseGradientColors(bgImage) {
|
||||
if (!bgImage || !bgImage.includes('gradient')) return [];
|
||||
const colors = [];
|
||||
const tokenSpans = [];
|
||||
let from = 0;
|
||||
// Stops arrive in whatever syntax the author wrote and the browser kept.
|
||||
// A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
|
||||
// to read as a gradient with no stops at all.
|
||||
for (const token of extractColorFunctionTokens(bgImage)) {
|
||||
const start = bgImage.indexOf(token, from);
|
||||
if (start < 0) break;
|
||||
tokenSpans.push({ start, end: start + token.length });
|
||||
from = start + token.length;
|
||||
const c = parseAnyColor(token);
|
||||
if (c) colors.push(c);
|
||||
}
|
||||
for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
|
||||
// Nested hex inside color-mix is an ingredient, not a stop (issue #578).
|
||||
if (tokenSpans.some(s => m.index >= s.start && m.index < s.end)) continue;
|
||||
const h = m[1];
|
||||
if (h.length === 6) {
|
||||
colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
|
||||
|
||||
@@ -33,13 +33,8 @@ import {
|
||||
stampProductSchema,
|
||||
} from './lib/artifact-schema.mjs';
|
||||
import {
|
||||
checkBuildPathUnset,
|
||||
checkConfig,
|
||||
checkDesignSidecar,
|
||||
collectBootFindingGroups,
|
||||
checkNativePlatformEvidence,
|
||||
checkProduct,
|
||||
checkProjectRoots,
|
||||
checkSurfaceBriefs,
|
||||
designSidecarCandidatesFor,
|
||||
} from './lib/staleness.mjs';
|
||||
import {
|
||||
@@ -106,34 +101,30 @@ async function collect(cwd, targetOptions) {
|
||||
extractPlatform,
|
||||
readFile: safeRead,
|
||||
});
|
||||
const bootFindings = collectBootFindingGroups(ctx, {
|
||||
absDesignPath,
|
||||
sidecarCandidates,
|
||||
projectRootPatterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
targetCandidates: workspaceCandidates,
|
||||
});
|
||||
|
||||
const findings = [
|
||||
...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
|
||||
...(ctx.product
|
||||
? checkNativePlatformEvidence({
|
||||
projectRoot,
|
||||
platform: ctx.platform,
|
||||
product: ctx.product,
|
||||
productPath: ctx.productPath,
|
||||
})
|
||||
: []),
|
||||
...checkDesignSidecar({ designPath: absDesignPath, sidecarCandidates, projectRoot }),
|
||||
...bootFindings.product,
|
||||
...bootFindings.nativePlatform,
|
||||
...bootFindings.designSidecar,
|
||||
...checkDesignDrift({ designPath: absDesignPath, projectRoot }),
|
||||
...checkDesignCoverage({ design: ctx.design, designPath: ctx.designPath, parseDesignMd }),
|
||||
...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
|
||||
...checkBuildPathUnset({ projectRoot, repoRoot: ctx.repoRoot, product: ctx.product }),
|
||||
...bootFindings.config,
|
||||
...bootFindings.buildPath,
|
||||
...checkDetectorIgnores({ projectRoot, knownRuleIds }),
|
||||
...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
|
||||
...bootFindings.surfaceBriefs,
|
||||
...checkHookInstallation({
|
||||
projectRoot,
|
||||
repoRoot: ctx.repoRoot,
|
||||
providerId: IMPECCABLE_PROVIDER_ID,
|
||||
}),
|
||||
...checkLegacyLiveState({ projectRoot }),
|
||||
...checkProjectRoots({
|
||||
patterns: readProjectRootPatterns(ctx.repoRoot),
|
||||
candidates: workspaceCandidates,
|
||||
}),
|
||||
...bootFindings.projectRoots,
|
||||
...workspaceResult.findings,
|
||||
];
|
||||
|
||||
|
||||
@@ -75,11 +75,11 @@ const HOOK_MANIFEST_TARGETS = [
|
||||
destRel: '.claude/settings.local.json',
|
||||
sharedDestRel: '.claude/settings.json',
|
||||
manifest: () => ({
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write/MultiEdit on UI files, full-rule deep pass on Stop.',
|
||||
description: 'Impeccable design detector: immediate-tier checks after Edit/Write on UI files, full-rule deep pass on Stop.',
|
||||
hooks: {
|
||||
PostToolUse: [
|
||||
{
|
||||
matcher: 'Edit|Write|MultiEdit',
|
||||
matcher: 'Edit|Write',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
|
||||
@@ -816,9 +816,9 @@ export function splitFindingsByTier(findings) {
|
||||
}
|
||||
|
||||
// Whether the per-edit pass for this harness should defer non-immediate
|
||||
// findings to a Stop deep pass. Only Claude Code and Codex dispatch our Stop
|
||||
// hook; Cursor and GitHub Copilot have no deep pass wired, so deferring for
|
||||
// them would silently drop the non-immediate rules entirely.
|
||||
// findings to a Stop deep pass. Claude Code, Codex, and Grok Build dispatch
|
||||
// our Stop hook; Cursor and GitHub Copilot have no deep pass wired, so
|
||||
// deferring for them would silently drop the non-immediate rules entirely.
|
||||
export function perEditTieringActive(config, harness) {
|
||||
if (harness === 'cursor' || harness === 'github') return false;
|
||||
return (config?.perEditRules || DEFAULT_CONFIG.perEditRules) !== 'all';
|
||||
@@ -1251,9 +1251,14 @@ export function resolveHarness(env = {}, event = null) {
|
||||
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
|
||||
if (explicit === 'cursor') return 'cursor';
|
||||
if (explicit === 'github') return 'github';
|
||||
if (explicit === 'grok') return 'grok';
|
||||
if (explicit === 'claude' || explicit === 'codex') return 'claude';
|
||||
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
|
||||
// has no `tool_name`/`tool_input`. That shape is the discriminator.
|
||||
// Grok Build sends camelCase `toolName`/`toolInput`/`hookEventName` and no
|
||||
// snake_case pair. GitHub Copilot sends camelCase `toolName`/`toolArgs`.
|
||||
// Check Grok first: the old GitHub heuristic (`toolName` and no
|
||||
// `tool_input`) also matches Grok, which is how live PostToolUse was
|
||||
// classified as Copilot and then skipped with no-file-path (#646).
|
||||
if (looksLikeGrokEnvelope(event)) return 'grok';
|
||||
if (event && typeof event === 'object'
|
||||
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
|
||||
&& event.tool_name === undefined && event.tool_input === undefined) {
|
||||
@@ -1263,6 +1268,27 @@ export function resolveHarness(env = {}, event = null) {
|
||||
return 'claude';
|
||||
}
|
||||
|
||||
function looksLikeGrokEnvelope(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
if (event.hook_event_name !== undefined
|
||||
|| event.tool_name !== undefined
|
||||
|| event.tool_input !== undefined) {
|
||||
return false;
|
||||
}
|
||||
if (event.toolArgs !== undefined) return false;
|
||||
if (typeof event.hookEventName === 'string') return true;
|
||||
return typeof event.toolName === 'string' && event.toolInput !== undefined;
|
||||
}
|
||||
|
||||
// Stop arrives as Claude's `hook_event_name: "Stop"` or Grok Build's
|
||||
// `hookEventName: "stop"`. hook.mjs routes on the raw stdin, before any
|
||||
// normalize, so both casings must match here.
|
||||
export function isStopEvent(event) {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const name = event.hook_event_name || event.hookEventName;
|
||||
return typeof name === 'string' && name.toLowerCase() === 'stop';
|
||||
}
|
||||
|
||||
// GitHub Copilot's postToolUse payload is
|
||||
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
|
||||
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
|
||||
@@ -1354,9 +1380,36 @@ function normalizeGitHubEvent(event, projectCwd) {
|
||||
};
|
||||
}
|
||||
|
||||
// Grok Build 1.0.5 (captured 2026-08-24) sends camelCase `toolName` /
|
||||
// `toolInput` / `sessionId` / `stopHookActive`, plus `cwd` alongside a
|
||||
// trailing-slashed `workspaceRoot` (every consumer path.resolve()s, so no
|
||||
// stripping here). Only the fields the hook reads are copied; the event
|
||||
// name stays camelCase because routing already happened on the raw stdin
|
||||
// (isStopEvent) and nothing downstream reads `hook_event_name`.
|
||||
function normalizeGrokEvent(event, projectCwd) {
|
||||
const cwd = event.cwd || event.workspaceRoot || envProjectDir(projectCwd) || projectCwd;
|
||||
const sessionId = event.sessionId || event.session_id || 'unknown';
|
||||
const rawInput = event.toolInput ?? event.tool_input;
|
||||
const toolInput = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
|
||||
? { ...rawInput }
|
||||
: {};
|
||||
const out = {
|
||||
...event,
|
||||
cwd,
|
||||
session_id: sessionId,
|
||||
tool_name: event.toolName || event.tool_name || null,
|
||||
tool_input: toolInput,
|
||||
};
|
||||
if (event.stopHookActive !== undefined && event.stop_hook_active === undefined) {
|
||||
out.stop_hook_active = event.stopHookActive;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
|
||||
if (!event || typeof event !== 'object') return event;
|
||||
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
|
||||
if (harness === 'grok') return normalizeGrokEvent(event, projectCwd);
|
||||
if (harness !== 'cursor') return event;
|
||||
|
||||
const cwd = event.cwd
|
||||
@@ -1959,7 +2012,15 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// findings stop being remembered and a reintroduced one reads as fresh.
|
||||
// Only the immediate tier is remembered: a deferred finding the per-edit
|
||||
// pass never reported must still read as fresh to the Stop deep pass.
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
//
|
||||
// Grok ignores PostToolUse stdout, so Stop is the user-visible pass.
|
||||
// Remembering here would dedupe those findings out of Stop. Touch the
|
||||
// file so Stop has it, and leave the finding list empty.
|
||||
if (harness === 'grok') {
|
||||
touchFile(cache, sessionId, filePath);
|
||||
} else {
|
||||
rememberFindings(cache, sessionId, filePath, immediate);
|
||||
}
|
||||
cacheDirty = true;
|
||||
|
||||
if (fresh.length > 0) {
|
||||
@@ -2191,22 +2252,32 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
event = normalizeHookEvent(event, cwd, harness);
|
||||
|
||||
// Claude Code's Stop-hook contract: `stop_hook_active` is true when this
|
||||
// hook is being re-invoked only because a prior invocation kept the turn
|
||||
// alive (here, via hookSpecificOutput.additionalContext). Re-scanning and
|
||||
// re-blocking now would loop until Claude Code's consecutive-block cap
|
||||
// force-ends the turn (issue #400). The prior fire already surfaced the
|
||||
// findings; whether to act on them is the agent's call. Exit fast with no
|
||||
// output before any scan. Only Claude Code sends this field; other
|
||||
// harnesses omit it, so the strict `=== true` is a no-op for them. This
|
||||
// guard makes the loop impossible regardless of the finding cache key's
|
||||
// line-number sensitivity (out of scope here; see findingCacheKey).
|
||||
// output before any scan. Claude sends `stop_hook_active`; Grok sends
|
||||
// `stopHookActive`, copied onto the snake_case field above. The strict
|
||||
// `=== true` is a no-op when the field is absent. This guard makes the
|
||||
// loop impossible regardless of the finding cache key's line-number
|
||||
// sensitivity (out of scope here; see findingCacheKey).
|
||||
if (event.stop_hook_active === true) {
|
||||
return result({ skipped: 'stop-hook-active', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
const harness = resolveHarness(env, event);
|
||||
audit.harness = harness;
|
||||
// Grok fires Stop twice: `end_turn` (the gate that can inject
|
||||
// additionalContext) then an observe-only `shutdown`. A second deep
|
||||
// pass would re-emit the same findings. Claude omits `reason`; only
|
||||
// skip when Grok named a reason that is not end_turn.
|
||||
if (harness === 'grok' && typeof event.reason === 'string' && event.reason !== 'end_turn') {
|
||||
return result({ skipped: 'stop-reason', reason: event.reason, durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
// A Stop event carries no file, so the session cwd is the project.
|
||||
// Umbrella-dir launches keyed their per-edit cache to the edited file's
|
||||
@@ -2241,6 +2312,7 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
|
||||
const freshGroups = [];
|
||||
let scanned = 0;
|
||||
let cacheDirty = false;
|
||||
for (const filePath of touched) {
|
||||
if (scanned >= STOP_MAX_FILES) break;
|
||||
if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) continue;
|
||||
@@ -2261,29 +2333,39 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
|
||||
|
||||
let findings;
|
||||
let detectorThrew = false;
|
||||
const useHtmlEngine = configuredExt
|
||||
? configuredExt.engine === 'html'
|
||||
: (ext === '.html' || ext === '.htm');
|
||||
|
||||
if (useHtmlEngine && typeof det.detectHtml === 'function') {
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
} else {
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; }
|
||||
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
|
||||
}
|
||||
|
||||
// A detector failure tells us nothing about the file. Leave whatever
|
||||
// was remembered alone rather than recording an empty scan as truth.
|
||||
if (detectorThrew) continue;
|
||||
|
||||
// Full rule set: no tier split here. Config/inline ignores still apply,
|
||||
// and the session dedupe drops everything the per-edit pass (or an
|
||||
// earlier Stop pass) already surfaced.
|
||||
const filtered = filterFindings(findings || [], content, ext, config);
|
||||
const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
|
||||
// Sync to the live scan, including empty. Remembering only `fresh`
|
||||
// (or skipping the write on a clean Stop) left stale keys in place, so
|
||||
// a finding that was fixed and later reintroduced never fired again.
|
||||
rememberFindings(cache, sessionId, filePath, filtered);
|
||||
cacheDirty = true;
|
||||
if (fresh.length > 0) {
|
||||
rememberFindings(cache, sessionId, filePath, fresh);
|
||||
freshGroups.push({ filePath, findings: fresh });
|
||||
}
|
||||
}
|
||||
audit.scannedFiles = scanned;
|
||||
|
||||
if (freshGroups.length === 0) {
|
||||
if (cacheDirty) persistCache(projectCwd, cache);
|
||||
return result({ emitted: false, skipped: 'stop-clean', durationMs: Date.now() - started });
|
||||
}
|
||||
|
||||
@@ -2300,8 +2382,8 @@ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), no
|
||||
);
|
||||
commitFooterShown(cache, sessionId, text);
|
||||
|
||||
// Fresh findings earn the cache write so the next Stop fire is silent
|
||||
// unless new issues appear; the notice flags ride along.
|
||||
// Persist the live finding set so the next Stop fire is silent unless
|
||||
// new issues appear; the notice flags ride along.
|
||||
persistCache(projectCwd, cache);
|
||||
return {
|
||||
exitCode: 0,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user