Files
pbakaus_impeccable/scripts/lib/utils.js
T
e587004ee4 Refactor: cleaner top-level directory structure (#138)
* refactor(content): merge content/site/ into site/content/

Phase 1 step 1 of the directory restructure. The dual content tree was
called out in CLAUDE.md as cleanup; both trees were already in sync
except for anti-patterns-catalog.js, which moves to site/data/.

- Delete content/site/skills/ and content/site/tutorials/ (duplicates of
  site/content/, which is what Astro's content collection actually reads).
- Move content/site/anti-patterns-catalog.js -> site/data/.
- Update scripts/lib/sub-pages-data.js and scripts/build.js to read from
  site/content/ and site/data/.
- Drop content/site/ from validateProse target list (site/content was
  already there).
- Rewrite the "Two content trees" section in CLAUDE.md as a single-tree
  pointer; update stale dev-server text mentioning the deleted
  server/index.js.

Tests: 186/186 pass. Skills build: clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(skill): rename source/skills/impeccable/ -> skill/

Phase 1 step 2 of the directory restructure. The path was redundantly
nested ("source/" wrapper plus "skills/impeccable/" — singular content
hidden behind the plural). Collapses to flat skill/SKILL.md +
skill/reference/ + skill/scripts/.

- Move source/skills/impeccable/ -> skill/.
- Rewrite scripts/lib/utils.js readSourceFiles(): drop the multi-skill
  iteration (CLAUDE.md commits to a single user-invocable skill); read
  skill/SKILL.md directly.
- Update scripts/build.js, scripts/generate-og-image.js, and the
  sub-pages data layer to point at skill/.
- Update tests/lib/utils.test.js: drop the "multi-skill" and "dir-name
  fallback" cases, update single-skill paths to skill/.
- Update tests/build.test.js similarly: drop "multiple skills"
  integration test, update paths.
- Update non-glob path joins in tests/framework-fixtures.test.mjs,
  tests/live-e2e/session.mjs, tests/live-e2e/agents/llm-agent.mjs,
  tools/live-loop.mjs.
- Update prose/text references in CLAUDE.md, AGENTS.md, DEVELOP.md,
  README.md, scripts/lib/sub-pages-data.js, bin/commands/skills.mjs,
  site/data/anti-patterns-catalog.js, site/pages/docs/[...slug].astro,
  docs/adr-live-variant-mode.md, docs/plans/.

Eval framework note: the separate impeccable-evals repo reads
../impeccable/source/skills/impeccable/ and needs a coordinated
rename to ../impeccable/skill/.

Tests: 186/186 pass. Skills build: clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: rename docs/ -> notes/

Phase 1 step 3 of the directory restructure. The internal docs/ dir
(ADRs and plans) clashed with the site's /docs route. Renaming it
"notes/" makes the difference unambiguous: notes/ is project-internal
process, /docs is the user-facing route under site/pages/docs/.

No code references the dir; the rename is a clean git mv.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(site): move public/ under site/public/

Phase 2 step 4 of the directory restructure. Public assets and the
Astro publicDir now live alongside the rest of the site, so site/
is fully self-contained for static content.

- git mv public site/public.
- astro.config.mjs: add publicDir: './site/public'. Astro defaults to
  ./public at the project root, so the override is required.
- scripts/build.js: write generated _data, _headers, _redirects,
  _routes.json, and js/detect-antipatterns-browser.js into
  site/public/. Also delete the dead _REMOVED() Bun static-site
  builder (replaced by Astro at #130; the placeholder no longer earns
  its keep).
- scripts/build.js validateProse: replace the stale public/index.html
  reference (deleted at the Astro migration) with site/pages/index.astro
  in the count-validation file list, restoring homepage drift detection.
- scripts/generate-og-image.js: write OG image into site/public/.
- scripts/screenshot-antipatterns.js: read examples from + write
  screenshots to site/public/antipattern-{examples,images}/.
- scripts/lib/sub-pages-data.js: load command demos from
  site/public/js/demos/commands.
- .gitignore: rename the public/* generator-output entries to
  site/public/*.
- CLAUDE.md: refresh CSS/data-file paths (still pointing at the old
  pre-Astro public/css/ + public/js/ tree), point the changelog and
  command-add checklists at site/pages/index.astro and
  site/scripts/data.js + site/scripts/components/framework-viz.js.

Cloudflare Pages note: functions/ stays at the repo root because
CF Pages auto-discovers it there with no configuration knob to
relocate. Moving it under site/ would either break deployment or
require a build-time copy step that adds more complexity than the
cleanup is worth.

Tests: 186/186 pass. Skills + site build clean. _headers,
_redirects, _routes.json, _data/ all land in build/ correctly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(cli): consolidate bin/ + src/ + lib/ under cli/

Phase 2 step 5 of the directory restructure. The CLI surface was split
across three top-level dirs whose names were easy to mistake for each
other (especially src/ vs source/ pre-step-2). Consolidates under cli/.

- git mv bin -> cli/bin (CLI entry + skills sub-command)
- git mv src -> cli/engine (detect-antipatterns engine + browser variant)
- git mv lib -> cli/lib (download-providers helper)

Update package.json:
- bin.impeccable: cli/bin/cli.js
- main + exports: cli/engine/detect-antipatterns.mjs and the
  ./browser variant
- files: ["cli/", "LICENSE"]

Update internal references:
- cli/bin/cli.js: dynamic import points at ../engine/, package.json
  read goes one level deeper (../../package.json).
- functions/api/download/[type]/[provider]/[id].js + bundle/[provider].js:
  cli/lib/download-providers.js path.
- scripts/build.js, scripts/build-browser-detector.js,
  scripts/build-extension.js: cli/engine path constants.
- scripts/lib/sub-pages-data.js, scripts/lib/utils.js, skill/scripts/
  live-server.mjs: comment refs.
- tests/detect-antipatterns{,-browser,-fixtures}.test.{js,mjs},
  tests/windows-path-fix.test.js: import + read paths.
- AGENTS.md, CLAUDE.md: doc paths.

Verified:
- npx node cli/bin/cli.js --version, --help, detect --help all work.
- bun run build, bun run build:browser, bun run build:extension all
  clean. Browser detector lands at cli/engine/detect-antipatterns-browser.js;
  extension/detector/detect.js still emits to the same location.
- bun run test: 186/186 pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: update browser-detector paths missed in cli/ rename

Bugbot caught two runtime path leaks where the comment got renamed
to cli/engine/ but the actual code still used the old src/ segment.

- skill/scripts/live-server.mjs: detectPaths array now joins cli, engine,
  detect-antipatterns-browser.js for both the repo-relative lookup
  (4 dirs up from .claude/skills/impeccable/scripts/ to repo root) and
  the npm node_modules fallback. Without this fix, the detection
  overlay would silently not load during live-server sessions.

- scripts/build.js: the post-build copy of the browser detector into
  site/public/js/ was reading from src/. The if (fs.existsSync(...))
  guard meant the copy was silently skipping, so antipattern-examples
  pages would 404 on /js/detect-antipatterns-browser.js once the site
  was deployed.

Tests: 186/186 pass. Build clean. site/public/js/detect-antipatterns-browser.js
re-emits as expected.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: cleanup-deprecated import path missed an extra .. in cli/ rename

Bugbot caught three call sites in cli/bin/commands/skills.mjs that
import '../../skill/scripts/cleanup-deprecated.mjs'. Pre-rename, that
was correct from bin/commands/ (one parent to bin/, one to repo root).
After moving the file from bin/commands/ to cli/bin/commands/, the
path is one directory deeper, so it needs three .. segments to reach
the repo root. Without the fix, every cleanup invocation throws on
import and gets swallowed by the surrounding try/catch — silent skip.

cli/bin/cli.js's package.json read already uses '../../package.json'
(the same depth pattern), confirming three levels is correct.

Verified: dynamic import resolves and exports the expected functions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: sweep stale path/file references missed in the restructure

Same root cause as the two bugbot finds: some references in moved or
related files weren't tracked because they didn't match a simple
sed pattern. Caught the rest by walking each moved dir's depth and
each Astro-migration deletion.

Stale path references (post-Astro migration, missed earlier):
- CLAUDE.md: legacy URL redirects "live in server/index.js" -> point
  at the actual sources (scripts/build.js generateCFConfig +
  site/public/_redirects).
- AGENTS.md: counts.js path (public/ -> site/public/), changelog file
  (public/index.html -> site/pages/index.astro), screenshots note
  (public/ -> site/), source-of-truth dirs (source/, src/ -> skill/,
  cli/).
- tests/detect-antipatterns-browser.test.mjs: comment about routes
  "in server/index.js".
- skill/reference/live.md: workflow.css example for "this repo" was
  pre-Astro (public/css/) -> site/styles/. (User-project Vite/Next
  example unchanged.)

Stale path that pointed at moved files:
- tests/skills-cli.test.js: CLI path was '..', 'bin', 'cli.js'; now
  '..', 'cli', 'bin', 'cli.js'. Test isn't wired into bun run test
  but it would have failed if invoked.

Dead files (orphaned by Astro migration, never cleaned up):
- tests/server/download-validation.test.js: imported from
  ../../server/lib/{validation,api-handlers}.js which were deleted in
  b8f09c8. Test was a silent failure waiting to happen.
- scripts/lib/render-markdown.js: 156-line module with zero consumers
  (the only caller, scripts/lib/render-page.js, was deleted in the
  Astro cleanup).
- scripts/build.js: dead commented-out generateSubPages import.

Tests: 186/186 pass. Build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(build): remove invalid Corepack packageManager spec

Cloudflare Pages rejects the build with `Unsupported package manager
specification (bun@1.3.11)`. The packageManager field follows
Corepack's syntax which only validates npm/pnpm/yarn — `bun@X.Y.Z`
parses as a malformed Corepack directive even though Bun itself
treats it as a hint.

Pre-existing on main since d874af0 (CF Pages deploy on main also
failing); just surfaces here because the PR triggers a fresh deploy.

CF Pages auto-detects Bun anyway (the build log confirms:
"Detected the following tools from environment: bun@1.3.11,
pnpm@10.11.1, nodejs@22.16.0"). Removing the field unblocks the
deploy without changing local dev behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Paul Bakaus <paulbakaus@pauls-mbp-3.lan>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 16:38:03 -07:00

680 lines
23 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from 'fs';
import path from 'path';
// Per-project artifacts live inside `scripts/` of an installed skill but
// belong to the consuming project, not the distributable skill. The build
// excludes them from dist, and the harness-sync step preserves them across
// the rm+recopy so local state isn't destroyed on every rebuild.
// - config.json: legacy live-mode inject target list for existing projects.
// New installs write project config at .impeccable/live/config.json instead.
export const PER_PROJECT_SCRIPT_ARTIFACTS = new Set(['config.json']);
// Walk the harness-dir skill tree and return any per-project script
// artifacts found, ready for restoration after a full sync rm+recopy.
// Returns [{ relPath, content: Buffer }], where relPath is relative to
// the passed-in rootDir (typically `<configDir>/skills`).
export function stashPerProjectArtifacts(rootDir) {
if (!fs.existsSync(rootDir)) return [];
const out = [];
const walk = (dir) => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, entry.name);
if (entry.isDirectory()) { walk(p); continue; }
// Only preserve files inside a skill's scripts/ directory.
if (path.basename(path.dirname(p)) !== 'scripts') continue;
if (PER_PROJECT_SCRIPT_ARTIFACTS.has(entry.name)) {
out.push({ relPath: path.relative(rootDir, p), content: fs.readFileSync(p) });
}
}
};
walk(rootDir);
return out;
}
export function restorePerProjectArtifacts(rootDir, stashed) {
for (const { relPath, content } of stashed) {
const target = path.join(rootDir, relPath);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
}
/**
* Parse frontmatter from markdown content
* Returns { frontmatter: object, body: string }
*/
export function parseFrontmatter(content) {
const frontmatterRegex = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
const match = content.match(frontmatterRegex);
if (!match) {
return { frontmatter: {}, body: content };
}
const [, frontmatterText, body] = match;
const frontmatter = {};
// Simple YAML parser (handles basic key-value and arrays)
const lines = frontmatterText.split(/\r?\n/);
let currentKey = null;
let currentArray = null;
for (const line of lines) {
if (!line.trim()) continue;
// Calculate indent level
const leadingSpaces = line.length - line.trimStart().length;
const trimmed = line.trim();
// Array item at level 2 (nested under a key)
if (trimmed.startsWith('- ') && leadingSpaces >= 2) {
if (currentArray) {
if (trimmed.startsWith('- name:')) {
// New object in array
const obj = {};
obj.name = trimmed.slice(7).trim();
currentArray.push(obj);
} else {
// Simple string item in array
currentArray.push(trimmed.slice(2));
}
}
continue;
}
// Property of array object (indented further)
if (leadingSpaces >= 4 && currentArray && currentArray.length > 0) {
const colonIndex = trimmed.indexOf(':');
if (colonIndex > 0) {
const key = trimmed.slice(0, colonIndex).trim();
const value = trimmed.slice(colonIndex + 1).trim();
const lastObj = currentArray[currentArray.length - 1];
lastObj[key] = value === 'true' ? true : value === 'false' ? false : value;
}
continue;
}
// Top-level key-value pair
if (leadingSpaces === 0) {
const colonIndex = trimmed.indexOf(':');
if (colonIndex > 0) {
const key = trimmed.slice(0, colonIndex).trim();
const value = trimmed.slice(colonIndex + 1).trim();
const isQuoted = /^(".*"|'.*')$/.test(value);
const unquotedValue = isQuoted ? value.slice(1, -1) : value;
const shouldCoerceBoolean =
key === 'user-invocable' || key === 'user-invokable' || !isQuoted;
if (value) {
frontmatter[key] = shouldCoerceBoolean
? unquotedValue === 'true'
? true
: unquotedValue === 'false'
? false
: unquotedValue
: unquotedValue;
currentKey = key;
currentArray = null;
} else {
// Start of array
currentKey = key;
currentArray = [];
frontmatter[key] = currentArray;
}
}
}
}
return { frontmatter, body: body.trim() };
}
/**
* Recursively read all .md files from a directory
*/
export function readFilesRecursive(dir, fileList = []) {
if (!fs.existsSync(dir)) {
return fileList;
}
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
readFilesRecursive(filePath, fileList);
} else if (file.endsWith('.md')) {
fileList.push(filePath);
}
}
return fileList;
}
/**
* Read and parse the impeccable skill source.
* After v3.0 the repo holds exactly one user-invocable skill, flat at skill/.
* Returns { skills: [oneEntry] } so downstream array-shaped consumers stay happy.
*/
export function readSourceFiles(rootDir) {
const skillDir = path.join(rootDir, 'skill');
const skills = [];
const skillMdPath = path.join(skillDir, 'SKILL.md');
if (!fs.existsSync(skillMdPath)) {
return { skills };
}
const content = fs.readFileSync(skillMdPath, 'utf-8');
const { frontmatter, body } = parseFrontmatter(content);
const references = [];
const referenceDir = path.join(skillDir, 'reference');
if (fs.existsSync(referenceDir)) {
const refFiles = fs.readdirSync(referenceDir).filter(f => f.endsWith('.md'));
for (const refFile of refFiles) {
const refPath = path.join(referenceDir, refFile);
references.push({
name: path.basename(refFile, '.md'),
content: fs.readFileSync(refPath, 'utf-8'),
filePath: refPath
});
}
}
// PER_PROJECT_SCRIPT_ARTIFACTS (defined at module top) are excluded from
// the distributable skill so the build never bundles one project's state
// into another's.
const scripts = [];
const scriptsDir = path.join(skillDir, 'scripts');
if (fs.existsSync(scriptsDir)) {
const scriptFiles = fs.readdirSync(scriptsDir).filter(f => {
if (PER_PROJECT_SCRIPT_ARTIFACTS.has(f)) return false;
return fs.statSync(path.join(scriptsDir, f)).isFile();
});
for (const scriptFile of scriptFiles) {
const scriptPath = path.join(scriptsDir, scriptFile);
scripts.push({
name: scriptFile,
content: fs.readFileSync(scriptPath, 'utf-8'),
filePath: scriptPath
});
}
}
skills.push({
name: frontmatter.name || 'impeccable',
description: frontmatter.description || '',
license: frontmatter.license || '',
compatibility: frontmatter.compatibility || '',
metadata: frontmatter.metadata || null,
allowedTools: frontmatter['allowed-tools'] || '',
userInvocable: frontmatter['user-invocable'] === true || frontmatter['user-invocable'] === 'true',
argumentHint: frontmatter['argument-hint'] || '',
context: frontmatter.context || null,
body,
filePath: skillMdPath,
references,
scripts
});
return { skills };
}
/**
* Ensure directory exists, create if needed
*/
export function ensureDir(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
/**
* Clean directory (remove all contents)
*/
export function cleanDir(dirPath) {
if (fs.existsSync(dirPath)) {
fs.rmSync(dirPath, { recursive: true, force: true });
}
}
/**
* Write file with automatic directory creation
*/
export function writeFile(filePath, content) {
const dir = path.dirname(filePath);
ensureDir(dir);
fs.writeFileSync(filePath, content, 'utf-8');
}
/**
* Extract DO/DON'T patterns from a skill markdown file, grouped by section
* (h3 `### ` headings). Recognizes both formats:
* - Markdown bullet form: `**DO**: …` / `**DON'T**: …`
* - Prose form: `DO …` / `DO NOT …`
*
* Defaults to the main impeccable SKILL.md but accepts any relative path so
* rules in `cli/engine/detect-antipatterns.mjs` can anchor to register-specific
* reference files (e.g. `reference/editorial.md`) via an optional `skillFile`
* field. Callers that don't pass `relativePath` get the legacy behavior.
*
* Returns { patterns: [...], antipatterns: [...] }
*/
// Curated short-list for the homepage Antidote section. Intentionally
// hand-written (not auto-extracted) so the copy stays tight and
// editorial. The long-form catalog lives on /slop — this is the teaser.
const CURATED_CATEGORIES = [
{
name: 'Typography',
do: [
'Pair a distinctive display face with a restrained body face; vary across projects.',
'Use a ≥1.25 scale ratio between hierarchy steps. Flat scales read as bland.',
'Cap body line length at 6575ch. Wider is fatiguing.',
],
dont: [
'Inter, Roboto, Plex, Fraunces, or any other reflex default. Look further.',
'Monospace as lazy shorthand for "technical."',
'Long passages in uppercase. Reserve all-caps for short labels.',
],
},
{
name: 'Color & Contrast',
do: [
'Use OKLCH. Reduce chroma near lightness extremes.',
'Tint neutrals toward the brand hue. Chroma 0.0050.01 is enough.',
'Pick a color strategy before picking colors (Restrained, Committed, Full, Drenched).',
],
dont: [
'Pure #000 or #fff. Always tint.',
'Dark mode + purple-to-cyan gradients. The AI tell.',
'Gradient text via background-clip. Use weight or size for emphasis.',
],
},
{
name: 'Layout & Space',
do: [
'Vary spacing for rhythm. Tight groupings, generous separations.',
'Use the simplest tool: Flexbox for 1D, Grid for 2D, plain flow often enough.',
'Let whitespace carry hierarchy before reaching for color or scale.',
],
dont: [
'Wrap everything in cards. Nested cards are always wrong.',
'Identical card grids of icon + heading + text, repeated endlessly.',
'The hero-metric template: big number, small label, supporting stats, gradient accent.',
],
},
{
name: 'Visual Details',
do: [
'Commit to an aesthetic direction and execute it with precision.',
'Use ornament only where it earns its place.',
],
dont: [
'Side-stripe borders (border-left/-right > 1px). The dashboard tell.',
'Glassmorphism everywhere. Rare and purposeful or nothing.',
'Rounded rectangles with generic drop shadows. "Could be any AI output."',
],
},
{
name: 'Motion',
do: [
'Use transform and opacity. Animate the composited properties only.',
'Ease out with exponential curves (quart / quint / expo).',
'Respect prefers-reduced-motion on every transition.',
],
dont: [
'Animate layout (width, height, padding, margin).',
'Bounce or elastic easing. Feels dated and tacky.',
'Decorative motion for its own sake. Motion should signal state.',
],
},
{
name: 'Interaction',
do: [
'Use optimistic UI: update immediately, sync later.',
'Design empty states that teach the interface, not just say "nothing here."',
'Progressive disclosure: start simple, reveal sophistication on demand.',
],
dont: [
'Make every button primary. Hierarchy matters.',
'Default to a modal. Exhaust inline alternatives first.',
'Repeat information the user can already see.',
],
},
];
export function readPatterns(_rootDir, _relativePath) {
// Hand-curated list — see CURATED_CATEGORIES above. The homepage
// Antidote teaser uses this; the full catalog lives on /slop.
return {
patterns: CURATED_CATEGORIES.map((c) => ({ name: c.name, items: c.do })),
antipatterns: CURATED_CATEGORIES.map((c) => ({ name: c.name, items: c.dont })),
};
}
// Previous SKILL.md parser retained below but disabled; kept as a
// reference for how prefix-style extraction used to work.
function _legacyReadPatterns(rootDir, relativePath = 'skill/SKILL.md') {
const skillPath = path.join(rootDir, relativePath);
if (!fs.existsSync(skillPath)) {
return { patterns: [], antipatterns: [] };
}
const content = fs.readFileSync(skillPath, 'utf-8');
const lines = content.split('\n');
const patternsMap = {}; // category -> items[]
const antipatternsMap = {}; // category -> items[]
let currentSection = null;
const pushPattern = (item) => {
if (!currentSection) return;
if (!patternsMap[currentSection]) patternsMap[currentSection] = [];
patternsMap[currentSection].push(item);
};
const pushAntipattern = (item) => {
if (!currentSection) return;
if (!antipatternsMap[currentSection]) antipatternsMap[currentSection] = [];
antipatternsMap[currentSection].push(item);
};
for (const line of lines) {
const trimmed = line.trim();
// Track section headings (### Typography, ### Color & Theme, etc.)
if (trimmed.startsWith('### ')) {
currentSection = trimmed.slice(4).trim();
// Normalize "Color & Theme" to "Color & Contrast" for consistency
if (currentSection === 'Color & Theme') {
currentSection = 'Color & Contrast';
}
continue;
}
// Markdown bullet form (legacy): **DO**: ... and **DON'T**: ...
if (trimmed.startsWith('**DO**:')) {
pushPattern(trimmed.slice(7).trim());
continue;
}
if (trimmed.startsWith("**DON'T**:")) {
pushAntipattern(trimmed.slice(10).trim());
continue;
}
// XML-block prose form (current). Both space and colon variants:
// "DO NOT use ..." / "DO NOT: Use ..."
// "DO use ..." / "DO: Use ..."
// IMPORTANT: check `DO NOT` BEFORE `DO` so the prefix doesn't get
// gobbled by the wrong matcher.
if (trimmed.startsWith('DO NOT: ')) {
pushAntipattern(trimmed.slice('DO NOT: '.length).trim());
continue;
}
if (trimmed.startsWith('DO NOT ')) {
pushAntipattern(trimmed.slice('DO NOT '.length).trim());
continue;
}
if (trimmed.startsWith('DO: ')) {
pushPattern(trimmed.slice('DO: '.length).trim());
continue;
}
if (trimmed.startsWith('DO ')) {
pushPattern(trimmed.slice('DO '.length).trim());
continue;
}
}
// Convert maps to arrays in consistent order
const sectionOrder = ['Typography', 'Color & Contrast', 'Layout & Space', 'Visual Details', 'Motion', 'Interaction', 'Responsive', 'UX Writing'];
const patterns = [];
const antipatterns = [];
for (const section of sectionOrder) {
if (patternsMap[section] && patternsMap[section].length > 0) {
patterns.push({ name: section, items: patternsMap[section] });
}
if (antipatternsMap[section] && antipatternsMap[section].length > 0) {
antipatterns.push({ name: section, items: antipatternsMap[section] });
}
}
return { patterns, antipatterns };
}
/**
* Provider-specific placeholders
*/
export const PROVIDER_PLACEHOLDERS = {
'claude-code': {
model: 'Claude',
config_file: 'CLAUDE.md',
ask_instruction: 'STOP and call the AskUserQuestion tool to clarify.',
command_prefix: '/'
},
'cursor': {
model: 'the model',
config_file: '.cursorrules',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
},
'gemini': {
model: 'Gemini',
config_file: 'GEMINI.md',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
},
'codex': {
model: 'GPT',
config_file: 'AGENTS.md',
ask_instruction: "STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.",
command_prefix: '$'
},
'agents': {
model: 'the model',
config_file: '.github/copilot-instructions.md',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
},
'kiro': {
model: 'Claude',
config_file: '.kiro/settings.json',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
},
opencode: {
model: 'Claude',
config_file: 'AGENTS.md',
ask_instruction: 'STOP and call the `question` tool to clarify.',
command_prefix: '/'
},
'pi': {
model: 'the model',
config_file: 'AGENTS.md',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
},
'qoder': {
model: 'the model',
config_file: 'AGENTS.md',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
},
'trae': {
model: 'the model',
config_file: 'RULES.md',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
},
'rovo-dev': {
model: 'Rovo Dev',
config_file: 'AGENTS.md',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
}
};
/**
* Replace all {{placeholder}} tokens with provider-specific values
*/
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const EXCLUDED_FROM_SUGGESTIONS = new Set([
'impeccable', // foundational skill, not a steering command
'teach-impeccable', // deprecated shim
'frontend-design', // deprecated shim
]);
// Sub-commands of /impeccable that should appear in {{available_commands}}.
// These are the commands that audit/critique/etc. reference when suggesting next steps.
const IMPECCABLE_SUB_COMMANDS = [
'adapt', 'animate', 'audit', 'bolder', 'clarify', 'colorize',
'critique', 'delight', 'distill', 'document', 'harden', 'layout',
'onboard', 'optimize', 'overdrive', 'polish', 'quieter', 'shape', 'typeset',
];
export function replacePlaceholders(content, provider, commandNames = [], allSkillNames = []) {
const placeholders = PROVIDER_PLACEHOLDERS[provider] || PROVIDER_PLACEHOLDERS['cursor'];
const cmdPrefix = placeholders.command_prefix || '/';
// Build the available_commands list.
// After the v3.0 consolidation, commands are sub-commands of /impeccable.
// If there's only one user-invocable skill (impeccable), generate sub-command references.
// Otherwise fall back to listing skill names (backwards compat for forks).
const nonExcluded = commandNames.filter(n => !EXCLUDED_FROM_SUGGESTIONS.has(n));
let commandList;
if (nonExcluded.length === 0) {
// Single-skill architecture: list sub-commands as /impeccable <sub>
commandList = IMPECCABLE_SUB_COMMANDS
.map(n => `${cmdPrefix}impeccable ${n}`)
.join(', ');
} else {
// Multi-skill architecture (backwards compat)
commandList = nonExcluded.map(n => `${cmdPrefix}${n}`).join(', ');
}
let result = content
.replace(/\{\{model\}\}/g, placeholders.model)
.replace(/\{\{config_file\}\}/g, placeholders.config_file)
.replace(/\{\{ask_instruction\}\}/g, placeholders.ask_instruction)
.replace(/\{\{command_prefix\}\}/g, cmdPrefix)
.replace(/\{\{available_commands\}\}/g, commandList);
// Replace `/skillname` invocations with the correct command prefix for this provider
// (e.g., `/normalize` → `$normalize` for Codex)
if (cmdPrefix !== '/' && allSkillNames.length > 0) {
const sorted = [...allSkillNames].sort((a, b) => b.length - a.length);
for (const name of sorted) {
result = result.replace(
new RegExp(`\\/(?=${escapeRegex(name)}(?:[^a-zA-Z0-9_-]|$))`, 'g'),
cmdPrefix
);
}
}
return result;
}
/**
* Decide whether a YAML scalar string value must be quoted to survive parsing.
*
* Plain (unquoted) YAML scalars cannot contain `: ` or ` #`, cannot start with
* a YAML indicator character, cannot look like a boolean/null/number, and
* cannot carry leading/trailing whitespace. parseFrontmatter strips surrounding
* quotes on input, so we must re-detect the need to quote on output — otherwise
* descriptions like "Handles: critique/review..." round-trip into invalid YAML.
*/
function yamlNeedsQuoting(value) {
if (typeof value !== 'string') return false;
if (value === '') return true;
// Leading or trailing whitespace
if (/^\s|\s$/.test(value)) return true;
// Starts with a YAML flow/indicator character
if (/^[\[\]{},&*!|>'"%@`#]/.test(value)) return true;
// Starts with `?`, `:`, or `-` followed by space or end of string
if (/^[?:-](\s|$)/.test(value)) return true;
// Contains `: ` (ends plain scalar) or ` #` (starts comment), or ends with `:`
if (/: |\s#|:$/.test(value)) return true;
// Reserved keywords that YAML 1.1 parsers coerce to boolean/null
if (/^(true|false|null|yes|no|on|off|~)$/i.test(value)) return true;
// Looks like a number
if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(value)) return true;
return false;
}
function formatYamlScalar(value) {
if (typeof value !== 'string') return String(value);
if (yamlNeedsQuoting(value)) {
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
}
return value;
}
function appendYamlObject(lines, data, indent = 0) {
const space = ' '.repeat(indent);
for (const [key, value] of Object.entries(data)) {
if (Array.isArray(value)) {
lines.push(`${space}${key}:`);
for (const item of value) {
if (item && typeof item === 'object' && !Array.isArray(item)) {
lines.push(`${space} -`);
appendYamlObject(lines, item, indent + 4);
} else {
lines.push(`${space} - ${formatYamlScalar(item)}`);
}
}
} else if (value && typeof value === 'object') {
lines.push(`${space}${key}:`);
appendYamlObject(lines, value, indent + 2);
} else if (typeof value === 'boolean') {
lines.push(`${space}${key}: ${value}`);
} else {
lines.push(`${space}${key}: ${formatYamlScalar(value)}`);
}
}
}
/**
* Generate YAML frontmatter string
*/
export function generateYamlFrontmatter(data) {
const lines = ['---'];
for (const [key, value] of Object.entries(data)) {
if (Array.isArray(value)) {
lines.push(`${key}:`);
for (const item of value) {
if (typeof item === 'object') {
lines.push(` - name: ${formatYamlScalar(item.name)}`);
if (item.description) lines.push(` description: ${formatYamlScalar(item.description)}`);
if (item.required !== undefined) lines.push(` required: ${item.required}`);
} else {
lines.push(` - ${formatYamlScalar(item)}`);
}
}
} else if (typeof value === 'boolean') {
lines.push(`${key}: ${value}`);
} else {
lines.push(`${key}: ${formatYamlScalar(value)}`);
}
}
lines.push('---');
return lines.join('\n');
}
/**
* Generate a plain YAML document string.
*/
export function generateYamlDocument(data) {
const lines = [];
appendYamlObject(lines, data);
return lines.join('\n');
}