Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ PowerShell:
| `clodex init` | Install native Claude/Codex instructions and MCP config |
| `clodex native status` | Show native instruction and MCP config state |
| `clodex native doctor` | Run native setup checks, CLI readiness, and launcher checks |
| `clodex doctor` | Check Python, git, Claude Code, Codex, and `CLODEX.md` |
| `clodex doctor [--strict]` | Check Python, git, both CLIs (login, supported flags), the live Codex model catalog, and `CLODEX.md` settings; `--strict` fails on warnings |
| `clodex init --migrate [--split-claude] [--dry-run]` | Update `CLODEX.md` settings that no longer work (retired models, unsupported efforts) |
| `clodex plan "<task>"` | Run Claude planning only |
| `clodex build "<task>"` | Run plan, implementation, and dual audit loop in an isolated worktree |
| `clodex audit --diff` | Audit current uncommitted changes |
Expand Down Expand Up @@ -175,6 +176,23 @@ approved diff hash; a local-workspace run is reported as already in the working
that fails unexpectedly is marked `failed` (traceback in `error.txt`) and its worktree is
removed; approved and blocked runs keep theirs until `clodex clean <run-id>`.

### Models and `clodex doctor`

`clodex doctor` validates the configuration against what is actually installed:

- **Models:** retired Codex models are errors, ones retiring soon are warnings (both name the
replacement). Efforts are checked against the live catalog (`codex debug models`, cached for
24h in `.clodex/models-cache.json`), so a stale `reasoning_effort` is caught before a run.
- **CLI flags:** the installed `claude` and `codex` are probed once per version
(`.clodex/capabilities.json`). Missing optional flags (`--json-schema`, `--output-schema`, ...)
are warnings and Clodex simply runs without them; missing required flags are errors.
- **Login:** `claude auth status` and `codex login status`.
- **Settings:** reviewers, quorum, sandbox, approval profile and workspace backend.

`clodex build`, `audit` and `task start` refuse to start on a retired Codex model
(`clodex init --migrate` fixes the file; `CLODEX_ALLOW_RETIRED_MODEL=1` overrides). Migration edits
only the YAML front matter, keeps comments and line endings, and is safe to re-run.

### Audit quorum

`audit.quorum` decides when the reviewers agree: `unanimous` (default), `majority`, or a number
Expand Down
113 changes: 113 additions & 0 deletions clodex/capabilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Detect which flags the installed Claude / Codex CLIs support by reading their `--help`.

Version numbers say little about which flags exist, so this probes the real help text and
caches the result per CLI version in `.clodex/capabilities.json`. Command builders consult the
cache and drop optional flags a CLI is known to lack; an empty cache means "assume supported".
"""

from __future__ import annotations

import json
import re
import shutil
import subprocess
from pathlib import Path
from typing import Any

CACHE_NAME = "capabilities.json"

# Without these a run cannot work at all.
REQUIRED_FLAGS: dict[str, tuple[str, ...]] = {
"claude": ("--effort", "--permission-mode", "--output-format", "--model"),
"codex": ("--sandbox", "--model", "--cd"),
}
# Clodex degrades gracefully without these (prompt + schema validation + stdout parsing).
OPTIONAL_FLAGS: dict[str, tuple[str, ...]] = {
"claude": ("--json-schema", "--fallback-model", "--max-budget-usd"),
"codex": ("--output-schema", "--output-last-message", "--approve-for-me", "--ephemeral"),
}
HELP_COMMANDS: dict[str, list[str]] = {
"claude": ["claude", "--help"],
"codex": ["codex", "exec", "--help"],
}
VERSION_COMMANDS: dict[str, list[str]] = {
"claude": ["claude", "--version"],
"codex": ["codex", "--version"],
}


def flags_in_help(text: str, flags: tuple[str, ...]) -> list[str]:
return [flag for flag in flags if re.search(rf"(?<![\w-]){re.escape(flag)}(?![\w-])", text)]


def _run(argv: list[str]) -> str | None:
exe = shutil.which(argv[0])
if not exe:
return None
try:
result = subprocess.run([exe, *argv[1:]], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, stdin=subprocess.DEVNULL, check=False)
except (OSError, subprocess.TimeoutExpired):
return None
return (result.stdout or "") + (result.stderr or "") if result.returncode == 0 else None


def _version(cli: str) -> str | None:
output = _run(VERSION_COMMANDS[cli])
return output.strip().splitlines()[0] if output and output.strip() else None


def probe_cli(cli: str) -> dict[str, Any]:
"""`{version, probed, supported, missing_required, missing_optional}`; probed is False if help was unreadable."""
version = _version(cli)
help_text = _run(HELP_COMMANDS[cli])
if help_text is None:
return {"version": version, "probed": False, "supported": [], "missing_required": [], "missing_optional": []}
required, optional = REQUIRED_FLAGS[cli], OPTIONAL_FLAGS[cli]
found = flags_in_help(help_text, required + optional)
return {
"version": version,
"probed": True,
"supported": found,
"missing_required": [flag for flag in required if flag not in found],
"missing_optional": [flag for flag in optional if flag not in found],
}


def cache_path(repo_root: Path) -> Path:
return repo_root / ".clodex" / CACHE_NAME


def load(repo_root: Path) -> dict[str, dict[str, Any]]:
try:
data = json.loads(cache_path(repo_root).read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}


def probe_all(repo_root: Path, clis: tuple[str, ...] = ("claude", "codex"), use_cache: bool = True) -> dict[str, dict[str, Any]]:
"""Probe each CLI, reusing the cached result while its version is unchanged."""
cached = load(repo_root) if use_cache else {}
result: dict[str, dict[str, Any]] = {}
for cli in clis:
version = _version(cli)
previous = cached.get(cli)
if previous and previous.get("probed") and version and previous.get("version") == version:
result[cli] = previous
else:
result[cli] = probe_cli(cli)
try:
path = cache_path(repo_root)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
except OSError:
pass
return result


def supports(repo_root: Path, cli: str, flag: str) -> bool | None:
"""True/False if the cache knows, None if unknown (then callers assume supported)."""
info = load(repo_root).get(cli)
if not info or not info.get("probed"):
return None
return flag in info.get("supported", [])
36 changes: 34 additions & 2 deletions clodex/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
from pathlib import Path
from typing import Any

from .config import ConfigError
from .doctor import run_doctor
from .evals import run_local_evals
from .hooks import hook_config, ingest_hook_event
from .mcp_server import main as mcp_main
from .migrate import migrate_contract
from .models import ModelRetiredError
from .native import (
ManagedBlockError,
apply_native_install,
Expand All @@ -22,17 +25,44 @@


def main(argv: list[str] | None = None) -> int:
try:
return _main(argv)
except (ConfigError, ModelRetiredError) as exc:
print(f"clodex: error: {exc}", file=sys.stderr)
return 2


def handle_migrate(args: argparse.Namespace) -> int:
contract = Path.cwd() / "CLODEX.md"
if not contract.is_file():
print_output({"ok": False, "error": f"{contract} not found"}, args.json)
return 1
with contract.open(encoding="utf-8", newline="") as handle: # keep CRLF endings as they are
text = handle.read()
migrated, changes = migrate_contract(text, split_claude=args.split_claude)
written = bool(changes) and not args.dry_run
if written:
with contract.open("w", encoding="utf-8", newline="") as handle:
handle.write(migrated)
print_output({"ok": True, "file": str(contract), "changes": changes, "dry_run": args.dry_run, "written": written}, args.json)
return 0


def _main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="clodex", description="Claude Code + Codex CLI workflow orchestrator")
parser.add_argument("--json", action="store_true", help="Print machine-readable JSON where supported")
sub = parser.add_subparsers(dest="command", required=True)

sub.add_parser("doctor", help="Check local Clodex, Claude Code, Codex, and git readiness")
doctor = sub.add_parser("doctor", help="Check local Clodex, Claude Code, Codex, and git readiness")
doctor.add_argument("--strict", action="store_true", help="Treat warnings (e.g. a model retiring soon) as failures")

init = sub.add_parser("init", help="Install native Claude Code and Codex collaboration instructions")
init.add_argument("--global", action="store_true", dest="global_mode")
init.add_argument("--dry-run", action="store_true")
init.add_argument("--no-mcp-config", action="store_true")
init.add_argument("--force", action="store_true")
init.add_argument("--migrate", action="store_true", help="Update CLODEX.md settings that no longer work (retired models, unsupported efforts)")
init.add_argument("--split-claude", action="store_true", help="With --migrate: split flat claude.model/effort into plan and audit roles")

native = sub.add_parser("native", help="Inspect native Clodex setup")
native_sub = native.add_subparsers(dest="native_command", required=True)
Expand Down Expand Up @@ -120,9 +150,11 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "mcp-server":
return mcp_main()
if args.command == "doctor":
exit_code, data = run_doctor()
exit_code, data = run_doctor(strict=args.strict)
print_output(data, args.json)
return exit_code
if args.command == "init" and args.migrate:
return handle_migrate(args)
if args.command == "init":
try:
exit_code = 0
Expand Down
48 changes: 26 additions & 22 deletions clodex/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from dataclasses import dataclass
from pathlib import Path

from . import capabilities
from .config import ClodexConfig
from .schemas import compact_schema, schema_path

Expand Down Expand Up @@ -65,11 +66,11 @@ def _claude_command(name: str, config: ClodexConfig, role: str, schema_name: str
"json",
]
fallback = settings.get("fallback_model")
if fallback:
if fallback and capabilities.supports(config.repo_root, "claude", "--fallback-model") is not False:
argv.extend(["--fallback-model", ",".join(fallback) if isinstance(fallback, (list, tuple)) else str(fallback)])
if settings.get("max_budget_usd") not in (None, ""):
if settings.get("max_budget_usd") not in (None, "") and capabilities.supports(config.repo_root, "claude", "--max-budget-usd") is not False:
argv.extend(["--max-budget-usd", str(settings["max_budget_usd"])])
if inline_schema_supported(settings.get("json_schema", "auto")):
if inline_schema_supported(settings.get("json_schema", "auto")) and capabilities.supports(config.repo_root, "claude", "--json-schema") is not False:
argv.extend(["--json-schema", compact_schema(schema_name)])
return AgentCommand(name=name, argv=argv, schema_name=schema_name)

Expand Down Expand Up @@ -107,26 +108,29 @@ def codex_review_command(config: ClodexConfig, repo_root: Path) -> AgentCommand:
# --output-schema, so audits run as a read-only `codex exec`; the audit prompt
# already embeds the diff.
codex = config.codex_role("audit")
argv = [
"codex",
"exec",
"-m",
str(codex["model"]),
"-c",
f'model_reasoning_effort="{codex["reasoning_effort"]}"',
"-c",
'approval_policy="never"',
"--sandbox",
"read-only",
"--ephemeral",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: --ephemeral is in OPTIONAL_FLAGS["codex"] but codex_review_command includes it unconditionally. The doctor warns "Clodex will run without it" when missing, but the command builder always passes it, so audits would fail at runtime on older Codex versions — the doctor's warning is misleading.

Wrap "--ephemeral", in if capabilities.supports(config.repo_root, "codex", "--ephemeral") is not False: to match the pattern used for --output-schema two lines below.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

"-C",
str(repo_root),
]
# An older Codex without these flags still works: the prompt asks for JSON, stdout is
# parsed, and the reply is validated against the schema either way.
if capabilities.supports(config.repo_root, "codex", "--output-schema") is not False:
argv.extend(["--output-schema", str(schema_path("audit_verdict"))])
argv.append("-")
return AgentCommand(
name="codex-audit",
argv=[
"codex",
"exec",
"-m",
str(codex["model"]),
"-c",
f'model_reasoning_effort="{codex["reasoning_effort"]}"',
"-c",
'approval_policy="never"',
"--sandbox",
"read-only",
"--ephemeral",
"-C",
str(repo_root),
"--output-schema",
str(schema_path("audit_verdict")),
"-",
],
argv=argv,
schema_name="audit_verdict",
capture_last_message=True,
capture_last_message=capabilities.supports(config.repo_root, "codex", "--output-last-message") is not False,
)
25 changes: 10 additions & 15 deletions clodex/config.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from __future__ import annotations

import sys
from datetime import date
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from .models import retirement

try:
import yaml
except ImportError: # npm installs have no site-packages PyYAML; use the vendored copy
Expand Down Expand Up @@ -64,26 +65,17 @@ class ConfigError(ValueError):
"""CLODEX.md could not be loaded."""


# Codex models being retired: model -> (retire date, successor). A fuller
# registry replaces this once model validation lands.
RETIRING_CODEX_MODELS: dict[str, tuple[str, str]] = {
"gpt-5.5": ("2026-10-14", "gpt-6.1-sol"),
}
_warned_models: set[str] = set()


def warn_if_model_retiring(model: str) -> None:
entry = RETIRING_CODEX_MODELS.get(model)
if entry is None or model in _warned_models:
info = retirement(model)
if info is None or model in _warned_models:
return
_warned_models.add(model)
retire_on, successor = entry
verb = "has retired" if date.today() >= date.fromisoformat(retire_on) else "retires"
print(
f"clodex: warning: Codex model '{model}' {verb} on {retire_on}. "
f"Set `model: {successor}` under `codex:` in the CLODEX.md front matter.",
file=sys.stderr,
)
verb = "has retired" if info.retired else "retires"
fix = f" Set `model: {info.successor}` under `codex:` in the CLODEX.md front matter (or run `clodex init --migrate`)." if info.successor else ""
print(f"clodex: warning: Codex model '{model}' {verb} on {info.on.isoformat()}.{fix}", file=sys.stderr)


@dataclass(frozen=True)
Expand Down Expand Up @@ -180,6 +172,9 @@ def load_config(repo_root: Path | None = None) -> ClodexConfig:
parsed = parse_front_matter(front_matter, str(contract))
merged = deep_merge(DEFAULT_CONFIG, parsed)
warn_if_model_retiring(str(merged["codex"].get("model", "")))
audit_override = merged["codex"].get("audit")
if isinstance(audit_override, dict) and audit_override.get("model"):
warn_if_model_retiring(str(audit_override["model"]))
return ClodexConfig(repo_root=root, raw=merged, prompt_body=body.strip(), user=parsed)


Expand Down
Loading
Loading