diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 797ab759..2bed0cbc 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -899,6 +899,16 @@ never read as alive. To stop a shift, `touch /STOP` (or comment `/stop` on its issue); to remove the watcher, `systemctl --user disable --now pyauto-orchestrator.timer`. +## Codex execution workers + +A brief may explicitly select `worker-backend: codex`; omitted means Claude. +The adapter changes execution, observations, stop and accounting only, retaining +this conductor's scheduling and autonomy contracts. Codex workers use an +accounted fresh Opus session for the required pre-ship review; close-outs remain +Opus. The canonical keys live in Mind `batches/AGENTS.md`. Read +[Codex setup and first-run checks](../../../docs/codex_orchestrator.md) before +the first Codex shift. No live shift is authorized by selecting a backend. + ## Running ``` diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 7a187f71..4b680866 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -1575,10 +1575,20 @@ def login_findings(top: dict, brief: dict | None) -> tuple[dict, list[str], list shadow brief starts no worker and is not probed.""" if brief is None or _brief.is_shadow(brief): return {"state": "skipped", "detail": "shadow shift", "expires_at": ""}, [], [] - login = _login.probe() + if _brief.backend_of(brief) == "codex": + import _codex + login = _codex.probe() + # Even merge-cap: 0 requires the independent Opus pre-ship review. + if login["state"] == "ok": + review_login = _login.probe() + if review_login["state"] not in {"ok", "skipped"}: + return login, ["review login: independent Opus pre-ship review requires a verified Claude login"], [] + else: + login = _login.probe() errors, warnings = [], [] if login["state"] == "expired": - errors.append(f"login: {_login.EXPIRED_LINE} ({login['detail']})") + errors.append(f"login: {login['detail']}" if _brief.backend_of(brief) == "codex" + else f"login: {_login.EXPIRED_LINE} ({login['detail']})") elif login["state"] == "unknown": warnings.append(f"login: could not tell whether the CLI login holds " f"({login['detail']})") diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index bd3edc95..f79b0851 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -208,6 +208,29 @@ def effective(brief: dict, counters: dict | None) -> dict: return out +def backend_of(brief: dict) -> str: + return brief.get("worker-backend", {}).get("value", "claude") + + +def backend_errors(brief: dict) -> list[str]: + backend = backend_of(brief) + if backend not in {"claude", "codex"}: + return ["brief.worker-backend: must be claude or codex"] + errors = [] + if backend == "codex": + model = brief.get("codex-model", {}).get("value", "") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", model): + errors.append("brief.codex-model: explicit Codex model id required") + if worker_mode_of(brief) not in {"auto", "dontAsk"}: + errors.append("brief.worker-mode: Codex supports auto or dontAsk; no acceptEdits equivalent") + effort = brief.get("codex-effort", {}).get("value", "medium") + if effort not in {"low", "medium", "high", "xhigh"}: + errors.append("brief.codex-effort: must be low, medium, high or xhigh") + elif any(k.startswith("codex-") for k in brief): + errors.append("brief.worker-backend: codex settings require worker-backend: codex") + return errors + + def worker_mode_of(brief: dict) -> str: return brief.get("worker-mode", {}).get("value") or DEFAULT_WORKER_MODE @@ -350,6 +373,7 @@ def check(path: Path, mind: Path) -> dict: if key in brief and _nonneg_int(brief[key]["value"]) is None: errors.append(f"brief.{key}: not a whole number ({brief[key]['value']!r})") + errors.extend(backend_errors(brief)) if "worker-mode" in brief and brief["worker-mode"]["value"] not in WORKER_MODES: errors.append(f"brief.worker-mode: {brief['worker-mode']['value']} — one of " + ", ".join(WORKER_MODES) diff --git a/agents/conductors/batch/_codex.py b/agents/conductors/batch/_codex.py new file mode 100644 index 00000000..35ee0d96 --- /dev/null +++ b/agents/conductors/batch/_codex.py @@ -0,0 +1,224 @@ +"""Codex CLI backend. Local Linux/WSL process records, never an API client. + +Opaque codex: identities route observations independently of a brief +which may subsequently change. Each runner owns one private session directory. +Unknown/corrupt state holds a lease; it is never evidence that a worker died. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time +import uuid + +PREFIX = "codex:" +ID_RE = re.compile(r"codex:([0-9a-f]{32})\Z") + + +def session_dir(agent_id: str, home: Path) -> Path: + match = ID_RE.fullmatch(agent_id) + if not match: + raise ValueError("invalid Codex worker identity") + return Path(home) / "codex-sessions" / match[1] + + +def write_json(path: Path, value: dict) -> None: + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps(value), encoding="utf-8") + tmp.replace(path) + + +def read_record(agent_id: str, home: Path) -> dict | None: + try: + obj = json.loads((session_dir(agent_id, home) / "state.json").read_text()) + if not isinstance(obj, dict) or obj.get("agent_id") != agent_id: + return None + if obj.get("state") not in {"starting", "working", "done", "error", "killed"}: + return None + for key in ("pid", "child_pid"): + if key in obj and (type(obj[key]) is not int or obj[key] <= 0): + return None + for key in ("identity", "child_identity"): + if key in obj and (not isinstance(obj[key], str) or not obj[key]): + return None + return obj + except (OSError, ValueError, TypeError): + return None + + +def process_identity(pid: int) -> str | None: + """Linux start ticks + boot id prevent PID reuse across ticks/reboots.""" + try: + stat = Path(f"/proc/{int(pid)}/stat").read_text().rsplit(")", 1)[1].split() + if stat[0] == "Z": + return None + boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip() + return f"{boot}:{stat[19]}" + except (OSError, ValueError, IndexError, TypeError): + return None + + +def state(agent_id: str, home: Path) -> str | None: + rec = read_record(agent_id, home) + if rec is None: + return None + if rec["state"] in {"done", "error", "killed"}: + return rec["state"] + if rec.get("pid") and rec.get("identity"): + if process_identity(rec["pid"]) == rec["identity"]: + return "working" + # A supervisor crash is not a worker crash while its child survives. + if not rec.get("child_pid") or not rec.get("child_identity"): + # Death between Popen and the child's identity write is ambiguous. + # Holding the lease is safer than starting a duplicate worker. + return None + if process_identity(rec["child_pid"]) == rec["child_identity"]: + return "working" + return "error" + # A launcher crash before the supervisor starts cannot silently free a slot. + return None + + +def usage(agent_id: str, home: Path) -> dict | None: + """Completed-turn usage. Missing/partial events retain the reservation. + + Codex input includes cached input: subtract it for the existing shift + budget's uncached-input + output convention; report cache reads separately. + """ + try: + totals = dict(input=0, output=0, cache_creation=0, cache_read=0, subagents=0) + found = False + for line in (session_dir(agent_id, home) / "events.jsonl").read_text().splitlines(): + try: + event = json.loads(line) + except ValueError: + continue # an in-flight final line is normal + if not isinstance(event, dict) or event.get("type") != "turn.completed": + continue + u = event.get("usage") + if not isinstance(u, dict): + return None + fields = [u.get(k) for k in ("input_tokens", "output_tokens", "cached_input_tokens")] + if any(type(n) is not int or n < 0 for n in fields) or fields[2] > fields[0]: + return None + found = True + totals["input"] += fields[0] - fields[2] + totals["output"] += fields[1] + totals["cache_read"] += fields[2] + if not found: + return None + for request in session_dir(agent_id, home).glob("review-*.request.json"): + result = request.with_name(request.name.replace(".request.json", ".result.json")) + try: + raw = json.loads(result.read_text())["usage"] + fields = [raw.get(k) for k in ("input_tokens", "output_tokens", + "cache_creation_input_tokens", "cache_read_input_tokens")] + if any(type(n) is not int or n < 0 for n in fields): + return None + except (OSError, ValueError, KeyError, TypeError, AttributeError): + return None + totals["input"] += fields[0] + totals["output"] += fields[1] + totals["cache_creation"] += fields[2] + totals["cache_read"] += fields[3] + totals["subagents"] += sum(fields[:3]) + totals["total"] = totals["input"] + totals["output"] + totals["cache_creation"] + return totals + except (OSError, ValueError): + return None + + +def probe(run=None) -> dict: + """Require ChatGPT CLI auth, never accept an API-key billing fallback.""" + run = run or subprocess.run + try: + res = run(["codex", "login", "status"], capture_output=True, text=True, timeout=30) + output = (res.stdout or "") + (res.stderr or "") + if res.returncode == 0 and "logged in using chatgpt" in output.lower(): + return {"state": "ok", "detail": "Codex ChatGPT login", "backend": "codex", "expires_at": ""} + # Do not echo CLI output: some versions show a masked API key. + return {"state": "expired", "detail": "Codex ChatGPT login required; run codex login", "backend": "codex", + "expires_at": ""} + except (OSError, subprocess.SubprocessError): + return {"state": "expired", "detail": "Codex login could not be verified; run codex login status", "backend": "codex", + "expires_at": ""} + + +def command(model: str, effort: str, mode: str, cwd: Path, write_root: Path) -> list[str]: + if mode not in {"auto", "dontAsk"}: + raise ValueError("Codex worker-mode must be auto or dontAsk (acceptEdits has no equivalent)") + argv = ["codex", "exec", "--json", "--color", "never", "--model", model, + "-c", f"model_reasoning_effort={json.dumps(effort)}", + "-c", 'model_provider="openai"', "-c", 'forced_login_method="chatgpt"', + "-c", "features.multi_agent=false", "-c", "features.goals=false", # usage is for this worker only + "--sandbox", "workspace-write", "--cd", str(cwd), + "--add-dir", str(write_root), "--skip-git-repo-check"] + if mode == "auto": + argv.append("--approve-for-me") + else: + argv += ["-c", 'approval_policy="never"'] + return argv + ["-"] + + +def launch(prompt: str, *, home: Path, cwd: Path, write_root: Path, model: str, + effort: str, mode: str, env: dict, scope=None, lease_path: Path | None = None) -> dict: + if not Path("/proc/self/stat").exists(): + raise ValueError("Codex shift workers currently require Linux/WSL process identity") + agent_id = PREFIX + uuid.uuid4().hex + directory = session_dir(agent_id, home) + directory.mkdir(parents=True, mode=0o700) + argv = command(model, effort, mode, cwd, write_root) + argv[-1:-1] = ["--add-dir", str(home)] + (directory / "prompt.txt").write_text(prompt, encoding="utf-8") + write_json(directory / "request.json", {"argv": argv, "cwd": str(cwd)}) + write_json(directory / "state.json", {"agent_id": agent_id, "state": "starting"}) + identity = {"pid": 0, "agent_id": agent_id, "session_id": agent_id, + "backend": "codex", "model": model, "effort": effort, "mode": mode} + if lease_path is not None: + lease = json.loads(lease_path.read_text()) + # Reserve identity before starting any process. A watcher killed after + # spawn can adopt this attempt instead of treating it as a dead stub. + write_json(lease_path, {**lease, **identity}) + clean_env = dict(env) + clean_env["PYAUTO_CODEX_SESSION_DIR"] = str(directory) + for key in ("OPENAI_API_KEY", "CODEX_API_KEY", "OPENAI_BASE_URL"): + clean_env.pop(key, None) + # The runner and child retain the existing Mind commit guard environment. + runner = [sys.executable, str(Path(__file__).with_name("_codex_runner.py")), str(directory)] + if scope: + runner = scope(runner) + with (directory / "runner.log").open("ab") as log: + proc = subprocess.Popen(runner, cwd=cwd, env=clean_env, stdin=subprocess.DEVNULL, + stdout=log, stderr=log, start_new_session=True) + # Only the runner writes state; a late parent cannot overwrite completion. + # No retry after an ambiguous start: that would duplicate the worker. + try: + for _ in range(100): + rec = read_record(agent_id, home) + if rec and rec["state"] != "starting": + break + if proc.poll() is not None: + write_json(directory / "state.json", {"agent_id": agent_id, "state": "error", + "reason": "runner exited before handshake"}) + break + time.sleep(0.02) + except OSError: + pass # Process exists: return the reserved identity, never permit a retry. + return identity + + +def stop(agent_id: str, home: Path) -> tuple[bool, str]: + rec = read_record(agent_id, home) + if not rec: + return False, "Codex session state unreadable; refusing to target an unverified process" + if rec["state"] in {"done", "error", "killed"}: + return True, "" + if not rec.get("pid") or process_identity(rec["pid"]) != rec.get("identity"): + return False, "Codex supervisor identity unavailable; inspect its local session record" + # Supervisor handles termination and escalation of its own child group. + (session_dir(agent_id, home) / "STOP").touch() + return True, "" diff --git a/agents/conductors/batch/_codex_review.py b/agents/conductors/batch/_codex_review.py new file mode 100644 index 00000000..f9f9a73c --- /dev/null +++ b/agents/conductors/batch/_codex_review.py @@ -0,0 +1,89 @@ +"""Accounted independent Opus review for one Codex shift worker. + +Invoked synchronously by the worker, never a timer or an autonomous close-out. +The reviewer gets the existing faculty contract and repository paths, not the +writer's conversation. All review attempts remain part of that worker's spend. +""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import uuid + +from _codex import write_json + +SCHEMA = {"type": "object", "properties": { + "verdict": {"type": "string", "enum": ["CLEAN", "FINDINGS", "BLOCKED"]}, + "report": {"type": "string"}}, "required": ["verdict", "report"], + "additionalProperties": False} + + +def review(task: str, repos: list[Path], *, run=None) -> dict: + directory = os.environ.get("PYAUTO_CODEX_SESSION_DIR") + if os.environ.get("PYAUTO_SHIFT_WORKER") != "1" or not directory: + raise ValueError("review helper is only for a registered Codex shift worker") + directory = Path(directory) + state = json.loads((directory / "state.json").read_text()) + if state.get("state") != "working" or state.get("agent_id") != "codex:" + directory.name: + raise ValueError("Codex worker session is not running") + repos = [p.resolve(strict=True) for p in repos] + session = str(uuid.uuid4()) + prefix = directory / f"review-{session}" + # Create evidence before the call; a killed/incomplete reviewer is unknown + # spend, never silently zero. Each fresh attempt has a different identity. + write_json(prefix.with_suffix(".request.json"), {"session_id": session, "task": task, + "repos": list(map(str, repos))}) + faculty = Path(__file__).resolve().parents[2] / "faculties" / "review" / "AGENTS.md" + brain = Path(__file__).resolve().parents[3] + prompt = (f"You are the independent review faculty for task {task}. " + f"Read {faculty}, then use {brain}/bin/pyauto-brain review --task {task} " + "to prepare its review surface (use explicit repo paths if needed). " + "Review both committed and uncommitted changes against origin/main in " + + ", ".join(map(str, repos)) + ". " + "Follow the faculty's code-review and verify pass. Read the task's " + "Mind prompt and its Witness. Never edit source, fix findings, write " + "Mind state, commit, push, merge or contact anyone. Never delegate or " + "start another model. If evidence or permissions are insufficient, " + "return BLOCKED. Return the structured verdict and full findings/evidence; " + "CLEAN only when the faculty's requirements pass. This is ship leg 3, " + "not the close-out adversary or merge authority.") + argv = ["claude", "--print", "--model", "opus", "--effort", "medium", + "--session-id", session, "--permission-mode", "auto", "--max-turns", "40", + "--tools", "Read,Glob,Grep,Bash", "--output-format", "json", + "--json-schema", json.dumps(SCHEMA), "--add-dir", *map(str, repos)] + run = run or subprocess.run + try: + result = run(argv, input=prompt, text=True, capture_output=True, cwd=brain.parent, + timeout=1800) + payload = json.loads(result.stdout) + if not isinstance(payload, dict): + raise ValueError("review output is not an object") + write_json(prefix.with_suffix(".result.json"), payload) + verdict = payload.get("structured_output") or {} + if result.returncode or payload.get("is_error") or not isinstance(verdict, dict): + raise ValueError("review session failed") + if verdict.get("verdict") not in {"CLEAN", "FINDINGS", "BLOCKED"}: + raise ValueError("review returned no recognized verdict") + return {**verdict, "session_id": session, "evidence": str(prefix.with_suffix(".result.json"))} + except (OSError, ValueError, subprocess.SubprocessError) as exc: + return {"verdict": "BLOCKED", "report": str(exc), "session_id": session} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--task", required=True) + parser.add_argument("--repo", type=Path, action="append", required=True) + args = parser.parse_args() + try: + result = review(args.task, args.repo) + except (ValueError, OSError) as exc: + result = {"verdict": "BLOCKED", "report": str(exc)} + print(json.dumps(result)) + return 0 if result["verdict"] == "CLEAN" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/agents/conductors/batch/_codex_runner.py b/agents/conductors/batch/_codex_runner.py new file mode 100644 index 00000000..cea9af68 --- /dev/null +++ b/agents/conductors/batch/_codex_runner.py @@ -0,0 +1,63 @@ +"""One detached Codex CLI worker. Only spawned by the explicitly selected backend.""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + +from _codex import process_identity, write_json + + +def run(directory: Path) -> int: + rec = json.loads((directory / "state.json").read_text()) + request = json.loads((directory / "request.json").read_text()) + rec.update(state="working", pid=os.getpid(), identity=process_identity(os.getpid())) + write_json(directory / "state.json", rec) + child = None + try: + with (directory / "prompt.txt").open("rb") as prompt, \ + (directory / "events.jsonl").open("wb") as output, \ + (directory / "stderr.log").open("wb") as errors: + child = subprocess.Popen(request["argv"], cwd=request["cwd"], stdin=prompt, + stdout=output, stderr=errors, start_new_session=True) + rec["child_pid"] = child.pid + identity = process_identity(child.pid) + if identity is not None: + rec["child_identity"] = identity + write_json(directory / "state.json", rec) + killed = False + while child.poll() is None: + if (directory / "STOP").exists(): + killed = True + os.killpg(child.pid, signal.SIGTERM) + try: + child.wait(timeout=3) + except subprocess.TimeoutExpired: + os.killpg(child.pid, signal.SIGKILL) + child.wait(timeout=3) + break + time.sleep(0.1) + # The leader can exit before its children. End the whole owned + # process group before publishing terminal state (also on success). + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + rec.update(state="killed" if killed else "done" if child.returncode == 0 else "error", + returncode=child.returncode) + except Exception as exc: + # A failed supervisor must not leave a live unaccounted worker. + if child is not None and child.poll() is None: + os.killpg(child.pid, signal.SIGKILL) + child.wait(timeout=3) + rec.update(state="error", reason=f"{type(exc).__name__}: {exc}") + write_json(directory / "state.json", rec) + return 0 + + +if __name__ == "__main__": + raise SystemExit(run(Path(sys.argv[1]))) diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index d25f1fab..d909be1a 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -419,7 +419,8 @@ def _login_expired(b: _Batch, result: dict) -> None: return since = login.get("since") or login.get("at") or b.now.isoformat() b.add("login-expired", f"login-expired:{since}", - _login.EXPIRED_LINE + ". No worker starts until it passes.", needs_you=True) + (login.get("detail", "Codex login required") if login.get("backend") == "codex" + else _login.EXPIRED_LINE) + ". No worker starts until it passes.", needs_you=True) def _late(b: _Batch, result: dict) -> None: diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 4335a58c..7a4e0e13 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -48,6 +48,7 @@ import _app_token # noqa: E402 — the batch conductor puts this directory on sys.path import _brief # noqa: E402 +import _codex # noqa: E402 import _digest # noqa: E402 import _events # noqa: E402 import _login # noqa: E402 — the CLI login probe @@ -682,6 +683,59 @@ def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Pa return {"pid": 0, "agent_id": m.group(1)} +class CodexSpawner(RealSpawner): + """Codex execution workers; independent close-outs still use Claude Opus.""" + + backend = "codex" + + def __init__(self, brief_path: Path, brief: dict, cwd: Path | None = None, **kw): + super().__init__(brief_path, _brief.worker_mode_of(brief), cwd=cwd, **kw) + self.model = brief["codex-model"]["value"] + self.effort = brief.get("codex-effort", {}).get("value", "medium") + + def login_probe(self): + result = _codex.probe() + if result["state"] == "ok": + review_login = _login.probe() + if review_login["state"] not in {"ok", "skipped"}: + return {"state": "expired", "backend": "codex", "expires_at": "", + "detail": "Claude login required for independent Opus pre-ship review"} + return result + + def spawn(self, task: str, prompt_path: str, lease_dir: Path, + redispatch: bool = False, resume: dict | None = None, + siblings: list[str] | None = None) -> dict: + if self.cwd is None: + raise OrchestratorError("Codex requires a resolved workspace root") + login = self.login_probe() + if login["state"] != "ok": + raise OrchestratorError(login["detail"]) + prompt = worker_prompt(task, prompt_path, self.brief_path, lease_dir, + redispatch, resume, siblings) + reviewer = Path(__file__).with_name("_codex_review.py") + prompt += ("\nCodex execution worker: use repository skills directly; slash " + "commands name their canonical instruction files. For the required " + "independent pre-ship review (leg 3), run: python3 " + f"{reviewer} --task {task} --repo " + "(repeat --repo for multiple repositories). This starts a fresh " + "Opus reviewer and accounts its usage to this worker. Require " + "CLEAN on the final diff; findings require fixes and a fresh review. " + "Do not use other model calls or subagents; the watcher owns " + "parallelism and the later independent Opus close-out. " + "If permissions or review block completion, queue the question " + "and write the documented question sidecar and .done marker, then stop.\n") + env = worker_env(lease_dir) + _ensure_kick_dir(env) + home = Path(lease_dir).parent.parent + # The existing worktree root is writable alongside the workspace root. + from _pyauto_root import pyauto_wt_root + return _codex.launch(prompt, home=home, cwd=self.cwd, + write_root=pyauto_wt_root(), model=self.model, + effort=self.effort, mode=self.mode, env=env, + scope=lambda argv: scope_command(argv, task, env), + lease_path=Path(lease_dir) / f"{task}.json") + + def default_spawner(brief_path: Path, brief: dict): if os.environ.get(FAKE_ENV) == "1": return FakeSpawner() @@ -692,6 +746,8 @@ def default_spawner(brief_path: Path, brief: dict): cwd = pyauto_root() except Exception: cwd = None + if _brief.backend_of(brief) == "codex": + return CodexSpawner(brief_path, brief, cwd=cwd) return RealSpawner(brief_path, _brief.worker_mode_of(brief), cwd=cwd) @@ -705,7 +761,8 @@ class AgentsView: *unknown* (`known()` is False) — never an empty list, which would declare every worker gone.""" - def __init__(self, sessions: list[dict] | None = None, run=None): + def __init__(self, sessions: list[dict] | None = None, run=None, home: Path | None = None): + self.home = home or orchestrator_home() self._sessions, self._run = sessions, run or subprocess.run self._failed = False @@ -728,6 +785,11 @@ def known(self) -> bool: """Whether this tick's read says anything at all about the workers.""" return self._load() is not None + def known_for(self, agent_id: str) -> bool: + if agent_id.startswith(_codex.PREFIX): + return _codex.state(agent_id, self.home) is not None + return self.known() + def _find(self, agent_id: str) -> dict | None: return next((s for s in self._load() or [] if s.get("id") == agent_id), None) @@ -735,11 +797,15 @@ def state(self, agent_id: str) -> str | None: """The CLI's state word — `working` while it runs, `blocked` waiting on a person, `done` — or None if unlisted. Anything but `blocked` / `done` / None is read as alive.""" + if agent_id.startswith(_codex.PREFIX): + return _codex.state(agent_id, self.home) s = self._find(agent_id) return None if s is None else (s.get("state") or "running") def session_of(self, agent_id: str) -> str | None: """The full session id — what the transcript file is named by.""" + if agent_id.startswith(_codex.PREFIX): + return agent_id s = self._find(agent_id) return s.get("sessionId") if s else None @@ -840,6 +906,8 @@ def transcript_usage(session_id: str, root: Path | None = None) -> dict | None: `/subagents/agent-*.jsonl`; they are included, deduped the same way, and `subagents` reports their share of `total`. None when there is no transcript or one cannot be read — never 0.""" + if session_id.startswith(_codex.PREFIX): + return _codex.usage(session_id, root or orchestrator_home()) root = root or Path.home() / ".claude" / "projects" main = list(root.glob(f"*/{session_id}.jsonl")) subs = list(root.glob(f"*/{session_id}/subagents/agent-*.jsonl")) @@ -1114,13 +1182,32 @@ def _reap(slot: Path, counters: dict, now: _dt.datetime, grace_s: float, """ events = [] lease_dir = slot / "leases" - agents = agents or AgentsView() + agents = agents or AgentsView(home=slot.parent) known = None # read lazily: a slot of fake workers never calls `claude agents` + unknown_reported = set() for task, lease in leases(slot).items(): done_marker = lease_dir / f"{task}.done" path = lease_dir / f"{task}.json" real = bool(lease.get("agent_id")) and not lease.get("pid") parked = lease.get("state") == "parked" + if lease.get("backend") == "codex" and lease.get("agent_id") not in counters["usage"]: + # Recover a watcher killed after the pre-spawn identity write but + # before its post-spawn counters commit. The usage key is the + # idempotency key for all attempt accounting, including late reap. + launch = lease.get("launch") or {} + key = lease["agent_id"] + counters["usage"][key] = {"kind": "worker", "task": task, "total": None, + "reserve": launch.get("reserve", 0)} + counters["sessions"] += 1 + if launch.get("pick"): + counters["picks"][task] = launch["pick"] + if launch.get("redispatch"): + if task in counters["pending_redispatch"]: + counters["pending_redispatch"].remove(task) + counters["redispatched"][task] = counters["redispatched"].get(task, 0) + 1 + if launch.get("released"): + _spawned_release(counters, task, now) + _write_counters(slot, counters) rec = worker_record(counters, _worker_key(lease, task), task, lease.get("started")) def mark(word, rec=rec): @@ -1129,13 +1216,19 @@ def mark(word, rec=rec): _exit(rec, word) state = None if real: - if known is None: + known_for = getattr(agents, "known_for", None) + if known_for is not None: + known = known_for(lease["agent_id"]) + elif known is None: known = _liveness_known(agents) - if not known: - events.append({"event": "liveness-unknown", - "why": "the `claude agents` read failed — " - "no liveness decision this tick"}) if not known: + backend = "codex" if lease["agent_id"].startswith(_codex.PREFIX) else "claude" + if backend not in unknown_reported: + events.append({"event": "liveness-unknown", + "why": ("the Codex session state read failed — " + if backend == "codex" else "the `claude agents` read failed — ") + + "no liveness decision this tick"}) + unknown_reported.add(backend) # No liveness decision, but the usage still counts: a known # transcript is read; without one the session is unavailable. _measure(counters, lease["agent_id"], lease.get("session_id"), tokens, @@ -1393,6 +1486,9 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, now = now or _now() brief_path = Path(brief_path) slot = slot_dir(brief_path, home) + if tokens is transcript_usage: + tokens = lambda sid: (transcript_usage(sid, root=slot.parent) + if sid.startswith(_codex.PREFIX) else transcript_usage(sid)) # The kill switch is the FIRST read: nothing else is touched while it exists. if (slot / STOP_FILE).exists(): @@ -2101,7 +2197,7 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, """The tick under its lock, then the live status: one `claude agents` view and one set of `gh pr checks` reads serve both.""" shift = shift or {} - agents = agents or AgentsView() + agents = agents or AgentsView(home=slot.parent) health = _TickHealth(health) out = _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health, pr_state, poster=poster, shift=shift, @@ -2389,6 +2485,9 @@ def settled(task: str, member: dict) -> bool: "heartbeat": _iso(now), "expires": _iso(now + _dt.timedelta(seconds=grace_s)), "pid": 0, "session_id": None, "worktree": None} + if getattr(spawner, "backend", None) == "codex": + lease["launch"] = {"reserve": reserve, "pick": pick_record(member, brief), + "redispatch": redo, "released": bool(released)} if (shift or {}).get("issue"): # Where a worker blocked past the grace is filed in the inbox. lease["shift_issue"] = shift["issue"] @@ -2472,7 +2571,7 @@ def _login_hold(counters: dict, spawner, members: list[dict], live: dict, wanted = any(task_id(m["path"]) not in held for m in members) if not (blocked or (wanted and last.get("state") != "ok")): return last if last.get("state") == "expired" else None - res = (probe or _login.probe)() + res = (probe or getattr(spawner, "login_probe", None) or _login.probe)() if res.get("state") == "skipped": return None rec = {**res, "at": _iso(now)} @@ -3171,8 +3270,13 @@ def _cmd_kill(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict return f"ignored: {task}'s worker {key} is already stopping (/kill at {old.get('at')})" # A crash between this stop and the counters write leaves the comment # unseen: the next tick stops the same agent id again, at most — never another session. - ok, why = (ctx.get("stop") or claude_stop)(agent) + codex = agent.startswith(_codex.PREFIX) + stop = ctx.get("stop") or ((lambda sid: _codex.stop(sid, slot.parent)) + if codex else claude_stop) + ok, why = stop(agent) if not ok: + if codex: + return f"refused: Codex stop failed: {why[:160]}" return (f"refused: claude stop failed: {why[:160]}. Stop it by hand: " f"claude stop {agent}") counters.setdefault("killed", {})[task] = {"by": who, "at": at, "key": key} @@ -3184,7 +3288,7 @@ def _cmd_kill(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict tail = "It is not restarted: its one retry is spent." else: tail = f"It is restarted once, unless you /drop {task}." - return f"stopping {task}'s worker {key} (claude stop). {tail}" + return f"stopping {task}'s worker {key} ({'Codex supervisor' if codex else 'claude stop'}). {tail}" # --- the shift-end cloud sweep -------------------------------------------------------- @@ -3613,7 +3717,7 @@ def late_sweep(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, runs while one is out.""" counters = read_counters(slot) counters["usage_unavailable"] = [] - agents = agents or AgentsView() + agents = agents or AgentsView(home=slot.parent) reaped = _reap(slot, counters, now, grace_s, agents, tokens, late=True) closed = reap_closeouts(slot, counters, now, agents, pr_state, tokens, late=True) counters["pending_redispatch"] = [] # the grant has ended: never re-dispatched @@ -3848,7 +3952,7 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, brief, top = rec["brief"] or {}, rec["top"] counters = read_counters(slot) counters["usage_unavailable"] = [] - agents = agents or AgentsView() # one `claude agents` read serves the closing status + agents = agents or AgentsView(home=slot.parent) # one `claude agents` read serves the closing status _reap(slot, counters, now, grace_s, agents, tokens) # A close-out that ended since the last tick lands in this digest; one # still out is reaped by the late sweep. @@ -4078,7 +4182,7 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta stage-2 row. `late` marks the events as after `review-at:`.""" events = {"merged": [], "refused": []} lease_dir = slot / "leases" - agents = agents or AgentsView() + agents = agents or AgentsView(home=slot.parent) known = None for pr, co in counters["closeouts"].items(): diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index 2c60ddff..b691f864 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -123,7 +123,7 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, tasks = list(dict.fromkeys(named + list(picks) + list(held))) if agents is None and not shadow and any(l.get("agent_id") for l in held.values()): - agents = _orchestrator.AgentsView() # one `claude agents --json` per refresh + agents = _orchestrator.AgentsView(home=slot.parent) # one `claude agents --json` per refresh health = health or _digest.pr_health links = _digest.MindLinks(mind, issue) if mind else None diff --git a/bin/codex_orchestrator_check.py b/bin/codex_orchestrator_check.py new file mode 100644 index 00000000..b791991f --- /dev/null +++ b/bin/codex_orchestrator_check.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Check local Codex shift prerequisites; --smoke explicitly runs one no-op worker.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / 'agents' / 'conductors' / 'batch')) +import _codex # noqa: E402 +import _login # noqa: E402 + + +def check() -> dict: + errors = [] + if not Path('/proc/self/stat').exists(): + errors.append('Linux/WSL with /proc process identity is required') + try: + help_result = subprocess.run(['codex', 'exec', '--help'], capture_output=True, + text=True, timeout=30) + for flag in ('--json', '--sandbox', '--add-dir', '--approve-for-me'): + if help_result.returncode or flag not in help_result.stdout: + errors.append(f'installed codex exec does not advertise {flag}') + except (OSError, subprocess.SubprocessError): + errors.append('codex exec is unavailable') + login = _codex.probe() + if login['state'] != 'ok': + errors.append(login['detail']) + reviewer = _login.probe() + if reviewer['state'] != 'ok': + errors.append('Claude login must be verified for independent Opus reviews') + return {'ok': not errors, 'errors': errors, + 'manual_check': 'Review and trust the current project hook hash with /hooks; ' + 'verify gh auth and Heart before a shift. This check starts no model.'} + + +def smoke(model: str) -> dict: + # Disposable workspace: no repositories, shift grants or publication. + import shutil + + root = Path(tempfile.mkdtemp(prefix="pyauto-codex-smoke-")) + home = root / 'state' + marker = root / 'smoke-ok.txt' + prompt = (f'This is a bounded CLI integration smoke test, not a development task. ' + f'Write exactly PYAUTO_CODEX_OK to {marker}, then stop. ' + 'Do not read other projects, call another model, use the network, ' + 'create a task, commit, push or launch any background work.') + lease = _codex.launch(prompt, home=home, cwd=root, write_root=root, model=model, + effort='medium', mode='dontAsk', env=dict(os.environ)) + sid = lease['agent_id'] + try: + end = time.monotonic() + 300 + while time.monotonic() < end: + state = _codex.state(sid, home) + if state in {'done', 'error', 'killed'}: + usage = _codex.usage(sid, home) + passed = state == 'done' and marker.exists() and marker.read_text().strip() == 'PYAUTO_CODEX_OK' + return {'ok': passed and usage is not None, 'state': state, 'usage': usage, + 'marker': passed, 'scope': 'no-op only; no development/merge readiness claim'} + time.sleep(.2) + return {'ok': False, 'error': 'smoke timed out after 300 seconds'} + finally: + _codex.stop(sid, home) + # Never remove a live supervisor's state directory. + end = time.monotonic() + 10 + while _codex.state(sid, home) not in {'done', 'error', 'killed'}: + if time.monotonic() >= end: + # Preserve evidence if the supervisor cannot be observed. + print(f'Smoke state retained at {root}; inspect before another attempt.', file=sys.stderr) + break + time.sleep(.1) + else: + shutil.rmtree(root) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--smoke', action='store_true', help='explicitly run one no-op model session') + parser.add_argument('--model', help='installed Codex model id; required with --smoke') + args = parser.parse_args() + if args.smoke and not args.model: + parser.error('--smoke requires --model') + result = check() + if args.smoke and result['ok']: + result = smoke(args.model) + print(json.dumps(result, indent=2)) + return 0 if result['ok'] else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/docs/codex_orchestrator.md b/docs/codex_orchestrator.md new file mode 100644 index 00000000..e75b9b71 --- /dev/null +++ b/docs/codex_orchestrator.md @@ -0,0 +1,121 @@ +# Codex workers in the existing shift orchestrator + +Codex is an opt-in execution backend, not a second scheduler. Existing briefs +continue to launch Claude workers. Queue order, leases, caps, questions, Mind's +single writer, proof packets, Heart, merge ordering and shift expiry keep their +existing contracts. The canonical brief schema is PyAutoMind `batches/AGENTS.md`. + +## Local prerequisites + +Use the laptop's Linux/WSL workspace and the same installed watcher. This chat's +cloud checkout cannot operate the laptop's watcher or prove its setup works. +No timer is installed or enabled by the backend. + +- A recent Codex CLI advertising `exec --json`, `--sandbox`, `--add-dir` and + `--approve-for-me`, authenticated with `codex login` using the subscription. + API-key authentication is refused; inherited OpenAI API-key variables are + removed from the worker. No OpenAI SDK or API fallback is used. +- Claude CLI authenticated for independent Opus reviews and close-outs. This + remains required even when a shift has `merge-cap: 0`: pre-ship review is + separate from close-out. +- The existing local `gh` identity, Heart readiness, Python environment, + trusted workspace and generated skills/hooks. Review the current Codex + project hook hash with `/hooks`; the backend never bypasses hook trust. +- Linux `/proc` identity checks (WSL supported). Native Windows and macOS + supervisors are not implemented by this adapter. + +Read-only check, with no model call: + +```bash +python3 PyAutoBrain/bin/codex_orchestrator_check.py +``` + +It checks CLI capabilities and both logins. Hook trust, GitHub permissions and +Heart remain separate checks; a green result is not a shift launch grant. + +## Opt into Codex in an approved brief + +Add these under the existing `brief:` block before approval/dispatch: + +```yaml + - worker-backend: codex + - codex-model: + - codex-effort: medium + - worker-mode: auto +``` + +The model is explicit rather than inherited from a laptop preference. Effort +is `low`, `medium`, `high` or `xhigh`, subject to model support. `auto` uses +Codex automatic approval review; `dontAsk` never asks. Both keep the +workspace-write sandbox and allow the workspace, worktree root and shift-state +root. `acceptEdits` has no equivalent and fails validation. Permission refusals +must become the existing question sidecar and `.done` outcome, not a stalled +interactive prompt. No unrestricted or hook-trust-bypass flags are passed. + +Run the existing `batch brief --check ` before dispatch. Backend +selection does not change `Lane:` or grant extra tasks, merges or runtime. +Do not switch an active brief's backend to change a running session: lease +identities retain the backend that actually launched them. + +## Reviews and accounting + +The shared worker prompt still requires independent pre-ship review. A Codex +worker calls `agents/conductors/batch/_codex_review.py --task --repo +` (repeat `--repo` for each affected repository). The helper starts a +fresh Opus CLI session with the existing review-faculty instructions and a +structured CLEAN/FINDINGS/BLOCKED verdict. It records every attempt before +calling the model. It cannot substitute a Codex self-review. The later +close-out remains the existing independent Opus session, with unchanged gates. + +Codex multi-agent tools are disabled for shift workers; the accounted review +helper is their only model delegation. Reviewer input, output and cache +creation are added to the worker's usage. Codex JSONL input includes cached +input, so cache reads are subtracted for the existing uncached-token budget +and separately reported. Incomplete/missing usage remains unknown and retains +the existing reservation; the budget is a dispatch budget, not a hard +inference-token ceiling. Accounting is updated from completed turns, not a +provider quota/weekly-limit API. The existing `bin/codex_usage.py` remains a +separate rollout-inspection tool. + +## Recovery and stopping + +Opaque `codex:` lease identities point to private `codex-sessions//` +directories under the orchestrator home. Each holds the prompt/request, +JSONL events, stderr, reviewer records and atomic supervisor state. It may +contain project data; it is local runtime state and should not be committed. + +The identity and attempt accounting are recoverable before process launch. +A watcher restart adopts the lease and reservation once. Linux boot id and +process start ticks protect against PID reuse. Unreadable state and ambiguous +supervisor/child startup are **unknown**: hold the lease and inspect the local +record; never redispatch just because an observation failed. A no-handshake +session likewise needs inspection, not an automatic retry. + +`/kill ` asks that worker's verified supervisor to stop its child process +group. The existing one-retry rule still applies; `/drop ` first if no +restart is wanted. `/stop` retains its existing whole-shift meaning. A normal +CLI exit without the task's `.done` proof remains an incomplete worker, not +proof that development succeeded. + +## First local check and pilot + +After the read-only check passes, explicitly run one disposable no-op session: + +```bash +python3 PyAutoBrain/bin/codex_orchestrator_check.py --smoke --model +``` + +This consumes a Codex session. It verifies launch, completion, a written marker +and usage in a temporary workspace. It does not create an issue, PR or shift, +run a reviewer, or prove repository permissions. It times out after five minutes. + +For the first real approved shift, use one named low-risk task, `backlog: none`, +`max-workers: 1`, `merge-cap: 0`, an explicit token budget and a human-stated +`review-at:`. Inspect its Opus pre-ship verdict, proof packet, usage, questions +and final PR before increasing concurrency or enabling merges. Use the +existing watcher installation and cockpit; do not create another timer. + +CLI contracts checked during implementation: +[Codex non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode), +[Codex configuration](https://learn.chatgpt.com/docs/config-file/config-reference), +and [Claude CLI reference](https://code.claude.com/docs/en/cli-reference). diff --git a/docs/index.md b/docs/index.md index 1614e995..0d9c0a91 100644 --- a/docs/index.md +++ b/docs/index.md @@ -88,6 +88,7 @@ example agent_failure_modes codex_usage +codex_orchestrator agent_reference context_efficiency agent_harness_smoke diff --git a/tests/test_chat_orchestration_contract.py b/tests/test_chat_orchestration_contract.py index 9b02bde9..f4cfd60a 100644 --- a/tests/test_chat_orchestration_contract.py +++ b/tests/test_chat_orchestration_contract.py @@ -104,6 +104,10 @@ def test_no_runtime_provider_switch_was_added(): for path in root.rglob("*"): if path.suffix not in {".py", ".sh"} or not path.is_file(): continue + # The explicitly selected Codex CLI adapter checks subscription + # auth; it is not a ChatGPT API or runtime fallback. + if path == ROOT / "agents/conductors/batch/_codex.py": + continue if "chatgpt" in path.read_text(encoding="utf-8", errors="replace").lower(): offenders.append(str(path.relative_to(ROOT))) assert not offenders, offenders diff --git a/tests/test_orchestrator_codex.py b/tests/test_orchestrator_codex.py new file mode 100644 index 00000000..d75d73d4 --- /dev/null +++ b/tests/test_orchestrator_codex.py @@ -0,0 +1,334 @@ +"""Codex backend contract and real local supervisor tests; no model/network calls.""" +from __future__ import annotations + +import datetime as dt +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from types import SimpleNamespace + +import pytest + +import test_orchestrator_dispatch as d +from test_orchestrator_dispatch import orch +import _brief +import _codex + + +def wait_for(check, seconds=8): + until = time.monotonic() + seconds + while time.monotonic() < until: + value = check() + if value: + return value + time.sleep(.03) + pytest.fail("supervisor did not reach expected state") + + +def fake_codex(tmp_path, monkeypatch, body=None): + bindir = tmp_path / "bin" + bindir.mkdir(exist_ok=True) + path = bindir / "codex" + path.write_text(f"#!{sys.executable}\n" + (body or '''import json, os, sys +if sys.argv[1:] == ['login', 'status']: + print('Logged in using ChatGPT') + raise SystemExit(0) +prompt = sys.stdin.read() +assert 'OPENAI_API_KEY' not in os.environ +assert 'CODEX_API_KEY' not in os.environ +print(json.dumps({'type': 'thread.started', 'thread_id': 'test-thread'}), flush=True) +print(json.dumps({'type': 'turn.completed', 'usage': { + 'input_tokens': 100, 'cached_input_tokens': 40, 'output_tokens': 20}}), flush=True) +''')) + path.chmod(0o755) + monkeypatch.setenv("PATH", str(bindir) + os.pathsep + os.environ["PATH"]) + monkeypatch.delenv("INVOCATION_ID", raising=False) + return path + + +def launch(tmp_path, monkeypatch, body=None): + fake_codex(tmp_path, monkeypatch, body) + env = dict(os.environ, OPENAI_API_KEY="must-not-reach-child", CODEX_API_KEY="nor-this") + home = tmp_path / "home" + lease = _codex.launch("test prompt", home=home, cwd=tmp_path, write_root=tmp_path, + model="test-model", effort="medium", mode="dontAsk", env=env) + return lease["agent_id"], home + + +def test_supervisor_completion_restart_and_usage(tmp_path, monkeypatch): + sid, home = launch(tmp_path, monkeypatch) + wait_for(lambda: _codex.state(sid, home) == "done") + # A new watcher instance needs no in-memory Popen or Claude session list. + view = orch.AgentsView(home=home, run=lambda *a, **k: pytest.fail("called Claude")) + assert view.known_for(sid) and view.state(sid) == "done" + assert view.session_of(sid) == sid + assert orch.transcript_usage(sid, root=home) == dict( + input=60, output=20, cache_creation=0, cache_read=40, total=80, subagents=0) + assert _codex.stop(sid, home) == (True, "") + request = json.loads((_codex.session_dir(sid, home) / "request.json").read_text()) + assert '--dangerously-bypass-approvals-and-sandbox' not in request['argv'] + assert 'forced_login_method="chatgpt"' in request['argv'] + + +def test_stop_terminates_owned_child_and_records_killed(tmp_path, monkeypatch): + sid, home = launch(tmp_path, monkeypatch, 'import time\ntime.sleep(30)\n') + rec = wait_for(lambda: (r if (r := _codex.read_record(sid, home)).get("child_pid") else None)) + try: + assert _codex.stop(sid, home) == (True, "") + wait_for(lambda: _codex.state(sid, home) == "killed") + assert _codex.process_identity(rec["child_pid"]) is None + finally: + _codex.stop(sid, home) + + +def test_pid_reuse_never_targets_unrelated_process(tmp_path): + sid = "codex:" + "a" * 32 + path = _codex.session_dir(sid, tmp_path) + path.mkdir(parents=True) + _codex.write_json(path / "state.json", dict(agent_id=sid, state="working", + pid=os.getpid(), identity="another-process")) + assert _codex.state(sid, tmp_path) is None + assert not _codex.stop(sid, tmp_path)[0] + assert not (path / "STOP").exists() + + +def test_bad_records_hold_liveness_and_missing_usage(tmp_path): + sid = "codex:" + "b" * 32 + view = orch.AgentsView(home=tmp_path) + assert not view.known_for(sid) + assert view.state(sid) is None + assert _codex.usage(sid, tmp_path) is None + path = _codex.session_dir(sid, tmp_path) + path.mkdir(parents=True) + (path / "state.json").write_text('{broken') + assert not view.known_for(sid) + (path / "events.jsonl").write_text('{"type":"turn.started"}\n{"type":') + assert _codex.usage(sid, tmp_path) is None + with pytest.raises(ValueError): + _codex.session_dir("codex:../../other", tmp_path) + + +@pytest.mark.parametrize("code,out,expected", [ + (0, "Logged in using ChatGPT", "ok"), + (0, "Logged in using an API key: secret", "expired"), + (1, "Not logged in", "expired"), + (0, "unexpected", "expired"), +]) +def test_auth_is_subscription_only(code, out, expected): + result = _codex.probe(run=lambda *a, **k: SimpleNamespace(returncode=code, stdout=out, stderr="")) + assert result["state"] == expected + assert "secret" not in result["detail"] + + +@pytest.mark.parametrize("mode", ["auto", "dontAsk"]) +def test_command_preserves_sandbox_and_model(mode, tmp_path): + argv = _codex.command("selected-model", "high", mode, tmp_path, tmp_path / "worktrees") + assert argv[:3] == ["codex", "exec", "--json"] + assert argv[argv.index("--model") + 1] == "selected-model" + assert argv[argv.index("--sandbox") + 1] == "workspace-write" + assert "features.multi_agent=false" in argv + assert ("--approve-for-me" in argv) == (mode == "auto") + assert "--trust" not in argv and "--dangerously-bypass-hook-trust" not in argv + + +def test_brief_schema_rejects_incompatible_settings(tmp_path): + mind, brief, home = d._shift(tmp_path, extra=" - worker-backend: codex\n") + assert any("codex-model" in e for e in _brief.check(brief, mind)["errors"]) + with brief.open("a") as f: + f.write(" - codex-model: selected-model\n - worker-mode: acceptEdits\n") + assert any("acceptEdits" in e for e in _brief.check(brief, mind)["errors"]) + brief.write_text(brief.read_text().replace("acceptEdits", "dontAsk")) + assert _brief.check(brief, mind)["ok"] + brief.write_text(brief.read_text().replace("worker-backend: codex", "worker-backend: typo")) + assert any("worker-backend" in e for e in _brief.check(brief, mind)["errors"]) + + +def test_default_remains_claude_and_closeout_remains_opus(tmp_path, monkeypatch): + monkeypatch.delenv(orch.FAKE_ENV, raising=False) + assert type(orch.default_spawner(tmp_path / "brief.md", {})) is orch.RealSpawner + brief = _brief.parse("- brief:\n - worker-backend: codex\n - codex-model: selected-model\n")["brief"] + spawner = orch.default_spawner(tmp_path / "brief.md", brief) + assert isinstance(spawner, orch.CodexSpawner) + assert spawner.spawn_closeout.__func__ is orch.RealSpawner.spawn_closeout + argv = orch.closeout_command("t", "https://github.com/a/b/pull/1", "draft/t.md", + tmp_path / "brief.md", tmp_path, "auto") + assert argv[0] == "claude" and argv[argv.index("--model") + 1] == "opus" + + +def test_watcher_reaps_codex_with_claude_unavailable(tmp_path, monkeypatch): + fake_codex(tmp_path, monkeypatch) + mind, brief, home = d._shift(tmp_path, extra=" - worker-backend: codex\n - codex-model: selected-model\n") + spawner = orch.CodexSpawner(brief, _brief.parse(brief.read_text())["brief"], cwd=tmp_path) + monkeypatch.setattr(orch, 'scope_command', lambda argv, *a, **kw: argv) + first = orch.tick(brief, mind, home=home, now=d.NOW, spawner=spawner, grace_s=0) + assert len(first["spawned"]) == 1 + slot = orch.slot_dir(brief, home) + lease = orch.leases(slot)["t1"] + assert lease["backend"] == "codex" + wait_for(lambda: _codex.state(lease["agent_id"], home) == "done") + # A worker's proof marker and successful CLI exit are separate evidence. + (slot / "leases" / "t1.done").write_text("obsolete: sandbox task\n") + second = orch.tick(brief, mind, home=home, now=d.NOW + dt.timedelta(minutes=1), + spawner=spawner, grace_s=0) + assert "t1" in orch.read_counters(slot)["done"] + assert not orch.leases(slot) + assert not second.get("spawned") + assert orch.read_counters(slot)["usage"][lease["agent_id"]]["total"] == 80 + + +def test_nonzero_child_exit_is_error_not_success(tmp_path, monkeypatch): + sid, home = launch(tmp_path, monkeypatch, 'raise SystemExit(7)\n') + wait_for(lambda: _codex.state(sid, home) == "error") + assert _codex.read_record(sid, home)["returncode"] == 7 + assert _codex.usage(sid, home) is None + + +@pytest.mark.parametrize('pid', ['broken', {}, [], True, -1]) +def test_malformed_process_identity_is_unknown(tmp_path, pid): + sid = 'codex:' + 'c' * 32 + directory = _codex.session_dir(sid, tmp_path) + directory.mkdir(parents=True) + _codex.write_json(directory / 'state.json', dict(agent_id=sid, state='working', pid=pid, identity='x')) + assert _codex.state(sid, tmp_path) is None + assert not _codex.stop(sid, tmp_path)[0] + + +def test_supervisor_child_handshake_gap_is_unknown(tmp_path): + sid = 'codex:' + 'd' * 32 + directory = _codex.session_dir(sid, tmp_path) + directory.mkdir(parents=True) + _codex.write_json(directory / 'state.json', dict(agent_id=sid, state='working', pid=999999999, identity='gone')) + assert _codex.state(sid, tmp_path) is None + + +def test_identity_is_reserved_before_process_start(tmp_path, monkeypatch): + lease_path = tmp_path / 'lease.json' + lease_path.write_text('{"task": "t"}') + def die_after_reservation(*args, **kw): + lease = json.loads(lease_path.read_text()) + assert lease['agent_id'].startswith('codex:') + assert lease['backend'] == 'codex' + raise KeyboardInterrupt('simulated watcher death') + monkeypatch.setattr(_codex.subprocess, 'Popen', die_after_reservation) + with pytest.raises(KeyboardInterrupt): + _codex.launch('test', home=tmp_path / 'home', cwd=tmp_path, write_root=tmp_path, + model='selected', effort='medium', mode='auto', env=dict(os.environ), + lease_path=lease_path) + sid = json.loads(lease_path.read_text())['agent_id'] + assert _codex.state(sid, tmp_path / 'home') is None + + +def test_reap_recovers_accounting_idempotently_after_launch_crash(tmp_path): + mind, brief, home = d._shift(tmp_path) + slot = orch.slot_dir(brief, home) + (slot / 'leases').mkdir(parents=True) + sid = 'codex:' + 'e' * 32 + lease = dict(task='t1', agent_id=sid, session_id=sid, pid=0, backend='codex', + started=orch._iso(d.NOW), expires=orch._iso(d.NOW), + launch=dict(reserve=12345, pick={'path': 'draft/t1.md'}, redispatch=True)) + (slot / 'leases' / 't1.json').write_text(json.dumps(lease)) + counters = orch.read_counters(slot) + counters['pending_redispatch'] = ['t1'] + for _ in range(2): + orch._reap(slot, counters, d.NOW, 0, tokens=lambda _: None) + assert counters['sessions'] == 1 + assert counters['redispatched']['t1'] == 1 + assert counters['pending_redispatch'] == [] + assert counters['picks']['t1'] == {'path': 'draft/t1.md'} + assert orch._committed_tokens(counters) == 12345 + assert (slot / 'leases' / 't1.json').exists() + + +def test_stop_cleans_descendants_when_leader_exits(tmp_path, monkeypatch): + child_path = tmp_path / 'grandchild' + body = '''import os, signal, time +pid = os.fork() +if pid == 0: + signal.signal(signal.SIGTERM, signal.SIG_IGN) + time.sleep(30) +else: + open(%r, 'w').write(str(pid)) + time.sleep(30) +''' % str(child_path) + sid, home = launch(tmp_path, monkeypatch, body) + wait_for(child_path.exists) + child = int(child_path.read_text()) + try: + assert _codex.stop(sid, home)[0] + wait_for(lambda: _codex.state(sid, home) == 'killed') + wait_for(lambda: _codex.process_identity(child) is None) + finally: + try: + os.kill(child, 9) + except ProcessLookupError: + pass + + +def test_accounted_opus_review_requires_structured_clean_and_adds_usage(tmp_path, monkeypatch): + import _codex_review + sid, home = launch(tmp_path, monkeypatch) + wait_for(lambda: _codex.state(sid, home) == 'done') + directory = _codex.session_dir(sid, home) + rec = _codex.read_record(sid, home) + rec['state'] = 'working' # helper fixture: owner is still doing development + _codex.write_json(directory / 'state.json', rec) + monkeypatch.setenv('PYAUTO_CODEX_SESSION_DIR', str(directory)) + monkeypatch.setenv('PYAUTO_SHIFT_WORKER', '1') + calls = [] + def reviewer(argv, **kw): + calls.append(argv) + assert argv[argv.index('--model') + 1] == 'opus' + assert '--session-id' in argv and '--resume' not in argv + return SimpleNamespace(returncode=0, stdout=json.dumps({ + 'structured_output': {'verdict': 'CLEAN', 'report': 'verified'}, + 'usage': {'input_tokens': 15, 'output_tokens': 5, + 'cache_creation_input_tokens': 10, 'cache_read_input_tokens': 50}})) + result = _codex_review.review('task', [tmp_path], run=reviewer) + assert result['verdict'] == 'CLEAN' and len(calls) == 1 + u = _codex.usage(sid, home) + assert u['total'] == 110 and u['subagents'] == 30 and u['cache_read'] == 90 + # An interrupted review attempt is unknown spend, not zero. + (directory / 'review-incomplete.request.json').write_text('{}') + assert _codex.usage(sid, home) is None + + +def test_preflight_requires_opus_even_without_merges(tmp_path, monkeypatch): + import _batch + monkeypatch.setattr(_codex, 'probe', lambda: {'state': 'ok', 'detail': 'ok', 'expires_at': ''}) + monkeypatch.setattr(_batch._login, 'probe', lambda: {'state': 'unknown', 'detail': 'missing'}) + for merge in ('', 'bad', '0'): + brief = _brief.parse('- brief:\n - worker-backend: codex\n - codex-model: selected\n' + f' - merge-cap: {merge}\n')['brief'] + login, errors, warnings = _batch.login_findings({}, brief) + assert errors and 'Opus' in errors[0] + + +def test_fast_exit_without_child_identity_is_terminal(tmp_path, monkeypatch): + import _codex_runner + sid = 'codex:' + 'f' * 32 + directory = _codex.session_dir(sid, tmp_path) + directory.mkdir(parents=True) + _codex.write_json(directory / 'state.json', {'agent_id': sid, 'state': 'starting'}) + _codex.write_json(directory / 'request.json', {'argv': [sys.executable, '-c', 'pass'], 'cwd': str(tmp_path)}) + (directory / 'prompt.txt').write_text('') + original = _codex_runner.process_identity + monkeypatch.setattr(_codex_runner, 'process_identity', lambda pid: original(pid) if pid == os.getpid() else None) + assert _codex_runner.run(directory) == 0 + assert _codex.state(sid, tmp_path) == 'done' + + +def test_check_default_does_not_launch_a_worker(tmp_path, monkeypatch): + import importlib.util + path = Path(orch.__file__).resolve().parents[3] / 'bin' / 'codex_orchestrator_check.py' + spec = importlib.util.spec_from_file_location('codex_check_test', path) + check = importlib.util.module_from_spec(spec) + spec.loader.exec_module(check) + monkeypatch.setattr(check._codex, 'launch', lambda *a, **kw: pytest.fail('default check launched a model')) + monkeypatch.setattr(check._codex, 'probe', lambda: {'state': 'ok', 'detail': 'ok'}) + monkeypatch.setattr(check._login, 'probe', lambda: {'state': 'ok'}) + monkeypatch.setattr(check.subprocess, 'run', lambda *a, **kw: SimpleNamespace( + returncode=0, stdout='--json --sandbox --add-dir --approve-for-me')) + assert check.check()['ok']