Skip to content

Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.

feat(package): prepare the Codex manifest for OpenAI's plugin directory (#264)

Cathryn Laveryebbea029044b
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 02bacd9..ac2f721 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -25,20 +25,23 @@
"skills": "./skills/",
"interface": {
"displayName": "Diagram Design",
- "shortDescription": "Create editorial technical and product diagrams as standalone HTML.",
+ "shortDescription": "Editorial HTML/SVG diagrams",
"longDescription": "Create branded architecture, IT current-state, flowchart, sequence, state machine, ER/data model, timeline, swimlane, quadrant, radar/spider, polar chart (polar/radial lollipop), loop/flywheel, nested, tree, org chart, layer stack, Venn, pyramid/funnel, treemap, heatmap, bar, waterfall, line, Gantt and scatter charts, high-level, process, medallion, data flow, DP integration, DP security matrix, Sankey, fishbone, Wardley map, kanban, user journey, deployment, dependency graph, UML class, story map, or database schema diagrams as standalone HTML/SVG/PNG. Redraw .drawio/.drawio.png/.drawio.svg, Mermaid .mmd, or Excalidraw .excalidraw sources at a chosen size/detail; onboard brand tokens from a website; add lifecycle phase maps, semantic patterns, callouts, accessible motion, or sketchy/hand-drawn styling.",
- "developerName": "Cathryn Lavery",
+ "developerName": "LittleMight",
"category": "Productivity",
"capabilities": [
"Read",
"Write"
],
"websiteURL": "https://github.com/cathrynlavery/diagram-design",
+ "privacyPolicyURL": "https://github.com/cathrynlavery/diagram-design/blob/main/PRIVACY.md",
"defaultPrompt": [
"Make an architecture diagram of my app.",
"Create a flowchart for this decision process.",
"Redraw this Mermaid diagram at the right size and detail level."
],
- "brandColor": "#b5523a"
+ "brandColor": "#b5523a",
+ "logo": "./assets/logo.png",
+ "composerIcon": "./assets/composer-icon.png"
}
}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bd98f49..9d775c2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,6 +46,9 @@ jobs:
- name: Verify maintainer policy tracks package and CI truth
run: python3 scripts/test-maintainer-policy.py
+ - name: Verify OpenAI plugin directory listing and upload ZIP
+ run: python3 scripts/test-build-openai-plugin-zip.py
+
# Versions are bumped on main by the Auto Version Bump workflow after
# each merge (ADR 0009); pull requests must leave them untouched.
# A pull_request checkout is GitHub's merge of the PR into the current
diff --git a/.gitignore b/.gitignore
index 935bd3f..0025705 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,4 @@
.mcp.json
__pycache__/
*.py[cod]
+dist/
diff --git a/.maintainer-policy.json b/.maintainer-policy.json
index 87d7440..873cca6 100644
--- a/.maintainer-policy.json
+++ b/.maintainer-policy.json
@@ -35,6 +35,7 @@
"local_commands": [
"python3 scripts/test-plugin-package.py",
"python3 scripts/test-maintainer-policy.py",
+ "python3 scripts/test-build-openai-plugin-zip.py",
"python3 scripts/verify-plugin-package.py --require-no-bump origin/main",
"npx --yes @anthropic-ai/[email protected] plugin validate . --strict",
"python3 scripts/test-lint-a11y.py",
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index db1a5bd..245df50 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -33,6 +33,7 @@ Every validation gate below must pass before a PR is ready. They also run automa
|---|---|
| Plugin bump helper and adversarial package cases | `python3 scripts/test-plugin-package.py` |
| Maintainer policy matches native manifests and current CI gates | `python3 scripts/test-maintainer-policy.py` |
+| OpenAI plugin directory listing limits and upload ZIP contents | `python3 scripts/test-build-openai-plugin-zip.py` |
| Manifest versions untouched and synchronized; valid marketplace paths; packaged skill | `python3 scripts/verify-plugin-package.py --require-no-bump origin/main` |
| Claude marketplace and plugin schema, with warnings treated as errors | `claude plugin validate . --strict` |
| Accessible SVG contract (unit tests for the a11y linter) | `python3 scripts/test-lint-a11y.py` |
@@ -97,11 +98,18 @@ They must still name every visual type; keep fuller feature details in the skill
frontmatter and Codex `longDescription`. The docs-sync gate checks both length
and routing vocabulary, and the package gate keeps native descriptions aligned.
+The Codex `interface` block doubles as the OpenAI plugin directory listing, so
+`displayName` and `shortDescription` stay within 30 characters and
+`longDescription` within 4,000. `scripts/build-openai-plugin-zip.py --check`
+enforces those limits. The maintainer publishes the directory listing; please
+don't submit this plugin to OpenAI or any other plugin directory yourself.
+
Run them all at once before pushing:
```bash
python3 scripts/test-plugin-package.py \
&& python3 scripts/test-maintainer-policy.py \
+ && python3 scripts/test-build-openai-plugin-zip.py \
&& python3 scripts/verify-plugin-package.py --require-no-bump origin/main \
&& claude plugin validate . --strict \
&& python3 scripts/test-lint-a11y.py \
diff --git a/PRIVACY.md b/PRIVACY.md
new file mode 100644
index 0000000..c8c1910
--- /dev/null
+++ b/PRIVACY.md
@@ -0,0 +1,20 @@
+# Privacy
+
+Diagram Design is a set of instructions, HTML templates, and small local scripts that run inside the AI agent you install it in. It has no server, no accounts, and no telemetry, and it sends nothing to the maintainer.
+
+## What uses the network
+
+- **Fonts.** Generated diagrams and the templates load their fonts from Google Fonts (`fonts.googleapis.com` and `fonts.gstatic.com`) when a browser opens them. Google receives the viewer's IP address and browser details under [its privacy policy](https://policies.google.com/privacy). PNG export renders in a local headless browser, which makes the same request, and standalone SVG export keeps the same font import.
+- **Brand onboarding.** If you give the skill a website to take a brand from, your agent fetches a few pages from that site with its own browsing tools. Nothing is fetched unless you ask.
+- **Your agent.** Your prompts, files, and diagrams are processed by the agent you use, under that provider's terms. Diagram Design does not change how your agent handles data.
+
+## What stays on your machine
+
+- The draw.io, Mermaid, and Excalidraw importers, the SVG export helper, and the verifiers read and write local files only. They make no network requests.
+- Saved brand profiles live in `~/.diagram-design/profiles/`.
+
+## Contact
+
+Ask questions in [GitHub issues](https://github.com/cathrynlavery/diagram-design/issues). Report security problems privately, as described in [SECURITY.md](SECURITY.md).
+
+Last updated 2026-10-01.
diff --git a/README.md b/README.md
index 66bcbce..91d6185 100644
--- a/README.md
+++ b/README.md
@@ -118,6 +118,8 @@ The v2.5.10 release added the final ten types above. Compare their light, dark,
## Install
+Official builds come only from this repository. LittleMight, Cathryn Lavery's company, publishes the plugin directory listings; a listing under any other name is an unofficial copy. [PRIVACY.md](PRIVACY.md) lists what the skill sends over the network.
+
**Claude Code:**
```text
diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md
index e880537..5311158 100644
--- a/THIRD_PARTY_LICENSES.md
+++ b/THIRD_PARTY_LICENSES.md
@@ -34,6 +34,14 @@ The MIT license is reproduced in full at https://github.com/log-z/logos/blob/mai
The MIT license is reproduced in full at https://github.com/devicons/devicon/blob/master/LICENSE.
+## Instrument Serif
+
+- **License:** SIL Open Font License 1.1
+- **Upstream:** https://github.com/Instrument/instrument-serif
+- **Used in:** the plugin logo (`assets/logo.svg`, `assets/logo.png`, `assets/composer-icon.png`), which contains the outline of the lowercase "d" from Instrument Serif Italic. No font file is bundled.
+
+The license is reproduced in full at https://github.com/google/fonts/blob/main/ofl/instrumentserif/OFL.txt.
+
## One-off sourced icons
The `scripts/vendor/icons/url/` directory contains one-off sourced icons for SAS, from [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:SAS_logo_horiz.svg) (public domain), and Stata, from the [IcePanel Technology Icons collection](https://icon.icepanel.io/Technology/svg/Stata.svg) published via techicons.dev. Their provenance is recorded here; use of these product marks is covered by the Trademarks note below.
diff --git a/assets/composer-icon.png b/assets/composer-icon.png
new file mode 100644
index 0000000..ed1b544
Binary files /dev/null and b/assets/composer-icon.png differ
diff --git a/assets/logo.png b/assets/logo.png
new file mode 100644
index 0000000..48eafa4
Binary files /dev/null and b/assets/logo.png differ
diff --git a/assets/logo.svg b/assets/logo.svg
new file mode 100644
index 0000000..1206bfa
--- /dev/null
+++ b/assets/logo.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-label="Diagram Design"><rect width="512" height="512" rx="112" fill="#f5f5f5"/><path d="M72 408.4 H440" stroke="#bfc0c0" stroke-width="4"/><path d="M72 205.0 H440" stroke="#bfc0c0" stroke-width="4"/><path d="M72 112.0 H440" stroke="#bfc0c0" stroke-width="4"/><path d="M273.3 438.4 L357.9 72.0" stroke="#bfc0c0" stroke-width="4"/><path transform="translate(159.14 408.41) scale(0.3989 -0.3989)" d="M90 -9Q53 -9 33.0 22.0Q13 53 13 113Q13 170 29.0 227.5Q45 285 73.0 337.0Q101 389 136.5 429.0Q172 469 211.5 492.5Q251 516 290 516Q317 516 337 502Q351 493 354 508L386 640Q391 658 386.5 665.0Q382 672 368 673L338 676Q323 677 325 689Q327 698 339 700Q375 706 403.0 714.5Q431 723 448 737Q456 743 463 743Q475 743 472 728L330 113Q315 48 350 48Q373 48 391.5 79.0Q410 110 429 175Q432 186 442 186Q449 186 451.0 180.0Q453 174 451 166Q432 72 398.5 31.5Q365 -9 320 -9Q281 -9 264.5 24.0Q248 57 261 114L272 160Q274 167 269.5 168.0Q265 169 262 163Q214 69 171.0 30.0Q128 -9 90 -9ZM114 42Q138 42 167.0 71.0Q196 100 224.5 146.0Q253 192 277.0 245.0Q301 298 315.5 347.0Q330 396 330 430Q330 491 287 491Q261 491 232.0 467.5Q203 444 176.5 404.0Q150 364 128.5 313.5Q107 263 94.0 208.5Q81 154 81 102Q81 67 90.5 54.5Q100 42 114 42Z" fill="#2d3142"/><circle cx="440.0" cy="408.4" r="16" fill="#eb6c36"/></svg>
diff --git a/scripts/build-openai-plugin-zip.py b/scripts/build-openai-plugin-zip.py
new file mode 100755
index 0000000..f444057
--- /dev/null
+++ b/scripts/build-openai-plugin-zip.py
@@ -0,0 +1,324 @@
+#!/usr/bin/env python3
+"""Build the ZIP uploaded to OpenAI's plugin directory (ChatGPT and Codex).
+
+The directory accepts a ZIP of the Codex-format plugin: `.codex-plugin/
+plugin.json`, the `skills/` it points at, and the listing assets the manifest
+names. This builder packages exactly those files as they are staged in the git
+index, so the upload matches what the Git marketplace ships, and never includes
+repository tooling, docs, or other hosts' manifests. The MIT LICENSE (required),
+THIRD_PARTY_LICENSES.md, and PRIVACY.md travel with it.
+
+It also enforces the submission form's listing limits so a manifest edit that
+would be rejected at upload fails here first.
+
+Usage:
+ python3 scripts/build-openai-plugin-zip.py --check # limits and asset paths only
+ python3 scripts/build-openai-plugin-zip.py # dist/<name>-<version>-openai.zip
+ python3 scripts/build-openai-plugin-zip.py --draft # allow missing logo/icon (private testing)
+
+For a given Python and zlib the ZIP is byte-reproducible: entries are sorted,
+timestamps and host metadata fixed, and contents read from git blobs rather
+than the working tree.
+"""
+
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import re
+import struct
+import subprocess
+import sys
+import zipfile
+from pathlib import Path, PurePosixPath
+
+ROOT = Path(__file__).resolve().parent.parent
+MANIFEST = ".codex-plugin/plugin.json"
+
+# Listing limits from the OpenAI plugin submission form.
+TEXT_LIMITS = {
+ "displayName": 30,
+ "shortDescription": 30,
+ "longDescription": 4000,
+ "developerName": 80,
+}
+MAX_CAPABILITIES = 20
+REQUIRED_TEXT = ("displayName", "shortDescription", "developerName", "category")
+
+# Interface fields that name package files. Logo and composer icon are required
+# to submit; screenshots are optional.
+REQUIRED_ASSETS = ("logo", "composerIcon")
+OPTIONAL_ASSETS = ("screenshots",)
+IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp", ".svg"}
+MAX_ASSET_BYTES = 5 * 1024 * 1024
+MIN_LOGO_PX = 48
+
+REQUIRED_FILES = ("LICENSE",)
+OPTIONAL_FILES = ("THIRD_PARTY_LICENSES.md", "PRIVACY.md")
+FIXED_TIME = (1980, 1, 1, 0, 0, 0)
+UNIX_HOST = 3
+SAFE_FILENAME_PART = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
+
+
+def git(root: Path, *args: str, data: bytes | None = None) -> bytes:
+ # Manifest-supplied paths are pathspecs; never let git glob them.
+ result = subprocess.run(
+ ["git", "--literal-pathspecs", "-C", str(root), *args],
+ input=data,
+ capture_output=True,
+ )
+ if result.returncode != 0:
+ raise SystemExit(
+ f"build-openai-plugin-zip: git {' '.join(args)} failed: "
+ f"{result.stderr.decode('utf-8', 'replace').strip()}"
+ )
+ return result.stdout
+
+
+def index_entries(root: Path, pathspecs: list[str], errors: list[str]) -> dict[str, str]:
+ """Map each staged path under *pathspecs* to its blob id in the index."""
+ raw = git(root, "ls-files", "-s", "-z", "--", *pathspecs)
+ entries: dict[str, str] = {}
+ unmerged: set[str] = set()
+ for record in raw.split(b"\0"):
+ if not record:
+ continue
+ meta, path_bytes = record.split(b"\t", 1)
+ mode, blob, stage = meta.split()
+ path = path_bytes.decode("utf-8")
+ if stage != b"0":
+ unmerged.add(path)
+ continue
+ if mode == b"160000": # submodule, not a file
+ continue
+ if mode == b"120000": # a symlink's blob is its target path, not content
+ errors.append(f"{path} is a symlink; commit the file itself")
+ continue
+ entries[path] = blob.decode("ascii")
+ for path in sorted(unmerged):
+ errors.append(f"{path} has an unresolved merge conflict in the index")
+ # `git add -N` records a path without content; it would ship as an empty file.
+ pending = git(root, "diff", "--name-only", "-z", "--diff-filter=A", "--", *pathspecs)
+ for path_bytes in pending.split(b"\0"):
+ if path_bytes:
+ path = path_bytes.decode("utf-8")
+ entries.pop(path, None)
+ errors.append(f"{path} is intent-to-add with no staged content; stage it or remove it")
+ return entries
+
+
+def read_blobs(root: Path, blobs: list[str]) -> list[bytes]:
+ """Read blob contents in one `git cat-file --batch` round-trip."""
+ if not blobs:
+ return []
+ stream = io.BytesIO(git(root, "cat-file", "--batch", data="\n".join(blobs).encode() + b"\n"))
+ contents = []
+ for blob in blobs:
+ header = stream.readline().split()
+ if len(header) != 3 or header[0].decode() != blob:
+ raise SystemExit(f"build-openai-plugin-zip: could not read blob {blob}")
+ size = int(header[2])
+ contents.append(stream.read(size))
+ stream.read(1) # trailing newline
+ return contents
+
+
+def package_path(value: object, label: str, errors: list[str]) -> str | None:
+ """Validate a manifest path and return it relative to the plugin root."""
+ if not isinstance(value, str) or not value:
+ errors.append(f"{label} must be a non-empty path")
+ return None
+ if not value.startswith("./"):
+ errors.append(f"{label} must start with ./ (got {value!r})")
+ return None
+ rest = value[2:]
+ relative = PurePosixPath(rest)
+ if rest.startswith("/") or relative.is_absolute() or ".." in relative.parts:
+ errors.append(f"{label} must stay inside the plugin (got {value!r})")
+ return None
+ if not relative.parts:
+ return "."
+ return relative.as_posix()
+
+
+def png_size(data: bytes) -> tuple[int, int] | None:
+ if len(data) < 24 or data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":
+ return None
+ return struct.unpack(">II", data[16:24])
+
+
+def check_listing(interface: dict, errors: list[str]) -> None:
+ for field in REQUIRED_TEXT:
+ if not isinstance(interface.get(field), str) or not interface[field].strip():
+ errors.append(f"interface.{field} is required")
+ for field, limit in TEXT_LIMITS.items():
+ value = interface.get(field)
+ if isinstance(value, str) and len(value) > limit:
+ errors.append(
+ f"interface.{field} is {len(value)} characters; the directory allows {limit}"
+ )
+ capabilities = interface.get("capabilities", [])
+ if not isinstance(capabilities, list):
+ errors.append("interface.capabilities must be a list")
+ elif len(capabilities) > MAX_CAPABILITIES:
+ errors.append(
+ f"interface.capabilities has {len(capabilities)} labels; "
+ f"the directory allows {MAX_CAPABILITIES}"
+ )
+
+
+def declared_assets(interface: dict, errors: list[str], pending: list[str]) -> list[tuple[str, str]]:
+ """Return (label, relative path) for every asset the interface names."""
+ paths: list[tuple[str, str]] = []
+ for field in REQUIRED_ASSETS:
+ if field not in interface:
+ pending.append(field)
+ continue
+ relative = package_path(interface[field], f"interface.{field}", errors)
+ if relative:
+ paths.append((field, relative))
+ for field in OPTIONAL_ASSETS:
+ values = interface.get(field, [])
+ if not isinstance(values, list):
+ errors.append(f"interface.{field} must be a list of paths")
+ continue
+ for i, value in enumerate(values):
+ relative = package_path(value, f"interface.{field}[{i}]", errors)
+ if relative:
+ paths.append((f"{field}[{i}]", relative))
+ return paths
+
+
+def check_assets(
+ root: Path, paths: list[tuple[str, str]], tracked: dict[str, str], errors: list[str]
+) -> list[str]:
+ assets = []
+ for label, relative in paths:
+ if PurePosixPath(relative).suffix.lower() not in IMAGE_SUFFIXES:
+ errors.append(f"interface.{label} must be PNG, JPEG, WebP, or SVG (got {relative})")
+ continue
+ if relative not in tracked:
+ state = "exists but is not tracked by git" if (root / relative).is_file() else "does not exist"
+ errors.append(f"interface.{label} file {relative} {state}")
+ continue
+ data = read_blobs(root, [tracked[relative]])[0]
+ if len(data) > MAX_ASSET_BYTES:
+ errors.append(f"interface.{label} file {relative} is larger than 5 MiB")
+ if label in REQUIRED_ASSETS and relative.lower().endswith(".png"):
+ size = png_size(data)
+ if size is None:
+ errors.append(f"interface.{label} file {relative} is not a valid PNG")
+ elif min(size) < MIN_LOGO_PX:
+ errors.append(
+ f"interface.{label} file {relative} is {size[0]}x{size[1]}px; "
+ f"the directory needs at least {MIN_LOGO_PX}x{MIN_LOGO_PX}"
+ )
+ assets.append(relative)
+ return assets
+
+
+def fail(errors: list[str]) -> int:
+ print(f"build-openai-plugin-zip: {len(errors)} problem(s):", file=sys.stderr)
+ for error in errors:
+ print(f" - {error}", file=sys.stderr)
+ return 1
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--root", type=Path, default=ROOT, help="plugin repository root")
+ parser.add_argument("--out", type=Path, help="output directory (default: <root>/dist)")
+ parser.add_argument("--check", action="store_true", help="validate only; write nothing")
+ parser.add_argument(
+ "--draft",
+ action="store_true",
+ help="build even if the logo or composer icon is missing (private testing only)",
+ )
+ args = parser.parse_args()
+ root = args.root.resolve()
+
+ errors: list[str] = []
+ pending: list[str] = []
+ manifest_entry = index_entries(root, [MANIFEST], errors)
+ if MANIFEST not in manifest_entry:
+ return fail(errors + [f"{MANIFEST} is not staged under {root}"])
+ manifest = json.loads(read_blobs(root, [manifest_entry[MANIFEST]])[0].decode("utf-8"))
+ interface = manifest.get("interface")
+ if not isinstance(interface, dict):
+ return fail(errors + ["manifest has no interface block"])
+
+ for field in ("name", "version"):
+ value = manifest.get(field)
+ if not isinstance(value, str) or not SAFE_FILENAME_PART.match(value):
+ errors.append(f"manifest {field} {value!r} is not a safe filename part")
+
+ check_listing(interface, errors)
+ asset_paths = declared_assets(interface, errors, pending)
+
+ skills_dir = None
+ if "skills" not in manifest:
+ errors.append("manifest skills is required; a plugin without skills ships nothing")
+ else:
+ skills_dir = package_path(manifest["skills"], "manifest skills", errors)
+ if skills_dir == ".":
+ errors.append("manifest skills must name a directory, not the repository root")
+ skills_dir = None
+
+ pathspecs = [MANIFEST, *REQUIRED_FILES, *OPTIONAL_FILES, *(path for _, path in asset_paths)]
+ if skills_dir:
+ pathspecs.append(skills_dir)
+ tracked = index_entries(root, pathspecs, errors)
+ assets = check_assets(root, asset_paths, tracked, errors)
+
+ skill_files: list[str] = []
+ if skills_dir:
+ prefix = skills_dir.rstrip("/") + "/"
+ skill_files = sorted(p for p in tracked if p.startswith(prefix) and p != MANIFEST)
+ if not any(p == "SKILL.md" or p.endswith("/SKILL.md") for p in skill_files):
+ errors.append(f"no staged SKILL.md under {skills_dir}")
+ for name in REQUIRED_FILES:
+ if name not in tracked:
+ errors.append(f"{name} must be tracked; the MIT notice ships with every copy")
+
+ if errors:
+ return fail(errors)
+
+ if args.check:
+ note = f"; pending before submission: {', '.join(pending)}" if pending else ""
+ print(f"OK OpenAI plugin listing: limits and asset paths valid{note}")
+ return 0
+
+ if pending and not args.draft:
+ print(
+ "build-openai-plugin-zip: the directory requires "
+ + ", ".join(f"interface.{field}" for field in pending)
+ + " to submit; add the asset(s) or pass --draft for a private test build",
+ file=sys.stderr,
+ )
+ return 1
+
+ files = sorted(
+ {MANIFEST, *skill_files, *assets, *REQUIRED_FILES}
+ | {name for name in OPTIONAL_FILES if name in tracked}
+ )
+ contents = read_blobs(root, [tracked[name] for name in files])
+ out_dir = (args.out or root / "dist").resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ target = out_dir / f"{manifest['name']}-{manifest['version']}-openai.zip"
+ with zipfile.ZipFile(target, "w", compression=zipfile.ZIP_DEFLATED) as archive:
+ for path, data in zip(files, contents):
+ info = zipfile.ZipInfo(path, date_time=FIXED_TIME)
+ info.compress_type = zipfile.ZIP_DEFLATED
+ info.create_system = UNIX_HOST
+ info.external_attr = 0o644 << 16
+ archive.writestr(info, data)
+ kind = "draft " if pending else ""
+ print(f"OK built {kind}{target} ({len(files)} files, {target.stat().st_size:,} bytes)")
+ if pending:
+ print(f"Draft only: missing {', '.join(pending)}; do not submit this ZIP.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/test-build-openai-plugin-zip.py b/scripts/test-build-openai-plugin-zip.py
new file mode 100755
index 0000000..8fe6e3b
--- /dev/null
+++ b/scripts/test-build-openai-plugin-zip.py
@@ -0,0 +1,454 @@
+#!/usr/bin/env python3
+"""Adversarial tests for scripts/build-openai-plugin-zip.py.
+
+The builder packages the Codex-format plugin for OpenAI's plugin directory
+upload. These cases pin what goes into the ZIP (the manifest, the shared skill,
+licenses, and declared listing assets, read from the git index), what stays
+out (repository tooling, docs, other hosts' manifests, untracked files), the
+directory's listing limits, and asset path safety. Fixture repositories are
+throwaway git checkouts, so the cases do not depend on this repository's
+current assets.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import struct
+import subprocess
+import sys
+import tempfile
+import zipfile
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+BUILDER = ROOT / "scripts" / "build-openai-plugin-zip.py"
+
+ALLOWED_PREFIXES = (
+ ".codex-plugin/plugin.json",
+ "skills/",
+ "assets/",
+ "LICENSE",
+ "THIRD_PARTY_LICENSES.md",
+ "PRIVACY.md",
+)
+FORBIDDEN_PREFIXES = (
+ "scripts/",
+ "docs/",
+ ".github/",
+ "commands/",
+ "prompts/",
+ ".claude-plugin/",
+ ".factory-plugin/",
+ ".agents/",
+)
+
+
+def png(width: int, height: int) -> bytes:
+ """A minimal valid grayscale PNG of the given size."""
+
+ def chunk(kind: bytes, data: bytes) -> bytes:
+ body = kind + data
+ return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
+
+ header = struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0)
+ rows = b"".join(b"\x00" + b"\xff" * width for _ in range(height))
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", header)
+ + chunk(b"IDAT", zlib.compress(rows))
+ + chunk(b"IEND", b"")
+ )
+
+
+def interface(**overrides: object) -> dict:
+ base = {
+ "displayName": "Demo",
+ "shortDescription": "Demo diagrams",
+ "longDescription": "Demo plugin used by the builder tests.",
+ "developerName": "Test Author",
+ "category": "Productivity",
+ "capabilities": ["Read", "Write"],
+ "logo": "./assets/logo.png",
+ "composerIcon": "./assets/icon.svg",
+ }
+ base.update(overrides)
+ return {key: value for key, value in base.items() if value is not None}
+
+
+def fixture(
+ tmp: Path,
+ name: str,
+ iface: dict,
+ *,
+ logo: bytes | None = None,
+ icon: bool = True,
+ license_file: bool = True,
+ track_logo: bool = True,
+ extra: dict[str, bytes] | None = None,
+ intent_to_add: tuple[str, ...] = (),
+ manifest_overrides: dict | None = None,
+ edit_after_add: dict[str, bytes] | None = None,
+ symlinks: dict[str, str] | None = None,
+) -> Path:
+ root = tmp / name
+ (root / ".codex-plugin").mkdir(parents=True)
+ manifest = {
+ "name": "demo",
+ "version": "1.2.3",
+ "description": "Demo plugin.",
+ "skills": "./skills/",
+ "interface": iface,
+ }
+ for key, value in (manifest_overrides or {}).items():
+ if value is None:
+ manifest.pop(key, None)
+ else:
+ manifest[key] = value
+ (root / ".codex-plugin/plugin.json").write_text(json.dumps(manifest, indent=2) + "\n")
+ skill = root / "skills/demo"
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: Demo.\n---\n\nDemo.\n")
+ (skill / "__pycache__").mkdir()
+ (skill / "__pycache__/junk.pyc").write_bytes(b"\x00junk")
+ (root / "scripts").mkdir()
+ (root / "scripts/tool.py").write_text("print('repo tooling')\n")
+ tracked = [".codex-plugin/plugin.json", "skills/demo/SKILL.md", "scripts/tool.py"]
+ if license_file:
+ (root / "LICENSE").write_text("MIT\n")
+ tracked.append("LICENSE")
+ (root / "assets").mkdir()
+ if logo is not None:
+ (root / "assets/logo.png").write_bytes(logo)
+ if track_logo:
+ tracked.append("assets/logo.png")
+ if icon:
+ (root / "assets/icon.svg").write_text(
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"/>\n'
+ )
+ tracked.append("assets/icon.svg")
+ for relative, data in (extra or {}).items():
+ (root / relative).parent.mkdir(parents=True, exist_ok=True)
+ (root / relative).write_bytes(data)
+ tracked.append(relative)
+ for relative, target in (symlinks or {}).items():
+ (root / relative).parent.mkdir(parents=True, exist_ok=True)
+ os.symlink(target, root / relative)
+ tracked.append(relative)
+ subprocess.run(["git", "init", "-q"], cwd=root, check=True)
+ subprocess.run(["git", "add", "--", *tracked], cwd=root, check=True)
+ for relative in intent_to_add:
+ (root / relative).parent.mkdir(parents=True, exist_ok=True)
+ (root / relative).write_text("not staged yet\n")
+ subprocess.run(["git", "add", "-N", "--", relative], cwd=root, check=True)
+ for relative, data in (edit_after_add or {}).items():
+ (root / relative).write_bytes(data)
+ return root
+
+
+def run(*args: str) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ [sys.executable, str(BUILDER), *args],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+
+
+def built_zip(out: Path) -> Path:
+ zips = sorted(out.glob("*.zip"))
+ if len(zips) != 1:
+ raise AssertionError(f"expected one ZIP in {out}, found {[z.name for z in zips]}")
+ return zips[0]
+
+
+def main() -> int:
+ failures: list[str] = []
+ passed = 0
+
+ def check(label: str, condition: bool, detail: str = "") -> None:
+ nonlocal passed
+ if condition:
+ passed += 1
+ else:
+ failures.append(f"{label}{': ' + detail if detail else ''}")
+
+ with tempfile.TemporaryDirectory() as raw:
+ tmp = Path(raw)
+
+ # This repository's manifest stays within the directory's listing limits.
+ result = run("--root", str(ROOT), "--check")
+ check("repo --check passes", result.returncode == 0, result.stdout + result.stderr)
+
+ # A draft build of this repository ships only the plugin surface.
+ out_a, out_b = tmp / "repo-a", tmp / "repo-b"
+ first = run("--root", str(ROOT), "--draft", "--out", str(out_a))
+ second = run("--root", str(ROOT), "--draft", "--out", str(out_b))
+ check("repo draft build succeeds", first.returncode == 0, first.stdout + first.stderr)
+ check("repo second draft build succeeds", second.returncode == 0, second.stdout + second.stderr)
+ if first.returncode == 0 and second.returncode == 0:
+ zip_a, zip_b = built_zip(out_a), built_zip(out_b)
+ names = zipfile.ZipFile(zip_a).namelist()
+ for required in (
+ ".codex-plugin/plugin.json",
+ "skills/diagram-design/SKILL.md",
+ "LICENSE",
+ "THIRD_PARTY_LICENSES.md",
+ "PRIVACY.md",
+ ):
+ check(f"repo ZIP contains {required}", required in names)
+ repo_interface = json.loads((ROOT / ".codex-plugin/plugin.json").read_text())["interface"]
+ declared = {
+ value[2:]
+ for key in ("logo", "composerIcon")
+ for value in [repo_interface.get(key)]
+ if isinstance(value, str)
+ } | {value[2:] for value in repo_interface.get("screenshots", []) if isinstance(value, str)}
+ stray = [n for n in names if not n.startswith(ALLOWED_PREFIXES) and n not in declared]
+ check("repo ZIP has only plugin-surface entries", not stray, ", ".join(stray[:5]))
+ forbidden = [n for n in names if n.startswith(FORBIDDEN_PREFIXES)]
+ check("repo ZIP excludes repository tooling", not forbidden, ", ".join(forbidden[:5]))
+ check(
+ "repo ZIP excludes caches",
+ not any("__pycache__" in n or n.endswith(".pyc") for n in names),
+ )
+ check(
+ "repo ZIP is byte-reproducible",
+ hashlib.sha256(zip_a.read_bytes()).digest()
+ == hashlib.sha256(zip_b.read_bytes()).digest(),
+ )
+ index_manifest = subprocess.run(
+ ["git", "show", ":.codex-plugin/plugin.json"],
+ cwd=ROOT,
+ capture_output=True,
+ check=True,
+ ).stdout
+ check(
+ "repo ZIP manifest matches the git index",
+ zipfile.ZipFile(zip_a).read(".codex-plugin/plugin.json") == index_manifest,
+ )
+
+ # A complete fixture builds for submission and carries its assets.
+ good = fixture(tmp, "good", interface(), logo=png(64, 64))
+ out = tmp / "good-out"
+ result = run("--root", str(good), "--out", str(out))
+ check("complete fixture builds", result.returncode == 0, result.stdout + result.stderr)
+ if result.returncode == 0:
+ names = zipfile.ZipFile(built_zip(out)).namelist()
+ check("fixture ZIP has logo", "assets/logo.png" in names)
+ check("fixture ZIP has composer icon", "assets/icon.svg" in names)
+ check("fixture ZIP excludes untracked cache", not any("__pycache__" in n for n in names))
+ check("fixture ZIP excludes repo scripts", "scripts/tool.py" not in names)
+ check("fixture ZIP is named for its version", built_zip(out).name == "demo-1.2.3-openai.zip")
+
+ # Submission builds refuse a missing required asset; drafts allow it.
+ no_logo = fixture(tmp, "no-logo", interface(logo=None), logo=None)
+ result = run("--root", str(no_logo), "--out", str(tmp / "no-logo-out"))
+ check(
+ "missing logo blocks a submission build",
+ result.returncode == 1 and "logo" in (result.stdout + result.stderr),
+ result.stdout + result.stderr,
+ )
+ result = run("--root", str(no_logo), "--draft", "--out", str(tmp / "no-logo-draft"))
+ check("missing logo allowed in a draft", result.returncode == 0, result.stdout + result.stderr)
+ result = run("--root", str(no_logo), "--check")
+ check("missing logo is pending, not an error, for --check", result.returncode == 0, result.stdout + result.stderr)
+
+ # Listing limits from the submission form.
+ limit_cases = {
+ "displayName": "x" * 31,
+ "shortDescription": "x" * 31,
+ "longDescription": "x" * 4001,
+ "developerName": "x" * 81,
+ "capabilities": [f"Cap{i}" for i in range(21)],
+ }
+ for field, value in limit_cases.items():
+ root = fixture(tmp, f"limit-{field}", interface(**{field: value}), logo=png(64, 64))
+ result = run("--root", str(root), "--check")
+ check(
+ f"{field} over the limit fails",
+ result.returncode == 1 and field in (result.stdout + result.stderr),
+ result.stdout + result.stderr,
+ )
+ root = fixture(tmp, "at-limit", interface(displayName="x" * 30, shortDescription="y" * 30), logo=png(64, 64))
+ result = run("--root", str(root), "--check")
+ check("30-character names pass", result.returncode == 0, result.stdout + result.stderr)
+
+ # Asset paths must stay inside the package and be tracked.
+ path_cases = {
+ "escape": "./../logo.png",
+ "no-dot-slash": "assets/logo.png",
+ "absolute": "/etc/passwd",
+ "dot-slash-absolute": ".//etc/passwd",
+ "nested-escape": "./assets/../../x.png",
+ }
+ for label, value in path_cases.items():
+ root = fixture(tmp, f"path-{label}", interface(logo=value), logo=png(64, 64))
+ result = run("--root", str(root), "--check")
+ check(f"logo path {label} fails", result.returncode == 1, result.stdout + result.stderr)
+ root = fixture(tmp, "untracked-logo", interface(), logo=png(64, 64), track_logo=False)
+ result = run("--root", str(root), "--check")
+ check(
+ "untracked logo fails",
+ result.returncode == 1 and "not tracked" in (result.stdout + result.stderr),
+ result.stdout + result.stderr,
+ )
+ root = fixture(tmp, "small-logo", interface(), logo=png(32, 32))
+ result = run("--root", str(root), "--check")
+ check("logo under 48px fails", result.returncode == 1, result.stdout + result.stderr)
+ root = fixture(tmp, "bad-ext", interface(logo="./assets/logo.gif"), logo=png(64, 64))
+ result = run("--root", str(root), "--check")
+ check("unsupported logo format fails", result.returncode == 1, result.stdout + result.stderr)
+
+ # Assets may live anywhere inside the package, not only assets/.
+ root = fixture(
+ tmp,
+ "brand-dir",
+ interface(logo="./brand/logo.png"),
+ extra={"brand/logo.png": png(64, 64)},
+ )
+ out = tmp / "brand-dir-out"
+ result = run("--root", str(root), "--out", str(out))
+ check("logo outside assets/ builds", result.returncode == 0, result.stdout + result.stderr)
+ if result.returncode == 0:
+ check("logo outside assets/ ships", "brand/logo.png" in zipfile.ZipFile(built_zip(out)).namelist())
+
+ # Screenshots are optional, but each one is checked like the logo.
+ root = fixture(
+ tmp,
+ "screens",
+ interface(screenshots=["./assets/shot.png"]),
+ logo=png(64, 64),
+ extra={"assets/shot.png": png(640, 400)},
+ )
+ out = tmp / "screens-out"
+ result = run("--root", str(root), "--out", str(out))
+ check("screenshots build", result.returncode == 0, result.stdout + result.stderr)
+ if result.returncode == 0:
+ check("screenshot ships", "assets/shot.png" in zipfile.ZipFile(built_zip(out)).namelist())
+ root = fixture(tmp, "screens-escape", interface(screenshots=["./../shot.png"]), logo=png(64, 64))
+ result = run("--root", str(root), "--check")
+ check("screenshot escape fails", result.returncode == 1, result.stdout + result.stderr)
+ root = fixture(tmp, "screens-type", interface(screenshots="./assets/shot.png"), logo=png(64, 64))
+ result = run("--root", str(root), "--check")
+ check("screenshots must be a list", result.returncode == 1, result.stdout + result.stderr)
+
+ # The ZIP carries staged bytes, never the working tree.
+ staged = b"---\nname: demo\ndescription: Demo.\n---\n\nDemo.\n"
+ root = fixture(
+ tmp,
+ "dirty-tree",
+ interface(),
+ logo=png(64, 64),
+ edit_after_add={"skills/demo/SKILL.md": b"unstaged edit\n"},
+ )
+ out = tmp / "dirty-tree-out"
+ result = run("--root", str(root), "--out", str(out))
+ check("dirty working tree builds", result.returncode == 0, result.stdout + result.stderr)
+ if result.returncode == 0:
+ check(
+ "ZIP holds staged bytes, not the working tree",
+ zipfile.ZipFile(built_zip(out)).read("skills/demo/SKILL.md") == staged,
+ )
+
+ # Paths with spaces and non-ASCII characters survive intact.
+ odd = "skills/demo/my caf\u00e9 notes.md"
+ root = fixture(tmp, "odd-path", interface(), logo=png(64, 64), extra={odd: b"notes\n"})
+ out = tmp / "odd-path-out"
+ result = run("--root", str(root), "--out", str(out))
+ check("unusual path builds", result.returncode == 0, result.stdout + result.stderr)
+ if result.returncode == 0:
+ check("unusual path ships unchanged", odd in zipfile.ZipFile(built_zip(out)).namelist())
+
+ # Intent-to-add files have no staged content; refuse rather than ship them empty.
+ root = fixture(tmp, "ita", interface(), logo=png(64, 64), intent_to_add=("skills/demo/new.md",))
+ result = run("--root", str(root), "--draft", "--out", str(tmp / "ita-out"))
+ check(
+ "intent-to-add file fails",
+ result.returncode == 1 and "new.md" in (result.stdout + result.stderr),
+ result.stdout + result.stderr,
+ )
+
+ # The manifest name and version become a filename; keep it inside --out.
+ root = fixture(tmp, "bad-name", interface(), logo=png(64, 64), manifest_overrides={"name": "../escaped"})
+ out = tmp / "bad-name-out"
+ result = run("--root", str(root), "--draft", "--out", str(out))
+ check("unsafe manifest name fails", result.returncode == 1, result.stdout + result.stderr)
+ check("unsafe manifest name writes nothing outside --out", not list(tmp.glob("escaped*")))
+
+ # A manifest without a skills path would ship an empty plugin.
+ root = fixture(tmp, "no-skills", interface(), logo=png(64, 64), manifest_overrides={"skills": None})
+ result = run("--root", str(root), "--draft", "--out", str(tmp / "no-skills-out"))
+ check("manifest without skills fails", result.returncode == 1, result.stdout + result.stderr)
+
+ # The repository root is not a skills directory; it would ship everything.
+ root = fixture(tmp, "root-skills", interface(), logo=png(64, 64), manifest_overrides={"skills": "./"})
+ result = run("--root", str(root), "--check")
+ check("skills at the repository root fails", result.returncode == 1, result.stdout + result.stderr)
+
+ # A truncated PNG is reported, not a traceback.
+ truncated = png(64, 64)[:20]
+ root = fixture(tmp, "truncated-png", interface(), logo=truncated)
+ result = run("--root", str(root), "--check")
+ output = result.stdout + result.stderr
+ check(
+ "truncated PNG is reported cleanly",
+ result.returncode == 1 and "Traceback" not in output and "logo" in output,
+ output,
+ )
+
+ # Symlinks would ship as text files holding their target path.
+ if hasattr(os, "symlink"):
+ try:
+ root = fixture(
+ tmp,
+ "symlink-skill",
+ interface(),
+ logo=png(64, 64),
+ symlinks={"skills/demo/linked.md": "SKILL.md"},
+ )
+ result = run("--root", str(root), "--draft", "--out", str(tmp / "symlink-skill-out"))
+ check(
+ "symlinked skill file fails",
+ result.returncode == 1 and "symlink" in (result.stdout + result.stderr),
+ result.stdout + result.stderr,
+ )
+ root = fixture(
+ tmp,
+ "symlink-logo",
+ interface(logo="./assets/link.png"),
+ logo=png(64, 64),
+ symlinks={"assets/link.png": "logo.png"},
+ )
+ result = run("--root", str(root), "--check")
+ check(
+ "symlinked logo fails",
+ result.returncode == 1 and "symlink" in (result.stdout + result.stderr),
+ result.stdout + result.stderr,
+ )
+ except OSError:
+ pass # symlinks unavailable on this platform
+
+ # The MIT notice must travel with every copy.
+ root = fixture(tmp, "no-license", interface(), logo=png(64, 64), license_file=False)
+ result = run("--root", str(root), "--draft", "--out", str(tmp / "no-license-out"))
+ check(
+ "missing LICENSE fails",
+ result.returncode == 1 and "LICENSE" in (result.stdout + result.stderr),
+ result.stdout + result.stderr,
+ )
+
+ if failures:
+ print(f"{len(failures)} OpenAI plugin ZIP case(s) failed ({passed} passed):")
+ for failure in failures:
+ print(f" - {failure}")
+ return 1
+ print(f"All OpenAI plugin ZIP cases passed ({passed}).")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())