phronesis v0.1.0: skill repository with python-tdd, autotest, docs, MIT license

- skill/python-tdd/SKILL.md ported from ~/.agents (MD029 numbering fixed)
- autotest.py: sanity, python_syntax, pycodestyle, shellcheck, frontmatter,
  markdown checks on every script and md file - all green

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
nvaldez
2026-11-19 08:54:21 +01:00
commit 8212ef038d
7 changed files with 624 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
# virtual environments
.venv/
venv/
# python artifacts
__pycache__/
*.py[cod]
*.egg-info/
build/
dist/
# tooling caches
.cache/
.pytest_cache/
.ruff_cache/
htmlcov/
# editors
.idea/
.vscode/
*.swp
+64
View File
@@ -0,0 +1,64 @@
# Contributing to phronesis
A **skill** is one directory under `skill/` containing a single
`SKILL.md` file. It must be self-contained: anyone (or any agent)
reading only that file should be able to follow the skill.
## Adding a skill
1. Create a directory named after the skill:
`skill/<kebab-case-name>/`.
2. Add `skill/<name>/SKILL.md` with this front matter:
```yaml
---
name: <name> # must equal the directory name
version: x.y.z # semantic, start at 1.0.0
description: <one line> # what the skill is for
---
```
3. Write the instructions below the front matter. Cover identity,
rules, workflow, and examples; avoid references that only make
sense inside your machine.
4. Add the skill to the table in [README.md](./README.md).
5. Run the checks. All of them must pass:
```bash
python -m pip install -r requirements.txt
python autotest.py
```
6. Commit with a semantic message, e.g.
`feat: add skill <name>`. If you plan to publish, keep the pip
package name in sync with the repo.
## Changing a skill
- Bump the `version` in the front matter for every change:
patch for fixes, minor for additions, major for breaking changes.
- Keep `SKILL.md` the only required file; support files are allowed
but must stay inside the skill's directory.
## Check failures
`autotest.py <check>` runs one check; without arguments it runs all:
- `sanity` — LF line endings, no private keys, file size limit
- `python_syntax` — `.py` files parse
- `pycodestyle` — PEP 8 on `.py` files
- `shellcheck` — shell scripts lint clean
- `frontmatter` — YAML header valid, `name` and `version` correct
- `markdown` — markdownlint (`md013` line length and `md033` inline
HTML are ignored)
## Style
- KISS/YAGNI: a skill that fits in one screen beats a manual.
- Plain, imperative sentences. Lists over prose where order matters.
- Test what you preach: a TDD skill is itself written cleanly.
## License
By contributing you agree your work is released under the
[MIT license](./LICENSE).
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 nvaldez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+61
View File
@@ -0,0 +1,61 @@
# phronesis
A repository of skills: self-contained, markdown-defined instruction
packages that teach an agent how to work.
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`).
## 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
```
## Skills
| Skill | Version | Purpose |
| --- | --- | --- |
| [python-tdd](./skill/python-tdd/SKILL.md) | 1.1.0 | Minimalist TDD architect for Python work |
## Checks
`autotest.py` verifies every script and markdown file in the repo:
- **sanity** — LF line endings, no committed private keys, file size limit
- **python_syntax** — every `.py` file parses (`ast.parse`)
- **pycodestyle** — PEP 8 style on every `.py` file
- **shellcheck** — every shell script (`.sh`, `.bash`, or shebang)
- **frontmatter** — every `skill/<name>/SKILL.md` carries a `---` fenced
YAML header with `name`, `version`, `description`; `name` matches the
directory and `version` is `x.y.z`
- **markdown** — markdownlint on every `.md` file, via `pymarkdownlnt`
with front-matter support; `md013` (line length) and `md033` (inline
HTML) are ignored
Run all checks:
```bash
python -m pip install -r requirements.txt
python autotest.py # every check
python autotest.py frontmatter # only the named checks
```
## Adding a skill
See [CONTRIBUTING.md](./CONTRIBUTING.md). The short version: one
directory per skill under `skill/`, everything the agent needs in a
single `SKILL.md`, and `python autotest.py` green before you commit.
## License
[MIT](./LICENSE)
+261
View File
@@ -0,0 +1,261 @@
"""Run every phronesis check: syntax, lint, frontmatter, and markdown.
Single entry point for local runs and CI.
Usage:
.venv/bin/python autotest.py # every check
.venv/bin/python autotest.py frontmatter # only the named checks
"""
import argparse
import ast
import concurrent.futures
import functools
import logging
import os
import pathlib
import re
import shutil
import subprocess
import sys
import time
import pycodestyle
import yaml
from pymarkdown.api import PyMarkdownApi
logger = logging.getLogger(__name__)
REPO_ROOT = pathlib.Path(__file__).resolve().parent
SKILL_ROOT = REPO_ROOT / "skill"
SKIP_DIRS = frozenset({
".git", ".venv", "venv", ".cache", ".pytest_cache", ".ruff_cache",
"__pycache__", "htmlcov", "node_modules", "build", "dist",
})
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+$")
PRIVATE_KEY = re.compile(rb"-----BEGIN [A-Z ]*PRIVATE KEY-----")
FRONTMATTER_KEYS = ("name", "version", "description")
PYCODESTYLE_IGNORE = ["E501", "E121", "E123", "E126", "E226", "E24", "E704", "W503", "W504"]
MARKDOWN_IGNORE = frozenset({"md013", "md033"})
MAX_FILE_SIZE = 2_000_000
def iter_files(root: pathlib.Path, suffixes: tuple[str, ...]) -> list[pathlib.Path]:
"""List files under root with a suffix, skipping SKIP_DIRS."""
found = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [name for name in dirnames if name not in SKIP_DIRS]
found.extend(pathlib.Path(dirpath, name) for name in filenames
if pathlib.Path(name).suffix in suffixes)
return sorted(found)
def is_shell_script(path: pathlib.Path) -> bool:
"""A *.sh / *.bash file, or a suffixless file with a shell shebang."""
if path.suffix in SHELL_SUFFIXES:
return True
if path.suffix:
return False
with path.open("rb") as stream:
return SHELL_SHEBANG.match(stream.readline()) is not None
def check_python_syntax(path: pathlib.Path) -> int:
"""Return 1 when the Python file does not parse."""
try:
ast.parse(path.read_bytes(), filename=str(path))
except (SyntaxError, ValueError) as error:
logger.error(" [FAIL] python syntax %s: %s", path, error)
return 1
return 0
def check_pycodestyle(paths: list[pathlib.Path]) -> int:
"""Return the number of PEP 8 violations in paths."""
style_guide = pycodestyle.StyleGuide(ignore=PYCODESTYLE_IGNORE, show_source=True)
return style_guide.check_files([str(path) for path in paths]).total_errors
def check_shell(path: pathlib.Path) -> int:
"""Return 1 when shellcheck reports a problem or is missing."""
shellcheck = shutil.which("shellcheck")
if shellcheck is None:
logger.error(" [FAIL] shellcheck not found; run: pip install -r requirements.txt")
return 1
result = subprocess.run(
[shellcheck, "--external-sources", str(path)],
capture_output=True, text=True, check=False,
)
if result.returncode != 0:
logger.error(" [FAIL] shellcheck %s\n%s%s", path, result.stdout, result.stderr)
return 1
return 0
def parse_frontmatter(path: pathlib.Path) -> dict | None:
"""Return the YAML front matter of a markdown file, or None."""
lines = path.read_text(encoding="utf-8").splitlines()
if not lines or lines[0].strip() != "---":
return None
try:
end = lines[1:].index("---") + 1
data = yaml.safe_load("\n".join(lines[1:end]))
except ValueError:
return None
except yaml.YAMLError:
return None
return data if isinstance(data, dict) else None
def check_frontmatter(path: pathlib.Path) -> int:
"""Check skill/<name>/SKILL.md front matter keys, name, and version."""
errors = 0
data = parse_frontmatter(path)
if data is None:
logger.error(" [FAIL] frontmatter %s: no '---' fenced YAML header", path)
return 1
for key in FRONTMATTER_KEYS:
if not data.get(key):
logger.error(" [FAIL] frontmatter %s: missing key '%s'", path, key)
errors += 1
if data.get("name") != path.parent.name:
logger.error(" [FAIL] frontmatter %s: name '%s' != directory '%s'",
path, data.get("name"), path.parent.name)
errors += 1
if not VERSION.match(str(data.get("version", ""))):
logger.error(" [FAIL] frontmatter %s: version '%s' is not x.y.z",
path, data.get("version"))
errors += 1
return errors
def check_skills_dir() -> int:
"""Every skill/<name>/ directory must contain a SKILL.md."""
errors = 0
for entry in sorted(SKILL_ROOT.iterdir()) if SKILL_ROOT.is_dir() else []:
if entry.is_dir() and not (entry / "SKILL.md").is_file():
logger.error(" [FAIL] skill '%s' has no SKILL.md", entry.name)
errors += 1
return errors
def check_markdown(paths: list[pathlib.Path]) -> int:
"""Markdownlint failure count, minus MARKDOWN_IGNORE; YAML front matter allowed."""
errors = 0
for path in paths:
api = PyMarkdownApi().enable_extension_by_identifier("front-matter")
for failure in api.scan_path(str(path)).scan_failures:
if failure.rule_id.lower() in MARKDOWN_IGNORE:
continue
errors += 1
logger.error(" [FAIL] markdown %s:%s [%s] %s", path, failure.line_number,
failure.rule_id, failure.rule_description)
return errors
def check_line_ending(path: pathlib.Path) -> int:
"""Text files must be LF, CRLF_SUFFIXES files CRLF; binary files are skipped."""
data = path.read_bytes()
if b"\0" in data:
return 0
if path.suffix.lower() in CRLF_SUFFIXES:
if b"\n" not in data.replace(b"\r\n", b""):
return 0
logger.error(" [FAIL] %s needs CRLF line endings (cmd.exe)", path)
return 1
if b"\r" not in data:
return 0
logger.error(" [FAIL] CRLF line endings: %s", path)
return 1
def check_private_key(path: pathlib.Path) -> int:
"""Return 1 when the file contains a PEM or OpenSSH private key."""
if PRIVATE_KEY.search(path.read_bytes()) is None:
return 0
logger.error(" [FAIL] private key must not be committed: %s", path)
return 1
def check_file_size(path: pathlib.Path) -> int:
"""Return 1 when the file is larger than MAX_FILE_SIZE bytes."""
size = path.stat().st_size
if size <= MAX_FILE_SIZE:
return 0
logger.error(" [FAIL] %s is %d bytes (limit %d)", path, size, MAX_FILE_SIZE)
return 1
def run_sanity() -> int:
"""Line endings, private keys, and file size on every repo file."""
checks = (check_line_ending, check_private_key, check_file_size)
all_files = iter_files(REPO_ROOT, ("",))
return sum(check(path) for path in all_files for check in checks)
def run_shellcheck() -> int:
"""shellcheck every shell script, including suffixless launchers."""
candidates = iter_files(REPO_ROOT, (*SHELL_SUFFIXES, ""))
return sum(check_shell(path) for path in candidates if is_shell_script(path))
def run_frontmatter() -> int:
"""Front matter and SKILL.md presence checks on every skill."""
if not SKILL_ROOT.is_dir():
return 0
skills = sorted(SKILL_ROOT.glob("*/SKILL.md"))
return check_skills_dir() + sum(check_frontmatter(path) for path in skills)
def run_each(check, suffixes: tuple[str, ...]) -> int:
"""Apply a per-file check to every repo file with a suffix."""
return sum(check(path) for path in iter_files(REPO_ROOT, suffixes))
def run_on_all(check, suffixes: tuple[str, ...]) -> int:
"""Apply a list check to every repo file with a suffix."""
return check(iter_files(REPO_ROOT, suffixes))
CHECKS = {
"sanity": run_sanity,
"python_syntax": functools.partial(run_each, check_python_syntax, (".py",)),
"pycodestyle": functools.partial(run_on_all, check_pycodestyle, (".py",)),
"shellcheck": run_shellcheck,
"frontmatter": run_frontmatter,
"markdown": functools.partial(run_on_all, check_markdown, (".md",)),
}
def timed(check) -> tuple[int, float]:
"""Run a check and return its error count and elapsed seconds."""
start = time.monotonic()
return check(), time.monotonic() - start
def main(names: list[str]) -> int:
"""Run the named checks in parallel, print a summary, return 1 on any failure."""
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = {name: executor.submit(timed, CHECKS[name]) for name in names}
results = {name: future.result() for name, future in futures.items()}
print("\n########################################")
print("autotest results")
print("########################################")
for name, (errors, elapsed) in results.items():
print(f"[ {'PASS' if errors == 0 else 'FAIL'} ] {elapsed:6.2f}s {name}")
return int(any(errors != 0 for errors, _ in results.values()))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("checks", nargs="*", metavar="CHECK",
help=f"checks to run (default: all): {', '.join(CHECKS)}")
selected = parser.parse_args().checks or list(CHECKS)
unknown = sorted(set(selected) - set(CHECKS))
if unknown:
parser.error(f"unknown check(s): {', '.join(unknown)}")
logging.basicConfig(level=logging.INFO, format="%(levelname)-5s %(message)s")
sys.exit(main(selected))
+5
View File
@@ -0,0 +1,5 @@
pycodestyle>=2.11
pymarkdownlnt>=0.9.20
pyyaml>=6.0
shellcheck-py>=0.10
setuptools>=68
+191
View File
@@ -0,0 +1,191 @@
---
name: python-tdd
version: 1.1.0
description: Python Test-Driven Development Skill
---
# Python TDD Skill: "Minimalist TDD Architect"
Use this skill when anything about Python is involved.
---
## Core Identity
You are a **senior Python developer** who believes in **writing the least amount
of code necessary** to solve problems effectively. Your philosophy is:
> Simplicity is the ultimate sophistication. Write code that is easy to
> understand, test, and maintain.
You **strictly follow Test-Driven Development (TDD)** and **Object-Oriented
Programming (OOP)** principles to ensure scalability, reusability, and
robustness.
---
## 🎯 Key Skills & Practices
---
### 0. Basic Rules
- Imports
- No Inline imports allowed
- place on top of the file.
- unless the import name is very long, we prefer to `import` without `from`
- ex. `import pathlib` instead of `from pathlib import Path`
- Usage: `p = pathlib.Path('/a/b/c')`
- No Broad Exceptions
- It's okay for the software to crash, we don't hide defects like this
- Avoid `os.chdir()` or similar change directory functions.
- Use absolute pathing if possible.
- IF absolutely neccesary, it should be inside a `try-finally` block
---
### 1. Test-Driven Development (TDD)
- **Red-Green-Refactor Cycle**:
- Write a **failing test** (Red) for the smallest possible feature or bugfix.
- Write the **minimal code** to pass the test (Green).
- **Refactor** the code while keeping tests passing.
- **Testing Frameworks**: `pytest` or `doctest`.
- **Test Coverage**: Aim for **100% coverage** for critical paths, but
prioritize **meaningful tests** over quantity.
- **Mocking**: Use `unittest.mock` or `pytest-mock` to isolate dependencies.
---
### 2. Minimalist Coding
- **DRY (Don’t Repeat Yourself)**: Avoid duplication; abstract only when necessary.
- **KISS (Keep It Simple, Stupid)**: Prefer straightforward solutions over
clever ones.
- **YAGNI (You Aren’t Gonna Need It)**: Don’t implement features "just in case."
- **Single Responsibility Principle (SRP)**: Each function/class does **one
thing well**.
- **EAFP (Easier to Ask for Forgiveness than Permission)**: Use Python’s duck
typing and exception handling (e.g., `try/except` over `if/else` for type
checks).
---
### 3. Object-Oriented Programming (OOP)
- **SOLID Principles**:
- **Single Responsibility**: One class, one job.
- **Open/Closed**: Open for extension, closed for modification.
- **Liskov Substitution**: Subclasses must be substitutable for their base classes.
- **Interface Segregation**: Small, specific interfaces > monolithic ones.
- **Dependency Inversion**: Depend on abstractions, not concretions.
- **Design Patterns**: Use **Factory, Strategy, Observer, or Decorator** when
they simplify the design.
- **Magic Methods**: Leverage `__str__`, `__repr__`, `__eq__`, etc., for
intuitive objects.
- **Composition over Inheritance**: Prefer composition to avoid deep hierarchies.
---
### 4. Code Quality & Best Practices
- **Type Hints**: Use Python’s `typing` module for clarity (e.g., `def
greet(name: str) -> str`).
- **PEP 8 Compliance**: Follow Python’s style guide (e.g., snake_case, 4-space indents).
- **Docstrings**: Write **Google-style** or **NumPy-style** docstrings for all
public functions/classes.
- **Logging**: Use the `logging` module for debug/traceability.
- **Error Handling**: Raise **custom exceptions** for domain-specific errors.
- **Performance**: Optimize only after profiling (e.g., `cProfile`, `timeit`).
---
### 5. Tools & Workflow
- **Version Control**: `git` + **semantic commits** (e.g., `feat: add user validation`).
- **Linters/Formatters**: `black`, `flake8`, `isort`, `mypy` for static type checking.
- **Dependency Management**: `poetry` or `pipenv` for isolated environments.
- **CI/CD**: Automate testing/deployment with **GitHub Actions**, **GitLab
CI**, or **Jenkins**.
- **Containerization**: Use `Docker` for reproducible environments.
---
### 6. Problem-Solving Approach
1. **Understand the Problem**: Ask clarifying questions before coding.
2. **Design First**: Sketch a **class diagram** or **flowchart** for complex logic.
3. **TDD Loop**:
- Write a test for the simplest case.
- Implement the minimal code to pass.
- Refactor ruthlessly.
4. **Review**: Use **pair programming** or **code reviews** to catch edge cases.
---
### 7. Example Project: Minimalist TDD + OOP
**Task**: Build a `BankAccount` class with `deposit`, `withdraw`, and `balance` methods.
**TDD Steps**:
1. **Test First** (Red):
```python
def test_deposit_increases_balance():
account = BankAccount()
account.deposit(100)
assert account.balance == 100
```
2. **Minimal Implementation** (Green):
```python
class BankAccount:
def __init__(self):
self.balance = 0
def deposit(self, amount: float) -> None:
self.balance += amount
```
3. **Refactor**:
- Add type hints.
- Add input validation (e.g., `if amount <= 0: raise ValueError`).
- Write tests for edge cases (e.g., negative amounts).
---
### 8. Collaboration & Mindset
- **Code Reviews**: Focus on **readability** and **testability**.
- **Documentation**: Write **tutorials** or **ADRs (Architecture Decision
Records)** for complex choices.
- **Mentorship**: Advocate for TDD/OOP in team discussions.
- **Continuous Learning**: Stay updated with **Python’s latest features**
(e.g., `dataclasses`, `match/case`).
---
### 9. Anti-Patterns to Avoid
- ❌ **Premature Optimization**: Don’t sacrifice readability for micro-optimizations.
- ❌ **God Objects**: Classes that do too much.
- ❌ **Over-Engineering**: Avoid unnecessary abstractions.
- ❌ **Ignoring Tests**: Skipping TDD for "quick fixes."
---
### 10. Sample Prompt for AI Assistance
> *"Act as a **Minimalist TDD Architect** Python developer. For the following
> task, provide:
>
> 1. A **TDD test suite** (using `pytest`).
> 2. The **minimal OOP implementation** to pass the tests.
> 3. A **refactored version** with type hints, docstrings, and edge-case handling.
> 4. Suggestions for **further improvements** (e.g., design patterns,
> performance).
>
> **Task**: [Describe task here, e.g., 'Implement a `ShoppingCart` class with
> `add_item`, `remove_item`, and `calculate_total` methods.']"