From 1ddd3e0eb65782f79547bd4ffb7152cdce945f4d Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 13:37:21 -0800 Subject: [PATCH 1/8] Add capability-checked Pi model and thinking options --- .../.codex-plugin/plugin.json | 2 +- plugins/codex-pi-coordination/README.md | 33 +- .../extensions/coordination.js | 30 +- plugins/codex-pi-coordination/package.json | 2 +- .../scripts/coordinate.py | 502 +++++++++++++++++- .../skills/codex-pi-coordination/SKILL.md | 63 ++- .../references/task-contract.md | 115 +++- .../tests/extension.test.mjs | 32 ++ .../tests/test_coordinate.py | 247 ++++++++- 9 files changed, 976 insertions(+), 50 deletions(-) diff --git a/plugins/codex-pi-coordination/.codex-plugin/plugin.json b/plugins/codex-pi-coordination/.codex-plugin/plugin.json index f9d4b23..be15d05 100644 --- a/plugins/codex-pi-coordination/.codex-plugin/plugin.json +++ b/plugins/codex-pi-coordination/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "codex-pi-coordination", - "version": "0.1.1", + "version": "0.2.0", "description": "Coordinate bounded implementation, research, review and validation tasks between Codex and Pi inside NVIDIA OpenShell.", "author": { "name": "Fakoli", diff --git a/plugins/codex-pi-coordination/README.md b/plugins/codex-pi-coordination/README.md index d7fc86f..58fbbad 100644 --- a/plugins/codex-pi-coordination/README.md +++ b/plugins/codex-pi-coordination/README.md @@ -6,12 +6,28 @@ native Pi extension returns work; a stdlib runner records actual checks, source changes and managed cleanup. Model selection is explicit and provider-neutral, including configured GLM routes. -From the plugin directory, with an existing private runtime profile: +From the plugin directory, register an existing private runtime profile once, +then use the default for discovery and runs. Paths below are synthetic examples: ```sh +python3 scripts/coordinate.py configure --profile /path/to/private/profile.json +python3 scripts/coordinate.py capabilities --output /private/evidence/new-capabilities python3 scripts/coordinate.py run task.json --output /private/evidence/new-run ``` +`configure` validates and registers `~/.config/codex-pi-coordination/profile.json`. +Identical settings are a no-op; conflicting defaults and symlinks refuse. It +does not copy credentials or qualify the runtime. `capabilities` uses the owned +disposable sandbox with zero prompts, tools or extensions, returning available +provider/model IDs and the configured model's supported thinking levels. + +Version-2 tasks may add `run_options`: an exact `provider`/`model` pair, +`thinking` alone, or both. Omitted options inherit the profile. `auto`, `dynamic` +and the literal `default` are refused; use omission for Default. Unsupported or +silently clamped selections fail before the task prompt, without fallback. +Version-1 task inputs remain readable. All new runs use bounded native RPC with +`--no-session`; saved-session continuation remains future work (P1b). + See the [skill](skills/codex-pi-coordination/SKILL.md) and [task/profile contract](skills/codex-pi-coordination/references/task-contract.md). Codex discovers the skill through the marketplace entry. The Pi package exposes @@ -21,12 +37,17 @@ The extension provides `coordination_status`, `coordination_handoff` and `/coordination-status`. File tools stay inside the assigned workspace, writes name exact files, and tool/turn budgets stop further work. Declared verification argv runs after Pi exits. Task policy is not an OS sandbox: OpenShell remains -the isolation and lifecycle owner. No background service, recursive Codex launch, -provider change or automatic patch application is installed. +the isolation and lifecycle owner. Selection is confined to the ephemeral Pi +child; global provider/model settings stay unchanged. No background service, +recursive Codex launch or automatic patch application is installed. -`delivery_valid` means a bounded handoff completed, not application acceptance, -latency qualification or deployment authority. Keep failed runs and actual -operator profiles/evidence outside public plugin source. +Inspect `rpc-configuration.json` and the worker receipt's `configuration` with +the existing changes/check evidence. They bind requested, inherited and +effective options, prompt admission, settlement and shutdown. `delivery_valid` +means a bounded handoff completed, not application acceptance, latency +qualification or deployment authority. `capabilities_valid` covers metadata +discovery and cleanup only. Keep failed runs and actual operator profiles and +evidence outside public plugin source. On execution failure, nonzero worker exit or timeout, the runner immediately enters managed OpenShell cleanup: verify identity, stop and record the readback. diff --git a/plugins/codex-pi-coordination/extensions/coordination.js b/plugins/codex-pi-coordination/extensions/coordination.js index f66e9d2..89d08df 100644 --- a/plugins/codex-pi-coordination/extensions/coordination.js +++ b/plugins/codex-pi-coordination/extensions/coordination.js @@ -68,12 +68,19 @@ export function loadTask(taskPath, cwd) { fs.closeSync(descriptor); } const task = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)); - if (!task || typeof task !== "object" || Array.isArray(task) || task.version !== 1 || !taskKinds.has(task.kind)) { - fail("invalid_task", "Expected a version 1 coordination task and supported kind"); + if (!task || typeof task !== "object" || Array.isArray(task) || ![1, 2].includes(task.version) || !taskKinds.has(task.kind)) { + fail("invalid_task", "Expected a supported versioned coordination task and kind"); } for (const key of ["run_id", "task_id"]) { if (!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(boundedString(task[key], key, 128))) fail("invalid_task", `Invalid ${key}`); } + if (task.version === 2) { + const options = task.run_options; + const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; + const identifier = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}$/.test(value) && !value.includes("://"); + if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => !["provider", "model", "thinking"].includes(key)) || (("provider" in options) !== ("model" in options)) || ("provider" in options && (!identifier(options.provider) || !identifier(options.model))) || ("thinking" in options && !levels.includes(options.thinking))) fail("invalid_task", "Invalid version 2 run options"); + if (task.operation !== "run" || !task.runtime_defaults || Object.keys(task.runtime_defaults).sort().join(",") !== "model,thinking" || !identifier(task.runtime_defaults.model) || !levels.includes(task.runtime_defaults.thinking)) fail("invalid_task", "Invalid version 2 runtime defaults"); + } boundedString(task.instructions, "instructions", 48000); for (const key of ["workspace", "output_directory"]) { if (!path.isAbsolute(boundedString(task[key], key, 4096))) fail("invalid_task", `${key} must be absolute`); @@ -141,6 +148,7 @@ export default function coordinationExtension(pi) { let toolCalls = 0; let turns = 0; let handedOff = false; + let configurationRecorded = false; const requested = () => pi.getFlag("coordination-task"); const status = () => ({ active: Boolean(loaded), run_id: loaded?.task.run_id, task_id: loaded?.task.task_id, task_sha256: loaded?.taskSha256, tool_calls: toolCalls, turns, handed_off: handedOff, failure }); const record = (type, fields = {}) => { @@ -154,7 +162,7 @@ export default function coordinationExtension(pi) { return { block: true, reason: `${code}: ${message}` }; }; - pi.registerFlag("coordination-task", { type: "string", description: "Absolute path to an external coordinator's version 1 task manifest" }); + pi.registerFlag("coordination-task", { type: "string", description: "Absolute path to an external coordinator's versioned task manifest" }); pi.registerCommand("coordination-status", { description: "Show the current delegated task and bounds", handler: async (_args, ctx) => { if (ctx.hasUI) ctx.ui.notify(JSON.stringify(status()), "info"); }, @@ -213,6 +221,22 @@ export default function coordinationExtension(pi) { stop(ctx, "task_unavailable", "Coordination task is unavailable or already handed off"); return; } + if (loaded.task.version === 2 && !configurationRecorded) { + const configuration = { provider: ctx.model?.provider, model: ctx.model?.id, thinking: pi.getThinkingLevel() }; + if (!configuration.provider || !configuration.model || !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(configuration.thinking)) { + stop(ctx, "configuration_unavailable", "Pi did not expose an effective run configuration"); + return; + } + const options = loaded.task.run_options; + const selectedModel = options.provider ? `${options.provider}/${options.model}` : loaded.task.runtime_defaults.model; + const selectedThinking = options.thinking ?? loaded.task.runtime_defaults.thinking; + if (`${configuration.provider}/${configuration.model}` !== selectedModel || configuration.thinking !== selectedThinking) { + stop(ctx, "configuration_mismatch", "Effective Pi options differ from the approved task"); + return; + } + record("run_configuration", { configuration }); + configurationRecorded = true; + } return { systemPrompt: `${event.systemPrompt}\n\nExternal coordinator task:\n${JSON.stringify({ run_id: loaded.task.run_id, task_id: loaded.task.task_id, kind: loaded.task.kind, instructions: loaded.task.instructions, source: loaded.sourceSummary, writable_paths: loaded.task.writable_paths, max_tool_calls: loaded.task.max_tool_calls, max_turns: loaded.task.max_turns })}\nWork only inside the assigned workspace and declared writable files. Shell execution is unavailable; the coordinator runs declared verification commands after Pi exits. Before the tool budget ends, call coordination_handoff exactly once with an honest self-report. Do not claim acceptance or verification from your report. Tool/path guards are task policy; the external runner owns OS isolation and custody.` }; }); pi.on("turn_start", async (_event, ctx) => { diff --git a/plugins/codex-pi-coordination/package.json b/plugins/codex-pi-coordination/package.json index b94014c..bbb4d2a 100644 --- a/plugins/codex-pi-coordination/package.json +++ b/plugins/codex-pi-coordination/package.json @@ -1,6 +1,6 @@ { "name": "codex-pi-coordination", - "version": "0.1.1", + "version": "0.2.0", "description": "Bounded Pi task handoff for an external Codex coordinator", "type": "module", "license": "MIT", diff --git a/plugins/codex-pi-coordination/scripts/coordinate.py b/plugins/codex-pi-coordination/scripts/coordinate.py index 7ae6949..2b65247 100644 --- a/plugins/codex-pi-coordination/scripts/coordinate.py +++ b/plugins/codex-pi-coordination/scripts/coordinate.py @@ -17,6 +17,7 @@ import os from pathlib import Path, PurePosixPath import re +import selectors import signal import stat import subprocess @@ -31,6 +32,7 @@ MAX_FILES = 10000 KINDS = {"implementation", "research", "review", "validation"} TOOLS = {"read", "grep", "find", "ls", "write", "edit"} +THINKING_LEVELS = {"off", "minimal", "low", "medium", "high", "xhigh", "max"} PLUGIN = Path(__file__).resolve().parents[1] @@ -73,12 +75,16 @@ def relative_file(value): def validate_task(task): required = {"version", "task_id", "kind", "instructions", "writable_paths", "checks"} optional = {"repository", "revision", "max_tool_calls", "max_turns", "wall_seconds"} + if isinstance(task, dict) and type(task.get("version")) is int and task["version"] == 2: + optional.add("run_options") if not isinstance(task, dict) or set(task) - required - optional or required - set(task): - raise ValueError("Task fields do not match the version 1 contract") - if type(task["version"]) is not int or task["version"] != 1 or not isinstance(task["kind"], str) or task["kind"] not in KINDS: + raise ValueError("Task fields do not match the versioned contract") + if type(task["version"]) is not int or task["version"] not in (1, 2) or not isinstance(task["kind"], str) or task["kind"] not in KINDS: raise ValueError("Unsupported task version or kind") - if not isinstance(task["task_id"], str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,79}", task["task_id"]): + pattern = r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}" if task["version"] == 2 else r"[A-Za-z0-9][A-Za-z0-9_.-]{0,79}" + if not isinstance(task["task_id"], str) or not re.fullmatch(pattern, task["task_id"]): raise ValueError("Invalid task_id") + validate_run_options(task.get("run_options", {})) if not isinstance(task["instructions"], str) or not 1 <= len(task["instructions"].encode()) <= 32000: raise ValueError("Instructions must contain 1..32000 bytes") paths = task["writable_paths"] @@ -107,6 +113,23 @@ def validate_task(task): return task +def model_identifier(value): + if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}", value) or "://" in value: + raise ValueError("Expected a bounded model identifier, not a URL or command") + return value + + +def validate_run_options(options): + if not isinstance(options, dict) or set(options) - {"provider", "model", "thinking"} or (("provider" in options) != ("model" in options)): + raise ValueError("run_options requires a provider/model pair and optional thinking") + for key in ("provider", "model"): + if key in options: + model_identifier(options[key]) + if "thinking" in options and (not isinstance(options["thinking"], str) or options["thinking"] not in THINKING_LEVELS): + raise ValueError("Unsupported thinking selection; omit it to inherit the profile") + return options + + def safe_archive_files(raw): """Git archives are data; reject links, devices, duplicates and traversal.""" files, total = {}, 0 @@ -232,7 +255,12 @@ def inspect_extension_events(path, task, pi_events, task_sha256): kinds = [event.get("type") for event in events] if kinds[0] != "task_loaded" or kinds.count("task_loaded") != 1 or kinds.count("handoff") != 1 or kinds.count("agent_settled") != 1 or kinds.count("session_shutdown") != 1 or kinds[-2:] != ["agent_settled", "session_shutdown"]: raise ValueError("Incomplete or unordered extension lifecycle") - if set(kinds) - {"task_loaded", "tool_call", "handoff", "agent_settled", "session_shutdown"} or any(event.get("failure") for event in events): + allowed_kinds = {"task_loaded", "tool_call", "handoff", "agent_settled", "session_shutdown"} + if task["version"] == 2: + allowed_kinds.add("run_configuration") + if kinds.count("run_configuration") != 1 or kinds[1] != "run_configuration": + raise ValueError("Missing or unordered extension run configuration") + if set(kinds) - allowed_kinds or any(event.get("failure") for event in events): raise ValueError("Extension refused the delegated task") for event in events: if event.get("run_id") != task["run_id"] or event.get("task_id") != task["task_id"] or event.get("task_sha256") != task_sha256: @@ -256,7 +284,349 @@ def inspect_extension_events(path, task, pi_events, task_sha256): # The final assistant response follows the handoff tool in a new turn. if not 1 <= events[handoff_index]["turns"] <= pi_events["assistant_turns"] or any(event["turns"] != pi_events["assistant_turns"] for event in events[-2:]): raise ValueError("Extension turn accounting differs from Pi") - return {"event_log_sha256": digest(raw), "model": events[0].get("model"), "tool_calls": len(calls), "assistant_turns": pi_events["assistant_turns"]} + result = {"event_log_sha256": digest(raw), "model": events[0].get("model"), "tool_calls": len(calls), "assistant_turns": pi_events["assistant_turns"]} + if task["version"] == 2: + result["configuration"] = validate_run_options(events[1].get("configuration")) + if set(result["configuration"]) != {"provider", "model", "thinking"}: + raise ValueError("Incomplete extension run configuration") + return result + + +RPC_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." + + +def rpc_model(value): + if not isinstance(value, dict): + raise ValueError("Missing RPC model identity") + return {"provider": model_identifier(value.get("provider")), "id": model_identifier(value.get("id"))} + + +def rpc_data(command, data): + """Discard model API objects, headers, URLs and free-form error messages.""" + if command == "get_available_models": + if not isinstance(data, dict) or not isinstance(data.get("models"), list) or len(data["models"]) > 1000: + raise ValueError("Invalid RPC model catalog") + models = [rpc_model(model) for model in data["models"]] + if len({(model["provider"], model["id"]) for model in models}) != len(models): + raise ValueError("Duplicate RPC model identity") + return {"models": models} + if command == "get_available_thinking_levels": + levels = data.get("levels") if isinstance(data, dict) else None + if not isinstance(levels, list) or not levels or any(not isinstance(level, str) or level not in THINKING_LEVELS for level in levels) or len(set(levels)) != len(levels): + raise ValueError("Invalid RPC thinking capabilities") + return {"levels": levels} + if command == "get_state": + if not isinstance(data, dict) or any(type(data.get(key)) is not bool for key in ("isStreaming", "isCompacting")) or type(data.get("pendingMessageCount")) is not int or data["pendingMessageCount"] < 0: + raise ValueError("Invalid RPC state") + if data.get("sessionFile") is not None or not isinstance(data.get("sessionId"), str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", data["sessionId"]): + raise ValueError("RPC must use an exact nonpersistent session") + thinking = data.get("thinkingLevel") + if not isinstance(thinking, str) or thinking not in THINKING_LEVELS: + raise ValueError("Invalid effective thinking level") + return {"model": rpc_model(data.get("model")), "thinkingLevel": thinking, + "isStreaming": data["isStreaming"], "isCompacting": data["isCompacting"], + "pendingMessageCount": data["pendingMessageCount"], "sessionId": data["sessionId"], "sessionFile": None} + if command == "set_model": + return rpc_model(data) + if command in {"set_thinking_level", "prompt"}: + return None + raise ValueError("Unexpected RPC command") + + +class PiRpc: + """One bounded stdlib RPC child; OpenShell remains its lifecycle owner.""" + def __init__(self, command, workspace, output, deadline, env): + self.deadline, self.output = deadline, output + self.pending, self.responses, self.records = {}, {}, [] + self.sequence, self.bytes_seen, self.settled = 0, 0, 0 + self.prompt_sent, self.stdin_closed = False, False + self.buffer, self.outgoing = b"", b"" + self.selector = selectors.DefaultSelector() + self.events = (output / "pi-events.jsonl").open("xb") + self.stderr = (output / "pi-stderr.log").open("xb") + self.control = (output / "rpc-events.jsonl").open("x", encoding="utf-8") + self.process = subprocess.Popen(command, cwd=workspace, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0) + for stream in (self.process.stdin, self.process.stdout, self.process.stderr): + os.set_blocking(stream.fileno(), False) + self.selector.register(self.process.stdout, selectors.EVENT_READ, "stdout") + self.selector.register(self.process.stderr, selectors.EVENT_READ, "stderr") + + def record(self, value): + self.records.append(value) + if len(self.records) > 10000: + raise ValueError("RPC record count exceeded") + self.control.write(json.dumps(value, ensure_ascii=True) + "\n") + self.control.flush() + if self.control.tell() > MAX_OUTPUT_BYTES: + raise ValueError("RPC control output exceeded") + + def send(self, command, **arguments): + self.sequence += 1 + request_id = f"request-{self.sequence}" + if command == "prompt": + if self.prompt_sent: + raise ValueError("A run permits exactly one prompt") + self.prompt_sent = True + self.pending[request_id] = command + retained = {"message_sha256": digest(arguments["message"].encode())} if command == "prompt" else arguments + self.record({"type": "request", "id": request_id, "command": command, "arguments": retained}) + self.outgoing += (json.dumps({"id": request_id, "type": command, **arguments}) + "\n").encode() + try: + self.selector.register(self.process.stdin, selectors.EVENT_WRITE, "stdin") + except KeyError: + pass + return request_id + + def consume(self, raw): + try: + value = json.loads(raw.decode("utf-8")) + except (UnicodeError, ValueError): + raise ValueError("Malformed Pi RPC JSONL") from None + if not isinstance(value, dict) or not isinstance(value.get("type"), str): + raise ValueError("Malformed Pi RPC record") + if value["type"] == "response": + request_id = value.get("id") + if not isinstance(request_id, str) or request_id not in self.pending or value.get("command") != self.pending[request_id]: + raise ValueError("Unmatched or duplicate RPC response") + command = self.pending.pop(request_id) + if value.get("success") is not True: + self.record({"type": "response", "id": request_id, "command": command, "success": False}) + raise ValueError("Pi RPC command refused: " + command) + safe = rpc_data(command, value.get("data")) + self.record({"type": "response", "id": request_id, "command": command, "success": True, "data": safe}) + self.responses[request_id] = safe + return + if not self.prompt_sent or value["type"] in {"extension_ui_request", "error"}: + raise ValueError("Unexpected activity outside the approved task prompt") + if value["type"] == "agent_settled": + self.settled += 1 + if self.settled != 1: + raise ValueError("Unexpected repeated RPC settlement") + self.record({"type": "event", "event": "agent_settled"}) + self.events.write(json.dumps(value, ensure_ascii=True).encode() + b"\n") + self.events.flush() + if self.events.tell() > MAX_OUTPUT_BYTES: + raise ValueError("Pi event output exceeded") + + def pump(self): + remaining = self.deadline - time.monotonic() + if remaining <= 0: + raise ValueError("Pi RPC deadline exceeded") + for key, _mask in self.selector.select(min(0.1, remaining)): + if key.data == "stdin": + try: + count = os.write(key.fd, self.outgoing) + except BrokenPipeError: + raise ValueError("Pi RPC stdin closed before acknowledgement") from None + self.outgoing = self.outgoing[count:] + if not self.outgoing: + self.selector.unregister(key.fileobj) + continue + raw = os.read(key.fd, 65536) + if not raw: + self.selector.unregister(key.fileobj) + if key.data == "stdout" and self.buffer: + raise ValueError("Partial Pi RPC JSONL at EOF") + continue + self.bytes_seen += len(raw) + if self.bytes_seen > MAX_OUTPUT_BYTES: + raise ValueError("Pi RPC aggregate output exceeded") + if key.data == "stderr": + self.stderr.write(raw) + self.stderr.flush() + else: + self.buffer += raw + while b"\n" in self.buffer: + line, self.buffer = self.buffer.split(b"\n", 1) + self.consume(line.removesuffix(b"\r")) + if self.process.poll() is not None and not self.selector.get_map() and not self.stdin_closed: + raise ValueError("Pi RPC exited before orderly shutdown") + + def wait(self, request_id): + while request_id not in self.responses: + self.pump() + return self.responses[request_id] + + def call(self, command, **arguments): + return self.wait(self.send(command, **arguments)) + + def finish(self): + if self.pending or self.outgoing: + raise ValueError("RPC has unacknowledged commands") + self.stdin_closed = True + self.record({"type": "stdin_closed"}) + self.process.stdin.close() + while self.process.poll() is None or self.selector.get_map(): + self.pump() + if self.process.wait() != 0: + raise ValueError("Pi RPC exited unsuccessfully") + self.record({"type": "exit", "exit_code": 0}) + + def close(self): + # On error EOF is best effort, never proof of remote cleanup. The host + # immediately enters its existing managed OpenShell stop path. + if not self.process.stdin.closed: + self.process.stdin.close() + try: + self.process.wait(timeout=0.2) + except subprocess.TimeoutExpired: + pass + self.selector.close() + for stream in (self.process.stdout, self.process.stderr, self.events, self.stderr, self.control): + stream.close() + + +def desired_configuration(task, models): + requested = validate_run_options(task["run_options"]) + defaults = task["runtime_defaults"] + if not isinstance(defaults, dict) or set(defaults) != {"model", "thinking"} or not isinstance(defaults["model"], str) or not isinstance(defaults["thinking"], str) or defaults["thinking"] not in THINKING_LEVELS: + raise ValueError("Invalid bound runtime defaults") + if "provider" in requested: + candidates = [model for model in models if model["provider"] == requested["provider"] and model["id"] == requested["model"]] + else: + candidates = [model for model in models if model["provider"] + "/" + model["id"] == defaults["model"]] + if len(candidates) != 1: + raise ValueError("Requested model is unavailable or ambiguous") + return {"provider": candidates[0]["provider"], "model": candidates[0]["id"], "thinking": requested.get("thinking", defaults["thinking"])} + + +def require_rpc_idle(state, effective=None, session_id=None): + if state["isStreaming"] or state["isCompacting"] or state["pendingMessageCount"] != 0: + raise ValueError("Pi RPC is not idle with an empty queue") + actual = {"provider": state["model"]["provider"], "model": state["model"]["id"], "thinking": state["thinkingLevel"]} + if (effective is not None and actual != effective) or (session_id is not None and state["sessionId"] != session_id): + raise ValueError("Pi effective model/thinking/session differs from the approved selection") + + +def rpc_configuration_record(task, models, levels, effective, session_id, results): + task_run = task["operation"] == "run" + return {"version": 1, "operation": task["operation"], "requested": task["run_options"], + "defaults": task["runtime_defaults"], "available_models": models, + "supported_thinking_levels": levels, "effective": effective, + "session_id": session_id, "session_file": None, "prompt_sent": task_run, + "settled": task_run, "shutdown": "stdin-eof", + "rpc_log_sha256": digest((results / "rpc-events.jsonl").read_bytes()), + "stderr_sha256": digest((results / "pi-stderr.log").read_bytes())} + + +def run_rpc(root, task, launch, deadline, env): + metadata = task["operation"] == "capabilities" + command = [*launch["pi_argv"], "--offline", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-approve", "--tools", "" if metadata else ",".join([*task["allowed_tools"], "coordination_status", "coordination_handoff"]), "--mode", "rpc"] + if not metadata: + command += ["--extension", str(root / "extension.js"), "--coordination-task", str(root / "task.json")] + rpc = PiRpc(command, root / "workspace", root / "results", deadline, env) + try: + models_request = rpc.send("get_available_models") + initial_request = rpc.send("get_state") + models = rpc.wait(models_request)["models"] + initial = rpc.wait(initial_request) + require_rpc_idle(initial) + effective = desired_configuration(task, models) + model_changed = initial["model"] != {"provider": effective["provider"], "id": effective["model"]} + if model_changed: + selected = rpc.call("set_model", provider=effective["provider"], modelId=effective["model"]) + if selected != {"provider": effective["provider"], "id": effective["model"]}: + raise ValueError("Pi selected a different model") + levels = rpc.call("get_available_thinking_levels")["levels"] + if effective["thinking"] not in levels: + raise ValueError("Selected model does not support requested thinking") + if model_changed or initial["thinkingLevel"] != effective["thinking"]: + rpc.call("set_thinking_level", level=effective["thinking"]) + admitted = rpc.call("get_state") + require_rpc_idle(admitted, effective, initial["sessionId"]) + if not metadata: + rpc.call("prompt", message=RPC_PROMPT) + while not rpc.settled: + rpc.pump() + require_rpc_idle(rpc.call("get_state"), effective, initial["sessionId"]) + rpc.finish() + configuration = rpc_configuration_record(task, models, levels, effective, initial["sessionId"], root / "results") + write_new_json(root / "results/rpc-configuration.json", configuration) + return configuration + except Exception as error: + if rpc.process.poll() is not None: + error.pi_exit_code = rpc.process.returncode + raise + finally: + rpc.close() + + +def verify_rpc_configuration(results, task): + """Reconstruct configuration from sanitized control records and bound input.""" + raw = (results / "rpc-events.jsonl").read_bytes() + if len(raw) > MAX_OUTPUT_BYTES: + raise ValueError("RPC transcript exceeds bounds") + records = [json.loads(line) for line in raw.split(b"\n") if line] + if not records or len(records) > 10000 or records[-2:] != [{"type": "stdin_closed"}, {"type": "exit", "exit_code": 0}]: + raise ValueError("RPC transcript lacks orderly shutdown") + requests, responses, events = [], {}, [] + for index, record in enumerate(records[:-2]): + if not isinstance(record, dict): + raise ValueError("Invalid RPC transcript record") + kind = record.get("type") + if kind == "request": + if set(record) != {"type", "id", "command", "arguments"} or record["id"] != f"request-{len(requests) + 1}" or not isinstance(record["arguments"], dict): + raise ValueError("Invalid RPC request binding") + requests.append((index, record)) + elif kind == "response": + if set(record) != {"type", "id", "command", "success", "data"} or record["success"] is not True or not isinstance(record["id"], str) or record["id"] in responses: + raise ValueError("Invalid RPC response binding") + matched = [request for _position, request in requests if request["id"] == record["id"]] + if len(matched) != 1 or record["command"] != matched[0]["command"] or rpc_data(record["command"], record["data"]) != record["data"]: + raise ValueError("RPC response differs from its safe request contract") + responses[record["id"]] = (index, record["data"]) + elif record == {"type": "event", "event": "agent_settled"}: + events.append(index) + else: + raise ValueError("Unknown RPC control record") + if len(requests) != len(responses) or len(requests) < 4: + raise ValueError("Incomplete RPC command sequence") + for number, (index, request) in enumerate(requests): + # Only the first two metadata queries may be outstanding together. + if number >= 2 and any(responses[prior["id"]][0] > index for _position, prior in requests[:number]): + raise ValueError("RPC admission precedes required acknowledgement") + def data(number): + if number >= len(requests): + raise ValueError("Incomplete RPC command sequence") + return responses[requests[number][1]["id"]][1] + if [request["command"] for _index, request in requests[:2]] != ["get_available_models", "get_state"]: + raise ValueError("RPC metadata preflight missing") + models, initial = data(0)["models"], data(1) + require_rpc_idle(initial) + effective = desired_configuration(task, models) + target_model = {"provider": effective["provider"], "id": effective["model"]} + changed = initial["model"] != target_model + expected = [("get_available_models", {}), ("get_state", {})] + if changed: + expected.append(("set_model", {"provider": effective["provider"], "modelId": effective["model"]})) + if data(2) != target_model: + raise ValueError("RPC returned the wrong selected model") + levels_index = len(expected) + expected.append(("get_available_thinking_levels", {})) + levels = data(levels_index)["levels"] + if effective["thinking"] not in levels: + raise ValueError("RPC selected unsupported thinking") + if changed or initial["thinkingLevel"] != effective["thinking"]: + expected.append(("set_thinking_level", {"level": effective["thinking"]})) + admitted_index = len(expected) + expected.append(("get_state", {})) + metadata = task["operation"] == "capabilities" + if not metadata: + expected += [("prompt", {"message_sha256": digest(RPC_PROMPT.encode())}), ("get_state", {})] + if [(request["command"], request["arguments"]) for _index, request in requests] != expected: + raise ValueError("RPC commands differ from approved options") + require_rpc_idle(data(admitted_index), effective, initial["sessionId"]) + if metadata: + if events or (results / "pi-events.jsonl").read_bytes(): + raise ValueError("Metadata discovery performed model activity") + else: + if len(events) != 1 or not requests[-2][0] < events[0] < requests[-1][0]: + raise ValueError("RPC completion did not settle before final state read") + require_rpc_idle(data(len(requests) - 1), effective, initial["sessionId"]) + expected_configuration = rpc_configuration_record(task, models, levels, effective, initial["sessionId"], results) + if read_json(results / "rpc-configuration.json") != expected_configuration: + raise ValueError("RPC configuration receipt differs from actual control records") + return expected_configuration def worker(root): @@ -264,7 +634,7 @@ def worker(root): root = Path(root).resolve(strict=True) task, launch = read_json(root / "task.json"), read_json(root / "launch.json") workspace, output = root / "workspace", root / "results" - receipt = {"version": 1, "run_id": task["run_id"], "task_id": task["task_id"], "started_at": utc_now(), "outcome": "incomplete", "checks": []} + receipt = {"version": task["version"], "run_id": task["run_id"], "task_id": task["task_id"], "started_at": utc_now(), "outcome": "incomplete", "checks": []} write_new_json(root / "worker-started.json", receipt) deadline = time.monotonic() + launch["wall_seconds"] before = snapshot(workspace) @@ -275,11 +645,24 @@ def worker(root): env = os.environ.copy() env.update(launch["environment"]) env["PYTHONDONTWRITEBYTECODE"] = "1" - receipt["pi_exit_code"] = execute_to_log(command, workspace, output / "pi-events.jsonl", deadline - time.monotonic(), remote_owner=True, env=env) + if task["version"] == 2: + receipt["configuration"] = run_rpc(root, task, launch, deadline, env) + receipt["pi_exit_code"] = 0 + if task["operation"] == "capabilities": + if snapshot(workspace) != before: + raise ValueError("Metadata discovery changed source") + receipt["outcome"] = "capabilities" + receipt["acceptance"] = "not_granted" + receipt["artifact_sha256"] = {name: digest(data) for name, data in snapshot(output).items()} + return 0 + else: + receipt["pi_exit_code"] = execute_to_log(command, workspace, output / "pi-events.jsonl", deadline - time.monotonic(), remote_owner=True, env=env) if receipt["pi_exit_code"] != 0: raise ValueError("Pi exited unsuccessfully") receipt["events"] = inspect_events(output / "pi-events.jsonl", task["max_tool_calls"], task["max_turns"]) receipt["extension"] = inspect_extension_events(output / "extension-events.jsonl", task, receipt["events"], digest((root / "task.json").read_bytes())) + if task["version"] == 2 and receipt["extension"].get("configuration") != receipt["configuration"]["effective"]: + raise ValueError("Extension effective options differ from RPC admission") report = read_json(output / "model-report.json") if report.get("run_id") != task["run_id"] or report.get("task_id") != task["task_id"] or report.get("model_self_report") is not True or report.get("task_sha256") != digest((root / "task.json").read_bytes()): raise ValueError("Model handoff identity mismatch") @@ -325,6 +708,8 @@ def worker(root): receipt["acceptance"] = "not_granted" receipt["artifact_sha256"] = {name: digest(data) for name, data in snapshot(output).items()} except Exception as error: + if getattr(error, "pi_exit_code", None) is not None: + receipt["pi_exit_code"] = error.pi_exit_code receipt["error"] = str(error) finally: receipt["ended_at"] = utc_now() @@ -342,8 +727,19 @@ def verify_return(results, task, source_files, run_id): observed_artifacts = {name: digest(data) for name, data in actual.items() if name != "worker-receipt.json"} if expected_artifacts != observed_artifacts: raise ValueError("Returned artifact manifest differs from actual bytes") - if receipt.get("run_id") != run_id or receipt.get("task_id") != task["task_id"] or receipt.get("outcome") != "returned" or type(receipt.get("pi_exit_code")) is not int or receipt["pi_exit_code"] != 0 or receipt.get("acceptance") != "not_granted": + if receipt.get("version") != task["version"]: + raise ValueError("Worker receipt version differs from task") + metadata = task.get("operation") == "capabilities" + if receipt.get("run_id") != run_id or receipt.get("task_id") != task["task_id"] or receipt.get("outcome") != ("capabilities" if metadata else "returned") or type(receipt.get("pi_exit_code")) is not int or receipt["pi_exit_code"] != 0 or receipt.get("acceptance") != "not_granted": raise ValueError("Worker identity or completion contract mismatch") + if task["version"] == 2: + configuration = verify_rpc_configuration(results, task) + if receipt.get("configuration") != configuration: + raise ValueError("Worker configuration differs from the verified RPC return") + if metadata: + if set(actual) != {"worker-receipt.json", "rpc-events.jsonl", "pi-events.jsonl", "pi-stderr.log", "rpc-configuration.json"} or task["writable_paths"] or task["checks"]: + raise ValueError("Metadata return contains task execution artifacts") + return receipt report = read_json(results / "model-report.json") if report.get("task_sha256") != digest(json.dumps(task).encode()) or report.get("task_id") != task["task_id"] or report.get("run_id") != run_id or report.get("model_self_report") is not True or report.get("status") != "completed": raise ValueError("Returned handoff does not bind this task") @@ -355,6 +751,8 @@ def verify_return(results, task, source_files, run_id): extension = inspect_extension_events(results / "extension-events.jsonl", task, events, digest(json.dumps(task).encode())) if receipt.get("extension") != extension: raise ValueError("Recorded extension lifecycle differs from returned log") + if task["version"] == 2 and extension.get("configuration") != configuration["effective"]: + raise ValueError("Extension configuration differs from the verified RPC return") checks = receipt.get("checks") if not isinstance(checks, list) or len(checks) != len(task["checks"]): raise ValueError("Missing declared check result") @@ -423,7 +821,7 @@ def profile_settings(path): protected = profile.get("protected_sandboxes", []) if not isinstance(protected, list) or any(not isinstance(name, str) or not name or name.startswith("-") for name in protected): raise ValueError("Invalid protected sandbox names") - if not isinstance(profile.get("thinking", "high"), str) or profile.get("thinking", "high") not in {"off", "minimal", "low", "medium", "high", "xhigh"}: + if not isinstance(profile.get("thinking", "high"), str) or profile.get("thinking", "high") not in THINKING_LEVELS: raise ValueError("Invalid thinking level") if not isinstance(profile.get("python", "python3"), str) or not profile.get("python", "python3") or "\x00" in profile.get("python", "python3"): raise ValueError("Invalid Python executable") @@ -435,6 +833,38 @@ def profile_settings(path): return profile +def configure_profile(source, destination=None): + """Register private settings without overwriting another default or provider.""" + profile = profile_settings(source) + destination = Path(destination) if destination is not None else Path.home() / ".config/codex-pi-coordination/profile.json" + destination = destination.absolute() + for path in (destination, *destination.parents): + if path.is_symlink(): + raise ValueError("Default profile path must not traverse symlinks") + missing = [] + parent = destination.parent + while not parent.exists(): + missing.append(parent) + parent = parent.parent + for parent in reversed(missing): + parent.mkdir(mode=0o700) + directory = destination.parent.stat() + if directory.st_uid != os.getuid() or stat.S_IMODE(directory.st_mode) != 0o700: + raise ValueError("Default profile directory must be owned and private (0700)") + if destination.exists(): + current = destination.stat() + if current.st_uid != os.getuid() or stat.S_IMODE(current.st_mode) != 0o600 or profile_settings(destination) != profile: + raise ValueError("Existing default profile differs or is not private; preserved") + return {"configured": True, "changed": False, "runtime_verified": False} + descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as output: + json.dump(profile, output, indent=2) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + return {"configured": True, "changed": True, "runtime_verified": False} + + def selected_state(state): return {key: state.get(key) for key in ("id", "name", "phase", "main_process_instance_id", "restart_count")} @@ -516,8 +946,9 @@ def cleanup_owner(owner, profile, receipt, protected): receipt["protected_readback_error"] = str(error) -def run_task(task_file, profile_file, output, lock_root): - task, profile = validate_task(read_json(task_file)), profile_settings(profile_file) +def run_task(task_file, profile_file, output, lock_root, *, capabilities_only=False): + task = validate_task({"version": 2, "task_id": "capabilities", "kind": "validation", "instructions": "Inspect configured runtime metadata without model work.", "writable_paths": [], "checks": [], "wall_seconds": 30} if capabilities_only else read_json(task_file)) + profile = profile_settings(profile_file) files, source = frozen_source(task) output = Path(output).absolute() output.mkdir(parents=True, exist_ok=False) @@ -527,7 +958,7 @@ def run_task(task_file, profile_file, output, lock_root): raise ValueError("remote_parent must be an absolute sandbox path") remote = str(remote_parent / run_id) remote_archive = str(remote_parent.parent / ("codex-pi-" + run_id + ".tar")) - native_task = {"version": 1, "run_id": run_id, "task_id": task["task_id"], "kind": task["kind"], "instructions": task["instructions"], "workspace": remote + "/workspace", "output_directory": remote + "/results", "writable_paths": task["writable_paths"], "allowed_tools": sorted(TOOLS if task["writable_paths"] else TOOLS - {"write", "edit"}), "max_tool_calls": task.get("max_tool_calls", 40), "max_turns": task.get("max_turns", 32), "source": source, "checks": task["checks"]} + native_task = {"version": 2, "run_id": run_id, "task_id": task["task_id"], "kind": task["kind"], "instructions": task["instructions"], "workspace": remote + "/workspace", "output_directory": remote + "/results", "writable_paths": task["writable_paths"], "allowed_tools": sorted(TOOLS if task["writable_paths"] else TOOLS - {"write", "edit"}), "max_tool_calls": task.get("max_tool_calls", 40), "max_turns": task.get("max_turns", 32), "source": source, "checks": task["checks"], "operation": "capabilities" if capabilities_only else "run", "run_options": task.get("run_options", {}), "runtime_defaults": {"model": profile["model"], "thinking": profile.get("thinking", "high")}} if len(json.dumps(native_task).encode()) > 1024 * 1024: raise ValueError("Exported task manifest exceeds 1 MiB") launch = {"pi_argv": profile["pi_argv"], "model": profile["model"], "thinking": profile.get("thinking", "high"), "environment": profile.get("environment", {}), "checks": task["checks"], "wall_seconds": task.get("wall_seconds", 600)} @@ -540,7 +971,7 @@ def run_task(task_file, profile_file, output, lock_root): info.size = len(data) info.mode = source["modes"].get(name.removeprefix("workspace/"), 0o600) if name.startswith("workspace/") else 0o600 archive.addfile(info, io.BytesIO(data)) - receipt = {"version": 1, "run_id": run_id, "task_id": task["task_id"], "kind": task["kind"], "started_at": utc_now(), "source": source, "input_sha256": digest(archive_path.read_bytes()), "remote_artifacts": remote + "/results", "cleanup_complete": False, "outcome": "incomplete"} + receipt = {"version": 2, "run_id": run_id, "task_id": task["task_id"], "kind": task["kind"], "started_at": utc_now(), "source": source, "input_sha256": digest(archive_path.read_bytes()), "remote_artifacts": remote + "/results", "cleanup_complete": False, "outcome": "incomplete"} write_new_json(output / "started.json", receipt) with exclusive_owner(profile, lock_root) as journal: if journal.exists() and not read_json(journal).get("cleanup_complete"): @@ -593,6 +1024,7 @@ def save_journal(): cleanup_owner(owner, profile, receipt, protected) receipt["ended_at"] = utc_now() receipt["delivery_valid"] = receipt["cleanup_complete"] and receipt.get("protected_unchanged", False) and receipt.get("artifacts_verified", False) and receipt.get("exec_exit_code") == 0 and receipt["outcome"] == "returned" + receipt["capabilities_valid"] = receipt["cleanup_complete"] and receipt.get("protected_unchanged", False) and receipt.get("artifacts_verified", False) and receipt.get("exec_exit_code") == 0 and receipt["outcome"] == "capabilities" receipt["acceptance"] = "not_granted" save_journal() write_new_json(output / "receipt.json", receipt) @@ -630,9 +1062,18 @@ def recovery_inputs(failed_directory, profile): if not isinstance(task, dict) or not isinstance(launch, dict): raise ValueError("Invalid retained task/launch") expected_keys = {"version", "run_id", "task_id", "kind", "instructions", "workspace", "output_directory", "writable_paths", "allowed_tools", "max_tool_calls", "max_turns", "source", "checks"} + if task.get("version") == 2: + expected_keys |= {"operation", "run_options", "runtime_defaults"} + if task.get("operation") != "run": + raise ValueError("Only task execution evidence is recoverable") if set(task) != expected_keys: raise ValueError("Unexpected retained native task fields") - validate_task({key: task[key] for key in ("version", "task_id", "kind", "instructions", "writable_paths", "checks", "max_tool_calls", "max_turns")}) + public_task = {key: task[key] for key in ("version", "task_id", "kind", "instructions", "writable_paths", "checks", "max_tool_calls", "max_turns")} + if task["version"] == 2: + public_task["run_options"] = task["run_options"] + if task["runtime_defaults"] != {"model": launch.get("model"), "thinking": launch.get("thinking")}: + raise ValueError("Retained runtime defaults differ from launch") + validate_task(public_task) remote = str(PurePosixPath(profile.get("remote_parent", "/sandbox/codex-pi")) / run_id) if task["run_id"] != run_id or task["task_id"] != original["task_id"] or task["kind"] != original["kind"] or task["source"] != original["source"] or task["workspace"] != remote + "/workspace" or task["output_directory"] != remote + "/results" or original["remote_artifacts"] != task["output_directory"]: raise ValueError("Retained task/source/remote identity mismatch") @@ -659,6 +1100,8 @@ def verify_recovered_artifacts(results, task, source_files): raise ValueError("Expected a regular recovered results directory") actual = snapshot(results) allowed = {"worker-receipt.json", "model-report.json", "pi-events.jsonl", "extension-events.jsonl", "changes.json", "changes.patch"} + if task["version"] == 2: + allowed |= {"rpc-events.jsonl", "pi-stderr.log", "rpc-configuration.json"} allowed.update(check["name"] + suffix for check in task["checks"] for suffix in (".started.json", ".result.json", ".log")) if any(name not in allowed and not name.startswith("changed-files/") for name in actual): raise ValueError("Unexpected recovered artifact") @@ -667,8 +1110,22 @@ def verify_recovered_artifacts(results, task, source_files): raise ValueError("Invalid recovered worker receipt") if "worker-receipt.json" in actual and (worker_receipt.get("run_id") != task["run_id"] or worker_receipt.get("task_id") != task["task_id"] or worker_receipt.get("outcome") not in {"returned", "failed", "incomplete"}): raise ValueError("Recovered worker identity/outcome mismatch") + if "version" in worker_receipt and worker_receipt["version"] != task["version"]: + raise ValueError("Recovered worker version differs from task") if "acceptance" in worker_receipt and worker_receipt["acceptance"] != "not_granted": raise ValueError("Recovered worker claims unauthorized acceptance") + if task["version"] == 2: + for name in ("rpc-events.jsonl", "pi-stderr.log"): + if len(actual.get(name, b"")) > MAX_OUTPUT_BYTES: + raise ValueError("Recovered RPC output exceeds limit") + if "rpc-configuration.json" in actual: + configuration = verify_rpc_configuration(results, task) + if "configuration" in worker_receipt and worker_receipt["configuration"] != configuration: + raise ValueError("Recovered RPC configuration differs from worker") + elif "configuration" in worker_receipt: + raise ValueError("Recovered worker configuration lacks its artifact") + if {"events", "extension", "model_report_sha256", "checks_passed"} & worker_receipt.keys() and "configuration" not in worker_receipt: + raise ValueError("Recovered post-Pi records lack RPC admission evidence") manifest = {name: digest(data) for name, data in actual.items() if name != "worker-receipt.json"} if "artifact_sha256" in worker_receipt and worker_receipt["artifact_sha256"] != manifest: raise ValueError("Recovered artifact manifest differs from actual bytes") @@ -712,6 +1169,8 @@ def verify_recovered_artifacts(results, task, source_files): if "extension" in worker_receipt: if events is None or "extension-events.jsonl" not in actual or worker_receipt["extension"] != inspect_extension_events(results / "extension-events.jsonl", task, events, task_hash): raise ValueError("Recovered extension binding mismatch") + if task["version"] == 2 and worker_receipt["extension"].get("configuration") != worker_receipt.get("configuration", {}).get("effective"): + raise ValueError("Recovered extension/RPC configuration differs") # An interrupted final JSONL write may be incomplete. Every complete extension # record that is present must still bind the retained task, even without a receipt. if "extension-events.jsonl" in actual: @@ -778,6 +1237,8 @@ def verify_recovered_artifacts(results, task, source_files): raise ValueError("Recovered change bytes lack their source manifest") complete = all(key in worker_receipt for key in ("artifact_sha256", "events", "extension", "model_report_sha256", "pi_exit_code", "checks", "checks_passed", "model_status", "acceptance", "ended_at")) and has_changes and len(completed_results) == len(task["checks"]) if complete: + if task["version"] == 2 and "configuration" not in worker_receipt: + raise ValueError("Recovered terminal RPC configuration is missing") expected_outcome = "returned" if report.get("status") == "completed" and worker_receipt["checks_passed"] is not False and worker_receipt.get("model_report_matches_changes") is True else "failed" if worker_receipt["outcome"] != expected_outcome or worker_receipt["pi_exit_code"] != 0: raise ValueError("Recovered worker outcome contradicts terminal evidence") @@ -853,6 +1314,12 @@ def main(argv=None): run.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") run.add_argument("--output", type=Path, required=True) run.add_argument("--lock-root", type=Path, default=Path.home() / ".local/state/codex-pi-coordination") + configure = sub.add_parser("configure", help="Register an existing private profile as the default, without replacing one") + configure.add_argument("--profile", type=Path, required=True) + capabilities = sub.add_parser("capabilities", help="Inspect sanitized model capabilities without sending a prompt") + capabilities.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") + capabilities.add_argument("--output", type=Path, required=True) + capabilities.add_argument("--lock-root", type=Path, default=Path.home() / ".local/state/codex-pi-coordination") recover = sub.add_parser("recover", help="Download evidence from the latest stopped failed run without rerunning it") recover.add_argument("failed_directory", type=Path) recover.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") @@ -865,6 +1332,13 @@ def main(argv=None): reconcile.add_argument("--lock-root", type=Path, default=Path.home() / ".local/state/codex-pi-coordination") args = parser.parse_args(argv) try: + if args.operation == "configure": + print(json.dumps(configure_profile(args.profile))) + return 0 + if args.operation == "capabilities": + receipt = run_task(None, args.profile, args.output, args.lock_root, capabilities_only=True) + print(json.dumps({"run_id": receipt["run_id"], "capabilities_valid": receipt["capabilities_valid"], "delivery_valid": False, "acceptance": "not_granted", "receipt": str(args.output / "receipt.json")})) + return 0 if receipt["capabilities_valid"] else 1 if args.operation == "worker": return worker(args.root) if args.operation == "reconcile": diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md index 8320dd6..72c3050 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md @@ -1,14 +1,15 @@ --- name: codex-pi-coordination -description: Delegate scoped implementation, research, review or validation from Codex to Pi in a caller-owned NVIDIA OpenShell sandbox, inspect returned work, or recover the latest stopped failed run without rerunning it. Use for Codex-Pi collaboration or Pi/GLM assistance; model selection and acceptance remain with the coordinator. +description: Delegate scoped work from Codex to Pi in a caller-owned NVIDIA OpenShell sandbox, configure a default profile, discover model/thinking capabilities, inspect returned work, or recover the latest stopped failed run without rerunning it. Use for Codex-Pi collaboration or Pi/GLM assistance; model selection and acceptance remain with the coordinator. --- # Codex and Pi coordination Codex owns task scope, integration and acceptance. Pi performs one bounded -assignment and returns work. Model selection is explicit in a private runtime -profile, including GLM when the configured Pi runtime supports it. This workflow -does not change routes, providers or global model settings. +assignment and returns work. Model selection comes from a private runtime +profile or exact per-task options, including GLM when the configured Pi runtime +supports it. Selection affects only the ephemeral child; this workflow does not +change routes, provider configuration or global model settings. ## Prepare @@ -30,22 +31,61 @@ be checked. Runtime setup belongs to its owner. Do not adopt a similarly named sandbox, copy credentials, read shared environment files, relax policy or substitute ordinary shell execution when OpenShell is unavailable. +## Configure and discover + +Resolve the script relative to this skill directory. Register an existing private +profile once; all paths in these examples are synthetic: + +```sh +python3 ../../scripts/coordinate.py configure --profile /path/to/private/profile.json +``` + +The default is `~/.config/codex-pi-coordination/profile.json`. Registration +validates settings, creates private files/directories, refuses symlinks and +conflicting defaults, and is a no-op for identical settings. There is no force +overwrite. It does not provision providers, copy credentials or verify runtime +behavior. Keep repeated settings in the profile; `--profile` on operational +commands selects another existing profile. + +Discover the configured runtime's available provider/model IDs and the default +model's supported thinking levels: + +```sh +python3 ../../scripts/coordinate.py capabilities --output /private/evidence/new-capabilities +``` + +This uses the same owned disposable lifecycle with zero prompts, tools or +extensions. It may select the configured model in its ephemeral child to query +its levels. `capabilities_valid` reports metadata and cleanup validity, never +task delivery, real-edit qualification or acceptance. + ## Run and inspect -Resolve the script relative to this skill directory: +Use task version 2 for optional `run_options`. Supply `provider` and `model` +together for an exact selection; `thinking` may appear alone. Omitted fields +inherit the profile. Default means omission, never the literal `default`. +Reject `auto`, `dynamic`, unknown/ambiguous models and unsupported thinking; +`max` requires actual support. There is no fallback or provider provisioning. +Version-1 inputs remain supported, but every new run uses native RPC and +`--no-session`. Saved-session continuation remains future work (P1b). ```sh python3 ../../scripts/coordinate.py run task.json --output /private/evidence/new-run ``` -The default profile is `~/.config/codex-pi-coordination/profile.json`; -`--profile` selects another existing profile. Keep repeated settings there. Outputs are exclusive. Independent assignments require separate outputs and owned sandboxes; this command does not schedule a fleet. Inspect `receipt.json`, `results/model-report.json`, `results/changes.json`, -returned files/patch and check logs/results. Verify task/source identities, -actual changes, exit codes and artifact hashes. Pi's handoff is a self-report. +`results/rpc-configuration.json`, returned files/patch and check logs/results. +Verify task/source identities, requested/inherited/effective options, the +extension's first `run_configuration` event, actual changes, exit codes and +artifact hashes. Configuration readback must match before the sole task prompt; +unsupported or clamped options admit zero task prompts. Prompt acknowledgement +and `agent_end` alone do not prove settlement. Require `agent_settled`, an idle +empty-queue readback, child exit and extension shutdown before checks. +`rpc-events.jsonl` retains sanitized control evidence; `pi-stderr.log` is separate +diagnostic output, not protocol. Pi's handoff is a self-report. `delivery_valid` means the bounded return/cleanup contract completed; it grants no acceptance, merge, deployment or proof of research truth. @@ -84,7 +124,8 @@ Preserve failed/partial artifacts; rework is a new assignment. physical capacity; retain failed measurements. Follow-up work gets a new manifest with relevant prior artifacts and the current -revision. Never retarget evidence or infer authority for additional work. Reuse -ship-loop for delivery and the target repository's benchmark/journey commands. +revision; it does not resume a saved Pi conversation. Never retarget evidence or +infer authority for additional work. Reuse ship-loop for delivery and the target +repository's benchmark/journey commands. The plugin uses explicit task files and a native Pi extension; it launches no recursive agents, second Codex process or persistent broker. diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md index a558cdb..42e1c92 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md @@ -1,16 +1,17 @@ # Task and runtime contracts Host: Python 3.10+ on POSIX and the installed OpenShell CLI. Sandbox: Python -3.10+, Pi with the supported extension API, Node 22+ for a JavaScript Pi launch, -and task dependencies. The runner installs nothing and has no third-party Python -dependencies; the extension has no npm dependencies. +3.10+, Pi with the supported extension and native RPC APIs, Node 22+ for a +JavaScript Pi launch, and task dependencies. Missing required RPC capabilities +fail explicitly. The runner installs nothing and has no third-party Python +dependencies; the extension has no npm dependencies. Examples below are synthetic. ## Task ```json { - "version": 1, - "task_id": "repair-parser", + "version": 2, + "task_id": "parser:T001", "kind": "implementation", "instructions": "Fix empty-input handling. Change only parser.py and return an honest handoff. Verification runs after your return.", "repository": "/workspace/project", @@ -19,7 +20,8 @@ dependencies; the extension has no npm dependencies. "checks": [{"name": "parser-check", "argv": ["python3", "check_parser.py"], "timeout_seconds": 30}], "max_tool_calls": 40, "max_turns": 32, - "wall_seconds": 600 + "wall_seconds": 600, + "run_options": {"thinking": "low"} } ``` @@ -31,6 +33,28 @@ use no writable files and report findings through the handoff tool. Commands are coordinator-authored argv, executed once after Pi exits; they share the overall deadline and retain actual logs and exit status. +Version 2 adds only optional `run_options` to the user task fields. It accepts +`provider`, `model` and `thinking`; provider/model must appear together and +thinking is independent. For example: + +```json +{"provider": "configured-provider", "model": "exact-model-id", "thinking": "low"} +``` + +Omitted fields inherit the private profile. Reject unknown fields, empty strings, +`auto`, `dynamic` and the literal `default`; a UI Default choice must omit the +field. IDs are bounded identifiers, never argv, endpoints or environment input. +Resolve the profile's qualified model selector against exact available +provider/model identities. Zero or ambiguous matches refuse; no fuzzy matching, +fallback or provider provisioning occurs. Named `max` is permitted only when the +selected runtime/model advertises it. + +Version-2 task IDs match `[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}`. Version-1 user +inputs keep their original fields and 80-character ID pattern +`[A-Za-z0-9][A-Za-z0-9_.-]{0,79}`; they cannot contain `run_options`. New runs +normalize either input version into the current native contract. Historical +version-1 return/recovery artifacts keep their original interpretation. + Bounds: source/returned workspace 64 MiB and 10,000 regular files, 128 writable paths, 32 checks, 4 MiB per log, 1 MiB task manifest, at most 500 tool calls, 200 turns and 1,800 seconds of worker time. Source links/submodules and @@ -57,9 +81,21 @@ Keep profiles outside public repositories. They reference configured provider storage, never credential values. Optional `openshell_argv` selects the CLI and owner-configured gateway/workspace arguments; default `["openshell"]`. Environment keys are restricted to runtime paths and the bytecode setting. -Extension events record the model identity exposed by Pi. An alias's actual -backend requires the provider owner's diagnostics; physical weights are not -attested by this plugin. +An omitted profile `thinking` retains the legacy `high` default; runtime support +must still be checked before prompting. An alias's actual backend requires the +provider owner's diagnostics; physical weights are not attested by this plugin. + +From the skill directory, register an existing private profile once: + +```sh +python3 ../../scripts/coordinate.py configure --profile /path/to/private/profile.json +``` + +This validates and registers `~/.config/codex-pi-coordination/profile.json` using +exclusive private creation. Semantically identical JSON is a no-op; symlinks and +conflicting defaults refuse. There is no force/overwrite mode. Registration +copies no credentials, edits no provider storage and proves no runtime behavior. +Normal commands use this default; `--profile` selects another existing profile. All cooperating callers must share the local per-sandbox lock root. A persistent custody journal blocks reuse after uncertain outcomes. Name-based OpenShell @@ -77,6 +113,47 @@ Do not collect remote artifacts while failed work may still be active. The runtime owner handles retention. Remote runs remain for diagnosis; preparation refuses when retained run data reaches 1 GiB. +## Native RPC execution and capabilities + +Every new run starts an ephemeral `--no-session` native RPC child in the owned +OpenShell worker, with only the explicit coordination extension and scoped tools. +Saved-session continuation is future work (P1b); fresh runs do not resume an +interactive process or official conversation file. + +Before the single task prompt, the runner queries available models, selects an +exact provider/model, queries `get_available_thinking_levels`, validates and +sets the requested/inherited thinking level, then reads `get_state`. Effective +provider, model and thinking must match exactly; the child must be idle, +noncompacting and have an empty pending queue. Unsupported options, clamping or +missing RPC capabilities refuse with zero task prompts. No uncertain prompt +acknowledgement is retried. + +The reader continuously consumes strict LF-framed JSONL, correlates command IDs +and enforces byte, line, wall, tool and turn bounds, including incomplete lines +and backpressure. Malformed/oversized data, unexpected EOF and missing, duplicate +or wrong response IDs fail. Stderr remains bounded and separate from protocol. +Full model objects are not retained; control evidence allowlists identity, level +and state fields before persistence. + +After one valid handoff, require `agent_settled` and an idle/empty-queue readback. +The runner closes stdin for orderly shutdown and requires child exit and +extension shutdown before executing checks. Prompt acknowledgement or +`agent_end` alone is insufficient. Timeout/cancellation retains managed +OpenShell stop; no arbitrary PID or process-group fallback is authorized. + +```sh +python3 ../../scripts/coordinate.py capabilities --output /private/evidence/new-capabilities +``` + +`capabilities` accepts the normal `--profile` and `--lock-root` options. It uses +the same owned disposable lifecycle with zero prompts, tools or extensions and +returns only available provider/model IDs, the configured model's supported +thinking levels and sanitized runtime identity. Any necessary model selection +is confined to the ephemeral child; no global setting persists. Its CLI reports +`capabilities_valid`; the receipt retains `delivery_valid: false` and +`acceptance: not_granted`. Metadata discovery is separate from actual setup, +model execution and real-edit qualification. + ## Return and trust `started.json` binds the run and input archive. `receipt.json` records worker @@ -85,6 +162,17 @@ records actual Pi exit, event completion, changes and checks. Every check has exclusive started/result records and a log SHA256; interruption never fabricates a successful terminal receipt. +New return evidence includes `rpc-events.jsonl` (sanitized control transcript), +`pi-stderr.log` (separate diagnostic output) and `rpc-configuration.json`. +The worker receipt's `configuration` binds requested options, profile defaults, +effective options, supported levels, ephemeral session ID, prompt admission, +settlement, shutdown and RPC/stderr hashes. Input/task/source hashes bind this +evidence to the assignment. The version-2 extension's `run_configuration` event +at the first `before_agent_start` records actual provider/model from its context +and thinking from `pi.getThinkingLevel()`. `task_loaded.model` records startup +state and does not prove the later RPC selection. Normal verification and +recovery decode v1/v2 explicitly; old evidence cannot acquire these new claims. + `model-report.json` is Pi's task-bound self-report. `extension-events.jsonl` records task loading, budget/tool observations and lifecycle events. These are not independent issuer attestations. Checks run trusted coordinator-selected @@ -95,6 +183,7 @@ cannot tamper with same-user files. Stronger claims need independent validation. `changes.patch` is a convenience text diff. Binary and empty-file changes require the manifest/bytes. Do not automatically apply patches to a newer checkout. Verification may create outputs but must not alter returned source/artifacts. +The byte-change receipt does not attest mode-only edits. For lower-level Pi loading, use `--extension /extensions/coordination.js --coordination-task `. That manifest additionally includes run_id, @@ -104,10 +193,10 @@ extension loading supplies neither OS isolation nor managed cleanup. Pi's CLI `--tools` allowlist must include `coordination_status` and `coordination_handoff` alongside the task's native tools. The extension checks -activation, records missing-tool refusal and blocks further tools. Pi 0.87.1 -print/JSON mode does not wire a shutdown callback for `ctx.shutdown()`, so this -refusal does not guarantee zero model requests. The runner's wall deadline and -managed OpenShell stop remain the process boundary. +activation, records missing-tool refusal and blocks further tools. Standalone +extension refusal does not establish the runner's pre-prompt configuration or +managed-stop guarantees. The runner's wall deadline and managed OpenShell stop +remain the process boundary. ## Failed-run recovery diff --git a/plugins/codex-pi-coordination/tests/extension.test.mjs b/plugins/codex-pi-coordination/tests/extension.test.mjs index 35bdc9f..1d81904 100644 --- a/plugins/codex-pi-coordination/tests/extension.test.mjs +++ b/plugins/codex-pi-coordination/tests/extension.test.mjs @@ -32,6 +32,7 @@ function runtime(taskPath, cwd, allowedTools) { registerCommand: (name, command) => commands.set(name, command), on: (name, handler) => handlers.set(name, handler), getActiveTools: () => active, + getThinkingLevel: () => ctx.thinking ?? "high", setActiveTools: (names) => { active = allowedTools ? names.filter((name) => allowedTools.includes(name)) : names; }, }; extension(pi); @@ -51,6 +52,37 @@ function runtime(taskPath, cwd, allowedTools) { const handoff = (changed_files = []) => ({ status: "completed", summary: "Inspected the provided fixture.", evidence: ["input.txt"], changed_files, limitations: ["Model self-report; external checks remain required."] }); const events = (f) => fs.readFileSync(path.join(f.output, "extension-events.jsonl"), "utf8").trim().split("\n").map(JSON.parse); +test("v2 binds namespaced scope and actual options before model work", async (t) => { + const f = fixture(t, { version: 2, task_id: "project:T001", operation: "run", run_options: { thinking: "low" }, runtime_defaults: { model: "fixture-provider/fixture-model", thinking: "high" } }); + const r = runtime(f.taskPath, f.workspace); + r.ctx.thinking = "low"; + await r.emit("session_start"); + await r.emit("before_agent_start", { systemPrompt: "original" }); + await r.emit("before_agent_start", { systemPrompt: "original" }); + assert.deepEqual(events(f).map((event) => event.type), ["task_loaded", "run_configuration"]); + assert.deepEqual(events(f)[1].configuration, { provider: "fixture-provider", model: "fixture-model", thinking: "low" }); + await r.emit("session_shutdown"); +}); + +test("v2 rejects malformed options and mismatched effective model or thinking", async (t) => { + const base = { version: 2, operation: "run", run_options: {}, runtime_defaults: { model: "fixture-provider/fixture-model", thinking: "high" } }; + for (const run_options of [{ model: "unpaired" }, { provider: "unpaired" }, { thinking: "auto" }, { thinking: "dynamic" }, { thinking: "default" }, { extra: "value" }]) { + const f = fixture(t, { ...base, run_options }); + assert.throws(() => loadTask(f.taskPath, f.workspace), /run options/); + } + for (const changes of [{ model: { provider: "foreign", id: "model" } }, { thinking: "low" }]) { + const f = fixture(t, base); + const r = runtime(f.taskPath, f.workspace); + Object.assign(r.ctx, changes); + await r.emit("session_start"); + assert.equal(await r.emit("before_agent_start", { systemPrompt: "original" }), undefined); + assert.equal(r.ctx.aborted, 1); + assert.equal(events(f).at(-1).code, "configuration_mismatch"); + assert.equal(fs.existsSync(path.join(f.output, "model-report.json")), false); + await r.emit("session_shutdown"); + } +}); + test("each task kind injects context and returns a bound self-report without acceptance", async (t) => { for (const kind of ["implementation", "research", "review", "validation"]) { await t.test(kind, async (t) => { diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 9d7ed55..0a9a132 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -50,6 +50,8 @@ def extension_event(kind, calls=1, turns=1, handed_off=True, **fields): return {'type':kind,'at':'2000-01-01T00:00:00Z','active':True,'run_id':task['run_id'],'task_id':task['task_id'],'task_sha256':task_digest,'tool_calls':calls,'turns':turns,'handed_off':handed_off,**fields} extension_events=[extension_event('task_loaded',0,0,False),extension_event('tool_call',handed_off=False,tool_name='coordination_handoff',tool_call_id='call-1'),extension_event('handoff',reported_status=report['status']),extension_event('agent_settled'),extension_event('session_shutdown')] +if task['version']==2: + extension_events.insert(1,extension_event('run_configuration',0,0,False,configuration=rpc_effective)) if behavior=='extension-refused': extension_events.insert(3,extension_event('refused',failure={'code':'task_unavailable','message':'No further tools'},code='task_unavailable')) if behavior=='extension-failure': extension_events[-1]['failure']={'code':'tool_budget_exhausted','message':'Budget exhausted'} if behavior=='extension-wrong-run': extension_events[1]['run_id']='different-run' @@ -71,6 +73,58 @@ def extension_event(kind, calls=1, turns=1, handed_off=True, **fields): raise SystemExit(7 if behavior=='exit-seven' else 0) ''' +FAKE_RPC = 'PRINT_FIXTURE = ' + repr(FAKE_PI) + '\n' + r''' +import json, pathlib, sys, os +behavior = sys.argv[1] +requests_file = pathlib.Path(__file__).with_suffix('.requests.jsonl') +model = {'provider':'example','id':'model','headers':{'Authorization':'synthetic-private-marker'},'baseUrl':'https://synthetic.invalid/private'} +thinking = 'high' +levels = ['off','minimal','low','medium','high','xhigh','max'] +held = None +def reply(request, data=None): + value={'type':'response','id':request['id'],'command':request['type'],'success':True,'data':data} + if behavior=='wrong-response': value['id']='foreign' + if behavior=='wrong-command': value['command']='foreign' + if behavior=='refused': value.update(success=False,error='synthetic-private-marker') + line=json.dumps(value)+'\r\n' + if behavior=='malformed': line='{bad}\n' + if behavior=='partial': sys.stdout.write('{"type":');sys.stdout.flush();raise SystemExit(0) + if behavior=='oversized': line='x'* (4*1024*1024+1)+'\n' + if behavior=='stderr-overflow': sys.stderr.write('x'*(4*1024*1024+1));sys.stderr.flush() + if behavior=='noisy': sys.stderr.write('synthetic diagnostic\n'*10000);sys.stderr.flush() + sys.stdout.write(line);sys.stdout.flush() + if behavior=='duplicate': sys.stdout.write(line);sys.stdout.flush() +for line in sys.stdin: + request=json.loads(line) + with requests_file.open('a') as stream: stream.write(json.dumps(request)+'\n') + command=request['type'] + if behavior=='no-response': continue + if command=='get_available_models': + data={'models':[model,{'provider':'second','id':'model-two','headers':{'secret':'synthetic-private-marker'}}]} + if behavior=='out-of-order': held=(request,data);continue + elif command=='get_state': + data={'model':model,'thinkingLevel':thinking,'sessionId':'session-one','sessionFile':None,'isStreaming':False,'isCompacting':False,'pendingMessageCount':0} + if behavior=='busy': data['pendingMessageCount']=1 + elif command=='get_available_thinking_levels': data={'levels':['low'] if behavior=='only-low' else levels} + elif command=='set_model': + model={'provider':request['provider'],'id':request['modelId']};data=model + elif command=='set_thinking_level': + thinking='low' if behavior=='clamped' else request['level'];data=None + elif command=='prompt': + if behavior=='no-prompt-ack': continue + reply(request) + namespace={'rpc_effective':{'provider':model['provider'],'model':model['id'],'thinking':thinking}} + try: exec(PRINT_FIXTURE,namespace) + except SystemExit as result: + if result.code: raise + if behavior!='no-settlement': print(json.dumps({'type':'agent_settled'}),flush=True) + continue + else: raise AssertionError(command) + reply(request,data) + if held: + reply(*held);held=None +''' + FAKE_EXEC = r''' import subprocess,sys command=sys.argv[sys.argv.index('--')+1:] @@ -103,6 +157,38 @@ def make_archive(entries): class ContractTests(unittest.TestCase): + def test_version_two_options_and_namespaced_ids_are_strict(self): + task = {**task_template(), "version": 2, "task_id": "project:T001", "run_options": {"thinking": "max"}} + self.assertEqual(coordinate.validate_task(task), task) + for options in [{"model": "unpaired"}, {"provider": "unpaired"}, {"thinking": "auto"}, {"thinking": "dynamic"}, {"thinking": "default"}, {"thinking": []}, {"extra": "value"}, {"provider": "https://example.invalid", "model": "id"}]: + with self.subTest(options=options), self.assertRaises(ValueError): + coordinate.validate_task({**task, "run_options": options}) + with self.assertRaises(ValueError): + coordinate.validate_task({**task, "version": 1}) + + def test_default_registration_is_private_idempotent_and_refuses_conflicts(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "source.json" + profile = {"sandbox_name": "fixture", "sandbox_id": "exact-id", "pi_argv": ["pi"], "model": "example/model"} + dump(source, profile) + destination = root / "settings/profile.json" + first = coordinate.configure_profile(source, destination) + self.assertTrue(first["changed"]) + self.assertFalse(first["runtime_verified"]) + self.assertEqual(destination.stat().st_mode & 0o777, 0o600) + self.assertEqual(destination.parent.stat().st_mode & 0o777, 0o700) + original = destination.read_bytes() + dump(source, dict(reversed(list(profile.items())))) + self.assertFalse(coordinate.configure_profile(source, destination)["changed"]) + self.assertEqual(destination.read_bytes(), original) + dump(source, {**profile, "thinking": "low"}) + with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + link = root / "linked"; link.symlink_to(destination.parent, target_is_directory=True) + with self.assertRaises(ValueError): coordinate.configure_profile(source, link / "profile.json") + destination.unlink(); destination.symlink_to(source) + with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + def test_malformed_tasks_fail_as_validation_errors(self): bad_fields = [("version", True), ("kind", []), ("task_id", "../escape"), ("instructions", ""), ("writable_paths", ["."]), @@ -443,10 +529,155 @@ def test_host_verifier_binds_artifacts_logs_task_and_source(self): coordinate.verify_return(pristine, task, source, "unrelated-run") +class RpcTests(unittest.TestCase): + setUp = WorkerTests.setUp + + def prepare(self, name="rpc", behavior="change", options=None, metadata=False): + root = WorkerTests.prepare(self, name=name, behavior=behavior) + (root / "fake-pi.py").write_text(FAKE_RPC) + task = coordinate.read_json(root / "task.json") + task.update(version=2, task_id="project:T001", operation="capabilities" if metadata else "run", run_options=options or {}, runtime_defaults={"model": "example/model", "thinking": "high"}) + if metadata: + task.update(writable_paths=[], checks=[]) + dump(root / "task.json", task) + launch = coordinate.read_json(root / "launch.json"); launch["wall_seconds"] = 1 + dump(root / "launch.json", launch) + return root + + def requests(self, root): + path = root / "fake-pi.requests.jsonl" + return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] + + def test_default_and_exact_overrides_return_real_changes_with_private_metadata_removed(self): + for index, options in enumerate([{}, {"thinking": "low"}, {"provider": "second", "model": "model-two", "thinking": "max"}]): + with self.subTest(options=options): + root = self.prepare(name=str(index), options=options) + launch_before = (root / "launch.json").read_bytes() + self.assertEqual(coordinate.worker(root), 0) + task = coordinate.read_json(root / "task.json") + receipt = coordinate.verify_return(root / "results", task, {"answer.txt": b"before\n"}, "run-one") + effective = receipt["configuration"]["effective"] + self.assertEqual(effective["thinking"], options.get("thinking", "high")) + self.assertEqual(effective["provider"], options.get("provider", "example")) + self.assertEqual((root / "results/changed-files/answer.txt").read_bytes(), b"after\n") + self.assertEqual((root / "launch.json").read_bytes(), launch_before) + self.assertEqual(sum(request["type"] == "prompt" for request in self.requests(root)), 1) + for contents in coordinate.snapshot(root / "results").values(): + self.assertNotIn(b"synthetic-private-marker", contents) + self.assertNotIn(b"synthetic.invalid", contents) + + def test_options_refuse_before_prompt_without_fallback(self): + cases = [("unchanged", {"provider": "absent", "model": "absent"}), ("only-low", {}), ("clamped", {"thinking": "max"}), ("busy", {})] + for index, (behavior, options) in enumerate(cases): + with self.subTest(behavior=behavior): + root = self.prepare(name=str(index), behavior=behavior, options=options) + self.assertEqual(coordinate.worker(root), 1) + self.assertFalse(any(request["type"] == "prompt" for request in self.requests(root))) + self.assertFalse((root / "results/model-report.json").exists()) + + def test_correlated_metadata_accepts_out_of_order_responses(self): + root = self.prepare(behavior="out-of-order") + self.assertEqual(coordinate.worker(root), 0) + coordinate.verify_return(root / "results", coordinate.read_json(root / "task.json"), {"answer.txt": b"before\n"}, "run-one") + + def test_stderr_backpressure_is_drained_without_becoming_protocol(self): + root = self.prepare(behavior="noisy") + self.assertEqual(coordinate.worker(root), 0) + self.assertGreater((root / "results/pi-stderr.log").stat().st_size, 65536) + self.assertNotIn(b"synthetic diagnostic", (root / "results/rpc-events.jsonl").read_bytes()) + coordinate.verify_return(root / "results", coordinate.read_json(root / "task.json"), {"answer.txt": b"before\n"}, "run-one") + + def test_interruption_closes_exact_child_stdin_without_fabricating_completion(self): + root = self.prepare(behavior="no-response") + children = [] + real_init = coordinate.PiRpc.__init__ + def track_child(instance, *args, **kwargs): + real_init(instance, *args, **kwargs) + children.append(instance.process) + with mock.patch.object(coordinate.PiRpc, "__init__", track_child), mock.patch.object(coordinate.PiRpc, "pump", side_effect=KeyboardInterrupt): + with self.assertRaises(KeyboardInterrupt): coordinate.worker(root) + self.assertEqual(len(children), 1) + self.assertEqual(children[0].wait(timeout=2), 0) + self.assertFalse((root / "results/rpc-configuration.json").exists()) + self.assertEqual(coordinate.read_json(root / "results/worker-receipt.json")["outcome"], "incomplete") + + def test_bad_protocol_and_bounds_never_prompt_or_return_success(self): + for behavior in ["wrong-response", "wrong-command", "duplicate", "refused", "malformed", "partial", "oversized", "stderr-overflow", "no-response"]: + with self.subTest(behavior=behavior): + root = self.prepare(name=behavior, behavior=behavior) + self.assertEqual(coordinate.worker(root), 1) + self.assertFalse(any(request["type"] == "prompt" for request in self.requests(root))) + self.assertFalse((root / "results/rpc-configuration.json").exists()) + + def test_missing_ack_or_settlement_is_not_retried_and_checks_do_not_run(self): + for behavior in ["no-prompt-ack", "no-settlement"]: + root = self.prepare(name=behavior, behavior=behavior) + self.assertEqual(coordinate.worker(root), 1) + self.assertEqual(sum(request["type"] == "prompt" for request in self.requests(root)), 1) + self.assertFalse((root / "results/changes.json").exists()) + + def test_metadata_only_has_no_prompt_extension_or_change_artifacts(self): + root = self.prepare(metadata=True) + self.assertEqual(coordinate.worker(root), 0) + task = coordinate.read_json(root / "task.json") + receipt = coordinate.verify_return(root / "results", task, {"answer.txt": b"before\n"}, "run-one") + self.assertEqual(receipt["outcome"], "capabilities") + self.assertFalse(receipt["configuration"]["prompt_sent"]) + self.assertFalse(any(request["type"] in {"prompt", "set_model", "set_thinking_level"} for request in self.requests(root))) + + def test_trusted_check_observes_changed_bytes_after_shutdown(self): + root = self.prepare() + task = coordinate.read_json(root / "task.json") + check = {"name": "after-shutdown", "argv": [sys.executable, "-c", "import json,pathlib; p=pathlib.Path; assert p('answer.txt').read_text()=='after\\n'; assert json.loads(p('../results/extension-events.jsonl').read_text().splitlines()[-1])['type']=='session_shutdown'; print('checked returned bytes after shutdown')"], "timeout_seconds": 2} + task["checks"] = [check]; dump(root / "task.json", task) + launch = coordinate.read_json(root / "launch.json"); launch["checks"] = [check]; dump(root / "launch.json", launch) + self.assertEqual(coordinate.worker(root), 0) + receipt = coordinate.verify_return(root / "results", task, {"answer.txt": b"before\n"}, "run-one") + self.assertTrue(receipt["checks_passed"]) + self.assertIn(b"checked returned bytes", (root / "results/after-shutdown.log").read_bytes()) + + def test_resealed_configuration_contradictions_are_rejected(self): + root = self.prepare() + self.assertEqual(coordinate.worker(root), 0) + configuration = coordinate.read_json(root / "results/rpc-configuration.json") + configuration["effective"]["thinking"] = "low" + dump(root / "results/rpc-configuration.json", configuration) + worker = coordinate.read_json(root / "results/worker-receipt.json") + worker["configuration"] = configuration + worker["artifact_sha256"] = {name: coordinate.digest(raw) for name, raw in coordinate.snapshot(root / "results").items() if name != "worker-receipt.json"} + dump(root / "results/worker-receipt.json", worker) + task = coordinate.read_json(root / "task.json") + with self.assertRaises(ValueError): coordinate.verify_return(root / "results", task, {"answer.txt": b"before\n"}, "run-one") + with self.assertRaises(ValueError): coordinate.verify_recovered_artifacts(root / "results", task, {"answer.txt": b"before\n"}) + + class RecoveryChangeTests(unittest.TestCase): setUp = WorkerTests.setUp prepare = WorkerTests.prepare + def test_historical_v1_inputs_and_failed_artifacts_remain_recoverable(self): + root = self.prepare(name="a" * 32, checks=[{"name": "failed", "argv": [sys.executable, "-c", "raise SystemExit(9)"], "timeout_seconds": 2}]) + task = coordinate.read_json(root / "task.json") + task["run_id"] = root.name + task["source"]["modes"] = {"answer.txt": 0o644} + task["allowed_tools"] = sorted(coordinate.TOOLS) + dump(root / "task.json", task) + self.assertEqual(coordinate.worker(root), 1) + payload = {"task.json": json.dumps(task).encode(), "launch.json": (root / "launch.json").read_bytes(), "coordinate.py": b"# retained version one worker", "extension.js": b"// retained version one extension", "package.json": b'{"type":"module"}', "workspace/answer.txt": b"before\n"} + archive = make_archive([(name, raw, tarfile.REGTYPE) for name, raw in payload.items()]) + (root / "inputs.tar").write_bytes(archive) + original = {"version": 1, "run_id": root.name, "task_id": task["task_id"], "kind": task["kind"], "started_at": "2000-01-01T00:00:00Z", "source": task["source"], "input_sha256": coordinate.digest(archive), "remote_artifacts": str(root / "results"), "delivery_valid": False} + dump(root / "started.json", original); dump(root / "receipt.json", original) + profile = {"remote_parent": str(self.root)} + before = {name: (root / name).read_bytes() for name in ["started.json", "receipt.json", "inputs.tar"]} + _original, retained_task, source, _hashes = coordinate.recovery_inputs(root, profile) + self.assertEqual(retained_task, task) + recovered = coordinate.verify_recovered_artifacts(root / "results", retained_task, source) + self.assertEqual(recovered["evidence_status"], "complete") + self.assertEqual(recovered["worker_outcome"], "failed") + self.assertEqual(recovered["checks"][0]["exit_code"], 9) + self.assertEqual(before, {name: (root / name).read_bytes() for name in before}) + def test_failed_check_change_bindings_remain_strict(self): check = {'name': 'proof', 'argv': [sys.executable, '-c', 'raise SystemExit(9)'], 'timeout_seconds': 2} root = self.prepare(behavior='change', checks=[check]) @@ -476,7 +707,7 @@ def setUp(self): "pi_argv": [sys.executable, str(self.root / "fake-pi.py"), "unchanged"], "model": "example/model", "remote_parent": str(self.root / "remote"), "python": sys.executable, "protected_sandboxes": ["protected"]} - (self.root / "fake-pi.py").write_text(FAKE_PI) + (self.root / "fake-pi.py").write_text(FAKE_RPC) (self.root / "fake-exec.py").write_text(FAKE_EXEC) self.profile["openshell_argv"] = [sys.executable, str(self.root / "fake-exec.py")] self.profile_path = self.root / "profile.json"; dump(self.profile_path, self.profile) @@ -538,6 +769,20 @@ def test_complete_fake_transport_uses_real_worker_and_stopped_custody(self): self.assertEqual(self.instances[0].calls.count("start"), 1) self.assertEqual(self.instances[0].calls.count("stop"), 1) + def test_registered_default_supports_capabilities_and_run_without_profile_flag(self): + with mock.patch.object(Path, "home", return_value=self.root), mock.patch.object(coordinate, "OpenShellOwner", self.factory()), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(coordinate.main(["configure", "--profile", str(self.profile_path)]), 0) + default = self.root / ".config/codex-pi-coordination/profile.json" + original = default.read_bytes() + self.assertEqual(coordinate.main(["capabilities", "--output", str(self.root / "metadata")]), 0) + metadata = coordinate.read_json(self.root / "metadata/receipt.json") + self.assertTrue(metadata["capabilities_valid"]) + self.assertFalse(metadata["delivery_valid"]) + self.assertTrue(metadata["cleanup_complete"]) + self.assertEqual(coordinate.main(["run", str(self.task_path), "--output", str(self.root / "default-run")]), 0) + self.assertTrue(coordinate.read_json(self.root / "default-run/receipt.json")["delivery_valid"]) + self.assertEqual(default.read_bytes(), original) + def test_identity_or_ready_refusal_has_no_lifecycle_side_effect(self): for mode in ["initial-wrong-id", "initial-ready"]: with self.subTest(mode=mode), self.assertRaises(ValueError): self.run_fake(mode, mode) From dcb9b49cddd4bde8967f71cb05a7eea7e07393d6 Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 13:47:00 -0800 Subject: [PATCH 2/8] Handle native Pi thinking-change events before prompts --- .../scripts/coordinate.py | 52 ++++++++++++++ .../references/task-contract.md | 7 ++ .../tests/test_coordinate.py | 69 ++++++++++++++++++- 3 files changed, 127 insertions(+), 1 deletion(-) diff --git a/plugins/codex-pi-coordination/scripts/coordinate.py b/plugins/codex-pi-coordination/scripts/coordinate.py index 2b65247..223e9a7 100644 --- a/plugins/codex-pi-coordination/scripts/coordinate.py +++ b/plugins/codex-pi-coordination/scripts/coordinate.py @@ -333,11 +333,24 @@ def rpc_data(command, data): raise ValueError("Unexpected RPC command") +def configuration_event_record(value, request_id, command, arguments, previous_level): + """Accept only the native, changing-level event of one authorized setter.""" + level = value.get("level") + if value.get("type") != "thinking_level_changed" or not isinstance(level, str) or level not in THINKING_LEVELS or level == previous_level or command not in {"set_model", "set_thinking_level"}: + raise ValueError("Unexpected or malformed RPC configuration event") + if command == "set_thinking_level" and arguments.get("level") != level: + raise ValueError("RPC thinking event differs from the requested selection") + return {"type": "configuration_event", "id": request_id, "command": command, + "event": "thinking_level_changed", "level": level} + + class PiRpc: """One bounded stdlib RPC child; OpenShell remains its lifecycle owner.""" def __init__(self, command, workspace, output, deadline, env): self.deadline, self.output = deadline, output self.pending, self.responses, self.records = {}, {}, [] + self.pending_arguments, self.configuration_events = {}, set() + self.observed_thinking = None self.sequence, self.bytes_seen, self.settled = 0, 0, 0 self.prompt_sent, self.stdin_closed = False, False self.buffer, self.outgoing = b"", b"" @@ -368,6 +381,7 @@ def send(self, command, **arguments): raise ValueError("A run permits exactly one prompt") self.prompt_sent = True self.pending[request_id] = command + self.pending_arguments[request_id] = arguments retained = {"message_sha256": digest(arguments["message"].encode())} if command == "prompt" else arguments self.record({"type": "request", "id": request_id, "command": command, "arguments": retained}) self.outgoing += (json.dumps({"id": request_id, "type": command, **arguments}) + "\n").encode() @@ -389,13 +403,31 @@ def consume(self, raw): if not isinstance(request_id, str) or request_id not in self.pending or value.get("command") != self.pending[request_id]: raise ValueError("Unmatched or duplicate RPC response") command = self.pending.pop(request_id) + arguments = self.pending_arguments.pop(request_id) if value.get("success") is not True: self.record({"type": "response", "id": request_id, "command": command, "success": False}) raise ValueError("Pi RPC command refused: " + command) safe = rpc_data(command, value.get("data")) + if command == "get_state": + if self.observed_thinking is not None and safe["thinkingLevel"] != self.observed_thinking: + raise ValueError("RPC thinking changed without a bound configuration event") + self.observed_thinking = safe["thinkingLevel"] + elif command == "set_thinking_level" and arguments["level"] != self.observed_thinking: + raise ValueError("RPC thinking acknowledgement lacks the requested level change") self.record({"type": "response", "id": request_id, "command": command, "success": True, "data": safe}) self.responses[request_id] = safe return + if value["type"] == "thinking_level_changed": + if self.prompt_sent or len(self.pending) != 1: + raise ValueError("Unsolicited RPC configuration event") + request_id, command = next(iter(self.pending.items())) + if request_id in self.configuration_events: + raise ValueError("Repeated RPC configuration event") + record = configuration_event_record(value, request_id, command, self.pending_arguments[request_id], self.observed_thinking) + self.configuration_events.add(request_id) + self.observed_thinking = record["level"] + self.record(record) + return if not self.prompt_sent or value["type"] in {"extension_ui_request", "error"}: raise ValueError("Unexpected activity outside the approved task prompt") if value["type"] == "agent_settled": @@ -560,6 +592,7 @@ def verify_rpc_configuration(results, task): if not records or len(records) > 10000 or records[-2:] != [{"type": "stdin_closed"}, {"type": "exit", "exit_code": 0}]: raise ValueError("RPC transcript lacks orderly shutdown") requests, responses, events = [], {}, [] + observed_thinking, configuration_requests = None, set() for index, record in enumerate(records[:-2]): if not isinstance(record, dict): raise ValueError("Invalid RPC transcript record") @@ -574,7 +607,26 @@ def verify_rpc_configuration(results, task): matched = [request for _position, request in requests if request["id"] == record["id"]] if len(matched) != 1 or record["command"] != matched[0]["command"] or rpc_data(record["command"], record["data"]) != record["data"]: raise ValueError("RPC response differs from its safe request contract") + if record["command"] == "get_state": + thinking = record["data"]["thinkingLevel"] + if observed_thinking is not None and thinking != observed_thinking: + raise ValueError("RPC state thinking differs from configuration events") + observed_thinking = thinking + elif record["command"] == "set_thinking_level" and matched[0]["arguments"].get("level") != observed_thinking: + raise ValueError("RPC setter acknowledgement lacks its level change") responses[record["id"]] = (index, record["data"]) + elif kind == "configuration_event": + pending = [request for _position, request in requests if request["id"] not in responses] + if len(pending) != 1 or any(request["command"] == "prompt" for _position, request in requests): + raise ValueError("Unsolicited returned RPC configuration event") + request = pending[0] + if request["id"] in configuration_requests: + raise ValueError("Repeated returned RPC configuration event") + expected_event = configuration_event_record({"type": record.get("event"), "level": record.get("level")}, request["id"], request["command"], request["arguments"], observed_thinking) + if record != expected_event: + raise ValueError("RPC configuration event is not bound to its operation") + configuration_requests.add(request["id"]) + observed_thinking = record["level"] elif record == {"type": "event", "event": "agent_settled"}: events.append(index) else: diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md index 42e1c92..1e15672 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md @@ -135,6 +135,13 @@ or wrong response IDs fail. Stderr remains bounded and separate from protocol. Full model objects are not retained; control evidence allowlists identity, level and state fields before persistence. +Pi can emit `thinking_level_changed` before acknowledging a model or thinking +setter. The runner retains only its level and binds the event to that one +outstanding setter. Unsolicited, repeated, malformed or mismatched configuration +events refuse; other pre-prompt agent/tool/UI activity remains forbidden. The +returned transcript must preserve this ordering and agree with effective-state +readback. A same-value setter needs no change event. + After one valid handoff, require `agent_settled` and an idle/empty-queue readback. The runner closes stdin for orderly shutdown and requires child exit and extension shutdown before executing checks. Prompt acknowledgement or diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 0a9a132..a0856cd 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -81,6 +81,16 @@ def extension_event(kind, calls=1, turns=1, handed_off=True, **fields): thinking = 'high' levels = ['off','minimal','low','medium','high','xhigh','max'] held = None +def change_thinking(level): + global thinking + if level == thinking: return + thinking = level + event={'type':'thinking_level_changed','level':level,'private_metadata':'synthetic-private-marker'} + if behavior=='malformed-configuration': event['level']=[] + if behavior=='agent-before-prompt': event={'type':'agent_start'} + if behavior not in ('missing-configuration','late-configuration'): + print(json.dumps(event),flush=True) + if behavior=='duplicate-configuration': print(json.dumps(event),flush=True) def reply(request, data=None): value={'type':'response','id':request['id'],'command':request['type'],'success':True,'data':data} if behavior=='wrong-response': value['id']='foreign' @@ -100,6 +110,7 @@ def reply(request, data=None): command=request['type'] if behavior=='no-response': continue if command=='get_available_models': + if behavior=='unsolicited-configuration': print(json.dumps({'type':'thinking_level_changed','level':'low'}),flush=True) data={'models':[model,{'provider':'second','id':'model-two','headers':{'secret':'synthetic-private-marker'}}]} if behavior=='out-of-order': held=(request,data);continue elif command=='get_state': @@ -108,8 +119,9 @@ def reply(request, data=None): elif command=='get_available_thinking_levels': data={'levels':['low'] if behavior=='only-low' else levels} elif command=='set_model': model={'provider':request['provider'],'id':request['modelId']};data=model + change_thinking('low') elif command=='set_thinking_level': - thinking='low' if behavior=='clamped' else request['level'];data=None + change_thinking('low' if behavior=='clamped' else request['level']);data=None elif command=='prompt': if behavior=='no-prompt-ack': continue reply(request) @@ -121,6 +133,7 @@ def reply(request, data=None): continue else: raise AssertionError(command) reply(request,data) + if behavior=='late-configuration' and command=='set_thinking_level': print(json.dumps({'type':'thinking_level_changed','level':thinking}),flush=True) if held: reply(*held);held=None ''' @@ -575,6 +588,60 @@ def test_options_refuse_before_prompt_without_fallback(self): self.assertFalse(any(request["type"] == "prompt" for request in self.requests(root))) self.assertFalse((root / "results/model-report.json").exists()) + def test_native_configuration_events_bind_setters_and_metadata_defaults(self): + cases = [("thinking", {"thinking": "low"}, False, "high", ["set_thinking_level"]), + ("model", {"provider": "second", "model": "model-two", "thinking": "max"}, False, "high", ["set_model", "set_thinking_level"]), + ("same-value", {}, False, "high", []), + ("metadata", {}, True, "low", ["set_thinking_level"])] + for name, options, metadata, default_thinking, expected in cases: + with self.subTest(case=name): + root = self.prepare(name=name, options=options, metadata=metadata) + task = coordinate.read_json(root / "task.json") + task["runtime_defaults"]["thinking"] = default_thinking + dump(root / "task.json", task) + self.assertEqual(coordinate.worker(root), 0) + coordinate.verify_return(root / "results", task, {"answer.txt": b"before\n"}, "run-one") + records = [json.loads(line) for line in (root / "results/rpc-events.jsonl").read_text().splitlines()] + changes = [record for record in records if record["type"] == "configuration_event"] + self.assertEqual([record["command"] for record in changes], expected) + for event in changes: + request_index = next(index for index, record in enumerate(records) if record["type"] == "request" and record["id"] == event["id"]) + response_index = next(index for index, record in enumerate(records) if record["type"] == "response" and record["id"] == event["id"]) + self.assertLess(request_index, records.index(event)) + self.assertLess(records.index(event), response_index) + self.assertNotIn(b"synthetic-private-marker", (root / "results/rpc-events.jsonl").read_bytes()) + if metadata: self.assertFalse(self.requests(root)[-1]["type"] == "prompt") + + def test_unsolicited_malformed_or_unacknowledged_configuration_refuses_before_prompt(self): + for behavior in ["unsolicited-configuration", "malformed-configuration", "duplicate-configuration", "missing-configuration", "late-configuration", "agent-before-prompt"]: + with self.subTest(behavior=behavior): + root = self.prepare(name=behavior, behavior=behavior, options={"thinking": "low"}) + self.assertEqual(coordinate.worker(root), 1) + self.assertFalse(any(request["type"] == "prompt" for request in self.requests(root))) + self.assertFalse((root / "results/rpc-configuration.json").exists()) + + def test_returned_configuration_event_reordering_or_rebinding_is_rejected(self): + root = self.prepare(options={"thinking": "low"}) + self.assertEqual(coordinate.worker(root), 0) + task = coordinate.read_json(root / "task.json") + for change in ["late", "foreign", "wrong-level", "duplicate", "missing"]: + with self.subTest(change=change): + output = root / change; shutil.copytree(root / "results", output) + records = [json.loads(line) for line in (output / "rpc-events.jsonl").read_text().splitlines()] + event_index = next(index for index, record in enumerate(records) if record["type"] == "configuration_event") + event = records[event_index] + if change == "late": + records.pop(event_index); records.insert(event_index + 1, event) + elif change == "foreign": event["id"] = "request-foreign" + elif change == "wrong-level": event["level"] = "medium" + elif change == "duplicate": records.insert(event_index, dict(event)) + else: records.pop(event_index) + (output / "rpc-events.jsonl").write_text(''.join(json.dumps(record)+'\n' for record in records)) + configuration = coordinate.read_json(output / "rpc-configuration.json"); configuration["rpc_log_sha256"] = coordinate.digest((output / "rpc-events.jsonl").read_bytes()); dump(output / "rpc-configuration.json", configuration) + receipt = coordinate.read_json(output / "worker-receipt.json"); receipt["configuration"] = configuration; receipt["artifact_sha256"] = {name: coordinate.digest(raw) for name, raw in coordinate.snapshot(output).items() if name != "worker-receipt.json"}; dump(output / "worker-receipt.json", receipt) + with self.assertRaises(ValueError): coordinate.verify_return(output, task, {"answer.txt": b"before\n"}, "run-one") + with self.assertRaises(ValueError): coordinate.verify_recovered_artifacts(output, task, {"answer.txt": b"before\n"}) + def test_correlated_metadata_accepts_out_of_order_responses(self): root = self.prepare(behavior="out-of-order") self.assertEqual(coordinate.worker(root), 0) From d05a42d439d70d53d8a059258e368d60d6e6fb28 Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 14:07:50 -0800 Subject: [PATCH 3/8] test(coordination): join owned fake RPC processes --- .../tests/test_coordinate.py | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index a0856cd..61ed4a7 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -543,7 +543,30 @@ def test_host_verifier_binds_artifacts_logs_task_and_source(self): class RpcTests(unittest.TestCase): - setUp = WorkerTests.setUp + def setUp(self): + WorkerTests.setUp(self) + self.fake_pi_processes = [] + real_initialize = coordinate.PiRpc.__init__ + + def retain_fake_pi_process(instance, *args, **kwargs): + real_initialize(instance, *args, **kwargs) + self.fake_pi_processes.append(instance.process) + + patcher = mock.patch.object(coordinate.PiRpc, "__init__", retain_fake_pi_process) + patcher.start() + self.addCleanup(patcher.stop) + self.addCleanup(self.join_fake_pi_processes) + + def join_fake_pi_processes(self): + # The worker closes its streams; the fixture owns the local children + # that stand in for the managed remote runtime's cleanup responsibility. + running_processes = [] + for process in self.fake_pi_processes: + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + running_processes.append(process.pid) + self.assertEqual(running_processes, [], "Fake Pi children did not exit after worker cleanup") def prepare(self, name="rpc", behavior="change", options=None, metadata=False): root = WorkerTests.prepare(self, name=name, behavior=behavior) From 67e739924c1e4e01646cb455f704a310ee18c829 Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 14:22:14 -0800 Subject: [PATCH 4/8] fix(coordination): bind model identity and isolate discovery logs --- plugins/codex-pi-coordination/README.md | 3 +- .../extensions/coordination.js | 6 ++- .../scripts/coordinate.py | 22 +++++----- .../skills/codex-pi-coordination/SKILL.md | 11 ++--- .../references/task-contract.md | 11 +++-- .../tests/extension.test.mjs | 19 ++++++++ .../tests/test_coordinate.py | 43 +++++++++++++++++-- 7 files changed, 90 insertions(+), 25 deletions(-) diff --git a/plugins/codex-pi-coordination/README.md b/plugins/codex-pi-coordination/README.md index 58fbbad..cd37d4c 100644 --- a/plugins/codex-pi-coordination/README.md +++ b/plugins/codex-pi-coordination/README.md @@ -19,7 +19,8 @@ python3 scripts/coordinate.py run task.json --output /private/evidence/new-run Identical settings are a no-op; conflicting defaults and symlinks refuse. It does not copy credentials or qualify the runtime. `capabilities` uses the owned disposable sandbox with zero prompts, tools or extensions, returning available -provider/model IDs and the configured model's supported thinking levels. +provider/model IDs and the current runtime model's supported thinking levels. +It reports actual idle settings without applying profile model/thinking defaults. Version-2 tasks may add `run_options`: an exact `provider`/`model` pair, `thinking` alone, or both. Omitted options inherit the profile. `auto`, `dynamic` diff --git a/plugins/codex-pi-coordination/extensions/coordination.js b/plugins/codex-pi-coordination/extensions/coordination.js index 89d08df..de42de7 100644 --- a/plugins/codex-pi-coordination/extensions/coordination.js +++ b/plugins/codex-pi-coordination/extensions/coordination.js @@ -228,9 +228,11 @@ export default function coordinationExtension(pi) { return; } const options = loaded.task.run_options; - const selectedModel = options.provider ? `${options.provider}/${options.model}` : loaded.task.runtime_defaults.model; + const selectedModelMatches = options.provider + ? configuration.provider === options.provider && configuration.model === options.model + : `${configuration.provider}/${configuration.model}` === loaded.task.runtime_defaults.model; const selectedThinking = options.thinking ?? loaded.task.runtime_defaults.thinking; - if (`${configuration.provider}/${configuration.model}` !== selectedModel || configuration.thinking !== selectedThinking) { + if (!selectedModelMatches || configuration.thinking !== selectedThinking) { stop(ctx, "configuration_mismatch", "Effective Pi options differ from the approved task"); return; } diff --git a/plugins/codex-pi-coordination/scripts/coordinate.py b/plugins/codex-pi-coordination/scripts/coordinate.py index 223e9a7..33b5b36 100644 --- a/plugins/codex-pi-coordination/scripts/coordinate.py +++ b/plugins/codex-pi-coordination/scripts/coordinate.py @@ -356,7 +356,8 @@ def __init__(self, command, workspace, output, deadline, env): self.buffer, self.outgoing = b"", b"" self.selector = selectors.DefaultSelector() self.events = (output / "pi-events.jsonl").open("xb") - self.stderr = (output / "pi-stderr.log").open("xb") + (output / "rpc").mkdir(mode=0o700) + self.stderr = (output / "rpc/stderr.log").open("xb") self.control = (output / "rpc-events.jsonl").open("x", encoding="utf-8") self.process = subprocess.Popen(command, cwd=workspace, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0) for stream in (self.process.stdin, self.process.stdout, self.process.stderr): @@ -528,6 +529,7 @@ def require_rpc_idle(state, effective=None, session_id=None): actual = {"provider": state["model"]["provider"], "model": state["model"]["id"], "thinking": state["thinkingLevel"]} if (effective is not None and actual != effective) or (session_id is not None and state["sessionId"] != session_id): raise ValueError("Pi effective model/thinking/session differs from the approved selection") + return actual def rpc_configuration_record(task, models, levels, effective, session_id, results): @@ -538,7 +540,7 @@ def rpc_configuration_record(task, models, levels, effective, session_id, result "session_id": session_id, "session_file": None, "prompt_sent": task_run, "settled": task_run, "shutdown": "stdin-eof", "rpc_log_sha256": digest((results / "rpc-events.jsonl").read_bytes()), - "stderr_sha256": digest((results / "pi-stderr.log").read_bytes())} + "stderr_sha256": digest((results / "rpc/stderr.log").read_bytes())} def run_rpc(root, task, launch, deadline, env): @@ -552,8 +554,8 @@ def run_rpc(root, task, launch, deadline, env): initial_request = rpc.send("get_state") models = rpc.wait(models_request)["models"] initial = rpc.wait(initial_request) - require_rpc_idle(initial) - effective = desired_configuration(task, models) + observed = require_rpc_idle(initial) + effective = observed if metadata else desired_configuration(task, models) model_changed = initial["model"] != {"provider": effective["provider"], "id": effective["model"]} if model_changed: selected = rpc.call("set_model", provider=effective["provider"], modelId=effective["model"]) @@ -644,8 +646,9 @@ def data(number): if [request["command"] for _index, request in requests[:2]] != ["get_available_models", "get_state"]: raise ValueError("RPC metadata preflight missing") models, initial = data(0)["models"], data(1) - require_rpc_idle(initial) - effective = desired_configuration(task, models) + observed = require_rpc_idle(initial) + metadata = task["operation"] == "capabilities" + effective = observed if metadata else desired_configuration(task, models) target_model = {"provider": effective["provider"], "id": effective["model"]} changed = initial["model"] != target_model expected = [("get_available_models", {}), ("get_state", {})] @@ -662,7 +665,6 @@ def data(number): expected.append(("set_thinking_level", {"level": effective["thinking"]})) admitted_index = len(expected) expected.append(("get_state", {})) - metadata = task["operation"] == "capabilities" if not metadata: expected += [("prompt", {"message_sha256": digest(RPC_PROMPT.encode())}), ("get_state", {})] if [(request["command"], request["arguments"]) for _index, request in requests] != expected: @@ -789,7 +791,7 @@ def verify_return(results, task, source_files, run_id): if receipt.get("configuration") != configuration: raise ValueError("Worker configuration differs from the verified RPC return") if metadata: - if set(actual) != {"worker-receipt.json", "rpc-events.jsonl", "pi-events.jsonl", "pi-stderr.log", "rpc-configuration.json"} or task["writable_paths"] or task["checks"]: + if set(actual) != {"worker-receipt.json", "rpc-events.jsonl", "pi-events.jsonl", "rpc/stderr.log", "rpc-configuration.json"} or task["writable_paths"] or task["checks"]: raise ValueError("Metadata return contains task execution artifacts") return receipt report = read_json(results / "model-report.json") @@ -1153,7 +1155,7 @@ def verify_recovered_artifacts(results, task, source_files): actual = snapshot(results) allowed = {"worker-receipt.json", "model-report.json", "pi-events.jsonl", "extension-events.jsonl", "changes.json", "changes.patch"} if task["version"] == 2: - allowed |= {"rpc-events.jsonl", "pi-stderr.log", "rpc-configuration.json"} + allowed |= {"rpc-events.jsonl", "rpc/stderr.log", "rpc-configuration.json"} allowed.update(check["name"] + suffix for check in task["checks"] for suffix in (".started.json", ".result.json", ".log")) if any(name not in allowed and not name.startswith("changed-files/") for name in actual): raise ValueError("Unexpected recovered artifact") @@ -1167,7 +1169,7 @@ def verify_recovered_artifacts(results, task, source_files): if "acceptance" in worker_receipt and worker_receipt["acceptance"] != "not_granted": raise ValueError("Recovered worker claims unauthorized acceptance") if task["version"] == 2: - for name in ("rpc-events.jsonl", "pi-stderr.log"): + for name in ("rpc-events.jsonl", "rpc/stderr.log"): if len(actual.get(name, b"")) > MAX_OUTPUT_BYTES: raise ValueError("Recovered RPC output exceeds limit") if "rpc-configuration.json" in actual: diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md index 72c3050..333678f 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md @@ -47,7 +47,7 @@ overwrite. It does not provision providers, copy credentials or verify runtime behavior. Keep repeated settings in the profile; `--profile` on operational commands selects another existing profile. -Discover the configured runtime's available provider/model IDs and the default +Discover the configured runtime's available provider/model IDs and the current model's supported thinking levels: ```sh @@ -55,9 +55,10 @@ python3 ../../scripts/coordinate.py capabilities --output /private/evidence/new- ``` This uses the same owned disposable lifecycle with zero prompts, tools or -extensions. It may select the configured model in its ephemeral child to query -its levels. `capabilities_valid` reports metadata and cleanup validity, never -task delivery, real-edit qualification or acceptance. +extensions. It reports actual idle model/thinking settings without applying +profile defaults or sending configuration setters. `capabilities_valid` reports +metadata and cleanup validity, never task delivery, real-edit qualification or +acceptance. ## Run and inspect @@ -84,7 +85,7 @@ artifact hashes. Configuration readback must match before the sole task prompt; unsupported or clamped options admit zero task prompts. Prompt acknowledgement and `agent_end` alone do not prove settlement. Require `agent_settled`, an idle empty-queue readback, child exit and extension shutdown before checks. -`rpc-events.jsonl` retains sanitized control evidence; `pi-stderr.log` is separate +`rpc-events.jsonl` retains sanitized control evidence; `rpc/stderr.log` is separate diagnostic output, not protocol. Pi's handoff is a self-report. `delivery_valid` means the bounded return/cleanup contract completed; it grants no acceptance, merge, deployment or proof of research truth. diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md index 1e15672..2d96d96 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md @@ -154,9 +154,10 @@ python3 ../../scripts/coordinate.py capabilities --output /private/evidence/new- `capabilities` accepts the normal `--profile` and `--lock-root` options. It uses the same owned disposable lifecycle with zero prompts, tools or extensions and -returns only available provider/model IDs, the configured model's supported -thinking levels and sanitized runtime identity. Any necessary model selection -is confined to the ephemeral child; no global setting persists. Its CLI reports +returns only available provider/model IDs, the current runtime model's supported +thinking levels and sanitized actual idle settings. It sends no model or thinking +setters and does not require profile defaults to be supported by the current model. +Task runs still require exact supported options before their one prompt. Its CLI reports `capabilities_valid`; the receipt retains `delivery_valid: false` and `acceptance: not_granted`. Metadata discovery is separate from actual setup, model execution and real-edit qualification. @@ -170,7 +171,9 @@ exclusive started/result records and a log SHA256; interruption never fabricates a successful terminal receipt. New return evidence includes `rpc-events.jsonl` (sanitized control transcript), -`pi-stderr.log` (separate diagnostic output) and `rpc-configuration.json`. +`rpc/stderr.log` (diagnostics outside the check-log namespace) and +`rpc-configuration.json`. Check logs retain `.log`, including the +valid name `pi-stderr`; started/result receipts and hash checks remain unchanged. The worker receipt's `configuration` binds requested options, profile defaults, effective options, supported levels, ephemeral session ID, prompt admission, settlement, shutdown and RPC/stderr hashes. Input/task/source hashes bind this diff --git a/plugins/codex-pi-coordination/tests/extension.test.mjs b/plugins/codex-pi-coordination/tests/extension.test.mjs index 1d81904..7d68d49 100644 --- a/plugins/codex-pi-coordination/tests/extension.test.mjs +++ b/plugins/codex-pi-coordination/tests/extension.test.mjs @@ -83,6 +83,25 @@ test("v2 rejects malformed options and mismatched effective model or thinking", } }); +test("explicit provider and model identifiers remain separate across slash boundaries", async (t) => { + for (const actual of [{ provider: "one", id: "two/three" }, { provider: "one/two", id: "three" }]) { + const f = fixture(t, { version: 2, operation: "run", run_options: { provider: "one/two", model: "three" }, runtime_defaults: { model: "one/two/three", thinking: "high" } }); + const r = runtime(f.taskPath, f.workspace); + r.ctx.model = actual; + await r.emit("session_start"); + const prompt = await r.emit("before_agent_start", { systemPrompt: "original" }); + if (actual.provider === "one/two") { + assert.ok(prompt.systemPrompt); + assert.equal(events(f).at(-1).type, "run_configuration"); + } else { + assert.equal(prompt, undefined); + assert.equal(r.ctx.aborted, 1); + assert.equal(events(f).at(-1).code, "configuration_mismatch"); + } + await r.emit("session_shutdown"); + } +}); + test("each task kind injects context and returns a bound self-report without acceptance", async (t) => { for (const kind of ["implementation", "research", "review", "validation"]) { await t.test(kind, async (t) => { diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 61ed4a7..05a1f48 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -80,6 +80,7 @@ def extension_event(kind, calls=1, turns=1, handed_off=True, **fields): model = {'provider':'example','id':'model','headers':{'Authorization':'synthetic-private-marker'},'baseUrl':'https://synthetic.invalid/private'} thinking = 'high' levels = ['off','minimal','low','medium','high','xhigh','max'] +if behavior=='off-only': thinking='off';levels=['off'] held = None def change_thinking(level): global thinking @@ -611,11 +612,11 @@ def test_options_refuse_before_prompt_without_fallback(self): self.assertFalse(any(request["type"] == "prompt" for request in self.requests(root))) self.assertFalse((root / "results/model-report.json").exists()) - def test_native_configuration_events_bind_setters_and_metadata_defaults(self): + def test_native_configuration_events_bind_setters_without_changing_metadata_defaults(self): cases = [("thinking", {"thinking": "low"}, False, "high", ["set_thinking_level"]), ("model", {"provider": "second", "model": "model-two", "thinking": "max"}, False, "high", ["set_model", "set_thinking_level"]), ("same-value", {}, False, "high", []), - ("metadata", {}, True, "low", ["set_thinking_level"])] + ("metadata", {}, True, "low", [])] for name, options, metadata, default_thinking, expected in cases: with self.subTest(case=name): root = self.prepare(name=name, options=options, metadata=metadata) @@ -673,7 +674,7 @@ def test_correlated_metadata_accepts_out_of_order_responses(self): def test_stderr_backpressure_is_drained_without_becoming_protocol(self): root = self.prepare(behavior="noisy") self.assertEqual(coordinate.worker(root), 0) - self.assertGreater((root / "results/pi-stderr.log").stat().st_size, 65536) + self.assertGreater((root / "results/rpc/stderr.log").stat().st_size, 65536) self.assertNotIn(b"synthetic diagnostic", (root / "results/rpc-events.jsonl").read_bytes()) coordinate.verify_return(root / "results", coordinate.read_json(root / "task.json"), {"answer.txt": b"before\n"}, "run-one") @@ -715,6 +716,42 @@ def test_metadata_only_has_no_prompt_extension_or_change_artifacts(self): self.assertFalse(receipt["configuration"]["prompt_sent"]) self.assertFalse(any(request["type"] in {"prompt", "set_model", "set_thinking_level"} for request in self.requests(root))) + def test_metadata_reports_off_only_model_without_applying_profile_defaults(self): + for index, default_model in enumerate(["example/model", "unavailable/profile-default"]): + with self.subTest(default_model=default_model): + root = self.prepare(name=str(index), behavior="off-only", metadata=True) + task = coordinate.read_json(root / "task.json") + task["runtime_defaults"]["model"] = default_model + dump(root / "task.json", task) + self.assertEqual(coordinate.worker(root), 0) + receipt = coordinate.verify_return(root / "results", task, {"answer.txt": b"before\n"}, "run-one") + self.assertEqual(receipt["configuration"]["supported_thinking_levels"], ["off"]) + self.assertEqual(receipt["configuration"]["effective"], {"provider": "example", "model": "model", "thinking": "off"}) + self.assertEqual([request["type"] for request in self.requests(root)], ["get_available_models", "get_state", "get_available_thinking_levels", "get_state"]) + task_run = self.prepare(name="task-run", behavior="off-only") + self.assertEqual(coordinate.worker(task_run), 1) + self.assertFalse(any(request["type"] == "prompt" for request in self.requests(task_run))) + + def test_check_named_pi_stderr_keeps_independent_diagnostics_and_recovery_bindings(self): + for exit_code in [0, 7]: + with self.subTest(exit_code=exit_code): + root = self.prepare(name=str(exit_code)) + check = {"name": "pi-stderr", "argv": [sys.executable, "-c", f"print('declared check output'); raise SystemExit({exit_code})"], "timeout_seconds": 2} + task = coordinate.read_json(root / "task.json"); task["checks"] = [check]; dump(root / "task.json", task) + launch = coordinate.read_json(root / "launch.json"); launch["checks"] = [check]; dump(root / "launch.json", launch) + self.assertEqual(coordinate.worker(root), int(exit_code != 0)) + self.assertEqual((root / "results/pi-stderr.log").read_bytes(), b"declared check output\n") + self.assertEqual((root / "results/rpc/stderr.log").read_bytes(), b"") + if exit_code == 0: + coordinate.verify_return(root / "results", task, {"answer.txt": b"before\n"}, "run-one") + coordinate.verify_recovered_artifacts(root / "results", task, {"answer.txt": b"before\n"}) + root = self.prepare(name="before-check", behavior="refused") + task = coordinate.read_json(root / "task.json"); task["checks"] = [check]; dump(root / "task.json", task) + launch = coordinate.read_json(root / "launch.json"); launch["checks"] = [check]; dump(root / "launch.json", launch) + self.assertEqual(coordinate.worker(root), 1) + self.assertFalse((root / "results/pi-stderr.log").exists()) + coordinate.verify_recovered_artifacts(root / "results", task, {"answer.txt": b"before\n"}) + def test_trusted_check_observes_changed_bytes_after_shutdown(self): root = self.prepare() task = coordinate.read_json(root / "task.json") From 103911e12f52468e8302b2b4ec8a346752921285 Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 14:41:35 -0800 Subject: [PATCH 5/8] fix(coordination): validate and compare effective profile defaults --- .../scripts/coordinate.py | 14 +++++- .../tests/test_coordinate.py | 47 +++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/plugins/codex-pi-coordination/scripts/coordinate.py b/plugins/codex-pi-coordination/scripts/coordinate.py index 33b5b36..3e2e52c 100644 --- a/plugins/codex-pi-coordination/scripts/coordinate.py +++ b/plugins/codex-pi-coordination/scripts/coordinate.py @@ -33,6 +33,7 @@ KINDS = {"implementation", "research", "review", "validation"} TOOLS = {"read", "grep", "find", "ls", "write", "edit"} THINKING_LEVELS = {"off", "minimal", "low", "medium", "high", "xhigh", "max"} +MODEL_IDENTIFIER_PATTERN = r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}" PLUGIN = Path(__file__).resolve().parents[1] @@ -114,7 +115,7 @@ def validate_task(task): def model_identifier(value): - if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}", value) or "://" in value: + if not isinstance(value, str) or not re.fullmatch(MODEL_IDENTIFIER_PATTERN, value) or "://" in value: raise ValueError("Expected a bounded model identifier, not a URL or command") return value @@ -865,6 +866,10 @@ def profile_settings(path): for key in required - {"pi_argv"}: if not isinstance(profile[key], str) or not profile[key] or profile[key].startswith("-"): raise ValueError("Invalid profile " + key) + # Validate a qualified spelling without choosing a slash boundary. Exact + # provider/model selection still requires an unambiguous runtime catalog. + if not re.fullmatch(f"{MODEL_IDENTIFIER_PATTERN}/{MODEL_IDENTIFIER_PATTERN}", profile["model"]) or "://" in profile["model"]: + raise ValueError("Profile model must be a bounded provider/model identifier") for key, default in (("pi_argv", []), ("openshell_argv", ["openshell"])): value = profile.get(key, default) if not isinstance(value, list) or not value or any(not isinstance(s, str) or not s or "\x00" in s for s in value): @@ -887,6 +892,11 @@ def profile_settings(path): return profile +def effective_profile_settings(profile): + return {"openshell_argv": ["openshell"], "python": "python3", "remote_parent": "/sandbox/codex-pi", + "thinking": "high", "environment": {}, "protected_sandboxes": [], **profile} + + def configure_profile(source, destination=None): """Register private settings without overwriting another default or provider.""" profile = profile_settings(source) @@ -907,7 +917,7 @@ def configure_profile(source, destination=None): raise ValueError("Default profile directory must be owned and private (0700)") if destination.exists(): current = destination.stat() - if current.st_uid != os.getuid() or stat.S_IMODE(current.st_mode) != 0o600 or profile_settings(destination) != profile: + if current.st_uid != os.getuid() or stat.S_IMODE(current.st_mode) != 0o600 or effective_profile_settings(profile_settings(destination)) != effective_profile_settings(profile): raise ValueError("Existing default profile differs or is not private; preserved") return {"configured": True, "changed": False, "runtime_verified": False} descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 05a1f48..2c1c63c 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -203,6 +203,53 @@ def test_default_registration_is_private_idempotent_and_refuses_conflicts(self): destination.unlink(); destination.symlink_to(source) with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + def test_profile_model_syntax_refuses_unusable_defaults_before_registration(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "source.json" + profile = {"sandbox_name": "fixture", "sandbox_id": "exact-id", "pi_argv": ["pi"], "model": "example/model"} + for index, model in enumerate(["bad model", "example/bad model", "https://example.invalid/model", "unqualified", "a" * 257 + "/model", "example/" + "b" * 257, "a" * 10000, "example/model\n"]): + with self.subTest(model=model[:40]): + dump(source, {**profile, "model": model}) + destination = root / str(index) / "profile.json" + with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + self.assertFalse(destination.parent.exists()) + with self.assertRaises(ValueError): coordinate.profile_settings(source) + for model in ["one/two/three", "provider/model:revision", "a" * 256 + "/" + "b" * 256, "a/" + "b" * 254 + "/c/" + "d" * 254]: + with self.subTest(valid_model=model[:40]): + dump(source, {**profile, "model": model}) + self.assertEqual(coordinate.profile_settings(source), {**profile, "model": model}) + + def test_default_registration_compares_effective_defaults_without_rewriting(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "source.json" + profile = {"sandbox_name": "fixture", "sandbox_id": "exact-id", "pi_argv": ["pi"], "model": "example/model"} + defaults = {"openshell_argv": ["openshell"], "python": "python3", "remote_parent": "/sandbox/codex-pi", "thinking": "high", "environment": {}, "protected_sandboxes": []} + cases = [{key: value} for key, value in defaults.items()] + [defaults] + for index, explicit in enumerate(cases): + for reverse in [False, True]: + with self.subTest(explicit=explicit, reverse=reverse): + initial, repeated = (profile, {**profile, **explicit}) if not reverse else ({**profile, **explicit}, profile) + dump(source, initial) + destination = root / f"{index}-{reverse}" / "profile.json" + self.assertTrue(coordinate.configure_profile(source, destination)["changed"]) + before = (destination.read_bytes(), destination.stat().st_ino, destination.stat().st_mtime_ns) + dump(source, repeated) + self.assertFalse(coordinate.configure_profile(source, destination)["changed"]) + self.assertEqual((destination.read_bytes(), destination.stat().st_ino, destination.stat().st_mtime_ns), before) + for key, value in {"openshell_argv": ["different-owner"], "python": "different-python", "remote_parent": "/sandbox/different", "thinking": "low", "environment": {"PYTHONDONTWRITEBYTECODE": "1"}, "protected_sandboxes": ["other-sandbox"]}.items(): + with self.subTest(conflict=key): + dump(source, {**profile, key: value}) + with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + self.assertEqual(destination.read_bytes(), before[0]) + dump(source, profile) + destination.chmod(0o644) + with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + destination.chmod(0o600); destination.parent.chmod(0o755) + with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + self.assertEqual(destination.read_bytes(), before[0]) + def test_malformed_tasks_fail_as_validation_errors(self): bad_fields = [("version", True), ("kind", []), ("task_id", "../escape"), ("instructions", ""), ("writable_paths", ["."]), From 861e745dd5c58765143870bdf79ce654e90de311 Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 14:49:01 -0800 Subject: [PATCH 6/8] fix(coordination): preserve legacy profile recovery entrypoints --- .../scripts/coordinate.py | 13 ++--- .../tests/test_coordinate.py | 52 ++++++++++++++++++- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/plugins/codex-pi-coordination/scripts/coordinate.py b/plugins/codex-pi-coordination/scripts/coordinate.py index 3e2e52c..b130db7 100644 --- a/plugins/codex-pi-coordination/scripts/coordinate.py +++ b/plugins/codex-pi-coordination/scripts/coordinate.py @@ -857,7 +857,7 @@ def verify_changes(results, actual, task, source_files, receipt, report): raise ValueError("Returned patch/files differ from the verified change manifest") -def profile_settings(path): +def profile_settings(path, *, require_qualified_model=False): profile = read_json(path) required = {"sandbox_name", "sandbox_id", "pi_argv", "model"} optional = {"openshell_argv", "python", "remote_parent", "thinking", "environment", "protected_sandboxes"} @@ -866,9 +866,10 @@ def profile_settings(path): for key in required - {"pi_argv"}: if not isinstance(profile[key], str) or not profile[key] or profile[key].startswith("-"): raise ValueError("Invalid profile " + key) - # Validate a qualified spelling without choosing a slash boundary. Exact - # provider/model selection still requires an unambiguous runtime catalog. - if not re.fullmatch(f"{MODEL_IDENTIFIER_PATTERN}/{MODEL_IDENTIFIER_PATTERN}", profile["model"]) or "://" in profile["model"]: + # New defaults/runs need qualified syntax without choosing a slash boundary. + # Recovery/reconcile preserve legacy selectors without executing model work. + # Exact provider/model selection still requires an unambiguous runtime catalog. + if require_qualified_model and (not re.fullmatch(f"{MODEL_IDENTIFIER_PATTERN}/{MODEL_IDENTIFIER_PATTERN}", profile["model"]) or "://" in profile["model"]): raise ValueError("Profile model must be a bounded provider/model identifier") for key, default in (("pi_argv", []), ("openshell_argv", ["openshell"])): value = profile.get(key, default) @@ -899,7 +900,7 @@ def effective_profile_settings(profile): def configure_profile(source, destination=None): """Register private settings without overwriting another default or provider.""" - profile = profile_settings(source) + profile = profile_settings(source, require_qualified_model=True) destination = Path(destination) if destination is not None else Path.home() / ".config/codex-pi-coordination/profile.json" destination = destination.absolute() for path in (destination, *destination.parents): @@ -1012,7 +1013,7 @@ def cleanup_owner(owner, profile, receipt, protected): def run_task(task_file, profile_file, output, lock_root, *, capabilities_only=False): task = validate_task({"version": 2, "task_id": "capabilities", "kind": "validation", "instructions": "Inspect configured runtime metadata without model work.", "writable_paths": [], "checks": [], "wall_seconds": 30} if capabilities_only else read_json(task_file)) - profile = profile_settings(profile_file) + profile = profile_settings(profile_file, require_qualified_model=True) files, source = frozen_source(task) output = Path(output).absolute() output.mkdir(parents=True, exist_ok=False) diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 2c1c63c..4fde848 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -208,17 +208,24 @@ def test_profile_model_syntax_refuses_unusable_defaults_before_registration(self root = Path(directory) source = root / "source.json" profile = {"sandbox_name": "fixture", "sandbox_id": "exact-id", "pi_argv": ["pi"], "model": "example/model"} + task_file = root / "task.json"; dump(task_file, task_template()) for index, model in enumerate(["bad model", "example/bad model", "https://example.invalid/model", "unqualified", "a" * 257 + "/model", "example/" + "b" * 257, "a" * 10000, "example/model\n"]): with self.subTest(model=model[:40]): dump(source, {**profile, "model": model}) destination = root / str(index) / "profile.json" with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) self.assertFalse(destination.parent.exists()) - with self.assertRaises(ValueError): coordinate.profile_settings(source) + with self.assertRaises(ValueError): coordinate.profile_settings(source, require_qualified_model=True) + self.assertEqual(coordinate.profile_settings(source)["model"], model) + output = root / f"run-{index}" + with mock.patch.object(coordinate, "OpenShellOwner") as owner, contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(coordinate.main(["run", str(task_file), "--profile", str(source), "--output", str(output)]), 1) + owner.assert_not_called() + self.assertFalse(output.exists()) for model in ["one/two/three", "provider/model:revision", "a" * 256 + "/" + "b" * 256, "a/" + "b" * 254 + "/c/" + "d" * 254]: with self.subTest(valid_model=model[:40]): dump(source, {**profile, "model": model}) - self.assertEqual(coordinate.profile_settings(source), {**profile, "model": model}) + self.assertEqual(coordinate.profile_settings(source, require_qualified_model=True), {**profile, "model": model}) def test_default_registration_compares_effective_defaults_without_rewriting(self): with tempfile.TemporaryDirectory() as directory: @@ -1116,6 +1123,47 @@ def recover(self, mode='normal', output='recovered'): with mock.patch.object(coordinate, 'OpenShellOwner', self.recovery_factory(mode)): return coordinate.recover_task(self.root / 'out', self.profile_path, self.root / output, self.root / 'locks') + def test_legacy_bare_model_profile_reconciles_and_recovers_v1_without_execution(self): + for index, model in enumerate(["llm.primary", "sonnet:high"]): + with self.subTest(model=model): + self.profile["model"] = model; dump(self.profile_path, self.profile) + run_id = format(index + 1, "032x") + remote = Path(self.profile["remote_parent"]) / run_id + results = remote / "results"; results.mkdir(parents=True) + source = {"kind": "empty-workspace", "files": {}, "modes": {}} + check = {"name": "never-run", "argv": [sys.executable, "-c", "raise AssertionError('Recovery cannot execute checks')"], "timeout_seconds": 2} + native = {"version": 1, "run_id": run_id, "task_id": "legacy-task", "kind": "validation", "instructions": "Retained legacy task", "workspace": str(remote / "workspace"), "output_directory": str(results), "writable_paths": [], "allowed_tools": sorted(coordinate.TOOLS - {"write", "edit"}), "max_tool_calls": 10, "max_turns": 10, "source": source, "checks": [check]} + launch = {"model": model, "thinking": "high", "checks": [check]} + payload = {"task.json": json.dumps(native).encode(), "launch.json": json.dumps(launch).encode(), "coordinate.py": b"# retained v1 worker", "extension.js": b"// retained v1 extension", "package.json": b'{"type":"module"}'} + archive = make_archive([(name, raw, tarfile.REGTYPE) for name, raw in payload.items()]) + failed = self.root / f"legacy-{index}"; failed.mkdir() + (failed / "inputs.tar").write_bytes(archive) + stopped = {"id": "sandbox-id", "name": "disposable", "phase": "Stopped", "main_process_instance_id": "legacy-main", "restart_count": 0} + original = {"version": 1, "run_id": run_id, "task_id": "legacy-task", "kind": "validation", "started_at": "2000-01-01T00:00:00Z", "source": source, "input_sha256": coordinate.digest(archive), "remote_artifacts": str(results), "delivery_valid": False, "cleanup_complete": False, "sandbox_running": {**stopped, "phase": "Ready"}, "sandbox_after": stopped} + dump(failed / "started.json", original); dump(failed / "receipt.json", original) + dump(results / "worker-receipt.json", {"version": 1, "run_id": run_id, "task_id": "legacy-task", "outcome": "incomplete", "pi_exit_code": 7}) + locks = self.root / "locks"; locks.mkdir(exist_ok=True) + journal = locks / (coordinate.digest(b"sandbox-id") + ".json"); dump(journal, original) + preserved = {path: path.read_bytes() for path in [self.profile_path, failed / "started.json", failed / "receipt.json", failed / "inputs.tar"]} + reconcile = ["reconcile", "--profile", str(self.profile_path), "--lock-root", str(locks)] + before = journal.read_bytes() + with mock.patch.object(coordinate, "OpenShellOwner", self.recovery_factory("initial-wrong-main")), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(coordinate.main(reconcile), 1) + self.assertEqual(journal.read_bytes(), before) + with mock.patch.object(coordinate, "OpenShellOwner", self.recovery_factory()), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(coordinate.main(reconcile), 0) + self.assertEqual(self.instances[-1].calls, []) + output = self.root / f"recovered-legacy-{index}" + with mock.patch.object(coordinate, "OpenShellOwner", self.recovery_factory()), mock.patch.object(coordinate, "execute_to_log", side_effect=AssertionError("Recovery cannot run Pi or checks")), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(coordinate.main(["recover", str(failed), "--profile", str(self.profile_path), "--output", str(output), "--lock-root", str(locks)]), 0) + recovered = coordinate.read_json(output / "receipt.json") + self.assertTrue(recovered["recovery_valid"]) + self.assertFalse(recovered["delivery_valid"]); self.assertFalse(recovered["task_delivery_valid"]) + self.assertEqual(recovered["outcome"], "recovered_partial") + self.assertEqual(recovered["evidence"]["checks"], [{"name": "never-run", "state": "unknown", "exit_code": None}]) + self.assertEqual(self.instances[-1].calls, ["start", "download", "stop"]) + self.assertEqual(preserved, {path: path.read_bytes() for path in preserved}) + def test_nonzero_check_recovers_without_reexecution_or_task_success(self): original = self.failed_run() before = {name: (self.root / 'out' / name).read_bytes() for name in ['receipt.json', 'inputs.tar', 'started.json']} From 0719450b5b6cd47c27333ab118e7d789f793d36a Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 15:02:09 -0800 Subject: [PATCH 7/8] Fix qualified default model bounds in Pi extension --- .../extensions/coordination.js | 8 +++- .../tests/extension.test.mjs | 27 ++++++++++++ .../tests/test_coordinate.py | 41 +++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/plugins/codex-pi-coordination/extensions/coordination.js b/plugins/codex-pi-coordination/extensions/coordination.js index de42de7..f35e53d 100644 --- a/plugins/codex-pi-coordination/extensions/coordination.js +++ b/plugins/codex-pi-coordination/extensions/coordination.js @@ -77,9 +77,13 @@ export function loadTask(taskPath, cwd) { if (task.version === 2) { const options = task.run_options; const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; - const identifier = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}$/.test(value) && !value.includes("://"); + const identifierPattern = "[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}"; + const matchesIdentifier = (value, pattern) => typeof value === "string" && !value.includes("://") && new RegExp(`^${pattern}$`).exec(value)?.[0] === value; + const identifier = (value) => matchesIdentifier(value, identifierPattern); + // Each component may contain slashes; only the exact runtime catalog picks a pair. + const qualifiedDefault = (value) => matchesIdentifier(value, `${identifierPattern}/${identifierPattern}`); if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => !["provider", "model", "thinking"].includes(key)) || (("provider" in options) !== ("model" in options)) || ("provider" in options && (!identifier(options.provider) || !identifier(options.model))) || ("thinking" in options && !levels.includes(options.thinking))) fail("invalid_task", "Invalid version 2 run options"); - if (task.operation !== "run" || !task.runtime_defaults || Object.keys(task.runtime_defaults).sort().join(",") !== "model,thinking" || !identifier(task.runtime_defaults.model) || !levels.includes(task.runtime_defaults.thinking)) fail("invalid_task", "Invalid version 2 runtime defaults"); + if (task.operation !== "run" || !task.runtime_defaults || Object.keys(task.runtime_defaults).sort().join(",") !== "model,thinking" || !qualifiedDefault(task.runtime_defaults.model) || !levels.includes(task.runtime_defaults.thinking)) fail("invalid_task", "Invalid version 2 runtime defaults"); } boundedString(task.instructions, "instructions", 48000); for (const key of ["workspace", "output_directory"]) { diff --git a/plugins/codex-pi-coordination/tests/extension.test.mjs b/plugins/codex-pi-coordination/tests/extension.test.mjs index 7d68d49..6ca8d8b 100644 --- a/plugins/codex-pi-coordination/tests/extension.test.mjs +++ b/plugins/codex-pi-coordination/tests/extension.test.mjs @@ -102,6 +102,33 @@ test("explicit provider and model identifiers remain separate across slash bound } }); +test("qualified defaults load and reach the pre-prompt guard at both component bounds", async (t) => { + for (const [provider, id] of [["fixture-provider", "fixture-model"], ["p", "m".repeat(255)], ["p".repeat(256), "m".repeat(256)], ["a/" + "b".repeat(254), "c/" + "d".repeat(254)]]) { + const f = fixture(t, { version: 2, operation: "run", run_options: {}, runtime_defaults: { model: `${provider}/${id}`, thinking: "high" } }); + assert.equal(loadTask(f.taskPath, f.workspace).task.runtime_defaults.model, `${provider}/${id}`); + const r = runtime(f.taskPath, f.workspace); + r.ctx.model = { provider, id }; + await r.emit("session_start"); + assert.ok((await r.emit("before_agent_start", { systemPrompt: "original" })).systemPrompt); + assert.equal(r.ctx.aborted, 0); + assert.deepEqual(events(f).at(-1).configuration, { provider, model: id, thinking: "high" }); + await r.emit("session_shutdown"); + } +}); + +test("qualified defaults reject malformed or overlong components without relaxing explicit options", (t) => { + const base = { version: 2, operation: "run", run_options: {}, runtime_defaults: { model: "p/m", thinking: "high" } }; + for (const model of [null, "", "bare", "p/", "/m", "_p/m", "p/_m", "https://example/model", "p/m\n", "p/m\r\n", "p/bad model", "p".repeat(257) + "/m", "p/" + "m".repeat(257), "p".repeat(256) + "/" + "m".repeat(257)]) { + const f = fixture(t, { ...base, runtime_defaults: { model, thinking: "high" } }); + assert.throws(() => loadTask(f.taskPath, f.workspace), /runtime defaults/); + assert.deepEqual(fs.readdirSync(f.output), []); + } + for (const run_options of [{ provider: "p".repeat(257), model: "m" }, { provider: "p", model: "m".repeat(257) }, { provider: "p\n", model: "m" }, { provider: "p", model: "m\n" }]) { + const f = fixture(t, { ...base, run_options }); + assert.throws(() => loadTask(f.taskPath, f.workspace), /run options/); + } +}); + test("each task kind injects context and returns a bound self-report without acceptance", async (t) => { for (const kind of ["implementation", "research", "review", "validation"]) { await t.test(kind, async (t) => { diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 4fde848..2e0fd18 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -227,6 +227,47 @@ def test_profile_model_syntax_refuses_unusable_defaults_before_registration(self dump(source, {**profile, "model": model}) self.assertEqual(coordinate.profile_settings(source, require_qualified_model=True), {**profile, "model": model}) + def test_python_qualified_defaults_match_actual_extension_loading(self): + valid_pairs = [("p", "m"), ("p", "m" * 255), ("p" * 256, "m" * 256), ("a/" + "b" * 254, "c/" + "d" * 254)] + invalid_models = ["bare", "p/", "/m", "_p/m", "p/_m", "https://example/model", "p/m\n", "p/m\r\n", "p/bad model", "p" * 257 + "/m", "p/" + "m" * 257, "p" * 256 + "/" + "m" * 257] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + workspace = root / "workspace"; workspace.mkdir() + output = root / "results"; output.mkdir() + source = root / "profile.json" + cases = [] + for index, (model, pair) in enumerate([(provider + "/" + model, (provider, model)) for provider, model in valid_pairs] + [(model, None) for model in invalid_models]): + profile = {"sandbox_name": "fixture", "sandbox_id": "exact-id", "pi_argv": ["pi"], "model": model} + dump(source, profile) + destination = root / f"default-{index}" / "profile.json" + if pair: + self.assertTrue(coordinate.configure_profile(source, destination)["changed"]) + defaults = {"model": coordinate.profile_settings(destination, require_qualified_model=True)["model"], "thinking": "high"} + self.assertEqual(coordinate.desired_configuration({"run_options": {}, "runtime_defaults": defaults}, [{"provider": pair[0], "id": pair[1]}]), {"provider": pair[0], "model": pair[1], "thinking": "high"}) + else: + with self.assertRaises(ValueError): coordinate.configure_profile(source, destination) + self.assertFalse(destination.parent.exists()) + defaults = {"model": model, "thinking": "high"} + task_path = root / f"task-{index}.json" + dump(task_path, {**task_template(), "version": 2, "run_id": "run-one", "operation": "run", "run_options": {}, "runtime_defaults": defaults, "workspace": str(workspace), "output_directory": str(output), "allowed_tools": ["read"], "max_tool_calls": 8}) + cases.append({"task": str(task_path), "cwd": str(workspace), "expected": pair is not None}) + # Use the actual native loader on Python-configured defaults, without + # Pi, an owner, a prompt or a duplicated JavaScript predicate. + program = """import fs from 'node:fs'; +const {loadTask} = await import(process.argv[1]); +const cases = JSON.parse(fs.readFileSync(0, 'utf8')); +console.log(JSON.stringify(cases.map(item => { try { loadTask(item.task, item.cwd); return true; } catch { return false; } }))); +""" + result = subprocess.run(["node", "--input-type=module", "-e", program, (SCRIPT.parent.parent / "extensions/coordination.js").as_uri()], input=json.dumps(cases), text=True, capture_output=True, timeout=10, check=True) + self.assertEqual(json.loads(result.stdout), [case["expected"] for case in cases]) + self.assertEqual(list(output.iterdir()), []) + ambiguous = [{"provider": "one/two", "id": "three"}, {"provider": "one", "id": "two/three"}] + selection = {"run_options": {}, "runtime_defaults": {"model": "one/two/three", "thinking": "high"}} + with self.assertRaisesRegex(ValueError, "ambiguous"): + coordinate.desired_configuration(selection, ambiguous) + selection["run_options"] = {"provider": "one/two", "model": "three"} + self.assertEqual(coordinate.desired_configuration(selection, ambiguous), {"provider": "one/two", "model": "three", "thinking": "high"}) + def test_default_registration_compares_effective_defaults_without_rewriting(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) From d0de41f72a56862fc27d7add694d90c1e85b5878 Mon Sep 17 00:00:00 2001 From: Sekou Doumbouya Date: Thu, 12 Nov 2026 15:25:17 -0800 Subject: [PATCH 8/8] Preserve versioned Pi task identifier boundaries --- .../extensions/coordination.js | 7 ++- .../references/task-contract.md | 6 +++ .../tests/extension.test.mjs | 28 +++++++++++ .../tests/test_coordinate.py | 48 +++++++++++++++---- 4 files changed, 79 insertions(+), 10 deletions(-) diff --git a/plugins/codex-pi-coordination/extensions/coordination.js b/plugins/codex-pi-coordination/extensions/coordination.js index f35e53d..3c1247b 100644 --- a/plugins/codex-pi-coordination/extensions/coordination.js +++ b/plugins/codex-pi-coordination/extensions/coordination.js @@ -72,8 +72,13 @@ export function loadTask(taskPath, cwd) { fail("invalid_task", "Expected a supported versioned coordination task and kind"); } for (const key of ["run_id", "task_id"]) { - if (!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(boundedString(task[key], key, 128))) fail("invalid_task", `Invalid ${key}`); + const pattern = key === "task_id" && task.version === 1 + ? /^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/ + : /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/; + const value = boundedString(task[key], key, 128); + if (pattern.exec(value)?.[0] !== value) fail("invalid_task", `Invalid ${key}`); } + if (task.version === 1 && "run_options" in task) fail("invalid_task", "Version 1 cannot contain run_options"); if (task.version === 2) { const options = task.run_options; const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md index 2d96d96..17afdf3 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md @@ -55,6 +55,12 @@ inputs keep their original fields and 80-character ID pattern normalize either input version into the current native contract. Historical version-1 return/recovery artifacts keep their original interpretation. +Public assignments never supply `run_id`. Native artifacts carry a separate +coordinator-generated run identity; the extension preserves its historical +128-character pattern `[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}` in both versions. +The version-1 task-ID limit does not apply to that native field. Both ID fields +must match their entire pattern, without trailing newlines. + Bounds: source/returned workspace 64 MiB and 10,000 regular files, 128 writable paths, 32 checks, 4 MiB per log, 1 MiB task manifest, at most 500 tool calls, 200 turns and 1,800 seconds of worker time. Source links/submodules and diff --git a/plugins/codex-pi-coordination/tests/extension.test.mjs b/plugins/codex-pi-coordination/tests/extension.test.mjs index 6ca8d8b..a5f474a 100644 --- a/plugins/codex-pi-coordination/tests/extension.test.mjs +++ b/plugins/codex-pi-coordination/tests/extension.test.mjs @@ -52,6 +52,34 @@ function runtime(taskPath, cwd, allowedTools) { const handoff = (changed_files = []) => ({ status: "completed", summary: "Inspected the provided fixture.", evidence: ["input.txt"], changed_files, limitations: ["Model self-report; external checks remain required."] }); const events = (f) => fs.readFileSync(path.join(f.output, "extension-events.jsonl"), "utf8").trim().split("\n").map(JSON.parse); +test("versioned task IDs preserve legacy native run IDs and reject unsupported options", async (t) => { + for (const version of [1, 2]) { + const maximum = version === 1 ? 80 : 128; + const base = { version, ...(version === 2 ? { operation: "run", run_options: {}, runtime_defaults: { model: "fixture-provider/fixture-model", thinking: "high" } } : {}) }; + const f = fixture(t, { ...base, task_id: "t".repeat(maximum), run_id: "run:" + "r".repeat(124) }); + assert.equal(loadTask(f.taskPath, f.workspace).task.run_id.length, 128); + const r = runtime(f.taskPath, f.workspace); + await r.emit("session_start"); + assert.ok((await r.emit("before_agent_start", { systemPrompt: "original" })).systemPrompt); + assert.equal(r.ctx.aborted, 0); + await r.emit("session_shutdown"); + for (const [field, invalid] of [["task_id", "t".repeat(maximum + 1)], ["task_id", "task-one\n"], ["task_id", "task-one\r\n"], ["run_id", "r".repeat(129)], ["run_id", "run-one\n"], ["run_id", "run-one\r\n"]]) { + const invalidFixture = fixture(t, { ...base, [field]: invalid }); + assert.throws(() => loadTask(invalidFixture.taskPath, invalidFixture.workspace), new RegExp(field)); + } + const namespaced = fixture(t, { ...base, task_id: "project:T001" }); + if (version === 1) { + assert.throws(() => loadTask(namespaced.taskPath, namespaced.workspace), /task_id/); + for (const run_options of [{}, { thinking: "low" }, null]) { + const invalidFixture = fixture(t, { ...base, run_options }); + assert.throws(() => loadTask(invalidFixture.taskPath, invalidFixture.workspace), /run_options/); + } + } else { + assert.equal(loadTask(namespaced.taskPath, namespaced.workspace).task.task_id, "project:T001"); + } + } +}); + test("v2 binds namespaced scope and actual options before model work", async (t) => { const f = fixture(t, { version: 2, task_id: "project:T001", operation: "run", run_options: { thinking: "low" }, runtime_defaults: { model: "fixture-provider/fixture-model", thinking: "high" } }); const r = runtime(f.taskPath, f.workspace); diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 2e0fd18..554c7a3 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -170,7 +170,45 @@ def make_archive(entries): return output.getvalue() +def native_extension_load_results(cases): + # Exercise the actual extension, without Pi, an owner or a model prompt. + program = """import fs from 'node:fs'; +const {loadTask} = await import(process.argv[1]); +const cases = JSON.parse(fs.readFileSync(0, 'utf8')); +console.log(JSON.stringify(cases.map(item => { try { loadTask(item.task, item.cwd); return true; } catch { return false; } }))); +""" + result = subprocess.run(["node", "--input-type=module", "-e", program, (SCRIPT.parent.parent / "extensions/coordination.js").as_uri()], input=json.dumps(cases), text=True, capture_output=True, timeout=10, check=True) + return json.loads(result.stdout) + + class ContractTests(unittest.TestCase): + def test_python_versioned_task_boundary_matches_actual_extension(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + workspace = root / "workspace"; workspace.mkdir() + output = root / "results"; output.mkdir() + cases = [] + for version, maximum in [(1, 80), (2, 128)]: + variants = [(identifier, {}, valid) for identifier, valid in [("task-one", True), ("t" * maximum, True), ("project:T001", version == 2), ("t" * (maximum + 1), False), ("task-one\n", False), ("task-one\r\n", False)]] + variants += [("task-one", {"run_options": options}, version == 2) for options in [{}, {"thinking": "low"}]] + for identifier, fields, expected in variants: + public = {**task_template(), "version": version, "task_id": identifier, **fields} + if expected: + self.assertEqual(coordinate.validate_task(public), public) + else: + with self.assertRaises(ValueError): coordinate.validate_task(public) + task_path = root / f"task-{len(cases)}.json" + native = {**public, "run_id": "run-one", "workspace": str(workspace), "output_directory": str(output), "allowed_tools": ["read"], "max_tool_calls": 8} + if version == 2: + native.update(operation="run", run_options=public.get("run_options", {}), runtime_defaults={"model": "example/model", "thinking": "high"}) + dump(task_path, native) + cases.append({"task": str(task_path), "cwd": str(workspace), "expected": expected}) + # The public assignment never chooses a run ID; native artifacts do. + with self.assertRaises(ValueError): + coordinate.validate_task({**task_template(), "version": version, "run_id": "run-one"}) + self.assertEqual(native_extension_load_results(cases), [case["expected"] for case in cases]) + self.assertEqual(list(output.iterdir()), []) + def test_version_two_options_and_namespaced_ids_are_strict(self): task = {**task_template(), "version": 2, "task_id": "project:T001", "run_options": {"thinking": "max"}} self.assertEqual(coordinate.validate_task(task), task) @@ -251,15 +289,7 @@ def test_python_qualified_defaults_match_actual_extension_loading(self): task_path = root / f"task-{index}.json" dump(task_path, {**task_template(), "version": 2, "run_id": "run-one", "operation": "run", "run_options": {}, "runtime_defaults": defaults, "workspace": str(workspace), "output_directory": str(output), "allowed_tools": ["read"], "max_tool_calls": 8}) cases.append({"task": str(task_path), "cwd": str(workspace), "expected": pair is not None}) - # Use the actual native loader on Python-configured defaults, without - # Pi, an owner, a prompt or a duplicated JavaScript predicate. - program = """import fs from 'node:fs'; -const {loadTask} = await import(process.argv[1]); -const cases = JSON.parse(fs.readFileSync(0, 'utf8')); -console.log(JSON.stringify(cases.map(item => { try { loadTask(item.task, item.cwd); return true; } catch { return false; } }))); -""" - result = subprocess.run(["node", "--input-type=module", "-e", program, (SCRIPT.parent.parent / "extensions/coordination.js").as_uri()], input=json.dumps(cases), text=True, capture_output=True, timeout=10, check=True) - self.assertEqual(json.loads(result.stdout), [case["expected"] for case in cases]) + self.assertEqual(native_extension_load_results(cases), [case["expected"] for case in cases]) self.assertEqual(list(output.iterdir()), []) ambiguous = [{"provider": "one/two", "id": "three"}, {"provider": "one", "id": "two/three"}] selection = {"run_options": {}, "runtime_defaults": {"model": "one/two/three", "thinking": "high"}}