Skip to content

An agent organization structured as a company — 15+ departments, 125+ skills, each independently installable, citing the standards and regulators that settle the question. Runs in Claude Code and ChatGPT.

9.6 KB
Raw Blame
#!/usr/bin/env python3
"""Generate the OpenAI/Codex manifests so this repository installs in ChatGPT as well as Claude.

The skills need no porting. ChatGPT and Claude Code read the same `SKILL.md` — YAML frontmatter
with `name` and `description`, a body, and optional `scripts/`, `references/` and `assets/`
alongside. What differs is where each tool looks for the manifests that describe a bundle:

    Claude Code    plugins/<dept>/.claude-plugin/plugin.json   .claude-plugin/marketplace.json
    OpenAI/Codex   plugins/<dept>/.codex-plugin/plugin.json    .agents/plugins/marketplace.json

So the port is a second set of manifests over the same tree, not a second tree. That is why this
emits *into* the repository rather than into `dist/` the way `build-vertical.py` does: there is no
fork to keep in step, one clone installs in either tool, and a skill fixed once is fixed for both.

The alternative, which this repository already had proposed to it, is to copy the whole tree into a
`Codex/` directory. That is the fork D8 rejected, and the copy offered was a month stale before it
was reviewed. Sixteen small generated manifests do the same job and cannot drift.

Generated, never hand-edited: `--check` fails the build when a manifest drifts from its Claude
counterpart.
"""
import argparse
import glob
import json
import os
import re
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Display titles live in build-readme.py's META and nowhere else. Parsed rather than imported,
# because importing that module runs its tree walk as a side effect; parsed rather than duplicated,
# because a second copy of sixteen titles is a second thing to forget.
META_ENTRY = re.compile(r'^\s*"([a-z-]+)":\s*\(\s*\d+,\s*"([^"]+)",\s*"([^"]+)"\s*\),', re.M)

# Codex publishes no category vocabulary, and its own marketplace entries use a small set of broad
# labels. Everything here is a business function, so one conservative label beats sixteen guesses.
CATEGORY = "Productivity"


def titles():
    source = open(os.path.join(ROOT, "scripts", "build-readme.py"), encoding="utf-8").read()
    found = {slug: title for slug, title, _ in META_ENTRY.findall(source)}
    if not found:
        sys.exit("build-port: could not read META from scripts/build-readme.py")
    return found


def departments(marketplace):
    return [p["name"] for p in marketplace["plugins"]]


def codex_plugin(claude, title):
    """The Codex manifest for one department, from the Claude manifest of the same department."""
    return {
        "name": claude["name"],
        "version": claude["version"],
        "description": claude["description"],
        "author": claude["author"],
        "repository": claude.get("repository", ""),
        "license": "MIT",
        "keywords": claude.get("keywords", []),
        # A path, not a list — Codex discovers the directory. One less thing to regenerate when a
        # skill is added.
        "skills": "./skills/",
        "interface": {
            "displayName": title,
            "category": CATEGORY,
            "shortDescription": f"{title}, as an installable department",
            "longDescription": claude["description"],
            "developerName": claude["author"]["name"],
        },
    }


def agents_md(department_count, skill_count, titles_by_slug, order):
    """The cross-tool repository context file.

    AGENTS.md is read by Codex, Cursor, Gemini CLI, Copilot and others, and describes the repository
    to an agent working *in* it — which is a different job from the skills, which describe how to do
    business work. Generated so the counts cannot go stale.
    """
    lines = [
        "# AGENTS.md",
        "",
        "<!-- Generated by scripts/build-port.py. Do not edit. -->",
        "",
        f"An agent organization structured as a company: {department_count} departments, "
        f"{skill_count} skills, each department installable on its own.",
        "",
        "This file describes the repository to an agent working *on* it. The skills under "
        "`plugins/` are a different thing — they describe how to do the work of a function, and "
        "they load when a request matches their description.",
        "",
        "## Installing, in either tool",
        "",
        "The skills are identical. Only the manifests differ, and both are generated from the same "
        "tree, so a skill fixed once is fixed for both.",
        "",
        "| | Manifests |",
        "|---|---|",
        "| Claude Code | `plugins/<department>/.claude-plugin/plugin.json`, `.claude-plugin/marketplace.json` |",
        "| ChatGPT / Codex | `plugins/<department>/.codex-plugin/plugin.json`, `.agents/plugins/marketplace.json` |",
        "",
        "## Before you open a pull request",
        "",
        "```",
        "./scripts/check-all.sh",
        "```",
        "",
        "Every check CI runs, in one script — the workflow calls this same file, so the two cannot "
        "drift. Stage new files first: the surface guard reads `git ls-files`, so an unstaged file "
        "is invisible to it and the check passes locally then fails in CI.",
        "",
        "## Rules that are enforced rather than suggested",
        "",
        "- **One owner per path.** `docs/AGENT-SURFACES.md` maps every tracked path to exactly one "
        "agent, and no two owners may claim the same path. A new department adds its roster row, "
        "its surface block and its charter in the same change.",
        "- **Generated files are never hand-edited.** The README, the org chart, the social card, "
        "each skill's `references/sources.md`, and these manifests are all emitted from the tree "
        "and verified with `--check`. An edit to one is lost on the next regenerate.",
        "- **Sources are references, never copies.** `sources/*.toml` maps outside authorities to "
        "the skills they settle questions for, and `scripts/build-sources.py` emits each skill's "
        "list into its own `references/sources.md`. The `license` field decides whether an agent "
        "may quote a source or only cite it — most of what a professional must cite is not open, "
        "so when torn between two classes take the more restrictive one.",
        "- **Verticals emit one way.** `verticals/<slug>/` plus the core emits a standalone "
        "repository via `scripts/build-vertical.py`. Generated output is never hand-edited and is "
        "not committed; `--verify` emits to a temporary directory and runs the emitted "
        "repository's own checks instead.",
        "- **US English**, by exact word form. `scripts/check-us-english.py --fix` rewrites. It "
        "leaves URLs alone, which it did not always do.",
        "- **No third-party licensed content.** All prose here is original; "
        "`scripts/check-provenance.py` is the backstop.",
        "",
        "## Departments",
        "",
    ]
    lines += [f"- `{slug}` — {titles_by_slug[slug]}" for slug in order]
    lines += [""]
    return "\n".join(lines)


def build():
    marketplace = json.load(open(os.path.join(ROOT, ".claude-plugin", "marketplace.json"),
                                 encoding="utf-8"))
    titles_by_slug = titles()
    order = departments(marketplace)

    wanted = {}
    total = 0
    for department in order:
        claude_path = f"plugins/{department}/.claude-plugin/plugin.json"
        claude = json.load(open(os.path.join(ROOT, claude_path), encoding="utf-8"))
        total += len(glob.glob(os.path.join(ROOT, "plugins", department, "skills", "*", "SKILL.md")))
        wanted[f"plugins/{department}/.codex-plugin/plugin.json"] = json.dumps(
            codex_plugin(claude, titles_by_slug[department]), indent=2) + "\n"

    wanted[".agents/plugins/marketplace.json"] = json.dumps({
        "name": marketplace["name"],
        "interface": {"displayName": marketplace["name"]},
        "plugins": [
            {
                "name": p["name"],
                "source": {"source": "local", "path": f"./plugins/{p['name']}"},
                "policy": {"installation": "AVAILABLE"},
                "category": CATEGORY,
            }
            for p in marketplace["plugins"]
        ],
    }, indent=2) + "\n"

    wanted["AGENTS.md"] = agents_md(len(order), total, titles_by_slug, order)
    return wanted


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true", help="report drift instead of writing")
    args = parser.parse_args()

    wanted = build()
    # A department removed from the tree must lose its Codex manifest too, or the marketplace
    # advertises a plugin that is not there.
    stale = sorted(set(glob.glob("plugins/*/.codex-plugin/plugin.json")) - set(wanted))

    if args.check:
        drifted = [p for p, text in sorted(wanted.items())
                   if not os.path.exists(p) or open(p, encoding="utf-8").read() != text]
        for path in drifted:
            print(f"  stale or missing: {path}")
        for path in stale:
            print(f"  department no longer exists: {path}")
        problems = len(drifted) + len(stale)
        if problems:
            print("  run: python3 scripts/build-port.py")
        print(f"openai/codex manifests: {len(wanted)} expected, {problems} out of date")
        return 1 if problems else 0

    for path, text in sorted(wanted.items()):
        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
        with open(path, "w", encoding="utf-8") as handle:
            handle.write(text)
    for path in stale:
        os.remove(path)
    print(f"openai/codex manifests: {len(wanted)} written"
          + (f", {len(stale)} removed" if stale else ""))
    return 0


if __name__ == "__main__":
    sys.exit(main())