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
351 lines
17 KiB
Python
351 lines
17 KiB
Python
"""The CLI end to end on fake_codex (design §9.2 `test_cli_codex` row, build plan 3.4). The caller
|
||
is pinned as Codex with a temp `CODEX_HOME` (tests/_pin.py); `--binary` is a wrapper that runs
|
||
tests/fake_codex.py, so no real `codex` and no real `~/.codex` is touched.
|
||
|
||
The read-only `CODEX_HOME` refusal at `init` (`codex_home_not_writable`, nothing written) is the
|
||
init preflight path and is covered through the cli in test_codex.PreflightTest; the `ro_home`
|
||
scenario here is the other path: a launch that fails at Codex startup."""
|
||
import contextlib
|
||
import io
|
||
import json
|
||
import os
|
||
import shutil
|
||
import signal
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import threading
|
||
import time
|
||
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, title # noqa: E402
|
||
from _pin import pin_caller # noqa: E402
|
||
|
||
FAKE = str(SKILL / "tests" / "fake_codex.py")
|
||
MODEL = "gpt-6-luna"
|
||
CACHE = {"models": [{"slug": MODEL, "supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}]}]}
|
||
# fake_codex's cache model (train 1100 in / 100 cached; each later call adds 50 + the 20 output)
|
||
BASE_CTX = 1100
|
||
|
||
|
||
def wrapper_bin(d: Path) -> str:
|
||
"""An executable `codex` that runs fake_codex.py with this interpreter."""
|
||
p = d / "codex"
|
||
p.write_text("#!%s\nimport os, sys\nos.execv(sys.executable, [sys.executable, %r] + sys.argv[1:])\n"
|
||
% (sys.executable, FAKE), encoding="utf-8")
|
||
p.chmod(0o755)
|
||
return str(p)
|
||
|
||
|
||
@unittest.skipIf(os.name == "nt", "the fake binary is a shebang script")
|
||
class CodexCliTest(unittest.TestCase):
|
||
def setUp(self):
|
||
self.tmp = Path(tempfile.mkdtemp())
|
||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||
self.repo = self.tmp / "repo"
|
||
self.repo.mkdir()
|
||
for a in (["init", "-q"], ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q",
|
||
"--allow-empty", "-m", "x"]):
|
||
subprocess.run(["git", *a], cwd=self.repo, check=True, capture_output=True)
|
||
self.run_md = str(self.tmp / "run" / "run.md")
|
||
self.state = self.tmp / "scratch" / "run" / "gremlins"
|
||
self.log = self.tmp / "fake.jsonl"
|
||
self.brief = self.tmp / "brief.md"
|
||
self.brief.write_text("do the thing\n", encoding="utf-8")
|
||
self.home = Path(pin_caller(self, "codex", self.tmp / "codex-home"))
|
||
self.home.mkdir()
|
||
(self.home / "models_cache.json").write_text(json.dumps(CACHE), encoding="utf-8")
|
||
env = mock.patch.dict(os.environ, {"FAKE_CODEX_LOG": str(self.log), "FAKE_CODEX_SCENARIO": "ok",
|
||
"SPIRE_SCRATCH": str(self.tmp / "scratch")})
|
||
env.start()
|
||
self.addCleanup(env.stop)
|
||
self.bin = wrapper_bin(self.tmp)
|
||
|
||
# ---- helpers ----
|
||
def g(self, *args, scenario=None):
|
||
if scenario:
|
||
os.environ["FAKE_CODEX_SCENARIO"] = scenario
|
||
buf = io.StringIO()
|
||
try:
|
||
with contextlib.redirect_stdout(buf):
|
||
code = cli.main(list(args))
|
||
finally:
|
||
os.environ["FAKE_CODEX_SCENARIO"] = "ok"
|
||
return code, json.loads(buf.getvalue().splitlines()[-1])
|
||
|
||
def init(self, *extra):
|
||
code, out = self.g("init", "--run", self.run_md, "--model", MODEL, "--effort", "low",
|
||
"--cwd", str(self.repo), "--binary", self.bin, *extra)
|
||
self.assertEqual(code, 0, out)
|
||
return out
|
||
|
||
def train(self, scenario=None):
|
||
return self.g("train", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief),
|
||
scenario=scenario)
|
||
|
||
def spawn(self, job, scenario=None):
|
||
return self.g("spawn", "--run", self.run_md, "--base", "B1", "--job", job,
|
||
"--brief", str(self.brief), scenario=scenario)
|
||
|
||
def rebase(self, scenario=None):
|
||
return self.g("rebase", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief),
|
||
scenario=scenario)
|
||
|
||
def calls(self):
|
||
if not self.log.exists():
|
||
return []
|
||
return [json.loads(ln) for ln in self.log.read_text(encoding="utf-8").splitlines()]
|
||
|
||
def ledger(self):
|
||
return [json.loads(ln) for ln in (self.state / "ledger.jsonl").read_text(encoding="utf-8").splitlines()]
|
||
|
||
def run_json(self):
|
||
return json.loads((self.state / "run.json").read_text(encoding="utf-8"))
|
||
|
||
def base_rec(self):
|
||
p = self.state / "bases" / "B1.json"
|
||
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None
|
||
|
||
def job(self, j):
|
||
return json.loads((self.state / "jobs" / (j + ".json")).read_text(encoding="utf-8"))
|
||
|
||
def tail(self, call):
|
||
"""The logged argv after the stored prefix (the fake logs its own path as argv[0])."""
|
||
stored = self.run_json()["argv"]
|
||
self.assertEqual(call["argv"][1:len(stored)], stored[1:])
|
||
return call["argv"][len(stored):]
|
||
|
||
# ---- happy path ----
|
||
def test_train_spawn_rebase_happy(self):
|
||
out = self.init()
|
||
self.assertEqual((out["harness"], out["fingerprint"]["binary_version"]), ("codex", "0.172.0"))
|
||
preamble = (self.state / "preamble.md").read_text(encoding="utf-8")
|
||
|
||
code, out = self.train()
|
||
self.assertEqual((code, out["status"], out["warnings"]), (0, "ok", []), out)
|
||
tid = out["session_id"]
|
||
self.assertTrue(tid)
|
||
self.assertEqual(self.base_rec()["session_id"], tid)
|
||
self.assertEqual(self.tail(self.calls()[0]), ["-"])
|
||
t = self.job("B1-train")["title"]
|
||
self.assertTrue(t.startswith("%s B1 · run · " % title.TITLE_EMOJI), t)
|
||
brief = (self.state / "briefs" / "B1-train.md").read_text(encoding="utf-8")
|
||
self.assertTrue(brief.startswith(t + "\n\n" + preamble), brief[:300])
|
||
self.assertTrue(self.calls()[0]["prompt_head"].startswith(t + "\n\n# Headless implementer"))
|
||
base = self.base_rec()
|
||
self.assertEqual((base["context_tokens"], base["ttl_s"], base["cost_cumulative_usd"]),
|
||
(BASE_CTX, 600, None))
|
||
self.assertEqual(base["model_usage"], {MODEL: {"inputTokens": 1000, "outputTokens": 20,
|
||
"cacheReadInputTokens": 100,
|
||
"cacheCreationInputTokens": 0}})
|
||
code, st = self.g("status", "--run", self.run_md)
|
||
self.assertEqual((st["bases"]["B1"]["base_state"], st["bases"]["B1"]["ttl_s"]), ("warm", 600))
|
||
|
||
code, out = self.spawn("1.1")
|
||
self.assertEqual((code, out["status"], out["cache"]), (0, "ok", "hit"), out)
|
||
self.assertEqual(self.tail(self.calls()[1]), ["--ephemeral", "fork", tid, "-"])
|
||
sp = (self.state / "briefs" / "1.1.md").read_text(encoding="utf-8")
|
||
for phrase in ("Trained once, as the base", "Forked once per task", "Headless implementer",
|
||
"newest delta header wins"):
|
||
self.assertNotIn(phrase, sp)
|
||
self.assertIn(codex.COMMIT_LINE, sp)
|
||
line = self.ledger()[-1]
|
||
self.assertEqual((line["job"], line["model"], line["models_used"], line["cache"]),
|
||
("1.1", MODEL, [MODEL], "hit"))
|
||
self.assertIsNone(line["cost_delta_usd"])
|
||
self.assertIsNone(line["cost_cumulative_usd"])
|
||
# per-call deltas, not the thread's running totals (which include the base)
|
||
self.assertEqual(line["tokens"], {"input": 70, "output": 20, "cache_creation": 0, "cache_read": 1100,
|
||
"cache_creation_1h": 0, "cache_creation_5m": 0})
|
||
self.assertEqual(self.base_rec(), base) # spawn never writes the base
|
||
|
||
code, out = self.rebase()
|
||
self.assertEqual((code, out["status"], out["session_id"], out["warnings"]), (0, "ok", tid, []), out)
|
||
self.assertEqual(self.tail(self.calls()[2]), ["resume", tid, "-"])
|
||
rb = self.base_rec()
|
||
self.assertEqual((rb["session_id"], rb["context_tokens"], len(rb["rebases"])), (tid, 1170, 1))
|
||
self.assertNotEqual(rb["model_usage"], base["model_usage"])
|
||
self.assertEqual(rb["model_usage"][MODEL]["cacheReadInputTokens"], 1200)
|
||
self.assertEqual(self.job("B1-rebase1")["title"].split(" · ")[0],
|
||
"%s B1 › rebase 1" % title.TITLE_EMOJI)
|
||
|
||
code, out = self.spawn("1.2") # a fork of the resumed base still hits
|
||
self.assertEqual((code, out["cache"], self.ledger()[-1]["tokens"]["cache_read"]), (0, "hit", 1170))
|
||
|
||
def test_prefix_unchanged(self):
|
||
"""§3.2: run.json argv, fp_hash and the preamble copy are constant; tails are per call."""
|
||
self.init()
|
||
r0 = self.run_json()
|
||
pre0 = (self.state / "preamble.md").read_bytes()
|
||
self.train()
|
||
self.spawn("1.1")
|
||
self.rebase()
|
||
r1 = self.run_json()
|
||
self.assertEqual((r1["argv"], r1["fp_hash"], r1["fingerprint"]), (r0["argv"], r0["fp_hash"], r0["fingerprint"]))
|
||
self.assertEqual((self.state / "preamble.md").read_bytes(), pre0)
|
||
self.assertEqual(len(self.calls()), 3)
|
||
for c in self.calls():
|
||
self.tail(c)
|
||
self.assertNotIn("-", r0["argv"])
|
||
self.assertFalse(any(x in r0["argv"] for x in ("fork", "resume", "--ephemeral")))
|
||
|
||
def test_codex_home_pinned_from_fingerprint(self):
|
||
"""D-B4: a caller CODEX_HOME that moved after init does not move the rollouts."""
|
||
self.init()
|
||
other = self.tmp / "other-home"
|
||
other.mkdir()
|
||
os.environ["CODEX_HOME"] = str(other) # pin_caller's patch restores it
|
||
code, out = self.train()
|
||
self.assertEqual((code, out["warnings"]), (0, []), out)
|
||
self.assertTrue(list((self.home / "sessions").glob("*/*/*/rollout-*-%s.jsonl" % out["session_id"])))
|
||
self.assertFalse((other / "sessions").exists())
|
||
|
||
def test_rendered_templates_have_no_unresolved_keys(self):
|
||
self.init()
|
||
self.train()
|
||
self.spawn("1.1")
|
||
self.rebase()
|
||
names = sorted(p.name for p in (self.state / "briefs").glob("*.md"))
|
||
self.assertEqual(names, ["1.1.md", "B1-rebase1.md", "B1-train.md"])
|
||
for n in names:
|
||
self.assertNotIn("${", (self.state / "briefs" / n).read_text(encoding="utf-8"), n)
|
||
|
||
# ---- failure paths ----
|
||
def test_miss_scenario_reads_partial(self):
|
||
"""D-B7: an ephemeral fork that reads only the generic prefix still has cache_read > 0."""
|
||
self.init()
|
||
self.train()
|
||
code, out = self.spawn("1.1", scenario="miss")
|
||
self.assertEqual((code, out["status"], out["cache"]), (0, "ok", "partial"))
|
||
|
||
def test_spawn_failures(self):
|
||
"""turn_failed -> error/is_error; usage_limit -> usage_limit; the base is untouched."""
|
||
self.init()
|
||
self.train()
|
||
base = self.base_rec()
|
||
for j, scenario, reason in (("f1", "turn_failed", "is_error"), ("f2", "usage_limit", "usage_limit"),
|
||
("f3", "noresult", "exit_code")):
|
||
code, out = self.spawn(j, scenario=scenario)
|
||
self.assertEqual((code, out["status"], out["reason"]), (1, "error", reason), scenario)
|
||
self.assertEqual(self.job(j)["status"], "error")
|
||
# review 2 M1: no usage means no verdict (as on Claude), not a recorded miss
|
||
self.assertIsNone(self.job(j)["cache"], scenario)
|
||
self.assertIsNone(self.ledger()[-1]["cache"], scenario)
|
||
self.assertEqual(len(self.ledger()), 4)
|
||
self.assertEqual(self.base_rec(), base)
|
||
|
||
def test_train_failures_write_no_base(self):
|
||
"""noresult and ro_home (a launch failing at Codex startup) end error/exit_code; a train
|
||
whose stream has no thread.started ends error and writes no base file."""
|
||
self.init()
|
||
for scenario, reason in (("noresult", "exit_code"), ("ro_home", "exit_code"), ("no_thread", "is_error")):
|
||
code, out = self.train(scenario)
|
||
self.assertEqual((code, out["status"], out["reason"]), (1, "error", reason), scenario)
|
||
self.assertIsNone(self.base_rec(), scenario)
|
||
self.assertEqual(out["result_excerpt"], "no thread.started event")
|
||
self.assertEqual(len(self.ledger()), 3)
|
||
self.assertEqual(list((self.state / "bases").iterdir()), [])
|
||
|
||
def test_no_rollout_warns(self):
|
||
"""review 2 M4, design §4.4: a train or rebase whose rollout is missing reports one warning
|
||
through the cli, and the base context is 0 (a later spawn cannot read `hit`)."""
|
||
self.init()
|
||
code, out = self.train("no_rollout")
|
||
self.assertEqual((code, out["status"]), (0, "ok"), out)
|
||
self.assertEqual(len(out["warnings"]), 1, out)
|
||
self.assertIn("no rollout found", out["warnings"][0])
|
||
self.assertEqual(self.base_rec()["context_tokens"], 0)
|
||
code, out = self.rebase("no_rollout")
|
||
self.assertEqual((code, out["status"]), (0, "ok"), out)
|
||
self.assertEqual([w for w in out["warnings"] if "no rollout found" in w], out["warnings"])
|
||
self.assertEqual(len(out["warnings"]), 1, out)
|
||
self.assertEqual(self.base_rec()["context_tokens"], 0)
|
||
code, out = self.spawn("1.1")
|
||
self.assertEqual((code, out["status"]), (0, "ok"))
|
||
self.assertNotEqual(out["cache"], "hit")
|
||
|
||
def test_ro_home_stderr_kept(self):
|
||
self.init()
|
||
code, out = self.train("ro_home")
|
||
self.assertEqual((code, out["reason"]), (1, "exit_code"))
|
||
self.assertIn(b"Read-only file system (os error 30)", (self.state / "raw" / "B1-train.err").read_bytes())
|
||
self.assertEqual((self.state / "raw" / "B1-train.jsonl").read_bytes(), b"")
|
||
|
||
def test_parallel_spawns(self):
|
||
self.init()
|
||
self.train()
|
||
ts = [threading.Thread(target=cli.main, args=(["spawn", "--run", self.run_md, "--base", "B1",
|
||
"--job", j, "--brief", str(self.brief)],))
|
||
for j in ("p1", "p2")]
|
||
with contextlib.redirect_stdout(io.StringIO()):
|
||
for t in ts:
|
||
t.start()
|
||
for t in ts:
|
||
t.join(60)
|
||
for j in ("p1", "p2"):
|
||
self.assertEqual((self.job(j)["status"], self.job(j)["cache"]), ("ok", "hit"))
|
||
lines = self.ledger()
|
||
self.assertEqual(sorted(ln["job"] for ln in lines[1:]), ["p1", "p2"])
|
||
|
||
def test_stop_signal(self):
|
||
"""B4 on Codex: the helper subprocess inherits the pinned env (a Codex caller)."""
|
||
self.init()
|
||
self.train()
|
||
env = dict(os.environ, FAKE_CODEX_SCENARIO="sleep")
|
||
h = subprocess.Popen([sys.executable, str(SKILL / "gremlins.py"), "spawn", "--run", self.run_md,
|
||
"--base", "B1", "--job", "s1", "--brief", str(self.brief)],
|
||
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||
jpath, raw = self.state / "jobs" / "s1.json", self.state / "raw" / "s1.jsonl"
|
||
deadline = time.time() + 30
|
||
while time.time() < deadline and not (
|
||
jpath.exists() and json.loads(jpath.read_text(encoding="utf-8")).get("child_pid")
|
||
and raw.exists() and b'"item.completed"' in raw.read_bytes()):
|
||
time.sleep(0.2)
|
||
pid = json.loads(jpath.read_text(encoding="utf-8"))["child_pid"]
|
||
os.kill(h.pid, signal.SIGTERM)
|
||
out, _ = h.communicate(timeout=30)
|
||
self.assertEqual(h.returncode, 1)
|
||
self.assertEqual(json.loads(out.decode("utf-8").splitlines()[-1])["status"], "stopped")
|
||
self.assertEqual(self.job("s1")["status"], "stopped")
|
||
self.assertIn(b'"thread.started"', raw.read_bytes())
|
||
with self.assertRaises(ProcessLookupError):
|
||
os.kill(pid, 0)
|
||
|
||
# ---- env scrub as the gremlin sees it ----
|
||
def test_scrub_names_in_child_env(self):
|
||
values = {"CLAUDE_CODE_OAUTH_TOKEN": "val-claude-oauth-1", "ANTHROPIC_BASE_URL": "val-anthropic-2",
|
||
"CLAUDE_PID": "val-claude-pid-3", "OPENAI_API_KEY": "val-openai-4",
|
||
"CODEX_SESSION_ID": "val-codex-session-5", "OTHER_SECRET": "val-other-6",
|
||
"GITEA_TOKEN": "val-gitea-7", "CODEX_ACCESS_TOKEN": "val-codex-access-8",
|
||
"PLAIN_SETTING": "val-plain-9"}
|
||
os.environ.update(values) # pin_caller's patch restores the env
|
||
out = self.init("--pass-env", "GITEA_TOKEN")
|
||
self.assertEqual(self.run_json()["fingerprint"]["env_pass"], ["GITEA_TOKEN"])
|
||
for n in ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_PID", "OPENAI_API_KEY",
|
||
"CODEX_SESSION_ID", "CODEX_THREAD_ID", "OTHER_SECRET"):
|
||
self.assertIn(n, out["env_dropped"])
|
||
self.train()
|
||
self.spawn("1.1")
|
||
calls = self.calls()
|
||
self.assertEqual(len(calls), 2)
|
||
for c in calls:
|
||
names = set(c["env_names"])
|
||
for n in ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_PID", "OPENAI_API_KEY",
|
||
"CODEX_SESSION_ID", "CODEX_THREAD_ID", "OTHER_SECRET", "CLAUDECODE"):
|
||
self.assertNotIn(n, names)
|
||
for n in ("CODEX_HOME", "GITEA_TOKEN", "CODEX_ACCESS_TOKEN", "PLAIN_SETTING", "PATH"):
|
||
self.assertIn(n, names)
|
||
text = self.log.read_text(encoding="utf-8") + json.dumps(out)
|
||
for v in values.values():
|
||
self.assertNotIn(v, text)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|