From 744a81fa7bf1a0d06d02e5beeae85975ca74b5a6 Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya <1631326+fakoli@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:31:49 -0800 Subject: [PATCH] feat(pi-coordination): add Antigravity support and hybrid parallel multi-Pi test runner --- .../.antigravity-plugin/plugin.json | 16 + .../.claude-plugin/plugin.json | 4 +- .../.codex-plugin/plugin.json | 4 +- plugins/codex-pi-coordination/package.json | 6 +- .../codex-pi-coordination/scripts/fanout.py | 1137 +++++++++++++++++ .../skills/pi-parallel-test/SKILL.md | 63 + .../pi-parallel-test/agents/openai.yaml | 4 + .../references/batch-contract.md | 75 ++ .../tests/test_fanout.py | 286 +++++ 9 files changed, 1588 insertions(+), 7 deletions(-) create mode 100644 plugins/codex-pi-coordination/.antigravity-plugin/plugin.json create mode 100644 plugins/codex-pi-coordination/scripts/fanout.py create mode 100644 plugins/codex-pi-coordination/skills/pi-parallel-test/SKILL.md create mode 100644 plugins/codex-pi-coordination/skills/pi-parallel-test/agents/openai.yaml create mode 100644 plugins/codex-pi-coordination/skills/pi-parallel-test/references/batch-contract.md create mode 100644 plugins/codex-pi-coordination/tests/test_fanout.py diff --git a/plugins/codex-pi-coordination/.antigravity-plugin/plugin.json b/plugins/codex-pi-coordination/.antigravity-plugin/plugin.json new file mode 100644 index 0000000..fce2236 --- /dev/null +++ b/plugins/codex-pi-coordination/.antigravity-plugin/plugin.json @@ -0,0 +1,16 @@ +{ + "name": "codex-pi-coordination", + "displayName": "Pi Coordination & Parallel Testing", + "version": "0.4.0", + "description": "Coordinate bounded Pi tasks inside NVIDIA OpenShell and launch parallel multi-Pi test agents across OpenShell sandbox pools or isolated local Pi workspaces.", + "author": { + "name": "Fakoli", + "url": "https://github.com/fakoli" + }, + "repository": "https://github.com/fakoli/agent-plugins", + "suggestedPrompts": [ + "Discover available Pi and OpenShell backends on this host", + "Launch 4 parallel isolated Pi agents to test this task and aggregate receipts", + "Delegate a bounded task to Pi in an owned OpenShell sandbox" + ] +} diff --git a/plugins/codex-pi-coordination/.claude-plugin/plugin.json b/plugins/codex-pi-coordination/.claude-plugin/plugin.json index 3febca2..19ccc4d 100644 --- a/plugins/codex-pi-coordination/.claude-plugin/plugin.json +++ b/plugins/codex-pi-coordination/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "codex-pi-coordination", - "version": "0.3.0", - "description": "Coordinate bounded tasks, saved Pi conversations and model capability discovery inside NVIDIA OpenShell.", + "version": "0.4.0", + "description": "Coordinate bounded Pi tasks inside NVIDIA OpenShell and launch parallel multi-Pi test agents across OpenShell sandbox pools or isolated local Pi workspaces.", "author": { "name": "Fakoli", "url": "https://github.com/fakoli" diff --git a/plugins/codex-pi-coordination/.codex-plugin/plugin.json b/plugins/codex-pi-coordination/.codex-plugin/plugin.json index c137996..0f71a5e 100644 --- a/plugins/codex-pi-coordination/.codex-plugin/plugin.json +++ b/plugins/codex-pi-coordination/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "codex-pi-coordination", - "version": "0.3.0", - "description": "Coordinate bounded tasks, saved Pi conversations and model capability discovery inside NVIDIA OpenShell.", + "version": "0.4.0", + "description": "Coordinate bounded Pi tasks inside NVIDIA OpenShell and launch parallel multi-Pi test agents across OpenShell sandbox pools or isolated local Pi workspaces.", "author": { "name": "Fakoli", "url": "https://github.com/fakoli" diff --git a/plugins/codex-pi-coordination/package.json b/plugins/codex-pi-coordination/package.json index ca7fe2c..2e88948 100644 --- a/plugins/codex-pi-coordination/package.json +++ b/plugins/codex-pi-coordination/package.json @@ -1,11 +1,11 @@ { "name": "codex-pi-coordination", - "version": "0.3.0", - "description": "Bounded Pi tasks, saved-session continuation and capability discovery for Codex", + "version": "0.4.0", + "description": "Bounded Pi tasks, saved-session continuation, capability discovery, and parallel multi-Pi testing", "type": "module", "license": "MIT", "engines": { "node": ">=22" }, - "files": [".codex-plugin/plugin.json", "extensions/coordination.js", "scripts/coordinate.py", "skills"], + "files": [".antigravity-plugin/plugin.json", ".codex-plugin/plugin.json", "extensions/coordination.js", "scripts/coordinate.py", "scripts/fanout.py", "skills"], "pi": { "extensions": ["./extensions/coordination.js"] }, "scripts": { "test:extension": "node --test tests/extension.test.mjs" } } diff --git a/plugins/codex-pi-coordination/scripts/fanout.py b/plugins/codex-pi-coordination/scripts/fanout.py new file mode 100644 index 0000000..9cafc01 --- /dev/null +++ b/plugins/codex-pi-coordination/scripts/fanout.py @@ -0,0 +1,1137 @@ +#!/usr/bin/env python3 +"""Hybrid parallel multi-Pi test runner for Antigravity, Codex, and Claude. + +Launches N bounded Pi agents concurrently for testing — model comparisons, +replica consistency/stress checks, parallel reviews, or scoped multi-task +batches — across two isolation backends: + + 1. ``local`` (Linux, macOS, Windows): spawns isolated local ``pi`` workers, + each in its own fresh workspace directory (or clean ``git archive`` export + of a committed revision) with explicit model/thinking flags, strict tool + allowlists, optional ``coordination.js`` enforcement, wall-clock timeouts, + and post-handoff verification checks. + 2. ``openshell`` (Linux hosts with NVIDIA OpenShell): fans out across a pool + of distinct OpenShell sandbox profiles (refusing duplicate or protected + sandboxes), delegating each worker to ``scripts/coordinate.py run``. + +Stdlib-only Python 3.10+. Never mutates the caller's repository working tree or +overwrites a non-empty output directory. +""" + +from __future__ import annotations + +import argparse +import concurrent.futures +import hashlib +import io +import json +import os +import queue +import re +import shutil +import signal +import subprocess +import sys +import tarfile +import time +import uuid +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +PLUGIN_ROOT = Path(__file__).resolve().parent.parent +COORDINATE_SCRIPT = Path(__file__).resolve().parent / "coordinate.py" +COORDINATION_EXTENSION = PLUGIN_ROOT / "extensions" / "coordination.js" +DEFAULT_PROFILE_PATH = Path.home() / ".config" / "codex-pi-coordination" / "profile.json" +DEFAULT_LOCK_ROOT = Path.home() / ".local" / "state" / "codex-pi-coordination" + +VALID_KINDS = frozenset({"implementation", "research", "review", "validation"}) +VALID_THINKING = frozenset({"off", "minimal", "low", "medium", "high", "xhigh", "max"}) +REFUSED_MODEL_TOKENS = frozenset({"auto", "dynamic", "default"}) +WORKER_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$") +TASK_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$") +MAX_CONCURRENCY = 32 +MAX_REPLICAS = 32 +MAX_LOG_BYTES = 2 * 1024 * 1024 +COORDINATION_PROMPT = ( + "Complete the assigned coordination task. Use coordination_status to inspect it " + "and coordination_handoff to return your work. Do not execute verification commands; " + "the coordinator runs declared checks after your handoff." +) + + +class FanoutError(ValueError): + """Validation or admission failure (exit code 2).""" + + +def _utc_now() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8") + tmp.replace(path) + + +def _read_json(path: Path, label: str) -> dict[str, Any]: + try: + raw = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise FanoutError(f"Unable to read {label} ({path}): {exc}") from exc + if not isinstance(raw, dict): + raise FanoutError(f"{label} must be a JSON object: {path}") + return raw + + +def _validate_relative_path(value: str) -> str: + if not isinstance(value, str) or not value.strip() or "\x00" in value: + raise FanoutError(f"Invalid relative writable path: {value!r}") + if value.startswith("/") or "\\" in value or (len(value) > 1 and value[1] == ":"): + raise FanoutError(f"Writable path must be normalized POSIX relative: {value!r}") + parts = value.split("/") + if any(p in ("", ".", "..") for p in parts): + raise FanoutError(f"Writable path cannot traverse or contain empty segments: {value!r}") + return value + + +def _validate_run_options(opts: dict[str, Any] | None) -> dict[str, str]: + if not opts: + return {} + if not isinstance(opts, dict): + raise FanoutError("run_options must be an object") + unknown = set(opts) - {"provider", "model", "thinking"} + if unknown: + raise FanoutError(f"Unknown run_options keys: {sorted(unknown)}") + out: dict[str, str] = {} + has_provider = "provider" in opts and opts["provider"] is not None + has_model = "model" in opts and opts["model"] is not None + if has_provider != has_model: + raise FanoutError("run_options.provider and run_options.model must be provided together") + if has_provider: + for key in ("provider", "model"): + val = opts[key] + if not isinstance(val, str) or not val.strip(): + raise FanoutError(f"run_options.{key} must be a non-empty string") + if val.strip().lower() in REFUSED_MODEL_TOKENS: + raise FanoutError(f"run_options.{key} refuses ambiguous token {val!r}") + out[key] = val.strip() + if "thinking" in opts and opts["thinking"] is not None: + th = opts["thinking"] + if not isinstance(th, str) or th not in VALID_THINKING: + raise FanoutError(f"Invalid thinking level {th!r}; expected one of {sorted(VALID_THINKING)}") + out["thinking"] = th + return out + + +def _validate_checks(checks: Any) -> list[dict[str, Any]]: + if checks is None: + return [] + if not isinstance(checks, list): + raise FanoutError("checks must be a list") + normalized: list[dict[str, Any]] = [] + seen_names: set[str] = set() + for idx, item in enumerate(checks): + if not isinstance(item, dict): + raise FanoutError(f"checks[{idx}] must be an object") + name = item.get("name") + argv = item.get("argv") + timeout = item.get("timeout_seconds", 60) + if not isinstance(name, str) or not WORKER_ID_RE.fullmatch(name): + raise FanoutError(f"Invalid check name: {name!r}") + if name in seen_names: + raise FanoutError(f"Duplicate check name: {name!r}") + seen_names.add(name) + if not isinstance(argv, list) or not argv or not all(isinstance(a, str) and a for a in argv): + raise FanoutError(f"Check {name!r} argv must be a non-empty list of strings") + if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0: + raise FanoutError(f"Check {name!r} timeout_seconds must be a positive number") + normalized.append({"name": name, "argv": list(argv), "timeout_seconds": float(timeout)}) + return normalized + + +def _normalize_task( + raw: dict[str, Any], + *, + worker_id: str, + defaults: dict[str, Any], + cli_run_options: dict[str, str], + cli_wall_seconds: int | None, +) -> dict[str, Any]: + if not WORKER_ID_RE.fullmatch(worker_id): + raise FanoutError(f"Invalid worker_id: {worker_id!r}") + merged = {**defaults, **raw} + task_id = str(merged.get("task_id") or worker_id) + if not TASK_ID_RE.fullmatch(task_id): + raise FanoutError(f"Invalid task_id for worker {worker_id}: {task_id!r}") + kind = merged.get("kind", "validation") + if kind not in VALID_KINDS: + raise FanoutError(f"Invalid kind for worker {worker_id}: {kind!r}") + instructions = merged.get("instructions") + if not isinstance(instructions, str) or not instructions.strip(): + raise FanoutError(f"Worker {worker_id} requires non-empty instructions") + writable = merged.get("writable_paths", []) + if not isinstance(writable, list): + raise FanoutError(f"Worker {worker_id} writable_paths must be a list") + writable_norm = [_validate_relative_path(p) for p in writable] + if len(writable_norm) != len(set(writable_norm)): + raise FanoutError(f"Worker {worker_id} has duplicate writable_paths") + + repository = merged.get("repository") + revision = merged.get("revision") + if bool(repository) != bool(revision): + raise FanoutError(f"Worker {worker_id}: repository and revision must be specified together") + if repository is not None: + repo_path = Path(str(repository)).expanduser().resolve() + if not repo_path.is_dir(): + raise FanoutError(f"Worker {worker_id}: repository directory not found: {repo_path}") + repository = str(repo_path) + revision = str(revision) + + # Merge run_options: defaults -> task -> CLI overrides + run_opts: dict[str, Any] = {} + if isinstance(defaults.get("run_options"), dict): + run_opts.update(defaults["run_options"]) + if isinstance(raw.get("run_options"), dict): + run_opts.update(raw["run_options"]) + run_opts.update(cli_run_options) + validated_opts = _validate_run_options(run_opts) + + wall_seconds = cli_wall_seconds if cli_wall_seconds is not None else merged.get("wall_seconds", 300) + if not isinstance(wall_seconds, int) or isinstance(wall_seconds, bool) or wall_seconds <= 0: + raise FanoutError(f"Worker {worker_id}: wall_seconds must be a positive integer") + + max_tool_calls = int(merged.get("max_tool_calls", 40)) + max_turns = int(merged.get("max_turns", 32)) + if max_tool_calls <= 0 or max_turns <= 0: + raise FanoutError(f"Worker {worker_id}: max_tool_calls and max_turns must be positive") + + checks = _validate_checks(merged.get("checks", [])) + + return { + "worker_id": worker_id, + "task_id": task_id, + "kind": kind, + "instructions": instructions, + "repository": repository, + "revision": revision, + "writable_paths": writable_norm, + "checks": checks, + "max_tool_calls": max_tool_calls, + "max_turns": max_turns, + "wall_seconds": wall_seconds, + "run_options": validated_opts, + } + + +def _resolve_pi_argv(pi_cmd: str | None) -> list[str]: + if pi_cmd: + parts = pi_cmd.split() + if not parts: + raise FanoutError("--pi-cmd cannot be empty") + return parts + found = shutil.which("pi") + if not found and os.name == "nt": + found = shutil.which("pi.cmd") or shutil.which("pi.exe") + if not found: + raise FanoutError("`pi` CLI not found on PATH; pass --pi-cmd or install Pi") + return [found] + + +def _terminate_tree(proc: subprocess.Popen[bytes]) -> None: + if proc.poll() is not None: + return + if os.name == "nt": + try: + subprocess.run( + ["taskkill", "/PID", str(proc.pid), "/T", "/F"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + timeout=5, + ) + except (OSError, subprocess.TimeoutExpired): + proc.kill() + else: + try: + os.killpg(proc.pid, signal.SIGTERM) + except OSError: + proc.terminate() + try: + proc.wait(timeout=3) + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + + +def _export_git_revision(repo: str, revision: str, dest: Path) -> None: + dest.mkdir(parents=True, exist_ok=True) + proc = subprocess.run( + ["git", "-C", repo, "archive", "--format=tar", revision], + capture_output=True, + timeout=60, + check=False, + ) + if proc.returncode != 0: + err = proc.stderr.decode("utf-8", errors="replace").strip() + raise FanoutError(f"git archive failed for {repo}@{revision}: {err}") + with tarfile.open(fileobj=io.BytesIO(proc.stdout), mode="r:") as tar: + tar.extractall(dest, filter="data") + + +def _snapshot_tree(root: Path) -> dict[str, str]: + snap: dict[str, str] = {} + for dirpath, dirnames, filenames in os.walk(root): + dirnames.sort() + for fname in sorted(filenames): + full = Path(dirpath) / fname + if full.is_symlink(): + snap[full.relative_to(root).as_posix()] = f"symlink:{os.readlink(full)}" + continue + h = hashlib.sha256() + with full.open("rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + snap[full.relative_to(root).as_posix()] = h.hexdigest() + return snap + + +def _diff_snapshots(before: dict[str, str], after: dict[str, str]) -> list[str]: + changed = sorted( + k for k in (set(before) | set(after)) if before.get(k) != after.get(k) + ) + return changed + + +def _run_checks( + checks: list[dict[str, Any]], workspace: Path, logs_dir: Path, deadline: float +) -> list[dict[str, Any]]: + logs_dir.mkdir(parents=True, exist_ok=True) + results: list[dict[str, Any]] = [] + for chk in checks: + remaining = max(1.0, deadline - time.monotonic()) + timeout = min(chk["timeout_seconds"], remaining) + t0 = time.monotonic() + stdout_path = logs_dir / f"{chk['name']}.stdout.log" + stderr_path = logs_dir / f"{chk['name']}.stderr.log" + timed_out = False + rc: int | None = None + err_msg: str | None = None + try: + proc = subprocess.Popen( + chk["argv"], + cwd=str(workspace), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=(os.name != "nt"), + ) + try: + out_b, err_b = proc.communicate(timeout=timeout) + rc = proc.returncode + except subprocess.TimeoutExpired: + timed_out = True + _terminate_tree(proc) + out_b, err_b = proc.communicate() + err_msg = f"check timed out after {timeout:.1f}s" + stdout_path.write_bytes(out_b[:MAX_LOG_BYTES]) + stderr_path.write_bytes(err_b[:MAX_LOG_BYTES]) + except OSError as exc: + err_msg = f"failed to launch check: {exc}" + stdout_path.write_bytes(b"") + stderr_path.write_bytes(err_msg.encode("utf-8")) + results.append( + { + "name": chk["name"], + "argv": chk["argv"], + "exit_code": rc, + "timed_out": timed_out, + "passed": (rc == 0 and not timed_out and err_msg is None), + "elapsed_seconds": round(time.monotonic() - t0, 3), + "stdout_log": str(stdout_path), + "stderr_log": str(stderr_path), + **({"error": err_msg} if err_msg else {}), + } + ) + return results + + +def _extract_last_assistant_text(events_path: Path) -> str | None: + if not events_path.is_file(): + return None + last_text: str | None = None + try: + for line in events_path.read_text(encoding="utf-8", errors="replace").splitlines(): + line = line.strip() + if not line.startswith("{"): + continue + try: + rec = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(rec, dict): + continue + # Pi JSON event stream: message_end / agent_end / assistant messages + msg = rec.get("message") if isinstance(rec.get("message"), dict) else None + if msg and msg.get("role") == "assistant": + content = msg.get("content") + if isinstance(content, str) and content.strip(): + last_text = content.strip() + elif isinstance(content, list): + texts = [ + c.get("text", "") + for c in content + if isinstance(c, dict) and c.get("type") == "text" and isinstance(c.get("text"), str) + ] + joined = "\n".join(t for t in texts if t.strip()).strip() + if joined: + last_text = joined + except OSError: + return None + return last_text[:1000] if last_text else None + + +def _run_local_worker( + task: dict[str, Any], + *, + output_root: Path, + pi_argv: list[str], + use_coordination_ext: bool, + allow_bash: bool, +) -> dict[str, Any]: + wid = task["worker_id"] + worker_dir = output_root / "workers" / wid + workspace = worker_dir / "workspace" + results_dir = worker_dir / "results" + control_dir = worker_dir / "control" + results_dir.mkdir(parents=True, exist_ok=True) + control_dir.mkdir(parents=True, exist_ok=True) + + started_at = _utc_now() + t0 = time.monotonic() + deadline = t0 + float(task["wall_seconds"]) + run_id = uuid.uuid4().hex + + try: + if task["repository"] and task["revision"]: + _export_git_revision(task["repository"], task["revision"], workspace) + else: + workspace.mkdir(parents=True, exist_ok=True) + except Exception as exc: + receipt = { + "worker_id": wid, + "task_id": task["task_id"], + "backend": "local", + "status": "setup_error", + "passed": False, + "started_at": started_at, + "finished_at": _utc_now(), + "elapsed_seconds": round(time.monotonic() - t0, 3), + "error": str(exc), + } + _write_json(worker_dir / "receipt.json", receipt) + return receipt + + before_snap = _snapshot_tree(workspace) + + # Build tools list + base_tools = ["read", "grep", "find", "ls"] + if task["writable_paths"] or allow_bash: + base_tools += ["write", "edit"] + if allow_bash: + base_tools.append("bash") + + use_ext = use_coordination_ext and not allow_bash and COORDINATION_EXTENSION.is_file() + cmd = list(pi_argv) + opts = task["run_options"] + if "provider" in opts and "model" in opts: + cmd += ["--provider", opts["provider"], "--model", opts["model"]] + if "thinking" in opts: + cmd += ["--thinking", opts["thinking"]] + + cmd += [ + "--offline", + "--no-session", + "--no-extensions", + "--no-skills", + "--no-prompt-templates", + "--no-context-files", + "--no-approve", + ] + + if use_ext: + allowed_native = ["read", "grep", "find", "ls"] + if task["writable_paths"]: + allowed_native += ["write", "edit"] + ext_task_id = re.sub(r"[^A-Za-z0-9_.-]", "-", task["task_id"])[:79] + if not ext_task_id or not ext_task_id[0].isalnum(): + ext_task_id = f"t-{wid}" + ext_task = { + "version": 1, + "run_id": run_id, + "task_id": ext_task_id, + "kind": task["kind"], + "instructions": task["instructions"], + "workspace": str(workspace.resolve()), + "output_directory": str(results_dir.resolve()), + "allowed_tools": allowed_native, + "writable_paths": task["writable_paths"], + "max_tool_calls": task["max_tool_calls"], + "max_turns": task["max_turns"], + } + task_file = control_dir / "task.json" + _write_json(task_file, ext_task) + tools_arg = ",".join([*allowed_native, "coordination_status", "coordination_handoff"]) + cmd += [ + "--tools", + tools_arg, + "--extension", + str(COORDINATION_EXTENSION), + "--coordination-task", + str(task_file.resolve()), + "--mode", + "json", + "-p", + COORDINATION_PROMPT, + ] + else: + cmd += [ + "--tools", + ",".join(base_tools), + "--mode", + "json", + "-p", + task["instructions"], + ] + + events_path = results_dir / "pi-events.jsonl" + stderr_path = results_dir / "stderr.log" + timed_out = False + pi_rc: int | None = None + launch_err: str | None = None + + try: + proc = subprocess.Popen( + cmd, + cwd=str(workspace), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=(os.name != "nt"), + ) + try: + out_b, err_b = proc.communicate(timeout=max(1.0, deadline - time.monotonic())) + pi_rc = proc.returncode + except subprocess.TimeoutExpired: + timed_out = True + _terminate_tree(proc) + out_b, err_b = proc.communicate() + events_path.write_bytes(out_b[:MAX_LOG_BYTES]) + stderr_path.write_bytes(err_b[:MAX_LOG_BYTES]) + except OSError as exc: + launch_err = f"failed to launch pi: {exc}" + events_path.write_bytes(b"") + stderr_path.write_bytes(launch_err.encode("utf-8")) + + after_snap = _snapshot_tree(workspace) + changed_files = _diff_snapshots(before_snap, after_snap) + + # Check writable path compliance + allowed_set = set(task["writable_paths"]) + unexpected_changes = ( + [f for f in changed_files if f not in allowed_set] + if (use_ext or not allow_bash) + else [] + ) + + handoff_data: dict[str, Any] | None = None + handoff_file = results_dir / "model-report.json" + if handoff_file.is_file(): + try: + handoff_data = json.loads(handoff_file.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + handoff_data = None + + # Run declared checks unless Pi timed out or failed to launch + check_results: list[dict[str, Any]] = [] + if not timed_out and launch_err is None and not unexpected_changes: + check_results = _run_checks(task["checks"], workspace, results_dir / "checks", deadline) + + checks_ok = all(c["passed"] for c in check_results) and len(check_results) == len(task["checks"]) + if timed_out: + status = "timeout" + err = f"worker exceeded wall_seconds={task['wall_seconds']}" + elif launch_err: + status = "launch_error" + err = launch_err + elif unexpected_changes: + status = "scope_violation" + err = f"unexpected file modifications outside writable_paths: {unexpected_changes}" + elif pi_rc != 0: + status = "pi_error" + err = f"pi exited with code {pi_rc}" + elif use_ext and handoff_data is None: + status = "missing_handoff" + err = "coordination extension enabled but no model-report.json was written" + elif not checks_ok: + status = "checks_failed" + err = "one or more verification checks failed" + else: + status = "ok" + err = None + + handoff_summary: str | None = None + if isinstance(handoff_data, dict): + s = handoff_data.get("summary") + if isinstance(s, str): + handoff_summary = s[:500] + if handoff_summary is None: + handoff_summary = _extract_last_assistant_text(events_path) + + receipt = { + "worker_id": wid, + "task_id": task["task_id"], + "run_id": run_id, + "backend": "local", + "coordination_extension": use_ext, + "status": status, + "passed": status == "ok", + "started_at": started_at, + "finished_at": _utc_now(), + "elapsed_seconds": round(time.monotonic() - t0, 3), + "pi_exit_code": pi_rc, + "workspace": str(workspace), + "changed_files": changed_files, + "unexpected_changes": unexpected_changes, + "checks": check_results, + "checks_passed": sum(1 for c in check_results if c["passed"]), + "checks_total": len(task["checks"]), + "handoff_summary": handoff_summary, + "events_log": str(events_path), + "stderr_log": str(stderr_path), + **({"error": err} if err else {}), + } + _write_json(worker_dir / "receipt.json", receipt) + return receipt + + +def _load_openshell_pool( + profile_paths: list[Path], +) -> list[dict[str, Any]]: + if not profile_paths: + raise FanoutError("No OpenShell profile files provided for --backend openshell") + pool: list[dict[str, Any]] = [] + seen_names: set[str] = set() + seen_ids: set[str] = set() + all_protected: set[str] = set() + for path in profile_paths: + resolved = path.expanduser().resolve() + data = _read_json(resolved, "OpenShell profile") + sname = data.get("sandbox_name") + sid = data.get("sandbox_id") + if not isinstance(sname, str) or not sname.strip(): + raise FanoutError(f"OpenShell profile missing sandbox_name: {resolved}") + if not isinstance(sid, str) or not sid.strip(): + raise FanoutError(f"OpenShell profile missing sandbox_id: {resolved}") + if sname in seen_names: + raise FanoutError(f"Duplicate sandbox_name {sname!r} in OpenShell pool") + if sid in seen_ids: + raise FanoutError(f"Duplicate sandbox_id {sid!r} in OpenShell pool") + seen_names.add(sname) + seen_ids.add(sid) + for p in data.get("protected_sandboxes") or []: + if isinstance(p, str) and p.strip(): + all_protected.add(p.strip()) + pool.append({"path": resolved, "sandbox_name": sname, "sandbox_id": sid}) + + for entry in pool: + if entry["sandbox_name"] in all_protected: + raise FanoutError( + f"Pool sandbox {entry['sandbox_name']!r} is listed in protected_sandboxes" + ) + return pool + + +def _run_openshell_worker( + task: dict[str, Any], + *, + output_root: Path, + pool_queue: queue.Queue[dict[str, Any]], + coordinate_script: Path, + lock_root: Path, +) -> dict[str, Any]: + wid = task["worker_id"] + worker_dir = output_root / "workers" / wid + control_dir = worker_dir / "control" + coord_out = worker_dir / "coordinate-out" + control_dir.mkdir(parents=True, exist_ok=True) + + started_at = _utc_now() + t0 = time.monotonic() + + slot = pool_queue.get() + try: + # Write version-2 task manifest compatible with scripts/coordinate.py + coord_task: dict[str, Any] = { + "version": 2, + "task_id": task["task_id"], + "kind": task["kind"], + "instructions": task["instructions"], + "writable_paths": task["writable_paths"], + "checks": task["checks"], + "max_tool_calls": task["max_tool_calls"], + "max_turns": task["max_turns"], + "wall_seconds": task["wall_seconds"], + } + if task["repository"] and task["revision"]: + coord_task["repository"] = task["repository"] + coord_task["revision"] = task["revision"] + if task["run_options"]: + coord_task["run_options"] = task["run_options"] + + task_file = control_dir / "task.json" + _write_json(task_file, coord_task) + + cmd = [ + sys.executable, + str(coordinate_script), + "run", + str(task_file), + "--profile", + str(slot["path"]), + "--output", + str(coord_out), + "--lock-root", + str(lock_root), + ] + timeout = float(task["wall_seconds"]) + 120.0 + timed_out = False + rc: int | None = None + proc = subprocess.Popen( + cmd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=(os.name != "nt"), + ) + try: + out_b, err_b = proc.communicate(timeout=timeout) + rc = proc.returncode + except subprocess.TimeoutExpired: + timed_out = True + _terminate_tree(proc) + out_b, err_b = proc.communicate() + + (worker_dir / "coordinate.stdout.log").write_bytes(out_b[:MAX_LOG_BYTES]) + (worker_dir / "coordinate.stderr.log").write_bytes(err_b[:MAX_LOG_BYTES]) + + inner_receipt: dict[str, Any] | None = None + inner_path = coord_out / "receipt.json" + if inner_path.is_file(): + try: + inner_receipt = json.loads(inner_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + inner_receipt = None + + inner_ok = bool( + inner_receipt + and inner_receipt.get("delivery_valid") + and "error" not in inner_receipt + and rc == 0 + and not timed_out + ) + status = "timeout" if timed_out else ("ok" if inner_ok else "openshell_failed") + err = ( + f"coordinate.py exceeded outer timeout ({timeout:.0f}s)" + if timed_out + else ( + None + if inner_ok + else ( + str(inner_receipt.get("error")) + if isinstance(inner_receipt, dict) and inner_receipt.get("error") + else f"coordinate.py exited {rc}" + ) + ) + ) + checks_raw = (inner_receipt or {}).get("checks") or [] + handoff_obj = (inner_receipt or {}).get("handoff") or {} + receipt = { + "worker_id": wid, + "task_id": task["task_id"], + "backend": "openshell", + "sandbox_name": slot["sandbox_name"], + "profile": str(slot["path"]), + "status": status, + "passed": inner_ok, + "started_at": started_at, + "finished_at": _utc_now(), + "elapsed_seconds": round(time.monotonic() - t0, 3), + "coordinate_exit_code": rc, + "changed_files": sorted((inner_receipt or {}).get("changed_files") or []), + "checks_passed": sum(1 for c in checks_raw if isinstance(c, dict) and c.get("exit_code") == 0), + "checks_total": len(task["checks"]), + "handoff_summary": handoff_obj.get("summary") if isinstance(handoff_obj, dict) else None, + "coordinate_receipt": str(inner_path) if inner_path.is_file() else None, + **({"error": err} if err else {}), + } + _write_json(worker_dir / "receipt.json", receipt) + return receipt + finally: + pool_queue.put(slot) + + +def cmd_discover(args: argparse.Namespace) -> int: + pi_bin = shutil.which("pi") or (shutil.which("pi.cmd") if os.name == "nt" else None) + pi_version: str | None = None + if pi_bin: + try: + r = subprocess.run([pi_bin, "--version"], capture_output=True, text=True, timeout=10, check=False) + if r.returncode == 0: + pi_version = (r.stdout or r.stderr).strip().splitlines()[0] + except (OSError, subprocess.TimeoutExpired): + pass + + os_bin = shutil.which("openshell") + sandboxes: list[dict[str, str]] = [] + if os_bin: + try: + r = subprocess.run([os_bin, "sandbox", "list"], capture_output=True, text=True, timeout=10, check=False) + if r.returncode == 0: + for line in r.stdout.splitlines()[1:]: + parts = line.split() + if len(parts) >= 2: + sandboxes.append({"name": parts[0], "phase": parts[-1]}) + except (OSError, subprocess.TimeoutExpired): + pass + + def _safe_profile(p: Path) -> dict[str, Any] | None: + if not p.is_file(): + return None + try: + d = json.loads(p.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {"path": str(p), "error": "unreadable"} + return { + "path": str(p), + "sandbox_name": d.get("sandbox_name"), + "model": d.get("model"), + "thinking": d.get("thinking"), + "protected_sandboxes": d.get("protected_sandboxes", []), + } + + default_prof = _safe_profile(DEFAULT_PROFILE_PATH) + pool_profiles: list[dict[str, Any]] = [] + if args.profile_dir: + pdir = Path(args.profile_dir).expanduser().resolve() + if pdir.is_dir(): + for f in sorted(pdir.glob("*.json")): + info = _safe_profile(f) + if info: + pool_profiles.append(info) + + backends: list[str] = [] + if pi_bin: + backends.append("local") + if os_bin: + backends.append("openshell") + + report = { + "platform": sys.platform, + "pi_binary": pi_bin, + "pi_version": pi_version, + "coordination_extension": str(COORDINATION_EXTENSION) if COORDINATION_EXTENSION.is_file() else None, + "openshell_binary": os_bin, + "openshell_sandboxes": sandboxes, + "default_profile": default_prof, + "pool_profiles": pool_profiles, + "supported_backends": backends, + } + print(json.dumps(report, indent=2)) + return 0 + + +def _collect_tasks(args: argparse.Namespace) -> tuple[str, str, int, list[dict[str, Any]]]: + cli_opts: dict[str, str] = {} + if args.provider or args.model: + cli_opts["provider"] = args.provider or "" + cli_opts["model"] = args.model or "" + if args.thinking: + cli_opts["thinking"] = args.thinking + cli_run_options = _validate_run_options(cli_opts) + + sources = sum(bool(x) for x in (args.batch, args.tasks, args.task)) + if sources != 1: + raise FanoutError("Specify exactly one of BATCH_JSON, --tasks, or --task") + + defaults: dict[str, Any] = {} + batch_id = f"pi-batch-{uuid.uuid4().hex[:8]}" + backend = args.backend or "local" + concurrency = args.concurrency or 4 + tasks: list[dict[str, Any]] = [] + + if args.batch: + doc = _read_json(Path(args.batch), "batch manifest") + if doc.get("version") != 1: + raise FanoutError("batch manifest requires version: 1") + batch_id = str(doc.get("batch_id") or batch_id) + if not args.backend and doc.get("backend"): + backend = str(doc["backend"]) + if not args.concurrency and doc.get("concurrency") is not None: + concurrency = int(doc["concurrency"]) + defaults = doc.get("defaults") if isinstance(doc.get("defaults"), dict) else {} + raw_tasks = doc.get("tasks") + if not isinstance(raw_tasks, list) or not raw_tasks: + raise FanoutError("batch manifest requires a non-empty tasks array") + for idx, item in enumerate(raw_tasks, 1): + if not isinstance(item, dict): + raise FanoutError(f"tasks[{idx-1}] must be an object") + wid = str(item.get("worker_id") or f"w{idx:02d}") + tasks.append( + _normalize_task( + item, + worker_id=wid, + defaults=defaults, + cli_run_options=cli_run_options, + cli_wall_seconds=args.wall_seconds, + ) + ) + elif args.tasks: + for idx, tpath in enumerate(args.tasks, 1): + raw = _read_json(Path(tpath), f"task[{idx}]") + wid = str(raw.get("worker_id") or f"w{idx:02d}") + tasks.append( + _normalize_task( + raw, + worker_id=wid, + defaults={}, + cli_run_options=cli_run_options, + cli_wall_seconds=args.wall_seconds, + ) + ) + else: + replicas = args.replicas + if replicas < 1 or replicas > MAX_REPLICAS: + raise FanoutError(f"--replicas must be between 1 and {MAX_REPLICAS}") + raw = _read_json(Path(args.task), "task") + base_id = str(raw.get("task_id") or Path(args.task).stem) + for idx in range(1, replicas + 1): + wid = f"r{idx:02d}" + cloned = dict(raw) + cloned["task_id"] = f"{base_id}-{wid}" + tasks.append( + _normalize_task( + cloned, + worker_id=wid, + defaults={}, + cli_run_options=cli_run_options, + cli_wall_seconds=args.wall_seconds, + ) + ) + + if backend not in ("local", "openshell"): + raise FanoutError(f"Unsupported backend {backend!r}; choose 'local' or 'openshell'") + if concurrency < 1 or concurrency > MAX_CONCURRENCY: + raise FanoutError(f"--concurrency must be between 1 and {MAX_CONCURRENCY}") + wids = [t["worker_id"] for t in tasks] + if len(wids) != len(set(wids)): + raise FanoutError("Duplicate worker_id in batch") + return batch_id, backend, concurrency, tasks + + +def cmd_run(args: argparse.Namespace) -> int: + batch_id, backend, requested_concurrency, tasks = _collect_tasks(args) + output_root = Path(args.output).expanduser().resolve() + if output_root.exists() and any(output_root.iterdir()): + raise FanoutError(f"--output directory already exists and is non-empty: {output_root}") + + pi_argv: list[str] = [] + pool: list[dict[str, Any]] = [] + effective_concurrency = min(requested_concurrency, len(tasks)) + + if backend == "local": + pi_argv = _resolve_pi_argv(args.pi_cmd) + else: + profile_paths: list[Path] = [] + if args.profiles: + profile_paths.extend(Path(p) for p in args.profiles) + if args.profile_dir: + pdir = Path(args.profile_dir).expanduser().resolve() + if not pdir.is_dir(): + raise FanoutError(f"--profile-dir not found: {pdir}") + profile_paths.extend(sorted(pdir.glob("*.json"))) + if not profile_paths: + profile_paths.append(Path(args.profile)) + pool = _load_openshell_pool(profile_paths) + effective_concurrency = min(effective_concurrency, len(pool)) + coord_script = Path(args.coordinate_script).expanduser().resolve() + if not coord_script.is_file(): + raise FanoutError(f"coordinate.py not found: {coord_script}") + + plan = { + "batch_id": batch_id, + "backend": backend, + "dry_run": bool(args.dry_run), + "requested_concurrency": requested_concurrency, + "effective_concurrency": effective_concurrency, + "total_workers": len(tasks), + "output": str(output_root), + **({"pool_sandboxes": [p["sandbox_name"] for p in pool]} if pool else {}), + "workers": [ + { + "worker_id": t["worker_id"], + "task_id": t["task_id"], + "kind": t["kind"], + "run_options": t["run_options"], + "writable_paths": t["writable_paths"], + "checks_total": len(t["checks"]), + "wall_seconds": t["wall_seconds"], + } + for t in tasks + ], + } + if args.dry_run: + print(json.dumps(plan, indent=2)) + return 0 + + output_root.mkdir(parents=True, exist_ok=True) + _write_json(output_root / "plan.json", plan) + + started_at = _utc_now() + t0 = time.monotonic() + receipts: list[dict[str, Any]] = [] + + if backend == "local": + use_ext = not args.no_coordination_ext + with concurrent.futures.ThreadPoolExecutor(max_workers=effective_concurrency) as ex: + futures = [ + ex.submit( + _run_local_worker, + t, + output_root=output_root, + pi_argv=pi_argv, + use_coordination_ext=use_ext, + allow_bash=bool(args.allow_bash), + ) + for t in tasks + ] + for fut in concurrent.futures.as_completed(futures): + receipts.append(fut.result()) + else: + pool_q: queue.Queue[dict[str, Any]] = queue.Queue() + for slot in pool: + pool_q.put(slot) + coord_script = Path(args.coordinate_script).expanduser().resolve() + lock_root = Path(args.lock_root).expanduser().resolve() + with concurrent.futures.ThreadPoolExecutor(max_workers=effective_concurrency) as ex: + futures = [ + ex.submit( + _run_openshell_worker, + t, + output_root=output_root, + pool_queue=pool_q, + coordinate_script=coord_script, + lock_root=lock_root, + ) + for t in tasks + ] + for fut in concurrent.futures.as_completed(futures): + receipts.append(fut.result()) + + # Deterministic order matching input task order + order = {t["worker_id"]: idx for idx, t in enumerate(tasks)} + receipts.sort(key=lambda r: order.get(r["worker_id"], 0)) + + passed_count = sum(1 for r in receipts if r.get("passed")) + timed_out_count = sum(1 for r in receipts if r.get("status") == "timeout") + failed_count = len(receipts) - passed_count + all_passed = failed_count == 0 + + summary = { + "batch_id": batch_id, + "backend": backend, + "started_at": started_at, + "finished_at": _utc_now(), + "elapsed_seconds": round(time.monotonic() - t0, 3), + "effective_concurrency": effective_concurrency, + "total_workers": len(receipts), + "passed_workers": passed_count, + "failed_workers": failed_count, + "timed_out_workers": timed_out_count, + "all_passed": all_passed, + "output": str(output_root), + "workers": [ + { + "worker_id": r["worker_id"], + "task_id": r["task_id"], + "status": r["status"], + "passed": r["passed"], + "elapsed_seconds": r["elapsed_seconds"], + **({"sandbox_name": r["sandbox_name"]} if "sandbox_name" in r else {}), + "changed_files": r.get("changed_files", []), + "checks_passed": r.get("checks_passed", 0), + "checks_total": r.get("checks_total", 0), + "handoff_summary": r.get("handoff_summary"), + **({"error": r["error"]} if r.get("error") else {}), + "receipt_path": str(output_root / "workers" / r["worker_id"] / "receipt.json"), + } + for r in receipts + ], + } + _write_json(output_root / "summary.json", summary) + print(json.dumps(summary, indent=2)) + return 0 if all_passed else 1 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + disc = sub.add_parser("discover", help="Inspect available Pi binary, OpenShell sandboxes, and profiles") + disc.add_argument("--profile-dir", help="Optional directory containing OpenShell pool profile JSON files") + + run = sub.add_parser("run", help="Launch multiple Pi test workers in parallel") + run.add_argument("batch", nargs="?", help="Path to a version-1 batch manifest JSON file") + run.add_argument("--tasks", nargs="+", help="One or more task JSON files to run in parallel") + run.add_argument("--task", help="Single task JSON file to clone across --replicas workers") + run.add_argument("--replicas", type=int, default=2, help="Replica count when using --task (default: 2)") + run.add_argument("--backend", choices=["local", "openshell"], help="Execution backend (default: local)") + run.add_argument("--concurrency", type=int, help="Max concurrent Pi workers (default: 4, max: 32)") + run.add_argument("--output", required=True, help="Fresh output directory for worker artifacts and summary.json") + run.add_argument("--pi-cmd", help="Override local Pi launch argv string (default: `pi` on PATH)") + run.add_argument("--provider", help="Explicit provider override (must pair with --model)") + run.add_argument("--model", help="Explicit model override (must pair with --provider)") + run.add_argument("--thinking", choices=sorted(VALID_THINKING), help="Explicit thinking level override") + run.add_argument("--wall-seconds", type=int, help="Override per-worker wall-clock timeout in seconds") + run.add_argument("--no-coordination-ext", action="store_true", help="Disable coordination.js extension in local mode") + run.add_argument("--allow-bash", action="store_true", help="Allow Pi bash tool in local mode (disables coordination.js)") + run.add_argument("--profile", default=str(DEFAULT_PROFILE_PATH), help="Single OpenShell profile JSON (openshell backend)") + run.add_argument("--profiles", nargs="+", help="Pool of distinct OpenShell profile JSON files (openshell backend)") + run.add_argument("--profile-dir", help="Directory of distinct OpenShell profile JSON files (openshell backend)") + run.add_argument("--lock-root", default=str(DEFAULT_LOCK_ROOT), help="Lock directory for OpenShell backend") + run.add_argument("--coordinate-script", default=str(COORDINATE_SCRIPT), help="Path to coordinate.py") + run.add_argument("--dry-run", action="store_true", help="Validate inputs and print planned workers without launching Pi") + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + try: + if args.command == "discover": + return cmd_discover(args) + return cmd_run(args) + except FanoutError as exc: + print(json.dumps({"error": str(exc)}), file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/codex-pi-coordination/skills/pi-parallel-test/SKILL.md b/plugins/codex-pi-coordination/skills/pi-parallel-test/SKILL.md new file mode 100644 index 0000000..1a2aa92 --- /dev/null +++ b/plugins/codex-pi-coordination/skills/pi-parallel-test/SKILL.md @@ -0,0 +1,63 @@ +--- +name: pi-parallel-test +description: Launch multiple bounded Pi agents in parallel for testing — model bake-offs, replica consistency and stress checks, parallel reviews, or multi-task test waves — across either isolated local Pi workspaces (Linux, macOS, Windows) or an NVIDIA OpenShell sandbox pool. Use when asked to fan out multiple Pi workers, test behavior across concurrent Pi agents, compare models with Pi, or run parallel Pi test batches from Antigravity, Codex, or Claude Code. +--- + +# Parallel Pi Testing (`fanout.py`) + +Resolve `PLUGIN_ROOT` from the host-provided `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT`, or relative to this loaded skill (`../..`). Do not assume the current directory is the plugin install root. + +Use `scripts/fanout.py` (stdlib-only Python 3.10+) to launch **multiple isolated Pi agents concurrently** with explicit budgets, clean workspace isolation, post-handoff verification checks, and per-worker JSON receipts. + +## 1. Discover available backends on this host + +```bash +python3 "${PLUGIN_ROOT}/scripts/fanout.py" discover +``` + +On Windows, use `python "${PLUGIN_ROOT}/scripts/fanout.py" discover`. + +- **`local` backend** (Linux, macOS, Windows): spawns up to `--concurrency K` local `pi` workers. Each worker runs in its own isolated directory (`/workers//workspace`) created either empty or via `git archive ` — your repository working tree is never mutated. By default, each worker loads `extensions/coordination.js` to enforce `writable_paths`, tool allowlists, turn/tool budgets, and structured `coordination_handoff`. +- **`openshell` backend** (Linux hosts with NVIDIA OpenShell): fans out across a pool of **distinct** OpenShell profiles (`--profiles p1.json p2.json` or `--profile-dir `), refusing duplicate `sandbox_name`/`sandbox_id` entries and protected sandboxes. Each worker delegates to `scripts/coordinate.py run` with exclusive sandbox locking. + +## 2. Dry-run first, then execute + +Read [the batch manifest contract](references/batch-contract.md) for schema details. Always pass a fresh `--output` directory (existing non-empty directories are refused). + +### A. Clone one task across N parallel Pi replicas (consistency / stress / contention testing) + +```bash +python3 "${PLUGIN_ROOT}/scripts/fanout.py" run \ + --task /tmp/test-task.json \ + --replicas 4 \ + --concurrency 4 \ + --backend local \ + --output /tmp/pi-fanout-run-01 \ + --dry-run +``` + +Remove `--dry-run` once the plan looks right. + +### B. Run a multi-task batch (model bake-off, multi-angle review, or parallel test wave) + +```bash +python3 "${PLUGIN_ROOT}/scripts/fanout.py" run /tmp/batch.json \ + --output /tmp/pi-batch-01 +``` + +### C. Fan out across an OpenShell sandbox pool + +```bash +python3 "${PLUGIN_ROOT}/scripts/fanout.py" run /tmp/batch.json \ + --backend openshell \ + --profiles /path/to/sandbox-a.json /path/to/sandbox-b.json \ + --concurrency 2 \ + --output /tmp/pi-openshell-batch-01 +``` + +## 3. Rules & safety invariants + +- **Never reuse a live protected sandbox** (such as a durable agent sandbox). Pool profiles must point exclusively to disposable sandboxes. +- **Explicit model selection only.** Pass `--provider

--model ` (paired) and/or `--thinking ` — never `auto`, `dynamic`, or `default`. Omit them to inherit the runtime's configured default. +- **Keep checks independent.** By default, Pi workers have no shell tool; declare verification commands as `checks` argv arrays so the coordinator executes them once after handoff and records actual exit codes and logs. Pass `--allow-bash` only when the test specifically requires Pi to invoke shell tools directly (this disables `coordination.js`). +- **Inspect `summary.json` and per-worker `receipt.json`** before reporting results: report `passed_workers / total_workers`, exact `status` values (`ok`, `checks_failed`, `scope_violation`, `timeout`, `missing_handoff`, `pi_error`), changed files, and elapsed time. diff --git a/plugins/codex-pi-coordination/skills/pi-parallel-test/agents/openai.yaml b/plugins/codex-pi-coordination/skills/pi-parallel-test/agents/openai.yaml new file mode 100644 index 0000000..9dcb132 --- /dev/null +++ b/plugins/codex-pi-coordination/skills/pi-parallel-test/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Parallel Pi Testing" + short_description: "Launch multiple isolated Pi agents in parallel for testing" + default_prompt: "Use $pi-parallel-test to launch multiple isolated Pi agents in parallel and aggregate their receipts." diff --git a/plugins/codex-pi-coordination/skills/pi-parallel-test/references/batch-contract.md b/plugins/codex-pi-coordination/skills/pi-parallel-test/references/batch-contract.md new file mode 100644 index 0000000..3fa063e --- /dev/null +++ b/plugins/codex-pi-coordination/skills/pi-parallel-test/references/batch-contract.md @@ -0,0 +1,75 @@ +# Parallel Pi Batch Contract + +## Batch manifest (`version: 1`) + +```json +{ + "version": 1, + "batch_id": "model-comparison-01", + "backend": "local", + "concurrency": 4, + "defaults": { + "repository": "/path/to/repo", + "revision": "HEAD", + "wall_seconds": 300, + "max_tool_calls": 40, + "max_turns": 32, + "run_options": { + "provider": "configured-provider", + "model": "exact-model-id", + "thinking": "low" + } + }, + "tasks": [ + { + "worker_id": "candidate-a", + "task_id": "bench:a", + "kind": "implementation", + "instructions": "Fix edge case in parser.py and return handoff.", + "writable_paths": ["parser.py"], + "checks": [ + { + "name": "unit-tests", + "argv": ["python3", "-m", "pytest", "-q"], + "timeout_seconds": 60 + } + ] + }, + { + "worker_id": "candidate-b", + "task_id": "bench:b", + "kind": "implementation", + "instructions": "Fix edge case in parser.py and return handoff.", + "writable_paths": ["parser.py"], + "run_options": { + "provider": "other-provider", + "model": "other-model-id", + "thinking": "medium" + }, + "checks": [ + { + "name": "unit-tests", + "argv": ["python3", "-m", "pytest", "-q"], + "timeout_seconds": 60 + } + ] + } + ] +} +``` + +## Outputs + +Under `--output

`: + +- `plan.json` — validated dispatch plan written before any worker starts. +- `summary.json` — aggregate counts (`total_workers`, `passed_workers`, `failed_workers`, `timed_out_workers`, `all_passed`) and per-worker verdicts. +- `workers//receipt.json` — full per-worker receipt (exit status, changed files, check results, handoff summary, log paths). +- `workers//workspace/` — isolated workspace snapshot (in `local` backend). +- `workers//results/` — `pi-events.jsonl`, `stderr.log`, `model-report.json` + `extension-events.jsonl` (when `coordination.js` is active), and `checks/*.log`. + +## Exit codes + +- `0`: all workers passed (or `--dry-run` / `discover` succeeded). +- `1`: at least one worker failed, timed out, or violated `writable_paths`. +- `2`: input, profile pool, or admission validation error (nothing launched). diff --git a/plugins/codex-pi-coordination/tests/test_fanout.py b/plugins/codex-pi-coordination/tests/test_fanout.py new file mode 100644 index 0000000..ad8fa3f --- /dev/null +++ b/plugins/codex-pi-coordination/tests/test_fanout.py @@ -0,0 +1,286 @@ +from __future__ import annotations + +import json +import os +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +FANOUT_SCRIPT = PLUGIN_ROOT / "scripts" / "fanout.py" + + +def _write_json(path: Path, data: object) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + return path + + +def _make_fake_pi(directory: Path, body: str) -> Path: + script = directory / "fake_pi.py" + script.write_text(body, encoding="utf-8") + if os.name != "nt": + script.chmod(script.stat().st_mode | stat.S_IXUSR) + return script + + +class FanoutTests(unittest.TestCase): + def _run_fanout(self, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(FANOUT_SCRIPT), *args], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + + def test_discover_returns_json_report(self) -> None: + r = self._run_fanout("discover") + self.assertEqual(r.returncode, 0, r.stderr) + data = json.loads(r.stdout) + self.assertIn("platform", data) + self.assertIn("supported_backends", data) + + def test_dry_run_validates_without_writing_output(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + fake_pi = _make_fake_pi(root, "import sys\nsys.exit(0)\n") + task = _write_json( + root / "task.json", + { + "task_id": "demo:t1", + "kind": "validation", + "instructions": "Inspect workspace", + "writable_paths": [], + "checks": [], + }, + ) + out = root / "out" + r = self._run_fanout( + "run", + "--task", + str(task), + "--replicas", + "3", + "--concurrency", + "2", + "--backend", + "local", + "--pi-cmd", + f"{sys.executable} {fake_pi}", + "--output", + str(out), + "--dry-run", + ) + self.assertEqual(r.returncode, 0, r.stderr) + plan = json.loads(r.stdout) + self.assertTrue(plan["dry_run"]) + self.assertEqual(plan["total_workers"], 3) + self.assertEqual(plan["effective_concurrency"], 2) + self.assertFalse(out.exists()) + + def test_local_parallel_replicas_isolated_workspaces_and_checks(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + # Fake Pi writes out.txt inside its cwd and writes handoff.json to task's output_directory + fake_pi = _make_fake_pi( + root, + """ +import json, sys, time +from pathlib import Path +args = sys.argv[1:] +task_idx = args.index("--coordination-task") + 1 +task = json.loads(Path(args[task_idx]).read_text(encoding="utf-8")) +time.sleep(0.1) +Path("out.txt").write_text("worker=" + task["task_id"] + "\\n", encoding="utf-8") +out_dir = Path(task["output_directory"]) +(out_dir / "model-report.json").write_text(json.dumps({"summary": "done " + task["task_id"]}), encoding="utf-8") +print(json.dumps({"type": "message_end", "message": {"role": "assistant", "content": "ok"}})) +""", + ) + task = _write_json( + root / "task.json", + { + "task_id": "replica-test", + "kind": "implementation", + "instructions": "Write out.txt", + "writable_paths": ["out.txt"], + "checks": [ + { + "name": "verify-file", + "argv": [sys.executable, "-c", "from pathlib import Path; assert Path('out.txt').read_text().startswith('worker=replica-test-')"], + "timeout_seconds": 15, + } + ], + }, + ) + out = root / "out" + r = self._run_fanout( + "run", + "--task", + str(task), + "--replicas", + "3", + "--concurrency", + "3", + "--backend", + "local", + "--pi-cmd", + f"{sys.executable} {fake_pi}", + "--output", + str(out), + ) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + summary = json.loads(r.stdout) + self.assertTrue(summary["all_passed"]) + self.assertEqual(summary["passed_workers"], 3) + self.assertEqual(len(summary["workers"]), 3) + for w in summary["workers"]: + self.assertEqual(w["status"], "ok") + self.assertEqual(w["changed_files"], ["out.txt"]) + self.assertEqual(w["checks_passed"], 1) + self.assertIn("done replica-test-", w["handoff_summary"]) + + # Refuses reusing non-empty output directory + r_dup = self._run_fanout( + "run", + "--task", + str(task), + "--replicas", + "1", + "--backend", + "local", + "--pi-cmd", + f"{sys.executable} {fake_pi}", + "--output", + str(out), + ) + self.assertEqual(r_dup.returncode, 2) + + def test_local_scope_violation_and_timeout_isolated_per_worker(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + fake_pi = _make_fake_pi( + root, + """ +import json, sys, time +from pathlib import Path +args = sys.argv[1:] +task = json.loads(Path(args[args.index("--coordination-task") + 1]).read_text(encoding="utf-8")) +out_dir = Path(task["output_directory"]) +if task["task_id"] == "slow": + time.sleep(10) +elif task["task_id"] == "rogue": + Path("forbidden.txt").write_text("bad", encoding="utf-8") + (out_dir / "model-report.json").write_text(json.dumps({"summary": "rogue"}), encoding="utf-8") +else: + Path("ok.txt").write_text("good", encoding="utf-8") + (out_dir / "model-report.json").write_text(json.dumps({"summary": "good"}), encoding="utf-8") +""", + ) + batch = _write_json( + root / "batch.json", + { + "version": 1, + "batch_id": "mixed-outcomes", + "backend": "local", + "concurrency": 3, + "tasks": [ + {"worker_id": "w-ok", "task_id": "good", "kind": "implementation", "instructions": "ok", "writable_paths": ["ok.txt"], "wall_seconds": 10}, + {"worker_id": "w-rogue", "task_id": "rogue", "kind": "implementation", "instructions": "rogue", "writable_paths": ["ok.txt"], "wall_seconds": 10}, + {"worker_id": "w-slow", "task_id": "slow", "kind": "validation", "instructions": "slow", "writable_paths": [], "wall_seconds": 1}, + ], + }, + ) + out = root / "out" + r = self._run_fanout( + "run", + str(batch), + "--pi-cmd", + f"{sys.executable} {fake_pi}", + "--output", + str(out), + ) + self.assertEqual(r.returncode, 1) + summary = json.loads(r.stdout) + by_id = {w["worker_id"]: w for w in summary["workers"]} + self.assertEqual(by_id["w-ok"]["status"], "ok") + self.assertEqual(by_id["w-rogue"]["status"], "scope_violation") + self.assertEqual(by_id["w-slow"]["status"], "timeout") + self.assertEqual(summary["passed_workers"], 1) + self.assertEqual(summary["failed_workers"], 2) + self.assertEqual(summary["timed_out_workers"], 1) + + def test_openshell_pool_refuses_duplicates_and_protected_sandboxes(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + p1 = _write_json(root / "p1.json", {"sandbox_name": "sb-a", "sandbox_id": "id-a", "protected_sandboxes": ["durable"]}) + p2_dup = _write_json(root / "p2.json", {"sandbox_name": "sb-a", "sandbox_id": "id-b"}) + p_prot = _write_json(root / "p3.json", {"sandbox_name": "durable", "sandbox_id": "id-c"}) + task = _write_json(root / "t.json", {"task_id": "t1", "kind": "validation", "instructions": "check"}) + + r1 = self._run_fanout("run", "--task", str(task), "--replicas", "2", "--backend", "openshell", "--profiles", str(p1), str(p2_dup), "--output", str(root / "o1"), "--dry-run") + self.assertEqual(r1.returncode, 2) + self.assertIn("Duplicate sandbox_name", r1.stderr) + + r2 = self._run_fanout("run", "--task", str(task), "--replicas", "2", "--backend", "openshell", "--profiles", str(p1), str(p_prot), "--output", str(root / "o2"), "--dry-run") + self.assertEqual(r2.returncode, 2) + self.assertIn("protected_sandboxes", r2.stderr) + + def test_openshell_pool_parallel_dispatch_leases_distinct_sandboxes(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + p1 = _write_json(root / "p1.json", {"sandbox_name": "sb-1", "sandbox_id": "id-1"}) + p2 = _write_json(root / "p2.json", {"sandbox_name": "sb-2", "sandbox_id": "id-2"}) + fake_coord = _make_fake_pi( + root, + """ +import json, sys, time +from pathlib import Path +args = sys.argv[1:] +prof = json.loads(Path(args[args.index("--profile") + 1]).read_text(encoding="utf-8")) +out_dir = Path(args[args.index("--output") + 1]) +out_dir.mkdir(parents=True, exist_ok=True) +time.sleep(0.05) +(out_dir / "receipt.json").write_text(json.dumps({ + "delivery_valid": True, + "changed_files": [], + "checks": [], + "handoff": {"summary": "ran on " + prof["sandbox_name"]}, +}), encoding="utf-8") +""", + ) + task = _write_json(root / "t.json", {"task_id": "os-test", "kind": "validation", "instructions": "check"}) + out = root / "out" + r = self._run_fanout( + "run", + "--task", + str(task), + "--replicas", + "3", + "--concurrency", + "2", + "--backend", + "openshell", + "--profiles", + str(p1), + str(p2), + "--coordinate-script", + str(fake_coord), + "--output", + str(out), + ) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + summary = json.loads(r.stdout) + self.assertTrue(summary["all_passed"]) + self.assertEqual(summary["effective_concurrency"], 2) + self.assertEqual(summary["passed_workers"], 3) + used_sandboxes = {w["sandbox_name"] for w in summary["workers"]} + self.assertEqual(used_sandboxes, {"sb-1", "sb-2"}) + + +if __name__ == "__main__": + unittest.main()