An agent skill for creating detailed, interactive isometric illustrations of real-world machines and complex systems. Generates polished SVGs with optional WebGL shaders and 3D effects.
Share figures in the community gallery: scripts/publish.mjs and references/publish.md
R.140360be2e4e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 89ba272..aeaad41 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ All notable changes to Anatomy are recorded here. The format follows [Keep a Cha### Added+- `scripts/publish.mjs` and `references/publish.md`: share a finished framework-free figure in the community gallery, `wheresryan22/anatomy-figures`. The script copies the figure, points its kit imports at the gallery's `.skill/` link, records the kit fingerprint (`scripts/fingerprint.mjs`) so the gallery can rebuild it with the same kit version, rebuilds the pages and takes the poster. It never pushes.- OpenCode and Codex support, alongside Claude Code. `SKILL.md` exposes `/anatomy` to OpenCode through `metadata`, `agents/openai.yaml` gives Codex its display name, and the README, CONTRIBUTING and the bug report form cover all three agents.- `examples/arcade-cabinet/`, an upright arcade cabinet with its side panel off. A quarter rolls down the coin chute past the coin-switch wire into the cash box, the switch's pulse runs along its cable to the board, and the CRT warms up, self-tests and runs an attract mode drawn in the plane of the tilted monitor; the stick closes a microswitch under the panel. It draws in the light and dark themes and passes `--audit`.- `examples/spot-plate/`, a second React figure from the same site as `test-rig`: six pairs of glass drops that run together into one piece of glass as a fan of feeler blades sets `merge`. It draws in the light and dark themes.diff --git a/README.md b/README.mdindex 36316d8..065b584 100644--- a/README.md+++ b/README.md@@ -301,6 +301,10 @@ anatomy/> [!NOTE]> **The 3D mode is beta.** It is proved on its example and one test figure, not yet on a production figure. A small 3D figure runs at 60 fps; the 380-part stress hand measured about 20 fps at 1440 px wide and 13 to 15 fps on a throttled phone profile, on a heavily loaded machine.+## Share a figure++Made something good? Ask your agent to publish it to the community gallery, [anatomy-figures](https://github.com/wheresryan22/anatomy-figures), or run `scripts/publish.mjs` yourself. It prepares the figure in your clone of the gallery and prints the commands to open a pull request; it never pushes for you. The gallery's own [CONTRIBUTING.md](https://github.com/wheresryan22/anatomy-figures/blob/main/CONTRIBUTING.md) has the steps.+## ContributingIssues and pull requests are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) first: it covers building the examples, the checks, and the house rules a change has to keep (among them, no comments in code, and kit changes that leave every existing example byte-identical). Please follow the [Code of Conduct](CODE_OF_CONDUCT.md), and report security problems as described in [SECURITY.md](SECURITY.md).diff --git a/SKILL.md b/SKILL.mdindex 1409108..aad98be 100644--- a/SKILL.md+++ b/SKILL.md@@ -170,3 +170,4 @@ Read these as you need them:- `references/webgl.md`: shaders inside the drawing: when one earns its place, the layer stack, the camera contract, ray-marching in the iso camera, the full API with a minimal page, the craft rules with the bugs that taught them, the light theme (inks on paper, per-phenomenon recipes, the reviewers' faults), and how to verify them.- `references/walkthrough.md`: how the test rig was designed, step by step, from concept to code.- `references/3d.md`: the optional 3D mode: groups and poses, live layers, convex parts and their rules, materials, free groups, hinge chains, painter's order, static clutter around a turntable, shaders that follow the turn, the orbit audit, browser checks, performance and limits.+- `references/publish.md`: sharing a finished figure in the community gallery with `scripts/publish.mjs`, only when the user asks; nothing is pushed for them.diff --git a/references/publish.md b/references/publish.mdnew file mode 100644index 0000000..fca9ce6--- /dev/null+++ b/references/publish.md@@ -0,0 +1,39 @@+# Publishing a figure to the community gallery++The community gallery is the repository `wheresryan22/anatomy-figures`. People share framework-free figures there: a build script that writes standalone pages next to itself, as the skill's examples do. React and Next.js figures can't be published yet.++Publish only when the user asks to share or publish a figure. Never push, fork or open a pull request yourself: prepare everything locally, show it, and give the user the commands to run.++## Steps++1. **Check the figure is finished.** Its pages are built and up to date, the line check passes, and `--audit` passes if it has pipes, cables or round parts. A figure that fails these will fail the gallery's checks too.+2. **Ask the user for what only they can give:**+ - their GitHub username (the author);+ - a title (at most 80 characters);+ - the license: MIT (the default) or CC-BY-4.0;+ - confirmation that it is their own work and they are happy to share it.+ The prompt is the request that made the figure; reuse it, trimmed to 600 characters.+3. **Get a local clone of the gallery.** If the user has none, give them the commands to fork and clone it (`gh repo fork wheresryan22/anatomy-figures --clone`), and wait.+4. **Publish into the clone:**+ ```sh+ node <skill>/scripts/publish.mjs <figure folder> --into <clone> --id <kebab-id> \+ --title "..." --author <github user> --prompt "..." \+ [--agent "Claude Code"|OpenCode|Codex|Other] [--model "..."] [--license MIT|CC-BY-4.0] \+ [--tags a,b] [--audit] [--pages dark.html,light.html]+ ```+ Pass `--agent` for the agent you are running in. It copies the figure's source into `figures/<id>/src/`, points its kit imports at the clone's `.skill/` link, records the kit fingerprint, rebuilds the pages there and takes `poster.png`.+ - If it says a file reaches outside the figure folder and the skill, copy what that file needs into the figure folder, rebuild, and publish again.+ - If it can't tell which pages are the figure, pass `--pages`.+5. **Validate inside the clone:** `node scripts/validate.mjs figures/<id>` must end `passed`. Fix what it names. It runs the same checks as the gallery's CI, which also fetches the exact skill version from GitHub.+6. **Show the user** the poster and the result, then give them the git and `gh` commands the publish script printed. They run them.++## What the gallery rejects++- network calls or outside addresses;+- `eval` or `new Function`;+- frames, cookies, or reaching the page around the figure;+- build imports other than the skill, the figure's own files and `node:fs`, `node:path`, `node:url`, `node:crypto` or `node:process`;+- reading environment variables;+- files other than source text under `src/`;+- pages that the build does not reproduce exactly.+Write figures that way from the start if the user plans to share them.diff --git a/scripts/fingerprint.mjs b/scripts/fingerprint.mjsnew file mode 100644index 0000000..a641496--- /dev/null+++ b/scripts/fingerprint.mjs@@ -0,0 +1,31 @@+import { createHash } from "node:crypto";+import { readdirSync, readFileSync, statSync } from "node:fs";+import { join, relative, sep } from "node:path";++export const KIT_FILES = (path) => path === "scripts/inline-kit.mjs" || (path.startsWith("kit/") && !path.split("/").some((part) => part.startsWith(".")));++const sha256 = (data) => createHash("sha256").update(data).digest("hex");++export function fingerprintOf(entries) {+ const lines = entries+ .filter(([path]) => KIT_FILES(path))+ .map(([path, content]) => `${path}\0${sha256(content)}\n`)+ .sort();+ if (!lines.length) throw new Error("fingerprint: no kit files found");+ return `sha256:${sha256(lines.join(""))}`;+}++function walk(root, dir = root, out = []) {+ for (const name of readdirSync(dir)) {+ const full = join(dir, name);+ const stat = statSync(full);+ if (stat.isDirectory()) walk(root, full, out);+ else if (stat.isFile()) out.push(relative(root, full).split(sep).join("/"));+ }+ return out;+}++export function fingerprintOfSkill(skillRoot) {+ const files = [...walk(join(skillRoot, "kit")).map((path) => `kit/${path}`), "scripts/inline-kit.mjs"];+ return fingerprintOf(files.map((path) => [path, readFileSync(join(skillRoot, path))]));+}diff --git a/scripts/publish.mjs b/scripts/publish.mjsnew file mode 100644index 0000000..b4cee9b--- /dev/null+++ b/scripts/publish.mjs@@ -0,0 +1,203 @@+import { spawnSync } from "node:child_process";+import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";+import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";+import { fileURLToPath } from "node:url";+import { fingerprintOfSkill } from "./fingerprint.mjs";++const SKILL = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const SOURCE_TYPES = [".mjs", ".js", ".css", ".html", ".json", ".md", ".txt", ".svg"];+const SKIP_DIRS = ["node_modules", "shots", ".git"];+const ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;+const AGENTS = ["Claude Code", "OpenCode", "Codex", "Other"];+const KINDS = ["SVG", "SVG + WebGL", "SVG + 3D", "SVG + WebGL + 3D"];++const posix = (path) => path.split(sep).join("/");+const inside = (root, path) => path === root || path.startsWith(root + sep);++function usage(message) {+ if (message) console.error(`publish: ${message}\n`);+ console.log(`Copy a figure into a local clone of the community gallery, ready for a pull request.++ node scripts/publish.mjs <figure folder> --into <anatomy-figures clone> --id <kebab-id> --title "..." --prompt "..." --author <github user>+ [--agent "Claude Code"|OpenCode|Codex|Other] [--model "..."] [--license MIT|CC-BY-4.0] [--tags a,b]+ [--build build.mjs] [--pages dark.html,light.html] [--kind "SVG + WebGL"] [--audit] [--no-poster] [--force]++The figure must be framework-free: a build script that writes standalone pages next to itself.+Nothing is pushed: the command prints the git and gh commands to run when you are ready.`);+ process.exit(message ? 1 : 0);+}++function parse(argv) {+ const options = { agent: "Claude Code", license: "MIT", build: "build.mjs", tags: [] };+ const take = (index) => {+ const value = argv[index + 1];+ if (value === undefined || value.startsWith("--")) usage(`${argv[index]} needs a value`);+ return value;+ };+ for (let index = 0; index < argv.length; index++) {+ const arg = argv[index];+ if (arg === "--help" || arg === "-h") usage();+ else if (["--into", "--id", "--title", "--prompt", "--author", "--agent", "--model", "--license", "--build", "--kind", "--date"].includes(arg)) options[arg.slice(2)] = take(index++);+ else if (arg === "--tags") options.tags = take(index++).split(",").map((tag) => tag.trim()).filter(Boolean);+ else if (arg === "--pages") options.pages = take(index++).split(",").map((page) => page.trim());+ else if (arg === "--audit") options.audit = true;+ else if (arg === "--no-poster") options.noPoster = true;+ else if (arg === "--force") options.force = true;+ else if (arg.startsWith("--")) usage(`unknown option ${arg}`);+ else if (!options.source) options.source = arg;+ else usage(`unexpected argument ${arg}`);+ }+ for (const key of ["source", "into", "id", "title", "prompt", "author"]) if (!options[key]) usage(`missing ${key === "source" ? "the figure folder" : `--${key}`}`);+ if (!ID.test(options.id)) usage("--id must be kebab-case, like token-bucket-bench");+ if (!AGENTS.includes(options.agent)) usage(`--agent must be one of: ${AGENTS.join(", ")}`);+ if (options.kind && !KINDS.includes(options.kind)) usage(`--kind must be one of: ${KINDS.join(", ")}`);+ return options;+}++function listFiles(root, dir = root, out = []) {+ for (const name of readdirSync(dir).sort()) {+ const full = join(dir, name);+ const stat = lstatSync(full);+ if (name.startsWith(".") || stat.isSymbolicLink()) continue;+ if (stat.isDirectory()) {+ if (!SKIP_DIRS.includes(name)) listFiles(root, full, out);+ } else out.push(posix(relative(root, full)));+ }+ return out;+}++function detectPages(source, files, given) {+ if (given) {+ const [dark, light] = given;+ return { dark: dark || undefined, light: light || undefined };+ }+ const html = files.filter((file) => !file.includes("/") && file.endsWith(".html"));+ const pairs = html.filter((file) => !file.endsWith("-light.html") && html.includes(file.replace(/\.html$/, "-light.html")));+ if (pairs.length === 1) return { dark: pairs[0], light: pairs[0].replace(/\.html$/, "-light.html") };+ const singles = html.filter((file) => !/-(light|verify)\.html$/.test(file));+ if (!pairs.length && singles.length === 1) return { dark: singles[0] };+ throw new Error(`can't tell which pages are the figure (found: ${html.join(", ") || "none"}); pass --pages dark.html,light.html`);+}++function detectKind(text) {+ const webgl = /getContext\(\s*["']webgl2?["']|\bGLSL_ISO\b|\bglLayer\b/.test(text);+ const turning = /\bTURN\.mount\b|\bturnScript\b|\bTURN_CSS\b|class="[^"]*iso-turn/.test(text);+ return `SVG${webgl ? " + WebGL" : ""}${turning ? " + 3D" : ""}`;+}++export function rewriteSkillPaths(text, { fromDir, toDir, source, skill, skillLink }) {+ const outside = [];+ const rewritten = text.replace(/(["'])((?:\.{1,2}\/|\/)[^"'\n]*)\1/g, (literal, quote, path) => {+ const target = resolve(fromDir, path);+ const dotted = (from, to) => {+ const r = posix(relative(from, to));+ return r.startsWith(".") ? r : `./${r}`;+ };+ if (!/\.[a-z]+$/i.test(path) && !inside(skill, target)) return literal;+ if (inside(source, target)) return isAbsolute(path) ? `${quote}${dotted(fromDir, target)}${quote}` : literal;+ if (inside(skill, target)) return `${quote}${dotted(toDir, join(skillLink, relative(skill, target)))}${quote}`;+ if (/\.(m?js|css|json|html|svg)$/.test(path)) outside.push(path);+ return literal;+ });+ return { text: rewritten, outside };+}++function run(args, cwd) {+ const result = spawnSync(process.execPath, args, { cwd, encoding: "utf8", maxBuffer: 64 << 20 });+ if (result.status !== 0) throw new Error(`${args.map((a) => basename(a)).join(" ")} failed:\n${`${result.stdout}${result.stderr}`.trim().split("\n").slice(-12).join("\n")}`);+ return result.stdout;+}++export function publish(options) {+ const source = resolve(options.source);+ const repo = resolve(options.into);+ if (!existsSync(join(source, options.build))) throw new Error(`no ${options.build} in ${source}`);+ if (!existsSync(join(repo, "figures")) || !existsSync(join(repo, "scripts", "validate.mjs"))) throw new Error(`${repo} doesn't look like a clone of anatomy-figures (no figures/ or scripts/validate.mjs)`);+ if (inside(SKILL, source) && !inside(join(SKILL, "examples"), source)) throw new Error("the figure folder is inside the skill itself; publish the folder where the figure was built");+ const dest = join(repo, "figures", options.id);+ if (existsSync(dest)) {+ if (!options.force) throw new Error(`figures/${options.id} already exists; pick another --id or pass --force to replace it`);+ rmSync(dest, { recursive: true, force: true });+ }++ const all = listFiles(source);+ const files = all.filter((file) => SOURCE_TYPES.includes(extname(file).toLowerCase()));+ const skipped = all.filter((file) => !files.includes(file));+ const pages = detectPages(source, files, options.pages);+ for (const page of Object.values(pages)) if (page && !files.includes(page)) throw new Error(`page ${page} not found in ${source}; build the figure first`);++ const skillLink = join(repo, ".skill");+ const kit = fingerprintOfSkill(SKILL);+ const outside = [];+ for (const file of files) {+ const from = join(source, file);+ const to = join(dest, "src", file);+ mkdirSync(dirname(to), { recursive: true });+ if (/\.m?js$/.test(file)) {+ const result = rewriteSkillPaths(readFileSync(from, "utf8"), { fromDir: dirname(from), toDir: dirname(to), source, skill: SKILL, skillLink });+ outside.push(...result.outside.map((path) => `${file}: ${path}`));+ writeFileSync(to, result.text);+ } else cpSync(from, to);+ }+ if (outside.length) {+ rmSync(dest, { recursive: true, force: true });+ throw new Error(`these files reach outside the figure folder and the skill; move what they need into the folder:\n ${outside.join("\n ")}`);+ }++ let linked = "existing";+ if (!existsSync(skillLink)) {+ symlinkSync(SKILL, skillLink, "dir");+ linked = "created";+ } else if (fingerprintOfSkill(skillLink) !== kit) {+ const where = lstatSync(skillLink).isSymbolicLink() ? readlinkSync(skillLink) : skillLink;+ throw new Error(`${repo}/.skill (${where}) is a different kit version than this skill; remove it and run again`);+ }++ const build = [[`src/${options.build}`]];+ if (pages.light) build.push([`src/${options.build}`, "--light"]);+ if (!pages.dark) build.shift();+ for (const command of build) run(command, dest);++ const pageText = Object.values(pages).filter(Boolean).map((page) => readFileSync(join(dest, "src", page), "utf8")).join("\n");+ const figure = {+ id: options.id,+ title: options.title.trim(),+ author: options.author.replace(/^@/, ""),+ prompt: options.prompt.trim(),+ kind: options.kind ?? detectKind(pageText),+ agent: options.agent,+ ...(options.model ? { model: options.model } : {}),+ skill: { kit },+ build,+ pages: Object.fromEntries(Object.entries(pages).filter(([, page]) => page).map(([key, page]) => [key, `src/${page}`])),+ ...(options.audit ? { audit: true } : {}),+ license: options.license,+ ...(options.tags.length ? { tags: options.tags } : {}),+ created: options.date ?? new Date().toISOString().slice(0, 10),+ };+ writeFileSync(join(dest, "figure.json"), JSON.stringify(figure, null, 2) + "\n");++ if (!options.noPoster) {+ const page = join(dest, "src", pages.light ?? pages.dark);+ run([join(SKILL, "scripts", "capture.mjs"), page, "--width", "1200", "--out", join(dest, "poster.png")], dest);+ const size = statSync(join(dest, "poster.png")).size;+ if (size > 600 << 10) throw new Error(`poster.png is ${(size / 1024).toFixed(0)} KB, over 600 KB; retake it smaller with scripts/capture.mjs --width 900`);+ }+ return { dest, figure, skipped, linked };+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const options = parse(process.argv.slice(2));+ try {+ const { dest, figure, skipped, linked } = publish(options);+ const repo = resolve(options.into);+ console.log(`published figures/${figure.id} (${figure.kind}, kit ${figure.skill.kit.slice(7, 19)})`);+ if (skipped.length) console.log(` left out (not a source type): ${skipped.join(", ")}`);+ console.log(` .skill link: ${linked}`);+ console.log(`\nCheck it:\n cd ${repo}\n node scripts/validate.mjs figures/${figure.id}`);+ console.log(`\nWhen you are happy with it, from your fork of anatomy-figures:\n git switch -c figure/${figure.id}\n git add figures/${figure.id}\n git commit -m "Add ${figure.title.replace(/"/g, "'")}"\n git push -u origin figure/${figure.id}\n gh pr create --repo wheresryan22/anatomy-figures --fill`);+ } catch (error) {+ console.error(`publish: ${error.message}`);+ process.exit(1);+ }+}diff --git a/scripts/publish.test.mjs b/scripts/publish.test.mjsnew file mode 100644index 0000000..ea628e7--- /dev/null+++ b/scripts/publish.test.mjs@@ -0,0 +1,61 @@+import assert from "node:assert/strict";+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import test from "node:test";+import { fingerprintOf, fingerprintOfSkill } from "./fingerprint.mjs";+import { publish, rewriteSkillPaths } from "./publish.mjs";++const SKILL = resolve(import.meta.dirname, "..");++function gallery() {+ const repo = mkdtempSync(join(tmpdir(), "anatomy-gallery-"));+ mkdirSync(join(repo, "figures"));+ mkdirSync(join(repo, "scripts"));+ writeFileSync(join(repo, "scripts", "validate.mjs"), "");+ return repo;+}++test("the fingerprint matches the gallery's algorithm", () => {+ assert.equal(fingerprintOf([["kit/a.mjs", "1"], ["kit/b.mjs", "2"], ["scripts/inline-kit.mjs", "3"]]), fingerprintOf([["kit/b.mjs", "2"], ["scripts/inline-kit.mjs", "3"], ["kit/a.mjs", "1"]]));+ assert.equal(fingerprintOf([["kit/a.mjs", "1"], ["kit/b.mjs", "2"], ["scripts/inline-kit.mjs", "3"]]), "sha256:a249319b0f2a8db4899fbb430c782c55b7699df73809c5c0e4c07495c72eae8c");+ assert.match(fingerprintOfSkill(SKILL), /^sha256:[0-9a-f]{64}$/);+});++test("skill paths are rewritten to the gallery's .skill link, and nothing else", () => {+ const source = "/work/fig";+ const text = 'import * as k from "../../kit/iso-kit.mjs";\nimport { kitScript } from "../../scripts/inline-kit.mjs";\nimport "./live.mjs";\nconst x = "/2";';+ const { text: out, outside } = rewriteSkillPaths(text, { fromDir: join(SKILL, "examples", "x"), toDir: "/g/figures/x/src", source: join(SKILL, "examples", "x"), skill: SKILL, skillLink: "/g/.skill" });+ assert.deepEqual(outside, []);+ assert.match(out, /from "\.\.\/\.\.\/\.\.\/\.skill\/kit\/iso-kit\.mjs"/);+ assert.match(out, /from "\.\.\/\.\.\/\.\.\/\.skill\/scripts\/inline-kit\.mjs"/);+ assert.match(out, /import "\.\/live\.mjs"/);+ assert.match(out, /"\/2"/);+ const away = rewriteSkillPaths('import "../../elsewhere/x.mjs";', { fromDir: source, toDir: "/g/figures/x/src", source, skill: SKILL, skillLink: "/g/.skill" });+ assert.deepEqual(away.outside, ["../../elsewhere/x.mjs"]);+});++test("publishing an example rebuilds it byte for byte in the gallery", () => {+ const repo = gallery();+ try {+ const { dest, figure } = publish({ source: join(SKILL, "examples", "dial-indicator"), into: repo, id: "dial-indicator", title: "Dial indicator", prompt: "/anatomy a dial indicator", author: "octo-cat", agent: "Codex", license: "MIT", build: "build.mjs", tags: [], noPoster: true, date: "2026-10-12" });+ assert.equal(figure.kind, "SVG");+ assert.equal(figure.skill.kit, fingerprintOfSkill(SKILL));+ assert.deepEqual(figure.build, [["src/build.mjs"], ["src/build.mjs", "--light"]]);+ assert.deepEqual(figure.pages, { dark: "src/dial-indicator.html", light: "src/dial-indicator-light.html" });+ for (const page of ["dial-indicator.html", "dial-indicator-light.html"]) assert.ok(readFileSync(join(dest, "src", page)).equals(readFileSync(join(SKILL, "examples", "dial-indicator", page))), page);+ assert.ok(existsSync(join(repo, ".skill", "kit", "iso-kit.mjs")));+ assert.throws(() => publish({ source: join(SKILL, "examples", "dial-indicator"), into: repo, id: "dial-indicator", title: "x", prompt: "x", author: "x", agent: "Codex", license: "MIT", build: "build.mjs", tags: [], noPoster: true }), /already exists/);+ } finally {+ rmSync(repo, { recursive: true, force: true });+ }+});++test("publishing refuses a folder that is not a gallery clone", () => {+ const empty = mkdtempSync(join(tmpdir(), "not-gallery-"));+ try {+ assert.throws(() => publish({ source: join(SKILL, "examples", "dial-indicator"), into: empty, id: "x", title: "x", prompt: "x", author: "x", agent: "Codex", license: "MIT", build: "build.mjs", tags: [], noPoster: true }), /doesn't look like a clone of anatomy-figures/);+ } finally {+ rmSync(empty, { recursive: true, force: true });+ }+});