feat(skills): add checkhealth
a75fa7145c479cf3684e6a92b709d3f511dbaea3
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 81b0a7582a5b
bugabingas pi extensions
a75fa7145c479cf3684e6a92b709d3f511dbaea3
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+343 / −0 text lines
+1 / −0 text lines
new file mode 100644+135 / −0 text lines
#!/usr/bin/env python3"""Validate Agent Skill frontmatter."""from __future__ import annotationsimport reimport shutilimport subprocessimport tempfilefrom pathlib import Pathfrom typing import AnyROOT = Path(__file__).resolve().parents[1]SKILLS = ROOT / "skills"NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")def skill_files() -> list[Path]: return sorted(SKILLS.glob("*/SKILL.md"))def frontmatter(path: Path) -> str: lines = path.read_text(encoding="utf-8").splitlines() if not lines or lines[0] != "---": raise ValueError("missing opening frontmatter fence") for index, line in enumerate(lines[1:], start=2): if line == "---": return "\n".join(lines[1 : index - 1]) + "\n" raise ValueError("missing closing frontmatter fence")def parse_yaml_with_pyyaml(text: str) -> dict[str, Any] | None: try: import yaml # type: ignore[import-untyped] except ModuleNotFoundError: return None data = yaml.safe_load(text) if not isinstance(data, dict): raise ValueError("frontmatter is not a mapping") return datadef lint_yaml_with_yamlfmt(text: str) -> None: yamlfmt = shutil.which("yamlfmt") if not yamlfmt: raise ValueError("install PyYAML or run under mise so yamlfmt is available") with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "frontmatter.yaml" path.write_text(text, encoding="utf-8") result = subprocess.run( [yamlfmt, "-lint", str(path)], capture_output=True, check=False, text=True, ) if result.returncode: raise ValueError((result.stderr or result.stdout).strip())def parse_shallow_yaml(text: str) -> dict[str, str]: data: dict[str, str] = {} lines = text.splitlines() index = 0 while index < len(lines): line = lines[index] index += 1 if not line or line.startswith(" "): continue match = re.match(r"^([A-Za-z0-9_-]+):(?:\s*(.*))?$", line) if not match: continue key, value = match.groups() value = value or "" if value in {">", "|-", "|"}: block: list[str] = [] while index < len(lines) and (not lines[index] or lines[index].startswith(" ")): block.append(lines[index].strip()) index += 1 value = "\n".join(block).strip() if (value.startswith('"') and value.endswith('"')) or ( value.startswith("'") and value.endswith("'") ): value = value[1:-1] data[key] = value return datadef parse_frontmatter(text: str) -> dict[str, Any]: data = parse_yaml_with_pyyaml(text) if data is not None: return data lint_yaml_with_yamlfmt(text) return parse_shallow_yaml(text)def validate(path: Path) -> list[str]: errors: list[str] = [] try: data = parse_frontmatter(frontmatter(path)) except Exception as error: # noqa: BLE001 return [str(error)] name = data.get("name") description = data.get("description") if not isinstance(name, str) or not name: errors.append("missing string field: name") elif not NAME_RE.fullmatch(name): errors.append(f"invalid skill name: {name!r}") elif path.parent.name != name: errors.append(f"directory/name mismatch: {path.parent.name!r} != {name!r}") if not isinstance(description, str) or not description.strip(): errors.append("missing string field: description") elif len(description) > 1024: errors.append(f"description too long: {len(description)} > 1024") return errorsdef main() -> int: failed = False for path in skill_files(): errors = validate(path) if not errors: continue failed = True rel = path.relative_to(ROOT) for error in errors: print(f"{rel}: {error}") return int(failed)if __name__ == "__main__": raise SystemExit(main())new file mode 100644+88 / −0 text lines
---name: checkhealthdescription: "Analyze current software project state: lifecycle stage, completion vs TODO, language/runtime versions, code style, deps, tooling, tests, build health, and what is going on in a repo/directory. Use when asked for project health, status, orientation, audit, inventory, roadmap, or 'what the hell is going on'."---# CheckhealthAnalyze project state.Report facts first.No fixes unless asked.For command recipes, read `references/toolbox.md`.## Workflow1. Map repo shape - `ls`, `find` top-level files/dirs. - Detect app/library/CLI/docs/config/monorepo. - Note entrypoints, package/workspace files, lockfiles.2. Identify stack - Languages + versions from manifests, tool files, lockfiles, CI. - Main deps/frameworks, build/test/lint tools. - Style conventions from config + actual files.3. Measure lifecycle - README claims vs implementation. - Tests present/runnable? CI present? release/build artifacts? - Git state if available: branch, dirty files, recent commits/tags. - TODO/FIXME/HACK/XXX and issue-like docs.4. Check health cheaply - Prefer static inspection first. - Run lightweight commands only when safe/obvious: `git status`, manifest scripts, version commands, `test`/`lint` dry equivalents. - Do not install deps, migrate DBs, start servers, mutate files, or run destructive commands.5. Summarize - Lifecycle: idea/prototype/MVP/active-dev/maintenance/production/abandoned. - Done vs TODO: coarse percentage + evidence. - Risks/blockers. - Next 3-7 concrete actions.## OutputUse this shape:```text## CheckhealthState: <one line>Lifecycle: <stage> (<confidence>)Done: <rough %>TODO: <rough %>Stack• Language/runtime: ...• Frameworks/deps: ...• Tooling: ...• Style: ...Repo map• ...Evidence• ...Health• Build/test/lint: ...• Git: ...• Docs: ...• Risks: ...Next1. ...2. ...3. ...```Keep it blunt.Distinguish observed fact from inference.new file mode 100644+119 / −0 text lines
# Checkhealth ToolboxUse cheap, read-mostly commands.Respect repo ignores.No installs.No servers.## System snapshot```bashmacchina --show host,kernel,distribution,shell,terminal,processor,memory,disk-space \ --long-kernel --memory-percentage --disk-space-percentage --disks /```Use only when host/runtime context matters.`macchina --show` values are lowercase.`macchina --doctor` diagnoses machine readouts, not project health.## File map```bashfd -d 3 -t f '^(package.json|mise.toml|pyproject.toml|README.md|SKILL.md)$' .fd -t f -e json -e toml -e yaml -e yml -e lock -e ts -e py .rg --files -g '!*.lock' -g '!node_modules/**'````fd` and `rg` respect ignore files by default.Add `--hidden` deliberately.Avoid `--no-ignore` unless looking for generated/ignored project state.## Content search```bashrg -n 'TODO|FIXME|HACK|XXX|DEPRECATED|legacy|compat' .rg -n 'scripts|dependencies|devDependencies|engines' package.json extensions/*/package.jsonrg -n 'test|lint|build|fmt|format|ci' mise.toml package.json pyproject.toml .github```Use `rg -S` for smart case.Use globs to exclude noise:```bashrg -n --hidden --glob '!.git/**' --glob '!.jj/**' --glob '!node_modules/**' PATTERN .```## File preview```bashbat --style=plain --color=never --paging=never --line-range 1:80 README.mdbat --style=plain --color=never --paging=never --diff```Use `bat` for human previews.Use `read` for exact agent file inspection.## Language / size profile```bashtokei . --exclude .git --exclude .jj --exclude node_modulestokei . --exclude .git --exclude .jj --exclude node_modules --output json > /tmp/tokei.jsonnu -c 'open /tmp/tokei.json | transpose lang data | where lang != Total | insert code {|r| $r.data.code } | insert files {|r| $r.data.reports | length } | sort-by code --reverse | first 12 | select lang files code'````tokei` is good for stack/scale, not completion %.Markdown code counts may be unhelpful; inspect docs separately.## Nushell structured probesLearn local syntax first:```bashnu -c 'help commands | where name in [ls where open from sort-by transpose insert first select]'nu -c 'help from json'nu -c 'help sort-by'```Useful probes:```bashnu -c '^git ls-files | lines | each {|p| $p | path parse | get extension } | where $it != "" | reduce -f {} {|ext acc| $acc | upsert $ext (($acc | get --optional $ext | default 0) + 1)} | transpose ext files | sort-by files --reverse | first 15'nu -c '^git ls-files | lines | each {|p| $p | path split | first } | where $it != "" | reduce -f {} {|dir acc| $acc | upsert $dir (($acc | get --optional $dir | default 0) + 1)} | transpose dir files | sort-by files --reverse'```Put external producers inside `nu -c` (`^git ls-files`).Do not rely on piping Bash stdin into `nu -c`; `$in` may be `nothing`.## Git / Jujutsu```bashgit status --short --branchgit status --porcelain=v1 -bgit log --oneline --decorate -5git tag --sort=-creatordate | head```For jj repos:```bashjj status --ignore-working-copyjj log -n 5 --no-graph --template 'change_id.short() ++ " " ++ commit_id.short() ++ " " ++ description.first_line() ++ "\n"'jj diff --summary```Edge case:`jj status` snapshots the working copy by default.Use `--ignore-working-copy` for non-mutating checks, but call out that it can bestale.## Man pages```bashMANWIDTH=100 MANPAGER=cat man rg | col -b | rg -n 'gitignore|--files|--glob'MANWIDTH=100 MANPAGER=cat man git-status | col -b | head -80```Use `man` for installed version truth.Some tools ship no man page (`tokei` here).