Files
paperclip-docs/scripts/verify-skill-source-blocks.mjs
c7b3f4cacf Render full SKILL.md as a code snippet on per-skill pages (PAP-16980) (#89)
> **Updated on current main:** #87 and the #90 cache hotfix are merged.
This PR now targets `main`, was rebased onto merge commit `8c5976f`, and
has a fresh successful Cloudflare preview plus post-rebase browser smoke
evidence.

## What & why (PAP-16980)

Improves SEO/AEO on the bundled/optional **per-skill reference pages**
(from PAP-16670) by clearly separating the *human-readable catalog
summary* (top of page) from the *authoritative full skill definition*.

Previously the "Full skill definition" section rendered the `SKILL.md`
as **parsed Markdown**, so each skill's own `##` headings, lists, and
fenced examples became real page content — competing with the summary,
inflating the on-page TOC (e.g. qa-acceptance went from **16 → 6** "On
this page" entries), and confusing crawlers/answer engines about the
page's true structure.

Now each per-skill page shows the **complete, verbatim `SKILL.md`**
(frontmatter + body) inline, rendered through the **existing production
code-snippet treatment**.

## Changes

- **Content (10 per-skill pages):** replaced the old `### Skill
frontmatter` bullets + parsed `### Skill instructions` layout with the
full `SKILL.md` embedded in a fenced ````markdown skill-source` block.
Source bytes were taken verbatim from each skill's authoritative
`SKILL.md` at the page's pinned `paperclip_version`, verified against
the page's own prior instructions body + frontmatter (name/description)
so no content drifted.
- **Renderers (`site/build-release.mjs`, `site/app.js`):** a
`skill-source` fence renders as `<pre><code class="language-markdown"
data-skill-download="SKILL.md">`. Every other code block is delegated to
marked's default renderer, so existing snippets are byte-for-byte
unchanged. Rendered identically in the crawler-visible build HTML and on
client SPA navigation.
- **Copy + Download (`site/app.js`, `site/styles.css`):**
`decorateCodeBlocks` reuses the existing Copy affordance and adds a
**Download `SKILL.md`** control beside it. Both share dimensions,
styling, hover/focus visibility, and the copied-success state; both
carry accessible labels/titles.
- **Readable full-source wrapping (`site/styles.css`):** only the
downloadable `SKILL.md` block uses `white-space: pre-wrap` and safe
long-token wrapping. Ordinary code snippets retain the existing
horizontal-scroll treatment.
- **Test:** `scripts/verify-skill-source-blocks.mjs` (`npm run
docs:test:skill-source-blocks`) asserts the render contract (single H1,
single `<pre>`, frontmatter present, no legacy headings) and that
ordinary docs pages emit no `data-skill-download`.

## Scope statement

No catalog-page layout, navigation, typography, summary-copy,
metadata-card, or information-architecture changes. `paperclip-website`
and generated `.site/` output are untouched. `optional/finance/ramp.md`
is intentionally excluded — it is a newer summary page with no embedded
full-definition section to reformat. The diff is the 10 skill pages +
the narrow renderer/Copy-Download support + the test.

## Evidence

**1–2. Before/after (desktop, 1280×900) + mobile after (390×844)** —
attached to Paperclip issue
[PAP-16980](https://paperclip-dev.tail29c1aa.ts.net/PAP/issues/3098577a-4f6f-4eb2-9151-a4b61917dffd)
(`before-desktop.png`, `after-desktop-controls.png`,
`after-controls-zoom.png`, `after-mobile.png`). GitHub cannot render the
auth-gated attachment URLs inline, so they live on the issue for
reviewers.

**4. Raw DOM/HTML (build output, qa-acceptance):**
- Article renders exactly **one H1**: `<h1 id="qa-acceptance">QA
Acceptance</h1>`
- Full source inside a single code block:
```html
<pre><code class="language-markdown" data-skill-download="SKILL.md">---
name: qa-acceptance
description: Produce QA acceptance criteria and a manual validation plan …
key: paperclipai/bundled/quality/qa-acceptance
recommendedForRoles:
  - qa
  …
</code></pre>
```
- Article `<pre>` count: **1** (inner ````` fences stay literal — no
breakout). 10/10 skill pages carry the block; 0 non-skill pages do.

**5. Copy + Download behavior (Playwright against the built site):**
```json
{
  "downloadFilename": "SKILL.md",
  "downloadMatchesBlock": true,     // downloaded file === code block text, byte-identical
  "downloadBytes": 3853,
  "copyShowsSuccess": true,          // Copy toggles the existing is-copied success state
  "accessibleLabels": { "copy": "Copy code", "download": "Download SKILL.md" }
}
```
Both controls reach `opacity: 1` on `.code-wrap:hover` and on keyboard
`:focus-visible` (verified `matches(':focus-visible') === true` →
computed opacity `1`).

**H1 audit (every generated route, incl. all skill URLs — requested on
the issue):** built the site on current `main` and scanned **all 184
generated `index.html` routes** (16 skill routes among them). **Every
route has exactly one `<h1>`.** The skill source's own `#`/`##` headings
live *inside* the `<pre><code>` block as literal text, so they do
**not** create competing H1s — the SEO/AEO goal.

## Tests

Run against current `main` after #87 and #90:

```
docs:build ............................. ok (184 routes)
docs:test:static-routes ................ pass (5 routes + 404 + root + subpath)
docs:test:skill-source-blocks .......... pass (10 skill pages, 1 control page)
H1 audit (all 184 routes) .............. pass (exactly 1 h1 each; 16 skill routes)
```

**Do not merge/deploy** — returning to Dotta/reviewers for approval per
PAP-16980.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: DevRel Gemini <[email protected]>
Co-authored-by: Paperclip <[email protected]>
2026-08-10 14:03:47 -07:00

135 lines
6.2 KiB
JavaScript

#!/usr/bin/env node
// Verifies the per-skill reference pages render their authoritative SKILL.md as
// a single markdown code block that reuses the production code-snippet treatment
// and exposes a Download control, without disturbing any other code snippet.
//
// Contract checked here (see PAP-16980):
// * Every per-skill page with a "## Full skill definition" section embeds the
// complete SKILL.md inside a fenced ```` ```markdown skill-source ```` block.
// * That block renders to <pre><code class="language-markdown"
// data-skill-download="SKILL.md"> in the crawler-visible HTML.
// * The full source is a single code block (inner ``` fences stay literal).
// * The page keeps exactly one H1, and the old parsed-markdown
// "### Skill frontmatter" / "### Skill instructions" layout is gone.
// * Ordinary code snippets are untouched (no stray Download affordance).
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parseFrontmatter, renderStaticMarkdown } from "../site/build-release.mjs";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const root = path.resolve(__dirname, "..");
const skillsRoot = path.join(root, "docs", "reference", "skills");
const CODE_OPEN = '<pre><code class="language-markdown" data-skill-download="SKILL.md">';
async function walk(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === "screenshots") continue;
files.push(...(await walk(full)));
} else if (entry.name.endsWith(".md")) {
files.push(full);
}
}
return files;
}
function fenceBlocks(markdown) {
// Match fenced blocks of >= 3 backticks whose info string carries the
// `skill-source` marker, closed by a fence of at least the same length.
const re = /(^|\n)(`{3,})([^\n]*)\n([\s\S]*?)\n\2`*(?=\n|$)/g;
const blocks = [];
let m;
while ((m = re.exec(markdown)) !== null) {
const info = m[3].trim().split(/\s+/);
if (info.includes("skill-source")) blocks.push({ info: m[3].trim(), body: m[4] });
}
return blocks;
}
let checkedSkillPages = 0;
let checkedControlBlocks = 0;
const failures = [];
const files = await walk(skillsRoot);
for (const file of files) {
const rel = path.relative(root, file);
const raw = await fs.readFile(file, "utf8");
const { body } = parseFrontmatter(raw);
if (!/^## Full skill definition$/m.test(body)) continue; // index pages / ramp-style summaries
checkedSkillPages += 1;
try {
const blocks = fenceBlocks(body);
assert.equal(blocks.length, 1, `expected exactly one skill-source block, found ${blocks.length}`);
const block = blocks[0];
assert.match(block.info, /^markdown\b/, `skill-source fence should be tagged "markdown", got "${block.info}"`);
assert.match(block.body, /^---\n/, "embedded SKILL.md should begin with YAML frontmatter");
assert.match(block.body, /\nname:\s*\S/, "embedded SKILL.md frontmatter should carry a name");
// The legacy parsed-markdown layout must be gone.
assert.doesNotMatch(body, /^### Skill frontmatter$/m, "leftover '### Skill frontmatter' heading");
assert.doesNotMatch(body, /^### Skill instructions$/m, "leftover '### Skill instructions' heading");
const html = renderStaticMarkdown(body);
const h1Count = (html.match(/<h1\b/g) || []).length;
assert.equal(h1Count, 1, `page should render a single H1, found ${h1Count}`);
const open = html.indexOf(CODE_OPEN);
assert.notEqual(open, -1, `rendered HTML missing ${CODE_OPEN}`);
// The whole SKILL.md — including its own ``` fences — must collapse into a
// single code block; a breakout would produce extra <pre>/<code> elements.
assert.equal((html.match(/<pre>/g) || []).length, 1, "skill source must render as exactly one <pre>");
assert.equal((html.match(/data-skill-download="SKILL.md"/g) || []).length, 1, "exactly one downloadable skill block");
const close = html.indexOf("</code></pre>", open);
const segment = html.slice(open, close);
assert.ok(segment.includes("name:"), "rendered skill source should include frontmatter");
// The Given/when/then and fenced snippets inside SKILL.md must be escaped, not re-parsed.
assert.ok(!segment.includes("<h2"), "SKILL.md headings must stay literal inside the code block");
} catch (error) {
failures.push(`${rel}: ${error.message}`);
}
}
// A control page with an ordinary code fence must not gain a Download affordance.
const controlPath = path.join(root, "docs", "how-to", "write-a-company-skill.md");
try {
const control = await fs.readFile(controlPath, "utf8");
const { body } = parseFrontmatter(control);
const html = renderStaticMarkdown(body);
checkedControlBlocks += 1;
assert.ok(!html.includes("data-skill-download"), "ordinary docs pages must not emit data-skill-download");
} catch (error) {
failures.push(`write-a-company-skill.md (control): ${error.message}`);
}
// Full skill source is prose-heavy and can contain very long argument hints,
// URLs, and examples. It should preserve source line breaks while wrapping
// within the viewport; ordinary code blocks retain horizontal scrolling.
try {
const styles = await fs.readFile(path.join(root, "site", "styles.css"), "utf8");
const skillRule = styles.match(/#article pre code\[data-skill-download="SKILL\.md"\]\s*\{([\s\S]*?)\}/);
assert.ok(skillRule, "missing skill-source-specific wrapping rule");
assert.match(skillRule[1], /white-space:\s*pre-wrap/, "skill source must preserve line breaks while wrapping");
assert.match(skillRule[1], /overflow-wrap:\s*anywhere/, "skill source must wrap long unbroken values");
} catch (error) {
failures.push(`site/styles.css (skill source wrapping): ${error.message}`);
}
if (failures.length) {
console.error("Skill source block verification FAILED:\n" + failures.map((f) => ` - ${f}`).join("\n"));
process.exit(1);
}
assert.ok(checkedSkillPages >= 10, `expected at least 10 per-skill pages, checked ${checkedSkillPages}`);
console.log(`Skill source block verification passed (${checkedSkillPages} skill pages, ${checkedControlBlocks} control page).`);