diff --git a/.github/workflows/directory-package.yml b/.github/workflows/directory-package.yml new file mode 100644 index 0000000..38eb705 --- /dev/null +++ b/.github/workflows/directory-package.yml @@ -0,0 +1,28 @@ +name: Directory package + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + package: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.11' + - name: Test directory packaging + run: bash tests/directory-zip.sh + - name: Build skills-only directory ZIP + run: python3 scripts/build_directory_zip.py + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: altimate-code-directory + path: dist/*.zip + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 98298ed..d07a5f3 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ .scratch/ .github/meta/ *.log +dist/ +__pycache__/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 798e884..029489c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -118,3 +118,10 @@ codex plugin marketplace remove altimate-codex-plugin ## Reporting bugs / requesting features Please open a GitHub issue on this repo. For security-sensitive reports, see [SECURITY.md](./SECURITY.md). + +## Directory package checks + +Run `bash tests/directory-zip.sh` to exercise the real builder, validate archive +contents and listing images, and check reproducibility and rejection cases. +Run `python3 scripts/build_directory_zip.py` to produce the upload artifact. +See [DIRECTORY.md](DIRECTORY.md) before changing package inclusion rules. diff --git a/DIRECTORY-README.md b/DIRECTORY-README.md new file mode 100644 index 0000000..573b1dc --- /dev/null +++ b/DIRECTORY-README.md @@ -0,0 +1,27 @@ +# Altimate Code + +This desktop plugin provides skills for dbt and warehouse work and dbt/SQL review. +Choose plugin setup or ask “Set up Altimate” to get started. Setup is user initiated. + +The Altimate CLI is installed separately. Setup checks for `altimate-code` or +`altimate`, explains installation choices, and guides you to authenticate in your +own terminal. You can request the npm installation: + +```sh +npm install -g @altimateai/altimate-code +``` + +For the standalone installer, follow the +[CLI installation instructions](https://github.com/AltimateAI/altimate-code) +in your own terminal. Then choose a dbt/warehouse task or request a dbt/SQL review. + +This directory package excludes lifecycle hooks. For optional automatic session +behavior and workspace team rules, follow the +[full GitHub plugin installation](https://github.com/AltimateAI/altimate-codex-plugin#install). +Disable the directory copy first to avoid duplicate skills. Review and trust the +manual plugin's hooks before use. This is a guided switch, not an automatic upgrade. +To switch back, disable the manual copy and re-enable the directory copy. + +Read [PRIVACY.md](PRIVACY.md) before enabling learning. The CLI and its provider +have separate authentication and data processing. See [TERMS.md](TERMS.md) and +[SECURITY.md](SECURITY.md), or [get support](https://github.com/AltimateAI/altimate-codex-plugin/issues). diff --git a/DIRECTORY.md b/DIRECTORY.md new file mode 100644 index 0000000..22c499a --- /dev/null +++ b/DIRECTORY.md @@ -0,0 +1,89 @@ +# Altimate Code: directory installation + +Altimate Code provides skills for dbt and warehouse work and dbt/SQL review. +The Altimate CLI must be installed separately. Run plugin setup (`get-started`) +to check the CLI, choose an installation method and configure authentication in +your terminal. Setup is user-initiated, not an automatic popup. + +## Two distributions + +| Capability | Public-directory ZIP | GitHub marketplace plugin | +|---|---|---| +| Altimate Code and review skills | Included, identical source files | Included | +| Guided setup skill and listing images | Included | Included | +| Lifecycle hooks and legacy commands | Excluded | Included | +| Local stdio MCP | Excluded by default; optional approved-partner build | Included when the source plugin provides it | +| Automatic team rules and optional learning | Not provided by this package | Requires trusted hooks, a linked workspace and a compatible CLI | + +The GitHub plugin remains in `.codex-plugin/plugin.json` format. Do not add a +root Agent Plugins `plugin.json`: format changes can change hook loading. +The directory build derives a separate archive without modifying that source. + +## Build from the repository + +Run `python3 scripts/build_directory_zip.py`. The version comes from the source +manifest; the output is `dist/altimate-code-.zip`. CI builds and uploads +this archive after its package tests pass. The archive root is the plugin root, +not a wrapping repository folder. Repeated builds of identical sources produce +identical bytes. Increase the source version for a new submission. + +The builder includes only Markdown skills, image assets (with validated square +SVG listing icons), the legacy manifest, +the user-facing DIRECTORY-README.md (as README.md) and legal/security documents. It removes hooks, legacy commands, +app references and MCP registration, and sets `requires_local_executor: true`. +It rejects missing manifest-referenced icons and onboarding files, and unsupported +file types. It does not parse links or resource references inside skill Markdown; +check those manually during installation testing. New skills that require scripts need a deliberate +packaging change and tests before they can be included. + +Only after OpenAI confirms local MCP eligibility for the submitting organization, +use `python3 scripts/build_directory_zip.py --include-local-mcp`. This requires a +source `.mcp.json` with stdio servers and creates a distinct `-local-mcp.zip`. +MCP `env` values must be `${VARIABLE}` references; literal values are rejected. +Only `mcpServers` is accepted at the top level, with `command`, `args`, `cwd`, +`env` and optional `type: "stdio"` per server. Unknown fields are rejected. +Commands and arguments use a deliberately small portable grammar: names and +relative paths containing ASCII letters, digits, underscores, dots, hyphens and +slashes; paths cannot contain empty, dot or parent components. `${PLUGIN_ROOT}` +may prefix a path. Options use `--name`, `-n`, or `--name=value`; glued path flags, +URI/colon syntax, other variables, absolute and home-relative paths are rejected. +Credential-named options must use environment references instead. This is not a +general-purpose secret scanner: review all names and arguments for secrets before +upload. Arbitrary shell expressions and launcher-specific syntax are unsupported. +The flag records the operator's choice; it cannot verify OpenAI allowlisting. +It does not add a server or bundle the separately installed CLI. Confirm that +external CLI dependency is accepted for your submission before uploading. + +## Before submitting + +The listing images use the existing Altimate gradient mark from +`AltimateAI/altimate-frontend`, `apps/web/src/assets/images/altimate_logo.svg`, +revision `854b86ad83d8d1a6cab576aab1dad1abfc573f78`. +The source SHA-256 is `d643aeef2a7ff3442901391f32b3f6bef280e9e8c7bcc164727030a0e93f6d1b`. +Only the outer SVG dimensions and viewBox differ: transparent square padding +centers the original artwork without changing its paths, gradients or colors. + +- Complete organization/publisher identity verification and confirm submission + access. A successful build is not directory approval. +- Test a clean desktop install, setup and the actual skills using the built ZIP. +- Select the listing route before the first upload: OpenAI currently does not + support adding MCP to an existing skills-only listing. This builder does not + implement a remote HTTPS MCP service. +- If skills-only submissions are rejected, reply to the review email or contact + your OpenAI representative with the submission and organization IDs. Setting + `requires_local_executor` does not bypass eligibility requirements. +- Recheck the [submission rules](https://developers.openai.com/plugins/deploy/submission) + and [desktop-only rules](https://developers.openai.com/plugins/deploy/desktop-only). + Desktop-only directory installation is documented for the ChatGPT desktop app; + do not promise public-directory CLI installation. + +## Optional hooks + +For automatic session behavior, follow the +[GitHub installation instructions](https://github.com/AltimateAI/altimate-codex-plugin#install). +Disable the directory copy before enabling the manual plugin. Review and trust +hooks in `/hooks` in Codex CLI; new or changed definitions need review again. +Read [the privacy policy](https://github.com/AltimateAI/altimate-codex-plugin/blob/main/PRIVACY.md) +before enabling learning. To return to the directory version, disable the manual +plugin and re-enable the directory copy. The directory's core skills remain useful +without hooks; this optional flow must be disclosed during submission review. diff --git a/README.md b/README.md index fa30598..f08318e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Codex plugin that delegates dbt and warehouse work to [`altimate-code`](https:// ## What this gives your Codex agent -Two skills and matching slash commands. **`altimate-code`** routes tasks that touch live warehouse state, column lineage, cross-database work, query-cost attribution, schema diffs, PII detection, or FinOps reporting to the altimate-code subprocess. The skill body encodes: +Two task skills and matching slash commands, plus a `get-started` setup skill. **`altimate-code`** routes tasks that touch live warehouse state, column lineage, cross-database work, query-cost attribution, schema diffs, PII detection, or FinOps reporting to the altimate-code subprocess. The skill body encodes: - how to resolve the CLI (`altimate-code`, falling back to `altimate`) and detect that it is not installed - which agent persona (`fast-edit` / `analyst` / `builder`) to pick for the task shape @@ -87,3 +87,10 @@ After install, run `altimate` once to configure your LLM provider auth and wareh - **Terms of use:** [TERMS.md](./TERMS.md) — governs your use of the plugin and the connected Altimate services. - **Security disclosure:** [SECURITY.md](./SECURITY.md) — how to report a vulnerability. - **Contributing:** [CONTRIBUTING.md](./CONTRIBUTING.md) · [Code of Conduct](./CODE_OF_CONDUCT.md). + +## Public directory package + +The full GitHub installation retains lifecycle hooks. A separate build produces +a hook-free desktop directory ZIP with the same skills and guided setup. +See [DIRECTORY.md](DIRECTORY.md) for build commands, optional local MCP packaging, +and submission prerequisites. Building the archive does not publish a listing. diff --git a/plugins/altimate-code/.codex-plugin/plugin.json b/plugins/altimate-code/.codex-plugin/plugin.json index 5ad5015..2e97012 100644 --- a/plugins/altimate-code/.codex-plugin/plugin.json +++ b/plugins/altimate-code/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "altimate-code", - "version": "1.3.0", + "version": "1.4.0", "description": "Delegates dbt and warehouse work to altimate-code, a specialized CLI agent with 100+ purpose-built data tools (SQL analysis, column-level lineage, dbt build/test/run, warehouse profiling, FinOps, connectivity to Snowflake, BigQuery, Redshift, Databricks, Postgres, MySQL, DuckDB).", "author": { "name": "Altimate AI", @@ -22,10 +22,15 @@ ], "skills": "./skills/", "commands": "./commands/", + "extensions": { + "com.openai": { + "onboardingSkill": "./skills/get-started/SKILL.md" + } + }, "interface": { "displayName": "Altimate Code", - "shortDescription": "Delegate dbt + warehouse work to the altimate-code CLI agent", - "longDescription": "Routes data-engineering tasks — column-level lineage, cross-database validation, warehouse profiling, FinOps reporting, PII detection, dbt builds against real warehouses — to altimate-code, which already ships the specialised sub-skills internally. Ships two skills: `altimate-code` for delegation and `review` for dbt/SQL PR review with signed verdict envelopes. Use this plugin when you want Codex to hand a task to altimate-code rather than reimplement the workflow with native tools.", + "shortDescription": "dbt and warehouse workflows", + "longDescription": "Routes data-engineering tasks — column-level lineage, cross-database validation, warehouse profiling, FinOps reporting, PII detection, dbt builds against real warehouses — to altimate-code, which already ships the specialised sub-skills internally. Ships two task skills plus a `get-started` setup skill: `altimate-code` for delegation and `review` for dbt/SQL PR review with signed verdict envelopes. Use this plugin when you want Codex to hand a task to altimate-code rather than reimplement the workflow with native tools.", "developerName": "Altimate AI", "category": "Developer Tools", "capabilities": [ @@ -36,10 +41,12 @@ "defaultPrompt": [ "Compare row counts between prod and staging in Snowflake.", "Show column-level lineage for dim_customers.", - "Review my dbt changes.", - "Run altimate-code review on this PR." + "Review my dbt changes." ], "websiteURL": "https://altimate.ai", + "supportURL": "https://github.com/AltimateAI/altimate-codex-plugin/issues", + "logo": "./assets/logo.svg", + "composerIcon": "./assets/composer-icon.svg", "privacyPolicyURL": "https://altimate.ai/privacy", "termsOfServiceURL": "https://altimate.ai/terms", "brandColor": "#3B82F6" diff --git a/plugins/altimate-code/CHANGELOG.md b/plugins/altimate-code/CHANGELOG.md index d481de1..e1a8db3 100644 --- a/plugins/altimate-code/CHANGELOG.md +++ b/plugins/altimate-code/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to the Altimate Code Codex plugin are recorded here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.4.0] — 2026-11-17 + +- Add guided setup with an optional, explicitly chosen manual hooks installation. +- Add square listing images, support link, and directory-compatible listing text. +- Provide a reproducible directory ZIP build that excludes hooks and commands; + local MCP is excluded unless explicitly selected for an approved submission. +- Preserve the full GitHub plugin's legacy manifest and lifecycle hooks. + ## [1.3.0] — 2026-11-12 ### Added diff --git a/plugins/altimate-code/assets/composer-icon.svg b/plugins/altimate-code/assets/composer-icon.svg new file mode 100644 index 0000000..b8380c0 --- /dev/null +++ b/plugins/altimate-code/assets/composer-icon.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/altimate-code/assets/logo.svg b/plugins/altimate-code/assets/logo.svg new file mode 100644 index 0000000..85b0065 --- /dev/null +++ b/plugins/altimate-code/assets/logo.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/altimate-code/skills/get-started/SKILL.md b/plugins/altimate-code/skills/get-started/SKILL.md new file mode 100644 index 0000000..db8d550 --- /dev/null +++ b/plugins/altimate-code/skills/get-started/SKILL.md @@ -0,0 +1,57 @@ +--- +name: get-started +description: Set up the Altimate Code plugin, check the separately installed CLI, and explain optional lifecycle hooks for a manual Codex installation. Use when the user asks to set up Altimate or runs plugin setup. +--- + +# Get started with Altimate Code + +Explain that the plugin supplies skills; the Altimate CLI is installed separately. +Setup runs when the user chooses it. Do not claim an automatic install-time banner. + +1. Check for an executable `altimate-code`, then `altimate`, ignoring aliases and + shell functions as in the other Altimate skills. Run the resolved executable + with `--version` and confirm it identifies Altimate before using it. If a + different program owns `altimate`, stop and explain the name conflict. +2. If absent, offer the documented installation choices: + `npm install -g @altimateai/altimate-code` or + `curl -fsSL https://www.altimate.sh/install | bash`. + For agent-assisted installation, explain and run only the npm command, and + only when the user asks to install. The standalone curl command is for the + user to run in their own terminal after reviewing the installer. Never execute + the curl pipeline or download and execute its script through a tool call. + Never run both methods. Recheck the CLI afterward. +3. Ask the user to launch the resolved CLI in their terminal for interactive + authentication and warehouse/workspace setup if needed. Never request tokens + in chat. Do not launch an interactive TUI into a non-interactive tool call. +4. Explain the two included workflows: ask Altimate for dbt/warehouse help, or + ask it to review dbt/SQL changes. Do not run a warehouse query or start a + model-backed task merely to prove installation; let the user choose a task. + +## Optional automatic session behavior + +The directory package works without hooks. Offer this once during setup, not +every turn: the manual GitHub plugin adds session-start routing hints and, in +a linked workspace with the required CLI support, team rules. With learning +enabled, its prompt/Stop hooks can capture corrections and draft rule proposals. +These are optional. Explain the transcript processing and the Altimate CLI's +separate model/provider described in the repository's PRIVACY.md before enabling +learning; do not describe it as local-only processing. + +If the user chooses the manual plugin, link to +https://github.com/AltimateAI/altimate-codex-plugin#install and guide them: + +- Inspect existing installations in `/plugins`. Disable the directory copy + before enabling the manual copy so skills and MCP servers are not duplicated. +- Add the marketplace with + `codex plugin marketplace add AltimateAI/altimate-codex-plugin`, then select + `altimate-code` in `/plugins` to install/enable it. +- Open `/hooks` in Codex CLI (or the desktop hook review UI) to inspect and trust + the exact hook definitions. Never bypass trust or silently edit user config. +- Start a new session and confirm the hooks are listed and trusted. A successful + package installation alone does not prove hook execution or workspace access. + +If the installed Codex version lacks those controls, stop with its version and +link to the installation docs; do not invent a fallback installer. To undo the +optional installation, disable its hooks/plugin and re-enable the directory copy. +Do not promise remote MCP, skill refresh, or other capabilities unless present in +the installed plugin version. diff --git a/scripts/build_directory_zip.py b/scripts/build_directory_zip.py new file mode 100644 index 0000000..53c07b9 --- /dev/null +++ b/scripts/build_directory_zip.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Build a directory submission without modifying the full marketplace plugin.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo + +REPO = Path(__file__).resolve().parents[1] +MANIFEST = ".codex-plugin/plugin.json" + + +def read_file(path): + if path.is_symlink() or not path.is_file(): + raise ValueError(f"Expected a regular file, not a symlink: {path}") + return path.read_bytes() + + +def require_object(value, label): + if not isinstance(value, dict): + raise ValueError(f"{label} must be a JSON object") + return value + + +def validate_mcp_token(value): + """Accept a small portable argv grammar, not arbitrary shell/launcher syntax.""" + if not isinstance(value, str) or not value: + raise ValueError("MCP command, args and cwd must be nonempty strings") + token = value + if value.startswith("-"): + option, separator, token = value.partition("=") + if not re.fullmatch(r"--?[A-Za-z][A-Za-z0-9-]*", option): + raise ValueError("MCP options require separate values or --option=value syntax") + if re.search(r"token|secret|password|credential|api-?key|authorization", option, re.I): + raise ValueError("Pass MCP credentials through env variable references, not arguments") + if not separator: + return + # Variables in argv are intentionally limited to the install-relative root. + if token.startswith("${PLUGIN_ROOT}"): + token = token[len("${PLUGIN_ROOT}"):] + if token == "": + return + if not token.startswith("/"): + raise ValueError("MCP plugin-root paths require a slash separator") + token = token[1:] + if not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_./-]*", token): + raise ValueError("MCP values require portable names or ${PLUGIN_ROOT} paths") + if any(part in ("", ".", "..") for part in token.split("/")): + raise ValueError("MCP paths must not contain empty, dot or parent components") + + +def validate_local_mcp(mcp): + require_object(mcp, "MCP configuration") + if set(mcp) != {"mcpServers"}: + raise ValueError("MCP configuration supports only mcpServers") + servers = mcp["mcpServers"] + if not isinstance(servers, dict) or not servers: + raise ValueError("Local MCP mode requires at least one server") + for server in servers.values(): + require_object(server, "MCP server") + if set(server) - {"command", "args", "cwd", "env", "type"}: + raise ValueError("Unsupported MCP server fields; use command, args, cwd, env and type") + if server.get("type", "stdio") != "stdio": + raise ValueError("Local MCP mode accepts stdio servers only") + command = server.get("command") + validate_mcp_token(command) + if command.startswith("-"): + raise ValueError("MCP command must be an executable name or portable path") + args = server.get("args", []) + if not isinstance(args, list): + raise ValueError("MCP args must be an array of strings") + for value in args: + validate_mcp_token(value) + if "cwd" in server: + validate_mcp_token(server["cwd"]) + if server["cwd"].startswith("-"): + raise ValueError("MCP cwd must be a portable path") + env = require_object(server.get("env", {}), "MCP env") + if any(not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key) or + not isinstance(value, str) or not re.fullmatch(r"\$\{[A-Za-z_][A-Za-z0-9_]*\}", value) + for key, value in env.items()): + raise ValueError("MCP env values must be ${VARIABLE} references, not literal values") + + +def build(repo, output, include_local_mcp=False): + source = repo / "plugins/altimate-code" + manifest = require_object(json.loads(read_file(source / MANIFEST)), "Manifest") + version = manifest["version"] + if not isinstance(version, str) or not re.fullmatch(r"\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?", version): + raise ValueError("Manifest version must be a semantic version") + if (source / "plugin.json").exists(): + raise ValueError("Keep the source in the legacy .codex-plugin format") + interface = require_object(manifest["interface"], "Manifest interface") + for field in ("displayName", "shortDescription"): + if not isinstance(interface.get(field), str) or not 1 <= len(interface[field]) <= 30: + raise ValueError(f"interface.{field} must contain 1–30 characters") + prompts = interface.get("defaultPrompt", []) + if not isinstance(prompts, list) or not 1 <= len(prompts) <= 3: + raise ValueError("Provide 1–3 default prompts") + if any(not isinstance(p, str) or not 1 <= len(p) <= 128 or "@" in p for p in prompts) or len(set(prompts)) != len(prompts): + raise ValueError("Default prompts must be unique strings of 1–128 characters without @mentions") + for field in ("websiteURL", "supportURL", "privacyPolicyURL", "termsOfServiceURL"): + if not isinstance(interface.get(field), str) or not interface[field].startswith("https://"): + raise ValueError(f"interface.{field} must be an HTTPS URL") + + # Only portable skills and images belong in the directory artifact. No blanket + # copy of the source tree: future hooks, scripts, app references and secrets + # must not accidentally become part of a public upload. + files = {} + for directory in ("skills", "assets"): + root = source / directory + if root.is_symlink() or not root.is_dir(): + raise ValueError(f"Missing regular {directory} directory") + for path in sorted(root.rglob("*")): + relative = path.relative_to(source) + if path.is_symlink(): + raise ValueError(f"Symlinks are not allowed: {relative}") + if path.is_dir(): + continue + if any(part.startswith(".") for part in relative.parts): + raise ValueError(f"Hidden files are not allowed: {relative}") + allowed = {".md"} if directory == "skills" else {".svg", ".png", ".jpg", ".jpeg", ".webp"} + if path.suffix.lower() not in allowed: + raise ValueError(f"Unsupported directory package file: {relative}") + files[relative.as_posix()] = read_file(path) + + def require_packaged(path): + if not isinstance(path, str) or not path.startswith("./") or path[2:] not in files: + raise ValueError(f"Missing packaged resource: {path}") + + for field in ("logo", "composerIcon"): + require_packaged(interface.get(field)) + path = interface[field][2:] + if not path.endswith(".svg"): + raise ValueError("This builder validates SVG listing icons; add validation before using raster icons") + data = files[path] + if len(data) > 5 * 1024 * 1024: + raise ValueError("Listing icons must be at most 5 MiB") + try: + icon = ET.fromstring(data) + width, height = float(icon.attrib["width"]), float(icon.attrib["height"]) + except (ET.ParseError, KeyError, ValueError) as error: + raise ValueError("Listing SVGs require numeric width and height") from error + if icon.tag != "{http://www.w3.org/2000/svg}svg" or width != height or not width >= 48: + raise ValueError("Listing icons must be square SVGs at least 48px wide") + extensions = require_object(manifest.setdefault("extensions", {}), "Manifest extensions") + extension = require_object(extensions.setdefault("com.openai", {}), "OpenAI extension") + require_packaged(extension.get("onboardingSkill")) + for holder in (manifest, extension): + for key in ("hooks", "commands", "apps", "mcpServers"): + holder.pop(key, None) + manifest["requires_local_executor"] = True + manifest["skills"] = "./skills/" + if include_local_mcp: + mcp = json.loads(read_file(source / ".mcp.json")) + validate_local_mcp(mcp) + files[".mcp.json"] = (json.dumps(mcp, indent=2) + "\n").encode() + manifest["mcpServers"] = "./.mcp.json" + files[MANIFEST] = (json.dumps(manifest, indent=2) + "\n").encode() + for name in ("LICENSE", "PRIVACY.md", "TERMS.md", "SECURITY.md"): + files[name] = read_file(repo / name) + files["README.md"] = read_file(repo / "DIRECTORY-README.md") + + mode = "-local-mcp" if include_local_mcp else "" + output.mkdir(parents=True, exist_ok=True) + target = output / f"altimate-code-{version}{mode}.zip" + # Fixed timestamps, order and permissions make the same source reproducible. + with ZipFile(target, "w", compression=ZIP_DEFLATED) as archive: + for name, data in sorted(files.items()): + info = ZipInfo(name, date_time=(2020, 1, 1, 0, 0, 0)) + info.compress_type = ZIP_DEFLATED + info.create_system = 3 + info.external_attr = 0o100644 << 16 + archive.writestr(info, data) + return target + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, default=REPO / "dist") + parser.add_argument( + "--include-local-mcp", action="store_true", + help="Include stdio MCP only after OpenAI confirms organization allowlisting", + ) + args = parser.parse_args() + try: + target = build(REPO, args.output_dir, args.include_local_mcp) + except (ValueError, KeyError, OSError) as error: + parser.exit(1, f"Directory build failed: {error}\n") + print(target) + print("Package built; this does not establish OpenAI submission eligibility or approval.") + + +if __name__ == "__main__": + main() diff --git a/tests/directory-zip.sh b/tests/directory-zip.sh new file mode 100644 index 0000000..ee07b1a --- /dev/null +++ b/tests/directory-zip.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +python3 -m unittest discover -s "$ROOT/tests" -p 'test_directory_zip.py' -v diff --git a/tests/test_directory_zip.py b/tests/test_directory_zip.py new file mode 100644 index 0000000..98f4e3c --- /dev/null +++ b/tests/test_directory_zip.py @@ -0,0 +1,238 @@ +"""Exercise upload artifacts, not just the manifest transformation.""" + +import importlib.util +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +import xml.etree.ElementTree as ET +from zipfile import ZipFile + +REPO = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("builder", REPO / "scripts/build_directory_zip.py") +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) + + +class DirectoryZipTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.repo = Path(self.temp.name) / "repo" + self.source = self.repo / "plugins/altimate-code" + shutil.copytree(REPO / "plugins/altimate-code", self.source) + for name in ("LICENSE", "PRIVACY.md", "TERMS.md", "SECURITY.md", "DIRECTORY.md", "DIRECTORY-README.md"): + shutil.copyfile(REPO / name, self.repo / name) + self.out = Path(self.temp.name) / "dist" + + def manifest(self): + return json.loads((self.source / builder.MANIFEST).read_text()) + + def save_manifest(self, manifest): + (self.source / builder.MANIFEST).write_text(json.dumps(manifest)) + + def test_real_cli_build_and_archive_contract(self): + before = {p.relative_to(REPO): p.read_bytes() for p in + (REPO / "plugins/altimate-code").rglob("*") if p.is_file()} + subprocess.run(["python3", str(REPO / "scripts/build_directory_zip.py"), + "--output-dir", str(self.out)], check=True, capture_output=True) + archives = list(self.out.glob("*.zip")) + self.assertEqual(len(archives), 1) + with ZipFile(archives[0]) as archive: + names = set(archive.namelist()) + self.assertIn(".codex-plugin/plugin.json", names) + self.assertNotIn("plugin.json", names) + self.assertNotIn(".mcp.json", names) + self.assertNotIn(".app.json", names) + self.assertFalse(any(n.startswith(("hooks/", "commands/", "scripts/")) for n in names)) + manifest = json.loads(archive.read(builder.MANIFEST)) + self.assertTrue(manifest["requires_local_executor"]) + for holder in (manifest, manifest["extensions"]["com.openai"]): + self.assertFalse(set(holder) & {"hooks", "commands", "apps", "mcpServers"}) + self.assertLessEqual(len(manifest["interface"]["shortDescription"]), 30) + self.assertLessEqual(len(manifest["interface"]["defaultPrompt"]), 3) + for field in ("logo", "composerIcon"): + image = ET.fromstring(archive.read(manifest["interface"][field][2:])) + self.assertEqual(image.attrib["width"], image.attrib["height"]) + self.assertGreaterEqual(int(image.attrib["width"]), 48) + for path in (REPO / "plugins/altimate-code/skills").rglob("*.md"): + self.assertEqual(archive.read(path.relative_to(REPO / "plugins/altimate-code").as_posix()), path.read_bytes()) + self.assertIn(manifest["extensions"]["com.openai"]["onboardingSkill"][2:], names) + for name in ("LICENSE", "PRIVACY.md", "TERMS.md", "SECURITY.md"): + self.assertEqual(archive.read(name), (REPO / name).read_bytes()) + self.assertEqual(archive.read("README.md"), (REPO / "DIRECTORY-README.md").read_bytes()) + self.assertTrue(all((REPO / p).read_bytes() == data for p, data in before.items())) + self.assertTrue((REPO / "plugins/altimate-code/hooks/hooks.json").exists()) + + def test_reproducible(self): + target = builder.build(self.repo, self.out) + first = target.read_bytes() + self.assertEqual(builder.build(self.repo, self.out).read_bytes(), first) + with ZipFile(target) as archive: + self.assertEqual(archive.namelist(), sorted(archive.namelist())) + for info in archive.infolist(): + self.assertEqual(info.date_time, (2020, 1, 1, 0, 0, 0)) + self.assertEqual(info.external_attr, 0o100644 << 16) + self.assertEqual(info.create_system, 3) + + def test_listing_artwork_matches_official_source(self): + # Hash of the unmodified content after the outer opening SVG tag in + # altimate-frontend's altimate_logo.svg, revision documented in DIRECTORY.md. + expected = "41237a050140116a0cde5beb481a572a0ef1cf70c9488ad1c620d13a0de26b12" + for name in ("logo", "composer-icon"): + svg = (self.source / f"assets/{name}.svg").read_bytes() + self.assertEqual(hashlib.sha256(svg.split(b">", 1)[1]).hexdigest(), expected) + + def test_mcp_only_on_explicit_opt_in_and_separate_artifact(self): + mcp = {"mcpServers": {"altimate-code": {"command": "altimate-code", "args": ["mcp", "serve", "--workspace-tools"]}}} + (self.source / ".mcp.json").write_text(json.dumps(mcp)) + manifest = self.manifest() + manifest.update({"mcpServers": "./.mcp.json", "apps": "./.app.json", "commands": "./commands/", "hooks": "./hooks/hooks.json"}) + manifest["extensions"]["com.openai"].update({"mcpServers": "./.mcp.json", "apps": "./.app.json", "commands": "./commands/", "hooks": "./hooks/hooks.json"}) + self.save_manifest(manifest) + (self.source / ".app.json").write_text('{"apps": {}}') + ordinary = builder.build(self.repo, self.out) + local = builder.build(self.repo, self.out, True) + self.assertNotEqual(ordinary, local) + for target in (ordinary, local): + with ZipFile(target) as archive: + packaged = json.loads(archive.read(builder.MANIFEST)) + for holder in (packaged, packaged["extensions"]["com.openai"]): + self.assertFalse(set(holder) & {"hooks", "commands", "apps"}) + self.assertNotIn("mcpServers", packaged["extensions"]["com.openai"]) + with ZipFile(ordinary) as archive: + self.assertNotIn(".mcp.json", archive.namelist()) + self.assertNotIn("mcpServers", json.loads(archive.read(builder.MANIFEST))) + with ZipFile(local) as archive: + self.assertEqual(json.loads(archive.read(".mcp.json")), mcp) + self.assertEqual(json.loads(archive.read(builder.MANIFEST))["mcpServers"], "./.mcp.json") + self.assertNotIn(".app.json", archive.namelist()) + + def test_mcp_mode_rejects_missing_and_remote_server(self): + with self.assertRaises((ValueError, OSError)): + builder.build(self.repo, self.out, True) + (self.source / ".mcp.json").write_text('{"mcpServers":{"remote":{"url":"https://example.com/mcp"}}}') + with self.assertRaises(ValueError): + builder.build(self.repo, self.out, True) + + def test_invalid_metadata_fails_without_archive(self): + original = self.manifest() + for field, value in (("shortDescription", "x" * 31), ("displayName", "x" * 31), + ("defaultPrompt", ["x"] * 4), ("defaultPrompt", ["x" * 129]), + ("defaultPrompt", ["Ask @altimate for help"]), ("logo", "../secret.svg"), + ("supportURL", "http://example.com")): + with self.subTest(field=field): + manifest = json.loads(json.dumps(original)) + manifest["interface"][field] = value + self.save_manifest(manifest) + with self.assertRaises(ValueError): + builder.build(self.repo, self.out) + self.assertFalse(self.out.exists()) + + def test_missing_onboarding_rejected(self): + (self.source / "skills/get-started/SKILL.md").unlink() + with self.assertRaises(ValueError): + builder.build(self.repo, self.out) + + def test_mcp_rejects_literal_environment_values_without_exposing_them(self): + for env in ({"TOKEN": "synthetic-secret"}, {"TOKEN": "prefix-${TOKEN}"}, + {"TOKEN": 7}, {"TOKEN": None}, [], None): + with self.subTest(env=env): + config = {"mcpServers": {"example": {"command": "example", "env": env}}} + (self.source / ".mcp.json").write_text(json.dumps(config)) + with self.assertRaises(ValueError) as error: + builder.build(self.repo, self.out, True) + self.assertNotIn("synthetic-secret", str(error.exception)) + self.assertFalse(self.out.exists()) + config["mcpServers"]["example"]["env"] = {"TOKEN": "${TOKEN}"} + (self.source / ".mcp.json").write_text(json.dumps(config)) + with ZipFile(builder.build(self.repo, self.out, True)) as archive: + self.assertEqual(json.loads(archive.read(".mcp.json")), config) + + def test_mcp_rejects_machine_local_paths(self): + for field, value in (("command", "/Users/example/bin/mcp"), + ("args", ["--config=/Users/example/config.json"]), + ("args", [r"C:\Users\example\config.json"]), + ("cwd", "~/workspace"), ("command", "./local-server"), + ("args", ["--config=../private/config.json"]), + ("cwd", "../workspace"), ("cwd", r"..\workspace")): + with self.subTest(field=field, value=value): + server = {"command": "example", field: value} + (self.source / ".mcp.json").write_text(json.dumps({"mcpServers": {"example": server}})) + with self.assertRaises(ValueError): + builder.build(self.repo, self.out, True) + self.assertFalse(self.out.exists()) + + def test_reviewed_mcp_bypasses_rejected(self): + values = ["server/../../../../Users/me/x.js", "--config=cfg/../../etc/secret", + "-c/Users/me/cfg.json", "-javaagent:/Users/me/a.jar", + "file:///Users/me/srv.js", "$HOME/srv/index.js", "${HOME}/srv/index.js", + "--token=sk-live-synthetic", "--token", "${PLUGIN_ROOT}/../secret", + "--config=${PLUGIN_ROOT}/cfg/../../secret"] + for value in values: + with self.subTest(value=value): + config = {"mcpServers": {"example": {"command": "example", "args": [value]}}} + (self.source / ".mcp.json").write_text(json.dumps(config)) + with self.assertRaises(ValueError): + builder.build(self.repo, self.out, True) + self.assertFalse(self.out.exists()) + + def test_mcp_schema_and_portable_references(self): + for field, value in (("type", "http"), ("headers", {"Authorization": "secret"}), + ("env_vars", {"TOKEN": "secret"}), ("unknown", "secret")): + with self.subTest(field=field): + config = {"mcpServers": {"example": {"command": "example", field: value}}} + (self.source / ".mcp.json").write_text(json.dumps(config)) + with self.assertRaises(ValueError): + builder.build(self.repo, self.out, True) + config = {"mcpServers": {"example": {"type": "stdio", "command": "node", + "args": ["${PLUGIN_ROOT}/server/index.js", "--config=${PLUGIN_ROOT}/config.json"], + "cwd": "${PLUGIN_ROOT}", "env": {"TOKEN": "${TOKEN}"}}}} + (self.source / ".mcp.json").write_text(json.dumps(config)) + with ZipFile(builder.build(self.repo, self.out, True)) as archive: + self.assertEqual(json.loads(archive.read(".mcp.json")), config) + config["extra"] = {"secret": "literal"} + (self.source / ".mcp.json").write_text(json.dumps(config)) + with self.assertRaises(ValueError): + builder.build(self.repo, self.out, True) + + def test_malformed_metadata_cli_errors_are_friendly(self): + script = self.repo / "scripts/build_directory_zip.py" + script.parent.mkdir() + shutil.copyfile(REPO / "scripts/build_directory_zip.py", script) + original = self.manifest() + malformed = [[], {**original, "version": 123}, {**original, "interface": []}, + {**original, "interface": {**original["interface"], "websiteURL": None}}, + {**original, "extensions": []}, + {**original, "extensions": {"com.openai": None}}] + for manifest in malformed: + with self.subTest(manifest=manifest): + self.save_manifest(manifest) + result = subprocess.run(["python3", str(script), "--output-dir", str(self.out)], + capture_output=True, text=True) + self.assertEqual(result.returncode, 1) + self.assertIn("Directory build failed:", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertFalse(self.out.exists()) + + def test_non_square_icon_rejected(self): + (self.source / "assets/logo.svg").write_text('') + with self.assertRaises(ValueError): + builder.build(self.repo, self.out) + + def test_symlink_and_unreviewed_skill_payload_rejected(self): + link = self.source / "assets/leak.svg" + link.symlink_to(self.repo / "PRIVACY.md") + with self.assertRaises(ValueError): + builder.build(self.repo, self.out) + link.unlink() + (self.source / "skills/get-started/install.sh").write_text("exit 0") + with self.assertRaises(ValueError): + builder.build(self.repo, self.out) + + +if __name__ == "__main__": + unittest.main()