repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/scripts/extensions.py
RawFile outline
- pkg_name line 57
- read_pkg line 64
- ext_dirs line 68
- ts_files line 87
- import_specs line 91
- err line 101
- static_check line 105
- external_deps line 182
- build line 189
- run_harness line 197
- cmd_list line 208
- git line 214
- git_dirty line 225
- git_changes line 231
- latest_release_tag line 241
- strip_terminal_noise line 247
- changelog_prompt line 251
- generate_changelog_entry line 279
- update_changelog line 295
- load_driver line 320
- drivers_for line 329
- update_demos line 342
- tag_name line 355
- create_tags line 360
- commit_release line 374
- push_release line 385
- check_static line 392
- check_build line 404
- cmd_test line 426
- cmd_check line 446
- cmd_changelog line 457
- cmd_publish line 468
- main line 497
#!/usr/bin/env python3
"""Pi extension workspace checks."""
from __future__ import annotations
import argparse
import importlib.util
import json
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from types import ModuleType
ROOT = Path(__file__).resolve().parents[1]
EXT_ROOT = ROOT / "agent" / "extensions"
DRIVER_ROOT = ROOT / "drivers"
PI_PEERS = {
"@earendil-works/pi-ai",
"@earendil-works/pi-agent-core",
"@earendil-works/pi-coding-agent",
"@earendil-works/pi-tui",
"typebox",
}
HARNESS = "@marcfargas/pi-test-harness"
IMPORT_RE = re.compile(r"(?:import|export)\s+(?:[^'\"]+?\s+from\s+)?['\"]([^'\"]+)['\"]|import\(['\"]([^'\"]+)['\"]\)")
SECRET_RE = re.compile(r"(api[_-]?key|secret|token|password)\s*[:=]\s*['\"][^'\"]{12,}", re.I)
RELEASE_IGNORED_SUBJECTS = ("update extension release changelogs",)
OSC_RE = re.compile(r"\x1b\][^\x07]*(?:\x07|\x1b\\)")
ANSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
CHANGELOG_STYLE = """Voice:
- terse, technical, human
- brutal minimalism: no marketing, no excitement, no filler
- concrete nouns/verbs; name actual commands, tools, hooks, files, API
- no corporate adjectives: enhanced, improved, streamlined, robust, seamless, powerful, comprehensive, leverage
- no vague "various fixes"
- write like a maintainer note, not an ad
- short fragments beat full sentences
Hard format:
## {version}
- bullet
- bullet
Hard limits:
- 3-5 bullets total
- max 100 chars per bullet; rewrite until every bullet fits
- each bullet must start with a verb, command name, or concrete noun
- combine details; do not enumerate implementation internals separately
- omit internal function names unless they are the change users maintain
"""
def pkg_name(spec: str) -> str:
if spec.startswith("@"):
parts = spec.split("/")
return "/".join(parts[:2])
return spec.split("/")[0]
def read_pkg(ext: Path) -> dict:
return json.loads((ext / "package.json").read_text())
def ext_dirs(selected: list[str]) -> list[Path]:
dirs = sorted(p.parent for p in EXT_ROOT.glob("*/package.json"))
if not selected:
return dirs
wanted = set(selected)
result = []
for ext in dirs:
pkg = read_pkg(ext)
if ext.name in wanted or pkg.get("name") in wanted:
result.append(ext)
found = {ext.name for ext in result} | {read_pkg(ext).get("name") for ext in result}
missing = wanted - found
if missing:
raise SystemExit(f"unknown extension(s): {', '.join(sorted(missing))}")
return result
def ts_files(ext: Path) -> list[Path]:
return sorted(p for p in ext.rglob("*.ts") if "node_modules" not in p.parts)
def import_specs(ext: Path) -> set[str]:
specs: set[str] = set()
for file in ts_files(ext):
for match in IMPORT_RE.finditer(file.read_text(errors="ignore")):
spec = match.group(1) or match.group(2)
if spec:
specs.add(spec)
return specs
def err(errors: list[str], ext: Path, msg: str) -> None:
errors.append(f"{ext.name}: {msg}")
def static_check(ext: Path) -> list[str]:
errors: list[str] = []
try:
pkg = read_pkg(ext)
except Exception as e:
return [f"{ext.name}: invalid package.json: {e}"]
expected = f"@bugabinga/pi-ext-{ext.name}"
if pkg.get("name") != expected:
err(errors, ext, f"package name must be {expected!r}")
if pkg.get("type") != "module":
err(errors, ext, "package.json type must be 'module'")
if pkg.get("main") != "index.ts":
err(errors, ext, "package.json main must be 'index.ts'")
if not (ext / "index.ts").exists():
err(errors, ext, "missing index.ts")
if pkg.get("license") != "MIT":
err(errors, ext, "package license must be MIT")
if not (ext / "README.md").exists():
err(errors, ext, "missing README.md")
deps = pkg.get("dependencies", {}) or {}
peers = pkg.get("peerDependencies", {}) or {}
dev = pkg.get("devDependencies", {}) or {}
scripts = pkg.get("scripts", {}) or {}
if dev.get(HARNESS) is None:
err(errors, ext, f"missing devDependency {HARNESS}")
if scripts.get("test:harness") != "bun test ./__tests__/harness.test.ts":
err(errors, ext, "missing script test:harness='bun test ./__tests__/harness.test.ts'")
if not (ext / "__tests__" / "harness.test.ts").exists():
err(errors, ext, "missing __tests__/harness.test.ts")
for dep in deps:
if dep in PI_PEERS:
err(errors, ext, f"Pi package {dep} belongs in peerDependencies, not dependencies")
if dep.startswith("@bugabinga/pi-ext-"):
err(errors, ext, f"must not depend on sibling extension {dep}")
for dep in peers:
if dep.startswith("@bugabinga/pi-ext-"):
err(errors, ext, f"must not peer-depend on sibling extension {dep}")
specs = import_specs(ext)
packages = {
pkg_name(s)
for s in specs
if not (s.startswith(".") or s.startswith("/") or s.startswith("node:") or s.startswith("bun:"))
}
for spec in specs:
if spec.startswith("@bugabinga/pi-ext-"):
err(errors, ext, f"must not import sibling extension {spec}")
for file in ts_files(ext):
text = file.read_text(errors="ignore")
for match in IMPORT_RE.finditer(text):
spec = match.group(1) or match.group(2)
if not spec or not spec.startswith("../"):
continue
resolved = (file.parent / spec).resolve()
try:
resolved.relative_to(ext.resolve())
except ValueError:
err(errors, ext, f"cross-extension relative import {spec} in {file.relative_to(ext)}")
if SECRET_RE.search(text):
err(errors, ext, f"possible secret in {file.relative_to(ext)}")
for dep in sorted(packages & PI_PEERS):
if dep not in peers:
err(errors, ext, f"imported {dep} but missing peerDependency")
for dep in sorted(packages - PI_PEERS):
if dep not in deps and dep not in peers and dep not in dev:
err(errors, ext, f"imported external package {dep} but package.json does not declare it")
return errors
def external_deps(pkg: dict) -> list[str]:
deps = set()
for key in ("dependencies", "peerDependencies", "devDependencies"):
deps.update((pkg.get(key) or {}).keys())
return sorted(deps)
def build(ext: Path, out_root: Path) -> None:
pkg = read_pkg(ext)
cmd = ["bun", "build", "index.ts", "--target", "bun", "--outdir", str(out_root / ext.name)]
for dep in external_deps(pkg):
cmd.extend(["--external", dep])
subprocess.run(cmd, cwd=ext, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def run_harness(ext: Path) -> None:
subprocess.run(
["bun", "test", "./__tests__/harness.test.ts"],
cwd=ext,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
def cmd_list(selected: list[str]) -> int:
for ext in ext_dirs(selected):
print(f"{ext.name}\t{read_pkg(ext).get('name')}")
return 0
def git(*args: str, check: bool = True, capture: bool = False) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", *args],
cwd=ROOT,
check=check,
text=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None,
)
def git_dirty(paths: list[Path]) -> bool:
rels = [str(p.relative_to(ROOT)) for p in paths]
proc = git("status", "--porcelain", "--", *rels, check=True, capture=True)
return bool(proc.stdout.strip())
def git_changes(ext: Path, since: str | None) -> list[str]:
cmd = ["log", "--format=%h %s"]
if since:
cmd.append(f"{since}..HEAD")
cmd.extend(["--", str(ext.relative_to(ROOT))])
proc = git(*cmd, capture=True)
lines = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
return [line for line in lines if not any(line.endswith(subject) for subject in RELEASE_IGNORED_SUBJECTS)]
def latest_release_tag(pkg_name: str) -> str | None:
proc = git("tag", "--list", f"{pkg_name}@*", "--sort=-creatordate", capture=True)
tags = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
return tags[0] if tags else None
def strip_terminal_noise(text: str) -> str:
return ANSI_RE.sub("", OSC_RE.sub("", text)).strip()
def changelog_prompt(ext: Path) -> str:
pkg = read_pkg(ext)
version = pkg.get("version", "0.0.0")
tag = latest_release_tag(pkg["name"])
commits = git_changes(ext, tag)
commit_text = "\n".join(f"- {line}" for line in commits) or "- no commits since previous tag"
rel = ext.relative_to(ROOT)
return f"""You are writing one changelog section for one Pi extension.
Output markdown only. No preamble. No code fence.
{CHANGELOG_STYLE.format(version=version)}
Task:
Extension: {ext.name}
Package: {pkg["name"]}
Path: {rel}
Version: {version}
Previous tag: {tag or "none"}
Inspect source/readme/tests/changelog under the path. Do not edit files.
Use tools if useful. You are in an ephemeral Pi session with normal tools/extensions loaded.
Git commits touching this extension:
{commit_text}
"""
def generate_changelog_entry(ext: Path, model: str | None = None) -> str:
cmd = ["pi", "--no-session", "-p"]
if model:
cmd.extend(["--model", model])
cmd.append(changelog_prompt(ext))
proc = subprocess.run(cmd, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if proc.returncode != 0:
if proc.stderr:
print(proc.stderr, file=sys.stderr)
raise subprocess.CalledProcessError(proc.returncode, proc.args, proc.stdout, proc.stderr)
out = strip_terminal_noise(proc.stdout)
if not out.startswith("## "):
raise RuntimeError(f"bad changelog output for {ext.name}: {out[:200]!r}")
return out.rstrip() + "\n"
def update_changelog(ext: Path, model: str | None = None) -> str:
pkg = read_pkg(ext)
path = ext / "CHANGELOG.md"
entry = generate_changelog_entry(ext, model)
heading = f"## {pkg.get('version', '0.0.0')}"
if not path.exists():
path.write_text(f"# Changelog\n\n{entry}")
print(f"OK changelog {ext.name}")
return entry
text = path.read_text()
if heading in text:
lines = text.splitlines(keepends=True)
start = next(i for i, line in enumerate(lines) if line.startswith(heading))
end = next((i for i in range(start + 1, len(lines)) if lines[i].startswith("## ")), len(lines))
path.write_text("".join(lines[:start]) + entry + "\n" + "".join(lines[end:]).lstrip("\n"))
elif text.startswith("# Changelog"):
_, rest = text.split("\n", 1)
path.write_text("# Changelog\n\n" + entry + "\n" + rest.lstrip("\n"))
else:
path.write_text(f"# Changelog\n\n{entry}\n{text}")
print(f"OK changelog {ext.name}")
return entry
def load_driver(path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location(f"driver_{path.stem}", path)
if spec is None or spec.loader is None:
raise SystemExit(f"cannot load driver: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def drivers_for(exts: list[Path]) -> list[tuple[str, list[str]]]:
selected = {ext.name for ext in exts}
drivers: list[tuple[str, list[str]]] = []
for path in sorted(DRIVER_ROOT.glob("*.py")):
if path.name.startswith("__"):
continue
module = load_driver(path)
targets = getattr(module, "targets", [])
if isinstance(targets, list) and selected.intersection(targets):
drivers.append((path.stem, [t for t in targets if isinstance(t, str)]))
return drivers
def update_demos(exts: list[Path]) -> list[Path]:
drivers = drivers_for(exts)
if not drivers:
print("OK demo none")
return []
touched: set[Path] = set()
for driver, targets in drivers:
subprocess.run(["python3", "scripts/demo.py", driver], cwd=ROOT, check=True)
touched.update(EXT_ROOT / target for target in targets)
print(f"OK demo {driver}")
return sorted(path for path in touched if path.exists())
def tag_name(ext: Path) -> str:
pkg = read_pkg(ext)
return f"{pkg['name']}@{pkg.get('version', '0.0.0')}"
def create_tags(exts: list[Path]) -> list[str]:
tags: list[str] = []
for ext in exts:
tag = tag_name(ext)
exists = git("rev-parse", "--verify", "--quiet", f"refs/tags/{tag}", check=False).returncode == 0
if exists:
print(f"OK tag {tag} exists")
else:
git("tag", tag)
print(f"OK tag {tag}")
tags.append(tag)
return tags
def commit_release(selected: list[Path], paths_to_add: list[Path]) -> None:
paths = sorted({str(path.relative_to(ROOT)) for path in paths_to_add})
git("add", *paths)
if git("diff", "--cached", "--quiet", "--", *paths, check=False).returncode == 0:
print("OK commit none")
return
names = ", ".join(ext.name for ext in selected)
git("commit", "-m", f"release(pi-ext): {names}", "--", *paths)
print(f"OK commit {names}")
def push_release(tags: list[str]) -> None:
git("push")
if tags:
git("push", "origin", *tags)
print("OK push")
def check_static(dirs: list[Path]) -> int:
errors: list[str] = []
for ext in dirs:
errors.extend(static_check(ext))
if errors:
for e in errors:
print(f"ERROR {e}", file=sys.stderr)
return 1
print(f"OK static {len(dirs)} extension package(s)")
return 0
def check_build(dirs: list[Path]) -> int:
if not shutil.which("bun"):
print("ERROR bun not found", file=sys.stderr)
return 1
with tempfile.TemporaryDirectory(prefix="pi-ext-build-") as tmp:
out_root = Path(tmp)
for ext in dirs:
try:
build(ext, out_root)
print(f"OK build {ext.name}")
except subprocess.CalledProcessError as e:
print(f"ERROR build {ext.name}", file=sys.stderr)
if e.stdout:
print(e.stdout, file=sys.stderr)
if e.stderr:
print(e.stderr, file=sys.stderr)
return e.returncode or 1
print(f"OK build {len(dirs)} extension package(s)")
return 0
def cmd_test(selected: list[str]) -> int:
dirs = ext_dirs(selected)
if not shutil.which("bun"):
print("ERROR bun not found", file=sys.stderr)
return 1
for ext in dirs:
try:
run_harness(ext)
print(f"OK harness {ext.name}")
except subprocess.CalledProcessError as e:
print(f"ERROR harness {ext.name}", file=sys.stderr)
if e.stdout:
print(e.stdout, file=sys.stderr)
if e.stderr:
print(e.stderr, file=sys.stderr)
return e.returncode or 1
print(f"OK harness {len(dirs)} extension package(s)")
return 0
def cmd_check(selected: list[str]) -> int:
dirs = ext_dirs(selected)
static = check_static(dirs)
if static != 0:
return static
built = check_build(dirs)
if built != 0:
return built
return cmd_test(selected)
def cmd_changelog(selected: list[str], model: str | None, write: bool) -> int:
dirs = ext_dirs(selected)
for ext in dirs:
if write:
entry = update_changelog(ext, model)
else:
entry = generate_changelog_entry(ext, model)
print(entry.rstrip())
return 0
def cmd_publish(selected: list[str], *, dry_run: bool, model: str | None, skip_demo: bool) -> int:
if not selected:
print("ERROR publish requires at least one extension", file=sys.stderr)
return 1
dirs = ext_dirs(selected)
checked = cmd_check(selected)
if checked != 0:
return checked
if dry_run:
demos = drivers_for(dirs)
print("DRY RUN publish")
print("demos: " + (", ".join(name for name, _targets in demos) if demos else "none"))
for ext in dirs:
print(generate_changelog_entry(ext, model).rstrip())
print("skip commit/tag/push")
return 0
demo_paths = [] if skip_demo else update_demos(dirs)
for ext in dirs:
update_changelog(ext, model)
commit_release(dirs, dirs + demo_paths)
tags = create_tags(dirs)
push_release(tags)
return 0
def main() -> int:
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest="command", required=True)
list_p = sub.add_parser("list")
list_p.add_argument("extensions", nargs="*")
check_p = sub.add_parser("check")
check_p.add_argument("extensions", nargs="*")
test_p = sub.add_parser("test")
test_p.add_argument("extensions", nargs="*")
changelog_p = sub.add_parser("changelog")
changelog_p.add_argument("extensions", nargs="+")
changelog_p.add_argument("--model")
changelog_p.add_argument("--write", action="store_true")
publish_p = sub.add_parser("publish")
publish_p.add_argument("extensions", nargs="+")
publish_p.add_argument("--dry-run", action="store_true")
publish_p.add_argument("--model")
publish_p.add_argument("--skip-demo", action="store_true")
args = parser.parse_args()
if args.command == "list":
return cmd_list(args.extensions)
if args.command == "check":
return cmd_check(args.extensions)
if args.command == "test":
return cmd_test(args.extensions)
if args.command == "changelog":
return cmd_changelog(args.extensions, args.model, args.write)
if args.command == "publish":
return cmd_publish(args.extensions, dry_run=args.dry_run, model=args.model, skip_demo=args.skip_demo)
raise AssertionError(args.command)
if __name__ == "__main__":
raise SystemExit(main())