diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 47f0b1b..cede52c 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -41,6 +41,14 @@ "version": "0.1.0", "keywords": ["video", "transcript", "screenshots", "yt-dlp", "reference-material"], "category": "utilities" + }, + { + "name": "zae", + "source": "./plugins/zae", + "description": "Hand-picked skills, agents, commands and output styles from other plugins, pinned to an upstream commit, plus our own", + "version": "0.1.0", + "keywords": ["curated", "skills", "writing", "vendored"], + "category": "productivity" } ] } diff --git a/README.md b/README.md index bed69b0..9cdf31a 100644 --- a/README.md +++ b/README.md @@ -10,10 +10,14 @@ A collection of Claude Code plugins for ZeroAE development standards and workflo |--------|-------------| | [`zstd`](plugins/zstd/) | Organization-wide development standards and conventions | | [`cspy`](plugins/cspy/) | Architecture patterns from [Cosmic Python](https://cosmicpython.com) for domain-driven design | +| [`dynamodb`](plugins/dynamodb/) | DynamoDB single-table design patterns, schema design and audits, based on Rick Houlihan's re:Invent talks | +| [`vidref`](plugins/vidref/) | Extract transcripts and screenshots from videos for skill reference material | +| [`zae`](plugins/zae/) | Hand-picked skills from other plugins, pinned to an upstream commit, plus our own | ## Installation ``` +/plugin marketplace add zeroae/claude-plugins /plugin install {plugin-name}@zeroae.com ``` diff --git a/plugins/cspy/.claude-plugin/plugin.json b/plugins/cspy/.claude-plugin/plugin.json index 82337b0..5067b4e 100644 --- a/plugins/cspy/.claude-plugin/plugin.json +++ b/plugins/cspy/.claude-plugin/plugin.json @@ -5,7 +5,7 @@ "author": { "name": "ZeroAE" }, - "repository": "https://github.com/zeroae/.claude", + "repository": "https://github.com/zeroae/claude-plugins", "license": "CC-BY-NC-ND-3.0", "keywords": ["architecture", "ddd", "patterns", "python", "cosmic-python", "repository-pattern", "unit-of-work", "cqrs", "event-driven"], "skills": "./skills/" diff --git a/plugins/dynamodb/.claude-plugin/plugin.json b/plugins/dynamodb/.claude-plugin/plugin.json index 31ba514..974a601 100644 --- a/plugins/dynamodb/.claude-plugin/plugin.json +++ b/plugins/dynamodb/.claude-plugin/plugin.json @@ -6,7 +6,7 @@ "name": "ZeroAE", "url": "https://github.com/zeroae" }, - "repository": "https://github.com/zeroae/.claude", + "repository": "https://github.com/zeroae/claude-plugins", "license": "MIT", "keywords": ["dynamodb", "nosql", "aws", "data-modeling", "single-table-design"], "skills": "./skills/" diff --git a/plugins/dynamodb/README.md b/plugins/dynamodb/README.md index 699de13..455e57a 100644 --- a/plugins/dynamodb/README.md +++ b/plugins/dynamodb/README.md @@ -18,14 +18,13 @@ Expert guidance on DynamoDB schema design using NoSQL-native patterns: |-------|---------------| | `help` | "How do I use the DynamoDB plugin?", `/dynamodb:help` | | `patterns` | Asking about DynamoDB design, access patterns, single-table design, GSIs | -| `design` | "Help me design a DynamoDB schema for X", "Model my data for DynamoDB" | -| `audit` | "Audit my DynamoDB schema", "Review this table design", "Check for issues" | +| `schema` | Design a new schema ("Help me design a DynamoDB schema for X", "Model my data for DynamoDB") or audit an existing one ("Audit my DynamoDB schema", "Review this table design") | ## Agents | Agent | Triggers When | |-------|---------------| -| `schema-auditor` | User shares DynamoDB code (CDK/CloudFormation/Terraform) and asks for feedback | +| `auditor` | User shares DynamoDB code (CDK/CloudFormation/Terraform) and asks for feedback | ## Usage Examples @@ -54,7 +53,7 @@ Expert guidance on DynamoDB schema design using NoSQL-native patterns: ## Diagram Outputs -The `design` skill generates visual diagrams to help understand schema structure: +The `schema` skill generates visual diagrams to help understand schema structure: | Diagram Type | Format | Purpose | |--------------|--------|---------| diff --git a/plugins/vidref/.claude-plugin/plugin.json b/plugins/vidref/.claude-plugin/plugin.json index 0b98ee4..a7a03cd 100644 --- a/plugins/vidref/.claude-plugin/plugin.json +++ b/plugins/vidref/.claude-plugin/plugin.json @@ -6,7 +6,7 @@ "name": "ZeroAE", "url": "https://github.com/zeroae" }, - "repository": "https://github.com/zeroae/.claude", + "repository": "https://github.com/zeroae/claude-plugins", "license": "MIT", "keywords": ["video", "transcript", "screenshots", "yt-dlp", "reference-material"], "skills": "./skills/" diff --git a/plugins/zae/.claude-plugin/plugin.json b/plugins/zae/.claude-plugin/plugin.json new file mode 100644 index 0000000..86277df --- /dev/null +++ b/plugins/zae/.claude-plugin/plugin.json @@ -0,0 +1,13 @@ +{ + "name": "zae", + "version": "0.1.0", + "description": "Hand-picked skills, agents, commands and output styles from other plugins, pinned to an upstream commit, plus our own", + "author": { + "name": "ZeroAE", + "url": "https://github.com/zeroae" + }, + "repository": "https://github.com/zeroae/claude-plugins", + "license": "MIT", + "keywords": ["curated", "skills", "writing", "vendored"], + "skills": "./skills/" +} diff --git a/plugins/zae/README.md b/plugins/zae/README.md new file mode 100644 index 0000000..88aac18 --- /dev/null +++ b/plugins/zae/README.md @@ -0,0 +1,79 @@ +# zae + +Hand-picked pieces of other people's plugins, one skill (or agent, command, +output style) at a time, next to ones we write ourselves. Call them as +`/zae:`. + +## Install + +``` +/plugin marketplace add zeroae/claude-plugins +/plugin install zae@zeroae.com +``` + +On Claude Code 2.1.275 or later, one step does both: + +``` +/plugin install zae --marketplace zeroae/claude-plugins +``` + +## Skills + +| Skill | Description | From | +|-------|-------------|------| +| `unslop` | Cut AI tells from any writing | [pstack-claude](https://github.com/michael-denyer/pstack-claude/tree/main/plugins/pstack/skills/unslop) (poteto's pstack), MIT | + +## Output styles + +| Style | Description | From | +|-------|-------------|------| +| `zae-plain` | Plain, direct replies with no AI tells. Keeps Claude Code's coding instructions | Our own, condensed from `unslop`'s rules | + +An output style applies to every reply in a session, so it is opt-in: pick it +with `/output-style`, or set `outputStyle` in `~/.claude/settings.json`. It +does not set `force-for-plugin`, so enabling `zae` does not turn it on. + +## Picked vs. our own + +A picked component is a copy of an upstream file or folder at a pinned +commit. [`vendored.json`](vendored.json) records, for each one, the upstream +repo and path, the commit, the git object id, the license and a hash of the +copied files. Do not edit a picked component by hand: `check` fails on it. +To change one, make it our own (below). + +Anything under `skills/`, `agents/`, `commands/` or `output-styles/` that +`vendored.json` does not list is our own. Write it here like in any other +plugin. + +## Managing picks + +From the repo root: + +```bash +# Pick a skill: a GitHub tree URL gives repo, ref and path in one go +scripts/zae-vendor.py add https://github.com///tree/main/skills/ + +# Or owner/repo and a path; --as renames it or says what kind it is +scripts/zae-vendor.py add / plugins/x/agents/reviewer.md --as agents/reviewer.md + +scripts/zae-vendor.py status # which picks are behind upstream HEAD (exit 2 = some are) +scripts/zae-vendor.py update skills/unslop # re-copy at upstream HEAD (or --ref ) +scripts/zae-vendor.py update --all +scripts/zae-vendor.py check # copies match vendored.json +scripts/zae-vendor.py remove skills/unslop +``` + +`add` and `update` refuse upstreams with no LICENSE near the component, and +symlinks. They copy that license to `licenses/`. They print a REVIEW block +when what the component can run or widen changes: frontmatter `hooks`, +`allowed-tools`, `tools`, `mcpServers`, `permissionMode` or `model`, and +executable files. Read the diff before you commit, like any third-party code. + +To make a picked component our own, so you can edit it: copy it aside, +`remove` it, put the copy back and edit away. Keep its license file in +`licenses/` and say where it came from in the table above. + +## License + +Our own content: MIT. Each picked component keeps its upstream license, copied +to [`licenses/`](licenses/) and named in `vendored.json`. diff --git a/plugins/zae/licenses/michael-denyer__pstack-claude.txt b/plugins/zae/licenses/michael-denyer__pstack-claude.txt new file mode 100644 index 0000000..3ebb69c --- /dev/null +++ b/plugins/zae/licenses/michael-denyer__pstack-claude.txt @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 Lauren Tan +Copyright (c) 2026 Michael Denyer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/zae/output-styles/zae-plain.md b/plugins/zae/output-styles/zae-plain.md new file mode 100644 index 0000000..dd3b2be --- /dev/null +++ b/plugins/zae/output-styles/zae-plain.md @@ -0,0 +1,47 @@ +--- +name: zae-plain +description: Plain, direct replies with no AI tells. Condensed from the unslop skill's rules. +keep-coding-instructions: true +--- + +# Plain replies + +Write like an engineer talking to a colleague. These rules apply to your replies in chat. For an editing pass over a document, a README or a PR body, use the `unslop` skill, which has the full rules. + +## Open and close + +- Start with the answer. No "Great question!", "You're absolutely right!", "Of course!" or "Certainly!". +- End when the content ends. No "I hope this helps!", "Let me know if...", or a summary line that repeats what you just said. +- No closing lines about the future ("The future looks bright"). Give the next concrete step, or nothing. + +## Words + +- Use the plain word: "use", not "utilize" or "leverage". "Help", not "facilitate". "Many", not "numerous". "If", not "in the event that". +- Avoid stock AI vocabulary: additionally, crucial, delve, enhance, fostering, garner, interplay, intricate, landscape, pivotal, showcase, tapestry, testament, underscore, vibrant. +- Say "is" or "has". Not "serves as", "stands as", "boasts" or "features". +- Skip metaphor jargon when a concrete word exists: substrate, wedge, vector, nexus, paradigm, north star, flywheel, surface (as in "API surface"), primitive (as a noun), harness (as a metaphor). +- Name things once and keep the name. Don't cycle synonyms. + +## Sentences + +- One idea per sentence. Split a sentence that makes the reader backtrack. +- Prefer active voice and name the actor: "the loader parses the file", not "the file is parsed". +- Cut filler: "to", not "in order to". "Because", not "due to the fact that". Drop "It is important to note that". +- Hedge once, where the doubt is real: "may", not "could potentially possibly". +- No "not just X, but Y". State the point. +- Group things in the number they come in, not in threes by habit. +- Say what something does, with a mechanism or a number, not how it feels. +- Name the source of a claim, or drop the claim. No "experts say". + +## Punctuation and formatting + +- No em dashes. Use a period or a comma. +- Colons go before a list or an example, not between two halves of a sentence. +- Bold sparingly, for the one thing the reader must not miss. +- Headings in sentence case. Straight quotes. +- No decorative emojis in headings, bullets or prose. + +## Exceptions + +- Follow the project's conventions where they conflict with these rules. Gitmoji prefixes on ZeroAE commits and issue titles (`✨ feat(scope): ...`) are required, not decorative. +- Leave code, commands, file paths, URLs, quoted text and error messages exactly as they are. diff --git a/plugins/zae/skills/unslop/SKILL.md b/plugins/zae/skills/unslop/SKILL.md new file mode 100644 index 0000000..be42292 --- /dev/null +++ b/plugins/zae/skills/unslop/SKILL.md @@ -0,0 +1,61 @@ +--- +name: unslop +description: Cut AI tells from any writing. +--- + +# Unslop + +Edit text to remove AI patterns. Scan for the patterns below, then rewrite. Preserve meaning and match the intended tone. + +## Patterns to detect and fix + +Rule numbers are stable ids that other skills cite. A removed rule leaves a gap. + +### Content + +3. **Superficial -ing phrases.** "highlighting...", "ensuring...", "reflecting...", "showcasing...", "fostering...". Delete or expand with real sources. +5. **Vague attributions.** "Experts believe", "Industry reports suggest", "Some critics argue". Name the source or delete. + +### Language + +7. **AI vocabulary.** Additionally, crucial, delve, enduring, enhance, fostering, garner, interplay, intricate, landscape (abstract), pivotal, showcase, tapestry (abstract), testament, underscore, vibrant. Replace with plain words. +8. **Fancy ways to say "is".** "serves as", "stands as", "boasts", "features". Say "is" or "has". +9. **"Not just X, but Y."** State the point directly instead. +10. **Rule of three.** Don't force ideas into groups of three. Use the natural number. +11. **Synonym cycling.** Protagonist, main character, central figure, hero all in one paragraph. Pick one, repeat it. +12. **False ranges.** "from X to Y" where X and Y aren't on a meaningful scale. List topics directly. + +### Style + +13. **Em dash overuse.** Avoid em dashes entirely. Use periods or commas only (no parentheses, no en dashes, no hyphen-as-dash substitutes). If a thought needs separation, end the sentence or use a comma. +14. **Colon overuse.** Colons are fine before a list or example, not as mid-sentence connectors. "If you're coming from traditional automation: instead of registering event handlers, you describe conditions" adds nothing with the colon. Rewrite to let the point stand on its own without comparison framing. "Describing when the scheduler should fire works best as plain English." Same meaning, no crutch punctuation. +15. **Boldface overuse.** Don't bold every proper noun or acronym. +16. **Inline-header lists.** The tell is a bold label and colon that restates the line: "**Performance:** Performance improved...". Convert those to prose. A bold lead-in that ends in a period, names the item, and is followed by genuinely new detail ("**Schema in TypeScript.** Tables live in one file.") is fine, not a tell. +17. **Title case headings.** Use sentence case. +18. **Decorative emojis.** Remove from headings and bullets. +19. **Curly quotes.** Use straight quotes. + +### Communication artifacts + +20. **Chatbot phrases.** "I hope this helps!", "Let me know if...", "Of course!", "Certainly!", "Found the smoking gun!" Remove. +22. **Sycophantic tone.** "Great question! You're absolutely right!" Respond directly. + +### Filler + +23. **Filler phrases.** "In order to" becomes "To". "Due to the fact that" becomes "Because". Delete "It is important to note that". +24. **Excessive hedging.** "could potentially possibly be argued that it might" becomes "may". +25. **Generic conclusions.** "The future looks bright." State specific plans or facts. + +### Jargon + +26. **Abstract metaphor nouns.** Substrate (base), wedge, wedge in (add), vector (way, method), locus, vantage, nexus, primitive as a noun, harness as a metaphor, surface as in "API surface", bedrock, scaffolding as a metaphor, modality, paradigm, gold-plating (more than the job needs), ratchet as a metaphor (the mechanism's real name, or a limit that only tightens), evacuate for moving code (move out), endgame (the last phase), north star, flywheel. These read as technical but usually have a plainer concrete word. Pick the concrete word. + +### Plain speech + +27. **Say what it does, not how it feels.** "the database stays close at hand", "SQL you can read", "types that follow your schema" name a feeling. The fix names the mechanism or a number: "`.toSQL()` returns the exact string sent to the database", "a column rename fails the build". Ask what the sentence tells the reader to do or know, then write that. If you can't restate it as a concrete instruction, fact, or number, cut it. One more check: if the sentence could appear unchanged in another project's docs, it says nothing about this one. Cut it. +28. **Shorten or split dense sentences.** If the reader has to backtrack to parse a sentence, break it in two or drop clauses. One idea per sentence. +29. **Active voice.** Prefer it. Catch "is/are/was/were + past participle" and name the actor: "queries are validated" becomes "the compiler validates queries", "the file is parsed by the loader" becomes "the loader parses the file". Passive is fine only when the actor is unknown or genuinely doesn't matter. +30. **Cut adverbs, or use a stronger verb.** "runs quickly" becomes "is fast" or the number, and "significantly improves" becomes the measured delta. An adverb propping up a weak verb means the verb is wrong. +31. **Prefer the plain word.** "utilize" and "leverage" become "use", "facilitate" becomes "help", "numerous" becomes "many", "in the event that" becomes "if". The fancier synonym is rarely clearer. +32. **Mannered prose.** Metaphor or flourish where a literal phrase exists: aphorisms ("wire it or delete it"), rhetorical fragments for effect, personified code ("the plan holds it"), figurative verbs ("rides along", "stands on"), stock framing phrases. "A dial worth turning" becomes "a parameter worth varying". Say what you mean. Rule 26 covers the metaphor nouns. +33. **Over-compression.** Dropped articles, verbless fragments, symbol-speak, and abbreviations that make the reader decode instead of read. "Parser rejects bad date → exit 2, no write" becomes "The parser rejects a bad date, exits with code 2, and writes nothing." Write whole sentences with their articles and verbs, and spell out arrows and abbreviations. diff --git a/plugins/zae/vendored.json b/plugins/zae/vendored.json new file mode 100644 index 0000000..5fe338f --- /dev/null +++ b/plugins/zae/vendored.json @@ -0,0 +1,15 @@ +{ + "components": { + "skills/unslop": { + "upstream": "https://github.com/michael-denyer/pstack-claude.git", + "path": "plugins/pstack/skills/unslop", + "ref": "d88063f3355a5ecff0e6dbb890a11bab4b08bc2e", + "object": "0c1e9c3014f788044725640bb0159562b5543068", + "license": "MIT", + "license_file": "licenses/michael-denyer__pstack-claude.txt", + "vendored_on": "2026-11-05", + "content_sha256": "acbe5327bed34310a121e825e5959c09c3ac63436ab873a252fff3d45c4b2bc6", + "needs_review": [] + } + } +} diff --git a/plugins/zstd/.claude-plugin/plugin.json b/plugins/zstd/.claude-plugin/plugin.json index 674f573..7e4fca2 100644 --- a/plugins/zstd/.claude-plugin/plugin.json +++ b/plugins/zstd/.claude-plugin/plugin.json @@ -5,7 +5,7 @@ "author": { "name": "ZeroAE" }, - "repository": "https://github.com/zeroae/.claude", + "repository": "https://github.com/zeroae/claude-plugins", "license": "MIT", "keywords": ["conventions", "standards", "commits", "github", "changelog"], "skills": "./skills/" diff --git a/scripts/zae-vendor.py b/scripts/zae-vendor.py new file mode 100755 index 0000000..de0552b --- /dev/null +++ b/scripts/zae-vendor.py @@ -0,0 +1,436 @@ +#!/usr/bin/env python3 +"""The pieces of the zae plugin that were picked from other people's plugins. + +A component is one skill folder, or one agent, command or output-style file, +copied into plugins/zae/ from an upstream git repository at a pinned commit. +plugins/zae/vendored.json records where each came from and a hash of what was copied. +Anything under plugins/zae/ that vendored.json does not list is our own and +this script leaves it alone. + + add [] [--as ] [--ref ] + pick a component. is owner/repo, a git URL, or a + GitHub tree/blob URL (which also gives the ref and path) + update [--ref ] + re-copy a component at (default: upstream HEAD) + update --all the same for every component + remove drop a component and its record + status each component's pin against upstream HEAD (network; + exit 2 = an update is available) + check the copied files equal what vendored.json records + install add the zeroae.com marketplace from GitHub (zeroae/claude-plugins) + and install zae@zeroae.com (once per machine) + + is the component's path inside plugins/zae, e.g. skills/unslop. +""" + +from __future__ import annotations + +import argparse +import datetime +import hashlib +import json +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +PLUGIN = ROOT / "plugins" / "zae" +LICENSES = PLUGIN / "licenses" +LOCK = PLUGIN / "vendored.json" +CATALOGUE = ROOT / ".claude-plugin" / "marketplace.json" +GITHUB_REPO = "zeroae/claude-plugins" +# Where each kind lives in a plugin, and whether it is a folder or one .md file. +KINDS = {"skills": "dir", "agents": "file", "commands": "file", "output-styles": "file"} +# Upstream files a component does not need, at any depth. +SKIP = {".git", "node_modules", ".github", ".DS_Store"} +# Frontmatter keys that change what Claude may run or reach: review them on every update. +REVIEW_KEYS = ("hooks", "allowed-tools", "tools", "mcpServers", "permissionMode", "model") +LICENSE_NAMES = ("LICENSE", "LICENSE.md", "LICENSE.txt", "LICENCE", "COPYING") + + +def die(msg: str) -> None: + print(f"zae: {msg}", file=sys.stderr) + sys.exit(1) + + +def load_lock() -> dict: + return json.loads(LOCK.read_text()) + + +def save_lock(lock: dict) -> None: + lock["components"] = dict(sorted(lock["components"].items())) + LOCK.write_text(json.dumps(lock, indent=2) + "\n") + + +def git(*args: str, cwd: Path | None = None) -> str: + run = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True) + if run.returncode != 0: + die(f"git {' '.join(args)} failed:\n{run.stderr.strip()}") + return run.stdout.strip() + + +def fetch(url: str, ref: str, dest: Path, *, blobs: bool = True) -> str: + git("init", "-q", str(dest)) + git("fetch", "-q", "--depth", "1", *([] if blobs else ["--filter=blob:none"]), url, ref, cwd=dest) + return git("rev-parse", "FETCH_HEAD", cwd=dest) + + +def object_of(clone: Path, path: str) -> str: + """The git object id of the component: equal ids mean identical content.""" + return git("rev-parse", f"FETCH_HEAD:{path}", cwd=clone) + + +def files_of(target: Path) -> list[Path]: + if target.is_file(): + return [target] + return sorted(p for p in target.rglob("*") if p.is_file() and not p.is_symlink()) + + +def symlinks(target: Path) -> list[str]: + if target.is_symlink(): + return [target.name] + if not target.is_dir(): + return [] + return sorted(p.relative_to(target).as_posix() for p in target.rglob("*") if p.is_symlink()) + + +def content_hash(target: Path) -> str: + """sha256 over every file's relative path, exec bit and bytes, in sorted order.""" + h = hashlib.sha256() + base = target.parent if target.is_file() else target + for path in files_of(target): + rel = path.relative_to(base).as_posix() + mode = b"x" if path.stat().st_mode & 0o111 else b"-" + h.update(rel.encode() + b"\0" + mode) + h.update(hashlib.sha256(path.read_bytes()).digest()) + return h.hexdigest() + + +def frontmatter(md: Path) -> tuple[str, list[str]]: + """(name, the lines that set a REVIEW_KEYS key) from a markdown file's frontmatter.""" + text = md.read_text(errors="replace") + m = re.match(r"---\n(.*?)\n---", text, re.S) + if not m: + return "", [] + name, review = "", [] + for line in m.group(1).splitlines(): + key = line.split(":", 1)[0].strip() + if key == "name" and not line.startswith(" "): + name = line.split(":", 1)[1].strip().strip("\"'") + if key in REVIEW_KEYS and not line.startswith(" "): + review.append(line.strip()) + return name, review + + +def needs_review(target: Path) -> list[str]: + """What in a component can run something or widen Claude's permissions.""" + md = target / "SKILL.md" if target.is_dir() else target + found = [f"frontmatter {line}" for line in frontmatter(md)[1]] if md.is_file() else [] + base = target.parent if target.is_file() else target + found += [ + f"executable {p.relative_to(base).as_posix()}" + for p in files_of(target) + if p.stat().st_mode & 0o111 + ] + return found + + +def parse_upstream(upstream: str, path: str | None, ref: str | None) -> tuple[str, str, str | None]: + """(git url, path in repo, ref or None) from owner/repo, a git URL, or a GitHub tree/blob URL.""" + m = re.match(r"https://github\.com/([^/]+/[^/]+)/(?:tree|blob)/([^/]+)/(.+?)/?$", upstream) + if m: + repo, url_ref, url_path = m.groups() + return f"https://github.com/{repo}.git", path or url_path, ref or url_ref + if re.fullmatch(r"[\w.-]+/[\w.-]+", upstream): + upstream = f"https://github.com/{upstream}.git" + if not path: + die("give the component's path in the upstream repo, or a GitHub tree/blob URL") + return upstream, path.strip("/"), ref + + +def infer_dest(source: Path, path: str) -> str: + parts = path.split("/") + if source.is_dir(): + if not (source / "SKILL.md").is_file(): + die(f"{path} is a folder without SKILL.md; only skills are folders. Pass --as to say what it is") + return f"skills/{parts[-1]}" + for kind, shape in KINDS.items(): + if shape == "file" and kind in parts[:-1] and path.endswith(".md"): + return f"{kind}/{parts[-1]}" + die(f"cannot tell what kind of component {path} is; pass --as /") + return "" + + +def check_dest(dest: str) -> None: + kind, _, name = dest.partition("/") + if kind not in KINDS or not name or "/" in name: + die(f"{dest}: expected one of {', '.join(f'{k}/' for k in KINDS)}") + if KINDS[kind] == "file" and not name.endswith(".md"): + die(f"{dest}: {kind} are single .md files") + + +def find_license(clone: Path, path: str) -> Path | None: + """The license nearest the component, walking up to the repo root.""" + here = clone / path + for folder in [here, *here.parents]: + for name in LICENSE_NAMES: + if (folder / name).is_file(): + return folder / name + if folder == clone: + break + return None + + +def spdx_guess(text: str) -> str: + head = text[:400] + for marker, spdx in ( + ("MIT License", "MIT"), + ("Permission is hereby granted, free of charge", "MIT"), + ("Apache License", "Apache-2.0"), + ("BSD 3-Clause", "BSD-3-Clause"), + ("BSD 2-Clause", "BSD-2-Clause"), + ("Mozilla Public License", "MPL-2.0"), + ("GNU GENERAL PUBLIC LICENSE", "GPL"), + ("ISC License", "ISC"), + ("CC0", "CC0-1.0"), + ): + if marker in head: + return spdx + return "unknown" + + +def license_slug(url: str, license_dir: str) -> str: + repo = re.sub(r"^https?://[^/]+/|\.git$", "", url).replace("/", "__") + return f"{repo}__{license_dir.replace('/', '-')}.txt" if license_dir else f"{repo}.txt" + + +def vendor(dest: str, rec: dict, ref: str | None, *, allow_unlicensed: bool = False) -> bool: + """Copy the component at ref (default HEAD) into plugins/zae/. True if it changed.""" + target = PLUGIN / dest + with tempfile.TemporaryDirectory() as tmp: + clone = Path(tmp) / "src" + commit = fetch(rec["upstream"], ref or "HEAD", clone) + obj = object_of(clone, rec["path"]) + intact = target.exists() and content_hash(target) == rec.get("content_sha256") + if rec.get("ref") and obj == rec.get("object") and intact: + print(f"{dest}: unchanged (same content at {commit[:12]}); nothing to do") + return False + git("checkout", "-q", "FETCH_HEAD", cwd=clone) + source = clone / rec["path"] + if symlinks(source): + die(f"{dest}: upstream has symlinks, which are refused: {symlinks(source)}") + found = find_license(clone, rec["path"]) + if found is None and not allow_unlicensed: + die(f"{rec['upstream']} has no LICENSE near {rec['path']}; without one you may not copy it. " + "Pass --allow-unlicensed only if you have permission") + before = needs_review(target) if target.exists() else [] + if target.is_dir(): + shutil.rmtree(target) + elif target.exists(): + target.unlink() + target.parent.mkdir(parents=True, exist_ok=True) + if source.is_dir(): + shutil.copytree(source, target, ignore=lambda _, names: {n for n in names if n in SKIP}) + else: + shutil.copy2(source, target) + license_file = "" + if found is not None: + license_file = license_slug(rec["upstream"], found.parent.relative_to(clone).as_posix().strip(".")) + LICENSES.mkdir(parents=True, exist_ok=True) + shutil.copy2(found, LICENSES / license_file) + spdx = spdx_guess(found.read_text(errors="replace")) + else: + spdx = "none" + after = needs_review(target) + old = rec.get("ref", "") + rec.update( + ref=commit, + object=obj, + license=spdx, + license_file=f"licenses/{license_file}" if license_file else "", + vendored_on=datetime.date.today().isoformat(), + content_sha256=content_hash(target), + needs_review=after, + ) + print(f"{dest}: {old[:12] or 'new'} -> {commit[:12]} (license {spdx})") + md = target / "SKILL.md" if target.is_dir() else target + name = frontmatter(md)[0] if md.is_file() else "" + stem = Path(dest).name.removesuffix(".md") + if name and name != stem: + print(f"NOTE: its frontmatter says name: {name}, but it lives at {dest}. Rename one so they agree") + if after != before: + print("REVIEW: what this component can run or widen changed:") + for line in sorted(set(before) - set(after)): + print(f" - {line}") + for line in sorted(set(after) - set(before)): + print(f" + {line}") + if old and old != commit and rec["upstream"].startswith("https://github.com/"): + print(f"Upstream changes: {rec['upstream'].removesuffix('.git')}/compare/{old}...{commit}") + return True + + +def add(upstream: str, path: str | None, dest: str | None, ref: str | None, allow_unlicensed: bool) -> int: + url, path, ref = parse_upstream(upstream, path, ref) + if dest is None: + with tempfile.TemporaryDirectory() as tmp: + clone = Path(tmp) / "src" + fetch(url, ref or "HEAD", clone) + git("checkout", "-q", "FETCH_HEAD", cwd=clone) + if not (clone / path).exists(): + die(f"{url} has no {path}") + dest = infer_dest(clone / path, path) + check_dest(dest) + lock = load_lock() + if dest in lock["components"]: + die(f"{dest} is already vendored; use `update {dest}`") + if (PLUGIN / dest).exists(): + die(f"plugins/zae/{dest} exists and is our own; pick another name with --as") + rec = {"upstream": url, "path": path} + vendor(dest, rec, ref, allow_unlicensed=allow_unlicensed) + lock["components"][dest] = rec + save_lock(lock) + print(f"Call it as /zae:{Path(dest).name.removesuffix('.md')} in a new session (or after /reload-plugins).") + return 0 + + +def update(dest: str | None, ref: str | None, every: bool) -> int: + lock = load_lock() + targets = list(lock["components"]) if every else [dest] + if every and ref: + die("--ref applies to one component, not --all") + for d in targets: + if d not in lock["components"]: + die(f"{d} is not vendored; `add` it first") + vendor(d, lock["components"][d], ref, allow_unlicensed=lock["components"][d].get("license") == "none") + save_lock(lock) + return 0 + + +def remove(dest: str) -> int: + lock = load_lock() + rec = lock["components"].pop(dest, None) + if rec is None: + die(f"{dest} is not vendored") + target = PLUGIN / dest + if target.is_dir(): + shutil.rmtree(target) + elif target.exists(): + target.unlink() + still_used = {r.get("license_file") for r in lock["components"].values()} + if rec.get("license_file") and rec["license_file"] not in still_used: + (PLUGIN / rec["license_file"]).unlink(missing_ok=True) + save_lock(lock) + print(f"{dest}: removed") + return 0 + + +def check() -> int: + lock = load_lock()["components"] + problems = [] + for dest, rec in lock.items(): + target = PLUGIN / dest + if not target.exists(): + problems.append(f"{dest}: plugins/zae/{dest} is missing") + elif symlinks(target): + problems.append(f"{dest}: symlinks are refused: {symlinks(target)}") + elif content_hash(target) != rec["content_sha256"]: + problems.append( + f"{dest}: its files differ from what vendored.json records. Either restore it with " + f"`scripts/zae-vendor.py update {dest} --ref {rec['ref']}`, or make it our own with " + f"`scripts/zae-vendor.py remove {dest}` and write it back by hand" + ) + if rec.get("license_file") and not (PLUGIN / rec["license_file"]).is_file(): + problems.append(f"{dest}: plugins/zae/{rec['license_file']} is missing") + for kind in KINDS: + for entry in sorted((PLUGIN / kind).glob("*")) if (PLUGIN / kind).is_dir() else []: + if entry.is_symlink(): + problems.append(f"{kind}/{entry.name}: symlinks are refused") + for p in problems: + print(f"FAIL {p}") + own = [ + f"{k}/{e.name}" + for k in KINDS + if (PLUGIN / k).is_dir() + for e in sorted((PLUGIN / k).iterdir()) + if f"{k}/{e.name}" not in lock and e.name != ".gitkeep" + ] + if not problems: + print(f"ok: {len(lock)} vendored components match vendored.json; {len(own)} of our own") + return 1 if problems else 0 + + +def status() -> int: + """Exit 2 when an update is available, so a scheduled job can act on it.""" + behind = False + heads: dict[str, tuple[str, Path]] = {} + with tempfile.TemporaryDirectory() as tmp: + for dest, rec in load_lock()["components"].items(): + url = rec["upstream"] + if url not in heads: + clone = Path(tmp) / str(len(heads)) + heads[url] = (fetch(url, "HEAD", clone, blobs=False), clone) + head, clone = heads[url] + try: + obj = object_of(clone, rec["path"]) + except SystemExit: + behind = True + print(f"{dest}: {rec['path']} is gone from {url} HEAD: decide whether to keep it") + continue + current = head == rec["ref"] or obj == rec["object"] + behind = behind or not current + state = "up to date" if current else f"update available: {head[:12]}" + print(f"{dest}: pinned {rec['ref'][:12]} ({rec['vendored_on']}), {state}") + return 2 if behind else 0 + + +def install() -> int: + if shutil.which("claude") is None: + die("the `claude` CLI is not on PATH") + market = json.loads(CATALOGUE.read_text())["name"] + added = subprocess.run(["claude", "plugin", "marketplace", "add", GITHUB_REPO]) + if added.returncode != 0: + subprocess.run(["claude", "plugin", "marketplace", "update", market], check=True) + subprocess.run(["claude", "plugin", "install", f"zae@{market}"], check=True) + print("Done. Start a new Claude Code session (or run /reload-plugins) to load it.") + return 0 + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + a = sub.add_parser("add") + a.add_argument("upstream") + a.add_argument("path", nargs="?") + a.add_argument("--as", dest="dest") + a.add_argument("--ref") + a.add_argument("--allow-unlicensed", action="store_true") + u = sub.add_parser("update") + u.add_argument("dest", nargs="?") + u.add_argument("--ref") + u.add_argument("--all", action="store_true") + r = sub.add_parser("remove") + r.add_argument("dest") + sub.add_parser("status") + sub.add_parser("check") + sub.add_parser("install") + args = ap.parse_args() + if args.cmd == "add": + return add(args.upstream, args.path, args.dest, args.ref, args.allow_unlicensed) + if args.cmd == "update": + if not args.all and not args.dest: + ap.error("update needs or --all") + return update(args.dest, args.ref, args.all) + if args.cmd == "remove": + return remove(args.dest) + if args.cmd == "status": + return status() + if args.cmd == "check": + return check() + return install() + + +if __name__ == "__main__": + sys.exit(main())