From 196df53a9b2749ba35324ec43024c49c7f0c6c46 Mon Sep 17 00:00:00 2001 From: nvaldez Date: Thu, 19 Nov 2026 09:50:26 +0100 Subject: [PATCH] phronesis v0.2.0: the CLI app per SPEC.md - list, filter, install, update - SPEC.md sectionized with stable ids (sectionize-markdown conventions) - src/phronesis: cli, registry, harnesses (modular, vibe first), state, formatting, completions; argcomplete completion; exit codes per SPEC - phronesis -> version line + skill table (name, version, category, description wrapped below, daedalus-style) - phronesis -> filtered table; close-match typos for skills+categories - phronesis --install | --project [--harness ] [-f] installs whole skill dir; prompt when present; EOF/default = skip; -f no prompt - phronesis --update -> refresh every state entry; warns unbundled; reinstalls missing - state: /phronesis/installed.json, unique by (name, harness, scope) - skill/python-tdd bumped 1.2.0 with category: development - test/ (56 tests, 92% cov) + autotest pytest check with 75% floor; all 7 autotest checks green Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .gitignore | 1 + CONTRIBUTING.md | 12 +- README.md | 69 ++++++-- SPEC.md | 302 +++++++++++++++++++++++++++++++++++ autotest.py | 16 +- pyproject.toml | 37 +++++ requirements.txt | 8 +- skill/python-tdd/SKILL.md | 5 +- src/phronesis/__init__.py | 26 +++ src/phronesis/__main__.py | 7 + src/phronesis/cli.py | 202 +++++++++++++++++++++++ src/phronesis/completions.py | 20 +++ src/phronesis/formatting.py | 81 ++++++++++ src/phronesis/harnesses.py | 54 +++++++ src/phronesis/registry.py | 106 ++++++++++++ src/phronesis/state.py | 79 +++++++++ test/test_cli.py | 215 +++++++++++++++++++++++++ test/test_completions.py | 18 +++ test/test_formatting.py | 75 +++++++++ test/test_harnesses.py | 26 +++ test/test_registry.py | 51 ++++++ test/test_state.py | 66 ++++++++ 22 files changed, 1453 insertions(+), 23 deletions(-) create mode 100644 SPEC.md create mode 100644 pyproject.toml create mode 100644 src/phronesis/__init__.py create mode 100644 src/phronesis/__main__.py create mode 100644 src/phronesis/cli.py create mode 100644 src/phronesis/completions.py create mode 100644 src/phronesis/formatting.py create mode 100644 src/phronesis/harnesses.py create mode 100644 src/phronesis/registry.py create mode 100644 src/phronesis/state.py create mode 100644 test/test_cli.py create mode 100644 test/test_completions.py create mode 100644 test/test_formatting.py create mode 100644 test/test_harnesses.py create mode 100644 test/test_registry.py create mode 100644 test/test_state.py diff --git a/.gitignore b/.gitignore index 1c4897e..107462c 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ htmlcov/ .idea/ .vscode/ *.swp +.coverage diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e6f2adf..b647e59 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,6 +15,7 @@ reading only that file should be able to follow the skill. name: # must equal the directory name version: x.y.z # semantic, start at 1.0.0 description: # what the skill is for + category: # lowercase label, used by `phronesis ` --- ``` @@ -26,12 +27,13 @@ reading only that file should be able to follow the skill. ```bash python -m pip install -r requirements.txt + python -m pip install -e . python autotest.py ``` -6. Commit with a semantic message, e.g. - `feat: add skill `. If you plan to publish, keep the pip - package name in sync with the repo. +6. Commit with a semantic message, e.g. `feat: add skill `. + A new category is announced to users the moment the skill is + bundled, since `phronesis` lists it live. ## Changing a skill @@ -48,9 +50,11 @@ reading only that file should be able to follow the skill. - `python_syntax` — `.py` files parse - `pycodestyle` — PEP 8 on `.py` files - `shellcheck` — shell scripts lint clean -- `frontmatter` — YAML header valid, `name` and `version` correct +- `frontmatter` — YAML header valid, `name`, `version`, and `category` + correct - `markdown` — markdownlint (`md013` line length and `md033` inline HTML are ignored) +- `pytest` — the suite in `test/`, coverage floor 75 percent ## Style diff --git a/README.md b/README.md index d27e64c..1f4b6e4 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,68 @@ # phronesis -A repository of skills: self-contained, markdown-defined instruction -packages that teach an agent how to work. +A chest of skills: a repository of `SKILL.md` instruction packages and +a CLI that lists them and installs them into an agent harness such as +[Vibe](https://mistral.ai). The name is [phronesis](https://en.wikipedia.org/wiki/Phronesis) — Aristotle's word for *practical wisdom*: the knowledge a skilled practitioner has, as opposed to abstract theory (`episteme`). +## Install + +```bash +pipx install phronesis # or: pip install phronesis +phronesis # list every bundled skill +``` + +## Command line + +```text +phronesis list every skill +phronesis filter the list +phronesis show one skill and an install hint +phronesis --install [--harness ] install globally (~/.vibe/skills) +phronesis --project [--harness ] install in the project only (.vibe/skills) +phronesis --update update every installed skill +``` + +- Already-installed skills prompt before being overwritten; `-f` / + `--force` skips the prompt. +- Installations are recorded in a per-machine state file + (`~/.config/phronesis/installed.json`), which powers `--update`. +- Shell completion via argcomplete; run + `activate-global-python-argcomplete` once after pipx install. + +The example table: + +```text +Phronesis Version: 0.1.0 + +skill version category +----------- ------- ---------- +python-tdd 1.2.0 development + Minimalist TDD architect for Python work +``` + ## Layout ```text phronesis/ -├── skill/ # one directory per skill -│ └── python-tdd/ -│ └── SKILL.md # the skill: front matter + instructions -├── autotest.py # every repo check, single entry point -├── README.md # this file -├── CONTRIBUTING.md # how to add or change a skill -├── LICENSE # MIT -└── requirements.txt # autotest dependencies +├── src/phronesis/ # the CLI package (cli, registry, harnesses, state, ...) +├── test/ # pytest suite +├── skill/ # one directory per skill; ships as package data +│ └── python-tdd/SKILL.md +├── autotest.py # every repo check, single entry point +├── SPEC.md # the full specification (sectionized, citable) +├── README.md, CONTRIBUTING.md, LICENSE +└── pyproject.toml, requirements.txt ``` ## Skills -| Skill | Version | Purpose | -| --- | --- | --- | -| [python-tdd](./skill/python-tdd/SKILL.md) | 1.1.0 | Minimalist TDD architect for Python work | +| Skill | Version | Category | Purpose | +| --- | --- | --- | --- | +| [python-tdd](./skill/python-tdd/SKILL.md) | 1.2.0 | development | Minimalist TDD architect for Python work | ## Checks @@ -36,16 +73,18 @@ phronesis/ - **pycodestyle** — PEP 8 style on every `.py` file - **shellcheck** — every shell script (`.sh`, `.bash`, or shebang) - **frontmatter** — every `skill//SKILL.md` carries a `---` fenced - YAML header with `name`, `version`, `description`; `name` matches the - directory and `version` is `x.y.z` + YAML header with `name`, `version`, `description`, `category`; `name` + matches the directory, `version` is `x.y.z`, `category` is kebab - **markdown** — markdownlint on every `.md` file, via `pymarkdownlnt` with front-matter support; `md013` (line length) and `md033` (inline HTML) are ignored +- **pytest** — the suite in `test/` with 75 percent coverage floor Run all checks: ```bash python -m pip install -r requirements.txt +python -m pip install -e . python autotest.py # every check python autotest.py frontmatter # only the named checks ``` diff --git a/SPEC.md b/SPEC.md new file mode 100644 index 0000000..eec8d0e --- /dev/null +++ b/SPEC.md @@ -0,0 +1,302 @@ +# phronesis specification + +How this repository is laid out, what the CLI does, and the rules for +maintaining it. This file alone is enough to rebuild the tool: it +states every observable behavior. Change this file first when the +behavior changes, then change the code and the tests to match. + + + +- [1. Purpose](#1-purpose) +- [2. Layout](#2-layout) +- [3. Command line](#3-command-line) +- [4. Skill registry and front matter](#4-skill-registry-and-front-matter) +- [5. Harnesses](#5-harnesses) +- [6. Install and project](#6-install-and-project) +- [7. Update](#7-update) +- [8. State file](#8-state-file) +- [9. Quality gates](#9-quality-gates) +- [10. Packaging](#10-packaging) +- [11. Implementation plan](#11-implementation-plan) + + + +## 1. Purpose + +- **1.1** Every heading and list item has a stable id. Cite an item as + `SPEC item 3.7.1`. New items get the next free number; numbers of + removed items are not reused. +- **1.2** phronesis is a repository of skills: self-contained + `SKILL.md` instruction packages. The CLI lists them, and installs + them into an agent harness such as Vibe: + +```text +phronesis list every skill +phronesis filter the list +phronesis show one skill and an install hint +phronesis --install [--harness ] install globally +phronesis --project [--harness ] install in the project only +phronesis --update update every installed skill +``` + +- **1.3** The tool is a pip or pipx package (section 10); after + `pipx install phronesis` the command `phronesis` is on `PATH` with the + skills bundled inside the wheel. +- **1.4** Harnesses are modular: the CLI knows only the harness + interface (section 5); each harness knows where that agent keeps its + skills. Adding a harness adds one class and one registry entry; no + other file changes. +- **1.5** The software may crash on bad input; no broad except hiding + defects (python-tdd skill item 0). The one dependency policy: reuse + first (daedalus SPEC item 1.5); today the dependencies are PyYAML + (front matter) and argcomplete (completion, guarded import). + +## 2. Layout + +- **2.1** Repository tree: + +```text +phronesis/ +├── src/ +│ └── phronesis/ # The CLI package +│ ├── __init__.py # Package version, REPO_ROOT +│ ├── __main__.py # python -m phronesis +│ ├── cli.py # Parser, list, install, update, dispatch +│ ├── registry.py # Skill dataclass, bundled SKILLS, front matter +│ ├── harnesses.py # Harness interface, HARNESS_REGISTRY, vibe harness +│ ├── state.py # installed.json load, save, record +│ ├── completions.py # Completion candidates for argcomplete +│ └── formatting.py # Table cells, wrapping, colors +├── test/ # pytest suite, one module per source module +├── skill/ # One directory per skill; ships as package data +│ └── / +│ └── SKILL.md +├── autotest.py # Every repo check, single entry point +├── SPEC.md # This file +├── README.md, CONTRIBUTING.md, LICENSE +└── pyproject.toml, requirements.txt +``` + +- **2.2** The skills ship through the package as + `phronesis._skills` mapped to the repository folder `skill/` + (SPEC item 10.3), so the registry resolves the same paths from a + checkout and from an installed package (daedalus `_library` pattern). + +## 3. Command line + +| Call | Result | Exit code | +| --- | --- | --- | +| `phronesis` | Version line, then every skill (SPEC items 3.3.1 to 3.3.5) | 0 | +| `phronesis -l`, `phronesis --list` | Same as the bare call | 0 | +| `phronesis ` | Version line, then the skills in that category | 0 | +| `phronesis ` | The one-row table for that skill plus an install hint | 0 | +| `phronesis --install [--harness ]` | Install globally (section 6) | 0, or 2 on error | +| `phronesis --project [--harness ]` | Install in the project only (section 6) | 0, or 2 on error | +| `phronesis --update` | Update every installed skill (section 7) | 0, or 2 on error | +| `phronesis --version` | `phronesis ` | 0 | +| `phronesis -h`, `phronesis --help` | Usage (SPEC item 3.8) | 0 | +| Unknown option, category, or skill; unknown harness | Error and close matches to stderr | 2 | + +- **3.1** One positional `` word is allowed. A token is + a category only when it matches a category in use; otherwise it is + treated as a skill name. Names and category labels must not collide + (SPEC item 4.6). +- **3.2** `--install` and `--project` are mutually exclusive; using + both exits 2. Each needs a skill word; with neither option the call + lists. +- **3.3** Listing format (bare, `--list`, filtered, one skill): + - **3.3.1** First line `Phronesis Version: `. When at least + one skill is listed, a blank line and the table follow. + - **3.3.2** The table has a header row `skill`, `version`, + `category`, then a rule row of `-` per column. Columns are + left-aligned, padded to the widest cell (header included), and + separated by two spaces. The `version` column is at least 7 wide. + - **3.3.3** One row per skill, sorted by name. `version` is the + front matter version, `category` the front matter category. + - **3.3.4** Under each row the description is wrapped to the terminal + width (at least 40 columns; 80 when the width cannot be read), + every line indented by 8 spaces. Long words and hyphenated words + are not split. + - **3.3.5** Color like daedalus: when enabled, the padded name cell + is green (`ESC[32m`), the version cell yellow (`ESC[33m`), the + category cell bright blue (`ESC[94m`), each followed by `ESC[0m`. + Enabled when `NO_COLOR` is unset or empty and either `FORCE_COLOR` + is non-empty or stdout is a terminal; a non-empty `NO_COLOR` wins. + +```text +Phronesis Version: 0.1.0 + +skill version category +----------- ------- ---------- +python-tdd 1.2.0 development + Minimalist TDD architect for Python work +``` + +- **3.4** `phronesis ` (no install option) prints the filtered + table for that one skill, then a blank line and + `install: phronesis --install --harness `. +- **3.5** Unknown skill or empty category: exit 2 with close matches + on stderr (up to 3 candidates, similarity at least 0.6). +- **3.6** `-h` / `--help` prints the argparse rendering of the parser + in SPEC item 3.10. +- **3.7** The installed command is the entry point + `phronesis = phronesis.cli:main`; `python -m phronesis` from the + repository root works the same. +- **3.8** Shell completion uses argcomplete and is off when the + package is not installed (guarded import). The completion candidates + are the category labels in use, the skill names, the `--harness` + choices, and `--install`, `--project`, `--force`, `-f`. +- **3.9** `--version` prints the installed distribution version; when + the metadata is missing, the version falls back to the checkout + `pyproject.toml`, else `unknown`. + +## 4. Skill registry and front matter + +- **4.1** A skill is one directory under `skill/` named after the + skill, containing a single required file `SKILL.md`. Support files + may follow later; the whole directory is copied on install. +- **4.2** `SKILL.md` starts with a `---` fenced YAML header with the + required keys `name`, `version`, `description`, `category`. +- **4.3** `name` equals the directory name; `version` is `x.y.z`; + `category` is a lowercase kebab label `^[a-z][a-z0-9-]*$`. +- **4.4** The registry loads every bundled skill at import time by + scanning `phronesis._skills/*/SKILL.md` through + `importlib.resources` and parsing the front matter; a malformed + skill raises at import, so tests and CI catch it immediately. +- **4.5** Skills cached in `SKILLS: dict[str, Skill]` keyed by name; + `Skill` carries name, version, description, category, and the source + directory path. +- **4.6** Every category in use is offered by completion and by the + `` word (SPEC items 3.1, 3.8). + +## 5. Harnesses + +- **5.1** A harness is a class with `name` and two locations: + `global_dir()` for the machine-level skill directory, and + `project_dir(cwd)` for the project-level skill directory. +- **5.2** `HARNESS_REGISTRY: dict[str, Harness]` maps names to instances; + `--harness ` picks from it. Unknown harness exits 2 with the + available names on stderr. +- **5.3** `--harness` defaults to `vibe`; the default can change when + more harnesses arrive, never silently in a patch release. +- **5.4** The `vibe` harness targets Mistral Vibe: + - **5.4.1** `global_dir()` is `~/.vibe/skills`. + - **5.4.2** `project_dir(cwd)` is `/.vibe/skills`. + - **5.4.3** Skills install as `//SKILL.md`; Vibe + discovers global skills in `~/.vibe/skills` and project skills in + the project's `.vibe/skills`. +- **5.5** A new harness adds one class and one `HARNESS_REGISTRY` entry; + the CLI, table, tests, and state file do not change. + +## 6. Install and project + +- **6.1** `phronesis --install` copies the whole skill + directory from the bundle into `harness.global_dir()//`; + `--project` copies into `harness.project_dir(cwd)//`. Parent + directories are created. +- **6.2** When the target `SKILL.md` already exists the CLI prompts + once on stderr and reads the answer from stdin: + `skill installed as , bundle has . update? [y/N]` + - **6.2.1** Answering `y` or `Y` overwrites and records the state. + - **6.2.2** Any other answer or end of stdin leaves the target + untouched, prints `skipped`, and exits 0. + - **6.2.3** `--force` (or `-f`) overwrites and records without + prompting. +- **6.3** After every install or overwrite the state file records the + entry (section 8). +- **6.4** Success prints one line to stdout: + `installed python-tdd 1.2.0 (vibe, global) -> /home/me/.vibe/skills/python-tdd/SKILL.md`. +- **6.5** A skill that is not bundled exits 2 with close matches + (SPEC item 3.5). + +## 7. Update + +- **7.1** `phronesis --update` loads the state file and processes + every recorded entry, so all installed skills end at the bundled + versions; it never prompts. +- **7.2** Per entry: copy the bundled directory over the recorded + path, print `updated python-tdd 1.0.0 -> 1.2.0 (vibe, global)`, and + record the new version in the state. +- **7.3** Entries whose local file is missing are reinstalled the same + way, so `--update` also repairs a broken tree. +- **7.4** Entries whose skill is no longer bundled print a warning to + stderr and are kept; the exit code stays 0. +- **7.5** When the state file records nothing, `--update` prints + `nothing installed` and exits 0. + +## 8. State file + +- **8.1** The CLI keeps one JSON state file per machine at + `/phronesis/installed.json`, where `` is + `%APPDATA%` on Windows and `$XDG_CONFIG_HOME` else `~/.config` + elsewhere. `$PHRONESIS_CONFIG` overrides the location wholesale for + tests and unusual setups. +- **8.2** The file is a JSON object holding a `skills` list; each + entry has `name`, `version`, `harness`, `scope`, `path`, and + `installed` (an ISO date): + +```json +{ + "skills": [ + { + "name": "python-tdd", + "version": "1.2.0", + "harness": "vibe", + "scope": "global", + "path": "/home/me/.vibe/skills/python-tdd/SKILL.md", + "installed": "2026-11-19" + } + ] +} +``` + +- **8.3** An entry is unique by `(name, harness, scope)`: reinstalling + updates the entry instead of appending a new one. The `path` is the + absolute `SKILL.md` path; `scope` is `global` or `project`. +- **8.4** Uninstalling is not part of the CLI; removing the harness + directory and the state entry is the workaround until section 6 + grows a `--remove`. + +## 9. Quality gates + +- **9.1** `autotest.py` is the single entry point and runs every check + in parallel; any check failing fails the run (exit 1). +- **9.2** `sanity`, `python_syntax`, `pycodestyle`, `shellcheck`, + `frontmatter`, and `markdown` cover every script and markdown file + in the repository as in the daedalus spec. +- **9.3** `frontmatter` requires the SPEC item 4.2 keys and checks the + SPEC item 4.3 formats on every `skill//SKILL.md`. +- **9.4** `pytest` runs the suite from `test/` in a subprocess with + coverage over the `phronesis` package and fails under 75 percent. +- **9.5** `requirements.txt` pins the check dependencies and the test + dependencies; the runtime dependencies live in `pyproject.toml` + (SPEC item 10.2). + +## 10. Packaging + +- **10.1** src layout: the package lives at `src/phronesis/`, the + console script is `phronesis = phronesis.cli:main`, the wheel + requires Python 3.11 or newer. +- **10.2** Runtime dependencies: `pyyaml`, `argcomplete`. +- **10.3** The `skill/` folder ships as package data: the distribution + maps the package `phronesis._skills` to the repository folder + `skill/` with every file included, so the registry sees the packaged + skills through `importlib.resources` (SPEC item 2.2). +- **10.4** Build backend is setuptools; a checkout can run + `python -m pip install -e .` and the CLI stays identical to the + installed one. + +## 11. Implementation plan + +- **11.1** `registry.py` first: front matter parsing, `Skill`, and the + SKILLS scan; unit tested alone. +- **11.2** `state.py`: the JSON load, save, and record logic with + roundtrip tests. +- **11.3** `harnesses.py`: the interface and the vibe harness, tested + against empty temporary home and project directories. +- **11.4** `formatting.py` and `completions.py`: the table rendering + and the completion candidate functions, tested as pure functions. +- **11.5** `cli.py` last: parser, dispatch, install, and update wiring + the parts above; end to end tests through `main(argv)`. +- **11.6** The implementation order is bottom up so every layer has a + test before its consumer exists. diff --git a/autotest.py b/autotest.py index d9f5a0e..9bd3c09 100644 --- a/autotest.py +++ b/autotest.py @@ -35,11 +35,13 @@ SHELL_SUFFIXES = (".sh", ".bash") CRLF_SUFFIXES = (".bat",) SHELL_SHEBANG = re.compile(rb"^#!.*\b(ba|da|k|z)?sh\b") VERSION = re.compile(r"^\d+\.\d+\.\d+$") +CATEGORY = re.compile(r"^[a-z][a-z0-9-]*$") PRIVATE_KEY = re.compile(rb"-----BEGIN [A-Z ]*PRIVATE KEY-----") -FRONTMATTER_KEYS = ("name", "version", "description") +FRONTMATTER_KEYS = ("name", "version", "description", "category") PYCODESTYLE_IGNORE = ["E501", "E121", "E123", "E126", "E226", "E24", "E704", "W503", "W504"] MARKDOWN_IGNORE = frozenset({"md013", "md033"}) MAX_FILE_SIZE = 2_000_000 +MIN_COVERAGE_PERCENT = 75 def iter_files(root: pathlib.Path, suffixes: tuple[str, ...]) -> list[pathlib.Path]: @@ -128,6 +130,10 @@ def check_frontmatter(path: pathlib.Path) -> int: logger.error(" [FAIL] frontmatter %s: version '%s' is not x.y.z", path, data.get("version")) errors += 1 + if not CATEGORY.match(str(data.get("category", ""))): + logger.error(" [FAIL] frontmatter %s: category '%s' is not kebab", + path, data.get("category")) + errors += 1 return errors @@ -219,6 +225,13 @@ def run_on_all(check, suffixes: tuple[str, ...]) -> int: return check(iter_files(REPO_ROOT, suffixes)) +def run_pytest() -> int: + """Run pytest in a subprocess so coverage is not skewed by imports here.""" + cmd = [sys.executable, "-m", "pytest", "--cov-report=term-missing:skip-covered", + f"--cov-fail-under={MIN_COVERAGE_PERCENT}", "--cov=phronesis"] + return subprocess.run(cmd, cwd=REPO_ROOT, check=False).returncode + + CHECKS = { "sanity": run_sanity, "python_syntax": functools.partial(run_each, check_python_syntax, (".py",)), @@ -226,6 +239,7 @@ CHECKS = { "shellcheck": run_shellcheck, "frontmatter": run_frontmatter, "markdown": functools.partial(run_on_all, check_markdown, (".md",)), + "pytest": run_pytest, } diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..2ecd6d9 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,37 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "phronesis" +version = "0.1.0" +description = "A chest of skills: list them, install them into an agent harness (vibe, ...)" +readme = "README.md" +requires-python = ">=3.11" +dependencies = ["pyyaml>=6.0", "argcomplete>=3.3"] + +[project.scripts] +phronesis = "phronesis.cli:main" + +# The skills ship in the wheel as phronesis._skills mapped to the +# repository folder skill/, so the registry resolves the same paths from +# a checkout and from an installed package (SPEC.md 10.3). +[tool.setuptools] +packages = ["phronesis", "phronesis._skills"] + +[tool.setuptools.package-dir] +"" = "src" +"phronesis._skills" = "skill" + +[tool.setuptools.package-data] +"phronesis._skills" = ["**/*"] + +[tool.setuptools.exclude-package-data] +"*" = ["*.pyc", "__pycache__/*", "**/__pycache__/*"] + +[tool.pytest.ini_options] +testpaths = ["test"] +pythonpath = ["src"] + +[tool.coverage.run] +omit = ["*/test/*", "*/__main__.py"] diff --git a/requirements.txt b/requirements.txt index 704d796..20bf87e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,11 @@ +# runtime (also in pyproject.toml) +pyyaml>=6.0 +argcomplete>=3.3 + +# autotest and CI checks pycodestyle>=2.11 pymarkdownlnt>=0.9.20 -pyyaml>=6.0 shellcheck-py>=0.10 setuptools>=68 +pytest>=8.0 +pytest-cov>=5.0 diff --git a/skill/python-tdd/SKILL.md b/skill/python-tdd/SKILL.md index 0e79796..b762067 100644 --- a/skill/python-tdd/SKILL.md +++ b/skill/python-tdd/SKILL.md @@ -1,7 +1,8 @@ --- name: python-tdd -version: 1.1.0 -description: Python Test-Driven Development Skill +version: 1.2.0 +description: Minimalist TDD architect for Python work +category: development --- # Python TDD Skill: "Minimalist TDD Architect" diff --git a/src/phronesis/__init__.py b/src/phronesis/__init__.py new file mode 100644 index 0000000..3eb625a --- /dev/null +++ b/src/phronesis/__init__.py @@ -0,0 +1,26 @@ +"""phronesis package init: version fallback and repository root. + +SPEC items 3.9, 10.4. +""" +from __future__ import annotations + +import importlib.metadata +import pathlib +import tomllib + +PACKAGE = "phronesis" +REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent + + +def version() -> str: + """Installed metadata, else version from checkout pyproject.toml (SPEC item 3.9).""" + try: + return importlib.metadata.version(PACKAGE) + except importlib.metadata.PackageNotFoundError: + pyproject = REPO_ROOT / "pyproject.toml" + if pyproject.is_file(): + project = tomllib.loads(pyproject.read_text(encoding="utf-8")).get("project", {}) + checkout_version = project.get("version") + if isinstance(checkout_version, str) and checkout_version: + return checkout_version + return "unknown" diff --git a/src/phronesis/__main__.py b/src/phronesis/__main__.py new file mode 100644 index 0000000..d778c56 --- /dev/null +++ b/src/phronesis/__main__.py @@ -0,0 +1,7 @@ +"""python -m phronesis (SPEC item 3.7). + +""" +from phronesis.cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/phronesis/cli.py b/src/phronesis/cli.py new file mode 100644 index 0000000..c32d987 --- /dev/null +++ b/src/phronesis/cli.py @@ -0,0 +1,202 @@ +"""phronesis command line: list, install, and update skills (SPEC section 3). + +Parsed with argparse; completion via argcomplete; every observable +behavior is stated in SPEC.md sections 3 to 7. +""" +from __future__ import annotations + +import argparse +import difflib +import pathlib +import shutil +import sys + +try: # SPEC item 1.5: completion is optional and never breaks the CLI + from argcomplete import autocomplete as _autocomplete +except ImportError: # pragma: no cover - only hit without argcomplete + _autocomplete = None + +from phronesis import completions +from phronesis import harnesses +from phronesis import registry +from phronesis import state +from phronesis import version +from phronesis.formatting import format_list + +USAGE = ("phronesis [-h] [-l | --list] [--version] [--update] " + "[--harness ] [] [--install | --project] [-f]") + +PARSER_DESCRIPTION = "One CLI, a chest of skills (SPEC.md)." + +PARSER_EPILOG = ("Forms: phronesis lists every skill; phronesis filters " + "the list; phronesis shows one skill; phronesis " + "--install | --project installs it; phronesis --update refreshes " + "every installed skill.") + + +class UsageError(Exception): + """Bad phronesis arguments or an unknown skill (SPEC items 3.2, 3.5).""" + + +class PhronesisParser(argparse.ArgumentParser): + """Parser that raises UsageError instead of exiting (SPEC item 3.6).""" + + def error(self, message: str) -> None: + """argparse would exit(2); return the message through main instead.""" + raise UsageError(message) + + +def build_parser() -> PhronesisParser: + """The phronesis parser (SPEC item 3.6).""" + parser = PhronesisParser(prog="phronesis", usage=USAGE, allow_abbrev=False, + description=PARSER_DESCRIPTION, epilog=PARSER_EPILOG) + parser.add_argument("-l", "--list", action="store_true", + help="list every bundled skill") + parser.add_argument("--version", action="store_true", help="print the installed version") + parser.add_argument("--update", action="store_true", + help="update every skill recorded in the state file") + parser.add_argument("--install", action="store_true", + help="install globally for the harness") + parser.add_argument("--project", action="store_true", + help="install in the project only") + parser.add_argument("-f", "--force", action="store_true", + help="install or update without the confirmation prompt") + harness_action = parser.add_argument("--harness", metavar="", + default="vibe", + choices=sorted(harnesses.HARNESS_REGISTRY), + help="target harness (default: vibe)") + words_action = parser.add_argument("words", nargs="*", metavar="", + help="a category label to filter, or a skill name") + harness_action.completer = completions.harness_completer + words_action.completer = completions.word_completer + return parser + + +def _close_matches(name: str, candidates: list[str]) -> list[str]: + """Up to 3 names with similarity at least 0.6 (SPEC item 3.5).""" + return difflib.get_close_matches(name, candidates, n=3) + + +def lookup_skill(name: str) -> registry.Skill: + """Bundled skill by name; UsageError with close matches otherwise (SPEC item 3.5).""" + skill = registry.SKILLS.get(name) + if skill is not None: + return skill + matches = _close_matches(name, [*registry.SKILLS, *registry.CATEGORIES]) + hint = f"did you mean: {', '.join(matches)}" if matches else "run 'phronesis'" + raise UsageError(f"unknown skill {name!r}; {hint}") + + +def copy_skill(skill: registry.Skill, target_dir: pathlib.Path) -> pathlib.Path: + """Copy the whole bundled skill directory into target_dir/ (SPEC item 6.1).""" + destination = target_dir / skill.name + target_dir.mkdir(parents=True, exist_ok=True) + shutil.copytree(skill.source_dir, destination, dirs_exist_ok=True) + return destination / "SKILL.md" + + +def installed_version(skill_md: pathlib.Path) -> str: + """The version recorded in an already installed SKILL.md (SPEC item 6.2).""" + try: + data = registry.parse_frontmatter(skill_md.read_text(encoding="utf-8"), + origin=str(skill_md)) + except registry.RegistryError: + return "unknown" + return str(data["version"]) + + +def install_skill(skill: registry.Skill, harness: harnesses.Harness, scope: str, + force: bool, ask=None) -> int: + """Install one skill, prompting when the target exists (SPEC section 6).""" + if ask is None: + ask = input + if scope == "global": + target_dir = harness.global_dir() + else: + target_dir = harness.project_dir(pathlib.Path.cwd()) + skill_md = target_dir / skill.name / "SKILL.md" + if skill_md.is_file() and not force: + try: + answer = ask(f"skill installed as {installed_version(skill_md)}, " + f"bundle has {skill.version}. update? [y/N] ") + except EOFError: # SPEC item 6.2.2: end of stdin leaves the target untouched + answer = "" + if answer.strip().lower() != "y": + print("skipped") + return 0 + skill_md = copy_skill(skill, target_dir) + path = state.state_path() + entries = state.record(state.load(path), skill, harness.name, scope, skill_md) + state.save(entries, path) + print(f"installed {skill.name} {skill.version} ({harness.name}, {scope}) -> {skill_md}") + return 0 + + +def update_all() -> int: + """Update every installed skill from the state file (SPEC section 7).""" + path = state.state_path() + entries = state.load(path) + if not entries: + print("nothing installed") + return 0 + for entry in entries: + skill = registry.SKILLS.get(entry["name"]) + if skill is None: + print(f"phronesis: skill {entry['name']!r} is no longer bundled; kept as is", + file=sys.stderr) + continue + copy_skill(skill, pathlib.Path(entry["path"]).parent) + print(f"updated {skill.name} {entry['version']} -> {skill.version} " + f"({entry['harness']}, {entry['scope']})") + state.refresh_version(entries, entry, skill.version) + state.save(entries, path) + return 0 + + +def show_skills(skills) -> None: + """The version line and table for skills (SPEC items 3.3.1 to 3.3.5).""" + print(format_list(f"Phronesis Version: {version()}", list(skills))) + + +def dispatch(parsed: argparse.Namespace) -> int: + """Handle the parsed arguments (SPEC items 3.1 to 3.5, sections 6 and 7).""" + if parsed.version: + print(f"phronesis {version()}") + return 0 + if parsed.update: + return update_all() + if parsed.install and parsed.project: + raise UsageError("pick one of --install or --project, not both") + if parsed.install or parsed.project: + if len(parsed.words) != 1: + raise UsageError("usage: phronesis --install | --project [-f] " + "[--harness ]") + scope = "global" if parsed.install else "project" + skill = lookup_skill(parsed.words[0]) + harness = harnesses.lookup(parsed.harness) + return install_skill(skill, harness, scope, parsed.force) + if parsed.list or not parsed.words: + show_skills(registry.SKILLS.values()) + return 0 + word = parsed.words[0] + if word in registry.CATEGORIES and len(parsed.words) == 1: + show_skills(registry.skills_in_category(word).values()) + return 0 + skill = lookup_skill(word) + show_skills([skill]) + print() + print(f"install: phronesis {skill.name} --install --harness {parsed.harness}") + return 0 + + +def main(argv: list[str] | None = None) -> int: + """CLI entry point; phronesis errors exit with 2 (SPEC items 3.1, 3.5).""" + parser = build_parser() + if _autocomplete is not None: # SPEC item 3.8 + _autocomplete(parser) + try: + parsed = parser.parse_args(sys.argv[1:] if argv is None else argv) + return dispatch(parsed) + except (UsageError, state.StateError, harnesses.HarnessError) as error: + print(f"phronesis: {error}", file=sys.stderr) + return 2 diff --git a/src/phronesis/completions.py b/src/phronesis/completions.py new file mode 100644 index 0000000..b830442 --- /dev/null +++ b/src/phronesis/completions.py @@ -0,0 +1,20 @@ +"""Completion candidates for argcomplete (SPEC item 3.8). + +Plain functions on the registry, so the CLI also runs where +argcomplete is not installed; completion is then off (SPEC item 1.5). +""" +from __future__ import annotations + +from phronesis import harnesses +from phronesis import registry + + +def word_completer(prefix: str, **_kwargs) -> list[str]: + """Category labels and skill names for the word (SPEC item 3.8).""" + candidates = set(registry.CATEGORIES) | set(registry.SKILLS) + return sorted(name for name in candidates if name.startswith(prefix)) + + +def harness_completer(prefix: str, **_kwargs) -> list[str]: + """Harness names for --harness (SPEC item 3.8).""" + return sorted(name for name in harnesses.HARNESS_REGISTRY if name.startswith(prefix)) diff --git a/src/phronesis/formatting.py b/src/phronesis/formatting.py new file mode 100644 index 0000000..5245db3 --- /dev/null +++ b/src/phronesis/formatting.py @@ -0,0 +1,81 @@ +"""Table rendering for the skills list (SPEC items 3.3.1 to 3.3.5). + +Pure functions: no I/O, so the tests drive them with fixed widths. +""" +from __future__ import annotations + +import os +import shutil +import sys +import textwrap + +VERSION_COLUMN_MIN_WIDTH = 7 +DESCRIPTION_INDENT = " " * 8 +MIN_WRAP_WIDTH = 40 +FALLBACK_WRAP_WIDTH = 80 + +NAME_COLOR = "\033[32m" +VERSION_COLOR = "\033[33m" +CATEGORY_COLOR = "\033[94m" +RESET = "\033[0m" + + +def colors_enabled(stream=None) -> bool: + """NO_COLOR unset/empty and (FORCE_COLOR or a terminal): SPEC item 3.3.5.""" + stream = sys.stdout if stream is None else stream + if os.environ.get("NO_COLOR"): + return False + if os.environ.get("FORCE_COLOR"): + return True + return stream.isatty() + + +def wrap_width() -> int: + """The terminal width, at least MIN, FALLBACK when unknowable (SPEC item 3.3.4).""" + return max(MIN_WRAP_WIDTH, shutil.get_terminal_size().columns or FALLBACK_WRAP_WIDTH) + + +def cell(text: str, width: int, color: str = "") -> str: + """One left-aligned table cell, colored when enabled (SPEC items 3.3.2, 3.3.5).""" + padded = f"{text:<{width}}" + if color and colors_enabled(): + return f"{color}{padded}{RESET}" + return padded + + +def column(items: list[str], minimum: int = 1) -> int: + """Widest cell with the header included, floored at minimum (SPEC item 3.3.2).""" + return max([minimum, *(len(item) for item in items)]) + + +def wrapped_description(description: str, width: int) -> list[str]: + """Description wrapped to width, indented 8 (SPEC item 3.3.4).""" + wrapper = textwrap.TextWrapper(width=max(width, MIN_WRAP_WIDTH), + break_long_words=False, break_on_hyphens=False, + initial_indent=DESCRIPTION_INDENT, + subsequent_indent=DESCRIPTION_INDENT) + return wrapper.wrap(description) + + +def format_list(version_line: str, skills: list) -> str: + """Version line, then the table with wrapped descriptions (SPEC item 3.3).""" + lines = [version_line] + if not skills: + return lines[0] + lines.append("") + entries = sorted(skills, key=lambda skill: skill.name) + name_width = column(["skill", *[s.name for s in entries]]) + version_width = column(["version", *[s.version for s in entries]], VERSION_COLUMN_MIN_WIDTH) + category_width = column(["category", *[s.category for s in entries]]) + lines.append(f"{'skill':<{name_width}} {'version':<{version_width}}" + f" {'category':<{category_width}}") + lines.append(f"{'-' * name_width} {'-' * version_width} {'-' * category_width}") + width = wrap_width() + for skill in entries: + lines.append(" ".join([ + cell(skill.name, name_width, NAME_COLOR), + cell(skill.version, version_width, VERSION_COLOR), + cell(skill.category, category_width, CATEGORY_COLOR), + ])) + lines.extend(wrapped_description(skill.description, width)) + return "\n".join(lines) diff --git a/src/phronesis/harnesses.py b/src/phronesis/harnesses.py new file mode 100644 index 0000000..505a441 --- /dev/null +++ b/src/phronesis/harnesses.py @@ -0,0 +1,54 @@ +"""Harness interface and the registry of harnesses (SPEC section 5). + +A harness only knows where its agent keeps skills; the CLI does the +install (SPEC item 1.4). +""" +from __future__ import annotations + +import abc +import pathlib + + +class HarnessError(Exception): + """Unknown or broken harness (SPEC item 5.2).""" + + +class Harness(abc.ABC): + """Where one agent keeps skills, machine-wide and per project (SPEC item 5.1).""" + + name: str + + @abc.abstractmethod + def global_dir(self) -> pathlib.Path: + """The machine-level skill directory.""" + + @abc.abstractmethod + def project_dir(self, cwd: pathlib.Path) -> pathlib.Path: + """The project-level skill directory for the project at cwd.""" + + +class VibeHarness(Harness): + """Mistral Vibe: ~/.vibe/skills and /.vibe/skills (SPEC item 5.4).""" + + name = "vibe" + home: pathlib.Path | None = None # tests override instead of the real home + + def global_dir(self) -> pathlib.Path: + """~/.vibe/skills (SPEC item 5.4.1); tests may redirect home.""" + home = self.home if self.home is not None else pathlib.Path.home() + return home / ".vibe" / "skills" + + def project_dir(self, cwd: pathlib.Path) -> pathlib.Path: + """/.vibe/skills (SPEC item 5.4.2).""" + return cwd / ".vibe" / "skills" + + +HARNESS_REGISTRY: dict[str, Harness] = {VibeHarness.name: VibeHarness()} + + +def lookup(name: str) -> Harness: + """The harness by name; HarnessError with known names otherwise (SPEC item 5.2).""" + harness = HARNESS_REGISTRY.get(name) + if harness is not None: + return harness + raise HarnessError(f"unknown harness {name!r}; available: {', '.join(sorted(HARNESS_REGISTRY))}") diff --git a/src/phronesis/registry.py b/src/phronesis/registry.py new file mode 100644 index 0000000..4350dc8 --- /dev/null +++ b/src/phronesis/registry.py @@ -0,0 +1,106 @@ +"""The bundled skill registry: front matter parsing and the SKILLS scan. + +SPEC section 4. A malformed bundled skill raises at import so tests and +CI catch it immediately (SPEC item 4.4). +""" +from __future__ import annotations + +import dataclasses +import importlib.resources +import pathlib +import re + +import yaml + +FRONTMATTER_KEYS = ("name", "version", "description", "category") +VERSION = re.compile(r"^\d+\.\d+\.\d+$") +CATEGORY = re.compile(r"^[a-z][a-z0-9-]*$") + + +class RegistryError(Exception): + """A bundled skill violates the front matter contract (SPEC item 4.3).""" + + +@dataclasses.dataclass(frozen=True) +class Skill: + """One bundled skill: front matter and its source directory (SPEC item 4.5).""" + + name: str + version: str + description: str + category: str + source_dir: pathlib.Path + + @property + def skill_md(self) -> pathlib.Path: + """Path of the bundled SKILL.md.""" + return self.source_dir / "SKILL.md" + + +def parse_frontmatter(text: str, origin: str = "skill") -> dict: + """The YAML front matter of a SKILL.md; RegistryError when malformed (SPEC item 4.2).""" + lines = text.splitlines() + if not lines or lines[0].strip() != "---": + raise RegistryError(f"{origin}: no '---' fenced YAML header") + try: + end = lines[1:].index("---") + 1 + except ValueError as error: + raise RegistryError(f"{origin}: unterminated front matter") from error + try: + data = yaml.safe_load("\n".join(lines[1:end])) + except yaml.YAMLError as error: + raise RegistryError(f"{origin}: invalid YAML: {error}") from error + if not isinstance(data, dict): + raise RegistryError(f"{origin}: front matter is not a mapping") + for key in FRONTMATTER_KEYS: + if not data.get(key): + raise RegistryError(f"{origin}: missing key {key!r}") + if not VERSION.match(str(data["version"])): + raise RegistryError(f"{origin}: version {data['version']!r} is not x.y.z") + if not CATEGORY.match(str(data["category"])): + raise RegistryError(f"{origin}: category {data['category']!r} is not kebab") + return data + + +def skills_root(): + """The skills root: the packaged phronesis._skills, else the checkout skill/ (SPEC item 2.2).""" + try: + return importlib.resources.files("phronesis._skills") + except ModuleNotFoundError: + from phronesis import REPO_ROOT + return REPO_ROOT / "skill" + + +def load_skills() -> dict[str, Skill]: + """Every bundled skill keyed by name (SPEC items 4.4, 4.5).""" + root = skills_root() + skills: dict[str, Skill] = {} + for entry in root.iterdir(): + if not entry.is_dir(): + continue + skill_md = entry / "SKILL.md" + if not skill_md.is_file(): + continue + text = skill_md.read_text(encoding="utf-8") + data = parse_frontmatter(text, origin=entry.name) + if data["name"] != entry.name: + raise RegistryError(f"{entry.name}: name {data['name']!r} != directory") + skill = Skill(name=str(data["name"]), version=str(data["version"]), + description=str(data["description"]), category=str(data["category"]), + source_dir=pathlib.Path(entry)) + if skill.name in skills: + raise RegistryError(f"{skill.name}: duplicate skill name") + skills[skill.name] = skill + return skills + + +SKILLS = load_skills() + +CATEGORIES: dict[str, list[str]] = {} +for _skill in SKILLS.values(): + CATEGORIES.setdefault(_skill.category, []).append(_skill.name) + + +def skills_in_category(category: str) -> dict[str, Skill]: + """The skills with the category (SPEC item 3.1).""" + return {name: skill for name, skill in SKILLS.items() if skill.category == category} diff --git a/src/phronesis/state.py b/src/phronesis/state.py new file mode 100644 index 0000000..97d4e7f --- /dev/null +++ b/src/phronesis/state.py @@ -0,0 +1,79 @@ +"""The installed-skills state file: load, save, and record (SPEC section 8). + +One JSON file per machine records every skill the CLI installed, so +`phronesis --update` knows what to update (SPEC item 7.1). +""" +from __future__ import annotations + +import datetime +import json +import os +import pathlib + +STATE_NAME = "installed.json" + + +class StateError(Exception): + """The state file exists but is not valid JSON or not a mapping (SPEC items 8.1, 8.2).""" + + +def config_home(environ: dict[str, str] | None = None) -> pathlib.Path: + """The config directory: PHRONESIS_CONFIG, else APPDATA / XDG_CONFIG_HOME / ~/.config.""" + env = os.environ if environ is None else environ + override = env.get("PHRONESIS_CONFIG") + if override: + return pathlib.Path(override) + if os.name == "nt": + appdata = env.get("APPDATA") + if appdata: + return pathlib.Path(appdata) + elif env.get("XDG_CONFIG_HOME"): + return pathlib.Path(env["XDG_CONFIG_HOME"]) + home = pathlib.Path.home() + return home / "AppData/Roaming" if os.name == "nt" else home / ".config" + + +def state_path(environ: dict[str, str] | None = None) -> pathlib.Path: + """Full path of installed.json inside the config directory (SPEC item 8.1).""" + return config_home(environ) / "phronesis" / STATE_NAME + + +def load(path: pathlib.Path) -> list[dict]: + """The skills list from the state file; missing file means nothing installed.""" + if not path.is_file(): + return [] + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, UnicodeDecodeError) as error: + raise StateError(f"{path}: {error}") from error + if not isinstance(data, dict) or not isinstance(data.get("skills"), list): + raise StateError(f"{path}: expected a JSON object with a 'skills' list") + return data["skills"] + + +def save(entries: list[dict], path: pathlib.Path) -> None: + """Write the skills list to the state file, parents created (SPEC item 8.2).""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"skills": entries}, indent=2) + "\n", encoding="utf-8") + + +def record(entries: list[dict], skill, harness: str, scope: str, target: pathlib.Path) -> list[dict]: + """Add or refresh the (name, harness, scope) entry in entries (SPEC item 8.3).""" + entry = { + "name": skill.name, + "version": skill.version, + "harness": harness, + "scope": scope, + "path": str(target), + "installed": datetime.date.today().isoformat(), + } + kept = [e for e in entries if not (e.get("name"), e.get("harness"), e.get("scope")) + == (skill.name, harness, scope)] + return sorted([*kept, entry], key=lambda e: (e["name"], e["harness"], e["scope"])) + + +def refresh_version(entries: list[dict], entry: dict, version: str) -> None: + """Set the version of the matching recorded entry in place.""" + for e in entries: + if e is entry: + e["version"] = version diff --git a/test/test_cli.py b/test/test_cli.py new file mode 100644 index 0000000..0326abf --- /dev/null +++ b/test/test_cli.py @@ -0,0 +1,215 @@ +"""CLI tests: list, filter, install, prompt, force, and update (SPEC sections 3, 6, 7).""" +import json + +import pytest + +from phronesis import cli +from phronesis import harnesses +from phronesis import state + + +@pytest.fixture +def config(tmp_path, monkeypatch): + """An isolated state file and an isolated vibe home.""" + monkeypatch.setenv("PHRONESIS_CONFIG", str(tmp_path / "cfg")) + harnesses.HARNESS_REGISTRY["vibe"].home = tmp_path / "home" + yield tmp_path / "cfg" + harnesses.HARNESS_REGISTRY["vibe"].home = None + + +def run(capsys, *argv): + code = cli.main(list(argv)) + out = capsys.readouterr() + return code, out.out, out.err + + +def test_bare_call_lists_every_skill(config, capsys): + code, out, err = run(capsys) + assert code == 0 + assert out.startswith("Phronesis Version:") + assert "python-tdd" in out and "1.2.0" in out and "development" in out + + +def test_list_flag_matches_bare_call(config, capsys): + assert run(capsys, "--list")[0] == 0 + + +def test_version_flag(config, capsys): + code, out, _ = run(capsys, "--version") + assert code == 0 + assert out.startswith("phronesis ") + + +def test_category_filters_the_table(config, capsys): + code, out, _ = run(capsys, "development") + assert code == 0 + assert "python-tdd" in out + + +def test_unknown_category_prompts_close_matches(config, capsys): + code, out, err = run(capsys, "developmint") + assert code == 2 + assert "did you mean" in err + + +def test_unknown_skill_suggests(config, capsys): + code, _, err = run(capsys, "python-tb", "--install") + assert code == 2 + assert "python-tdd" in err + + +def test_show_one_skill_prints_install_hint(config, capsys): + code, out, _ = run(capsys, "python-tdd") + assert code == 0 + assert out.count("python-tdd") >= 2 + assert "install: phronesis python-tdd --install --harness vibe" in out + + +def test_install_and_project_reject_each_other(config, capsys): + code, _, err = run(capsys, "python-tdd", "--install", "--project") + assert code == 2 + + +def test_unknown_harness_exits_two(config, capsys): + code, _, err = run(capsys, "python-tdd", "--install", "--harness", "colossus") + assert code == 2 + assert "vibe" in err + + +def test_install_needs_one_skill_word(config, capsys): + code, _, err = run(capsys, "--install") + assert code == 2 + + +def test_install_writes_skill_and_state(config, capsys): + code, out, _ = run(capsys, "python-tdd", "--install") + assert code == 0 + target = config.parent / "home" / ".vibe" / "skills" / "python-tdd" / "SKILL.md" + assert target.is_file() + assert str(target) in out + entries = state.load(state.state_path()) + assert [e["name"] for e in entries] == ["python-tdd"] + assert entries[0]["version"] == "1.2.0" + assert entries[0]["scope"] == "global" + + +def test_project_install_lands_in_the_project(config, capsys, tmp_path, monkeypatch): + work = tmp_path / "work" + work.mkdir() + monkeypatch.chdir(work) + code, _, _ = run(capsys, "python-tdd", "--project") + assert code == 0 + target = tmp_path / "work" / ".vibe" / "skills" / "python-tdd" / "SKILL.md" + assert target.is_file() + assert state.load(state.state_path())[0]["scope"] == "project" + + +def test_prompt_shown_when_installed(config, capsys, monkeypatch, tmp_path): + answers = iter(["y"]) + monkeypatch.setattr("builtins.input", lambda prompt: answers.__next__()) + run(capsys, "python-tdd", "--install") + asked = run(capsys, "python-tdd", "--install") + assert asked[0] == 0 + + +def test_prompt_no_leaves_target_untouched(config, capsys, monkeypatch): + monkeypatch.setattr("builtins.input", lambda prompt: "n") + run(capsys, "python-tdd", "--install") + target = config.parent / "home" / ".vibe" / "skills" / "python-tdd" / "SKILL.md" + before = target.read_text(encoding="utf-8") + code, out, err = run(capsys, "python-tdd", "--install") + assert code == 0 + assert "skipped" in out + assert target.read_text(encoding="utf-8") == before + + +def test_prompt_accepts_default_no(config, capsys, monkeypatch): + monkeypatch.setattr("builtins.input", lambda prompt: "") + run(capsys, "python-tdd", "--install") + code, out, _ = run(capsys, "python-tdd", "--install") + assert code == 0 + assert "skipped" in out + + +def test_prompt_eof_on_stdin_means_no(config, capsys, monkeypatch): + def eof(prompt): + raise EOFError + + monkeypatch.setattr("builtins.input", eof) + run(capsys, "python-tdd", "--install") + code, out, _ = run(capsys, "python-tdd", "--install") + assert code == 0 + assert "skipped" in out + + +def test_force_overwrites_without_prompt(config, capsys, monkeypatch): + def fail(prompt): + raise AssertionError("force must not prompt") + + monkeypatch.setattr("builtins.input", fail) + run(capsys, "python-tdd", "--install") + code, out, _ = run(capsys, "python-tdd", "--install", "--force") + assert code == 0 + assert "installed" in out + + +def test_short_force_flag_matches_long(config, capsys): + code, out, _ = run(capsys, "python-tdd", "--install", "-f") + assert code == 0 + + +def test_update_refreshes_installed_skills(config, capsys): + path = state.state_path() + state.save([{"name": "python-tdd", "version": "1.0.0", "harness": "vibe", + "scope": "global", + "path": str(config.parent / "home" / ".vibe" / "skills" / "python-tdd" / "SKILL.md"), + "installed": "2026-01-01"}], path) + code, out, _ = run(capsys, "--update") + assert code == 0 + assert "1.0.0 -> 1.2.0" in out + assert state.load(path)[0]["version"] == "1.2.0" + + +def test_update_nothing_installed(config, capsys): + code, out, _ = run(capsys, "--update") + assert code == 0 + assert "nothing installed" in out + + +def test_update_warns_for_unbundled_skill(config, capsys): + path = state.state_path() + state.save([{"name": "ghost", "version": "1.0.0", "harness": "vibe", + "scope": "global", "path": "/tmp/ghost/SKILL.md", + "installed": "2026-01-01"}], path) + code, out, err = run(capsys, "--update") + assert code == 0 + assert "no longer bundled" in err + + +def test_update_reinstalls_a_missing_target(config, capsys, tmp_path): + path = state.state_path() + state.save([{"name": "python-tdd", "version": "1.1.0", "harness": "vibe", + "scope": "global", + "path": str(config.parent / "home" / ".vibe" / "skills" / "python-tdd" / "SKILL.md"), + "installed": "2026-01-01"}], path) + code, out, _ = run(capsys, "--update") + assert code == 0 + assert "1.1.0 -> 1.2.0" in out + + +def test_state_entries_unique_by_scope(config, capsys, tmp_path, monkeypatch): + run(capsys, "python-tdd", "--install") + work = tmp_path / "work2" + work.mkdir() + monkeypatch.chdir(work) + run(capsys, "python-tdd", "--project") + entries = state.load(state.state_path()) + assert sorted(e["scope"] for e in entries) == ["global", "project"] + + +def test_installed_json_is_plain_json(config, capsys): + run(capsys, "python-tdd", "--install") + data = json.loads(state.state_path().read_text(encoding="utf-8")) + assert set(data) == {"skills"} + assert set(data["skills"][0]) == {"name", "version", "harness", "scope", + "path", "installed"} diff --git a/test/test_completions.py b/test/test_completions.py new file mode 100644 index 0000000..2564ebc --- /dev/null +++ b/test/test_completions.py @@ -0,0 +1,18 @@ +"""Completion candidate tests (SPEC item 3.8).""" +from phronesis import completions +from phronesis import registry + + +def test_word_completer_offers_categories_and_skills(): + candidates = completions.word_completer("") + assert set(registry.CATEGORIES) <= set(candidates) + assert "python-tdd" in candidates + + +def test_word_completer_respects_the_prefix(): + assert completions.word_completer("python") == ["python-tdd"] + assert completions.word_completer("dev") == ["development"] + + +def test_harness_completer_lists_registered(): + assert completions.harness_completer("") == ["vibe"] diff --git a/test/test_formatting.py b/test/test_formatting.py new file mode 100644 index 0000000..5721bb1 --- /dev/null +++ b/test/test_formatting.py @@ -0,0 +1,75 @@ +"""Formatting tests: table layout and the description wrapping (SPEC items 3.3.1 to 3.3.5).""" +import phronesis.formatting as fmt + + +class FakeSkill: + def __init__(self, description): + self.name = "python-tdd" + self.version = "1.2.0" + self.category = "development" + self.description = description + + +def forces_plain(monkeypatch): + monkeypatch.setenv("NO_COLOR", "1") + + +def test_format_list_starts_with_version_line(monkeypatch): + forces_plain(monkeypatch) + assert fmt.format_list("Phronesis Version: 0.1.0", []).startswith("Phronesis Version: 0.1.0") + + +def test_no_skills_is_just_the_version_line(monkeypatch): + forces_plain(monkeypatch) + assert fmt.format_list("Phronesis Version: 0.1.0", []) == "Phronesis Version: 0.1.0" + + +def test_table_header_and_row(monkeypatch): + forces_plain(monkeypatch) + out = fmt.format_list("Phronesis Version: 0.1.0", [FakeSkill("a description")]) + lines = out.splitlines() + assert lines[0] == "Phronesis Version: 0.1.0" + assert lines[1] == "" + assert lines[2].rstrip() == "skill version category" + assert lines[3].rstrip() == "---------- ------- -----------" + assert lines[4].rstrip() == "python-tdd 1.2.0 development" + assert lines[5] == fmt.DESCRIPTION_INDENT + "a description" + + +def test_long_descriptions_wrap_indented(monkeypatch): + forces_plain(monkeypatch) + long_text = " ".join(["word"] * 60) + out = fmt.format_list("Phronesis Version: 0.1.0", [FakeSkill(long_text)]) + description_lines = [line for line in out.splitlines() if line.startswith(" " * 8)] + assert len(description_lines) > 1 + for line in description_lines: + assert len(line.rstrip()) <= 80 + + +def test_wrapping_never_splits_a_long_word(): + wide = fmt.wrapped_description("x" * 100, 40) + assert wide == [fmt.DESCRIPTION_INDENT + "x" * 100] + + +def test_colors_respect_no_color_over_force_color(monkeypatch): + class Tty: + def isatty(self): + return True + + monkeypatch.setenv("NO_COLOR", "1") + monkeypatch.setenv("FORCE_COLOR", "1") + assert fmt.colors_enabled(Tty()) is False + monkeypatch.setenv("NO_COLOR", "") + assert fmt.colors_enabled(Tty()) is True + monkeypatch.delenv("FORCE_COLOR") + assert fmt.colors_enabled(Tty()) is True + + +def test_cell_left_aligned(monkeypatch): + forces_plain(monkeypatch) + assert fmt.cell("ab", 5) == "ab " + + +def test_wrapped_description_indents_subsequent_lines(): + lines = fmt.wrapped_description("one two three four five " * 4, 40) + assert all(line.startswith(fmt.DESCRIPTION_INDENT) for line in lines) diff --git a/test/test_harnesses.py b/test/test_harnesses.py new file mode 100644 index 0000000..016ce68 --- /dev/null +++ b/test/test_harnesses.py @@ -0,0 +1,26 @@ +"""Harness tests: lookup and the vibe locations (SPEC section 5).""" +import pathlib + +import pytest + +from phronesis import harnesses + + +def test_lookup_returns_the_vibe_harness(): + assert harnesses.lookup("vibe").name == "vibe" + + +def test_lookup_unknown_names_the_available(): + with pytest.raises(harnesses.HarnessError, match="vibe"): + harnesses.lookup("colossus") + + +def test_vibe_global_dir(tmp_path): + harness = harnesses.VibeHarness() + harness.home = tmp_path + assert harness.global_dir() == tmp_path / ".vibe" / "skills" + + +def test_vibe_project_dir(tmp_path): + harness = harnesses.VibeHarness() + assert harness.project_dir(tmp_path) == tmp_path / ".vibe" / "skills" diff --git a/test/test_registry.py b/test/test_registry.py new file mode 100644 index 0000000..2ff4415 --- /dev/null +++ b/test/test_registry.py @@ -0,0 +1,51 @@ +"""Registry tests: front matter contract and the bundled SKILLS scan (SPEC section 4).""" +import pytest + +from phronesis import registry + +GOOD = """--- +name: python-tdd +version: 1.2.0 +description: Minimalist TDD architect for Python work +category: development +--- +""" +BAD_VERSION = GOOD.replace("1.2.0", "1.2") +BAD_CATEGORY = GOOD.replace("development", "Development") + + +def test_parse_frontmatter_reads_every_key(): + data = registry.parse_frontmatter(GOOD) + assert data["name"] == "python-tdd" + assert data["version"] == "1.2.0" + assert data["category"] == "development" + + +@pytest.mark.parametrize("text", [ + "no front matter at all", + GOOD.replace("---\n", "", 1), + "---\nname: x\nversion: 1.0.0\n", + BAD_VERSION, + BAD_CATEGORY, +]) +def test_parse_frontmatter_rejects_malformed(text): + with pytest.raises(registry.RegistryError): + registry.parse_frontmatter(text) + + +def test_skills_loads_the_bundled_python_tdd(): + assert "python-tdd" in registry.SKILLS + skill = registry.SKILLS["python-tdd"] + assert skill.version == "1.2.0" + assert skill.category == "development" + assert skill.description + assert (skill.source_dir / "SKILL.md").is_file() + + +def test_categories_list_the_packed_skills(): + assert "python-tdd" in registry.CATEGORIES[registry.SKILLS["python-tdd"].category] + + +def test_skills_in_category_filters_by_label(): + assert registry.skills_in_category("development") == {"python-tdd": registry.SKILLS["python-tdd"]} + assert registry.skills_in_category("nonesuch") == {} diff --git a/test/test_state.py b/test/test_state.py new file mode 100644 index 0000000..bb07027 --- /dev/null +++ b/test/test_state.py @@ -0,0 +1,66 @@ +"""State tests: config path, roundtrip, record, and refresh (SPEC section 8).""" +import json +import pathlib + +import pytest + +from phronesis import registry +from phronesis import state + + +def test_config_home_honors_override(): + env = {"PHRONESIS_CONFIG": "/tmp/cfg"} + assert state.config_home(env) == pathlib.Path("/tmp/cfg") + + +def test_config_home_uses_xdg_when_set(monkeypatch): + monkeypatch.setenv("XDG_CONFIG_HOME", "/home/me/.xdg") + assert state.config_home() == pathlib.Path("/home/me/.xdg") + + +def test_state_path_lands_in_phronesis_dir(tmp_path): + env = {"PHRONESIS_CONFIG": str(tmp_path)} + assert state.state_path(env) == tmp_path / "phronesis" / "installed.json" + + +def test_load_missing_file_is_empty(tmp_path): + assert state.load(tmp_path / "none.json") == [] + + +def test_save_then_load_roundtrip(tmp_path): + path = tmp_path / "installed.json" + entries = [{"name": "python-tdd", "version": "1.2.0", "harness": "vibe", + "scope": "global", "path": "/x/SKILL.md", "installed": "2026-11-19"}] + state.save(entries, path) + assert state.load(path) == entries + data = json.loads(path.read_text(encoding="utf-8")) + assert data["skills"] == entries + + +def test_load_rejects_garbage(tmp_path): + path = tmp_path / "installed.json" + path.write_text("{oops", encoding="utf-8") + with pytest.raises(state.StateError): + state.load(path) + + +def test_record_replaces_same_entry_keeps_others(): + skill = registry.SKILLS["python-tdd"] + old = {"name": "python-tdd", "version": "1.0.0", "harness": "vibe", + "scope": "project", "path": "/p/SKILL.md", "installed": "2026-01-01"} + other = {"name": "other", "version": "9.9.9", "harness": "vibe", + "scope": "global", "path": "/o/SKILL.md", "installed": "2026-01-02"} + entries = state.record([old, other], skill, "vibe", "project", + pathlib.Path("/p/SKILL.md")) + assert len(entries) == 2 + entry = next(e for e in entries if e["name"] == "python-tdd") + assert entry["version"] == "1.2.0" + assert entry["harness"] == "vibe" + assert entry["scope"] == "project" + + +def test_refresh_version_updates_in_place(): + entry = {"name": "python-tdd", "version": "1.0.0"} + entries = [entry] + state.refresh_version(entries, entry, "1.2.0") + assert entry["version"] == "1.2.0"