From a428222162fdb80cbbb6feec1293782de5211cdb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 31 Aug 2026 19:57:28 +0000 Subject: [PATCH] Restore two-way agent config sync with standardized bootstrap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bring back the .agents/ canon and the per-checkout, gitignored harness adapters, consolidated: one sync.py now owns rendering, skill symlinks, the skills lock, and validation. The sync is two-way — a skill or MCP server installed through any one harness is adopted into .agents/ and rendered for every other — enforced by a dependency-free git pre-commit hook that .agents/setup installs. Bootstrap is standardized across environments: committed native hooks for devcontainers, Claude Code (SessionStart), Cursor cloud, Copilot's coding agent, and Amp all call the same .agents/setup, which needs only stdlib Python. setup also installs rtk, best-effort, to compress the command output agents read. Instructions consolidate into AGENTS.md (with one-line CLAUDE.md/GEMINI.md imports) plus one .agents/README.md; no skills or MCP servers ship preinstalled. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017NWDrWeqhFGvENtps4UNf7 --- .agents/README.md | 61 ++ .agents/mcp/servers.json | 1 + .agents/setup | 43 ++ .agents/skills/.gitkeep | 0 .agents/sync.py | 784 ++++++++++++++++++++++ .claude/settings.json | 15 + .cursor/environment.json | 3 + .devcontainer/Dockerfile | 3 + .devcontainer/devcontainer.json | 11 + .editorconfig | 5 + .gitattributes | 3 +- .github/workflows/agent-config.yml | 33 + .github/workflows/copilot-setup-steps.yml | 13 + .gitignore | 68 +- AGENTS.md | 22 +- skills-lock.json | 4 + 16 files changed, 1054 insertions(+), 15 deletions(-) create mode 100644 .agents/README.md create mode 100644 .agents/mcp/servers.json create mode 100755 .agents/setup create mode 100644 .agents/skills/.gitkeep create mode 100755 .agents/sync.py create mode 100644 .claude/settings.json create mode 100644 .cursor/environment.json create mode 100644 .devcontainer/Dockerfile create mode 100644 .devcontainer/devcontainer.json create mode 100644 .github/workflows/agent-config.yml create mode 100644 .github/workflows/copilot-setup-steps.yml create mode 100644 skills-lock.json diff --git a/.agents/README.md b/.agents/README.md new file mode 100644 index 0000000..995d4fc --- /dev/null +++ b/.agents/README.md @@ -0,0 +1,61 @@ +# `.agents/` + +Canonical agent configuration, following [AGENTS.md](https://agents.md) and +the [Agent Skills](https://agentskills.io) standard. Two tiers, nothing else: + +| Tier | Contents | +|---|---| +| **Canonical**, committed | `skills/`, `mcp/servers.json`, `sync.py`, `setup`, plus the standard files at the root: `AGENTS.md`, one-line `CLAUDE.md`/`GEMINI.md` imports, and the environment hooks below | +| **Generated**, gitignored | Everything else a harness reads, rendered per checkout by `sync.py` for the harnesses detected on the machine | + +Most harnesses — Codex cloud, Copilot's coding agent, Windsurf, Goose, Zed, +Cline, Jules, Devin, and friends — read `AGENTS.md` and `.agents/skills/` +natively and need no adapter at all. `sync.py list` shows who gets what. + +## Two-way sync + +`python3 .agents/sync.py` converges both directions in one run: + +- **Canon → harnesses**: renders MCP configs (`.mcp.json`, `.cursor/mcp.json`, + `.codex/config.toml`, …) and skill symlinks (`.claude/skills/`, + `.codebuddy/skills/`) from `.agents/`. +- **Harnesses → canon**: a skill directory dropped in a harness skills dir, or + an MCP server added to any rendered config (`claude mcp add`, a hand edit), + is adopted into `.agents/` and rendered back out to every other harness. + Commit the changed files under `.agents/` and `skills-lock.json`. + +`setup` installs a git pre-commit hook running `sync.py check`, and CI runs +the same, so nothing can be committed while the two sides disagree or a +generated file is tracked. The lock records a hash per skill (the same +convention `npx skills add` writes), so vendored skills can't drift silently; +after deliberately editing one, run `sync.py lock`. + +## Environments + +Every environment reaches the same `.agents/setup` through its native, +committed hook — that one script is where project setup (dependencies, +codegen) goes. It also installs [rtk](https://github.com/rtk-ai/rtk), +best-effort, to compress command output agents read. + +| Environment | Committed hook | +|---|---| +| Claude Code (web and local) | `SessionStart` hook in `.claude/settings.json` | +| Devcontainers: Codespaces, Ona, DevPod | `postCreateCommand` in `.devcontainer/devcontainer.json` | +| Cursor cloud agents | `install` in `.cursor/environment.json` | +| Copilot coding agent | `.github/workflows/copilot-setup-steps.yml` | +| Amp orbs | runs `.agents/setup` by convention | +| CI | `.github/workflows/agent-config.yml` | +| Codex cloud, Jules, Devin, … | no in-repo hook exists; paste `bash .agents/setup` into the environment's setup-script field. They read `AGENTS.md` and `.agents/skills/` natively, so this only matters once project setup does something. | + +## Rules + +- Edit skills in `.agents/skills/` and MCP servers in `mcp/servers.json`; the + per-harness copies are generated. `mcp/servers.json` uses the Claude + `mcpServers` dialect plus an optional `tools` read-only allowlist (rendered + where supported: Codex `enabled_tools`, Gemini/Qwen `includeTools`). +- Credentials never go in configs — reference environment variables. +- To support a new harness, add one `HARNESSES` entry (and renderer) in + `sync.py` and mirror its outputs in `.gitignore`'s generated block; + `sync.py check` fails until both agree. +- Codex trusts a project `.codex/config.toml` only after you trust the + project; `sync.py install-codex` writes the user-level config instead. diff --git a/.agents/mcp/servers.json b/.agents/mcp/servers.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/.agents/mcp/servers.json @@ -0,0 +1 @@ +{} diff --git a/.agents/setup b/.agents/setup new file mode 100755 index 0000000..43ab236 --- /dev/null +++ b/.agents/setup @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# The one setup entry point. Every environment calls this same script through +# its native, committed hook — see the environments table in .agents/README.md +# — so setup stays standardized instead of per-harness. Idempotent and +# non-interactive; everything below the sync is best-effort so restricted +# sandboxes still get a working checkout. +set -euo pipefail +cd "$(git -C "$(dirname "$0")" rev-parse --show-toplevel)" + +# Adopt harness-local agent config into .agents/ and render adapters back out. +# Arguments name additional harnesses to render (each hook passes its own). +python3 .agents/sync.py "$@" + +# Guard commits: harness-local agent config must be absorbed into .agents/ +# before it lands. Never clobbers a hook this repo's users wrote themselves. +hooks_dir="$(git rev-parse --git-path hooks)" +hook="$hooks_dir/pre-commit" +if [ ! -e "$hook" ] || grep -q '\.agents/sync\.py' "$hook" 2>/dev/null; then + mkdir -p "$hooks_dir" + printf '%s\n' '#!/usr/bin/env bash' \ + '# Installed by .agents/setup. Fails until harness-local agent config' \ + '# is absorbed into .agents/ — fix with: python3 .agents/sync.py' \ + 'exec python3 .agents/sync.py check' > "$hook" + chmod +x "$hook" +fi + +# rtk (github.com/rtk-ai/rtk) compresses command output before agents read it. +export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH" +if ! command -v rtk >/dev/null 2>&1; then + curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh >/dev/null 2>&1 || true +fi +if command -v rtk >/dev/null 2>&1; then + rtk init -g >/dev/null 2>&1 || true # hooks Claude Code, Copilot, and more + if command -v gemini >/dev/null 2>&1; then + rtk init -g --gemini >/dev/null 2>&1 || true + fi + if command -v cursor-agent >/dev/null 2>&1 || command -v cursor >/dev/null 2>&1; then + rtk init -g --agent cursor >/dev/null 2>&1 || true + fi +fi + +# Project setup goes here (dependency install, codegen, migrations). Keep it +# idempotent and fast when there is nothing to do. diff --git a/.agents/skills/.gitkeep b/.agents/skills/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.agents/sync.py b/.agents/sync.py new file mode 100755 index 0000000..7fbdfb5 --- /dev/null +++ b/.agents/sync.py @@ -0,0 +1,784 @@ +#!/usr/bin/env python3 +"""Two-way sync between the canonical agent config in .agents/ and harnesses. + +Canonical, committed sources: + .agents/skills/ shared skills (Agent Skills standard) + .agents/mcp/servers.json MCP servers, Claude `mcpServers` dialect plus an + optional `tools` read-only allowlist per server + +Forward: everything a harness reads is rendered from the canon per checkout +and gitignored — never hand-edited or committed. Rendering runs automatically +through the committed environment hooks that call .agents/setup (table in +.agents/README.md). Reverse: additions made through one harness — a skill +directory dropped in .claude/skills/, a server added with `claude mcp add` or +a hand edit to any rendered config — are adopted into the canon on the next +sync and rendered back out to every other harness. A git pre-commit hook +installed by .agents/setup runs `check`, so a commit fails until local state +and canon have converged. Stdlib only, so all of this runs in any sandbox. + +Usage: + sync.py [harness ...] absorb harness-local additions into the canon, then + render for detected harnesses plus any named ones + sync.py --all same, rendering every known harness (CI default) + sync.py check read-only: fail on unabsorbed local additions, + unrendered/broken skill links, adapters that are + committed or unignored, or a stale skills lock + sync.py lock re-record skill hashes after deliberately editing one + sync.py list show known harnesses, detection state, and outputs + sync.py install-codex install this repo's MCP block into ~/.codex/config.toml + +Harnesses that read AGENTS.md and .agents/skills/ natively need no adapter and +no entry here: Copilot's coding agent, Windsurf, Goose, Zed, Crush, Cline, +Trae, Augment, Hermes, Antigravity, Jules, Devin, dsh, gsd. +""" +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +try: + import tomllib +except ImportError: # Python < 3.11: .codex/config.toml is skipped on absorb + tomllib = None + +REPO_ROOT = Path(__file__).resolve().parents[1] +SKILLS_ROOT = REPO_ROOT / ".agents" / "skills" +SERVERS_PATH = REPO_ROOT / ".agents" / "mcp" / "servers.json" +LOCK_PATH = REPO_ROOT / "skills-lock.json" +HASH_IGNORED = {".git", "node_modules", "__pycache__"} +FRONTMATTER = re.compile(r"\A---\r?\n(.*?)\r?\n---(?:\r?\n|\Z)", re.DOTALL) + +# Each harness: how to detect it on this machine (env vars set, commands on +# PATH, directories under $HOME), where its per-skill symlinks go (None = it +# reads .agents/skills natively), and which renderer produces its config files +# (None = nothing to generate). Detection never probes a path sync.py itself +# creates — one run would make that harness sticky-detected. +HARNESSES = { + "claude": {"env": ["CLAUDECODE", "CLAUDE_CODE_REMOTE"], "cmd": ["claude"], "home": [".claude"], "skills": ".claude/skills", "render": "claude"}, + "codex": {"cmd": ["codex"], "home": [".codex"], "skills": None, "render": "codex"}, + "cursor": {"cmd": ["cursor-agent", "cursor"], "home": [".cursor"], "skills": None, "render": "cursor"}, + "gemini": {"cmd": ["gemini"], "home": [".gemini"], "skills": None, "render": "gemini"}, + "qwen": {"cmd": ["qwen"], "home": [".qwen"], "skills": None, "render": "qwen"}, + "opencode": {"cmd": ["opencode"], "home": [".config/opencode"], "skills": None, "render": "opencode"}, + "vscode": {"cmd": ["code"], "skills": None, "render": "vscode"}, + "kilo": {"cmd": ["kilo"], "home": [".config/kilo"], "skills": None, "render": "kilo"}, + "factory": {"cmd": ["droid"], "home": [".factory"], "skills": None, "render": "factory"}, + "amp": {"cmd": ["amp"], "home": [".amp"], "skills": None, "render": "amp"}, + "codebuddy": {"cmd": ["codebuddy"], "home": [".codebuddy"], "skills": ".codebuddy/skills", "render": None}, +} + +NATIVE = ("copilot", "windsurf", "goose", "zed", "crush", "cline", "trae", + "augment", "hermes", "antigravity", "jules", "devin", "dsh", "gsd") + + +def detected(spec): + return ( + any(os.environ.get(var) for var in spec.get("env", ())) + or any(shutil.which(cmd) for cmd in spec.get("cmd", ())) + or any((Path.home() / rel).exists() for rel in spec.get("home", ())) + ) + + +def load_servers(): + try: + servers = json.loads(SERVERS_PATH.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SystemExit(f"ERROR: cannot read {SERVERS_PATH}: {exc}") + if not isinstance(servers, dict): + raise SystemExit("ERROR: .agents/mcp/servers.json must contain a JSON object") + for name, config in servers.items(): + if not isinstance(name, str) or not name: + raise SystemExit("ERROR: every MCP server must have a non-empty string name") + if not isinstance(config, dict): + raise SystemExit(f"ERROR: MCP server {name!r} must contain an object") + if not isinstance(config.get("url"), str) and not isinstance(config.get("command"), str): + raise SystemExit(f"ERROR: MCP server {name!r} needs a `url` or a `command`") + tools = config.get("tools") + if tools is not None and not ( + isinstance(tools, list) and all(isinstance(tool, str) and tool for tool in tools) + ): + raise SystemExit(f"ERROR: MCP server {name!r} has a malformed tools allowlist") + return servers + + +def json_document(value): + return json.dumps(value, indent=2, ensure_ascii=False) + "\n" + + +def body_of(config): + """The server config without the canonical-only `tools` allowlist.""" + return {key: value for key, value in config.items() if key != "tools"} + + +def is_remote(config): + return "url" in config + + +# ── Renderers: canon → harness ──────────────────────────────────────────────── +# Each takes the canonical servers dict and returns {relative path: content}. + + +def render_claude(servers): + # Instructions and approval need no rendering: CLAUDE.md is a committed + # one-line import of AGENTS.md, and the committed .claude/settings.json + # enables all project MCP servers, so .mcp.json is the whole adapter. + rendered = {} + for name, config in servers.items(): + body = body_of(config) + if is_remote(body): + body.setdefault("type", "http") + rendered[name] = body + return {".mcp.json": json_document({"mcpServers": rendered})} + + +def render_cursor(servers): + rendered = {} + for name, config in servers.items(): + body = body_of(config) + body.pop("type", None) + rendered[name] = body + return {".cursor/mcp.json": json_document({"mcpServers": rendered})} + + +def render_vscode(servers): + # VS Code names the top-level key `servers` and wants an explicit type. + rendered = {} + for name, config in servers.items(): + body = body_of(config) + body.setdefault("type", "http" if is_remote(body) else "stdio") + rendered[name] = body + return {".vscode/mcp.json": json_document({"servers": rendered})} + + +def gemini_servers(servers): + # Gemini CLI names streamable HTTP `httpUrl`, keeps `url` for SSE, and + # spells the allowlist `includeTools`. + rendered = {} + for name, config in servers.items(): + body = body_of(config) + transport = body.pop("type", None) + if "url" in body and transport != "sse": + body["httpUrl"] = body.pop("url") + if config.get("tools"): + body["includeTools"] = list(config["tools"]) + rendered[name] = body + return rendered + + +def render_gemini(servers): + # Context needs no configuration: the committed GEMINI.md imports AGENTS.md. + return {".gemini/settings.json": json_document({"mcpServers": gemini_servers(servers)})} + + +def render_qwen(servers): + document = { + "contextFileName": ["AGENTS.md", "QWEN.md"], + "mcpServers": gemini_servers(servers), + } + return {".qwen/settings.json": json_document(document)} + + +def opencode_mcp(servers): + rendered = {} + for name, config in servers.items(): + if is_remote(config): + entry = {"type": "remote", "url": config["url"]} + if config.get("headers"): + entry["headers"] = config["headers"] + else: + entry = {"type": "local", "command": [config["command"], *config.get("args", [])]} + if config.get("env"): + entry["environment"] = config["env"] + rendered[name] = entry + return rendered + + +def render_opencode(servers): + return {"opencode.json": json_document({"mcp": opencode_mcp(servers)})} + + +def render_kilo(servers): + return {"kilo.jsonc": json_document({"mcp": opencode_mcp(servers)})} + + +def render_factory(servers): + rendered = {} + for name, config in servers.items(): + body = body_of(config) + body.setdefault("type", "http" if is_remote(body) else "stdio") + rendered[name] = body + return {".factory/mcp.json": json_document({"mcpServers": rendered})} + + +def render_amp(servers): + rendered = {name: body_of(config) for name, config in servers.items()} + return {".amp/settings.json": json_document({"amp.mcpServers": rendered})} + + +def toml_key(value): + if re.fullmatch(r"[A-Za-z0-9_-]+", value): + return value + return json.dumps(value, ensure_ascii=False) + + +def toml_value(value): + if isinstance(value, str): + # json.dumps escapes U+0000-U+001F but leaves U+007F raw, which TOML forbids. + return json.dumps(value, ensure_ascii=False).replace("\x7f", "\\u007f") + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float)): + return repr(value) + if isinstance(value, list): + return "[" + ", ".join(toml_value(item) for item in value) + "]" + if isinstance(value, dict): + pairs = (f"{toml_key(key)} = {toml_value(item)}" for key, item in value.items()) + return "{ " + ", ".join(pairs) + " }" + raise SystemExit(f"ERROR: unsupported TOML value in MCP config: {value!r}") + + +def codex_toml(servers): + lines = ["# Generated by .agents/sync.py; do not edit."] + for name, config in servers.items(): + lines.extend(("", f"[mcp_servers.{toml_key(name)}]")) + for key, value in config.items(): + if key in ("type", "tools"): + continue + lines.append(f"{toml_key(key)} = {toml_value(value)}") + if config.get("tools"): + lines.append(f"enabled_tools = {toml_value(list(config['tools']))}") + return "\n".join(lines) + "\n" + + +def render_codex(servers): + # Codex loads a project .codex/config.toml only once the project is + # trusted; `install-codex` covers the user-level config instead. + return {".codex/config.toml": codex_toml(servers)} + + +RENDERERS = { + "claude": render_claude, + "codex": render_codex, + "cursor": render_cursor, + "gemini": render_gemini, + "qwen": render_qwen, + "opencode": render_opencode, + "vscode": render_vscode, + "kilo": render_kilo, + "factory": render_factory, + "amp": render_amp, +} + + +def output_paths(): + """Every repo-relative path any renderer can write, across all harnesses.""" + servers = load_servers() + paths = set() + for spec in HARNESSES.values(): + if spec["render"]: + paths.update(RENDERERS[spec["render"]](servers)) + if spec["skills"]: + # Trailing slash: `git check-ignore` only matches a directory-only + # .gitignore pattern when the path is spelled as a directory. + paths.add(spec["skills"] + "/") + return sorted(paths) + + +# ── Absorption: harness → canon ─────────────────────────────────────────────── +# Additions made through one harness are adopted into the canon, so the next +# render propagates them to every other harness. + + +def strip_default_type(entry): + config = dict(entry) + if config.get("type") in ("http", "stdio"): + del config["type"] + return config + + +def from_gemini(entry): + config = dict(entry) + if "httpUrl" in config: + config["url"] = config.pop("httpUrl") + if "includeTools" in config: + config["tools"] = config.pop("includeTools") + return strip_default_type(config) + + +def from_opencode(entry): + config = dict(entry) + kind = config.pop("type", None) + command = config.pop("command", None) + if kind == "local" and isinstance(command, list) and command: + config["command"] = command[0] + if command[1:]: + config["args"] = list(command[1:]) + elif command is not None: + config["command"] = command + if "environment" in config: + config["env"] = config.pop("environment") + return config + + +def from_codex(entry): + config = dict(entry) + if "enabled_tools" in config: + config["tools"] = config.pop("enabled_tools") + return config + + +# Where each harness's config gains servers out-of-band (`claude mcp add`, a +# hand edit, another agent's installer), and how to read entries back into the +# canonical dialect. +FOREIGN_SOURCES = ( + (".mcp.json", ("mcpServers",), strip_default_type), + (".cursor/mcp.json", ("mcpServers",), strip_default_type), + (".vscode/mcp.json", ("servers",), strip_default_type), + (".factory/mcp.json", ("mcpServers",), strip_default_type), + (".gemini/settings.json", ("mcpServers",), from_gemini), + (".qwen/settings.json", ("mcpServers",), from_gemini), + ("opencode.json", ("mcp",), from_opencode), + ("kilo.jsonc", ("mcp",), from_opencode), + (".amp/settings.json", ("amp.mcpServers",), strip_default_type), + (".codex/config.toml", ("mcp_servers",), from_codex), +) + + +def foreign_servers(servers): + """Servers found in a harness config on disk but missing from the canon. + + Returns ({name: (canonical config, source path)}, [unreadable-file notes]). + """ + found, problems = {}, [] + for rel, keys, normalize in FOREIGN_SOURCES: + path = REPO_ROOT / rel + if not path.is_file(): + continue + try: + if rel.endswith(".toml"): + if tomllib is None: + continue + data = tomllib.loads(path.read_text(encoding="utf-8")) + else: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + problems.append(f"{rel}: unreadable, rendering will replace it ({exc})") + continue + for key in keys: + data = data.get(key) if isinstance(data, dict) else None + if not isinstance(data, dict): + continue + for name, entry in data.items(): + if name in servers or name in found or not isinstance(entry, dict): + continue + config = normalize(entry) + if isinstance(config.get("url"), str) or isinstance(config.get("command"), str): + found[name] = (config, rel) + return found, problems + + +def foreign_skills(): + """Real directories inside a harness skills dir; canon holds only symlinks.""" + found = [] + for spec in HARNESSES.values(): + if not spec["skills"]: + continue + target_dir = REPO_ROOT / spec["skills"] + if not target_dir.is_dir(): + continue + found.extend( + (spec["skills"], entry) + for entry in sorted(target_dir.iterdir()) + if entry.is_dir() and not entry.is_symlink() + ) + return found + + +def lock_add(names): + """Add or refresh lock entries for these skills; report frontmatter faults.""" + try: + lock = json.loads(LOCK_PATH.read_text(encoding="utf-8")) + except (OSError, ValueError): + lock = {"version": 1} + skills = lock.setdefault("skills", {}) + failures = [] + for name in names: + failures.extend(skill_failures(name, skills.setdefault(name, {}), update=True)) + lock["skills"] = {name: skills[name] for name in sorted(skills)} + atomic_write(LOCK_PATH, json_document(lock)) + return failures + + +def absorb(servers): + """Adopt harness-local additions into the canon before rendering.""" + adopted_skills = [] + for rel, entry in foreign_skills(): + canonical = SKILLS_ROOT / entry.name + if canonical.exists(): + if skill_hash(canonical) != skill_hash(entry): + raise SystemExit( + f"ERROR: {rel}/{entry.name} and .agents/skills/{entry.name} differ; " + "merge them manually — .agents/skills is the canon." + ) + shutil.rmtree(entry) # identical duplicate; the symlink replaces it + else: + SKILLS_ROOT.mkdir(parents=True, exist_ok=True) + shutil.move(str(entry), str(canonical)) + adopted_skills.append(entry.name) + print(f"Adopted skill {entry.name!r} from {rel}/ into .agents/skills/") + + adopted_servers, _ = foreign_servers(servers) + for name, (config, rel) in adopted_servers.items(): + servers[name] = config + print(f"Adopted MCP server {name!r} from {rel} into .agents/mcp/servers.json") + if adopted_servers: + atomic_write(SERVERS_PATH, json_document(servers)) + + if adopted_skills: + failures = lock_add(adopted_skills) + if failures: + print("Adopted skills need fixes (then run .agents/sync.py lock):", file=sys.stderr) + for failure in failures: + print(f" {failure}", file=sys.stderr) + raise SystemExit(1) + if adopted_skills or adopted_servers: + print("Commit the updated files under .agents/ (and skills-lock.json).") + + +# ── Skill symlinks ──────────────────────────────────────────────────────────── + + +def skill_names(): + if not SKILLS_ROOT.is_dir(): + return [] + return sorted(path.name for path in SKILLS_ROOT.iterdir() if path.is_dir()) + + +def sync_skills(target_rel): + target_dir = REPO_ROOT / target_rel + if not skill_names() and not target_dir.is_dir(): + return # nothing to link and nothing stale to prune + target_dir.mkdir(parents=True, exist_ok=True) + link_prefix = Path(os.path.relpath(SKILLS_ROOT, target_dir)) + + for name in skill_names(): + link_target = link_prefix / name + link_path = target_dir / name + if link_path.is_symlink(): + if os.readlink(link_path) == str(link_target): + continue + link_path.unlink() + elif link_path.exists(): + raise SystemExit(f"ERROR: {link_path} exists but is not a symlink.") + link_path.symlink_to(link_target) + + for link_path in target_dir.iterdir(): + if not link_path.is_symlink(): + continue + resolved = Path(os.path.normpath(target_dir / os.readlink(link_path))) + if resolved.parent == SKILLS_ROOT and not resolved.exists(): + link_path.unlink() + + +def skill_link_failures(target_rel): + """If this skills dir was rendered, its links must be complete and live.""" + target_dir = REPO_ROOT / target_rel + if not target_dir.is_dir(): + return [] + failures = [ + f"{target_rel}/{name}: missing or broken symlink (run .agents/sync.py)" + for name in skill_names() + if not (target_dir / name).is_symlink() or not (target_dir / name).exists() + ] + failures.extend( + f"{target_rel}/{link.name}: dangling symlink (run .agents/sync.py)" + for link in target_dir.iterdir() + if link.is_symlink() and not link.exists() and link.name not in skill_names() + ) + return failures + + +# ── Skills lock ─────────────────────────────────────────────────────────────── + + +def skill_hash(skill_root): + """Hash a skill directory: sorted relative path plus file bytes. + + Matches the folder-hash convention used by skill installers, so hashes + written by `npx skills add` stay valid here. + """ + digest = hashlib.sha256() + files = [ + path + for path in skill_root.rglob("*") + if path.is_file() and not HASH_IGNORED.intersection(path.relative_to(skill_root).parts) + ] + for path in sorted(files, key=lambda path: path.relative_to(skill_root).as_posix()): + digest.update(path.relative_to(skill_root).as_posix().encode("utf-8")) + digest.update(path.read_bytes()) + return digest.hexdigest() + + +def frontmatter_field(block, field): + """Read one top-level scalar or folded value out of YAML frontmatter.""" + match = re.search(rf"^{field}:[ \t]*(.*)$", block, re.MULTILINE) + if not match: + return None + value = match.group(1).strip() + if value in ("", "|", ">", "|-", ">-"): + # Folded or literal block: take the indented lines that follow. + rest = block[match.end():].splitlines() + folded = [] + for line in rest[1:] if rest[:1] == [""] else rest: + if line.strip() and not line.startswith((" ", "\t")): + break + folded.append(line.strip()) + value = " ".join(part for part in folded if part).strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": + value = value[1:-1] + return value.strip() + + +def skill_failures(name, entry, update): + skill_file = SKILLS_ROOT / name / "SKILL.md" + if not skill_file.is_file(): + return [f"{name}: locked but .agents/skills/{name}/SKILL.md is missing"] + + failures = [] + match = FRONTMATTER.match(skill_file.read_text(encoding="utf-8")) + if not match: + failures.append(f"{name}: SKILL.md has no YAML frontmatter") + else: + declared = frontmatter_field(match.group(1), "name") + if declared != name: + failures.append(f"{name}: SKILL.md declares name {declared!r}") + if not frontmatter_field(match.group(1), "description"): + failures.append(f"{name}: SKILL.md has no description") + + actual = skill_hash(SKILLS_ROOT / name) + if update: + entry["computedHash"] = actual + elif entry.get("computedHash") != actual: + failures.append(f"{name}: content changed since it was locked (run .agents/sync.py lock)") + return failures + + +def verify_lock(update=False): + """Check skills-lock.json against the skills on disk; heal it on update.""" + try: + lock = json.loads(LOCK_PATH.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + return [f"cannot read {LOCK_PATH.name}: {exc}"] + skills = lock.setdefault("skills", {}) + + on_disk = set(skill_names()) + failures = [] + for name in sorted(on_disk - set(skills)): + if update: + skills[name] = {} + else: + failures.append(f"{name}: present in .agents/skills but not in skills-lock.json") + for name in sorted(set(skills) - on_disk): + if update: + del skills[name] + else: + failures.append(f"{name}: locked but no .agents/skills/{name} directory") + + for name in sorted(skills): + failures.extend(skill_failures(name, skills[name], update)) + + if update and not failures: + lock["skills"] = {name: skills[name] for name in sorted(skills)} + document = json_document(lock) + if document != LOCK_PATH.read_text(encoding="utf-8"): + LOCK_PATH.write_text(document, encoding="utf-8") + print(f"Updated {LOCK_PATH.name}") + return failures + + +# ── Modes ───────────────────────────────────────────────────────────────────── + + +def atomic_write(path, content): + path.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(content) + try: + mode = path.stat().st_mode & 0o777 + except OSError: + mode = 0o644 + os.chmod(temporary, mode) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def active_harnesses(arguments): + """Detected harnesses plus any named ones; environment hooks name their own.""" + named = [argument for argument in arguments if not argument.startswith("-")] + unknown = sorted(set(named) - set(HARNESSES) - set(NATIVE)) + if unknown: + known = ", ".join([*HARNESSES, *NATIVE]) + raise SystemExit(f"ERROR: unknown harness {', '.join(unknown)}. Known: {known}") + if "--all" in arguments or os.environ.get("GITHUB_ACTIONS") == "true": + return list(HARNESSES) + return [name for name, spec in HARNESSES.items() if name in named or detected(spec)] + + +def sync(arguments): + servers = load_servers() + absorb(servers) + active = active_harnesses(arguments) + generated = [] + for name in active: + spec = HARNESSES[name] + files = RENDERERS[spec["render"]](servers) if spec["render"] else {} + for rel, content in files.items(): + atomic_write(REPO_ROOT / rel, content) + if spec["skills"]: + sync_skills(spec["skills"]) + files = {**files, spec["skills"] + "/": None} + if files: + generated.append(f"{name}: {', '.join(sorted(files))}") + # Heal skill links a past render created for harnesses not active now. + for name, spec in HARNESSES.items(): + if name not in active and spec["skills"] and (REPO_ROOT / spec["skills"]).is_dir(): + sync_skills(spec["skills"]) + for line in generated: + print(f"Generated {line}") + if not generated: + print("No harnesses detected; run with --all or name one to force.") + + +def git(*arguments): + return subprocess.run( + ["git", "-C", str(REPO_ROOT), *arguments], + capture_output=True, text=True, check=False, + ).stdout.splitlines() + + +def check(): + """Read-only verification of every invariant; the pre-commit hook runs this. + + Generated adapters must be gitignored and out of the index, harness-local + additions must be absorbed into the canon, rendered output must parse, + rendered skill symlinks must resolve, and the skills lock must match disk. + """ + failures = [] + + outputs = output_paths() + tracked = git("ls-files", "--", *outputs) + # --no-index: a tracked path would otherwise also be reported as unignored. + ignored = set(git("check-ignore", "--no-index", "--", *outputs)) + failures.extend(f"{path}: committed generated adapter; remove it from git" for path in tracked) + failures.extend( + f"{path}: missing from .gitignore's generated-adapters block" + for path in outputs if path not in ignored + ) + + servers = load_servers() + for rel, entry in foreign_skills(): + failures.append(f"{rel}/{entry.name}: skill not in .agents/skills (run .agents/sync.py)") + foreign, problems = foreign_servers(servers) + failures.extend( + f"{rel}: MCP server {name!r} not in .agents/mcp/servers.json (run .agents/sync.py)" + for name, (_, rel) in foreign.items() + ) + failures.extend(problems) + + for spec in HARNESSES.values(): + if spec["render"]: + for rel, content in RENDERERS[spec["render"]](servers).items(): + try: + if rel.endswith(".toml"): + if tomllib: + tomllib.loads(content) + else: + json.loads(content) + except ValueError as exc: + failures.append(f"{rel}: renderer produced invalid output: {exc}") + if spec["skills"]: + failures.extend(skill_link_failures(spec["skills"])) + + for rel in (".claude/settings.json", ".cursor/environment.json", + ".devcontainer/devcontainer.json"): + try: + json.loads((REPO_ROOT / rel).read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + failures.append(f"{rel}: {exc}") + + failures.extend(verify_lock()) + + if failures: + print("Agent config problems:", file=sys.stderr) + for failure in failures: + print(f" {failure}", file=sys.stderr) + raise SystemExit(1) + print(f"OK: {len(outputs)} generated paths ignored, {len(skill_names())} skill(s) locked.") + + +def lock(): + failures = verify_lock(update=True) + if failures: + print("Skill problems:", file=sys.stderr) + for failure in failures: + print(f" {failure}", file=sys.stderr) + raise SystemExit(1) + print(f"{len(skill_names())} skill(s) locked and current.") + + +def list_harnesses(): + servers = load_servers() + for name, spec in HARNESSES.items(): + adapters = [] + if spec["skills"]: + adapters.append(f"skills → {spec['skills']}") + if spec["render"]: + adapters.append("files → " + ", ".join(sorted(RENDERERS[spec["render"]](servers)))) + state = "detected" if detected(spec) else "not detected" + print(f"{name:10} {state:13} {'; '.join(adapters)}") + print(f"{'native':10} {'—':13} AGENTS.md + .agents/skills, no adapter: {', '.join(NATIVE)}") + + +def install_codex(): + repo_name = re.sub(r"[^A-Za-z0-9_-]+", "-", REPO_ROOT.name).strip("-") or "repo" + begin = f"# BEGIN {repo_name} managed MCP" + end = f"# END {repo_name} managed MCP" + block = begin + "\n" + codex_toml(load_servers()) + end + user_config = Path.home() / ".codex" / "config.toml" + try: + current = user_config.read_text(encoding="utf-8") + except FileNotFoundError: + current = "" + pattern = re.compile( + rf"(?ms)^[ \t]*{re.escape(begin)}\n.*?^[ \t]*{re.escape(end)}[ \t]*\n?" + ) + current = re.sub(r"\n{3,}", "\n\n", pattern.sub("", current)).rstrip() + merged = (current + "\n\n" if current else "") + block + "\n" + atomic_write(user_config, merged) + print(f"Installed managed MCP block: {user_config}") + + +def main(arguments): + modes = {"check": check, "lock": lock, "list": list_harnesses, "install-codex": install_codex} + if arguments and arguments[0] in modes: + if arguments[1:]: + raise SystemExit(f"ERROR: {arguments[0]} takes no further arguments") + modes[arguments[0]]() + elif all(argument == "--all" or not argument.startswith("-") for argument in arguments): + sync(arguments) + else: + print(__doc__, file=sys.stderr) + raise SystemExit(2) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..7e645ac --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "enableAllProjectMcpServers": true, + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "bash \"$CLAUDE_PROJECT_DIR\"/.agents/setup claude" + } + ] + } + ] + } +} diff --git a/.cursor/environment.json b/.cursor/environment.json new file mode 100644 index 0000000..c57621a --- /dev/null +++ b/.cursor/environment.json @@ -0,0 +1,3 @@ +{ + "install": "bash .agents/setup cursor" +} diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..8b77f7f --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,3 @@ +# Base image kept here rather than in devcontainer.json so a project can swap +# in the stack it needs and Dependabot can keep it current. +FROM mcr.microsoft.com/devcontainers/base:ubuntu diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..0892b59 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,11 @@ +{ + "name": "devcontainer", + "build": { + "dockerfile": "Dockerfile" + }, + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/devcontainers/features/python:1": {} + }, + "postCreateCommand": "bash .agents/setup" +} diff --git a/.editorconfig b/.editorconfig index f999431..e169c92 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,3 +5,8 @@ charset = utf-8 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true + +# Vendored third-party skills stay byte-identical to upstream. +[.agents/skills/**] +trim_trailing_whitespace = false +insert_final_newline = false diff --git a/.gitattributes b/.gitattributes index 176a458..60b7789 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ -* text=auto +# Normalize line endings so scripts and symlinks survive a Windows checkout. +* text=auto eol=lf diff --git a/.github/workflows/agent-config.yml b/.github/workflows/agent-config.yml new file mode 100644 index 0000000..c2f0469 --- /dev/null +++ b/.github/workflows/agent-config.yml @@ -0,0 +1,33 @@ +name: Agent config + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: Canon renders clean for every harness + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - name: Run the shared setup entry point + run: bash .agents/setup --all + + - name: Verify invariants + # Adapters gitignored and untracked, local state absorbed, rendered + # output parses, skill symlinks resolve, skills lock current. + run: python3 .agents/sync.py check + + - name: No untracked files left behind + run: | + if [ -n "$(git status --porcelain)" ]; then + git status --porcelain + echo "Setup left files that are neither tracked nor ignored." + exit 1 + fi diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml new file mode 100644 index 0000000..450e1cc --- /dev/null +++ b/.github/workflows/copilot-setup-steps.yml @@ -0,0 +1,13 @@ +# Copilot's cloud coding agent runs the `copilot-setup-steps` job before the +# agent starts. It reads AGENTS.md and .agents/skills/ natively; this hook +# exists so project setup in .agents/setup reaches it too. +name: Copilot setup steps + +on: workflow_dispatch + +jobs: + copilot-setup-steps: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - run: bash .agents/setup diff --git a/.gitignore b/.gitignore index 4f87bc5..fb5af83 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,69 @@ -# Secrets — never committed; use the environment or an ignored .env. +# ─── Agent local state ──────────────────────────────────── +CLAUDE.local.md +.claude/settings.local.json +.claude/worktrees/ + +# ─── Generated agent adapters ───────────────────────────── +# Rendered per checkout from .agents/ by .agents/sync.py; never hand-edited +# or committed. Keep in step with sync.py's renderers — `sync.py check` fails +# if a renderer output is unignored or tracked. +/.mcp.json +/.claude/skills/ +/.codebuddy/skills/ +/.gemini/settings.json +/.qwen/settings.json +/.cursor/mcp.json +/.codex/config.toml +/.vscode/mcp.json +/.factory/mcp.json +/.amp/settings.json +/opencode.json +/kilo.jsonc + +# ─── Secrets & env ──────────────────────────────────────── .env .env.* !.env.example *.pem *.key +*.p12 +id_rsa* +id_ed25519* +service-account*.json +.netrc -# Agent-local files -CLAUDE.local.md -.claude/settings.local.json - -# OS / editor -.DS_Store -Thumbs.db -.idea/ -*.swp - -# Dependencies and build output — extend as the stack takes shape. +# ─── Dependencies ───────────────────────────────────────── node_modules/ -__pycache__/ .venv/ +venv/ +__pycache__/ +*.py[cod] + +# ─── Build output ───────────────────────────────────────── dist/ build/ +out/ target/ coverage/ +*.egg-info/ + +# ─── Logs & caches ──────────────────────────────────────── *.log +logs/ +.cache/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ tmp/ + +# ─── Editors & OS ───────────────────────────────────────── +.DS_Store +Thumbs.db +.idea/ +*.swp +*~ + +# ─── Local data ─────────────────────────────────────────── +*.sqlite +*.sqlite3 +*.db diff --git a/AGENTS.md b/AGENTS.md index 1820f9c..ab3af9d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,4 +1,4 @@ -# Project +# Created from a blank, stack-agnostic template. The first real task defines the project: pick the stack that fits, set up its tooling, and replace this @@ -22,3 +22,23 @@ being true. - Secrets stay in the environment or a gitignored `.env`, out of git and code. - Update docs in the same change that outdates them. Write a README once there is something honest to describe, not before. + +## Agent config + +- Skills and MCP servers are written once, in `.agents/skills/` and + `.agents/mcp/servers.json` (both empty by default; third-party skills: + `npx skills add @ -y`). Run `python3 .agents/sync.py` after + editing either: it renders each harness's gitignored config — never edit or + commit those files. +- The sync is two-way. Anything installed through one harness — `claude mcp + add`, a skill dropped in `.claude/skills/`, a server hand-added to any + rendered config — is adopted into `.agents/` by that same command and + rendered for every other harness. A pre-commit hook installed by + `.agents/setup` blocks commits until converged; `python3 .agents/sync.py + check` (CI runs it too) says what's off. Details: `.agents/README.md`. +- Every environment bootstraps through the same `.agents/setup`, reached via + committed hooks (devcontainer, Claude Code, Cursor, Copilot, Amp). Project + setup belongs in that script; keep it idempotent. +- `.agents/setup` installs `rtk` to compress command output. When a command + will print a lot and no hook rewrote it, prefix it: `rtk git diff`, + `rtk pytest`. diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..ff044d1 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,4 @@ +{ + "version": 1, + "skills": {} +}