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
204 lines
8.3 KiB
Python
204 lines
8.3 KiB
Python
"""Fake `codex exec --json` for the CLI tests (design §9.1), modelled on fake_claude.py.
|
|
|
|
Argv: `--version` prints `codex-cli 0.172.0`. Otherwise `exec`, options, then an optional
|
|
`fork <id>` or `resume <id>`, then the prompt (`-` reads stdin). `fork` without a prompt exits 2.
|
|
|
|
State lives in the fake home `$CODEX_HOME`: `fake_threads.json` (running totals and context per
|
|
thread id) and rollouts `sessions/2026/11/24/rollout-<ts>-<id>.jsonl` for train, resume and
|
|
persisted forks. An `--ephemeral` fork writes nothing.
|
|
|
|
Cache model: every first request reads the generic GENERIC tokens from cache. An ephemeral fork,
|
|
or a resume of a known thread, also reads the thread's last request input (the base context). A
|
|
persisted fork reads only the generic prefix (as measured, research §4).
|
|
|
|
$FAKE_CODEX_SCENARIO: ok (default), miss (an ephemeral fork or resume reads only the generic
|
|
prefix), turn_failed, usage_limit (`error` + `turn.failed`, exit 1), noresult (exit 1 after
|
|
`thread.started`), sleep, ro_home (stderr "Read-only file system (os error 30)", exit 1, no
|
|
events), no_thread (`turn.completed` without `thread.started`), no_rollout (as ok, but no
|
|
rollout file is written; the thread state is kept).
|
|
$FAKE_CODEX_LOG: one JSON line per call: argv, pid, prompt_chars, prompt_head (200 chars) and
|
|
the sorted env names (never values)."""
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
VERSION = "codex-cli 0.172.0"
|
|
GENERIC = 100 # the generic Codex prefix every fresh request reads from cache
|
|
TRAIN_TOKENS = 1000 # the train prompt's own tokens
|
|
CALL_TOKENS = 50 # a fork's or resume's new prompt tokens
|
|
OUTPUT_TOKENS = 20
|
|
VALUE_OPTS = {"-m", "--model", "-C", "--cd", "-s", "--sandbox", "--add-dir", "-c", "--config",
|
|
"-p", "--profile", "-o", "--output-last-message", "--color"}
|
|
USAGE_KEYS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens")
|
|
|
|
|
|
def emit(ev):
|
|
print(json.dumps(ev), flush=True)
|
|
|
|
|
|
def fail(msg, code):
|
|
sys.stderr.write(msg + "\n")
|
|
sys.stderr.flush()
|
|
sys.exit(code)
|
|
|
|
|
|
def parse(args):
|
|
"""(options, flags, positionals) of the args after `exec`."""
|
|
opts, flags, pos = {}, set(), []
|
|
i = 0
|
|
while i < len(args):
|
|
a = args[i]
|
|
if a in VALUE_OPTS:
|
|
if i + 1 >= len(args):
|
|
fail("error: %s needs a value" % a, 2)
|
|
opts.setdefault(a, []).append(args[i + 1])
|
|
i += 2
|
|
continue
|
|
if a.startswith("-") and a != "-":
|
|
flags.add(a)
|
|
else:
|
|
pos.append(a)
|
|
i += 1
|
|
return opts, flags, pos
|
|
|
|
|
|
def home() -> str:
|
|
h = os.environ.get("CODEX_HOME")
|
|
if not h:
|
|
fail("fake_codex: CODEX_HOME must be set by the test", 3)
|
|
return h
|
|
|
|
|
|
def load_threads() -> dict:
|
|
try:
|
|
with open(os.path.join(home(), "fake_threads.json"), "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
except FileNotFoundError:
|
|
return {}
|
|
|
|
|
|
def save_threads(threads: dict) -> None:
|
|
path = os.path.join(home(), "fake_threads.json")
|
|
tmp = "%s.%d.tmp" % (path, os.getpid())
|
|
with open(tmp, "w", encoding="utf-8") as f:
|
|
json.dump(threads, f)
|
|
os.replace(tmp, path)
|
|
|
|
|
|
def new_thread_id() -> str:
|
|
"""UUIDv7-like: a time-ordered head, a random tail."""
|
|
h = "%012x" % (int(time.time() * 1000) & 0xFFFFFFFFFFFF) + uuid.uuid4().hex[12:]
|
|
h = h[:12] + "7" + h[13:]
|
|
return "%s-%s-%s-%s-%s" % (h[:8], h[8:12], h[12:16], h[16:20], h[20:32])
|
|
|
|
|
|
def rollout_dir() -> str:
|
|
d = os.path.join(home(), "sessions", "2026", "11", "24")
|
|
os.makedirs(d, exist_ok=True)
|
|
return d
|
|
|
|
|
|
def rollout_for(tid: str) -> str:
|
|
"""The thread's rollout path (an existing one for a resume)."""
|
|
d = rollout_dir()
|
|
for name in sorted(os.listdir(d)):
|
|
if name.endswith("-%s.jsonl" % tid):
|
|
return os.path.join(d, name)
|
|
ts = time.strftime("%Y-%m-%dT%H-%M-%S")
|
|
return os.path.join(d, "rollout-%s-%s.jsonl" % (ts, tid))
|
|
|
|
|
|
def write_rollout(tid: str, request: dict, totals: dict, meta: dict | None) -> None:
|
|
lines = []
|
|
if meta is not None:
|
|
lines.append({"type": "session_meta", "payload": meta})
|
|
lines.append({"type": "event_msg", "payload": {"type": "token_count", "info": None}})
|
|
lines.append({"type": "response_item", "payload": {"type": "message", "role": "assistant"}})
|
|
lines.append({"type": "event_msg", "payload": {"type": "token_count", "info": {
|
|
"last_token_usage": dict(request, reasoning_output_tokens=0,
|
|
total_tokens=request["input_tokens"] + request["output_tokens"]),
|
|
"total_token_usage": dict(totals), "model_context_window": 200000}}})
|
|
with open(rollout_for(tid), "a", encoding="utf-8") as f:
|
|
for ln in lines:
|
|
f.write(json.dumps(ln) + "\n")
|
|
|
|
|
|
def main():
|
|
argv = sys.argv[1:]
|
|
if argv[:1] == ["--version"]:
|
|
print(VERSION)
|
|
return
|
|
if not argv or argv[0] != "exec":
|
|
fail("fake_codex: only `exec` is faked", 2)
|
|
opts, flags, pos = parse(argv[1:])
|
|
sub = pos[0] if pos and pos[0] in ("fork", "resume") else None
|
|
ref = pos[1] if sub and len(pos) > 1 else None
|
|
rest = pos[2:] if sub else pos
|
|
if sub and ref is None:
|
|
fail("error: %s needs a session id" % sub, 2)
|
|
if not rest:
|
|
fail("error: a prompt is required here (ForkOnly is not faked)", 2)
|
|
prompt = sys.stdin.buffer.read().decode("utf-8") if rest[0] == "-" else rest[0]
|
|
scen = os.environ.get("FAKE_CODEX_SCENARIO", "ok")
|
|
if os.environ.get("FAKE_CODEX_LOG"):
|
|
with open(os.environ["FAKE_CODEX_LOG"], "a", encoding="utf-8") as f:
|
|
f.write(json.dumps({"argv": sys.argv, "pid": os.getpid(), "prompt_chars": len(prompt),
|
|
"prompt_head": prompt[:200],
|
|
"env_names": sorted(os.environ)}) + "\n") # names, never values
|
|
if scen == "ro_home":
|
|
fail("WARNING: proceeding, even though we could not create PATH aliases: Read-only file "
|
|
"system (os error 30)\nError: failed to initialize in-process app-server client: "
|
|
"Read-only file system (os error 30)", 1)
|
|
if "-m" not in opts and "--model" not in opts:
|
|
fail("fake_codex: the stored argv always passes -m", 2)
|
|
ephemeral = "--ephemeral" in flags
|
|
threads = load_threads()
|
|
base = None
|
|
if sub:
|
|
base = threads.get(ref)
|
|
if base is None:
|
|
fail("Error: thread/session not found: %s" % ref, 1)
|
|
# this call's single request and the thread's running totals after it
|
|
if base is None: # train: a fresh thread
|
|
cached, inp = GENERIC, GENERIC + TRAIN_TOKENS
|
|
before = {k: 0 for k in USAGE_KEYS}
|
|
else:
|
|
reads_base = (ephemeral or sub == "resume") and scen != "miss"
|
|
cached = base["last_input"] if reads_base else GENERIC
|
|
inp = base["ctx"] + CALL_TOKENS
|
|
before = base["totals"]
|
|
request = {"input_tokens": inp, "cached_input_tokens": cached, "cache_write_input_tokens": 0,
|
|
"output_tokens": OUTPUT_TOKENS}
|
|
totals = {k: int(before.get(k) or 0) + request[k] for k in USAGE_KEYS}
|
|
tid = ref if sub == "resume" else new_thread_id()
|
|
|
|
if scen != "no_thread":
|
|
emit({"type": "thread.started", "thread_id": tid})
|
|
emit({"type": "turn.started"})
|
|
if scen == "noresult":
|
|
sys.exit(1)
|
|
if scen in ("turn_failed", "usage_limit"):
|
|
msg = ("You've hit your usage limit. Try again later." if scen == "usage_limit"
|
|
else "stream disconnected before completion")
|
|
if scen == "usage_limit":
|
|
emit({"type": "error", "message": msg})
|
|
emit({"type": "turn.failed", "error": {"message": msg}})
|
|
sys.exit(1)
|
|
emit({"type": "item.completed", "item": {"id": "item_0", "type": "agent_message", "text": "reading"}})
|
|
if scen == "sleep":
|
|
time.sleep(60)
|
|
emit({"type": "item.completed", "item": {"id": "item_1", "type": "agent_message", "text": "done"}})
|
|
if scen != "no_thread" and not ephemeral: # persisted: train, resume, persisted fork
|
|
meta = None if sub == "resume" else {"id": tid, "forked_from_id": ref}
|
|
if scen != "no_rollout":
|
|
write_rollout(tid, request, totals, meta)
|
|
threads[tid] = {"totals": totals, "last_input": inp, "ctx": inp + OUTPUT_TOKENS}
|
|
save_threads(threads)
|
|
emit({"type": "turn.completed", "usage": totals})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|