From cd5c3102dd85e565e2230f5ab8fc4546222e06ba Mon Sep 17 00:00:00 2001 From: Justin Carlson <40642470+justcarlson@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:37:43 -0500 Subject: [PATCH] feat(skills): add prove and jstack-setup with install-time rig rendering --- README.md | 12 + rig.example.json | 23 + scripts/check_privacy.py | 5 + scripts/install.py | 309 +++++++++- scripts/validate_skills.py | 29 + skills/jstack-setup/SKILL.md | 33 ++ skills/jstack-setup/scripts/jstack-rig.py | 440 ++++++++++++++ skills/prove/SKILL.md | 76 +++ skills/prove/references/surfaces.md | 82 +++ skills/prove/scripts/proof-pack.py | 615 ++++++++++++++++++++ tests/test_install.py | 4 +- tests/test_prove_and_rig.py | 666 ++++++++++++++++++++++ tests/test_validate_skills.py | 4 +- 13 files changed, 2277 insertions(+), 21 deletions(-) create mode 100644 rig.example.json create mode 100644 skills/jstack-setup/SKILL.md create mode 100755 skills/jstack-setup/scripts/jstack-rig.py create mode 100644 skills/prove/SKILL.md create mode 100644 skills/prove/references/surfaces.md create mode 100755 skills/prove/scripts/proof-pack.py create mode 100644 tests/test_prove_and_rig.py diff --git a/README.md b/README.md index 723afe9..eb2dc59 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,8 @@ The nine tstack skills, patched. [UPSTREAM.md](UPSTREAM.md) pins the upstream co | `epic` | Plan and ship multi-issue or multi-repo work, from options to live proof | | `hindsight` | Find agent mistakes that repeat across sessions and fix each at its source | | `hindsight-setup` | Choose which agent logs `hindsight` reads | +| `prove` | Prove a change works with an L0-L4 evidence ladder and a mechanical proof packet | +| `jstack-setup` | Describe your local tools and fallback model once, and render them into deployed skills | | `ci-retro` | Make CI faster from its own run history | | `bug` | Take an upstream bug from first error to a merged fix | | `omarchy-dev` | Test Omarchy changes in throwaway Omarchy VMs, the way upstream does | @@ -94,6 +96,16 @@ The skills name no models, hosts or private paths. Put those in your own instruc - Put your model roster in `AGENTS.md` or `CLAUDE.md`, for example the three `council` members and the `sol-loop` reviewer. The skills use the models you name there. - Run `hindsight-setup` once. It writes `~/.config/hindsight/sources.json`, which tells `hindsight` which harness logs and stores to read. +- Run `jstack-setup` once. It writes `~/.config/jstack/rig.json` (mode 0600, names only, never committed), and `./install.sh --reconcile` renders it into deployed skills such as `prove`. [rig.example.json](rig.example.json) shows the shape. Without a rig, installs stay stock. + +Paste this into your agent to do it all: + +```text +Install jstack from github.com/justcarlson/jstack with ./install.sh. +Run the jstack-setup skill: inventory my tools, show the table, ask once, write ~/.config/jstack/rig.json. +Run ./install.sh --reconcile, then ./install.sh --check and jstack-rig.py check until both pass. +Then run hindsight-setup. Keep secrets and private hostnames out of any repo. +``` ## Development diff --git a/rig.example.json b/rig.example.json new file mode 100644 index 0000000..64fee9c --- /dev/null +++ b/rig.example.json @@ -0,0 +1,23 @@ +{ + "schema": "jstack.rig/1", + "harnesses": [""], + "endpoints": { + "ollama": "http://127.0.0.1:" + }, + "lanes": { + "web": [""], + "auth": [""], + "native_gui": ["", ""], + "vnc": [""], + "video": ["", ""], + "audio": [""], + "vm": [""], + "ssh": [""], + "secrets": [""] + }, + "media_uploader": "", + "fallback": { + "provider": "", + "model": "" + } +} diff --git a/scripts/check_privacy.py b/scripts/check_privacy.py index f68eaf1..6cf0fbc 100755 --- a/scripts/check_privacy.py +++ b/scripts/check_privacy.py @@ -33,6 +33,7 @@ ("CGNAT address", re.compile(r"(? str | None: @@ -47,6 +48,10 @@ def forbidden_file(path: str) -> str | None: return f"secret file ({prefix})" if name in (".netrc", ".npmrc"): return f"secret file ({name})" + # Personal rig and profile files hold local tool names and endpoints. + # Names like rig.example.json are different names and stay allowed. + if name in PRIVATE_CONFIG_FILES: + return f"private config file ({name})" return None diff --git a/scripts/install.py b/scripts/install.py index c9adcdc..5ebc0bd 100755 --- a/scripts/install.py +++ b/scripts/install.py @@ -4,15 +4,26 @@ Stdlib only. Links (or copies) each skills/ folder into the client's skills folder. It never puts a binary on $PATH, and uninstall removes only entries this checkout owns. + +Rig rendering: when ~/.config/jstack/rig.json (or --rig PATH) exists, every +skill whose SKILL.md holds a `` block is rendered into +~/.local/share/jstack/rendered/skills// (or --render-dir) and installed +from there. The slot grows by at most 1,024 bytes. Without a rig, installs are +the plain links or copies of skills/. """ from __future__ import annotations import argparse import hashlib +import importlib.machinery +import importlib.util import json import os +import re +import shlex import shutil +import subprocess import sys from dataclasses import dataclass from pathlib import Path @@ -20,6 +31,12 @@ REPO = Path(__file__).resolve().parent.parent SKILLS_DIR = REPO / "skills" MARKER = ".jstack-install.json" +RIG_TOOL = REPO / "skills" / "jstack-setup" / "scripts" / "jstack-rig.py" +RIG_SCHEMA = "jstack.rig/1" +OVERLAY_CAP = 1024 +SLOT = re.compile(r"(.*?)", re.DOTALL) +HOOK_MARK = "# jstack:managed-hook" +HOOKS = ("post-merge", "post-checkout") CLIENTS = ("claude", "codex", "antigravity", "opencode") # Never touch these names, even if a stray marker or link claims them. PROTECTED = frozenset({"synced"}) @@ -45,6 +62,7 @@ "t3-launch-worktrees", ), "hindsight-setup": ("hindsight",), + "jstack-setup": ("prove",), } @@ -123,16 +141,26 @@ def targets(home: Path, client: str, env: dict[str, str]) -> list[Target]: return [Target(c, d) for c in chosen for d in client_dirs(home, c, env)] -def tree_digest(src: Path) -> str: - """Deterministic SHA-256 of a skill folder, ignoring install markers, bytecode and Finder noise.""" +def tree_digest(src: Path, follow: bool = False) -> str: + """Deterministic SHA-256 of a skill folder, ignoring install markers, bytecode and Finder noise. + + With follow=True, symlinks are read through, so a rendered folder that links + its static subfolders hashes like a real copy of itself. + """ h = hashlib.sha256() - for path in sorted(src.rglob("*")): + if follow: + paths = sorted( + Path(dirpath) / name for dirpath, _dirs, files in os.walk(src, followlinks=True) for name in files + ) + else: + paths = sorted(src.rglob("*")) + for path in paths: rel = path.relative_to(src) if any(part in ("__pycache__", ".DS_Store", MARKER) for part in rel.parts): continue if path.suffix in (".pyc", ".pyo", ".pyd"): continue - if path.is_symlink(): + if path.is_symlink() and not follow: h.update(b"L" + rel.as_posix().encode("utf-8") + b"\0") h.update(os.readlink(path).encode("utf-8", errors="surrogateescape") + b"\0") continue @@ -142,6 +170,21 @@ def tree_digest(src: Path) -> str: return h.hexdigest() +def is_rendered_dir(path: Path, name: str) -> bool: + """True for a folder this checkout rendered: a real folder with our non-symlink render marker.""" + marker = path / MARKER + if path.is_symlink() or not path.is_dir() or marker.is_symlink() or not marker.is_file(): + return False + try: + data = json.loads(marker.read_text()) + raw_source = data["source"] + if not isinstance(raw_source, str) or not Path(raw_source).is_absolute(): + return False + return bool(data.get("rendered")) and data.get("skill") == name and Path(raw_source).resolve() == REPO.resolve() + except (OSError, ValueError, KeyError, TypeError): + return False + + def owns_link(entry: Path) -> bool: """True only for entries this checkout installed. @@ -156,7 +199,9 @@ def owns_link(entry: Path) -> bool: dest = entry.resolve(strict=False) except (OSError, RuntimeError): return False - return dest.parent == SKILLS_DIR.resolve() and dest.name == entry.name + if dest.name != entry.name: + return False + return dest.parent == SKILLS_DIR.resolve() or is_rendered_dir(dest, entry.name) marker = entry / MARKER if entry.is_dir() and not marker.is_symlink() and marker.is_file(): try: @@ -187,8 +232,9 @@ def is_modified_copy(entry: Path) -> bool: return not recorded or tree_digest(entry) != recorded -def status(entry: Path, name: str, mode: str) -> str: - src = (SKILLS_DIR / name).resolve() +def status(entry: Path, name: str, mode: str, rendered: Path | None = None) -> str: + """State of one installed entry. `rendered` is the folder it must come from, when a rig renders this skill.""" + src = (rendered if rendered is not None else SKILLS_DIR / name).resolve() if not entry.exists() and not entry.is_symlink(): return "missing" if not owns_link(entry): @@ -202,7 +248,7 @@ def status(entry: Path, name: str, mode: str) -> str: data = json.loads((entry / MARKER).read_text()) recorded = data.get("digest") current = tree_digest(entry) - target = tree_digest(src) + target = tree_digest(src, follow=rendered is not None) if not recorded or (current != recorded and current != target): return "modified" if data.get("version") != version() or recorded != target or current != target or data.get("skill") != name: @@ -221,8 +267,8 @@ def remove(entry: Path) -> None: shutil.rmtree(entry) -def place(entry: Path, name: str, mode: str) -> None: - src = SKILLS_DIR / name +def place(entry: Path, name: str, mode: str, rendered: Path | None = None) -> None: + src = rendered if rendered is not None else SKILLS_DIR / name if mode == "symlink": entry.symlink_to(src.resolve(), target_is_directory=True) return @@ -231,11 +277,168 @@ def place(entry: Path, name: str, mode: str) -> None: "source": str(REPO.resolve()), "skill": name, "version": version(), - "digest": tree_digest(src), + "digest": tree_digest(src, follow=rendered is not None), } + if rendered is not None: + recorded = json.loads((rendered / MARKER).read_text()) + for key in ("source_digest", "rig_digest", "rendered_digest"): + marker[key] = recorded.get(key) (entry / MARKER).write_text(json.dumps(marker, indent=2) + "\n") +# Rig rendering ------------------------------------------------------------ + + +def rig_tool(): + """Load the rig validator from jstack-setup without leaving bytecode in the checkout.""" + loader = importlib.machinery.SourceFileLoader("jstack_rig", str(RIG_TOOL)) + spec = importlib.util.spec_from_loader("jstack_rig", loader) + module = importlib.util.module_from_spec(spec) + keep = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + loader.exec_module(module) + finally: + sys.dont_write_bytecode = keep + return module + + +def load_rig(path: Path) -> dict: + """Read and validate a rig file. Exits with a clear message when it is unusable.""" + try: + rig = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise SystemExit(f"rig {path.name}: cannot read as JSON ({exc.__class__.__name__}); fix or remove it") from None + problems = rig_tool().validate(rig) + if problems: + raise SystemExit("rig file is invalid:\n " + "\n ".join(problems)) + return rig + + +def rig_digest(rig: dict) -> str: + return hashlib.sha256(json.dumps(rig, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest() + + +def render_slot_body(slot: str, rig: dict) -> str | None: + """Replacement text for one slot, or None to keep the stock text. Only the `rig` slot is known.""" + if slot != "rig": + return None + lines = [] + fallback = rig.get("fallback") + if isinstance(fallback, dict): + lines.append(f"- Fallback model: `{fallback['provider']}/{fallback['model']}`") + if rig.get("media_uploader"): + lines.append(f"- Media uploader: `{rig['media_uploader']}`") + for lane, tools in sorted((rig.get("lanes") or {}).items()): + if tools: + lines.append(f"- Lane {lane}: " + ", ".join(f"`{t}`" for t in tools)) + if not lines: + return None + return "\nLocal rig, rendered by jstack from the rig file. Edit the rig file, not this skill.\n" + "\n".join(lines) + "\n" + + +def render_text(text: str, rig: dict) -> str: + def swap(match: re.Match[str]) -> str: + body = render_slot_body(match.group(1), rig) + if body is None: + return match.group(0) + return f"{body}" + + return SLOT.sub(swap, text) + + +def has_slot(name: str) -> bool: + skill_md = SKILLS_DIR / name / "SKILL.md" + return skill_md.is_file() and SLOT.search(skill_md.read_text(encoding="utf-8")) is not None + + +def render_state(name: str, rig_dig: str, render_root: Path) -> str | None: + """None when the rendered folder is current; otherwise why it is not.""" + out = render_root / name + if not is_rendered_dir(out, name): + return "not rendered" + try: + marker = json.loads((out / MARKER).read_text()) + except (OSError, ValueError): + return "render marker unreadable" + if marker.get("source_digest") != tree_digest(SKILLS_DIR / name): + return "skill source changed" + if marker.get("rig_digest") != rig_dig: + return "rig changed" + if marker.get("rendered_digest") != tree_digest(out): + return "rendered folder edited" + return None + + +def render_skill(name: str, rig: dict, rig_dig: str, render_root: Path) -> None: + """Write render_root// from the stock skill and the rig. Raises ValueError over the overlay cap.""" + src = SKILLS_DIR / name + stock = (src / "SKILL.md").read_text(encoding="utf-8") + text = render_text(stock, rig) + growth = len(text.encode("utf-8")) - len(stock.encode("utf-8")) + if growth > OVERLAY_CAP: + raise ValueError(f"overlay adds {growth} bytes, over the {OVERLAY_CAP}-byte cap; trim the rig") + out = render_root / name + if (out.exists() or out.is_symlink()) and not is_rendered_dir(out, name): + raise ValueError(f"{out.name} exists in the render folder and was not rendered by jstack") + render_root.mkdir(parents=True, exist_ok=True) + tmp = render_root / f".{name}.tmp" + if tmp.exists() or tmp.is_symlink(): + remove(tmp) + tmp.mkdir() + (tmp / "SKILL.md").write_text(text, encoding="utf-8") + for child in sorted(src.iterdir()): + if child.name in ("SKILL.md", "__pycache__", ".DS_Store", MARKER): + continue + (tmp / child.name).symlink_to(child.resolve(), target_is_directory=child.is_dir()) + marker = { + "source": str(REPO.resolve()), + "skill": name, + "version": version(), + "rendered": True, + "source_digest": tree_digest(src), + "rig_digest": rig_dig, + "rendered_digest": tree_digest(tmp), + } + (tmp / MARKER).write_text(json.dumps(marker, indent=2) + "\n") + if out.exists() or out.is_symlink(): + remove(out) + tmp.rename(out) + + +def hooks_dir(override: Path | None) -> Path: + if override: + return override + proc = subprocess.run( + ["git", "-C", str(REPO), "rev-parse", "--git-path", "hooks"], capture_output=True, text=True, check=False + ) + if proc.returncode != 0 or not proc.stdout.strip(): + raise SystemExit("cannot find this checkout's git hooks folder; pass --hooks-dir") + path = Path(proc.stdout.strip()) + return path if path.is_absolute() else REPO / path + + +def install_hooks(folder: Path, reconcile_args: list[str] | None = None) -> int: + """Opt-in post-merge and post-checkout hooks that run --reconcile. Never replaces a hook it did not write.""" + rc = 0 + folder.mkdir(parents=True, exist_ok=True) + extra = "".join(f" {shlex.quote(arg)}" for arg in (reconcile_args or [])) + script = ( + f"#!/bin/sh\n{HOOK_MARK}\n" + f"python3 {shlex.quote(str(REPO / 'scripts' / 'install.py'))} --reconcile{extra} >/dev/null 2>&1 || true\n" + ) + for name in HOOKS: + hook = folder / name + if hook.exists() and HOOK_MARK not in hook.read_text(errors="replace"): + print(f"hook {name}: skipped, a hook this checkout did not write already exists", file=sys.stderr) + rc = 1 + continue + hook.write_text(script) + hook.chmod(0o755) + print(f"hook {name}: installed") + return rc + + def run(argv: list[str] | None = None, environ: dict[str, str] | None = None) -> int: parser = argparse.ArgumentParser( prog="install.py", @@ -248,9 +451,21 @@ def run(argv: list[str] | None = None, environ: dict[str, str] | None = None) -> parser.add_argument("--check", action="store_true", help="report state; change nothing") parser.add_argument("--uninstall", action="store_true", help="remove entries this checkout owns") parser.add_argument("--home", type=Path, help="home folder to install into (default: $HOME)") + parser.add_argument("--rig", type=Path, help="rig file to render slots from (default: ~/.config/jstack/rig.json)") + parser.add_argument("--render-dir", type=Path, help="where rendered skills go (default: ~/.local/share/jstack/rendered/skills)") + parser.add_argument( + "--reconcile", + action="store_true", + help="re-render and repair entries this checkout already installed; install nothing new", + ) + parser.add_argument("--install-hook", action="store_true", help="also add post-merge and post-checkout hooks that run --reconcile") + parser.add_argument("--hooks-dir", type=Path, help="git hooks folder for --install-hook (default: this checkout's)") args = parser.parse_args(argv) - if args.check and args.uninstall: - parser.error("--check and --uninstall are exclusive") + exclusive = [flag for flag, on in (("--check", args.check), ("--uninstall", args.uninstall), ("--reconcile", args.reconcile)) if on] + if len(exclusive) > 1: + parser.error(f"{' and '.join(exclusive)} are exclusive") + if args.install_hook and exclusive: + parser.error(f"--install-hook cannot combine with {exclusive[0]}") env = dict(os.environ if environ is None else environ) if args.home: @@ -258,6 +473,12 @@ def run(argv: list[str] | None = None, environ: dict[str, str] | None = None) -> env = {} else: home = Path(env.get("HOME") or Path.home()) + config_home = Path(env.get("XDG_CONFIG_HOME") or home / ".config") + data_home = Path(env.get("XDG_DATA_HOME") or home / ".local" / "share") + rig_path = args.rig.expanduser() if args.rig else config_home / "jstack" / "rig.json" + render_root = args.render_dir.expanduser() if args.render_dir else data_home / "jstack" / "rendered" / "skills" + if args.rig and not rig_path.is_file(): + parser.error(f"--rig {rig_path.name} does not exist") if args.only is not None: picked = [s.strip() for s in args.only.split(",") if s.strip()] @@ -275,8 +496,47 @@ def run(argv: list[str] | None = None, environ: dict[str, str] | None = None) -> names = available_skills() rc = 0 + # Slot rendering. With no rig file, nothing here runs and installs stay stock. + renders: dict[str, Path] = {} + reasons: dict[str, str] = {} + if rig_path.is_file() and not args.uninstall: + rig = load_rig(rig_path) + rig_dig = rig_digest(rig) + for name in names: + if not has_slot(name): + continue + why = render_state(name, rig_dig, render_root) + if why and not args.check: + try: + render_skill(name, rig, rig_dig, render_root) + why = None + except ValueError as exc: + print(f"{name}: not rendered, {exc}; installing stock", file=sys.stderr) + rc = 1 + continue + renders[name] = render_root / name + if why: + reasons[name] = why + for target in targets(home, args.client, env): label = f"{target.client}: {target.path}" + if args.reconcile: + for name in names: + entry = target.path / name + if not (entry.exists() or entry.is_symlink()) or not owns_link(entry): + continue + mode = "symlink" if entry.is_symlink() else "copy" + state = status(entry, name, mode, renders.get(name)) + if state == "ok": + continue + if state in ("conflict", "modified"): + print(f"{label}/{name}: skipped, {state}", file=sys.stderr) + rc = 1 + continue + remove(entry) + place(entry, name, mode, renders.get(name)) + print(f"{label}/{name}: reconciled ({mode})") + continue if args.uninstall: if not target.path.is_dir(): continue @@ -293,9 +553,11 @@ def run(argv: list[str] | None = None, environ: dict[str, str] | None = None) -> continue for name in names: entry = target.path / name - state = status(entry, name, args.mode) + state = status(entry, name, args.mode, renders.get(name)) + if state == "ok" and name in reasons: + state = "drift" if args.check: - print(f"{label}/{name}: {state}") + print(f"{label}/{name}: {state}" + (f" ({reasons[name]})" if state == "drift" else "")) rc |= state != "ok" continue if state in ("conflict", "modified"): @@ -314,8 +576,21 @@ def run(argv: list[str] | None = None, environ: dict[str, str] | None = None) -> break if state != "missing": remove(entry) - place(entry, name, args.mode) - print(f"{label}/{name}: installed ({args.mode})") + place(entry, name, args.mode, renders.get(name)) + print(f"{label}/{name}: installed ({args.mode}{', rendered' if name in renders else ''})") + if args.install_hook: + reconcile_args: list[str] = [] + if args.client != "all": + reconcile_args += ["--client", args.client] + if args.mode != "symlink": + reconcile_args += ["--mode", args.mode] + if args.home: + reconcile_args += ["--home", str(home)] + if args.rig: + reconcile_args += ["--rig", str(args.rig.expanduser().resolve())] + if args.render_dir: + reconcile_args += ["--render-dir", str(args.render_dir.expanduser().resolve())] + rc |= install_hooks(hooks_dir(args.hooks_dir), reconcile_args) return rc diff --git a/scripts/validate_skills.py b/scripts/validate_skills.py index f4657e0..96435bf 100755 --- a/scripts/validate_skills.py +++ b/scripts/validate_skills.py @@ -237,6 +237,34 @@ def check_links(skill: Path, deps: tuple[str, ...] = ()) -> list[str]: return errors +SLOT_TAG = re.compile(r"") +SLOT_NAME = re.compile(r"^[a-z0-9][a-z0-9-]*\Z") + + +def check_slots(skill: Path) -> list[str]: + """Rig slots in SKILL.md must be named in lowercase and opened and closed in matching pairs.""" + text = (skill / "SKILL.md").read_text(encoding="utf-8") + rel = f"skills/{skill.name}/SKILL.md" + errors: list[str] = [] + opened: str | None = None + for closing, name in SLOT_TAG.findall(text): + if not SLOT_NAME.match(name): + errors.append(f"{rel}: slot name {name!r} must be lowercase letters, digits and hyphens") + if closing: + if opened != name: + errors.append(f"{rel}: closing slot {name!r} does not match open slot {opened!r}") + opened = None + else: + opened = None + else: + if opened is not None: + errors.append(f"{rel}: slot {name!r} opened while {opened!r} is still open") + opened = name + if opened is not None: + errors.append(f"{rel}: unclosed slot {opened!r}") + return errors + + def manifest_versions(root: Path) -> dict[str, str]: out = {} for rel in (".claude-plugin/plugin.json", ".codex-plugin/plugin.json"): @@ -337,6 +365,7 @@ def validate(root: Path) -> list[str]: if not isinstance(desc, str) or not desc.strip(): errors.append(f"{rel}: description must be a non-empty string") errors.extend(check_links(d, deps.get(d.name, ()))) + errors.extend(check_slots(d)) if f"`{d.name}`" not in readme: errors.append(f"README.md: skill `{d.name}` is not listed") errors.extend(check_manifests(root)) diff --git a/skills/jstack-setup/SKILL.md b/skills/jstack-setup/SKILL.md new file mode 100644 index 0000000..69679eb --- /dev/null +++ b/skills/jstack-setup/SKILL.md @@ -0,0 +1,33 @@ +--- +name: jstack-setup +description: Describe your local rig once (tools, uploader, fallback model). Use for "jstack setup", "/jstack-setup", or after adding a browser, desktop, VM or model tool. Renders it into deployed skills. +--- + +# jstack setup + +Save your local tools in `~/.config/jstack/rig.json`. The installer renders them into the deployed skills that have a rig slot, such as `prove`. The public repo stays stock. +Ask short questions. Write nothing until the user confirms. + +## Steps + +1. **Inventory.** Run `scripts/jstack-rig.py discover --human` from this skill. It is read-only: it looks up program names, config folders and loopback ports, and runs `gh auth status` for its exit code. Also note whether T3 Code or other MCP tools are visible in this session. +2. **Show the table.** Give lane, tools found and gaps. Lanes: `web`, `auth`, `native_gui`, `vnc`, `video`, `audio`, `vm`, `ssh`, `secrets`. A gap is not a failure; it means that surface falls back to stock behavior. +3. **Ask once, together:** + - Which found tools to keep or drop per lane? Any tool to add? + - A media uploader command, if you have one? + - A fallback `provider/model` for tasks a worker refuses or avoids? Optional. + - Any local endpoint to record (OpenCode, Ollama, llama-server)? +4. **Write the rig.** Run `scripts/jstack-rig.py write --from-discover` with the answers: `--lane NAME=tool,tool`, `--uploader CMD`, `--fallback PROVIDER/MODEL`, `--endpoint NAME=URL`. Add `--dry-run` first to show the result. The file is written atomically with mode 0600. It holds names only. The script rejects any value that looks like a token, password or credential URL, and it never echoes the value. Move such a value into your secret manager. +5. **Render.** From the jstack checkout, run `./install.sh --reconcile`. It re-renders deployed skills from the rig and repairs only entries jstack installed. If nothing is installed yet, run `./install.sh` first. Offer `./install.sh --install-hook` so `git pull` re-renders on its own; add it only if the user says yes. +6. **Verify.** Run `scripts/jstack-rig.py check` and `./install.sh --check`. Both must exit 0. A `drift` line means the rig or a skill changed since the last render: run `--reconcile` again. +7. **Chain.** Offer `hindsight-setup` next, if the user has not set up their log sources. +8. **Close.** Tell the user which lanes are live, which are stock, and to re-run `jstack-setup` after adding a tool. + +## Rules + +- Setup reads program names, folder names and loopback ports only. It does not open transcripts, key files or credential stores. +- Never put a secret in the rig. Keep tokens in your secret manager. +- Do not overwrite a rig that is invalid JSON. Show the error and ask. +- The overlay per skill is capped at 1,024 bytes. If a render is refused for size, shorten the lane lists. +- Do not edit `AGENTS.md` or `CLAUDE.md` unless the user says yes. +- Do not copy rig values into a repository, a PR or a public message. `rig.example.json` shows the shape with placeholders. diff --git a/skills/jstack-setup/scripts/jstack-rig.py b/skills/jstack-setup/scripts/jstack-rig.py new file mode 100755 index 0000000..24adb4d --- /dev/null +++ b/skills/jstack-setup/scripts/jstack-rig.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +"""Discover, write and check the jstack rig file. Stdlib only. + +The rig file (default ~/.config/jstack/rig.json, schema jstack.rig/1) names the +local tools, endpoints and fallback model that `scripts/install.py` renders into +deployed skills. It holds names only, never secrets. + +Discovery is read-only. It looks up program names on $PATH, checks that a few +config folders exist, tries a TCP connect to loopback ports, and runs +`gh auth status` for its exit code alone. It never opens a secret file, a +transcript or a credential store, and never prints a token. + +Commands: + discover inventory this machine; print JSON, or a table with --human + write validate and write the rig file atomically with mode 0600 + check validate an existing rig file and report problems + +Exit codes: 0 ok, 1 check found a problem, 2 usage or validation error. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import socket +import subprocess +import sys +import tempfile +from pathlib import Path + +SCHEMA = "jstack.rig/1" +DISCOVER_SCHEMA = "jstack.discover/1" +TOP_KEYS = ("schema", "harnesses", "endpoints", "lanes", "media_uploader", "fallback") + +# Verification lanes and the program names that can serve each one. +LANE_TOOLS: dict[str, tuple[str, ...]] = { + "web": ("agent-browser", "browser-harness", "playwright", "chromium", "google-chrome-stable", "firefox"), + "auth": ("oathtool", "ykman", "op", "bw"), + "native_gui": ("cua-driver", "grim", "slurp", "wtype", "ydotool", "xdotool", "screencapture", "cliclick"), + "vnc": ("vncviewer", "remmina", "wayvnc", "x11vnc"), + "video": ("ffmpeg", "ffprobe", "wf-recorder"), + "audio": ("whisper", "whisper-cli", "whisper-cpp", "arecord", "parecord", "pw-record", "sox", "say"), + "vm": ("qemu-system-x86_64", "virsh", "limactl", "multipass", "quickemu", "docker", "podman"), + "ssh": ("ssh", "mosh", "scp", "tailscale"), + "secrets": ("op", "bw", "pass", "gopass", "vault", "sops"), +} +UPLOADER_TOOLS = ("gh", "rclone", "aws", "gcloud", "wrangler", "scp") +LOOPBACK_ENDPOINTS = {"opencode": 4096, "ollama": 11434, "llama_server": 8080} +# (name, config folder under $HOME or None, program on $PATH or None) +HARNESSES = ( + ("claude", ".claude", "claude"), + ("codex", ".codex", "codex"), + ("antigravity", ".gemini", None), + ("opencode", ".config/opencode", "opencode"), + ("pi", ".pi", "pi"), + ("t3", ".t3", None), +) + +NAME = r"[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,63}" +PLACEHOLDER = r"<[A-Za-z0-9._ -]{1,40}>" +NAME_RE = re.compile(rf"^(?:{NAME}|{PLACEHOLDER})\Z") +COMMAND_RE = re.compile(r"^(?:[A-Za-z0-9<][A-Za-z0-9._:/@+<>= ,-]{0,79})\Z") +LANE_RE = re.compile(r"^[a-z][a-z0-9_]{0,23}\Z") +ENDPOINT_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,23}\Z") +URL_RE = re.compile( + r"^https?://(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\]|<[A-Za-z0-9._ -]{1,20}>)" + r"(?::(?:\d{1,5}|<[A-Za-z0-9._ -]{1,20}>))?(?:/[A-Za-z0-9._/-]*)?\Z" +) +MAX_LANES = 16 +MAX_TOOLS = 16 + +SECRET_PATTERNS = [ + re.compile(r"://[^/\s@]*@"), # credentials in a URL + re.compile(r"(?i)[?&;](?:access_?token|token|key|apikey|api_key|secret|password|pass|auth|sig|signature)="), + re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}"), + re.compile(r"github_pat_[A-Za-z0-9_]{16,}"), + re.compile(r"\bsk-[A-Za-z0-9_-]{12,}"), + re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{6,}"), + re.compile(r"\bAKIA[0-9A-Z]{16}\b"), + re.compile(r"\bAIza[0-9A-Za-z_-]{30,}"), + re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\."), + re.compile(r"-----BEGIN"), + re.compile(r"(?i)\bbearer\s+\S{8,}"), + re.compile(r"(?i)(?:password|passwd|secret|token|api[_-]?key|credential|authorization)\s*[:=]"), + re.compile(r"\b[0-9a-fA-F]{32,}\b"), +] +LONG_TOKEN = re.compile(r"[A-Za-z0-9+_=]{32,}") + + +def looks_secret(value: str) -> bool: + """True when a string resembles a token, password or credential URL.""" + if any(p.search(value) for p in SECRET_PATTERNS): + return True + for chunk in LONG_TOKEN.findall(value): + if re.search(r"[A-Za-z]", chunk) and re.search(r"\d", chunk): + return True + return False + + +def _check(label: str, value: object, pattern: re.Pattern[str], errors: list[str]) -> None: + """Record a problem for one string value. The value itself is never echoed.""" + if not isinstance(value, str) or not value: + errors.append(f"{label}: must be a non-empty string") + elif looks_secret(value): + errors.append(f"{label}: value looks like a token, password or credential URL; rig files hold names only") + elif not pattern.match(value): + errors.append(f"{label}: value has characters outside the allowed set") + + +def validate(rig: object) -> list[str]: + """Return problems with a rig document. Empty means valid.""" + if not isinstance(rig, dict): + return ["rig must be a JSON object"] + errors: list[str] = [] + if rig.get("schema") != SCHEMA: + errors.append(f"schema must be {SCHEMA}") + for i, key in enumerate(rig): + if key not in TOP_KEYS: + errors.append(f"unknown top-level key #{i + 1}") + harnesses = rig.get("harnesses", []) + if not isinstance(harnesses, list): + errors.append("harnesses: must be a list") + else: + for i, h in enumerate(harnesses): + _check(f"harnesses[{i}]", h, NAME_RE, errors) + endpoints = rig.get("endpoints", {}) + if not isinstance(endpoints, dict): + errors.append("endpoints: must be an object") + else: + for i, (name, url) in enumerate(endpoints.items()): + if not isinstance(name, str) or not ENDPOINT_NAME_RE.match(name) or looks_secret(name): + errors.append(f"endpoints: name #{i + 1} is not a plain lowercase name") + continue + _check(f"endpoints.{name}", url, URL_RE, errors) + lanes = rig.get("lanes", {}) + if not isinstance(lanes, dict): + errors.append("lanes: must be an object") + else: + if len(lanes) > MAX_LANES: + errors.append(f"lanes: at most {MAX_LANES} lanes") + for i, (lane, tools) in enumerate(lanes.items()): + if not isinstance(lane, str) or not LANE_RE.match(lane): + errors.append(f"lanes: name #{i + 1} must match [a-z][a-z0-9_]*") + continue + if not isinstance(tools, list) or len(tools) > MAX_TOOLS: + errors.append(f"lanes.{lane}: must be a list of at most {MAX_TOOLS} tool names") + continue + for j, tool in enumerate(tools): + _check(f"lanes.{lane}[{j}]", tool, NAME_RE, errors) + if "media_uploader" in rig: + _check("media_uploader", rig["media_uploader"], COMMAND_RE, errors) + if "fallback" in rig: + fb = rig["fallback"] + if not isinstance(fb, dict) or set(fb) != {"provider", "model"}: + errors.append("fallback: must be an object with exactly provider and model") + else: + _check("fallback.provider", fb["provider"], NAME_RE, errors) + _check("fallback.model", fb["model"], NAME_RE, errors) + return errors + + +def default_path(env: dict[str, str] | None = None) -> Path: + env = dict(os.environ if env is None else env) + base = env.get("XDG_CONFIG_HOME") or str(Path(env.get("HOME") or Path.home()) / ".config") + return Path(base) / "jstack" / "rig.json" + + +def which(name: str, env: dict[str, str]) -> bool: + return shutil.which(name, path=env.get("PATH")) is not None + + +def tcp_open(port: int, timeout: float = 0.3) -> bool: + try: + with socket.create_connection(("127.0.0.1", port), timeout=timeout): + return True + except OSError: + return False + + +def gh_state(env: dict[str, str]) -> dict[str, object]: + if not which("gh", env): + return {"installed": False, "authenticated": None} + try: + proc = subprocess.run( + ["gh", "auth", "status"], capture_output=True, timeout=10, check=False, env=env + ) + except (OSError, subprocess.SubprocessError): + return {"installed": True, "authenticated": None} + return {"installed": True, "authenticated": proc.returncode == 0} + + +def discover(home: Path, env: dict[str, str], net: bool = True, gh: bool = True) -> dict[str, object]: + harnesses = {} + for name, folder, program in HARNESSES: + found = (home / folder).exists() or bool(program and which(program, env)) + harnesses[name] = found + lanes = {lane: [t for t in tools if which(t, env)] for lane, tools in LANE_TOOLS.items()} + uploaders = [t for t in UPLOADER_TOOLS if which(t, env)] + endpoints = {} + if net: + for name, port in LOOPBACK_ENDPOINTS.items(): + if tcp_open(port): + endpoints[name] = f"http://127.0.0.1:{port}" + candidate: dict[str, object] = { + "schema": SCHEMA, + "harnesses": sorted(n for n, ok in harnesses.items() if ok), + "endpoints": endpoints, + "lanes": {lane: tools for lane, tools in lanes.items() if tools}, + } + return { + "schema": DISCOVER_SCHEMA, + "harnesses": harnesses, + "lanes": lanes, + "uploader_candidates": uploaders, + "endpoints": endpoints, + "network_probed": net, + "gh": gh_state(env) if gh else None, + "rig": candidate, + } + + +def human(report: dict[str, object]) -> str: + rows = ["lane tools found"] + lanes = report["lanes"] + assert isinstance(lanes, dict) + for lane, tools in lanes.items(): + rows.append(f"{lane:<11} {', '.join(tools) if tools else '(none)'}") + harnesses = report["harnesses"] + assert isinstance(harnesses, dict) + rows.append("") + rows.append("harnesses " + (", ".join(n for n, ok in harnesses.items() if ok) or "(none)")) + endpoints = report["endpoints"] + assert isinstance(endpoints, dict) + probed = report["network_probed"] + rows.append("endpoints " + (", ".join(endpoints) or ("(none on loopback)" if probed else "(not probed)"))) + uploaders = report["uploader_candidates"] + assert isinstance(uploaders, list) + rows.append("uploaders " + (", ".join(uploaders) or "(none)")) + gh = report["gh"] + if isinstance(gh, dict): + auth = gh["authenticated"] + rows.append("gh " + ("not installed" if not gh["installed"] else "signed in" if auth else "not signed in")) + return "\n".join(rows) + + +def atomic_write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".rig.", suffix=".tmp", dir=path.parent) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(text) + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + os.chmod(path, 0o600) + + +def load_rig(path: Path) -> dict: + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, dict): + raise TypeError("rig must be a JSON object") + return data + + +def read_input(source: str) -> dict: + raw = sys.stdin.read() if source == "-" else Path(source).read_text(encoding="utf-8") + data = json.loads(raw) + if isinstance(data, dict) and data.get("schema") == DISCOVER_SCHEMA: + data = data.get("rig", {}) + if not isinstance(data, dict): + raise TypeError("input must be a JSON object") + return data + + +def split_pair(raw: str, what: str, *, allow_empty: bool = False) -> tuple[str, str]: + key, sep, value = raw.partition("=") + if not sep or not key or (not allow_empty and not value): + raise ValueError(f"error: {what} must look like NAME=VALUE") + return key, value + + +def cmd_discover(args: argparse.Namespace) -> int: + env = dict(os.environ) + home = args.home.expanduser().resolve() if args.home else Path(env.get("HOME") or Path.home()) + report = discover(home, env, net=not args.no_net, gh=not args.no_gh) + print(human(report) if args.human else json.dumps(report, indent=2, sort_keys=True)) + return 0 + + +def cmd_write(args: argparse.Namespace) -> int: + path = args.path or default_path() + rig: dict = {} + try: + if args.merge and path.is_file(): + rig.update(load_rig(path)) + if args.from_discover: + found = discover(Path(os.environ.get("HOME") or Path.home()), dict(os.environ), net=not args.no_net, gh=False)["rig"] + assert isinstance(found, dict) + for key, value in found.items(): + if isinstance(value, dict) and isinstance(rig.get(key), dict): + rig[key] = {**rig[key], **value} + else: + rig[key] = value + if args.input: + rig.update(read_input(args.input)) + except (OSError, TypeError, ValueError) as exc: + print(f"error: cannot read rig input: {exc.__class__.__name__}", file=sys.stderr) + return 2 + rig["schema"] = SCHEMA + if args.fallback: + provider, sep, model = args.fallback.partition("/") + if not sep or not provider or not model: + print("error: --fallback must look like PROVIDER/MODEL", file=sys.stderr) + return 2 + rig["fallback"] = {"provider": provider, "model": model} + if args.uploader: + rig["media_uploader"] = args.uploader + if args.harness: + rig["harnesses"] = sorted(set(args.harness)) + try: + for raw in args.lane or []: + lane, tools = split_pair(raw, "--lane", allow_empty=True) + lanes = dict(rig.get("lanes") or {}) + items = [t for t in tools.split(",") if t] + if items: + lanes[lane] = items + else: + lanes.pop(lane, None) + rig["lanes"] = lanes + for raw in args.endpoint or []: + name, url = split_pair(raw, "--endpoint") + endpoints = dict(rig.get("endpoints") or {}) + endpoints[name] = url + rig["endpoints"] = endpoints + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 2 + problems = validate(rig) + if problems: + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + print("error: nothing written", file=sys.stderr) + return 2 + text = json.dumps(rig, indent=2, sort_keys=True) + "\n" + if args.dry_run: + sys.stdout.write(text) + return 0 + atomic_write(path, text) + print(f"wrote {path} (mode 0600)") + return 0 + + +def cmd_check(args: argparse.Namespace) -> int: + path = args.path or default_path() + env = dict(os.environ) + errors: list[str] = [] + warnings: list[str] = [] + if not path.is_file(): + print(f"error: {path} does not exist; run jstack-setup", file=sys.stderr) + return 1 + mode = path.stat().st_mode & 0o777 + if mode & 0o077: + errors.append(f"mode is {mode:04o}; run chmod 600 on the rig file") + try: + rig = load_rig(path) + except (OSError, TypeError, ValueError) as exc: + print(f"error: rig is not valid JSON ({exc.__class__.__name__}); fix or rewrite it", file=sys.stderr) + return 1 + errors.extend(validate(rig)) + lanes = rig.get("lanes") if isinstance(rig.get("lanes"), dict) else {} + for lane, tools in sorted(lanes.items()): + for tool in tools if isinstance(tools, list) else []: + if isinstance(tool, str) and not tool.startswith("<") and not which(tool, env): + warnings.append(f"lanes.{lane}: {tool} is not on PATH") + if "fallback" not in rig: + warnings.append("fallback: not set; a refused or avoided task will be reported as blocked") + if "media_uploader" not in rig: + warnings.append("media_uploader: not set; artifacts stay local") + if args.strict: + errors.extend(warnings) + warnings = [] + for line in warnings: + print(f"warn: {line}") + for line in errors: + print(f"error: {line}") + if errors: + return 1 + print(f"ok: {path} valid ({len(lanes)} lane(s))") + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="jstack-rig.py", description="Discover, write and check the jstack rig file.") + sub = parser.add_subparsers(dest="command", required=True) + + d = sub.add_parser("discover", help="inventory this machine (read-only)") + d.add_argument("--human", action="store_true", help="print a table instead of JSON") + d.add_argument("--no-net", action="store_true", help="skip loopback port probes") + d.add_argument("--no-gh", action="store_true", help="skip the gh auth status check") + d.add_argument("--home", type=Path, help="home folder to inspect (default: $HOME)") + d.set_defaults(func=cmd_discover) + + w = sub.add_parser("write", help="validate and atomically write the rig file (mode 0600)") + w.add_argument("--path", type=Path, help="rig file (default: ~/.config/jstack/rig.json)") + w.add_argument("--input", metavar="FILE", help="rig or discover JSON; - reads stdin") + w.add_argument("--from-discover", action="store_true", help="start from discovered harnesses, lanes and endpoints") + w.add_argument("--merge", action="store_true", help="start from the existing rig file") + w.add_argument("--fallback", metavar="PROVIDER/MODEL") + w.add_argument("--uploader", metavar="COMMAND") + w.add_argument("--lane", action="append", metavar="NAME=TOOL[,TOOL]", help="set a lane (repeatable)") + w.add_argument("--endpoint", action="append", metavar="NAME=URL", help="set an endpoint (repeatable)") + w.add_argument("--harness", action="append", metavar="NAME", help="set the harness list (repeatable)") + w.add_argument("--no-net", action="store_true") + w.add_argument("--dry-run", action="store_true", help="print the rig; write nothing") + w.set_defaults(func=cmd_write) + + c = sub.add_parser("check", help="validate the rig file") + c.add_argument("--path", type=Path) + c.add_argument("--strict", action="store_true", help="treat warnings as errors") + c.set_defaults(func=cmd_check) + return parser + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/prove/SKILL.md b/skills/prove/SKILL.md new file mode 100644 index 0000000..674fec8 --- /dev/null +++ b/skills/prove/SKILL.md @@ -0,0 +1,76 @@ +--- +name: prove +description: Prove a change works with real evidence on the real surface. Use before saying done, or when a worker reports success. L0-L4 ladder, proof packet, orchestrator gate, refusal fallback. +--- + +# Prove + +A claim is not proof. Run it, capture it, check it against the current head. +Say the level you reached. Never claim a higher one. + +## Ladder + +Pick the lowest level that could show the claim false. Go higher for anything a user sees or an integration touches. + +- **L0 static:** lint, types, format, build. +- **L1 automated:** unit and integration tests. +- **L2 real run:** the CLI, service or API runs for real, with its output kept. +- **L3 real surface:** the UI, desktop, audio or video is seen, heard or transcribed through a real tool. See `references/surfaces.md`. +- **L4 live:** real accounts, devices, a remote host or VM, or a prod-like environment. + +A green L1 does not prove a UI change. A screenshot of the wrong page proves nothing: open the artifact. + +## Packet + +Use `scripts/proof-pack.py`. It is stdlib Python. Options go after the command: `--dir` (default `.proof`), `--rig`, `--head`. + +```sh +proof-pack.py init --task "what you claim" --level L2 +proof-pack.py run --level L1 --label tests -- pytest -q +proof-pack.py run --level L2 --label smoke -- ./tool --version +proof-pack.py attach shot.png --surface web --level L3 +proof-pack.py verify --markdown +``` + +- `run` records exact argv with secrets redacted, exit code, timing, head sha and a hashed log. A later `run` with the same `--label` replaces an earlier one. +- `attach` records size, sha256 and surface. Auth, desktop and VNC captures on a public or unknown repo need `--redacted`, after you redact them. +- `block` records a surface you could not reach. It refuses until every lane the rig lists for that surface is logged with `--tried LANE=EVIDENCE`. Use `--human-only` only for physical blockers: a hardware touch, biometrics, presence. +- `verify` fails on a stale head, a missing or empty artifact, a hash mismatch, a non-zero exit, empty output, an unexhausted block, or a level below the one required. +- `verify --markdown` prints the PR Evidence block. Paste it; do not retype it. + +## Gate + +Worker output is a claim. The Senior or Orchestrator checks it before merge or "done": + +1. Run `proof-pack.py verify` on the head under review. It must exit 0. +2. Re-run one L1 or higher command yourself. +3. Open at least one artifact and read it. +4. Reject a packet whose head is not the head you will merge. + +## Refused or avoided + +Use this only for a task the user authorized. + +1. If a worker refuses or avoids a lawful, authorized step, do not retry the same prompt. +2. Hand it to the rig's fallback provider and model, if one is set. Write a neutral brief with the goal, the user's authorization and the packet path. Run the same gate on the result. +3. If a refusal names a real safety or policy concern, stop and tell the user. +4. With no fallback, report the blocker. + +Never route around these. Record them with `block --class`, stop and ask the user: + +- An unapproved `full-send` user gate. +- A CAPTCHA or anti-bot check, or a human 2FA prompt (`captcha`, `anti-bot`, `2fa`). +- An access-control denial or an approval denial (`access-denied`, `approval`). + +## Rig + + +Stock defaults, no local rig. Use your harness's browser and screenshot tools. No fallback model: report the blocker. No media uploader: keep artifacts local and say so. + + +Run `jstack-setup` to describe your tools, uploader and fallback model. + +## Files + +- `references/surfaces.md`: read when choosing how to verify a surface: web, auth, desktop, VNC, video, audio, SSH, VM. +- `scripts/proof-pack.py`: the packet CLI above. diff --git a/skills/prove/references/surfaces.md b/skills/prove/references/surfaces.md new file mode 100644 index 0000000..711a556 --- /dev/null +++ b/skills/prove/references/surfaces.md @@ -0,0 +1,82 @@ +# Verification surfaces + +Recipes for L2 to L4 evidence. Use the rig's lane for a surface first, then the stock tool named here. Attach each result with `proof-pack.py attach --surface NAME`. Surface names match rig lane names: `web`, `auth`, `native_gui`, `vnc`, `video`, `audio`, `vm`, `ssh`. + +Every recipe has the same shape: drive the real thing, capture what a user would see or hear, open the capture, then attach it. Do not keep a screenshot you did not look at. + +## Web and UI (`web`) + +1. Open the page in a real browser tool (`agent-browser`, Playwright or the harness browser). +2. Do the user's path: click, type, submit. Do not stop at page load. +3. Check state, not only pixels: the visible text, the URL, a console with no errors. +4. Capture a screenshot of the result. For motion, record a short clip. +5. Check a narrow phone width and a desktop width for layout changes. + +Attach: `--surface web --kind screenshot`. + +## Auth, secrets and passkeys (`auth`) + +Auth captures can show codes, tokens and account names. They are gated. + +1. Take the credential from the rig's secret manager at run time. Never type it into a command line, a log or a brief. +2. Prefer a test account. Use a real account only when the user said so. +3. Passkeys and one-time codes the tool can generate, such as TOTP through an authenticator CLI, are in scope. Codes that need a person are not: see the human-only rule below. +4. Prove the outcome, such as the signed-in page, with the sensitive area cropped or blurred. +5. Redact first, then attach with `--redacted`. A public or unknown repo refuses anything else. + +## Native GUI: Wayland, X11, macOS (`native_gui`) + +1. Drive the app through its accessibility tree first (`cua-driver` or the platform equivalent). Use pixel clicks only for surfaces the tree lacks. +2. Capture the one window, not the whole desktop: `grim -g` with a window geometry on Wayland, `screencapture -l` on macOS, a window grab on X11. +3. Verify after the action with a fresh read of state, not the cached one. +4. Crop out other windows, notifications and the clock before attaching. + +Attach: `--surface native_gui --redacted`. + +## VNC and remote desktop (`vnc`) + +1. Connect with the rig's viewer. Use a view-only session when you only need to look. +2. Capture the viewer window or the framebuffer, not the host screen. +3. Name the remote machine by role (`build-vm`), never by hostname or address, in anything you attach or write. +4. Redact, then attach with `--redacted`. + +## Video contact sheets (`video`) + +Do not attach a long clip nobody will watch. Prove it with frames. + +1. Record with the rig's recorder, such as `wf-recorder` or `ffmpeg`. +2. Check the clip is real: `ffprobe` for duration and streams, non-zero size. +3. Build a contact sheet: `ffmpeg -i clip.mp4 -vf "fps=1,scale=320:-1,tile=4x3" sheet.png`. +4. Open the sheet. Confirm the start, the action and the end are all there. +5. Attach the sheet at L3 and the clip at L3 or L4. + +## Audio in and out, and ASR (`audio`) + +1. For output: play to a loopback or capture the sink, then transcribe it. Compare the transcript to the expected text. +2. For input: feed a known recording and check what the app did with it. +3. Transcribe with the rig's ASR tool. Keep the transcript beside the audio. +4. State the match plainly: exact, near or off. A transcript that differs is a failed check, not a warning. + +Attach the audio and the transcript, both `--surface audio`. + +## SSH, remote hosts and VMs (`ssh`, `vm`) + +1. Name the target by role. Never put a hostname, tailnet name or address in a packet. +2. Run the real command on the remote side. Keep argv and output with `proof-pack.py run -- ssh ROLE ...`. +3. For a VM, start from a clean snapshot or image, install the change, run it, and keep the log. Destroy or revert the VM afterward. +4. Check the exit code and the output. A connection that opens proves nothing about the change. +5. Do not add keys, edit `known_hosts` or change firewall rules to get in. If access is denied, record `block --class access-denied` and stop. + +## Human-only: physical exhaustion rule + +A step is `human-only` only when a person's body is required: touch a hardware key, scan a finger or face, plug in a device, be in the room. + +Before you record `block --human-only --class physical`: + +1. List every lane the rig has for the surface. +2. Try each one. Log what happened with `--tried LANE=EVIDENCE`. +3. If the rig has no lane for the surface, log at least two different methods. + +`proof-pack.py block` refuses until the log covers every lane, and `verify` checks it again. + +CAPTCHA, anti-bot checks, human 2FA prompts, access denials and approval denials are not physical. Do not try to get past them. Record `block --class captcha|anti-bot|2fa|access-denied|approval`, stop and ask the user. They are never handed to a fallback model. diff --git a/skills/prove/scripts/proof-pack.py b/skills/prove/scripts/proof-pack.py new file mode 100755 index 0000000..b703f07 --- /dev/null +++ b/skills/prove/scripts/proof-pack.py @@ -0,0 +1,615 @@ +#!/usr/bin/env python3 +"""Build and verify a mechanical proof packet. Stdlib only. + +A packet is `/pack.json` (default dir: .proof) plus logs under `/logs/`. +Every record carries the git HEAD it was made at, so a packet goes stale when +the branch moves. Secrets are redacted before anything is stored. + +Commands: + init start a packet for a task and required level (L0-L4) + run run one command, record argv, exit code, timing, HEAD and a log hash + attach record an artifact file (size, sha256, surface, level) + block record a blocked surface; refused until the rig's lanes are exhausted + verify re-check every record against disk and HEAD; --markdown for a PR + +Exit codes: 0 ok, 1 verify failed, 2 usage or state error, 3 redaction gate +refused an artifact, 4 block refused as unexhausted. `run` returns the exit code +of the command it ran. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +import tempfile +import time +from datetime import UTC, datetime +from pathlib import Path + +SCHEMA = "jstack.proof/1" +LEVELS = ("L0", "L1", "L2", "L3", "L4") +# Captures of these surfaces can show credentials, codes or private windows. +GATED_SURFACES = frozenset({"auth", "native_gui", "vnc", "desktop"}) +# Blockers an agent must never work around: stop and ask the user. +GATE_CLASSES = ("captcha", "anti-bot", "2fa", "access-denied", "approval") +BLOCK_CLASSES = ("physical", "other", *GATE_CLASSES) +SURFACE_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$") +REDACTED = "[REDACTED]" + +TOKEN_PATTERNS = [ + re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}"), + re.compile(r"github_pat_[A-Za-z0-9_]{16,}"), + re.compile(r"\bsk-[A-Za-z0-9_-]{12,}"), + re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{6,}"), + re.compile(r"\bAKIA[0-9A-Z]{16}\b"), + re.compile(r"\bAIza[0-9A-Za-z_-]{30,}"), + re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*"), + re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)"), +] +URL_USERINFO = re.compile(r"(://)[^/\s@]+@") +BEARER = re.compile(r"(?i)\bbearer\s+[^\s\"']+") +KEY_VALUE = re.compile( + r"""(?i)(["']?)\b([A-Za-z0-9_-]*(?:password|passwd|secret|token|api[_-]?key|authorization))\b\1(\s*[:=]\s*)(?:(["'])(?:\\.|(?!\4).)*\4|([^\s"',;&}\]]+))""" +) +# Keep public packets free of the machine's identity. +HOME_PATH = re.compile(r"/(?:home|Users)/[A-Za-z0-9._-]+") +TAILNET = re.compile(r"\b[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.ts\.net\b", re.IGNORECASE) +CGNAT = re.compile(r"(? str: + for pattern in TOKEN_PATTERNS: + text = pattern.sub(REDACTED, text) + text = URL_USERINFO.sub(rf"\1{REDACTED}@", text) + text = BEARER.sub(f"Bearer {REDACTED}", text) + text = KEY_VALUE.sub( + lambda m: f"{m.group(1)}{m.group(2)}{m.group(1)}{m.group(3)}{m.group(4) or ''}{REDACTED}{m.group(4) or ''}", + text, + ) + text = HOME_PATH.sub("~", text) + text = TAILNET.sub("", text) + return CGNAT.sub("", text) + + +def secret_flag(flag: str) -> bool: + parts = set(re.split(r"[-_]+", flag.lstrip("-").lower())) + return bool( + parts & SECRET_WORDS + or {"api", "key"} <= parts + or {"private", "key"} <= parts + ) + + +def redact_argv(argv: list[str]) -> list[str]: + out: list[str] = [] + hide_next = False + for arg in argv: + if hide_next and not arg.startswith("-"): + out.append(REDACTED) + hide_next = False + continue + hide_next = False + pair = re.match(r"^(--?[A-Za-z0-9_-]+)=(.*)$", arg, re.DOTALL) + if pair and secret_flag(pair.group(1)): + out.append(f"{pair.group(1)}={REDACTED}") + continue + if arg.startswith("-") and secret_flag(arg): + out.append(redact_text(arg)) + hide_next = True + continue + env = ENV_SECRET.match(arg) + if env: + out.append(f"{env.group(1)}={REDACTED}") + continue + out.append(redact_text(arg)) + return out + + +def now() -> str: + return datetime.now(UTC).isoformat(timespec="seconds") + + +def sha256_file(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as fh: + for block in iter(lambda: fh.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def git_head(repo: Path, override: str | None) -> str | None: + if override: + return override + try: + proc = subprocess.run( + ["git", "rev-parse", "HEAD"], cwd=repo, capture_output=True, text=True, timeout=10, check=False + ) + except (OSError, subprocess.SubprocessError): + return None + sha = proc.stdout.strip() + return sha if proc.returncode == 0 and re.fullmatch(r"[0-9a-f]{40,64}", sha) else None + + +def detect_visibility(repo: Path) -> str: + """public, private or unknown. Unknown is treated as public by the redaction gate.""" + try: + proc = subprocess.run( + ["gh", "repo", "view", "--json", "isPrivate", "--jq", ".isPrivate"], + cwd=repo, + capture_output=True, + text=True, + timeout=10, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return "unknown" + answer = proc.stdout.strip() + if proc.returncode == 0 and answer in ("true", "false"): + return "private" if answer == "true" else "public" + return "unknown" + + +def default_rig(env: dict[str, str] | None = None) -> Path: + env = dict(os.environ if env is None else env) + base = env.get("XDG_CONFIG_HOME") or str(Path(env.get("HOME") or Path.home()) / ".config") + return Path(base) / "jstack" / "rig.json" + + +def rig_lanes(rig_path: Path | None, surface: str) -> list[str]: + """Lanes the rig configures for a surface. Empty when there is no rig or no lane.""" + path = rig_path or default_rig() + try: + data = json.loads(path.read_text(encoding="utf-8")) + tools = data["lanes"][surface] + except (OSError, ValueError, KeyError, TypeError): + return [] + return [t for t in tools if isinstance(t, str)] if isinstance(tools, list) else [] + + +class Pack: + def __init__(self, directory: Path) -> None: + self.dir = directory + self.file = directory / "pack.json" + self.data: dict = {} + + def load(self) -> dict: + try: + self.data = json.loads(self.file.read_text(encoding="utf-8")) + except (OSError, ValueError): + raise SystemExit(f"error: no readable packet at {self.file}; run init first") from None + if not isinstance(self.data, dict) or self.data.get("schema") != SCHEMA: + raise SystemExit(f"error: {self.file} is not a {SCHEMA} packet") + return self.data + + def save(self) -> None: + self.dir.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".pack.", suffix=".tmp", dir=self.dir) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(self.data, fh, indent=2, sort_keys=True) + fh.write("\n") + os.replace(tmp, self.file) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + def next_id(self, prefix: str, key: str) -> str: + return f"{prefix}{len(self.data.get(key, [])) + 1}" + + def rel(self, path: Path) -> str: + return os.path.relpath(path.resolve(), self.dir.resolve().parent) + + def resolve(self, rel: str) -> Path: + return (self.dir.resolve().parent / rel).resolve() + + +def cmd_init(args: argparse.Namespace, pack: Pack) -> int: + if pack.file.exists() and not args.force: + print(f"error: {pack.file} exists; pass --force to start over", file=sys.stderr) + return 2 + visibility = args.visibility if args.visibility != "auto" else detect_visibility(args.repo) + pack.data = { + "schema": SCHEMA, + "task": redact_text(args.task), + "created": now(), + "head_sha": git_head(args.repo, args.head), + "required_level": args.level, + "visibility": visibility, + "steps": [], + "artifacts": [], + "blocks": [], + } + pack.save() + print(f"packet started: {pack.file} (level {args.level}, repo {visibility}, head {short(pack.data['head_sha'])})") + return 0 + + +def cmd_run(args: argparse.Namespace, pack: Pack) -> int: + pack.load() + argv = list(args.cmd) + if argv and argv[0] == "--": + argv = argv[1:] + if not argv: + print("error: run needs a command after --", file=sys.stderr) + return 2 + label = args.label or re.sub(r"[^A-Za-z0-9._-]+", "-", Path(argv[0]).name)[:40] or "step" + step_id = pack.next_id("s", "steps") + head = git_head(args.repo, args.head) + started = now() + t0 = time.monotonic() + timed_out = False + error = None + try: + proc = subprocess.run( + argv, cwd=args.cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=args.timeout, check=False + ) + code, raw = proc.returncode, proc.stdout + except subprocess.TimeoutExpired as exc: + code, raw, timed_out = 124, exc.stdout or b"", True + except OSError as exc: + code, raw, error = 127, b"", exc.__class__.__name__ + text = redact_text(raw.decode("utf-8", errors="replace")) + logs = pack.dir / "logs" + logs.mkdir(parents=True, exist_ok=True) + safe_label = re.sub(r"[^A-Za-z0-9._-]+", "-", label).strip(".-")[:40] or "step" + log_path = logs / f"{len(pack.data['steps']) + 1:03d}-{safe_label}.log" + log_path.write_text(text, encoding="utf-8") + step = { + "id": step_id, + "label": label, + "level": args.level, + "argv": redact_argv(argv), + "exit_code": code, + "head_sha": head, + "started": started, + "finished": now(), + "duration_s": round(time.monotonic() - t0, 2), + "log": pack.rel(log_path), + "log_sha256": sha256_file(log_path), + "output_bytes": log_path.stat().st_size, + "allow_empty": bool(args.allow_empty), + "timed_out": timed_out, + } + if error: + step["error"] = error + pack.data["steps"].append(step) + pack.save() + sys.stdout.write(text) + print(f"[proof-pack] {step_id} {label}: exit {code}, {step['output_bytes']} bytes logged", file=sys.stderr) + return code + + +def cmd_attach(args: argparse.Namespace, pack: Pack) -> int: + if not SURFACE_RE.fullmatch(args.surface): + print(f"error: invalid surface {args.surface!r}; use lowercase letters, digits, hyphens or underscores", file=sys.stderr) + return 2 + data = pack.load() + path = Path(args.path) + if not path.is_file(): + print(f"error: {path.name} is not a file", file=sys.stderr) + return 2 + size = path.stat().st_size + if size == 0: + print(f"error: {path.name} is empty", file=sys.stderr) + return 2 + if args.surface in GATED_SURFACES and data.get("visibility") != "private" and not args.redacted: + print( + f"refused: {args.surface} captures can show credentials or private windows, and this repo is " + f"{data.get('visibility', 'unknown')}. Redact the file, then attach with --redacted.", + file=sys.stderr, + ) + return 3 + seq = int(data.get("seq", 0)) + 1 + data["seq"] = seq + art = { + "id": pack.next_id("a", "artifacts"), + "seq": seq, + "path": pack.rel(path), + "sha256": sha256_file(path), + "bytes": size, + "surface": args.surface, + "level": args.level, + "kind": args.kind, + "redacted": bool(args.redacted), + "head_sha": git_head(args.repo, args.head), + "added": now(), + } + if args.note: + art["note"] = redact_text(args.note) + data["artifacts"].append(art) + pack.save() + print(f"attached {art['id']}: {path.name} ({size} bytes, sha256 {art['sha256'][:12]}, {args.surface} {args.level})") + return 0 + + +def exhaustion_gaps(surface: str, tried: dict[str, str], lanes: list[str]) -> list[str]: + """Reasons a block is not yet exhausted. Empty means every lane was tried with evidence.""" + gaps = [f"lane {lane} not tried" for lane in lanes if not tried.get(lane)] + if not lanes and len(tried) < 2: + gaps.append("no rig lanes for this surface; log at least two distinct methods tried") + return gaps + + +def cmd_block(args: argparse.Namespace, pack: Pack) -> int: + if not SURFACE_RE.fullmatch(args.surface): + print(f"error: invalid surface {args.surface!r}; use lowercase letters, digits, hyphens or underscores", file=sys.stderr) + return 2 + data = pack.load() + tried: dict[str, str] = {} + for item in args.tried or []: + lane, sep, evidence = item.partition("=") + if not sep or not lane.strip() or not evidence.strip(): + print("error: --tried must look like LANE=EVIDENCE", file=sys.stderr) + return 2 + tried[lane.strip()] = redact_text(evidence.strip()) + gate = args.cls in GATE_CLASSES + if args.human_only and args.cls != "physical" and not gate: + print("error: --human-only is for physical blockers (touch, biometrics, presence)", file=sys.stderr) + return 2 + lanes = rig_lanes(args.rig, args.surface) + if not gate: + gaps = exhaustion_gaps(args.surface, tried, lanes) + if gaps: + for gap in gaps: + print(f"refused: {gap}", file=sys.stderr) + print("refused: exhaust every configured lane before blocking", file=sys.stderr) + return 4 + seq = int(data.get("seq", 0)) + 1 + data["seq"] = seq + block = { + "id": pack.next_id("b", "blocks"), + "seq": seq, + "surface": args.surface, + "class": args.cls, + "reason": redact_text(args.reason), + "tried": tried, + "human_only": bool(args.human_only or gate), + "escalate": False if gate else None, + "head_sha": git_head(args.repo, args.head), + "added": now(), + } + data["blocks"].append(block) + pack.save() + print(f"blocked {block['id']}: {args.surface} ({args.cls}); stop and ask the user" if gate else f"blocked {block['id']}: {args.surface} ({args.cls})") + return 0 + + +def short(sha: str | None) -> str: + return sha[:7] if sha else "none" + + +def level_index(level: str) -> int: + return LEVELS.index(level) + + +def evaluate(pack: Pack, args: argparse.Namespace) -> dict: + data = pack.load() + head = git_head(args.repo, args.head) + required = args.level or data.get("required_level", "L1") + failures: list[str] = [] + rows: list[dict] = [] + reached = -1 + allow_blocked = args.allow_blocked + + def stale(kind: str, rec: dict) -> bool: + if rec.get("head_sha") != head: + failures.append(f"stale {kind} {rec.get('id')}: recorded at {short(rec.get('head_sha'))}, HEAD is {short(head)}") + return True + return False + + effective: dict[str, dict] = {} + for step in data.get("steps", []): + effective[step.get("label", step.get("id"))] = step + for step in effective.values(): + ok = True + if step.get("exit_code") != 0: + failures.append(f"step {step['id']} ({step['label']}) exited {step.get('exit_code')}") + ok = False + log = pack.resolve(step.get("log", "")) + if not log.is_file(): + failures.append(f"step {step['id']}: log is missing") + ok = False + elif sha256_file(log) != step.get("log_sha256"): + failures.append(f"step {step['id']}: log hash mismatch") + ok = False + elif step.get("output_bytes", 0) == 0 and not step.get("allow_empty"): + failures.append(f"step {step['id']} ({step['label']}): empty output; add --allow-empty if expected") + ok = False + if stale("step", step): + ok = False + if ok and step.get("level") in LEVELS: + reached = max(reached, level_index(step["level"])) + rows.append( + { + "id": step["id"], + "level": step.get("level"), + "what": " ".join(step.get("argv", [])), + "result": f"exit {step.get('exit_code')}, {step.get('output_bytes', 0)} B, log sha256 {str(step.get('log_sha256', ''))[:12]}", + "ok": ok, + } + ) + def order_key(rec: dict) -> tuple[int, str]: + return (int(rec.get("seq", 0)), str(rec.get("added", ""))) + + proven_after: dict[str, tuple[int, str]] = {} + for art in data.get("artifacts", []): + ok = True + path = pack.resolve(art.get("path", "")) + if not path.is_file(): + failures.append(f"artifact {art['id']}: file is missing") + ok = False + elif path.stat().st_size == 0: + failures.append(f"artifact {art['id']}: file is empty") + ok = False + elif sha256_file(path) != art.get("sha256"): + failures.append(f"artifact {art['id']}: sha256 mismatch") + ok = False + if art.get("surface") in GATED_SURFACES and data.get("visibility") != "private" and not art.get("redacted"): + failures.append(f"artifact {art['id']}: unredacted {art['surface']} capture on a non-private repo") + ok = False + if stale("artifact", art): + ok = False + if ok: + surface = art.get("surface", "") + key = order_key(art) + if surface not in proven_after or key > proven_after[surface]: + proven_after[surface] = key + if art.get("level") in LEVELS: + reached = max(reached, level_index(art["level"])) + rows.append( + { + "id": art["id"], + "level": art.get("level"), + "what": f"{art.get('surface')} {art.get('kind')} {Path(art.get('path', '')).name}", + "result": f"{art.get('bytes')} B, sha256 {str(art.get('sha256', ''))[:12]}" + (", redacted" if art.get("redacted") else ""), + "ok": ok, + } + ) + blocked: list[dict] = [] + for block in data.get("blocks", []): + latest = proven_after.get(block.get("surface", "")) + if latest is not None and latest > order_key(block): + continue + stale("block", block) + if block.get("class") not in GATE_CLASSES: + lanes = rig_lanes(args.rig, block.get("surface", "")) + for gap in exhaustion_gaps(block.get("surface", ""), block.get("tried", {}), lanes): + failures.append(f"block {block['id']}: {gap}") + blocked.append(block) + if not allow_blocked: + failures.append(f"block {block['id']}: {block['surface']} is blocked ({block.get('class')}): {block.get('reason')}") + if required not in LEVELS: + failures.append(f"required level {required!r} is not one of {', '.join(LEVELS)}") + elif reached < level_index(required): + got = LEVELS[reached] if reached >= 0 else "none" + failures.append(f"level {required} required, reached {got}") + return { + "task": data.get("task", ""), + "head": head, + "required": required, + "reached": LEVELS[reached] if reached >= 0 else None, + "rows": rows, + "blocked": blocked, + "failures": failures, + "ok": not failures, + } + + +def cell(text: object, limit: int = 90) -> str: + out = str(text).replace("|", "\\|").replace("\n", " ") + return out if len(out) <= limit else out[: limit - 1] + "…" + + +def markdown(report: dict) -> str: + status = "PASS" if report["ok"] else "FAIL" + lines = [ + "## Proof packet", + "", + f"**Task:** {cell(report['task'], 200)}", + f"**Head:** `{short(report['head'])}` · **Level:** {report['reached'] or 'none'} reached, {report['required']} required · **{status}**", + "", + "| Id | Level | Evidence | Result |", + "| --- | --- | --- | --- |", + ] + for row in report["rows"]: + what = f"`{cell(row['what'])}`" if row["id"].startswith("s") else cell(row["what"]) + mark = "" if row["ok"] else " ✗" + lines.append(f"| {row['id']} | {row['level']} | {what} | {cell(row['result'])}{mark} |") + if not report["rows"]: + lines.append("| - | - | no evidence recorded | - |") + for block in report["blocked"]: + lines += ["", f"**Blocked:** {block['surface']} ({block.get('class')}): {cell(block.get('reason', ''), 160)}"] + if report["failures"]: + lines += ["", "**Failures:**", *[f"- {cell(f, 200)}" for f in report["failures"]]] + return "\n".join(lines) + "\n" + + +def cmd_verify(args: argparse.Namespace, pack: Pack) -> int: + report = evaluate(pack, args) + if args.markdown: + sys.stdout.write(markdown(report)) + else: + print(f"task: {report['task']}") + print(f"head: {short(report['head'])} level: {report['reached'] or 'none'} reached, {report['required']} required") + for row in report["rows"]: + print(f"{'ok ' if row['ok'] else 'FAIL'} {row['id']} {row['level']} {cell(row['what'], 60)}: {row['result']}") + for block in report["blocked"]: + print(f"blocked {block['id']}: {block['surface']} ({block.get('class')})") + for failure in report["failures"]: + print(f"error: {failure}", file=sys.stderr) + print("verified" if report["ok"] else "NOT verified") + return 0 if report["ok"] else 1 + + +def build_parser() -> argparse.ArgumentParser: + common = argparse.ArgumentParser(add_help=False) + common.add_argument("--dir", type=Path, default=Path(os.environ.get("JSTACK_PROOF_DIR", ".proof")), help="packet folder (default: .proof)") + common.add_argument("--repo", type=Path, default=Path("."), help="git checkout the packet is about (default: .)") + common.add_argument("--head", help="override the git HEAD sha (for non-git work and tests)") + common.add_argument("--rig", type=Path, help="rig file (default: ~/.config/jstack/rig.json)") + + parser = argparse.ArgumentParser(prog="proof-pack.py", description="Build and verify a mechanical proof packet.") + sub = parser.add_subparsers(dest="command", required=True) + + i = sub.add_parser("init", parents=[common], help="start a packet") + i.add_argument("--task", required=True) + i.add_argument("--level", choices=LEVELS, default="L2", help="level the claim needs (default: L2)") + i.add_argument("--visibility", choices=("public", "private", "auto"), default="auto", help="repo visibility; auto asks gh, unknown counts as public") + i.add_argument("--force", action="store_true") + i.set_defaults(func=cmd_init) + + r = sub.add_parser("run", parents=[common], help="run a command and record it") + r.add_argument("--level", choices=LEVELS, default="L1") + r.add_argument("--label", help="step name; a later step with the same label replaces an earlier one") + r.add_argument("--timeout", type=int, default=900) + r.add_argument("--cwd", type=Path) + r.add_argument("--allow-empty", action="store_true", help="empty output is expected") + r.add_argument("cmd", nargs=argparse.REMAINDER, help="-- COMMAND [ARGS...]") + r.set_defaults(func=cmd_run) + + a = sub.add_parser("attach", parents=[common], help="record an artifact file") + a.add_argument("path") + a.add_argument("--surface", required=True) + a.add_argument("--level", choices=LEVELS, default="L3") + a.add_argument("--kind", default="screenshot") + a.add_argument("--redacted", action="store_true", help="the file has no credentials, codes or private windows") + a.add_argument("--note") + a.set_defaults(func=cmd_attach) + + b = sub.add_parser("block", parents=[common], help="record a blocked surface") + b.add_argument("--surface", required=True) + b.add_argument("--reason", required=True) + b.add_argument("--class", dest="cls", choices=BLOCK_CLASSES, default="other") + b.add_argument("--tried", action="append", metavar="LANE=EVIDENCE", help="a lane tried, with what happened (repeatable)") + b.add_argument("--human-only", action="store_true", help="physical blocker only") + b.set_defaults(func=cmd_block) + + v = sub.add_parser("verify", parents=[common], help="re-check the packet") + v.add_argument("--level", choices=LEVELS, help="override the required level") + v.add_argument("--allow-blocked", action="store_true", help="list blocked surfaces without failing") + v.add_argument("--markdown", action="store_true", help="print a PR-ready summary") + v.set_defaults(func=cmd_verify) + return parser + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + return args.func(args, Pack(args.dir)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_install.py b/tests/test_install.py index 63709b6..ff757e6 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -38,8 +38,8 @@ def entries(folder: Path) -> list[str]: return sorted(p.name for p in folder.iterdir()) if folder.exists() else [] -def test_eighteen_skills_and_deps_exist(): - assert len(ALL) == 18 +def test_twenty_skills_and_deps_exist(): + assert len(ALL) == 20 for name, deps in install.DEPS.items(): assert name in ALL assert set(deps) <= set(ALL), name diff --git a/tests/test_prove_and_rig.py b/tests/test_prove_and_rig.py new file mode 100644 index 0000000..56fda76 --- /dev/null +++ b/tests/test_prove_and_rig.py @@ -0,0 +1,666 @@ +"""Tests for the prove skill, the jstack-setup rig tool and install-time rig rendering. + +Secrets and private-looking strings are built at run time so no literal trips a scanner. +""" + +from __future__ import annotations + +import importlib.machinery +import importlib.util +import json +import os +import stat +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +SCRIPTS = ROOT / "scripts" +PACK = ROOT / "skills" / "prove" / "scripts" / "proof-pack.py" +RIG = ROOT / "skills" / "jstack-setup" / "scripts" / "jstack-rig.py" + + +def load(name: str, path: Path): + loader = importlib.machinery.SourceFileLoader(name, str(path)) + spec = importlib.util.spec_from_loader(name, loader) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + loader.exec_module(module) + return module + + +install = load("jstack_install_rig", SCRIPTS / "install.py") +privacy = load("jstack_privacy_rig", SCRIPTS / "check_privacy.py") +validator = load("jstack_validate_rig", SCRIPTS / "validate_skills.py") +rigtool = load("jstack_rig_tool", RIG) +proof = load("jstack_proof_pack", PACK) + +HEAD = "a" * 40 +OTHER = "b" * 40 + +# Built at run time, never written as literals. +FAKE_TOKEN = "gh" + "p_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8" +FAKE_HOME = "/" + "home" + "/" + "someone" +FAKE_TAILNET = "box." + "tail1234" + "." + "ts" + "." + "net" +FAKE_CGNAT = "100" + ".101.102.103" + + +def cli(script: Path, *args: str, cwd: Path | None = None, env: dict[str, str] | None = None): + merged = {**os.environ, **(env or {})} + return subprocess.run( + [sys.executable, "-I", str(script), *map(str, args)], + cwd=cwd, + env=merged, + capture_output=True, + text=True, + check=False, + ) + + +# proof-pack --------------------------------------------------------------- + + +@pytest.fixture +def work(tmp_path: Path) -> Path: + w = tmp_path / "work" + w.mkdir() + return w + + +def pp(work: Path, *args: str, head: str = HEAD, rig: Path | None = None): + extra = ["--dir", str(work / ".proof"), "--head", head] + if rig is not None: + extra += ["--rig", str(rig)] + sub, rest = args[0], list(args[1:]) + if sub == "run" and "--" in rest: + i = rest.index("--") + return cli(PACK, sub, *rest[:i], *extra, *rest[i:], cwd=work) + return cli(PACK, sub, *rest, *extra, cwd=work) + + +def no_rig(work: Path) -> Path: + return work / "absent-rig.json" + + +def make_rig(path: Path, lanes: dict[str, list[str]] | None = None) -> Path: + path.write_text(json.dumps({"schema": "jstack.rig/1", "lanes": lanes or {}})) + path.chmod(0o600) + return path + + +def test_lifecycle_passes_and_prints_markdown(work: Path): + rig = no_rig(work) + assert pp(work, "init", "--task", "demo claim", "--level", "L3", "--visibility", "public", rig=rig).returncode == 0 + run = pp(work, "run", "--level", "L1", "--label", "tests", "--", sys.executable, "-c", "print('3 passed')", rig=rig) + assert run.returncode == 0 and "3 passed" in run.stdout + shot = work / "shot.png" + shot.write_bytes(b"not-really-a-png") + assert pp(work, "attach", str(shot), "--surface", "web", "--level", "L3", rig=rig).returncode == 0 + ver = pp(work, "verify", rig=rig) + assert ver.returncode == 0 and "verified" in ver.stdout + md = pp(work, "verify", "--markdown", rig=rig) + assert md.returncode == 0 + assert "## Proof packet" in md.stdout and "PASS" in md.stdout and "| s1 | L1 |" in md.stdout and "| a1 | L3 |" in md.stdout + + +def test_stale_head_is_rejected(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L1", "--visibility", "public", rig=rig) + pp(work, "run", "--label", "tests", "--", sys.executable, "-c", "print('ok')", rig=rig) + assert pp(work, "verify", rig=rig).returncode == 0 + stale = pp(work, "verify", head=OTHER, rig=rig) + assert stale.returncode == 1 + assert "stale step" in stale.stderr + + +def test_failing_step_and_empty_output_are_rejected(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L1", "--visibility", "public", rig=rig) + pp(work, "run", "--label", "bad", "--", sys.executable, "-c", "raise SystemExit(3)", rig=rig) + out = pp(work, "verify", rig=rig) + assert out.returncode == 1 and "exited 3" in out.stderr + pp(work, "run", "--label", "bad", "--", sys.executable, "-c", "pass", rig=rig) + quiet = pp(work, "verify", rig=rig) + assert quiet.returncode == 1 and "empty output" in quiet.stderr + pp(work, "run", "--label", "bad", "--allow-empty", "--", sys.executable, "-c", "pass", rig=rig) + assert pp(work, "verify", rig=rig).returncode == 0 + + +def test_missing_and_tampered_artifacts_are_rejected(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L3", "--visibility", "public", rig=rig) + shot = work / "shot.png" + shot.write_bytes(b"first") + assert pp(work, "attach", str(shot), "--surface", "web", rig=rig).returncode == 0 + shot.write_bytes(b"second") + assert "sha256 mismatch" in pp(work, "verify", rig=rig).stderr + shot.unlink() + assert "file is missing" in pp(work, "verify", rig=rig).stderr + empty = work / "empty.png" + empty.write_bytes(b"") + refused = pp(work, "attach", str(empty), "--surface", "web", rig=rig) + assert refused.returncode == 2 and "empty" in refused.stderr + + +def test_level_below_required_fails(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L3", "--visibility", "public", rig=rig) + pp(work, "run", "--level", "L1", "--label", "tests", "--", sys.executable, "-c", "print(1)", rig=rig) + out = pp(work, "verify", rig=rig) + assert out.returncode == 1 and "level L3 required, reached L1" in out.stderr + assert pp(work, "verify", "--level", "L1", rig=rig).returncode == 0 + + +def test_gated_surface_needs_redaction_on_public_repo(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L3", "--visibility", "public", rig=rig) + shot = work / "desk.png" + shot.write_bytes(b"pixels") + for surface in ("auth", "native_gui", "vnc", "desktop"): + assert pp(work, "attach", str(shot), "--surface", surface, rig=rig).returncode == 3, surface + assert pp(work, "attach", str(shot), "--surface", "auth", "--redacted", rig=rig).returncode == 0 + + +def test_gated_surface_is_allowed_on_private_repo(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L3", "--visibility", "private", rig=rig) + shot = work / "desk.png" + shot.write_bytes(b"pixels") + assert pp(work, "attach", str(shot), "--surface", "auth", rig=rig).returncode == 0 + + +def test_block_requires_every_rig_lane(work: Path): + rig = make_rig(work / "rig.json", {"vnc": ["viewer-a", "viewer-b"]}) + pp(work, "init", "--task", "t", "--level", "L1", "--visibility", "public", rig=rig) + base = ["block", "--surface", "vnc", "--reason", "needs a hardware touch", "--class", "physical", "--human-only"] + refused = pp(work, *base, "--tried", "viewer-a=connected, key prompt", rig=rig) + assert refused.returncode == 4 and "lane viewer-b not tried" in refused.stderr + done = pp(work, *base, "--tried", "viewer-a=connected, key prompt", "--tried", "viewer-b=same prompt", rig=rig) + assert done.returncode == 0 and "blocked b1" in done.stdout + + +def test_block_without_lanes_needs_two_methods(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L1", "--visibility", "public", rig=rig) + base = ["block", "--surface", "usb", "--reason", "plug in a device", "--class", "physical", "--human-only"] + assert pp(work, *base, "--tried", "one=nothing", rig=rig).returncode == 4 + assert pp(work, *base, "--tried", "one=nothing", "--tried", "two=nothing", rig=rig).returncode == 0 + + +def test_unexhausted_block_fails_verify_even_if_edited_in(work: Path): + rig = make_rig(work / "rig.json", {"vnc": ["viewer-a"]}) + pp(work, "init", "--task", "t", "--level", "L1", "--visibility", "public", rig=rig) + pp(work, "run", "--label", "tests", "--", sys.executable, "-c", "print(1)", rig=rig) + pack = work / ".proof" / "pack.json" + data = json.loads(pack.read_text()) + data["blocks"].append( + {"id": "b1", "surface": "vnc", "class": "physical", "reason": "x", "tried": {}, "human_only": True, "head_sha": HEAD} + ) + pack.write_text(json.dumps(data)) + out = pp(work, "verify", rig=rig) + assert out.returncode == 1 and "lane viewer-a not tried" in out.stderr + assert pp(work, "verify", "--allow-blocked", rig=rig).returncode == 1 # exhaustion is still checked + + +@pytest.mark.parametrize("cls", ["captcha", "anti-bot", "2fa", "access-denied", "approval"]) +def test_gate_classes_stop_and_ask_without_exhaustion(work: Path, cls: str): + rig = make_rig(work / "rig.json", {"web": ["tool-a", "tool-b"]}) + pp(work, "init", "--task", "t", "--level", "L1", "--visibility", "public", rig=rig) + out = pp(work, "block", "--surface", "web", "--reason", "a gate", "--class", cls, rig=rig) + assert out.returncode == 0 and "stop and ask the user" in out.stdout + block = json.loads((work / ".proof" / "pack.json").read_text())["blocks"][0] + assert block["escalate"] is False and block["human_only"] is True + + +def test_human_only_rejects_non_physical_other_class(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "t", "--level", "L1", "--visibility", "public", rig=rig) + out = pp(work, "block", "--surface", "web", "--reason", "slow", "--class", "other", "--human-only", rig=rig) + assert out.returncode == 2 + + +def test_redaction_helpers(): + text = " ".join([FAKE_TOKEN, FAKE_HOME + "/project", FAKE_TAILNET, FAKE_CGNAT, "Bearer abcdefghijklmnop"]) + out = proof.redact_text(text) + for leaked in (FAKE_TOKEN, FAKE_HOME, FAKE_TAILNET, FAKE_CGNAT, "abcdefghijklmnop"): + assert leaked not in out + assert "~/project" in out and "" in out and "" in out + argv = proof.redact_argv(["tool", "--token", "hunter2", "--api-key=hunter3", "SECRET_KEY=hunter4", "--name", "ok"]) + joined = " ".join(argv) + assert "hunter" not in joined and "--name ok" in joined + + +def test_run_log_and_packet_hold_no_secrets(work: Path): + rig = no_rig(work) + pp(work, "init", "--task", "uses " + FAKE_TOKEN, "--level", "L1", "--visibility", "public", rig=rig) + code = f"print({FAKE_TOKEN!r}); print({FAKE_HOME!r} + '/x')" + pp(work, "run", "--label", "leak", "--", sys.executable, "-c", code, rig=rig) + blob = (work / ".proof" / "pack.json").read_text() + "".join(p.read_text() for p in (work / ".proof" / "logs").iterdir()) + assert FAKE_TOKEN not in blob and FAKE_HOME not in blob + + +def test_init_refuses_to_overwrite_without_force(work: Path): + rig = no_rig(work) + assert pp(work, "init", "--task", "t", "--visibility", "public", rig=rig).returncode == 0 + assert pp(work, "init", "--task", "t", "--visibility", "public", rig=rig).returncode == 2 + assert pp(work, "init", "--task", "t", "--visibility", "public", "--force", rig=rig).returncode == 0 + + +# jstack-rig --------------------------------------------------------------- + + +def good_rig() -> dict: + return { + "schema": "jstack.rig/1", + "harnesses": ["claude"], + "endpoints": {"ollama": "http://127.0.0.1:11434"}, + "lanes": {"web": ["agent-browser"], "ssh": ["ssh"]}, + "media_uploader": "upload-tool", + "fallback": {"provider": "prov", "model": "mod-1"}, + } + + +def test_example_rig_has_schema_and_is_not_a_forbidden_file(): + example = json.loads((ROOT / "rig.example.json").read_text()) + assert example["schema"] == "jstack.rig/1" + assert set(example) <= set(rigtool.TOP_KEYS) + assert privacy.forbidden_file("rig.example.json") is None + + +def test_validate_accepts_good_rig(): + assert rigtool.validate(good_rig()) == [] + + +@pytest.mark.parametrize( + "mutate", + [ + lambda r: r.update(schema="other/1"), + lambda r: r.update(surprise=True), + lambda r: r["lanes"].update({"Bad Lane": ["x"]}), + lambda r: r["lanes"].update({"web": "not-a-list"}), + lambda r: r.update(fallback={"provider": "only"}), + lambda r: r.update(endpoints={"x": "not a url"}), + ], +) +def test_validate_rejects_bad_shapes(mutate): + rig = good_rig() + mutate(rig) + assert rigtool.validate(rig) + + +@pytest.mark.parametrize( + "field", + ["uploader", "tool", "endpoint", "model"], +) +def test_validate_rejects_secret_values_without_echoing_them(field: str): + rig = good_rig() + secret = FAKE_TOKEN + if field == "uploader": + rig["media_uploader"] = "upload --key " + secret + elif field == "tool": + rig["lanes"]["web"] = [secret] + elif field == "endpoint": + rig["endpoints"]["ollama"] = "http://user:" + "pw" + "@127.0.0.1:1" + else: + rig["fallback"]["model"] = secret + problems = rigtool.validate(rig) + assert problems + assert secret not in " ".join(problems) and "pw@" not in " ".join(problems) + + +def test_write_creates_0600_file_and_check_passes(tmp_path: Path): + path = tmp_path / "cfg" / "rig.json" + out = cli(RIG, "write", "--path", path, "--lane", "web=agent-browser", "--fallback", "prov/mod", "--uploader", "upload-tool") + assert out.returncode == 0, out.stderr + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert json.loads(path.read_text())["fallback"] == {"provider": "prov", "model": "mod"} + assert cli(RIG, "check", "--path", path).returncode == 0 + + +def test_write_refuses_secret_and_leaves_no_file(tmp_path: Path): + path = tmp_path / "rig.json" + out = cli(RIG, "write", "--path", path, "--uploader", "up --token " + FAKE_TOKEN) + assert out.returncode == 2 + assert FAKE_TOKEN not in out.stdout + out.stderr + assert not path.exists() + + +def test_write_dry_run_writes_nothing(tmp_path: Path): + path = tmp_path / "rig.json" + out = cli(RIG, "write", "--path", path, "--lane", "web=agent-browser", "--dry-run") + assert out.returncode == 0 and not path.exists() and "agent-browser" in out.stdout + + +def test_check_flags_loose_mode_and_invalid_json(tmp_path: Path): + path = tmp_path / "rig.json" + path.write_text(json.dumps(good_rig())) + path.chmod(0o644) + assert cli(RIG, "check", "--path", path).returncode == 1 + path.chmod(0o600) + assert cli(RIG, "check", "--path", path).returncode == 0 + path.write_text("{ nope") + bad = cli(RIG, "check", "--path", path) + assert bad.returncode == 1 and "not valid JSON" in bad.stderr + + +def test_discover_is_read_only_json_and_human(tmp_path: Path): + home = tmp_path / "home" + home.mkdir() + out = cli(RIG, "discover", "--no-net", "--no-gh", "--home", home) + assert out.returncode == 0 + data = json.loads(out.stdout) + assert "lanes" in data and "harnesses" in data + assert FAKE_HOME not in out.stdout + human = cli(RIG, "discover", "--human", "--no-net", "--no-gh", "--home", home) + assert human.returncode == 0 and "lane" in human.stdout and "tools found" in human.stdout + assert list(home.iterdir()) == [] + + +# install: slot rendering -------------------------------------------------- + + +def run_install(home: Path, *args: str) -> int: + return install.run(["--home", str(home), *args], environ={}) + + +@pytest.fixture +def home(tmp_path: Path) -> Path: + h = tmp_path / "home" + (h / ".claude").mkdir(parents=True) + return h + + +@pytest.fixture +def rigfile(tmp_path: Path) -> Path: + return make_rig_full(tmp_path / "rig.json") + + +def make_rig_full(path: Path) -> Path: + path.write_text(json.dumps(good_rig())) + path.chmod(0o600) + return path + + +def rendered(tmp_path: Path) -> Path: + return tmp_path / "rendered" + + +def test_stock_install_without_rig_has_no_rendering(home: Path, tmp_path: Path, capsys): + # No --rig and no default rig file under the fake home: stock symlink to the checkout. + assert run_install(home, "--client", "claude", "--only", "prove", "--no-deps", "--render-dir", str(rendered(tmp_path))) == 0 + entry = home / ".claude" / "skills" / "prove" + assert entry.is_symlink() and entry.resolve() == (ROOT / "skills" / "prove").resolve() + assert not rendered(tmp_path).exists() + assert "rendered" not in capsys.readouterr().out + + +def test_install_renders_slot_from_rig(home: Path, tmp_path: Path, rigfile: Path): + args = ["--client", "claude", "--only", "prove", "--no-deps", "--rig", str(rigfile), "--render-dir", str(rendered(tmp_path))] + assert run_install(home, *args) == 0 + entry = home / ".claude" / "skills" / "prove" + text = (entry / "SKILL.md").read_text() + assert "Fallback model: `prov/mod-1`" in text and "Lane web: `agent-browser`" in text and "Media uploader: `upload-tool`" in text + assert "Stock defaults, no local rig" not in text + assert (entry / "references" / "surfaces.md").is_file() + assert (entry / "scripts" / "proof-pack.py").is_file() + stock = (ROOT / "skills" / "prove" / "SKILL.md").read_text() + assert "Stock defaults, no local rig" in stock # the repo copy stays stock + marker = json.loads((rendered(tmp_path) / "prove" / ".jstack-install.json").read_text()) + assert marker["rendered"] is True + assert {"source_digest", "rig_digest", "rendered_digest"} <= set(marker) + + +def test_overlay_cap_falls_back_to_stock(home: Path, tmp_path: Path, capsys): + big = good_rig() + big["lanes"] = {f"lane{i:02d}": [f"tool-{i:02d}-{j:02d}-padding-padding" for j in range(8)] for i in range(12)} + path = tmp_path / "rig.json" + path.write_text(json.dumps(big)) + path.chmod(0o600) + code = run_install( + home, "--client", "claude", "--only", "prove", "--no-deps", "--rig", str(path), "--render-dir", str(rendered(tmp_path)) + ) + err = capsys.readouterr().err + assert code == 1 and "1024-byte cap" in err + entry = home / ".claude" / "skills" / "prove" + assert "Stock defaults, no local rig" in (entry / "SKILL.md").read_text() + + +def test_render_skill_raises_over_cap(tmp_path: Path): + big = good_rig() + big["lanes"] = {f"lane{i:02d}": [f"tool-{i:02d}-{j:02d}-padding-padding" for j in range(8)] for i in range(12)} + with pytest.raises(ValueError, match="cap"): + install.render_skill("prove", big, install.rig_digest(big), tmp_path / "r") + + +def test_check_reports_drift_when_rig_changes_and_reconcile_repairs(home: Path, tmp_path: Path, rigfile: Path): + args = ["--client", "claude", "--only", "prove", "--no-deps", "--rig", str(rigfile), "--render-dir", str(rendered(tmp_path))] + assert run_install(home, *args) == 0 + assert run_install(home, "--check", *args) == 0 + + changed = good_rig() + changed["fallback"] = {"provider": "prov", "model": "mod-2"} + rigfile.write_text(json.dumps(changed)) + assert run_install(home, "--check", *args) == 1 # drift, and --check never rewrites + assert "mod-1" in (home / ".claude" / "skills" / "prove" / "SKILL.md").read_text() + + assert run_install(home, "--reconcile", *args) == 0 + text = (home / ".claude" / "skills" / "prove" / "SKILL.md").read_text() + assert "mod-2" in text and "mod-1" not in text + assert run_install(home, "--check", *args) == 0 + + +def test_check_reports_edited_rendered_folder(home: Path, tmp_path: Path, rigfile: Path, capsys): + args = ["--client", "claude", "--only", "prove", "--no-deps", "--rig", str(rigfile), "--render-dir", str(rendered(tmp_path))] + assert run_install(home, *args) == 0 + (rendered(tmp_path) / "prove" / "SKILL.md").write_text("edited\n") + capsys.readouterr() + assert run_install(home, "--check", *args) == 1 + assert "drift (rendered folder edited)" in capsys.readouterr().out + + +def test_reconcile_touches_only_owned_entries(home: Path, tmp_path: Path, rigfile: Path): + skills = home / ".claude" / "skills" + (skills / "prove").mkdir(parents=True) + (skills / "prove" / "SKILL.md").write_text("mine\n") + args = ["--client", "claude", "--only", "prove", "--no-deps", "--rig", str(rigfile), "--render-dir", str(rendered(tmp_path))] + assert run_install(home, "--reconcile", *args) == 0 + assert (skills / "prove" / "SKILL.md").read_text() == "mine\n" + assert not skills.joinpath("hindsight").exists() + + +def test_reconcile_installs_nothing_new(home: Path, tmp_path: Path, rigfile: Path): + args = ["--client", "claude", "--rig", str(rigfile), "--render-dir", str(rendered(tmp_path))] + assert run_install(home, "--reconcile", *args) == 0 + assert not (home / ".claude" / "skills").exists() + + +def test_uninstall_removes_rendered_link(home: Path, tmp_path: Path, rigfile: Path): + args = ["--client", "claude", "--only", "prove", "--no-deps", "--rig", str(rigfile), "--render-dir", str(rendered(tmp_path))] + assert run_install(home, *args) == 0 + assert run_install(home, "--uninstall", "--client", "claude", "--only", "prove") == 0 + assert not (home / ".claude" / "skills" / "prove").exists() + + +def test_copy_mode_renders_and_checks_ok(home: Path, tmp_path: Path, rigfile: Path): + args = ["--client", "claude", "--only", "prove", "--no-deps", "--mode", "copy", "--rig", str(rigfile), "--render-dir", str(rendered(tmp_path))] + assert run_install(home, *args) == 0 + entry = home / ".claude" / "skills" / "prove" + assert not entry.is_symlink() and "Fallback model" in (entry / "SKILL.md").read_text() + assert run_install(home, "--check", *args) == 0 + + +def test_invalid_rig_stops_the_install(home: Path, tmp_path: Path): + bad = tmp_path / "rig.json" + bad.write_text("{ not json") + with pytest.raises(SystemExit): + run_install(home, "--client", "claude", "--only", "prove", "--no-deps", "--rig", str(bad)) + assert not (home / ".claude" / "skills").exists() + + +def test_deps_and_exclusive_flags(home: Path, tmp_path: Path): + assert install.DEPS["jstack-setup"] == ("prove",) + assert install.resolve(["jstack-setup"]) == ["jstack-setup", "prove"] + with pytest.raises(SystemExit): + run_install(home, "--check", "--reconcile") + with pytest.raises(SystemExit): + run_install(home, "--install-hook", "--reconcile") + + +def test_install_hook_writes_and_never_clobbers(home: Path, tmp_path: Path, capsys): + hooks = tmp_path / "hooks" + assert run_install(home, "--client", "claude", "--only", "prove", "--no-deps", "--install-hook", "--hooks-dir", str(hooks)) == 0 + for name in ("post-merge", "post-checkout"): + hook = hooks / name + assert hook.is_file() and os.access(hook, os.X_OK) + assert "--reconcile" in hook.read_text() and install.HOOK_MARK in hook.read_text() + # Re-running updates its own hooks. + assert run_install(home, "--client", "claude", "--only", "prove", "--no-deps", "--install-hook", "--hooks-dir", str(hooks)) == 0 + (hooks / "post-merge").write_text("#!/bin/sh\necho theirs\n") + capsys.readouterr() + code = run_install(home, "--client", "claude", "--only", "prove", "--no-deps", "--install-hook", "--hooks-dir", str(hooks)) + assert code == 1 and "echo theirs" in (hooks / "post-merge").read_text() + assert "skipped" in capsys.readouterr().err + + +# slot syntax and privacy rules ------------------------------------------- + + +def test_render_text_only_swaps_known_slot_and_keeps_unknown(): + text = "a\n\nstock\n\nb\nx\n" + out = install.render_text(text, good_rig()) + assert "stock" not in out and "prov/mod-1" in out + assert "x" in out + assert install.render_text(text, {"schema": "jstack.rig/1"}) == text # empty rig keeps stock text + + +def test_validator_checks_slot_pairs(tmp_path: Path): + ok = tmp_path / "ok" + ok.mkdir() + (ok / "SKILL.md").write_text("\nx\n\n") + assert validator.check_slots(ok) == [] + for body in ( + "\nno close\n", + "\n\n", + "\n", + ): + bad = tmp_path / "bad" + bad.mkdir(exist_ok=True) + (bad / "SKILL.md").write_text(body) + assert validator.check_slots(bad), body + + +@pytest.mark.parametrize("name", ["rig.json", "profile.toml", "sub/dir/rig.json", "x/profile.toml"]) +def test_privacy_blocks_private_config_files(name: str): + assert privacy.forbidden_file(name) + + +@pytest.mark.parametrize("name", ["rig.example.json", "profile.example.toml", "skills/jstack-setup/rig.example.json"]) +def test_privacy_allows_example_files(name: str): + assert privacy.forbidden_file(name) is None + + +def test_proof_pack_redacts_json_secrets(tmp_path: Path): + pack = tmp_path / "pack" + assert cli(PACK, "init", "--dir", pack, "--task", "json-redact", "--head", "abc1234").returncode == 0 + out = cli( + PACK, + "run", + "--dir", + pack, + "--head", + "abc1234", + "--label", + "json", + "--", + sys.executable, + "-c", + 'print(\'{"password": "hunter2", "token": "opaque-value"}\')', + ) + assert out.returncode == 0 + assert "hunter2" not in out.stdout and "opaque-value" not in out.stdout + data = json.loads((pack / "pack.json").read_text()) + log = (pack / "logs" / Path(data["steps"][0]["log"]).name).read_text() + assert "hunter2" not in log and "opaque-value" not in log + assert '"password": "[REDACTED]"' in log and '"token": "[REDACTED]"' in log + + +def test_later_gate_blocker_stays_active_after_earlier_artifact(tmp_path: Path): + pack = tmp_path / "pack" + shot = tmp_path / "shot.png" + shot.write_bytes(b"\x89PNG\r\n\x1a\n1234") + assert cli(PACK, "init", "--dir", pack, "--task", "gate-order", "--head", "abc1234", "--level", "L3").returncode == 0 + assert cli(PACK, "attach", "--dir", pack, "--head", "abc1234", "--surface", "web", "--level", "L3", "--kind", "screenshot", shot).returncode == 0 + assert cli(PACK, "block", "--dir", pack, "--head", "abc1234", "--surface", "web", "--class", "access-denied", "--reason", "403 after login").returncode == 0 + bad = cli(PACK, "verify", "--dir", pack, "--head", "abc1234") + assert bad.returncode == 1 and "access-denied" in bad.stdout + bad.stderr + # A subsequent qualifying artifact after the blocker resolves it. + assert cli(PACK, "attach", "--dir", pack, "--head", "abc1234", "--surface", "web", "--level", "L3", "--kind", "screenshot", shot).returncode == 0 + assert cli(PACK, "verify", "--dir", pack, "--head", "abc1234").returncode == 0 + + +def test_install_hook_preserves_custom_rig_and_render_dir(home: Path, tmp_path: Path, rigfile: Path): + hooks = tmp_path / "hooks" + rdir = rendered(tmp_path) + args = [ + "--client", + "claude", + "--only", + "prove", + "--no-deps", + "--rig", + str(rigfile), + "--render-dir", + str(rdir), + "--install-hook", + "--hooks-dir", + str(hooks), + ] + assert run_install(home, *args) == 0 + hook = hooks / "post-merge" + body = hook.read_text() + assert "--rig" in body and str(rigfile.resolve()) in body and "--render-dir" in body and str(rdir.resolve()) in body + proc = subprocess.run(["sh", str(hook)], check=False) + assert proc.returncode == 0 + assert "Fallback model: `prov/mod-1`" in (home / ".claude" / "skills" / "prove" / "SKILL.md").read_text() + + +def test_sol_loop_regressions_rig_and_pack(tmp_path: Path): + # S1: legitimate >=32-char hyphen/slash model IDs pass looks_secret; S6: trailing newline fails. + rig = good_rig() + rig["fallback"] = {"provider": "opencode", "model": "openrouter/anthropic/claude-sonnet-4-5-20250929"} + assert rigtool.validate(rig) == [] + bad_nl = good_rig() + bad_nl["lanes"] = {"web": ["agent-browser\n"]} + assert rigtool.validate(bad_nl) + # S8: --lane NAME= clears a lane cleanly and malformed pair exits 2. + rig_path = tmp_path / "rig.json" + assert cli(RIG, "write", "--path", rig_path, "--lane", "vnc=wayvnc", "--lane", "web=agent-browser").returncode == 0 + assert cli(RIG, "write", "--path", rig_path, "--merge", "--lane", "vnc=").returncode == 0 + assert "vnc" not in json.loads(rig_path.read_text())["lanes"] + assert cli(RIG, "write", "--path", rig_path, "--endpoint", "broken").returncode == 2 + # S2, S3, S4, S5: slash label, prefixed secret/PEM/uppercase ts host, surface validation, stale block. + pack = tmp_path / "pack" + assert cli(PACK, "init", "--dir", pack, "--task", "sol", "--head", "aaa1111").returncode == 0 + out = cli(PACK, "run", "--dir", pack, "--head", "aaa1111", "--label", "api/auth", "--", sys.executable, "-c", 'print("ok")') + assert out.returncode == 0 + fake_tailnet = "BOX.TAIL99." + "TS.NET" + red = proof.redact_text( + f'{{"access_token": "sec123"}} GITHUB_TOKEN=tok456 {fake_tailnet}\n' + "-----BEGIN RSA PRIVATE KEY-----\nBODYSECRET\n-----END RSA PRIVATE KEY-----" + ) + for leaked in ("sec123", "tok456", "BODYSECRET", "TAIL99"): + assert leaked not in red + shot = tmp_path / "s.png" + shot.write_bytes(b"\x89PNG\r\n\x1a\n1234") + assert cli(PACK, "attach", "--dir", pack, "--head", "aaa1111", "--surface", "AUTH", "--level", "L3", "--kind", "screenshot", shot).returncode == 2 + assert cli(PACK, "block", "--dir", pack, "--head", "aaa1111", "--surface", "VNC", "--class", "physical", "--reason", "x", "--tried", "a=1", "--tried", "b=2").returncode == 2 + assert cli(PACK, "block", "--dir", pack, "--head", "aaa1111", "--surface", "web", "--class", "access-denied", "--reason", "403").returncode == 0 + stale_check = cli(PACK, "verify", "--dir", pack, "--head", "bbb2222", "--allow-blocked") + assert stale_check.returncode == 1 and "stale block" in stale_check.stdout + stale_check.stderr + # S7: inverted slots fail check_slots. + inv = tmp_path / "inv" + inv.mkdir() + (inv / "SKILL.md").write_text("\nx\n\n") + assert validator.check_slots(inv) diff --git a/tests/test_validate_skills.py b/tests/test_validate_skills.py index 20f1463..d2676d1 100644 --- a/tests/test_validate_skills.py +++ b/tests/test_validate_skills.py @@ -53,7 +53,7 @@ def errors(root: Path) -> list[str]: def test_repo_is_valid(): assert vs.validate(ROOT) == [] - assert len(vs.skill_dirs(ROOT)) == 18 + assert len(vs.skill_dirs(ROOT)) == 20 def test_cli_ok(): @@ -61,7 +61,7 @@ def test_cli_ok(): [sys.executable, str(ROOT / "scripts" / "validate_skills.py")], capture_output=True, text=True, check=False ) assert proc.returncode == 0, proc.stderr - assert "18 skills valid" in proc.stdout + assert "20 skills valid" in proc.stdout def test_parser_matches_pyyaml():