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>
This commit is contained in:
Paul Bakaus
2026-05-04 16:38:03 -07:00
committed by GitHub
co-authored by Paul Bakaus Claude Opus 4.7
parent 2aeac48b19
commit e587004ee4
256 changed files with 383 additions and 2650 deletions
+3 -3
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
/**
* Generates src/detect-antipatterns-browser.js
* Generates cli/engine/detect-antipatterns-browser.js
* by stripping Node-specific sections from the universal source and wrapping in an IIFE.
*
* Run: node scripts/build-browser-detector.js
@@ -14,8 +14,8 @@ import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const SOURCE = path.join(ROOT, 'src/detect-antipatterns.mjs');
const OUTPUT = path.join(ROOT, 'src/detect-antipatterns-browser.js');
const SOURCE = path.join(ROOT, 'cli/engine/detect-antipatterns.mjs');
const OUTPUT = path.join(ROOT, 'cli/engine/detect-antipatterns-browser.js');
let code = fs.readFileSync(SOURCE, 'utf-8');
+1 -1
View File
@@ -18,7 +18,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const EXT_DIR = path.join(ROOT, 'extension');
const SOURCE = path.join(ROOT, 'src/detect-antipatterns.mjs');
const SOURCE = path.join(ROOT, 'cli/engine/detect-antipatterns.mjs');
const DETECTOR_OUTPUT = path.join(EXT_DIR, 'detector/detect.js');
const AP_OUTPUT = path.join(EXT_DIR, 'detector/antipatterns.json');
+18 -110
View File
@@ -22,10 +22,9 @@ import { readSourceFiles, readPatterns, stashPerProjectArtifacts, restorePerProj
import { createTransformer, PROVIDERS } from './lib/transformers/index.js';
import { createAllZips } from './lib/zip.js';
// Sub-page generation is now handled by Astro content collections.
// import { generateSubPages } from './build-sub-pages.js';
/**
* Generate authoritative counts from source data and write to public/js/generated/counts.js.
* Generate authoritative counts from source data and write to site/public/js/generated/counts.js.
* Also validates that key HTML files reference the correct numbers.
*/
function generateCounts(rootDir, skills, buildDir) {
@@ -50,7 +49,7 @@ function generateCounts(rootDir, skills, buildDir) {
}
// Count detection rules from impeccable package
const detectPkgPath = path.join(rootDir, 'src/detect-antipatterns.mjs');
const detectPkgPath = path.join(rootDir, 'cli/engine/detect-antipatterns.mjs');
const detectorSrc = fs.readFileSync(detectPkgPath, 'utf-8');
const ruleIds = new Set();
for (const match of detectorSrc.matchAll(/^\s+id: '([^']+)'/gm)) {
@@ -59,7 +58,7 @@ function generateCounts(rootDir, skills, buildDir) {
const detectionCount = ruleIds.size;
// Write generated counts module
const genDir = path.join(rootDir, 'public/js/generated');
const genDir = path.join(rootDir, 'site/public/js/generated');
fs.mkdirSync(genDir, { recursive: true });
fs.writeFileSync(path.join(genDir, 'counts.js'),
`// GENERATED by build.js — do not edit\n` +
@@ -69,7 +68,7 @@ function generateCounts(rootDir, skills, buildDir) {
// Validate counts in key files
const filesToCheck = [
'public/index.html',
'site/pages/index.astro',
'README.md',
'NOTICE.md',
'AGENTS.md',
@@ -137,7 +136,7 @@ function validateSkillFrontmatter(skills) {
* The denylist is the editorial brief in STYLE.md, enforced. Each rule has a
* rationale that prints with the failure so the next author understands why.
*
* Scope: every surface a reader sees. Not source/skills/impeccable/, where
* Scope: every surface a reader sees. Not skill/, where
* LLM-facing reference instructions can use technical phrasings the marketing
* copy can't.
*
@@ -145,7 +144,6 @@ function validateSkillFrontmatter(skills) {
*/
function validateProse(rootDir) {
const targets = [
'content/site',
'site/components',
'site/content',
'site/layouts',
@@ -247,7 +245,7 @@ function validateProse(rootDir) {
* Returns the number of occurrences found. Build fails if > 0.
*/
function validateSkillProse(rootDir) {
const target = 'source/skills/impeccable';
const target = 'skill';
const extensions = new Set(['.md']);
const emDashPatterns = [/—/g, /&mdash;/gi, /&#8212;/gi, /&#x2014;/gi];
// Tighter than validateProse: only the rules that have no technical reading.
@@ -314,9 +312,9 @@ function validateSkillProse(rootDir) {
if (fs.existsSync(full)) scan(full, target);
if (errors === 0) {
console.log(`✓ Skill prose validator: source/skills/impeccable/ is clean`);
console.log(`✓ Skill prose validator: skill/ is clean`);
} else {
console.error(`\n${errors} prose issue(s) in source/skills/impeccable/. See STYLE.md.`);
console.error(`\n${errors} prose issue(s) in skill/. See STYLE.md.`);
}
return errors;
}
@@ -360,96 +358,6 @@ const DIST_DIR = path.join(ROOT_DIR, 'dist');
// buildStaticSite (Bun HTML bundler) removed — now handled by Astro.
// Placeholder so the line-number-based edits below don't shift.
async function _REMOVED() {
const entrypoints = [
path.join(ROOT_DIR, 'public', 'index.html'),
path.join(ROOT_DIR, 'public', 'privacy.html'),
...extraEntrypoints,
];
const outdir = path.join(ROOT_DIR, 'build');
console.log(`📦 Building static site with Bun (${entrypoints.length} HTML entries)...`);
try {
const result = await Bun.build({
entrypoints: entrypoints,
outdir: outdir,
minify: true,
sourcemap: 'linked',
// Older Bun versions (e.g. the one Cloudflare Pages ships) don't dedupe
// shared CSS/JS chunks across HTML entrypoints — every entry tries to
// emit its own copy, and three different sub-pages all named index.html
// (under docs/, tutorials/, slop/) collide on the same
// chunk filename. Including [dir] in the chunk template scopes each
// chunk to its entry's directory so the names stay unique even when
// dedupe is off. Local Bun still emits a single shared chunk; CF Bun
// emits one per entry but each lands in its own directory.
naming: {
entry: '[dir]/[name].[ext]',
chunk: '[dir]/[name]-[hash].[ext]',
asset: '[dir]/[name]-[hash].[ext]',
},
});
if (!result.success) {
console.error('Build failed:');
for (const log of result.logs) {
console.error(log.message || log);
if (log.position) {
console.error(` at ${log.position.file}:${log.position.line}:${log.position.column}`);
}
}
process.exit(1);
}
// Calculate total size
const totalSize = result.outputs.reduce((sum, o) => sum + o.size, 0);
const htmlFiles = result.outputs.filter(o => o.path.endsWith('.html'));
const jsFiles = result.outputs.filter(o => o.path.endsWith('.js'));
const cssFiles = result.outputs.filter(o => o.path.endsWith('.css'));
// When entrypoints span multiple depths under public/ (e.g. public/index.html
// + public/docs/polish.html), Bun's HTML loader preserves the full public/
// prefix in the output tree. Flatten build/public/* up to build/*.
const nestedPublic = path.join(outdir, 'public');
if (fs.existsSync(nestedPublic)) {
for (const entry of fs.readdirSync(nestedPublic, { withFileTypes: true })) {
const from = path.join(nestedPublic, entry.name);
const to = path.join(outdir, entry.name);
if (fs.existsSync(to)) fs.rmSync(to, { recursive: true, force: true });
fs.renameSync(from, to);
}
fs.rmdirSync(nestedPublic);
}
console.log(`✓ Static site built to ./build/`);
console.log(` HTML: ${htmlFiles.length} file(s)`);
console.log(` JS: ${jsFiles.length} file(s) (${(jsFiles.reduce((s, f) => s + f.size, 0) / 1024).toFixed(1)} KB)`);
console.log(` CSS: ${cssFiles.length} file(s) (${(cssFiles.reduce((s, f) => s + f.size, 0) / 1024).toFixed(1)} KB)`);
console.log(` Total: ${(totalSize / 1024).toFixed(1)} KB\n`);
return result;
} catch (error) {
// Bun's build aggregator errors expose details on `error.errors` (an
// array of resolution / parse failures), not `error.stack`. Print
// both so CI logs surface the real cause instead of "undefined".
console.error('Failed to build static site:', error.message);
if (error.errors?.length) {
for (const e of error.errors) {
console.error(' -', e.message || e);
}
}
if (error.logs?.length) {
for (const log of error.logs) {
console.error(log.message || log);
}
}
if (error.stack) console.error(error.stack);
process.exit(1);
}
}
/**
* Assemble universal directory from all provider outputs
*/
@@ -521,11 +429,11 @@ function generateApiData(buildDir, skills, patterns) {
// /impeccable. Load them from command-metadata.json and include the root
// impeccable skill itself so UI surfaces like the cheatsheet can list them.
// Each entry also picks up a short `tagline` from its editorial file
// (content/site/skills/<id>.md) when one exists. Taglines are used by UI
// (site/content/skills/<id>.md) when one exists. Taglines are used by UI
// surfaces that need a human-friendly one-liner, while `description` stays
// optimized for auto-trigger keyword matching in the AI harness.
const readTagline = (id) => {
const editorialPath = path.join(ROOT_DIR, 'content/site/skills', `${id}.md`);
const editorialPath = path.join(ROOT_DIR, 'site/content/skills', `${id}.md`);
if (!fs.existsSync(editorialPath)) return null;
const raw = fs.readFileSync(editorialPath, 'utf-8');
const match = raw.match(/^---\n([\s\S]*?)\n---/);
@@ -534,13 +442,13 @@ function generateApiData(buildDir, skills, patterns) {
return taglineMatch ? taglineMatch[1] : null;
};
const metadataPath = path.join(ROOT_DIR, 'source/skills/impeccable/scripts/command-metadata.json');
const metadataPath = path.join(ROOT_DIR, 'skill/scripts/command-metadata.json');
if (!fs.existsSync(metadataPath)) {
throw new Error(`command-metadata.json is missing at ${metadataPath}. This file is required to generate the commands API.`);
}
const impeccable = skills.find(s => s.name === 'impeccable');
if (!impeccable) {
throw new Error('impeccable skill not found in source/skills/. The build system expects a single impeccable skill.');
throw new Error('impeccable skill not found at skill/SKILL.md. The build system expects exactly one skill at that path.');
}
const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8'));
@@ -688,11 +596,11 @@ async function build() {
// handled by Astro (bun run build:site). This script focuses on skills,
// API data, and Cloudflare config.
// Copy browser detector to public/js/ so the antipattern examples can
// reference it (Astro serves public/ as-is).
const detectorSrc = path.join(ROOT_DIR, 'src', 'detect-antipatterns-browser.js');
// Copy browser detector to site/public/js/ so the antipattern examples can
// reference it (Astro serves site/public/ as-is).
const detectorSrc = path.join(ROOT_DIR, 'cli', 'engine', 'detect-antipatterns-browser.js');
if (fs.existsSync(detectorSrc)) {
const jsDir = path.join(ROOT_DIR, 'public', 'js');
const jsDir = path.join(ROOT_DIR, 'site', 'public', 'js');
fs.mkdirSync(jsDir, { recursive: true });
fs.copyFileSync(detectorSrc, path.join(jsDir, 'detect-antipatterns-browser.js'));
}
@@ -727,10 +635,10 @@ async function build() {
await createAllZips(DIST_DIR);
// Generate static API data and Cloudflare Pages config
// Write API data and CF config to public/ so Astro copies them to build/.
// Write API data and CF config to site/public/ so Astro copies them to build/.
// Astro wipes build/ before writing, so anything written directly to build/
// during build:skills would be destroyed when build:site runs.
const publicDir = path.join(ROOT_DIR, 'public');
const publicDir = path.join(ROOT_DIR, 'site', 'public');
generateApiData(publicDir, skills, patterns);
generateCFConfig(publicDir);
+9 -23
View File
@@ -19,7 +19,7 @@ import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT_DIR = path.resolve(__dirname, '..');
const OUTPUT_PATH = path.join(ROOT_DIR, 'public', 'og-image.jpg');
const OUTPUT_PATH = path.join(ROOT_DIR, 'site', 'public', 'og-image.jpg');
const EXTENSION_IMAGE_PATH = path.join(
ROOT_DIR,
'public',
@@ -27,29 +27,15 @@ const EXTENSION_IMAGE_PATH = path.join(
'extension-detection.png',
);
// Count user-invocable, non-deprecated skills from source/skills/
// (In v2.0, commands and skills were unified — every command is a skill.)
// Count sub-commands from skill/scripts/command-metadata.json (the post-v3.0
// single source of truth). Commands and skills were unified in v2.0; v3.0
// then collapsed to a single user-invocable skill (`impeccable`) with
// sub-commands listed in command-metadata.json.
function getCommandCount() {
const skillsDir = path.join(ROOT_DIR, 'source', 'skills');
if (!fs.existsSync(skillsDir)) return 0;
let count = 0;
for (const entry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const skillFile = path.join(skillsDir, entry.name, 'SKILL.md');
if (!fs.existsSync(skillFile)) continue;
const content = fs.readFileSync(skillFile, 'utf8');
const fm = content.match(/^---\n([\s\S]*?)\n---/);
if (!fm) continue;
const frontmatter = fm[1];
const isUserInvocable = /^user-invocable:\s*true\s*$/m.test(frontmatter);
const isDeprecated = /^description:\s*["']?DEPRECATED/mi.test(frontmatter);
if (isUserInvocable && !isDeprecated) count++;
}
return count;
const metadataPath = path.join(ROOT_DIR, 'skill', 'scripts', 'command-metadata.json');
if (!fs.existsSync(metadataPath)) return 0;
const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
return Object.keys(metadata).length;
}
// Load extension screenshot as base64 data URL so setContent is self-contained
-156
View File
@@ -1,156 +0,0 @@
/**
* Markdown → HTML rendering for sub-pages.
*
* Wraps `marked` with a custom link renderer that resolves cross-references
* between skill bodies and their references, and emits stable heading slugs
* so anti-pattern → skill section anchors work.
*
* Skeleton in commit 1. Link resolution and heading slugger are wired up in
* commit 3 (skills generator) when the data model lands.
*/
import { marked } from 'marked';
/**
* Slugify a heading text into a stable anchor id.
* Matches the convention: lowercase, strip non-alphanum, spaces → dashes.
*
* @param {string} text
* @returns {string}
*/
export function slugify(text) {
return String(text)
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/[\s_]+/g, '-')
.replace(/^-+|-+$/g, '');
}
/**
* Build a marked renderer configured for impeccable's skill/tutorial bodies.
*
* @param {object} opts
* @param {Set<string>} [opts.knownSkillIds] - slugs of skills the site knows about; unknown /name mentions render as plain text
* @param {string} [opts.currentSkillId] - when rendering a skill body, resolve `reference/foo.md` to `#reference-foo` on the current page
* @returns {import('marked').Renderer}
*/
export function createRenderer({ knownSkillIds = new Set(), currentSkillId = null } = {}) {
const renderer = new marked.Renderer();
// Heading slugger — stable ids so we can anchor-link from elsewhere.
// Supports {#custom-id} suffix (kramdown/pandoc style) for explicit anchors.
renderer.heading = ({ tokens, depth }) => {
const raw = tokens.map((t) => t.raw || '').join('');
const customIdMatch = raw.match(/\s*\{#([a-z0-9_-]+)\}\s*$/i);
let id, text;
if (customIdMatch) {
id = customIdMatch[1];
// Strip the {#id} suffix from the rendered text
const cleanRaw = raw.slice(0, customIdMatch.index);
text = renderer.parser.parseInline(marked.lexer(cleanRaw, { gfm: true })[0]?.tokens || tokens);
} else {
id = slugify(raw);
text = renderer.parser.parseInline(tokens);
}
return `<h${depth} id="${id}">${text}</h${depth}>\n`;
};
// Link resolver.
renderer.link = ({ href, title, tokens }) => {
const text = renderer.parser.parseInline(tokens);
const resolved = resolveHref(href, { knownSkillIds, currentSkillId });
const titleAttr = title ? ` title="${escapeAttr(title)}"` : '';
const relAttr = resolved.external ? ' target="_blank" rel="noopener"' : '';
return `<a href="${escapeAttr(resolved.href)}"${titleAttr}${relAttr}>${text}</a>`;
};
// Fenced code blocks — minimal glass-terminal styling, no syntax highlighter in v1.
// Wrapped in a container with a copy button; click handling lives in the
// page-level inline script added by render-page.js.
renderer.code = ({ text, lang }) => {
const langClass = lang ? ` code-block--${escapeAttr(lang)}` : '';
const copyValue = escapeAttr(text);
return `<div class="code-block-wrap"><pre class="code-block${langClass}"><code>${escapeHtml(text)}</code></pre><button class="code-block-copy" type="button" data-copy="${copyValue}" aria-label="Copy to clipboard"></button></div>\n`;
};
return renderer;
}
/**
* Resolve a markdown link href against the site's URL scheme.
*
* - `http(s)://…` → unchanged, external
* - `reference/foo.md` → `#reference-foo` on current skill page
* - `/skill-id` (known) → `/docs/skill-id`
* - `#anchor` → unchanged (in-page anchor)
* - anything else → unchanged (will be caught by build warnings later)
*
* @param {string} href
* @param {{ knownSkillIds: Set<string>, currentSkillId: string|null }} ctx
* @returns {{ href: string, external: boolean }}
*/
function resolveHref(href, { knownSkillIds, currentSkillId }) {
if (!href) return { href: '', external: false };
// External links
if (/^https?:\/\//i.test(href) || /^mailto:/i.test(href)) {
return { href, external: true };
}
// In-page anchor
if (href.startsWith('#')) {
return { href, external: false };
}
// reference/foo.md → #reference-foo on the current skill page
const refMatch = href.match(/^reference\/([a-z0-9-]+)\.md$/i);
if (refMatch && currentSkillId) {
return { href: `#reference-${refMatch[1].toLowerCase()}`, external: false };
}
// /skill-id mentioned in prose (e.g. "run /polish")
const slashMatch = href.match(/^\/([a-z0-9-]+)$/i);
if (slashMatch && knownSkillIds.has(slashMatch[1])) {
return { href: `/docs/${slashMatch[1]}`, external: false };
}
// [text](other-skill) → /docs/other-skill
if (/^[a-z0-9-]+$/i.test(href) && knownSkillIds.has(href)) {
return { href: `/docs/${href}`, external: false };
}
// Unknown — pass through. Generator can warn separately.
return { href, external: false };
}
/**
* Render a markdown string to HTML.
*
* @param {string} markdown
* @param {object} [opts]
* @param {Set<string>} [opts.knownSkillIds]
* @param {string} [opts.currentSkillId]
* @returns {string} HTML
*/
export function renderMarkdown(markdown, opts = {}) {
const renderer = createRenderer(opts);
return marked.parse(markdown, {
renderer,
gfm: true,
breaks: false,
});
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function escapeAttr(str) {
return String(str).replace(/"/g, '&quot;');
}
+13 -13
View File
@@ -3,11 +3,11 @@
* generators.
*
* Single source of truth:
* - source/skills/{id}/SKILL.md → skill frontmatter + body
* - source/skills/{id}/reference/*.md → skill reference files
* - src/detect-antipatterns.mjs → ANTIPATTERNS array (parsed)
* - content/site/skills/{id}.md → optional editorial wrapper
* - content/site/tutorials/{slug}.md → full tutorial content
* - skill/SKILL.md → skill frontmatter + body
* - skill/reference/*.md → skill reference files
* - cli/engine/detect-antipatterns.mjs → ANTIPATTERNS array (parsed)
* - site/content/skills/{id}.md → optional editorial wrapper
* - site/content/tutorials/{slug}.md → full tutorial content
*/
import fs from 'node:fs';
@@ -19,13 +19,13 @@ import {
VISUAL_EXAMPLES,
LLM_ONLY_RULES,
GALLERY_ITEMS,
} from '../../content/site/anti-patterns-catalog.js';
} from '../../site/data/anti-patterns-catalog.js';
export {
LAYER_LABELS,
LAYER_DESCRIPTIONS,
GALLERY_ITEMS,
} from '../../content/site/anti-patterns-catalog.js';
} from '../../site/data/anti-patterns-catalog.js';
/**
* Skills that should be excluded from the index and not get a detail page.
@@ -137,12 +137,12 @@ export const COMMAND_RELATIONSHIPS = {
};
/**
* Parse the ANTIPATTERNS array out of src/detect-antipatterns.mjs.
* Parse the ANTIPATTERNS array out of cli/engine/detect-antipatterns.mjs.
* Mirrors the trick in scripts/build.js validateAntipatternRules() so we
* don't have to run the browser-only module.
*/
export function readAntipatternRules(rootDir) {
const detectPath = path.join(rootDir, 'src/detect-antipatterns.mjs');
const detectPath = path.join(rootDir, 'cli/engine/detect-antipatterns.mjs');
const src = fs.readFileSync(detectPath, 'utf-8');
const match = src.match(/const ANTIPATTERNS = \[([\s\S]*?)\n\];/);
if (!match) {
@@ -170,7 +170,7 @@ export function readEditorialWrapper(contentDir, kind, slug) {
* should treat a missing entry as "no demo".
*/
export async function loadCommandDemos(rootDir) {
const demosDir = path.join(rootDir, 'public/js/demos/commands');
const demosDir = path.join(rootDir, 'site/public/js/demos/commands');
if (!fs.existsSync(demosDir)) return {};
const demos = {};
@@ -210,7 +210,7 @@ export async function loadCommandDemos(rootDir) {
*/
export async function buildSubPageData(rootDir) {
const { skills: rawSkills } = readSourceFiles(rootDir);
const contentDir = path.join(rootDir, 'content/site');
const contentDir = path.join(rootDir, 'site/content');
const commandDemos = await loadCommandDemos(rootDir);
// After the v3.0 consolidation there's only one source skill (impeccable).
@@ -218,7 +218,7 @@ export async function buildSubPageData(rootDir) {
// We synthesize a virtual skill entry for each sub-command so the sub-page
// generators can keep rendering per-command pages, index cards, etc.
const impeccableSkill = rawSkills.find((s) => s.name === 'impeccable');
const metadataPath = path.join(rootDir, 'source/skills/impeccable/scripts/command-metadata.json');
const metadataPath = path.join(rootDir, 'skill/scripts/command-metadata.json');
let commandMetadata = {};
if (fs.existsSync(metadataPath)) {
commandMetadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8'));
@@ -310,7 +310,7 @@ export async function buildSubPageData(rootDir) {
}));
const rules = [...detectedRules, ...llmRules];
// Tutorials: each required file in content/site/tutorials/.
// Tutorials: each required file in site/content/tutorials/.
const tutorialsDir = path.join(contentDir, 'tutorials');
const tutorials = [];
if (fs.existsSync(tutorialsDir)) {
+59 -72
View File
@@ -153,85 +153,72 @@ export function readFilesRecursive(dir, fileList = []) {
}
/**
* Read and parse all source files (unified skills architecture)
* All source lives in source/skills/{name}/SKILL.md
* Returns { skills } where each skill has userInvocable flag
* 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 skillsDir = path.join(rootDir, 'source/skills');
const skillDir = path.join(rootDir, 'skill');
const skills = [];
if (fs.existsSync(skillsDir)) {
const entries = fs.readdirSync(skillsDir, { withFileTypes: true });
const skillMdPath = path.join(skillDir, 'SKILL.md');
if (!fs.existsSync(skillMdPath)) {
return { skills };
}
for (const entry of entries) {
const entryPath = path.join(skillsDir, entry.name);
const content = fs.readFileSync(skillMdPath, 'utf-8');
const { frontmatter, body } = parseFrontmatter(content);
if (entry.isDirectory()) {
// Directory-based skill with potential references
const skillMdPath = path.join(entryPath, 'SKILL.md');
if (fs.existsSync(skillMdPath)) {
const content = fs.readFileSync(skillMdPath, 'utf-8');
const { frontmatter, body } = parseFrontmatter(content);
// Read reference files if they exist
const references = [];
const referenceDir = path.join(entryPath, '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);
const refContent = fs.readFileSync(refPath, 'utf-8');
references.push({
name: path.basename(refFile, '.md'),
content: refContent,
filePath: refPath
});
}
}
// Read script files if they exist. 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(entryPath, '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);
const scriptContent = fs.readFileSync(scriptPath, 'utf-8');
scripts.push({
name: scriptFile,
content: scriptContent,
filePath: scriptPath
});
}
}
skills.push({
name: frontmatter.name || entry.name,
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
});
}
}
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 };
}
@@ -269,7 +256,7 @@ export function writeFile(filePath, content) {
* - Prose form: `DO …` / `DO NOT …`
*
* Defaults to the main impeccable SKILL.md but accepts any relative path so
* rules in `src/detect-antipatterns.mjs` can anchor to register-specific
* 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.
*
@@ -369,7 +356,7 @@ export function readPatterns(_rootDir, _relativePath) {
// Previous SKILL.md parser retained below but disabled; kept as a
// reference for how prefix-style extraction used to work.
function _legacyReadPatterns(rootDir, relativePath = 'source/skills/impeccable/SKILL.md') {
function _legacyReadPatterns(rootDir, relativePath = 'skill/SKILL.md') {
const skillPath = path.join(rootDir, relativePath);
if (!fs.existsSync(skillPath)) {
+2 -2
View File
@@ -15,8 +15,8 @@ import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT_DIR = path.resolve(__dirname, '..');
const EXAMPLES_DIR = path.join(ROOT_DIR, 'public', 'antipattern-examples');
const OUTPUT_DIR = path.join(ROOT_DIR, 'public', 'antipattern-images');
const EXAMPLES_DIR = path.join(ROOT_DIR, 'site', 'public', 'antipattern-examples');
const OUTPUT_DIR = path.join(ROOT_DIR, 'site', 'public', 'antipattern-images');
async function screenshotAntipatterns() {
// Ensure output directory exists