Files
reliquary/plugins/spire/skills/gremlins/tests/test_codex.py
T
g4borg f6dc43be19 ✨ export: 36 files (features)
M plugins/gitea/.claude-plugin/plugin.json
M plugins/gitea/.codex-plugin/plugin.json
M plugins/gitea/README.md
M plugins/gitea/skills/gitea/SKILL.md
M plugins/gitea/skills/gitea/scripts/fetch_ticket.py
M plugins/gitea/skills/gitea/scripts/start_ticket.py
A plugins/spire/UPGRADES.md
A plugins/spire/agents/designer.md
M plugins/spire/agents/planner.md
A plugins/spire/providers/README.md
A plugins/spire/providers/hosts/claude-desktop/spawning.md
A plugins/spire/providers/hosts/t3-code/spawning.md
A plugins/spire/providers/runtimes/codex/spawning.md
M plugins/spire/skills/gremlins/grm/call.py
M plugins/spire/skills/gremlins/grm/cli.py
A plugins/spire/skills/gremlins/grm/codex.py
A plugins/spire/skills/gremlins/grm/errors.py
A plugins/spire/skills/gremlins/grm/harness.py
M plugins/spire/skills/gremlins/grm/launch.py
A plugins/spire/skills/gremlins/grm/scrub.py
M plugins/spire/skills/gremlins/grm/stream.py
A plugins/spire/skills/gremlins/grm/title.py
A plugins/spire/skills/gremlins/tests/_pin.py
M plugins/spire/skills/gremlins/tests/fake_claude.py
A plugins/spire/skills/gremlins/tests/fake_codex.py
M plugins/spire/skills/gremlins/tests/test_cli.py
A plugins/spire/skills/gremlins/tests/test_cli_codex.py
A plugins/spire/skills/gremlins/tests/test_codex.py
A plugins/spire/skills/gremlins/tests/test_harness.py
A plugins/spire/skills/gremlins/tests/test_scrub.py
A plugins/spire/skills/gremlins/tests/test_title.py
A plugins/spire/skills/igor/references/upgrades.md
A plugins/spire/skills/igor/tests/test_upgrade_notes.py
A plugins/spire/skills/igor/upgrade-notes.sh
R plugins/spire/skills/implementation/references/spawning-claude-code.md -> plugins/spire/providers/runtimes/claude-code/spawning.md
M plugins/spire/skills/project/SKILL.md
2026-11-25 01:52:10 +01:00

533 lines
26 KiB
Python

"""Codex adapter, block 3.1 rows: argv and fingerprint, init checks, model and effort check
(design §4.1-4.2, build plan §2). No real `codex`, no real `~/.codex`: every test pins
`CODEX_HOME` to a temp dir and uses a fake binary."""
import contextlib
import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
SKILL = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(SKILL))
sys.path.insert(0, str(SKILL / "tests"))
from grm import cli, codex, harness, launch, stream # noqa: E402
from grm.errors import Refusal # noqa: E402
from _pin import pin_caller # noqa: E402
MODEL = "gpt-6-luna"
CACHE = {"models": [{"slug": MODEL, "supported_reasoning_levels": [
{"effort": "low", "description": "d"}, {"effort": "medium"}, {"effort": "high"}]},
{"slug": "gpt-6-sol", "supported_reasoning_levels": []}]}
FP_KEYS = {"harness", "binary", "binary_version", "model", "effort", "sandbox", "network", "add_dirs",
"cwd", "ignore_user_config", "config", "ephemeral_forks", "codex_home", "preamble", "env_pass"}
def fake_codex_bin(d: Path) -> str:
"""An executable that prints `codex-cli 0.172.0` for `--version`."""
p = d / "codex"
p.write_text("#!%s\nprint('codex-cli 0.172.0')\n" % sys.executable, encoding="utf-8")
p.chmod(0o755)
return str(p)
def git_repo(d: Path) -> Path:
d.mkdir(parents=True)
subprocess.run(["git", "init", "-q"], cwd=d, check=True, capture_output=True)
return d
class _Tmp(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.home = self.tmp / "codex-home"
self.home.mkdir()
pin_caller(self, "codex", self.home)
self.h = harness.named("codex")
def write_cache(self, data):
p = self.home / "models_cache.json"
p.write_bytes(data if isinstance(data, bytes) else json.dumps(data).encode("utf-8"))
def refused(self, fn, *a, **kw):
with self.assertRaises(Refusal) as e:
fn(*a, **kw)
return e.exception.payload
class AdapterBasicsTest(_Tmp):
def test_members(self):
self.assertIsInstance(self.h, codex.CodexAdapter)
self.assertEqual((self.h.name, self.h.binary_name, self.h.preassigns_session_id), ("codex", "codex", False))
self.assertTrue(self.h.commit_line.startswith(" You cannot commit here (`.git` is read-only"))
self.assertEqual(self.h.infer_ttl({"cache_creation_1h": 5}, None), 600)
self.assertEqual(self.h.infer_ttl(None, 900), 900)
@unittest.skipIf(os.name == "nt", "shebang script")
def test_version_parse(self):
self.assertEqual(self.h.binary_version(fake_codex_bin(self.tmp)), "0.172.0")
self.assertIsNone(self.h.binary_version(str(self.tmp / "nope")))
def test_resolve_binary(self):
self.assertEqual(self.h.resolve_binary("rel/codex"), os.path.abspath("rel/codex"))
with mock.patch.object(codex.shutil, "which", return_value=None):
self.assertIsNone(self.h.resolve_binary(None))
def test_codex_home(self):
self.assertEqual(codex.codex_home(), str(self.home))
self.assertEqual(codex.codex_home({}), os.path.abspath(os.path.expanduser("~/.codex")))
self.assertEqual(codex.codex_home({"CODEX_HOME": "rel"}), os.path.abspath("rel"))
class CheckInitTest(_Tmp):
def test_agent_refused(self):
repo = git_repo(self.tmp / "repo")
p = self.refused(self.h.check_init, cwd=str(repo), agent="reviewer", network=False)
self.assertEqual(p["error"], "Codex has no main-thread agent")
self.h.check_init(cwd=str(repo), agent=None, network=True)
def test_non_git_cwd_refused(self):
d = self.tmp / "plain"
d.mkdir()
with mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.tmp)}):
p = self.refused(self.h.check_init, cwd=str(d), agent=None, network=False)
self.assertEqual(p["error"], "Codex runs need a git repository")
class CheckModelTest(_Tmp):
def test_against_cache(self):
self.write_cache(CACHE)
self.h.check_model(MODEL, "low")
p = self.refused(self.h.check_model, "gpt-6-nova", "low")
self.assertEqual((p["error"], p["models"]), ("unknown model", ["gpt-6-luna", "gpt-6-sol"]))
self.assertIn("run `codex` once to refresh", p["remedy"])
p = self.refused(self.h.check_model, MODEL, "max")
self.assertEqual((p["error"], p["efforts"]), ("unknown effort", ["low", "medium", "high"]))
# a listed model without levels: the effort enum
self.h.check_model("gpt-6-sol", "ultra")
self.assertEqual(self.refused(self.h.check_model, "gpt-6-sol", "bogus")["error"], "unknown effort")
def test_slug_shape(self):
self.write_cache(CACHE)
for m in ("claude-opus-5-5", "Gpt-6", "gpt 6", "", "-gpt"):
self.assertEqual(self.refused(self.h.check_model, m, "low")["error"],
"model must be a Codex model slug", m)
def test_no_cache_or_unparsable(self):
for data in (None, b"{not json", {"models": "x"}, {"other": 1}, []):
if data is None:
(self.home / "models_cache.json").unlink(missing_ok=True)
else:
self.write_cache(data)
self.h.check_model("gpt-anything", "persistent")
self.assertEqual(self.refused(self.h.check_model, "gpt-anything", "bogus")["error"],
"unknown effort")
class FingerprintTest(_Tmp):
def setUp(self):
super().setUp()
self.cwd = git_repo(self.tmp / "repo")
self.bin = fake_codex_bin(self.tmp)
def fp(self, state, network=False, env_pass=()):
state = Path(state)
state.mkdir(parents=True, exist_ok=True)
pre = state / "preamble.md"
pre.write_text("# preamble\n", encoding="utf-8")
return self.h.build_fingerprint(binary=self.bin, model=MODEL, effort="low", cwd=str(self.cwd),
agent=None, network=network, state=str(state),
preamble_path=str(pre), mcp_config=str(state / "mcp-empty.json"),
env_pass=list(env_pass))
def test_stored_argv_and_tails(self):
fpd = self.fp(self.cwd / ".spire" / "scratch" / "r" / "gremlins")
argv = fpd["argv"]
self.assertEqual(argv, [os.path.abspath(self.bin), "exec", "--json", "--ignore-user-config",
"-s", "workspace-write", "-C", str(self.cwd), "-m", MODEL,
"-c", 'model_reasoning_effort="low"', "-c", 'web_search="disabled"',
"-c", "agents.enabled=false"])
run = {"argv": argv}
n = len(argv)
for a, tail in ((self.h.train_argv(run, None, "t"), ["-"]),
(self.h.fork_argv(run, "th-1", None, "t"), ["--ephemeral", "fork", "th-1", "-"]),
(self.h.resume_argv(run, "th-1", "t"), ["resume", "th-1", "-"])):
self.assertEqual((a[:n], a[n:]), (argv, tail))
self.assertNotIn("t", a)
self.assertEqual(len(run["argv"]), n) # the stored list is not mutated
def test_add_dir_only_outside_cwd(self):
self.assertEqual(self.fp(self.cwd / "s")["fingerprint"]["add_dirs"], [])
out = self.tmp / "scratch" / "r" / "gremlins"
fpd = self.fp(out)
self.assertEqual(fpd["fingerprint"]["add_dirs"], [str(out)])
i = fpd["argv"].index("--add-dir")
self.assertEqual(fpd["argv"][i + 1], str(out))
self.assertLess(i, fpd["argv"].index("-m"))
def test_network(self):
off, on = self.fp(self.cwd / "a"), self.fp(self.cwd / "a", network=True)
self.assertFalse(off["fingerprint"]["network"])
self.assertNotIn(codex.NETWORK_CONFIG, off["argv"])
self.assertTrue(on["fingerprint"]["network"])
self.assertEqual(on["argv"][-2:], ["-c", "sandbox_workspace_write.network_access=true"])
self.assertNotEqual(off["fp_hash"], on["fp_hash"])
@unittest.skipIf(os.name == "nt", "shebang script")
def test_fingerprint_keys_and_hash(self):
fpd = self.fp(self.cwd / "a", env_pass=["GH_TOKEN", "GITEA_TOKEN"])
fp = fpd["fingerprint"]
self.assertEqual(set(fp), FP_KEYS)
self.assertEqual((fp["harness"], fp["binary_version"], fp["sandbox"], fp["ignore_user_config"],
fp["ephemeral_forks"], fp["codex_home"], fp["env_pass"]),
("codex", "0.172.0", "workspace-write", True, True, str(self.home),
["GH_TOKEN", "GITEA_TOKEN"]))
self.assertEqual(fp["config"], ['model_reasoning_effort="low"', 'web_search="disabled"',
"agents.enabled=false"])
self.assertEqual(set(fp["preamble"]), {"path", "sha256", "placement"})
self.assertEqual(fp["preamble"]["placement"], "train_prompt")
self.assertEqual(fpd["fp_hash"], launch._sha256_bytes(launch.canonical_json(fp).encode("utf-8")))
def test_env_pins_codex_home(self):
fp = self.fp(self.cwd / "a")["fingerprint"]
env = self.h.env(fp, {"CODEX_HOME": "/host/codex", "CODEX_THREAD_ID": "x", "CLAUDECODE": "1",
"PATH": os.defpath})
self.assertEqual(env["CODEX_HOME"], str(self.home))
self.assertNotIn("CODEX_THREAD_ID", env)
self.assertNotIn("CLAUDECODE", env)
def test_train_prompt(self):
state = self.cwd / "a"
self.fp(state)
p = self.h.train_prompt(state, "TITLE", "RENDERED")
self.assertEqual(p, "TITLE\n\n# preamble\n\n\n---\n\nRENDERED")
class InitCliTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.repo = git_repo(self.tmp / "repo")
self.run_md = str(self.tmp / "run" / "run.md")
self.state = self.tmp / "scratch" / "run" / "gremlins"
env = mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(self.tmp / "scratch")})
env.start()
self.addCleanup(env.stop)
self.bin = fake_codex_bin(self.tmp)
def g(self, *args):
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
code = cli.main(list(args))
return code, json.loads(buf.getvalue().splitlines()[-1])
def init(self, *extra, model=MODEL):
return self.g("init", "--run", self.run_md, "--model", model, "--effort", "low",
"--cwd", str(self.repo), "--binary", self.bin, *extra)
def run_json(self):
p = self.state / "run.json"
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None
def test_init_codex_writes_run(self):
home = pin_caller(self, "codex")
code, out = self.init("--harness", "codex", "--network")
self.assertEqual(code, 0, out)
r = self.run_json()
fp = r["fingerprint"]
self.assertEqual((fp["harness"], r["caller_harness"], out["harness"], fp["codex_home"], fp["network"]),
("codex", "codex", "codex", home, True))
self.assertEqual(r["argv"][1:3], ["exec", "--json"])
self.assertEqual(fp["add_dirs"], [str(self.state)]) # SPIRE_SCRATCH is outside the repo
self.assertIn(codex.NETWORK_CONFIG, r["argv"])
self.assertNotIn("-", r["argv"])
self.assertTrue((self.state / "preamble.md").is_file())
def test_init_codex_refusals_write_nothing(self):
pin_caller(self, "codex")
for extra, model, error in ((["--agent", "a"], MODEL, "Codex has no main-thread agent"),
([], "claude-opus-5-5", "model must be a Codex model slug"),
(["--effort", "bogus"], MODEL, "unknown effort")):
code, out = self.init(*extra, model=model)
self.assertEqual((code, out["error"]), (2, error), out)
self.assertFalse(self.state.exists())
def test_network_refused_on_claude(self):
"""D5: `--network` reaches the Claude adapter's check and is refused."""
pin_caller(self, "claude")
code, out = self.g("init", "--run", self.run_md, "--model", "claude-opus-5-5", "--cwd", str(self.repo),
"--binary", sys.executable, "--network")
self.assertEqual((code, out["error"]), (2, "Claude gremlins have no sandbox network switch"))
self.assertFalse(self.state.exists())
# ---- block 3.3: stream, accounting, verdict, rollout, preflight ----
def usage(inp, cached, out=10, write=0):
return {"input_tokens": inp, "cached_input_tokens": cached, "cache_write_input_tokens": write,
"output_tokens": out, "reasoning_output_tokens": 0}
def events(tid, u, text="done", tool=False):
"""A `codex exec --json` stream in the P3 shapes (event types and usage keys only)."""
evs = [{"type": "thread.started", "thread_id": tid}, {"type": "turn.started"},
{"type": "item.completed", "item": {"id": "i0", "type": "agent_message", "text": "reading"}}]
if tool:
cmd = {"id": "i1", "type": "command_execution", "command": "ls", "aggregated_output": "",
"exit_code": None, "status": "in_progress"}
evs += [{"type": "item.started", "item": cmd},
{"type": "item.completed", "item": dict(cmd, exit_code=0, status="completed")}]
evs += [{"type": "item.completed", "item": {"id": "i2", "type": "agent_message", "text": text}},
{"type": "turn.completed", "usage": u}]
return evs
def feed(evs, model=MODEL):
ss = stream.CodexStreamState(model)
for i, ev in enumerate(evs):
ss.feed(ev, 100.0 + i)
return ss
def mapped(inp, cached, out=10):
return {MODEL: {"inputTokens": inp - cached, "outputTokens": out, "cacheReadInputTokens": cached,
"cacheCreationInputTokens": 0}}
class CodexStreamTest(unittest.TestCase):
def test_p3_train_stream(self):
"""P3 base B2 train (one tool call): id, first item time, last text, mapped totals."""
ss = feed(events("th-b2", usage(38778, 11648, 151), text="trained", tool=True))
self.assertEqual((ss.session_id, ss.first_at, ss.last_assistant_at), ("th-b2", 102.0, 106.0))
r = ss.result
self.assertEqual((r["is_error"], r["session_id"], r["result"], r["total_cost_usd"]),
(False, "th-b2", "trained", None))
self.assertEqual(r["modelUsage"], mapped(38778, 11648, 151))
self.assertEqual(stream.classify(ss, 0, False), ("ok", None))
def test_first_thread_id_wins(self):
evs = events("th-1", usage(1, 0))
ss = feed(evs[:1] + [{"type": "thread.started", "thread_id": "th-2"}] + evs[1:])
self.assertEqual((ss.session_id, ss.result["session_id"]), ("th-1", "th-1"))
def test_no_thread_started_is_error(self):
"""Build plan §2: an `ok` turn without `thread.started` must not write a base."""
ss = feed(events("x", usage(23827, 11648))[1:])
self.assertIsNone(ss.session_id)
self.assertEqual((ss.result["is_error"], ss.result["result"]), (True, "no thread.started event"))
self.assertEqual(stream.classify(ss, 0, False), ("error", "is_error"))
def test_failures_classify(self):
"""usage limit -> usage_limit; unmatched text -> is_error; no turn end -> exit_code."""
limit = "You've hit your usage limit. Try again later."
ss = feed(events("th", usage(1, 0))[:2] + [{"type": "error", "message": limit},
{"type": "turn.failed", "error": {"message": limit}}])
self.assertEqual(stream.classify(ss, 1, False), ("error", "usage_limit"))
self.assertEqual(ss.session_id, "th")
ss = feed(events("th", usage(1, 0))[:2] + [{"type": "turn.failed", "error": {"message": "sandbox denied"}}])
self.assertEqual(stream.classify(ss, 1, False), ("error", "is_error"))
ss = feed(events("th", usage(1, 0))[:2] + [{"type": "error"}])
self.assertEqual((ss.result["result"], stream.classify(ss, 1, False)), ("error", ("error", "is_error")))
ss = feed(events("th", usage(1, 0))[:3])
self.assertIsNone(ss.result)
self.assertEqual(stream.classify(ss, 1, False), ("error", "exit_code"))
def test_later_turn_completed_replaces_an_error(self):
evs = events("th", usage(5, 0))
ss = feed(evs[:2] + [{"type": "error", "message": "Reconnecting... 1/5"}] + evs[2:])
self.assertEqual(stream.classify(ss, 0, False), ("ok", None))
def test_ignores_junk(self):
ss = stream.CodexStreamState(MODEL)
for ev in (None, [], {"type": 3}, {"no": "type"}, {"type": "item.updated", "item": None}):
ss.feed(ev, 1.0)
self.assertEqual((ss.session_id, ss.result, ss.first_at), (None, None, 1.0))
class CodexUsageTest(unittest.TestCase):
def test_train_counts_whole_total(self):
u = stream.codex_usage({"usage": usage(23827, 11648, 34), "modelUsage": mapped(23827, 11648, 34)},
None, None)
self.assertEqual(u["tokens"], {"input": 12179, "output": 34, "cache_creation": 0, "cache_read": 11648,
"cache_creation_1h": 0, "cache_creation_5m": 0})
self.assertEqual((u["models_used"], u["cost_delta"], u["total"]), ([MODEL], None, None))
self.assertEqual(u["model_usage"], mapped(23827, 11648, 34))
def test_r5_fork_delta(self):
"""r5 (persisted fork): 47,688 - 23,827 input, 23,296 - 11,648 cached."""
base = mapped(23827, 11648)
u = stream.codex_usage({"usage": usage(47688, 23296, 20), "modelUsage": mapped(47688, 23296, 20)},
base, None)
self.assertEqual((u["tokens"]["input"] + u["tokens"]["cache_read"], u["tokens"]["cache_read"]),
(47688 - 23827, 23296 - 11648))
self.assertEqual((u["tokens"]["input"], u["tokens"]["output"]), (12213, 10))
def test_n4_after_resume(self):
"""n4: the resumed base's totals are the new basis (71,565 - 47,678; 59,008 - 35,328)."""
u = stream.codex_usage({"usage": usage(71565, 59008), "modelUsage": mapped(71565, 59008)},
mapped(47678, 35328), None)
self.assertEqual((u["tokens"]["input"] + u["tokens"]["cache_read"], u["tokens"]["cache_read"]),
(23887, 23680))
def test_error_result_without_usage(self):
for res in ({"is_error": True, "result": "x", "usage": None, "modelUsage": {}}, {}, None):
u = stream.codex_usage(res, mapped(100, 50), None)
self.assertEqual(set(u["tokens"].values()), {0})
self.assertEqual((u["models_used"], u["model_usage"], u["cost_delta"]), ([], {}, None))
def test_through_the_adapter(self):
h = codex.CodexAdapter()
ss = h.new_stream({"model": MODEL})
self.assertIsInstance(ss, stream.CodexStreamState)
for i, ev in enumerate(events("g1", usage(65748, 38400, 188))):
ss.feed(ev, float(i))
u = h.usage(ss, mapped(38778, 11648, 151), None)
self.assertEqual((u["tokens"]["cache_read"], u["tokens"]["input"]), (26752, 218))
self.assertEqual(h.cache_verdict(ss, u, 26904), "hit")
self.assertIsNone(h.cache_verdict(ss, None, 26904))
class CodexVerdictTest(unittest.TestCase):
def tok(self, inp, cr):
return {"input": inp, "cache_read": cr}
def test_verdicts(self):
v = stream.codex_cache_verdict
self.assertEqual(v(self.tok(218, 26752), 26904), "hit") # P3 g1/g2
self.assertEqual(v(self.tok(181, 23680), 23827), "hit") # r7 ephemeral
self.assertEqual(v(self.tok(12213, 11648), 23827), "partial") # r5 persisted
self.assertEqual(v(self.tok(23861, 0), 23827), "miss")
self.assertEqual(v(self.tok(20000, 26752), 26904), "partial") # big fork
self.assertEqual(v(self.tok(218, 26752), 0), "partial") # no rollout: never hit
self.assertEqual(v(self.tok(218, 26752), None), "partial")
self.assertIsNone(v(None, 26904))
def rollout_lines(*input_tokens):
out = [{"timestamp": "t", "type": "session_meta", "payload": {"id": "x"}},
{"type": "event_msg", "payload": {"type": "token_count", "info": None}},
{"type": "response_item", "payload": {"type": "message", "content": "token_count mention"}}]
for n in input_tokens:
out.append({"type": "event_msg", "payload": {"type": "token_count", "info": {
"last_token_usage": usage(n, n // 2), "total_token_usage": usage(n * 2, n)}}})
return "\n".join(json.dumps(x) for x in out) + "\nnot json token_count\n"
class RolloutTest(_Tmp):
def write(self, day, tid, text, mtime=None):
d = self.home / "sessions" / "2026" / "11" / day
d.mkdir(parents=True, exist_ok=True)
p = d / ("rollout-2026-11-%sT10-00-00-%s.jsonl" % (day, tid))
p.write_text(text, encoding="utf-8")
if mtime is not None:
os.utime(p, (mtime, mtime))
return p
def ss(self, tid):
s = stream.CodexStreamState(MODEL)
s.session_id = tid
return s
def test_last_token_count_and_newest_wins(self):
tid = "019a-th-b2"
self.write("23", tid, rollout_lines(999), mtime=1_000_000)
self.write("24", tid, rollout_lines(11648, 26904), mtime=2_000_000)
self.write("24", "019a-other", rollout_lines(5))
fp = {"codex_home": str(self.home)}
self.assertEqual(self.h.context_tokens(fp, self.ss(tid)), (26904, []))
self.assertEqual(codex.rollout_path(str(self.home), tid).split(os.sep)[-2], "24")
# no fp codex_home: the env (init-time) home
self.assertEqual(self.h.context_tokens({}, self.ss(tid)), (26904, []))
def test_none_found(self):
fp = {"codex_home": str(self.home)}
for tid in ("missing", None):
n, warnings = self.h.context_tokens(fp, self.ss(tid))
self.assertEqual((n, len(warnings)), (0, 1))
self.write("24", "th-empty", rollout_lines())
n, warnings = self.h.context_tokens(fp, self.ss("th-empty"))
self.assertEqual(n, 0)
self.assertIn("no token_count record", warnings[0])
def test_glob_chars_in_id_are_literal(self):
self.write("24", "abc", rollout_lines(7))
self.assertIsNone(codex.rollout_path(str(self.home), "a*"))
class PreflightTest(_Tmp):
def test_ok_creates_tmp_and_leaves_no_file(self):
self.h.preflight({"codex_home": str(self.home)})
self.assertEqual(list((self.home / "tmp").iterdir()), [])
def test_init_inputs_fall_back_to_env_home(self):
"""review 2 M3: with init inputs (no `codex_home`) preflight probes the env's CODEX_HOME,
a fresh pinned home; HOME is pinned too, so a wrong fallback can never reach ~/.codex."""
other, fake_home = self.tmp / "other-home", self.tmp / "user-home"
other.mkdir()
fake_home.mkdir()
with mock.patch.dict(os.environ, {"CODEX_HOME": str(other), "HOME": str(fake_home)}):
self.h.preflight({"harness": "codex", "binary": "b", "cwd": "c", "env_pass": []})
self.assertEqual(list((other / "tmp").iterdir()), [])
self.assertFalse((self.home / "tmp").exists())
self.assertEqual(list(fake_home.iterdir()), [])
def test_missing_home_refused_not_created(self):
"""review 2 M2: a CODEX_HOME that does not exist is refused, never created."""
missing = self.tmp / "no-such-home"
p = self.refused(self.h.preflight, {"codex_home": str(missing)})
self.assertEqual((p["error"], p["codex_home"]), ("codex_home_missing", str(missing)))
self.assertIn("run `codex` once", p["remedy"])
self.assertFalse(missing.exists())
state = self.tmp / "scratch" / "run" / "gremlins"
repo = git_repo(self.tmp / "repo")
buf = io.StringIO()
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(self.tmp / "scratch"),
"CODEX_HOME": str(missing)}), contextlib.redirect_stdout(buf):
code = cli.main(["init", "--run", str(self.tmp / "run" / "run.md"), "--model", MODEL,
"--effort", "low", "--cwd", str(repo), "--binary", sys.executable])
out = json.loads(buf.getvalue().splitlines()[-1])
self.assertEqual((code, out["error"]), (2, "codex_home_missing"))
self.assertFalse(state.exists())
self.assertFalse(missing.exists())
@unittest.skipIf(os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0),
"POSIX permissions; root writes anywhere")
def test_read_only_home_refused(self):
for make_tmp in (False, True):
home = self.tmp / ("ro-%s" % make_tmp)
(home / "tmp").mkdir(parents=True) if make_tmp else home.mkdir()
ro = home / "tmp" if make_tmp else home
ro.chmod(0o555)
self.addCleanup(ro.chmod, 0o755)
p = self.refused(self.h.preflight, {"codex_home": str(home)})
self.assertEqual(p["error"], "codex_home_not_writable")
self.assertIn("run G escalated", p["remedy"])
self.assertIn("--add-dir %s -c sandbox_workspace_write.network_access=true" % home, p["remedy"])
@unittest.skipIf(os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0),
"POSIX permissions; root writes anywhere")
def test_init_refuses_before_writing(self):
state = self.tmp / "scratch" / "run" / "gremlins"
repo = git_repo(self.tmp / "repo")
self.home.chmod(0o555)
self.addCleanup(self.home.chmod, 0o755)
buf = io.StringIO()
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(self.tmp / "scratch")}), \
contextlib.redirect_stdout(buf):
code = cli.main(["init", "--run", str(self.tmp / "run" / "run.md"), "--model", MODEL,
"--effort", "low", "--cwd", str(repo), "--binary", sys.executable])
out = json.loads(buf.getvalue().splitlines()[-1])
self.assertEqual((code, out["error"]), (2, "codex_home_not_writable"))
self.assertFalse(state.exists())
if __name__ == "__main__":
unittest.main()