diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f9e9675..8e31c57 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,7 +2,7 @@ name: Validate setup on: [push, pull_request, workflow_dispatch] jobs: test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: matrix: python: ['3.9', '3.12'] diff --git a/README.md b/README.md index 45a1be9..70ddc57 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,10 @@ Missing Zsh and other base tools are installed automatically on Ubuntu/Debian without sudo. Existing base programs, Vite+, and uv are reused. If bootstrap prerequisites are missing, `./install.sh --install-prerequisites` offers the administrative package installation and index refresh before continuing. +On an interactive first run, the installer also offers Git author and optional +GitHub CLI account setup. See [Git and GitHub profiles](docs/developer-workflow.md#git-and-github-profiles). +It also offers an optional [AI skill manager](docs/developer-workflow.md#ai-skills) +for Codex and Claude Code; run `skill-manager` anytime to add or remove skills. Choose a **Nerd Font** in your terminal settings to display prompt icons. In WSL or SSH, configure the font on the desktop client. Installation leaves your @@ -91,7 +95,7 @@ that registration is missing; pass `--skip-mcp` to skip it. | Area | Included | | --- | --- | -| Shell and prompt | Zsh, Oh My Posh, two bundled themes, autosuggestions, syntax highlighting, completion, persistent history | +| Shell and prompt | Zsh, Oh My Posh, upstream theme selection and two bundled themes, autosuggestions, syntax highlighting, completion, persistent history | | Search and navigation | fzf, fd, ripgrep, zoxide, custom command picker | | Files and previews | eza, bat, Yazi, jq | | Git and sessions | lazygit, delta, tmux, project session helper | diff --git a/bin/git-profile b/bin/git-profile new file mode 100755 index 0000000..dc0efdd --- /dev/null +++ b/bin/git-profile @@ -0,0 +1,6 @@ +#!/usr/bin/env python3 +"""Manage Git author details and GitHub CLI accounts.""" +from pathlib import Path +import runpy + +runpy.run_path(str(Path(__file__).resolve().parents[1] / "scripts/git_profiles.py"), run_name="__main__") diff --git a/bin/skill-manager b/bin/skill-manager new file mode 100755 index 0000000..f355a3b --- /dev/null +++ b/bin/skill-manager @@ -0,0 +1,6 @@ +#!/usr/bin/env python3 +"""Browse and manage local AI agent skills.""" +from pathlib import Path +import runpy + +runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/skill_manager.py'), run_name='__main__') diff --git a/config/zsh/zshrc b/config/zsh/zshrc index 40a26ba..c596af4 100644 --- a/config/zsh/zshrc +++ b/config/zsh/zshrc @@ -60,7 +60,7 @@ if [[ -r "$_dev_plugin_dir/zsh-autosuggestions/current/zsh-autosuggestions.zsh" fi if (( $+commands[oh-my-posh] )); then - eval "$(oh-my-posh init zsh --config "$LINUX_SETUP_DIR/config/oh-my-posh/quick-term.omp.json")" + eval "$(oh-my-posh init zsh --config "${LINUX_SETUP_POSH_THEME:-$LINUX_SETUP_DIR/config/oh-my-posh/quick-term.omp.json}")" fi # These stay private to the device. Portable customizations belong in this repo. diff --git a/docs/customization.md b/docs/customization.md index 1ea1bf5..746f785 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -12,18 +12,20 @@ for Zsh; the `iterm2` name does not require the iTerm2 application. | Quick-term | Orange accents, two-line prompt, duration and clock, compact command history | [`quick-term.omp.json`](../config/oh-my-posh/quick-term.omp.json) | | iTerm2 | Blue and lime segments, exit-status color, rocket prompt, contextual segments | [`iterm2.omp.json`](../config/oh-my-posh/iterm2.omp.json) | -To try the alternative in your current Zsh session: +Select any theme from the [Oh My Posh theme gallery](https://ohmyposh.dev/docs/themes/) +by setting its name in `~/.config/linux-setup-local/zshenv`: ```zsh -eval "$(oh-my-posh init zsh --config "$LINUX_SETUP_DIR/config/oh-my-posh/iterm2.omp.json")" +export LINUX_SETUP_POSH_THEME='paradox' ``` -To make it the shared default, change the `--config` path in -[`config/zsh/zshrc`](../config/zsh/zshrc) from `quick-term.omp.json` to -`iterm2.omp.json`, then run `reload`. To keep the choice private to one device, -put the initialization command above in `~/.config/linux-setup-local/zshrc`, -which loads after the shared prompt configuration. Remove that override to use -the shared default again. +Create the directory and file if needed, then run `reload`. Oh My Posh also +accepts a local configuration path or HTTPS URL in this variable. For the bundled +iTerm2 configuration, use `export LINUX_SETUP_POSH_THEME="$LINUX_SETUP_DIR/config/oh-my-posh/iterm2.omp.json"`. +Remove the setting to restore the bundled quick-term default. Upstream theme names +and URLs require network access and are cached by Oh My Posh; local files work +offline. The installed Oh My Posh version determines which upstream themes are +available. Use a Nerd Font in your terminal emulator. Font, terminal colors, Git state, screen width, and available hardware affect the appearance. Battery and Python @@ -56,9 +58,9 @@ linux-setup/ Add shared aliases to `config/zsh/aliases.zsh`, functions to `config/zsh/functions.zsh`, and executable scripts to `bin/`. Rerun the installer -to link new scripts. Edit the active theme in -`config/oh-my-posh/quick-term.omp.json`. Change its path in `config/zsh/zshrc` to -switch themes. Use `reload` after changing shell initialization or prompt settings. +to link new scripts. Edit the bundled default in +`config/oh-my-posh/quick-term.omp.json`. Use `reload` after changing shell +initialization or prompt settings. Private or device-specific additions go in: diff --git a/docs/developer-workflow.md b/docs/developer-workflow.md index 9f52885..b7e74ba 100644 --- a/docs/developer-workflow.md +++ b/docs/developer-workflow.md @@ -21,6 +21,63 @@ exec zsh Use the persistent checkout for installation, rather than a temporary review worktree. Configuration-only installation keeps existing tools and their versions. +## Git and GitHub profiles + +Run `./install.sh --github-setup` from the setup checkout to fill missing global +Git author settings, install GitHub CLI if needed, and add accounts. You can also +run `git-profile add` later: it offers GitHub CLI login, or you can reuse an +account already logged in. Add each GitHub username with its commit author name +and email, then use: + +```sh +git-profile list +cd ~/projects/my-repository +git-profile use my-github-username +``` + +`use` selects the account in GitHub CLI and sets `user.name` and `user.email` +for the current repository. GitHub CLI's active account is shared across terminal +sessions for that host, so switching accounts affects other repositories and +terminals too; their saved repository author settings do not change. Run +`gh auth status` to inspect accounts. HTTPS Git credentials use the GitHub CLI +account only if its credential helper is configured (for example, with +`gh auth setup-git`); SSH authentication depends on your SSH configuration. +Environment tokens such as `GH_TOKEN` can override saved GitHub CLI accounts. +GitHub CLI manages credentials separately and may store tokens in a plain-text +file if no credential store is available. The profile file contains only author +details and usernames, not tokens. Use an email associated with the intended +GitHub account, including its no-reply address if desired. + +## AI skills + +Run `skill-manager` to install, list, or remove local skills. From a checkout that +has not been installed, run `python3 scripts/skill_manager.py` instead. Select +Codex or Claude Code, then global or project scope. For project scope, provide +the path of an existing project directory; enter `.` to use the current directory. +The install menu groups the catalog by work area and accepts multiple selections. + +| Agent | Global directory | Project directory | +| --- | --- | --- | +| Codex | `~/.agents/skills/` | `/.agents/skills/` | +| Claude Code | `~/.claude/skills/` | `/.claude/skills/` | + +These are local agent skills, not skills uploaded to ChatGPT or another hosted +service. The manager lists and removes skill directories in the selected location, +including skills installed by other tools; it displays the exact paths and asks +for confirmation before deleting. It does not overwrite existing skills. Skills +installed as symlinks are removed by unlinking them; their targets are kept. Skills +in other discovery locations, such as `~/.codex/skills`, are not listed there. + +The catalog includes UI/UX Pro Max, Humanizer, frontend design, web guidelines, +React, testing, DevOps, and writing skills. OpenAI's Codex-specific skills are +offered only for Codex. The catalog records upstream repositories and commit +IDs in [`skills.catalog.json`](../skills.catalog.json). Downloads need network +access; files are then installed locally with their supporting resources. UI/UX +Pro Max's plugin-specific script paths are adapted to the selected installation +directory, so reinstall it after moving that directory. Review the displayed +source URLs: third-party skills contain instructions and may include scripts. +Restart the agent session if it does not immediately discover new skills. + ## Check a checkout ```sh diff --git a/docs/installation.md b/docs/installation.md index 84989a1..319e6e7 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -38,7 +38,10 @@ exec zsh linux-doctor ``` -The preflight checks prerequisites before installation. The dry run describes the +The preflight checks prerequisites before installation. Its GitHub homepage probe +is advisory: a failure may not reflect access to release downloads, which are +checked during installation. If installation fails, do not run `exec zsh` until +the error has been resolved and installation succeeds. The dry run describes the installation without applying it. Downloaded artifacts are verified against the SHA-256 values in `tools.lock.json`; repeat installs reuse verified downloads. @@ -77,6 +80,20 @@ installation, including Zsh. At completion, the installer prints an `exec` comma with the full Zsh path so it also works before your current shell has added `~/.local/bin` to `PATH`. +On an interactive normal installation, the installer asks for a Git author name +and email only when the corresponding global value is missing. It then offers +GitHub CLI installation and account setup on the first interactive run. Existing +values and an existing `gh` installation are preserved. Non-interactive runs, +preflight, dry runs, and configuration-only runs do not prompt. You can revisit +the account flow with `./install.sh --github-setup`, or install just the optional +CLI with `./install.sh --install-gh`. The GitHub CLI download is pinned and +checksum-verified like the other managed tools. + +The first interactive installation also offers the optional AI skill manager. +Choose Codex or Claude Code, an area of work, and global or project scope. You +can skip this step and run `skill-manager` later. See +[AI skills](developer-workflow.md#ai-skills) for sources and removal. + The PostgreSQL dependency is the `psql` client only. Installing it does not create a database cluster or start a server. Your applications retain responsibility for their Node/Python versions and dependency lockfiles. diff --git a/scripts/git_profiles.py b/scripts/git_profiles.py new file mode 100644 index 0000000..c9580b0 --- /dev/null +++ b/scripts/git_profiles.py @@ -0,0 +1,121 @@ +"""Interactive Git identity and GitHub account helpers; never store credentials.""" +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + + +def profiles_path(): + return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "linux-setup-local/git-profiles.json" + + +def load_profiles(): + path = profiles_path() + return json.loads(path.read_text()) if path.exists() else {} + + +def save_profiles(profiles): + path = profiles_path() + path.parent.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".git-profiles-", dir=path.parent) + try: + with os.fdopen(fd, "w") as stream: + json.dump(profiles, stream, indent=2, ensure_ascii=False) + stream.write("\n") + os.replace(name, path) + finally: + if os.path.exists(name): + os.unlink(name) + + +def ask_yes(prompt, default=False): + suffix = " [Y/n] " if default else " [y/N] " + while True: + answer = input(prompt + suffix).strip().lower() + if not answer: + return default + if answer in ("y", "yes"): + return True + if answer in ("n", "no"): + return False + print("Please answer yes or no.") + + +def ask_required(prompt, default=""): + while True: + answer = input(prompt + (f" [{default}]" if default else "") + ": ").strip() or default + if answer: + return answer + print("A value is required.") + + +def configure_identity(): + for key, label in (("user.name", "Git author name"), ("user.email", "Git author email")): + result = subprocess.run(["git", "config", "--global", "--get", key], capture_output=True, text=True) + if result.returncode not in (0, 1): + raise RuntimeError(f"Cannot read global Git setting {key}: {result.stderr.strip()}") + if not result.stdout.strip(): + value = ask_required(label) + subprocess.run(["git", "config", "--global", key, value], check=True) + + +def add_profile(): + if not shutil.which("gh"): + raise RuntimeError("GitHub CLI is missing. Run ./install.sh --install-gh first.") + if ask_yes("Authenticate another GitHub account now?", default=True): + subprocess.run(["gh", "auth", "login"], check=True) + username = ask_required("GitHub username") + profiles = load_profiles() + if username in profiles and not ask_yes(f"Replace saved author details for {username}?"): + return + name = ask_required("Git author name") + email = ask_required("Git author email") + profiles[username] = {"name": name, "email": email} + save_profiles(profiles) + print(f"Saved {username}. Use git-profile use {username} inside a repository.") + + +def use_profile(username): + profiles = load_profiles() + if username not in profiles: + raise RuntimeError(f"No saved profile for {username}. Run git-profile add first.") + subprocess.run(["git", "rev-parse", "--git-dir"], check=True, stdout=subprocess.DEVNULL) + if not shutil.which("gh"): + raise RuntimeError("GitHub CLI is missing. Run ./install.sh --install-gh first.") + subprocess.run(["gh", "auth", "switch", "--hostname", "github.com", "--user", username], check=True) + for key, value in (("user.name", profiles[username]["name"]), ("user.email", profiles[username]["email"])): + subprocess.run(["git", "config", "--local", key, value], check=True) + print(f"Selected {username}: repository author updated; GitHub CLI active account changed for github.com.") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="action", required=True) + sub.add_parser("add", help="Add an account and its Git author details") + sub.add_parser("list", help="List saved profiles") + use = sub.add_parser("use", help="Select an account and set this repository's author") + use.add_argument("username") + args = parser.parse_args() + if args.action == "add": + add_profile() + elif args.action == "use": + use_profile(args.username) + else: + profiles = load_profiles() + for username, profile in sorted(profiles.items()): + print(f"{username}: {profile['name']} <{profile['email']}>") + if not profiles: + print("No profiles saved. Run git-profile add.") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except (RuntimeError, OSError, subprocess.CalledProcessError, ValueError, EOFError) as error: + print(f"git-profile: {error}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/preflight.py b/scripts/preflight.py index 416866d..0609a47 100644 --- a/scripts/preflight.py +++ b/scripts/preflight.py @@ -101,12 +101,15 @@ def check(root, config, data, state, cache, bin_dir, *, config_only=False, netwo if network and not config_only and not errors: try: ssl.create_default_context() - request = urllib.request.Request("https://github.com/", method="HEAD", headers={"User-Agent": "linux-setup/preflight"}) + request = urllib.request.Request("https://github.com/", headers={"User-Agent": "linux-setup/1"}) with urllib.request.urlopen(request, timeout=8): pass messages.append("GitHub HTTPS and certificate verification succeeded. Individual release downloads are verified during installation.") - except (OSError, ValueError, urllib.error.URLError): - errors.append("Cannot reach GitHub over verified HTTPS. Check network/proxy access and the system CA certificates; keep TLS verification enabled. On Ubuntu/Debian, --install-prerequisites installs ca-certificates.") + except (OSError, ValueError, urllib.error.URLError) as exc: + # A homepage probe can be blocked independently of release downloads. + # Let the actual checksum-verified downloads determine availability. + detail = f"HTTP {exc.code}" if isinstance(exc, urllib.error.HTTPError) else str(getattr(exc, "reason", exc)) + messages.append(f"Warning: GitHub HTTPS probe failed ({detail}). Installation will still try the actual downloads with TLS verification enabled. Check proxy settings and CA certificates if downloads fail; on Ubuntu/Debian, --install-prerequisites installs ca-certificates.") elif not network or config_only: messages.append("Network check skipped; no files were downloaded.") messages.append("Optional: a Nerd Font on the terminal-rendering device; ffmpeg, Poppler, and 7-Zip for extra Yazi previews.") diff --git a/scripts/setup.py b/scripts/setup.py index b668287..4cea0a8 100755 --- a/scripts/setup.py +++ b/scripts/setup.py @@ -573,13 +573,34 @@ def doctor(): failed.append(name) zsh = shutil.which("zsh") if zsh: - result = subprocess.run([zsh, "-lic", '(( $+functions[_zsh_autosuggest_start] && $+functions[_zsh_highlight] && $+functions[_omp_precmd] && $+functions[z] && $+functions[y] )) && [[ -r "$POSH_CONFIG" ]]'], capture_output=True, text=True) + result = subprocess.run([zsh, "-lic", '(( $+functions[_zsh_autosuggest_start] && $+functions[_zsh_highlight] && $+functions[_omp_precmd] && $+functions[z] && $+functions[y] )) && [[ "$POSH_CONFIG" == https://* || -r "$POSH_CONFIG" ]]'], capture_output=True, text=True) print("OK shell integrations" if result.returncode == 0 else "FAIL shell integrations: " + result.stderr) if result.returncode: failed.append("shell integrations") return 1 if failed else 0 +def install_gh(lock, key, deploy): + install_tools({"tools": {"gh": lock["optional_tools"]["gh"]}, "plugins": {}}, key, deploy) + + +def github_setup(lock, key, deploy): + from git_profiles import add_profile, ask_yes, configure_identity + + configure_identity() + if not find_tool("gh"): + if ask_yes("Install GitHub CLI (gh)?", default=True): + install_gh(lock, key, deploy) + else: + print("You can install it later with ./install.sh --install-gh.") + return + if any(os.environ.get(name) for name in ("GH_TOKEN", "GITHUB_TOKEN")): + print("GH_TOKEN or GITHUB_TOKEN is set and can override saved GitHub CLI accounts.") + while ask_yes("Add a GitHub account and author profile?"): + add_profile() + print("Manage accounts later with git-profile add, list, and use.") + + def main(): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group() @@ -589,6 +610,8 @@ def main(): group.add_argument("--restore", action="store_true", help="Restore files replaced by this installer") group.add_argument("--dry-run", action="store_true", help="Print the install plan without changing anything") group.add_argument("--preflight", action="store_true", help="Check prerequisites and network without installing") + group.add_argument("--install-gh", action="store_true", help="Install GitHub CLI without changing Git identity") + group.add_argument("--github-setup", action="store_true", help="Set up Git identity and GitHub accounts interactively") parser.add_argument("--skip-mcp", action="store_true", help="Do not modify Codex MCP configuration") args = parser.parse_args() os.environ["PATH"] = str(BIN) + os.pathsep + os.environ.get("PATH", "") @@ -613,6 +636,14 @@ def main(): return 0 key = platform_key() lock = json.loads((ROOT / "tools.lock.json").read_text()) + if args.install_gh: + install_gh(lock, key, Deployment()) + return 0 + if args.github_setup: + if not sys.stdin.isatty(): + raise RuntimeError("GitHub setup requires an interactive terminal.") + github_setup(lock, key, Deployment()) + return 0 from preflight import check cached = all(find_tool(TOOLS.get(name, name)) for name in lock["tools"]) for message in check(ROOT, CONFIG, DATA, STATE, CACHE, BIN, config_only=args.config_only, @@ -636,6 +667,21 @@ def main(): install_config(deploy) if not args.skip_mcp: install_mcp(deploy) + if not args.config_only and sys.stdin.isatty(): + from git_profiles import configure_identity + configure_identity() + if not deploy.state.get("github_setup_prompted"): + github_setup(lock, key, deploy) + deploy.state["github_setup_prompted"] = True + deploy.save() + if not deploy.state.get("skills_setup_prompted"): + from git_profiles import ask_yes + if ask_yes("Would you like to install AI skills?"): + result = subprocess.run([sys.executable, str(ROOT / "scripts/skill_manager.py")]) + if result.returncode: + print("Skill manager did not complete; rerun skill-manager when ready.") + deploy.state["skills_setup_prompted"] = True + deploy.save() print(f"\nInstalled from {ROOT}\nBackups: {STATE / 'backups'}") zsh = shutil.which("zsh") if zsh: diff --git a/scripts/skill_manager.py b/scripts/skill_manager.py new file mode 100755 index 0000000..5537645 --- /dev/null +++ b/scripts/skill_manager.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Browse, install, and remove local skills for Codex and Claude Code.""" +import json +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import sys +import tarfile +import tempfile +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +CATALOG = ROOT / "skills.catalog.json" +AGENTS = {"codex": "Codex", "claude": "Claude Code"} +MAX_ARCHIVE = 150 * 1024 * 1024 +MAX_SKILL = 80 * 1024 * 1024 + + +def choose(title, options): + print("\n" + title) + for i, label in enumerate(options, 1): + print(f" {i}. {label}") + while True: + answer = input("Choose a number (or q to cancel): ").strip().lower() + if answer in ("q", ""): + return None + if answer.isdigit() and 1 <= int(answer) <= len(options): + return int(answer) - 1 + print("Choose one of the displayed numbers.") + + +def choose_many(title, options): + print("\n" + title) + for i, label in enumerate(options, 1): + print(f" {i}. {label}") + while True: + answer = input("Numbers separated by commas (or Enter to cancel): ").strip() + if not answer or answer.lower() == "q": + return [] + try: + numbers = [int(part.strip()) for part in answer.replace(" ", ",").split(",") if part.strip()] + if not numbers or any(n < 1 or n > len(options) for n in numbers): + raise ValueError + return list(dict.fromkeys(n - 1 for n in numbers)) + except ValueError: + print("Enter numbers from the list, separated by commas.") + + +def confirm(prompt): + while True: + answer = input(prompt + " [y/N] ").strip().lower() + if answer in ("", "n", "no"): + return False + if answer in ("y", "yes"): + return True + print("Please answer yes or no.") + + +def destination(agent, scope, project=None): + if agent not in AGENTS or scope not in ("global", "project"): + raise ValueError("Unsupported agent or scope") + if scope == "global": + return Path.home() / (".agents/skills" if agent == "codex" else ".claude/skills") + if not project or not Path(project).expanduser().is_dir(): + raise ValueError("Project path must be an existing directory") + return Path(project).expanduser().resolve() / (".agents/skills" if agent == "codex" else ".claude/skills") + + +def get_archive(repository, commit, directory): + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) or not re.fullmatch(r"[0-9a-f]{40}", commit): + raise ValueError("Invalid catalog repository or commit") + archive = Path(directory) / (repository.replace("/", "--") + ".tar.gz") + if archive.exists(): + return archive + request = urllib.request.Request(f"https://codeload.github.com/{repository}/tar.gz/{commit}", headers={"User-Agent": "linux-setup/1"}) + try: + with urllib.request.urlopen(request, timeout=90) as response, archive.open("wb") as out: + total = 0 + while True: + chunk = response.read(1024 * 1024) + if not chunk: + break + total += len(chunk) + if total > MAX_ARCHIVE: + raise ValueError("Skill archive exceeds the download limit") + out.write(chunk) + except BaseException: + archive.unlink(missing_ok=True) + raise + return archive + + +def unpack_skill(archive, item, stage): + """Copy regular files from exactly one skill directory, without following links.""" + prefix = PurePosixPath(item["path"]) + if prefix.is_absolute() or ".." in prefix.parts: + raise ValueError("Invalid skill path in catalog") + seen, total = set(), 0 + with tarfile.open(archive, "r:gz") as bundle: + for member in bundle: + parts = PurePosixPath(member.name).parts + if len(parts) < 2: + continue + relative = PurePosixPath(*parts[1:]) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError("Unsafe path in skill archive") + try: + target_path = relative.relative_to(prefix) + except ValueError: + continue + if str(target_path) == "." or member.isdir(): + continue + if item.get("root_files") and str(target_path) not in item["root_files"]: + continue + if not member.isfile() or str(target_path) in seen: + raise ValueError(f"Unsafe or duplicate skill file: {target_path}") + seen.add(str(target_path)) + total += member.size + if total > MAX_SKILL: + raise ValueError("Skill exceeds the extracted size limit") + target = stage.joinpath(*target_path.parts) + target.parent.mkdir(parents=True, exist_ok=True) + with bundle.extractfile(member) as source, target.open("wb") as out: + shutil.copyfileobj(source, out) + target.chmod(0o755 if member.mode & 0o111 else 0o644) + if not (stage / "SKILL.md").is_file(): + raise ValueError("Selected source does not contain SKILL.md") + + +def install_skill(item, repository, root, temp): + name = item["id"] + if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", name): + raise ValueError("Invalid skill name in catalog") + target = root / name + if target.exists() or target.is_symlink(): + print(f"Keeping existing skill: {target}") + return False + print(f"Downloading {name} from https://github.com/{repository['repo']} at {repository['commit']} ...", flush=True) + archive = get_archive(repository["repo"], repository["commit"], temp) + with tempfile.TemporaryDirectory(prefix="linux-skill-stage-") as staged: + stage = Path(staged) + unpack_skill(archive, item, stage) + if item.get("adapt_uiux"): + skill = stage / "SKILL.md" + text = skill.read_text() + old = '${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max' + if old not in text: + raise ValueError("UI/UX Pro Max path format changed; catalog needs review") + escaped = str(target).replace('\\', '\\\\').replace('"', '\\"').replace('$', '\\$').replace('`', '\\`') + skill.write_text(text.replace(old, escaped)) + root.mkdir(parents=True, exist_ok=True) + target.mkdir() # Exclusive: do not replace an existing skill. + try: + shutil.copytree(stage, target, dirs_exist_ok=True) + except BaseException: + shutil.rmtree(target) + raise + print(f"Installed {name}: {target}") + return True + + +def list_installed(root): + if not root.is_dir(): + return [] + return sorted((p for p in root.iterdir() if not p.name.startswith('.') and p.is_dir() and (p / 'SKILL.md').is_file()), key=lambda p: p.name.lower()) + + +def remove_skills(root): + installed = list_installed(root) + if not installed: + print(f"No skills found in {root}.") + return + selected = choose_many("Select installed skills to remove", [p.name + (" (symlink; target kept)" if p.is_symlink() else "") for p in installed]) + if not selected: + return + chosen = [installed[i] for i in selected] + print("The following skill directories will be deleted:") + for path in chosen: + print(" " + str(path)) + if confirm("Remove these skills?"): + for path in chosen: + if path.is_symlink(): + path.unlink() + elif path.is_dir(): + shutil.rmtree(path) + else: + print(f"Skipping changed path: {path}") + continue + print(f"Removed {path.name}") + + +def install_menu(catalog, agent, root): + available = [item for item in catalog['skills'] if agent in item['agents']] + areas = sorted({area for item in available for area in item['areas']}) + area = choose("Choose your area", areas + ["All skills"]) + if area is None: + return + entries = available if area == len(areas) else [item for item in available if areas[area] in item['areas']] + labels = [f"{item['id']} — {item['description']} ({catalog['repositories'][item['repository']]['repo']})" for item in entries] + selected = choose_many("Select skills to install", labels) + if not selected: + return + print(f"Destination: {root}") + print("Skills are third-party instructions and may include scripts. Review their sources before use.") + for i in selected: + item = entries[i] + repo = catalog['repositories'][item['repository']] + print(f" {item['id']}: https://github.com/{repo['repo']}/tree/{repo['commit']}/{item['path']}") + if not confirm("Install these skills?"): + return + with tempfile.TemporaryDirectory(prefix="linux-skills-download-") as temp: + for i in selected: + item = entries[i] + try: + install_skill(item, catalog['repositories'][item['repository']], root, temp) + except (OSError, ValueError, tarfile.TarError) as error: + print(f"Could not install {item['id']}: {error}", file=sys.stderr) + print("Restart your agent session if it does not discover new skills immediately.") + + +def main(): + if not sys.stdin.isatty(): + print("skill-manager requires an interactive terminal.", file=sys.stderr) + return 1 + catalog = json.loads(CATALOG.read_text()) + while True: + action = choose("AI skill manager", ["Install skills", "Review or remove installed skills", "Exit"]) + if action is None or action == 2: + return 0 + agent_index = choose("Choose your AI agent", list(AGENTS.values())) + if agent_index is None: + continue + agent = list(AGENTS)[agent_index] + scope = choose("Choose the scope", ["Global (all projects)", "Project"]) + if scope is None: + continue + project = None + if scope == 1: + project = input("Existing project directory (absolute path, or . for current directory): ").strip() + if not project: + continue + try: + root = destination(agent, "global" if scope == 0 else "project", project) + except ValueError as error: + print(error) + continue + print(f"Skill directory: {root}") + if action == 0: + install_menu(catalog, agent, root) + else: + remove_skills(root) + + +if __name__ == "__main__": + try: + sys.exit(main()) + except (EOFError, KeyboardInterrupt): + print("\nCancelled.") + sys.exit(0) + except (OSError, ValueError, json.JSONDecodeError) as error: + print(f"skill-manager: {error}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/update-lock.py b/scripts/update-lock.py index f5ee4b2..ac6f761 100755 --- a/scripts/update-lock.py +++ b/scripts/update-lock.py @@ -9,11 +9,11 @@ path = root / "tools.lock.json" lock = json.loads(path.read_text()) parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument("tools", nargs="+", choices=list(lock["tools"])) +parser.add_argument("tools", nargs="+", choices=list(lock["tools"]) + list(lock.get("optional_tools", {}))) args = parser.parse_args() for name in args.tools: - item = lock["tools"][name] + item = (lock["tools"] | lock.get("optional_tools", {}))[name] repo = item["repository"].removeprefix("https://github.com/") request = urllib.request.Request(f"https://api.github.com/repos/{repo}/releases/latest", headers={"User-Agent": "linux-setup/1"}) with urllib.request.urlopen(request, timeout=45) as response: diff --git a/skills.catalog.json b/skills.catalog.json new file mode 100644 index 0000000..27cfcfa --- /dev/null +++ b/skills.catalog.json @@ -0,0 +1,240 @@ +{ + "repositories": { + "uiux": { + "repo": "nextlevelbuilder/ui-ux-pro-max-skill", + "commit": "4f2dbb67e64969a9a30ab00742f2d55d66ddec2b" + }, + "humanizer": { + "repo": "blader/humanizer", + "commit": "0ef9fe5bc3572734fd3ae6c448fe00a30cd5dcf0" + }, + "vercel": { + "repo": "vercel-labs/agent-skills", + "commit": "1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62" + }, + "anthropic": { + "repo": "anthropics/skills", + "commit": "2c5958ecac7cee2b583967a2c4981d0f4a75c579" + }, + "openai": { + "repo": "openai/skills", + "commit": "49f948faa9258a0c61caceaf225e179651397431" + }, + "agents": { + "repo": "wshobson/agents", + "commit": "9c61ab243def98f72da12abd41cfcf5bcd91af9d" + } + }, + "skills": [ + { + "id": "ui-ux-pro-max", + "description": "Searchable UI/UX design, accessibility, and design systems", + "repository": "uiux", + "path": ".claude/skills/ui-ux-pro-max", + "areas": [ + "UI and UX", + "Web development", + "Full stack" + ], + "agents": [ + "codex", + "claude" + ], + "adapt_uiux": true + }, + { + "id": "humanizer", + "description": "Edit prose while preserving meaning and the writer’s voice", + "repository": "humanizer", + "path": ".", + "areas": [ + "Content and writing" + ], + "agents": [ + "codex", + "claude" + ], + "root_files": [ + "SKILL.md", + "LICENSE" + ] + }, + { + "id": "frontend-design", + "description": "Build distinctive, intentional interfaces", + "repository": "anthropic", + "path": "skills/frontend-design", + "areas": [ + "UI and UX", + "Web development", + "Full stack" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "web-design-guidelines", + "description": "Review web interfaces for usability and accessibility", + "repository": "vercel", + "path": "skills/web-design-guidelines", + "areas": [ + "UI and UX", + "Web development" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "vercel-react-best-practices", + "description": "React and Next.js performance guidelines", + "repository": "vercel", + "path": "skills/react-best-practices", + "areas": [ + "Web development", + "Full stack" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "vercel-composition-patterns", + "description": "React component composition patterns", + "repository": "vercel", + "path": "skills/composition-patterns", + "areas": [ + "Web development", + "Full stack" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "webapp-testing", + "description": "Test web applications using Playwright", + "repository": "anthropic", + "path": "skills/webapp-testing", + "areas": [ + "Web development", + "Full stack", + "Testing and quality" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "api-design-principles", + "description": "REST and API design guidance", + "repository": "agents", + "path": "plugins/backend-development/skills/api-design-principles", + "areas": [ + "Full stack" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "github-actions-templates", + "description": "GitHub Actions CI/CD workflows", + "repository": "agents", + "path": "plugins/cicd-automation/skills/github-actions-templates", + "areas": [ + "DevOps and cloud", + "Testing and quality" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "terraform-module-library", + "description": "Terraform infrastructure module patterns", + "repository": "agents", + "path": "plugins/cloud-infrastructure/skills/terraform-module-library", + "areas": [ + "DevOps and cloud" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "writing-guidelines", + "description": "Review and improve technical writing", + "repository": "vercel", + "path": "skills/writing-guidelines", + "areas": [ + "Content and writing" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "doc-coauthoring", + "description": "Collaboratively draft and review documents", + "repository": "anthropic", + "path": "skills/doc-coauthoring", + "areas": [ + "Content and writing" + ], + "agents": [ + "codex", + "claude" + ] + }, + { + "id": "playwright", + "description": "Browser automation with Playwright", + "repository": "openai", + "path": "skills/.curated/playwright", + "areas": [ + "Testing and quality", + "Web development" + ], + "agents": [ + "codex" + ] + }, + { + "id": "gh-fix-ci", + "description": "Investigate and fix GitHub Actions failures", + "repository": "openai", + "path": "skills/.curated/gh-fix-ci", + "areas": [ + "DevOps and cloud", + "Testing and quality" + ], + "agents": [ + "codex" + ] + }, + { + "id": "security-best-practices", + "description": "Language-specific application security guidance", + "repository": "openai", + "path": "skills/.curated/security-best-practices", + "areas": [ + "Testing and quality", + "Full stack" + ], + "agents": [ + "codex" + ] + } + ] +} diff --git a/tests/test_git_profiles.py b/tests/test_git_profiles.py new file mode 100644 index 0000000..6af409e --- /dev/null +++ b/tests/test_git_profiles.py @@ -0,0 +1,90 @@ +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("git_profiles", ROOT / "scripts/git_profiles.py") +profiles = importlib.util.module_from_spec(spec) +spec.loader.exec_module(profiles) + + +class ProfileTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.env = patch.dict(os.environ, {"HOME": str(self.root), "XDG_CONFIG_HOME": str(self.root / "config"), "GIT_CONFIG_NOSYSTEM": "1"}) + self.env.start() + + def tearDown(self): + self.env.stop() + self.temp.cleanup() + + def test_identity_only_fills_missing_global_values(self): + subprocess.run(["git", "config", "--global", "user.name", "Existing"], check=True) + with patch("builtins.input", return_value="person@example.com") as prompt: + profiles.configure_identity() + self.assertEqual(prompt.call_count, 1) + self.assertEqual(subprocess.check_output(["git", "config", "--global", "user.name"], text=True).strip(), "Existing") + self.assertEqual(subprocess.check_output(["git", "config", "--global", "user.email"], text=True).strip(), "person@example.com") + + def test_add_existing_account_saves_only_author_details(self): + with patch.object(profiles.shutil, "which", return_value="/usr/bin/gh"), patch("builtins.input", side_effect=["n", "alice", "Alice Example", "alice@example.com"]), patch.object(profiles.subprocess, "run") as run: + profiles.add_profile() + run.assert_not_called() + self.assertEqual(profiles.load_profiles(), {"alice": {"name": "Alice Example", "email": "alice@example.com"}}) + self.assertEqual(profiles.profiles_path().stat().st_mode & 0o777, 0o600) + + def test_add_new_account_runs_github_login(self): + with patch.object(profiles.shutil, "which", return_value="/usr/bin/gh"), patch("builtins.input", side_effect=["y", "alice", "Alice", "a@example.com"]), patch.object(profiles.subprocess, "run") as run: + profiles.add_profile() + run.assert_called_once_with(["gh", "auth", "login"], check=True) + + def test_declining_replace_keeps_profile(self): + original = {"alice": {"name": "Alice", "email": "a@example.com"}} + profiles.save_profiles(original) + with patch.object(profiles.shutil, "which", return_value="/usr/bin/gh"), patch("builtins.input", side_effect=["n", "alice", "n"]): + profiles.add_profile() + self.assertEqual(profiles.load_profiles(), original) + + def test_use_changes_only_repository_identity_and_switches_account(self): + repo = self.root / "repo" + repo.mkdir() + subprocess.run(["git", "init", "-q", str(repo)], check=True) + profiles.save_profiles({"alice": {"name": "Alice Example", "email": "alice@example.com"}}) + calls = [] + actual_run = subprocess.run + def run(command, **kwargs): + if command[0] == "gh": + calls.append(command) + return subprocess.CompletedProcess(command, 0) + return actual_run(command, **kwargs) + old = Path.cwd() + try: + os.chdir(repo) + with patch.object(profiles.shutil, "which", return_value="/usr/bin/gh"), patch.object(profiles.subprocess, "run", side_effect=run): + profiles.use_profile("alice") + finally: + os.chdir(old) + self.assertEqual(calls, [["gh", "auth", "switch", "--hostname", "github.com", "--user", "alice"]]) + self.assertEqual(subprocess.check_output(["git", "-C", str(repo), "config", "--local", "user.email"], text=True).strip(), "alice@example.com") + self.assertFalse((self.root / ".gitconfig").exists()) + + def test_failed_switch_leaves_repository_identity_unchanged(self): + profiles.save_profiles({"alice": {"name": "Alice", "email": "a@example.com"}}) + def run(command, **kwargs): + if command[0] == "gh": + raise subprocess.CalledProcessError(1, command) + return subprocess.CompletedProcess(command, 0) + with patch.object(profiles.shutil, "which", return_value="/usr/bin/gh"), patch.object(profiles.subprocess, "run", side_effect=run) as mock: + with self.assertRaises(subprocess.CalledProcessError): + profiles.use_profile("alice") + self.assertEqual(mock.call_count, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_preflight.py b/tests/test_preflight.py index f9ba770..9fd7f4c 100644 --- a/tests/test_preflight.py +++ b/tests/test_preflight.py @@ -93,10 +93,15 @@ def test_missing_package_utilities_give_manual_remedy(self): with self.assertRaisesRegex(RuntimeError, "apt-get and dpkg-deb"): self.check(network=False) - def test_tls_failure_is_actionable(self): + def test_tls_failure_is_actionable_but_does_not_block_install(self): with patch.object(preflight.urllib.request, "urlopen", side_effect=urllib.error.URLError("certificate verify failed")): - with self.assertRaisesRegex(RuntimeError, "CA certificates"): - self.check() + messages = self.check() + self.assertTrue(any("CA certificates" in line and "certificate verify failed" in line for line in messages)) + + def test_network_probe_uses_get_like_downloads(self): + with patch.object(preflight.urllib.request, "urlopen") as network: + self.check() + self.assertEqual(network.call_args.args[0].get_method(), "GET") def test_bootstrap_dry_run_does_not_install_packages(self): # Run only the dry-run branch. The actual administrator commands must diff --git a/tests/test_setup.py b/tests/test_setup.py index ff802a3..b1ca1e3 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -87,6 +87,24 @@ def test_checkout_can_live_at_config_destination(self): class ArchiveTests(unittest.TestCase): + def test_optional_github_cli_installs_from_pinned_archive(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "gh.tar.gz" + with tarfile.open(archive, "w:gz") as bundle: + payload = b"#!/bin/sh\necho gh\n" + member = tarfile.TarInfo("gh_2.103.3_linux_amd64/bin/gh") + member.size = len(payload) + bundle.addfile(member, io.BytesIO(payload)) + lock = json.loads((ROOT / "tools.lock.json").read_text()) + with patch.object(setup, "STATE", root / "state"), patch.object(setup, "DATA", root / "data"), patch.object(setup, "BIN", root / "bin"), patch.object(setup, "find_tool", return_value=None), patch.object(setup, "download", return_value=archive) as download: + deploy = setup.Deployment() + setup.install_gh(lock, "linux-x86_64", deploy) + asset = lock["optional_tools"]["gh"]["platforms"]["linux-x86_64"] + download.assert_called_once_with(asset["url"], asset["sha256"], asset["name"]) + self.assertEqual(subprocess.check_output([str(root / "bin/gh")], text=True).strip(), "gh") + self.assertTrue(deploy.state["programs"]["gh"]["owned"]) + def test_executables_ignore_archive_paths(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) @@ -232,6 +250,18 @@ def install_base(deploy): base.assert_called_once() self.assertIn("Run: exec " + shlex.quote(str(setup.BIN / "zsh")), output.getvalue()) + def test_first_interactive_install_offers_skills_once(self): + import git_profiles + terminal = Mock() + terminal.isatty.return_value = True + self.deploy.state['github_setup_prompted'] = True + with patch.object(sys, 'argv', ['setup.py', '--skip-mcp']), patch.object(sys, 'stdin', terminal), patch.dict(os.environ, {'PATH': '/usr/bin:/bin'}), patch('preflight.check', return_value=[]), patch.object(setup, 'Deployment', return_value=self.deploy), patch.object(setup, 'migrate_legacy'), patch.object(setup, 'install_base'), patch.object(setup, 'install_tools'), patch.object(setup, 'install_config'), patch.object(git_profiles, 'configure_identity'), patch.object(git_profiles, 'ask_yes', return_value=True) as ask, patch.object(setup.subprocess, 'run', return_value=Mock(returncode=0)) as run: + self.assertEqual(setup.main(), 0) + self.assertEqual(setup.main(), 0) + ask.assert_called_once_with('Would you like to install AI skills?') + run.assert_called_once_with([sys.executable, str(ROOT / 'scripts/skill_manager.py')]) + self.assertTrue(self.deploy.state['skills_setup_prompted']) + class ManagerTests(unittest.TestCase): def test_existing_managers_are_not_reinstalled_or_reconfigured(self): diff --git a/tests/test_skill_manager.py b/tests/test_skill_manager.py new file mode 100644 index 0000000..510d7fc --- /dev/null +++ b/tests/test_skill_manager.py @@ -0,0 +1,117 @@ +import importlib.util +import io +import json +import os +from pathlib import Path +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('skill_manager', ROOT / 'scripts/skill_manager.py') +manager = importlib.util.module_from_spec(spec) +spec.loader.exec_module(manager) + + +class SkillManagerTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.addCleanup(self.temp.cleanup) + + def archive(self, files): + archive = self.root / 'source.tar.gz' + with tarfile.open(archive, 'w:gz') as tar: + for name, payload in files.items(): + member = tarfile.TarInfo(name) + if payload is None: + member.type = tarfile.SYMTYPE + member.linkname = '/etc/passwd' + tar.addfile(member) + else: + contents = payload.encode() + member.size = len(contents) + tar.addfile(member, io.BytesIO(contents)) + return archive + + def test_agent_and_project_locations(self): + with patch.object(manager.Path, 'home', return_value=self.root): + self.assertEqual(manager.destination('codex', 'global'), self.root / '.agents/skills') + self.assertEqual(manager.destination('claude', 'global'), self.root / '.claude/skills') + self.assertEqual(manager.destination('codex', 'project', self.root), self.root / '.agents/skills') + self.assertEqual(manager.destination('claude', 'project', self.root), self.root / '.claude/skills') + with self.assertRaises(ValueError): + manager.destination('codex', 'project', self.root / 'missing') + + def test_install_copies_support_files_and_does_not_replace_existing(self): + archive = self.archive({'repo/skills/demo/SKILL.md': '---\nname: demo\n---', 'repo/skills/demo/scripts/tool.py': 'print(1)'}) + item = {'id': 'demo', 'path': 'skills/demo'} + target = self.root / 'skills' + with patch.object(manager, 'get_archive', return_value=archive) as fetch: + self.assertTrue(manager.install_skill(item, {'repo': 'org/repo', 'commit': 'a' * 40}, target, self.root)) + self.assertEqual((target / 'demo/scripts/tool.py').read_text(), 'print(1)') + (target / 'demo/SKILL.md').write_text('my version') + self.assertFalse(manager.install_skill(item, {'repo': 'org/repo', 'commit': 'a' * 40}, target, self.root)) + self.assertEqual(fetch.call_count, 1) + self.assertEqual((target / 'demo/SKILL.md').read_text(), 'my version') + + def test_uiux_search_paths_point_to_actual_skill(self): + archive = self.archive({'repo/skill/SKILL.md': 'python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py"'}) + item = {'id': 'ui-ux-pro-max', 'path': 'skill', 'adapt_uiux': True} + with patch.object(manager, 'get_archive', return_value=archive): + manager.install_skill(item, {'repo': 'org/repo', 'commit': 'a' * 40}, self.root / 'skills', self.root) + result = (self.root / 'skills/ui-ux-pro-max/SKILL.md').read_text() + self.assertIn(str(self.root / 'skills/ui-ux-pro-max/scripts/search.py'), result) + self.assertNotIn('CLAUDE_PLUGIN_ROOT', result) + + def test_archive_rejects_symlinks_and_traversal(self): + for files in ({'repo/skill/SKILL.md': 'ok', 'repo/skill/link': None}, {'repo/skill/SKILL.md': 'ok', 'repo/skill/../../outside': 'bad'}): + with self.subTest(files=files): + archive = self.archive(files) + stage = self.root / 'stage' + stage.mkdir(exist_ok=True) + with self.assertRaises(ValueError): + manager.unpack_skill(archive, {'path': 'skill'}, stage) + self.assertFalse((self.root / 'outside').exists()) + + def test_remove_requires_selection_and_confirmation(self): + skill = self.root / 'demo' + skill.mkdir() + (skill / 'SKILL.md').write_text('my content') + with patch('builtins.input', side_effect=['1', 'n']): + manager.remove_skills(self.root) + self.assertTrue(skill.exists()) + with patch('builtins.input', side_effect=['1', 'y']): + manager.remove_skills(self.root) + self.assertFalse(skill.exists()) + + def test_remove_symlink_keeps_the_target(self): + target = self.root / 'actual' + target.mkdir() + (target / 'SKILL.md').write_text('keep') + directory = self.root / 'skills' + directory.mkdir() + (directory / 'linked').symlink_to(target, target_is_directory=True) + with patch('builtins.input', side_effect=['1', 'y']): + manager.remove_skills(directory) + self.assertFalse((directory / 'linked').is_symlink()) + self.assertEqual((target / 'SKILL.md').read_text(), 'keep') + + def test_catalog_pins_repositories_and_valid_skill_paths(self): + catalog = json.loads(manager.CATALOG.read_text()) + ids = set() + for item in catalog['skills']: + self.assertNotIn(item['id'], ids) + ids.add(item['id']) + self.assertTrue(set(item['agents']) <= set(manager.AGENTS)) + self.assertTrue(item['areas']) + self.assertNotIn('..', Path(item['path']).parts) + repo = catalog['repositories'][item['repository']] + self.assertRegex(repo['commit'], r'^[0-9a-f]{40}$') + self.assertIn('humanizer', ids) + self.assertIn('ui-ux-pro-max', ids) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools.lock.json b/tools.lock.json index ac9c31c..d2a83d6 100644 --- a/tools.lock.json +++ b/tools.lock.json @@ -239,5 +239,24 @@ "url": "https://codeload.github.com/zsh-users/zsh-syntax-highlighting/tar.gz/db085e4661f6aafd24e5acb5b2e17e4dd5dddf3e", "sha256": "874999413d147b7ad6776077e1b756d31d68284f9ef2ef240b33a4c842f0e1d8" } + }, + "optional_tools": { + "gh": { + "repository": "https://github.com/cli/cli", + "version": "v2.103.3", + "install_if_missing": true, + "platforms": { + "linux-x86_64": { + "name": "gh_2.103.3_linux_amd64.tar.gz", + "url": "https://github.com/cli/cli/releases/download/v2.103.3/gh_2.103.3_linux_amd64.tar.gz", + "sha256": "4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d" + }, + "linux-aarch64": { + "name": "gh_2.103.3_linux_arm64.tar.gz", + "url": "https://github.com/cli/cli/releases/download/v2.103.3/gh_2.103.3_linux_arm64.tar.gz", + "sha256": "ee32df2323c8847f5fac6cb6b4b69ca75828e9329a8f22f677021f7b3306ce63" + } + } + } } }