🛰️ export from upstream (91f8f89)

This commit is contained in:
2026-11-01 17:40:01 +01:00
commit f4add8ad80
184 changed files with 19140 additions and 0 deletions
@@ -0,0 +1,9 @@
{
"name": "project-uv",
"version": "0.1.0",
"description": "Detects how uv (Astral) is configured in the current Python project and advertises the right invocation patterns for running scripts.",
"author": {
"name": "Gabor Körber",
"email": "gab@g4b.org"
}
}
@@ -0,0 +1,22 @@
{
"name": "project-uv",
"version": "0.1.0",
"description": "Detects how uv is configured in the current Python project and advertises the right invocation patterns.",
"author": {
"name": "Gabor Korber",
"email": "gab@g4b.org"
},
"skills": "./skills/",
"interface": {
"displayName": "project-uv",
"shortDescription": "Probe uv project layout before running Python commands.",
"longDescription": "Context-aware uv project tooling detection for Python repositories. Probes project layout, lockfiles, and script declarations before suggesting uv commands.",
"developerName": "Gabor Korber",
"category": "Coding",
"capabilities": ["Skills"],
"defaultPrompt": [
"Probe this Python project's uv setup.",
"Find the right uv command for this repo."
]
}
}
+18
View File
@@ -0,0 +1,18 @@
# project-uv
Pilot skill for **context-aware project tooling detection**: when a Python project uses [uv](https://docs.astral.sh/uv/), the agent should discover *how* uv is wired up here (sync model, lockfile presence, script declarations, project layout) before running anything, rather than guessing.
## Skills
- **project-uv** — Activates for Python work in repos containing `pyproject.toml`. Tells the agent to probe the project layout via `scripts/probe.py` before suggesting `uv run` / `uv sync` invocations.
## The bigger idea
This plugin is also a **pilot for granular activation via flag files**. The long-term plan: a skill activates not just from its description, but from the presence (or absence) of marker files in the repo — `Justfile`, `pyproject.toml`, `uv.lock`, custom flags like `.reliquary/run-uv-with-just`, etc. Combined skills like `run_uv_with_just` would light up only when both signals are present. See `docs/workpad/research/` in the reliquary repo for the open question on glob negation support.
## Install
```
/plugin marketplace add git@git.g4b.org:dirigence/reliquary.git
/plugin install project-uv@reliquary
```
@@ -0,0 +1,44 @@
---
name: project-uv
description: Probe for python once per conversation, before the first `python`, `pip`, `uv run`, or `.py` invocation. Skip if the correct uv invocation for this repo is already established in the conversation.
globs:
- pyproject.toml
---
# project-uv
Probe once per conversation. Read keys, don't guess.
## Run
POSIX: `sh "$CLAUDE_PLUGIN_ROOT/skills/project-uv/scripts/probe.sh"`
Windows: `& "$env:CLAUDE_PLUGIN_ROOT\skills\project-uv\scripts\probe.ps1"`
Successful execution is the proof python works here. If it fails, stop and report.
## Env-var contract
- `SCRIPTS_UV` — path to the `uv` executable.
- `SCRIPTS_DIR` — project script dir (default `scripts/`).
- `SCRIPTS_STORE` — scratch dir for throwaway scripts (default: platform temp).
Output echoes each as a key — empty value means unset or invalid. Use the `uv=` value if `scripts_uv=` is empty.
## Acting on `mode`
- `managed-project-locked` — `uv run <cmd>`; `uv sync` if `.venv` missing.
- `managed-project-unlocked` — `uv run <cmd>`; `uv sync` to create env.
- `pep723-only` — `uv run path/to/script.py`; edit `# /// script` block for deps.
- `uv-tool-only` — `[tool.uv]` without `[project]`; ask before assuming.
- `agent-tool-only` — uv exists but no python project; use for agent scratchpad in `scripts_store`.
- `none` — no python here; stop.
## Other keys
- `venv_tainted=true` — warn the user; uv isn't fully embraced here.
- `recipes=` — if a `just:`/`make:` recipe covers the task, prefer it.
- `default_packages=` — already importable; no install needed.
## Out of scope
Does not install uv, modify `pyproject.toml`, or pick a Python version.
@@ -0,0 +1,21 @@
$ErrorActionPreference = "Stop"
$probe = Join-Path $PSScriptRoot "probe.py"
if ($env:SCRIPTS_UV -and (Test-Path $env:SCRIPTS_UV)) {
& $env:SCRIPTS_UV run --no-project python $probe
exit $LASTEXITCODE
}
$uv = Get-Command uv -ErrorAction SilentlyContinue
if ($uv) {
& $uv.Source run --no-project python $probe
exit $LASTEXITCODE
}
foreach ($name in @("python", "python3", "py")) {
$cmd = Get-Command $name -ErrorAction SilentlyContinue
if ($cmd) {
& $cmd.Source $probe
exit $LASTEXITCODE
}
}
Write-Error "probe: no python found"
exit 1
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""project-uv probe: detect uv wiring and prove python works here.
Stdlib only, targets Python 3.7+. No TOML parser — pyproject.toml is
line-grepped for the handful of facts we need, so this probe runs on any
Python the launcher can reach. Successful execution is itself the proof
that python works in this project.
Output: KEY=VALUE lines on stdout. One key per line. Read keys, not prose.
"""
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
def emit(key, value):
if isinstance(value, bool):
value = "true" if value else "false"
elif isinstance(value, (list, tuple)):
value = ",".join(str(v) for v in value) if value else ""
elif value is None:
value = ""
value = str(value).replace("\n", " ").replace("\r", " ")
print("{}={}".format(key, value))
def detect_platform():
if sys.platform.startswith("win"):
return "windows"
if sys.platform == "darwin":
return "macos"
if sys.platform.startswith("linux"):
return "linux"
return sys.platform
def detect_uv(preferred):
candidates = []
if preferred:
candidates.append(preferred)
found = shutil.which("uv")
if found and found not in candidates:
candidates.append(found)
for c in candidates:
try:
out = subprocess.run(
[c, "--version"], capture_output=True, text=True, timeout=5
)
if out.returncode == 0:
return c, (out.stdout or out.stderr).strip()
except (OSError, subprocess.SubprocessError):
continue
return None, None
def scan_pyproject(path):
facts = {
"has_project": False,
"has_tool_uv": False,
"scripts": [],
"requires_python": "",
}
if not path.exists():
return facts
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return facts
section = None
for raw in text.splitlines():
line = raw.strip()
if line.startswith("[") and line.endswith("]"):
section = line[1:-1].strip()
if section == "project":
facts["has_project"] = True
elif section == "tool.uv" or section.startswith("tool.uv."):
facts["has_tool_uv"] = True
continue
if not line or line.startswith("#"):
continue
if section == "project" and line.startswith("requires-python"):
m = re.search(r'"([^"]+)"', line)
if m:
facts["requires_python"] = m.group(1)
elif section == "project.scripts":
m = re.match(r"([A-Za-z0-9_.\-]+)\s*=", line)
if m:
facts["scripts"].append(m.group(1))
return facts
def detect_pep723(root):
hits = []
for py in root.glob("*.py"):
try:
head = py.read_text(encoding="utf-8", errors="replace")[:2000]
except OSError:
continue
if "# /// script" in head:
hits.append(py.name)
return hits
def detect_venv_taint(venv):
if not venv.is_dir():
return False, []
reasons = []
if not (venv / "pyvenv.cfg").exists():
reasons.append("no-pyvenv.cfg")
expected = {
"pyvenv.cfg",
"bin",
"Scripts",
"Lib",
"lib",
"Lib64",
"lib64",
"Include",
"include",
"share",
".gitignore",
".lock",
"uv",
}
try:
extras = sorted(p.name for p in venv.iterdir() if p.name not in expected)
except OSError:
extras = []
if extras:
reasons.append("extra:" + "|".join(extras[:5]))
libdir = venv / "lib"
if libdir.is_dir():
try:
py_dirs = [p.name for p in libdir.iterdir() if p.name.startswith("py")]
except OSError:
py_dirs = []
if len(py_dirs) > 1:
reasons.append("multi-python:" + "|".join(py_dirs))
return bool(reasons), reasons
def detect_default_packages(venv):
if not venv.is_dir():
return []
targets = {
"requests",
"httpx",
"python-dotenv",
"pydantic",
"pytest",
"pyyaml",
"tomli",
"mcp",
}
site_dirs = []
libdir = venv / "lib"
if libdir.is_dir():
try:
for child in libdir.iterdir():
sp = child / "site-packages"
if sp.is_dir():
site_dirs.append(sp)
except OSError:
pass
win_sp = venv / "Lib" / "site-packages"
if win_sp.is_dir():
site_dirs.append(win_sp)
found = set()
for sp in site_dirs:
try:
for entry in sp.iterdir():
if not entry.name.endswith(".dist-info"):
continue
stem = entry.name[: -len(".dist-info")]
pkg = stem.rsplit("-", 1)[0].lower().replace("_", "-")
if pkg in targets:
found.add(pkg)
except OSError:
continue
if sys.version_info >= (3, 11):
found.add("tomllib(stdlib)")
return sorted(found)
def detect_recipes(root):
hits = []
for name in ("Justfile", "justfile", ".justfile"):
p = root / name
if p.exists():
try:
for line in p.read_text(
encoding="utf-8", errors="replace"
).splitlines():
m = re.match(r"^([a-zA-Z0-9_\-]+)\s*:", line)
if m:
hits.append("just:" + m.group(1))
except OSError:
pass
break
mk = root / "Makefile"
if mk.exists():
try:
for line in mk.read_text(encoding="utf-8", errors="replace").splitlines():
m = re.match(r"^([a-zA-Z0-9_\-]+)\s*:", line)
if m and m.group(1) not in ("PHONY",):
hits.append("make:" + m.group(1))
except OSError:
pass
return hits
def main():
root = Path(os.environ.get("PROJECT_ROOT", ".")).resolve()
emit("platform", detect_platform())
emit("root", root)
scripts_uv = os.environ.get("SCRIPTS_UV", "").strip()
scripts_dir = os.environ.get("SCRIPTS_DIR", "scripts/").strip()
scripts_store = os.environ.get("SCRIPTS_STORE", tempfile.gettempdir()).strip()
scripts_uv_valid = (
bool(scripts_uv)
and Path(scripts_uv).exists()
and os.access(scripts_uv, os.X_OK)
)
scripts_dir_valid = (root / scripts_dir).is_dir()
scripts_store_valid = Path(scripts_store).is_dir() and os.access(
scripts_store, os.W_OK
)
emit("scripts_uv", scripts_uv if scripts_uv_valid else "")
emit("scripts_dir", scripts_dir if scripts_dir_valid else "")
emit("scripts_store", scripts_store if scripts_store_valid else "")
uv_path, _ = detect_uv(scripts_uv if scripts_uv_valid else None)
emit("uv", uv_path or "")
pp = root / "pyproject.toml"
facts = scan_pyproject(pp)
emit("pyproject_scripts", facts["scripts"])
emit("uv_lock", (root / "uv.lock").exists())
emit("uv_toml", (root / "uv.toml").exists())
emit("requirements", sorted(p.name for p in root.glob("requirements*.txt")))
venv = root / ".venv"
emit("venv", venv.exists())
tainted, reasons = detect_venv_taint(venv)
emit("venv_tainted", tainted)
emit("venv_taint", reasons)
pep723 = detect_pep723(root)
emit("pep723", pep723)
src = root / "src"
if src.is_dir():
pkgs = sorted(
p.name for p in src.iterdir() if p.is_dir() and (p / "__init__.py").exists()
)
else:
pkgs = sorted(
p.name
for p in root.iterdir()
if p.is_dir()
and (p / "__init__.py").exists()
and not p.name.startswith(".")
)
emit("packages", pkgs)
emit(
"justfile",
any((root / n).exists() for n in ("Justfile", "justfile", ".justfile")),
)
emit("makefile", (root / "Makefile").exists())
emit("mise", any((root / n).exists() for n in ("mise.toml", ".mise.toml")))
emit("recipes", detect_recipes(root))
emit("default_packages", detect_default_packages(venv))
if facts["has_project"] and (root / "uv.lock").exists():
mode = "managed-project-locked"
elif facts["has_project"]:
mode = "managed-project-unlocked"
elif pep723:
mode = "pep723-only"
elif facts["has_tool_uv"]:
mode = "uv-tool-only"
elif uv_path:
mode = "agent-tool-only"
else:
mode = "none"
emit("mode", mode)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,18 @@
#!/usr/bin/env sh
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROBE="$SCRIPT_DIR/probe.py"
if [ -n "$SCRIPTS_UV" ] && [ -x "$SCRIPTS_UV" ]; then
exec "$SCRIPTS_UV" run --no-project python "$PROBE"
fi
if command -v uv >/dev/null 2>&1; then
exec uv run --no-project python "$PROBE"
fi
for name in python3 python; do
if command -v "$name" >/dev/null 2>&1; then
exec "$name" "$PROBE"
fi
done
echo "probe: no python found" >&2
exit 1