#!/usr/bin/env node
// Generates every platform adapter in this repository from canonical/.
//
// node scripts/build-packages.mjs write the adapters
// node scripts/build-packages.mjs --check fail if anything drifted
// node scripts/build-packages.mjs --release stamp the release marker at the current version
//
// Canonical inputs (hand-edited): canonical/facts.json, SKILL.md, AGENTS.md,
// .cursor/rules/charming.mdc, charming-icon.png, canonical/assets/.
// Everything this script writes is generated; see DISTRIBUTION.md.
import { createHash } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { dirname, join, relative, resolve, sep } from 'node:path';
// Draft 2020-12 entry point: both vendored schemas declare
// $schema: https://json-schema.org/draft/2020-12/schema, and the default
// `ajv` export only understands draft-07.
import Ajv2020 from 'ajv/dist/2020.js';
const ROOT = resolve(import.meta.dirname, '..');
const CHECK = process.argv.includes('--check');
const RELEASE = process.argv.includes('--release');
const read = (p) => readFileSync(join(ROOT, p), 'utf8');
const readBytes = (p) => readFileSync(join(ROOT, p));
/** A malformed canonical input cannot be reported as drift; nothing downstream is meaningful. */
function die(message) {
console.error(`canonical input is unusable: ${message}`);
process.exit(1);
}
let facts;
try {
facts = JSON.parse(read('canonical/facts.json'));
} catch (error) {
die(`canonical/facts.json is not valid JSON (${error.message})`);
}
validateFacts(facts);
/**
* Every value below is hand-edited and flows into published packages, so a typo
* must stop the run rather than reach a template as `undefined`.
*/
function validateFacts(f) {
const problems = [];
const req = (path, type) => {
const value = path.split('.').reduce((acc, key) => (acc == null ? acc : acc[key]), f);
const actual = Array.isArray(value) ? 'array' : typeof value;
if (value == null || actual !== type) problems.push(`${path} must be a ${type} (got ${actual})`);
return value;
};
for (const path of [
'product.name',
'product.slug',
'product.shortDescription',
'product.packageDescription',
'product.longDescription',
'product.category',
'product.brandColor',
'product.license',
'product.publisher.name',
'product.publisher.url',
'product.publisher.org',
'version',
'endpoints.mcp',
'endpoints.chatgptMcp',
'marketplace.name',
'marketplace.displayName',
'marketplace.owner.name',
'assets.icon',
'assets.animatedLogo',
]) {
req(path, 'string');
}
for (const path of ['product.keywords', 'defaultPrompts', 'clients', 'tools', 'branding.forbidden', 'branding.allowedTokens', 'branding.exemptFiles', 'checks.allowedIdentifiers', 'checks.fixtureFiles', 'ownedHosts', 'externalHosts']) {
req(path, 'array');
}
req('urls', 'object');
for (const [i, client] of (f.clients ?? []).entries()) {
if (!client?.label) problems.push(`clients[${i}].label is missing`);
if (!f.endpoints?.[client?.endpoint]) {
problems.push(`clients[${i}].endpoint "${client?.endpoint}" is not a key of endpoints`);
}
}
for (const [i, tool] of (f.tools ?? []).entries()) {
if (!tool?.name || !tool?.summary) problems.push(`tools[${i}] needs both name and summary`);
}
// An endpoint or asset that points off-repo would publish something we do not control.
const hostOf = (url) => {
try {
const parsed = new URL(url);
return parsed.protocol === 'https:' ? parsed.hostname : null;
} catch {
return null;
}
};
for (const [key, url] of Object.entries(f.endpoints ?? {})) {
if (!f.ownedHosts?.includes(hostOf(url))) problems.push(`endpoints.${key} must be https on an owned host: ${url}`);
}
const allowedUrlHosts = [...(f.ownedHosts ?? []), ...(f.externalHosts ?? [])];
for (const [key, url] of Object.entries(f.urls ?? {})) {
if (!allowedUrlHosts.includes(hostOf(url))) problems.push(`urls.${key} must be https on a declared host: ${url}`);
}
for (const [key, rel] of Object.entries(f.assets ?? {})) {
const target = resolve(ROOT, String(rel));
if (!target.startsWith(ROOT + sep)) problems.push(`assets.${key} escapes the repository: ${rel}`);
}
if (problems.length > 0) die(`\n - ${problems.join('\n - ')}`);
}
const BANNER = '<!-- Generated by scripts/build-packages.mjs from canonical/. Do not edit. -->';
const MCP = facts.endpoints.mcp;
const TOOL_NAMES = facts.tools.map((t) => t.name);
const canonicalSkill = read('SKILL.md');
const canonicalAgents = read('AGENTS.md');
const canonicalRule = read('.cursor/rules/charming.mdc');
// Vendored, not fetched: the Agent Plugins spec forbids a client (and by
// extension a build) retrieving schemas over the network at load time.
const AGENT_PLUGINS_SCHEMA_VERSION = '1.0.0';
const agentPluginsPluginSchema = JSON.parse(read(`schemas/agent-plugins/${AGENT_PLUGINS_SCHEMA_VERSION}/plugin.schema.json`));
const agentPluginsMcpSchema = JSON.parse(read(`schemas/agent-plugins/${AGENT_PLUGINS_SCHEMA_VERSION}/mcp.schema.json`));
// allErrors so one run reports every violation instead of stopping at the
// first; strict (the default, kept explicit) so an unrecognized keyword in a
// future vendored schema is a thrown error, not a silently ignored no-op.
const ajv = new Ajv2020({ allErrors: true, strict: true });
const validateAgentPluginsManifest = ajv.compile(agentPluginsPluginSchema);
const validateAgentPluginsMcp = ajv.compile(agentPluginsMcpSchema);
const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
const problems = [];
const fail = (message) => problems.push(message);
const VERSION_LOCK = 'canonical/version-lock.json';
/**
* Fingerprint of everything that reaches a package except the version itself,
* so a content change can be told apart from a version-only bump.
*/
function canonicalInputHash() {
const hash = createHash('sha256');
const withoutVersion = JSON.parse(read('canonical/facts.json'));
delete withoutVersion.version;
hash.update(JSON.stringify(withoutVersion));
for (const path of ['SKILL.md', 'AGENTS.md', '.cursor/rules/charming.mdc']) hash.update(read(path));
const notesDir = join(ROOT, 'canonical/platform-notes');
if (existsSync(notesDir)) {
for (const name of readdirSync(notesDir).sort()) hash.update(name).update(read(`canonical/platform-notes/${name}`));
}
for (const rel of Object.values(facts.assets)) hash.update(readBytes(rel));
return hash.digest('hex').slice(0, 16);
}
/**
* Hosts pin an installed plugin to its version string: Claude Code, Cursor, and
* Codex all read it, and an unchanged version means an installed plugin never
* receives regenerated content. So content may not change without a bump.
*
* The lock holds the last RELEASED version and its content, refreshed only by
* `--release`. Bumping once therefore covers a whole release: edits keep passing
* while the version differs from the released one.
*/
const canonicalInputs = canonicalInputHash();
const lock = existsSync(join(ROOT, VERSION_LOCK)) ? JSON.parse(read(VERSION_LOCK)) : null;
const versionGateViolated =
!RELEASE && Boolean(lock) && lock.canonicalInputs !== canonicalInputs && lock.version === facts.version;
if (versionGateViolated) {
// Reported alongside any content problems rather than short-circuiting, so one
// run tells you everything. The lock is withheld below so nothing is blessed.
fail(
`canonical content changed but version is still ${facts.version}. ` +
'Installed plugins only update when the version string changes, so bump "version" in canonical/facts.json.',
);
}
/** Index just past a document's closing frontmatter fence, or -1 when it has none. */
function frontmatterEnd(markdown) {
if (!markdown.startsWith('---\n')) return -1;
const fence = markdown.indexOf('\n---\n', 3);
return fence === -1 ? -1 : fence + 5;
}
/**
* Insert the generated banner after YAML frontmatter, which must stay first.
* Unterminated frontmatter would otherwise splice the banner inside the YAML.
*/
function withBanner(markdown, label = 'canonical markdown') {
if (!markdown.startsWith('---\n')) return `${BANNER}\n\n${markdown}`;
const end = frontmatterEnd(markdown);
if (end === -1) die(`${label} opens YAML frontmatter but never closes it`);
return `${markdown.slice(0, end)}\n${BANNER}\n${markdown.slice(end)}`;
}
function skillFor(platform) {
let body = withBanner(canonicalSkill, 'SKILL.md');
const notePath = `canonical/platform-notes/${platform}.md`;
if (existsSync(join(ROOT, notePath))) {
const note = read(notePath).replaceAll('{{mcpEndpoint}}', MCP);
body = `${body.trimEnd()}\n\n${note.trimStart()}`;
}
return body;
}
const author = {
name: facts.product.publisher.name,
url: facts.product.publisher.org,
};
function packageReadme(platform, installSteps, headerImage) {
return [
BANNER,
'',
...(headerImage ? [`<img src="${headerImage}" alt="Charming" width="160">`, ''] : []),
`# Charming for ${platform}`,
'',
facts.product.longDescription,
'',
'## Install',
'',
installSteps.trim(),
'',
'## What it ships',
'',
`- The Charming MCP server at \`${MCP}\`.`,
'- The canonical `charming` skill: the MCP-first authoring workflow and the app contract.',
'',
'Every file in this directory is generated from `canonical/` by `scripts/build-packages.mjs`, including the JSON manifests, which cannot carry a comment. Edit `canonical/`, not these copies.',
'',
`Full authoring guide: <${facts.urls.llmsFull}>. Published by ${facts.product.publisher.name} (<${facts.product.publisher.url}>).`,
'',
].join('\n');
}
/** platform -> { dir, files, assets } */
const PLATFORMS = {
// agent-plugins.org v1.0.0: plugin.json and mcp.json sit at the package
// root (no client-specific subdirectory), per spec §4.2 and §6.1. The
// manifest schema is closed, so client-specific data would go under an
// `extensions` namespace instead of a top-level field; Charming has none
// to add yet. mcp.json carries no `headers` and no `env`: Agent Plugins
// defines no credential mechanism, and Charming's OAuth is client-managed.
'agent-plugins': {
dir: 'plugins/agent-plugins/charming',
files: {
'plugin.json': json({
$schema: 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json',
name: facts.product.slug,
version: facts.version,
description: facts.product.packageDescription,
author,
homepage: facts.urls.website,
repository: facts.urls.repository,
license: facts.product.license,
keywords: facts.product.keywords,
}),
'mcp.json': json({
$schema: 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json',
mcpServers: { charming: { type: 'streamable-http', url: MCP } },
}),
'skills/charming/SKILL.md': skillFor('agent-plugins'),
},
assets: {},
},
cursor: {
dir: 'plugins/cursor/charming',
files: {
'.cursor-plugin/plugin.json': json({
name: facts.product.slug,
displayName: facts.product.name,
version: facts.version,
description: facts.product.packageDescription,
author,
license: facts.product.license,
keywords: facts.product.keywords,
logo: 'assets/icon.png',
}),
// Cursor discovers MCP servers from mcp.json under that exact name only.
'mcp.json': json({ mcpServers: { charming: { url: MCP } } }),
'rules/charming.mdc': withBanner(canonicalRule, '.cursor/rules/charming.mdc'),
'skills/charming/SKILL.md': skillFor('cursor'),
'README.md': packageReadme(
'Cursor',
[
'```sh',
`cursor plugin marketplace add ${facts.urls.repository}.git`,
'```',
'',
'Then install **Charming** from the **Tambo Labs** marketplace in Cursor.',
].join('\n'),
),
},
assets: { 'assets/icon.png': facts.assets.icon },
},
'claude-code': {
dir: 'plugins/claude-code/charming',
files: {
'.claude-plugin/plugin.json': json({
name: facts.product.slug,
displayName: facts.product.name,
version: facts.version,
description: facts.product.packageDescription,
author,
homepage: facts.urls.website,
repository: facts.urls.repository,
license: facts.product.license,
keywords: facts.product.keywords,
}),
// Claude Code reads a url entry with no type as stdio and skips the server.
'.mcp.json': json({ mcpServers: { charming: { type: 'http', url: MCP } } }),
'skills/charming/SKILL.md': skillFor('claude-code'),
'README.md': packageReadme(
'Claude Code',
[
'```sh',
`/plugin marketplace add ${facts.urls.repository.replace('https://github.com/', '')}`,
`/plugin install ${facts.product.slug}@${facts.marketplace.name}`,
'```',
].join('\n'),
),
},
assets: { 'assets/icon.png': facts.assets.icon },
},
codex: {
dir: 'plugins/codex/charming',
files: {
'.codex-plugin/plugin.json': json({
name: facts.product.slug,
version: facts.version,
description: facts.product.packageDescription,
author,
homepage: facts.urls.start,
repository: facts.urls.repository,
license: facts.product.license,
keywords: facts.product.keywords,
skills: './skills/',
mcpServers: './.mcp.json',
interface: {
displayName: facts.product.name,
shortDescription: facts.product.shortDescription,
longDescription: facts.product.longDescription,
developerName: facts.product.publisher.name,
category: facts.product.category,
capabilities: ['Interactive', 'Write'],
websiteURL: facts.urls.website,
privacyPolicyURL: facts.urls.privacy,
termsOfServiceURL: facts.urls.terms,
brandColor: facts.product.brandColor,
composerIcon: './assets/icon.png',
logo: './assets/icon.png',
defaultPrompt: facts.defaultPrompts,
},
}),
'.mcp.json': json({ mcpServers: { charming: { url: MCP } } }),
'skills/charming/SKILL.md': skillFor('codex'),
'README.md': packageReadme(
'Codex',
[
'```sh',
`codex plugin marketplace add ${facts.urls.repository}.git`,
'```',
'',
'Then restart Codex, open **Plugins**, choose **Tambo Labs**, install **Charming**, and start a new thread.',
].join('\n'),
'assets/logo-animated.svg',
),
},
assets: {
'assets/icon.png': facts.assets.icon,
'assets/logo-animated.svg': facts.assets.animatedLogo,
},
},
};
/** Repo-root files each host looks for. */
const ROOT_FILES = {
'.cursor-plugin/marketplace.json': json({
name: facts.marketplace.name,
owner: facts.marketplace.owner,
metadata: {
description: facts.product.longDescription,
version: facts.version,
},
plugins: [
{
name: facts.product.slug,
source: `./${PLATFORMS.cursor.dir}`,
description: facts.product.packageDescription,
},
],
}),
'.claude-plugin/marketplace.json': json({
name: facts.marketplace.name,
owner: facts.marketplace.owner,
description: facts.product.longDescription,
plugins: [
{
name: facts.product.slug,
source: `./${PLATFORMS['claude-code'].dir}`,
description: facts.product.packageDescription,
version: facts.version,
author,
homepage: facts.urls.website,
license: facts.product.license,
category: facts.product.category,
keywords: facts.product.keywords,
},
],
}),
'.agents/plugins/marketplace.json': json({
name: facts.marketplace.name,
interface: { displayName: facts.marketplace.displayName },
plugins: [
{
name: facts.product.slug,
source: { source: 'local', path: `./${PLATFORMS.codex.dir}` },
policy: { installation: 'AVAILABLE', authentication: 'ON_INSTALL' },
category: facts.product.category,
},
],
}),
// Gemini CLI gallery discovery requires this manifest at the absolute repo root.
'gemini-extension.json': json({
name: facts.product.slug,
version: facts.version,
description: facts.product.packageDescription,
contextFileName: 'GEMINI.md',
mcpServers: { charming: { httpUrl: MCP } },
}),
'GEMINI.md': withBanner(canonicalAgents, 'AGENTS.md'),
};
/** README blocks the generator owns, keyed by marker name. */
const README_BLOCKS = {
'connect-table': [
'| Client | Endpoint |',
'|--------|----------|',
...facts.clients.map((c) => {
const url = `\`${facts.endpoints[c.endpoint]}\``;
return `| ${c.label} | ${c.note ? `${url} (${c.note})` : url} |`;
}),
].join('\n'),
'tools-table': [
`Charming exposes ${facts.tools.length} tools. Connected clients discover them automatically via \`tools/list\`.`,
'',
'| Tool | What it does |',
'|------|-------------|',
...facts.tools.map((t) => `| \`${t.name}\` | ${t.summary} |`),
].join('\n'),
};
function applyReadmeBlocks(source) {
let out = source;
for (const [name, body] of Object.entries(README_BLOCKS)) {
const open = `<!-- generated:${name} -->`;
const close = `<!-- /generated:${name} -->`;
const start = out.indexOf(open);
const end = out.indexOf(close);
const opens = out.split(open).length - 1;
const closes = out.split(close).length - 1;
if (opens !== 1 || closes !== 1) {
fail(`README.md must hold exactly one ${open} block (found ${opens} open, ${closes} close)`);
continue;
}
if (start === -1 || end === -1 || end < start) {
fail(`README.md is missing the ${open} to ${close} block`);
continue;
}
out = `${out.slice(0, start)}${open}\n${body}\n${close}${out.slice(end + close.length)}`;
}
return out;
}
// ---------------------------------------------------------------------------
// Emit or verify
const written = [];
const generatedText = new Map();
const generatedBinary = new Map();
for (const [platform, spec] of Object.entries(PLATFORMS)) {
for (const [rel, body] of Object.entries(spec.files)) {
generatedText.set(`${spec.dir}/${rel}`, body);
}
for (const [rel, source] of Object.entries(spec.assets)) {
if (!existsSync(join(ROOT, source))) {
fail(`${platform}: canonical asset ${source} is missing`);
continue;
}
generatedBinary.set(`${spec.dir}/${rel}`, readBytes(source));
}
}
for (const [rel, body] of Object.entries(ROOT_FILES)) generatedText.set(rel, body);
generatedText.set('README.md', applyReadmeBlocks(read('README.md')));
function emit(rel, body) {
const target = join(ROOT, rel);
const current = existsSync(target) ? readFileSync(target) : null;
const next = Buffer.isBuffer(body) ? body : Buffer.from(body, 'utf8');
if (current && current.equals(next)) return;
if (CHECK) {
fail(current ? `${rel} is out of date. Run: node scripts/build-packages.mjs` : `${rel} is missing`);
return;
}
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, next);
written.push(rel);
}
for (const [rel, body] of generatedText) emit(rel, body);
for (const [rel, body] of generatedBinary) emit(rel, body);
// ---------------------------------------------------------------------------
// Fact checks over every text file in the repository
const TEXT_EXTENSIONS = new Set(['.md', '.mdc', '.json', '.txt', '.toml', '.yml', '.yaml', '.mjs', '.svg']);
const SKIP_DIRS = new Set(['.git', 'node_modules']);
/** Files whose text the fact checks read. Symlinks are excluded and reported separately. */
function allFiles(dir = ROOT) {
const out = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (SKIP_DIRS.has(entry.name)) continue;
const full = join(dir, entry.name);
if (entry.isSymbolicLink()) out.push({ path: full, symlink: true });
else if (entry.isDirectory()) out.push(...allFiles(full));
else out.push({ path: full, symlink: false });
}
return out;
}
const REPO_FILES = allFiles();
// Extensionless files carry text too, and the scans would otherwise skip them.
const TEXT_NAMES = new Set(['LICENSE', 'NOTICE', '.gitattributes', '.gitignore']);
const isTextFile = (path) => {
const name = path.slice(path.lastIndexOf(sep) + 1);
return TEXT_NAMES.has(name) || TEXT_EXTENSIONS.has(name.slice(name.lastIndexOf('.')));
};
const KNOWN_URLS = new Set([...Object.values(facts.endpoints), ...Object.values(facts.urls)]);
const ALLOWED_IDENTIFIERS = new Set(facts.checks.allowedIdentifiers);
const ALLOWED_BRAND_TOKENS = facts.branding.allowedTokens;
const BRANDING_EXEMPT = new Set(facts.branding.exemptFiles);
// Files that hold deliberate counter-examples: the drift fixtures the checker
// is tested against, which must not be read as claims about the product.
const FIXTURE_FILES = new Set(facts.checks.fixtureFiles);
// Built from facts.ownedHosts so adding a host cannot silently skip the scan.
const OWNED_HOST = new RegExp(
`https://(?:${facts.ownedHosts.map((h) => h.replaceAll('.', '\\.')).join('|')})[^\\s"'\`)\\]<>,]*`,
'g',
);
// An identifier inside any code span or fenced block is a claim about the tool
// surface; the same words in English prose or a YAML key are not.
const CODE_SPAN = /`([^`\n]+)`/g;
const FENCED_BLOCK = /^```[^\n]*\n([\s\S]*?)^```/gm;
const SNAKE_IDENTIFIER = /\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b/g;
for (const { path: file, symlink } of REPO_FILES) {
const rel = relative(ROOT, file);
if (symlink) {
fail(`${rel}: symlink. Packages must be self-contained, so every file must be a real file`);
continue;
}
if (!isTextFile(file)) continue;
if (FIXTURE_FILES.has(rel)) continue;
const body = readFileSync(file, 'utf8');
const isFacts = rel === 'canonical/facts.json';
const isMarkdown = rel.endsWith('.md') || rel.endsWith('.mdc');
for (const match of body.matchAll(OWNED_HOST)) {
// Trailing sentence punctuation belongs to the prose, not the URL.
const url = match[0].replace(/\.git$/, '').replace(/[.,;:!?)\]]+$/, '');
if (!KNOWN_URLS.has(url) && !KNOWN_URLS.has(`${url}/`)) {
fail(`${rel}: URL ${url} is not declared in canonical/facts.json`);
}
}
if (!isFacts && !BRANDING_EXEMPT.has(rel)) {
let stripped = body;
for (const token of ALLOWED_BRAND_TOKENS) stripped = stripped.replaceAll(token, '');
for (const word of facts.branding.forbidden) {
const hit = new RegExp(word, 'i').exec(stripped);
if (hit) fail(`${rel}: stale branding "${hit[0]}" (allowed only as ${ALLOWED_BRAND_TOKENS.join(', ')})`);
}
}
// Qualifiers are allowed between the count and the noun, as in "<n> MCP tools".
// Spelling that example with a digit would make this scan fail on its own source.
for (const match of body.matchAll(/\b(\d+)\s+(?:[A-Za-z][\w-]*\s+){0,2}tools\b/g)) {
if (Number(match[1]) !== facts.tools.length) {
fail(`${rel}: says "${match[0]}" but canonical/facts.json declares ${facts.tools.length}`);
}
}
if (isMarkdown) {
const codeText = [
...[...body.matchAll(CODE_SPAN)].map((m) => m[1]),
...[...body.matchAll(FENCED_BLOCK)].map((m) => m[1]),
];
for (const chunk of codeText) {
for (const match of chunk.matchAll(SNAKE_IDENTIFIER)) {
const name = match[0];
if (TOOL_NAMES.includes(name) || ALLOWED_IDENTIFIERS.has(name)) continue;
fail(`${rel}: \`${name}\` is not a Charming tool. Add it to facts.tools or checks.allowedIdentifiers`);
}
}
}
}
// A package must contain exactly its generated files. Byte parity alone only
// covers files the generator knows about, so an added file would ship unnoticed.
const GENERATED = new Set([...generatedText.keys(), ...generatedBinary.keys()]);
const PACKAGE_ROOT = 'plugins';
const KNOWN_PACKAGE_DIRS = Object.values(PLATFORMS).map((spec) => spec.dir);
for (const { path: file } of REPO_FILES) {
const rel = relative(ROOT, file).split(sep).join('/');
if (!rel.startsWith(`${PACKAGE_ROOT}/`)) continue;
if (GENERATED.has(rel)) continue;
const inKnownPackage = KNOWN_PACKAGE_DIRS.some((dir) => rel.startsWith(`${dir}/`));
fail(
inKnownPackage
? `${rel} is not generated from canonical/. Delete it or add it to the generator`
: `${rel} sits outside every known package. Delete it or register its platform in the generator`,
);
}
// Package self-containment: no path escapes, and every referenced path exists.
for (const [platform, spec] of Object.entries(PLATFORMS)) {
const manifestRel = Object.keys(spec.files).find((f) => f.endsWith('plugin.json'));
const manifest = JSON.parse(spec.files[manifestRel]);
const refs = [
manifest.logo,
manifest.skills,
manifest.mcpServers,
manifest.interface?.composerIcon,
manifest.interface?.logo,
].filter((v) => typeof v === 'string');
for (const ref of refs) {
if (ref.includes('..')) fail(`${platform}: manifest path ${ref} escapes the package`);
if (!existsSync(join(ROOT, spec.dir, ref))) fail(`${platform}: manifest path ${ref} does not exist`);
}
if (!existsSync(join(ROOT, spec.dir, 'skills/charming/SKILL.md'))) {
fail(`${platform}: skills/charming/SKILL.md is missing`);
}
}
// Agent Plugins v1.0.0 conformance, checked against the vendored schemas
// rather than re-deriving the shape the generator above already assumes, so
// a schema-breaking edit to the generator itself is caught here too.
{
const dir = PLATFORMS['agent-plugins'].dir;
const manifest = JSON.parse(PLATFORMS['agent-plugins'].files['plugin.json']);
const mcp = JSON.parse(PLATFORMS['agent-plugins'].files['mcp.json']);
if (!validateAgentPluginsManifest(manifest)) {
for (const err of validateAgentPluginsManifest.errors) {
fail(`${dir}/plugin.json does not conform to ${agentPluginsPluginSchema.$id}: ${err.instancePath || '(root)'} ${err.message}`);
}
}
if (!validateAgentPluginsMcp(mcp)) {
for (const err of validateAgentPluginsMcp.errors) {
fail(`${dir}/mcp.json does not conform to ${agentPluginsMcpSchema.$id}: ${err.instancePath || '(root)'} ${err.message}`);
}
}
if (mcp.$schema !== manifest.$schema.replace('plugin.schema.json', 'mcp.schema.json')) {
fail(`${dir}/mcp.json targets a different Agent Plugins version than ${dir}/plugin.json`);
}
const servers = Object.entries(mcp.mcpServers ?? {});
if (servers.length !== 1) {
fail(`${dir}/mcp.json must declare exactly one MCP server, found ${servers.length}`);
}
const [, server] = servers[0] ?? [];
if (server?.type !== 'streamable-http') fail(`${dir}/mcp.json server must use type "streamable-http"`);
if (server?.url !== MCP) fail(`${dir}/mcp.json server url must be ${MCP}`);
if (server && 'headers' in server) fail(`${dir}/mcp.json must not declare headers; the spec forbids embedded credentials`);
}
// Marketplace entries must point at a real package directory holding its manifest.
const MARKETPLACE_MANIFEST = {
'.cursor-plugin/marketplace.json': '.cursor-plugin/plugin.json',
'.claude-plugin/marketplace.json': '.claude-plugin/plugin.json',
'.agents/plugins/marketplace.json': '.codex-plugin/plugin.json',
};
for (const [marketplaceRel, pluginManifest] of Object.entries(MARKETPLACE_MANIFEST)) {
const catalog = JSON.parse(ROOT_FILES[marketplaceRel]);
if (!/^[a-z0-9-]+$/.test(catalog.name)) fail(`${marketplaceRel}: marketplace name must be kebab-case`);
for (const entry of catalog.plugins) {
if (!/^[a-z0-9-]+$/.test(entry.name)) fail(`${marketplaceRel}: plugin name ${entry.name} must be kebab-case`);
const source = typeof entry.source === 'string' ? entry.source : entry.source.path;
if (!source.startsWith('./')) fail(`${marketplaceRel}: source ${source} must start with ./`);
const dir = join(ROOT, source);
if (!existsSync(dir) || !lstatSync(dir).isDirectory()) {
fail(`${marketplaceRel}: source ${source} is not a directory`);
continue;
}
if (!existsSync(join(dir, pluginManifest))) {
fail(`${marketplaceRel}: ${source} is missing ${pluginManifest}`);
}
}
}
// The canonical skill and rule must carry the frontmatter every host requires.
for (const [label, body] of [
['SKILL.md', canonicalSkill],
['.cursor/rules/charming.mdc', canonicalRule],
]) {
const end = frontmatterEnd(body);
if (end === -1) {
fail(`${label}: YAML frontmatter is missing or never closed`);
continue;
}
if (!/\ndescription:\s*\S/.test(body.slice(0, end))) fail(`${label}: frontmatter needs a description`);
}
if (!/\nname:\s*charming\b/.test(canonicalSkill.slice(0, 200))) {
fail('SKILL.md: frontmatter name must be "charming"');
}
// ---------------------------------------------------------------------------
// Settled last, and only when asked: a run that reports problems must not move
// the release marker, and an ordinary regenerate must not either.
if (!lock && CHECK) {
fail(`${VERSION_LOCK} is missing. Run: node scripts/build-packages.mjs --release`);
}
if (problems.length === 0 && (RELEASE || !lock)) {
const desiredLock = json({ version: facts.version, canonicalInputs });
const lockPath = join(ROOT, VERSION_LOCK);
if ((existsSync(lockPath) ? readFileSync(lockPath, 'utf8') : null) !== desiredLock) {
if (CHECK) {
fail(`${VERSION_LOCK} is out of date. Run: node scripts/build-packages.mjs --release`);
} else {
mkdirSync(dirname(lockPath), { recursive: true });
writeFileSync(lockPath, desiredLock);
written.push(VERSION_LOCK);
}
}
}
if (problems.length > 0) {
console.error(`${problems.length} problem(s):`);
for (const p of problems) console.error(` - ${p}`);
process.exit(1);
}
const hash = createHash('sha256');
for (const rel of [...generatedText.keys()].sort()) hash.update(rel).update(generatedText.get(rel));
console.log(
CHECK
? `ok: ${generatedText.size + generatedBinary.size + 1} generated files match canonical/ (${hash.digest('hex').slice(0, 12)})`
: written.length > 0
? `wrote ${written.length} file(s):\n${written.map((f) => ` ${f}`).join('\n')}`
: 'ok: nothing to write',
);