Repository navigation
Expand file tree
/
Copy pathtest_codex_launch.py
More file actions
648 lines (560 loc) · 36.4 KB
/
Copy pathtest_codex_launch.py
File metadata and controls
648 lines (560 loc) · 36.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# Copyright (c) 2026 Firefly Software Solutions Inc.
# SPDX-License-Identifier: Apache-2.0
"""Codex crew launches: the launch record, the crew slots, the depth limit, the binding to a plan step, and the
member's required skills, all made at SubagentStart.
Codex CLI 0.167.0 fires no PreToolUse for `collaboration.spawn_agent`, so nothing can refuse or rewrite a Codex launch
before its agent starts. What it gives (captured on 2026-11-09): SubagentStart with `agent_id` and `agent_type`, its
`transcript_path` the new agent's own rollout, whose session_meta names the spawn (`source.subagent.thread_spawn`:
parent thread, depth, `agent_path` /root/<task_name>); the parent's rollout holds the `spawn_agent` call (`task_name`
in plain text, the brief encrypted) and a `SubAgentActivity` item that joins the call to the agent; and SubagentStart
output accepts `hookSpecificOutput.additionalContext`. The record shapes below are copied from that capture.
Every hook runs as Codex runs it: `dev hook <event> --agent codex` with the payload on stdin, in a sandbox Mac
(tests/test_acceptance_crew_sessions.py, tests/_sandbox.py).
Run: python3 -m unittest tests.test_codex_launch -v (and with /usr/bin/python3, for Python 3.9)
"""
import builtins
import json
import sys
import tempfile
import time
import unittest
from datetime import datetime, timezone
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
sys.path.insert(0, str(ROOT / "lib"))
from test_acceptance_crew_sessions import Crew # noqa: E402 (activates the hermetic net and the sandbox)
LEAD = "01a1c190-2665-7ca1-9a5d-046a95cee8bc" # the Codex tech lead's thread (UUIDv7, like Codex's own)
CLAUDE_LEAD = "7b2e0c4d-1a2b-4c3d-8e9f-0a1b2c3d4e5f"
TANK = "01a1c190-64c7-7ac1-81c6-000000000001"
TANK_2 = "01a1c190-64c7-7ac1-81c6-000000000005" # a second Backend engineer, spawned in the same turn
TRINITY = "01a1c190-64c7-7ac1-81c6-000000000002"
HELPER = "01a1c190-64c7-7ac1-81c6-000000000003"
REVIEWER = "01a1c190-64c7-7ac1-81c6-000000000004"
BRIEF = "gAAAAABq8gpXjj5jSrk7DNZsjERW3HLAzwcFxC3osbfOZq1eLFOwX9OY0PNTLmLRTZ-w5dfnusBVXc2tjIulRwmdOH9H81mHvCMeanY="
SUBAGENT_START_KEYS = {"continue", "hookSpecificOutput", "stopReason", "suppressOutput", "systemMessage"}
def _line(rec: dict) -> str:
return json.dumps(rec) + "\n"
def _now():
return datetime.now(timezone.utc).isoformat()
class CodexCrew(Crew):
"""A Codex tech lead's thread and its spawns, written as Codex 0.167.0 writes them."""
def rollout(self, thread: str) -> Path:
return self.home / ".codex" / "sessions" / "2026" / "11" / "09" / f"rollout-2026-11-09T10-00-55-{thread}.jsonl"
def parent_rollout(self, s, parent: str = "") -> Path:
"""The rollout of the thread that spawns: the tech lead's (the session's transcript) or a member's."""
path = self.rollout(parent) if parent else s.transcript
if not path.exists() or not path.read_text().strip():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(_line({"timestamp": _now(), "type": "session_meta", "payload": {
"session_id": s.sid, "id": parent or s.sid, "cli_version": "0.167.0", "originator": "codex_exec",
"source": "exec"}}))
return path
def spawn_call(self, s, member: str, task: str, call: str, parent: str = ""):
"""The spawn_agent call in the spawning thread's rollout: task_name in plain text, the brief encrypted."""
with self.parent_rollout(s, parent).open("a") as fh:
fh.write(_line({"timestamp": _now(), "type": "response_item", "payload": {
"type": "function_call", "status": "completed", "id": f"fc_{call}", "name": "spawn_agent",
"namespace": "collaboration", "call_id": call,
"arguments": json.dumps({"task_name": task, "agent_type": member, "message": BRIEF})}}))
def spawn_started(self, s, aid: str, task: str, call: str, parent: str = ""):
"""Codex's record that the call started the agent (`SubAgentActivity`, its id the call's)."""
with self.parent_rollout(s, parent).open("a") as fh:
where = self.agent_path(s, task, parent)
fh.write(_line({"timestamp": _now(), "type": "event_msg", "payload": {
"type": "item_completed", "thread_id": parent or s.sid, "turn_id": "01a1c178-28b7-7fa1-a67c-2bd8b7433d66",
"item": {"type": "SubAgentActivity", "model": "gpt-6-luna", "reasoning_effort": "low", "id": call,
"kind": "started", "agent_thread_id": aid, "agent_path": where}}}))
fh.write(_line({"timestamp": _now(), "type": "response_item", "payload": {
"type": "function_call_output", "call_id": call, "output": json.dumps({"task_name": f"/root/{task}"})}}))
def agent_rollout(self, s, aid: str, member: str, task: str, parent: str = "", depth: int = 1, source=None):
"""The new agent's own rollout, which opens with its session_meta (a spawn: source.subagent.thread_spawn)."""
path = self.rollout(aid)
path.parent.mkdir(parents=True, exist_ok=True)
where = self.agent_path(s, task, parent)
src = source if source is not None else {"subagent": {"thread_spawn": {
"parent_thread_id": parent or s.sid, "depth": depth, "agent_path": where, "agent_nickname": "Halley",
"agent_role": member}}}
path.write_text(_line({"timestamp": _now(), "type": "session_meta", "payload": {
"session_id": s.sid, "id": aid, "forked_from_id": parent or s.sid, "parent_thread_id": parent or s.sid,
"cwd": str(s.repo), "originator": "codex_exec", "cli_version": "0.167.0", "source": src,
"thread_source": "subagent", "agent_role": member, "agent_path": where}}))
return path
def agent_path(self, s, task, parent=""):
meta = json.loads(self.parent_rollout(s, parent).read_text().splitlines()[0])["payload"]
return (meta.get("agent_path") or "/root") + "/" + task
def subagent_start(self, s, aid: str, member: str) -> dict:
"""SubagentStart as Codex 0.167.0 sends it: the transcript is the new agent's own rollout."""
return s.hook("subagent-start", s.payload("SubagentStart", agent_id=aid, agent_type=member,
model="gpt-6-luna", transcript_path=str(self.rollout(aid))))
def spawn(self, s, aid: str, member: str, task: str, parent: str = "", depth: int = 1) -> dict:
"""The whole launch as Codex records it, then SubagentStart -> what the hook printed."""
call = f"call_{aid[-6:]}"
self.spawn_call(s, member, task, call, parent)
self.agent_rollout(s, aid, member, task, parent, depth)
self.spawn_started(s, aid, task, call, parent)
return self.subagent_start(s, aid, member)
def session_doc(self, s) -> dict:
return json.loads((self.state / "sessions" / f"{s.agent}-{s.sid}.json").read_text())
def launch_of(self, s, aid: str) -> dict:
return next((dict(v, key=k) for k, v in (self.session_doc(s).get("launches") or {}).items()
if v.get("agent_id") == aid), {})
def step(self, s, name: str) -> dict:
return next(st for st in s.run_doc()["plan"] if st["name"] == name)
def lead(self, plan="api=30m [backend]; ui=30m [frontend]", **progress):
"""A Codex tech lead with a run whose steps are assigned to Tank (api) and Trinity (ui)."""
self.config(**{"max_parallel": 2, "reserve": 0, **progress})
s = self.codex(LEAD, self.api)
s.ok("progress", "start", "Invoice export", "--plan", plan)
for step, name in (("api", "Tank"), ("ui", "Trinity")):
if f"{step}=" in plan:
s.ok("progress", "assign", step, "--to", name, "--scope", f"{step}/**")
return s
@staticmethod
def context(out: dict) -> str:
return ((out or {}).get("hookSpecificOutput") or {}).get("additionalContext") or ""
class CodexLaunchRecord(CodexCrew):
"""A Codex spawn gets the launch record and the lane a Claude Code Agent call gets."""
def test_a_codex_launch_binds_to_the_step_its_task_name_names(self):
s = self.lead()
self.spawn(s, TANK, "tank", "api")
lane = s.run_doc()["agents"][TANK]
self.assertEqual((lane["binding"], lane["label"], lane["parent"], lane["depth"], lane["persona"]),
("exact", "Tank: api", "main", 1, "Tank"))
self.assertEqual((self.step(s, "api")["owner"], self.step(s, "api")["state"]), (TANK, "running"))
self.assertEqual(self.step(s, "ui")["owner"], "main") # Trinity's step waits for Trinity's own launch
rec = self.launch_of(s, TANK)
self.assertEqual((rec["key"], rec["state"], rec["type"], rec["parent"]),
(f"call_{TANK[-6:]}", "started", "tank", "main"))
def test_a_trusted_child_tool_hook_recovers_a_missed_start(self):
s = self.lead()
self.spawn_call(s, "tank", "api", "call_missed")
self.agent_rollout(s, TANK, "tank", "api")
self.spawn_started(s, TANK, "api", "call_missed")
s.hook("pre-tool", s.payload("PreToolUse", agent_id=TANK, agent_type="tank", tool_use_id="call_read",
tool_name="Read", tool_input={"file_path": str(s.repo / "api/example.py")},
transcript_path=str(self.rollout(TANK))))
self.assertEqual(self.launch_of(s, TANK).get("key"), "call_missed")
self.assertEqual(self.step(s, "api")["owner"], TANK)
self.assertEqual(s.run_doc()["agents"][TANK]["scope"], ["api/**"])
def test_the_first_recovered_call_uses_its_own_scratch_context(self):
s = self.lead()
self.spawn_call(s, "tank", "api", "call_scratch")
self.agent_rollout(s, TANK, "tank", "api")
self.spawn_started(s, TANK, "api", "call_scratch")
scratch = self.home / "Development/.tmp/codex" / LEAD / "scratchpad/tank/probe.txt"
out = s.hook("pre-tool", s.payload("PreToolUse", agent_id=TANK, agent_type="tank",
tool_use_id="call_scratch_write", tool_name="Write",
tool_input={"file_path": str(scratch), "content": "diagnostic"},
transcript_path=str(self.rollout(TANK))))
self.assertEqual(self.step(s, "api")["owner"], TANK)
self.assertNotEqual(out.get("hookSpecificOutput", {}).get("permissionDecision"), "deny", out)
def test_native_parent_hook_uses_task_name_instead_of_the_brief(self):
self.parent_hook_launch()
def test_reciprocal_proof_repairs_an_old_pending_message_label(self):
self.parent_hook_launch(old_label=True)
def test_reciprocal_proof_never_overwrites_a_pending_launchs_role(self):
s = self.lead()
s.hook("pre-tool", s.payload("PreToolUse", tool_use_id="call_conflict", tool_name="spawn_agent",
tool_input={"agent_type": "neo", "task_name": "api", "message": "Implement the change."}))
self.spawn_call(s, "tank", "api", "call_conflict")
self.agent_rollout(s, TANK, "tank", "api")
self.spawn_started(s, TANK, "api", "call_conflict")
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.launch_of(s, TANK), {})
self.assertEqual(self.step(s, "api")["owner"], "main")
def parent_hook_launch(self, old_label=False):
s = self.lead()
task = {"agent_type": "tank", "task_name": "api", "message": "Implement the requested change."}
if old_label:
task["description"] = task["message"] # the derived label an earlier hook persisted
s.hook("pre-tool", s.payload("PreToolUse", tool_use_id="call_parent", tool_name="spawn_agent", tool_input=task))
self.spawn_call(s, "tank", "api", "call_parent")
self.agent_rollout(s, TANK, "tank", "api")
self.spawn_started(s, TANK, "api", "call_parent")
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.step(s, "api")["owner"], TANK)
self.assertEqual(s.run_doc()["agents"][TANK]["scope"], ["api/**"])
self.assertEqual(self.launch_of(s, TANK)["label"], "Tank: api")
def test_conflicting_reciprocal_task_never_takes_a_step(self):
s = self.lead()
self.spawn_call(s, "tank", "other", "call_conflict")
self.agent_rollout(s, TANK, "tank", "api")
self.spawn_started(s, TANK, "api", "call_conflict")
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.launch_of(s, TANK), {})
self.assertEqual(self.step(s, "api")["owner"], "main")
patch = "*** Begin Patch\n*** Add File: ui/unauthorized.py\n+changed\n*** End Patch"
edit = s.hook("pre-tool", s.payload("PreToolUse", agent_id=TANK, agent_type="tank", tool_use_id="bad_write",
tool_name="apply_patch", tool_input={"input": patch}, transcript_path=str(self.rollout(TANK))))
spec = edit.get("hookSpecificOutput") or {}
self.assertNotIn("permissionDecision", spec)
self.assertIn("its edits count for no crew step", spec.get("additionalContext") or "")
def test_a_prior_runs_registered_launch_cannot_bind_the_replacement_run(self):
s = self.lead()
self.spawn(s, TANK, "tank", "api")
s.ok("progress", "start", "Replacement", "--plan", "api=10m [backend]", "--replace",
"--why", "new work generation")
s.ok("progress", "assign", "api", "--to", "Tank", "--scope", "api/**")
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.step(s, "api")["owner"], "main")
self.assertNotIn(TANK, s.run_doc()["agents"])
def test_a_task_name_in_snake_case_binds_the_step_whose_words_it_names(self):
s = self.lead(plan="invoice csv=30m [backend]")
s.ok("progress", "assign", "invoice csv", "--to", "Tank")
self.spawn(s, TANK, "tank", "invoice_csv")
self.assertEqual(self.step(s, "invoice csv")["owner"], TANK)
def test_a_codex_launch_holds_a_crew_slot(self):
s = self.lead()
self.spawn(s, TANK, "tank", "api")
self.assertIn("1 of 2 slots in use", s.ok("crew", "next"))
def test_a_launch_waits_for_its_own_metadata_then_a_tool_hook_binds_it(self):
s = self.lead()
call = "call_parent_only"
self.spawn_call(s, "tank", "api", call)
self.spawn_started(s, TANK, "api", call)
self.rollout(TANK).parent.mkdir(parents=True, exist_ok=True)
self.rollout(TANK).write_text("") # Codex has not written the agent's session_meta yet
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.launch_of(s, TANK), {})
self.assertEqual(self.step(s, "api")["owner"], "main")
self.agent_rollout(s, TANK, "tank", "api")
s.hook("pre-tool", s.payload("PreToolUse", agent_id=TANK, agent_type="tank", tool_use_id="retry_read",
tool_name="Read", tool_input={"file_path": str(s.repo / "api/example.py")},
transcript_path=str(self.rollout(TANK))))
self.assertEqual(self.launch_of(s, TANK)["key"], call)
self.assertEqual(self.step(s, "api")["owner"], TANK)
def test_a_launch_never_takes_an_unbound_spawn_only_because_its_type_matches(self):
s = self.lead()
self.spawn(s, TRINITY, "trinity", "ui") # an earlier spawn, already bound to its agent
self.spawn_call(s, "tank", "api", "call_tank_newest") # no SubAgentActivity yet, no session_meta
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.launch_of(s, TANK), {})
self.assertEqual(self.step(s, "api")["owner"], "main")
self.assertEqual(self.launch_of(s, TRINITY)["key"], f"call_{TRINITY[-6:]}") # untouched
def test_two_starts_at_once_with_two_spawns_of_their_type_waiting_take_neither_and_the_lead_is_told(self):
s = self.lead(plan="api=30m [backend]; db=30m [backend]")
s.ok("progress", "assign", "db", "--to", "Tank", "--scope", "db/**")
self.spawn_call(s, "tank", "api", "call_tank_api") # Codex wrote both calls, no SubAgentActivity yet,
self.spawn_call(s, "tank", "db", "call_tank_db") # and neither agent's session_meta
rids = []
for aid in (TANK, TANK_2):
self.rollout(aid).parent.mkdir(parents=True, exist_ok=True)
self.rollout(aid).write_text("")
rids.append(s.hook("subagent-start", s.payload("SubagentStart", agent_id=aid, agent_type="tank",
model="gpt-6-luna", transcript_path=str(self.rollout(aid))),
wait=False))
for rid in rids:
s._hook_result(rid)
self.assertEqual([self.launch_of(s, aid).get("key") for aid in (TANK, TANK_2)],
[None, None]) # neither guessed: one would take the other's task
self.assertEqual([self.step(s, name)["owner"] for name in ("api", "db")], ["main", "main"])
told = [m["text"] for m in s.messages() if m.get("to") == "main" and "could not verify" in m["text"]]
self.assertEqual(sorted(aid for aid in (TANK, TANK_2) for t in told if aid in t), sorted([TANK, TANK_2]), told)
self.assertTrue(all("“api”" in t and "“db”" in t for t in told), told)
def test_a_matching_task_waits_for_the_exact_native_started_result(self):
s = self.lead(plan="api=30m [backend]; db=30m [backend]")
self.spawn_call(s, "tank", "api", "call_tank_api")
self.spawn_call(s, "tank", "db", "call_tank_db")
self.agent_rollout(s, TANK, "tank", "api") # its session_meta names its task; no SubAgentActivity yet
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.launch_of(s, TANK), {})
self.assertEqual(self.step(s, "api")["owner"], "main")
self.spawn_started(s, TANK, "api", "call_tank_api")
self.subagent_start(s, TANK, "tank")
self.assertEqual(self.launch_of(s, TANK)["key"], "call_tank_api")
def test_codex_own_helper_takes_no_launch_from_the_spawn_waiting_for_its_agent(self):
s = self.lead()
self.spawn_call(s, "", "list_files", "call_worker") # a spawn of Codex's default role, its agent not started
self.agent_rollout(s, REVIEWER, "default", "review", source={"subagent": "review"})
self.assertEqual(self.subagent_start(s, REVIEWER, "default"), {}) # Codex's own review helper starts first
self.agent_rollout(s, HELPER, "default", "list_files")
self.spawn_started(s, HELPER, "list_files", "call_worker")
self.subagent_start(s, HELPER, "default")
self.assertEqual(self.launch_of(s, REVIEWER), {})
self.assertNotIn(REVIEWER, s.run_doc().get("agents") or {})
self.assertEqual(self.launch_of(s, HELPER)["key"], "call_worker")
def test_a_second_start_of_the_same_agent_records_no_second_launch(self):
s = self.lead()
self.spawn(s, TANK, "tank", "api")
launch = self.launch_of(s, TANK)
owner = self.step(s, "api")["owner"]
again = self.subagent_start(s, TANK, "tank") # the tech lead sent it a follow-up: a new turn starts
scratch = self.home / "Development/.tmp/codex" / LEAD / "scratchpad/tank-api" # its lane's, for its step
self.assertTrue(scratch.is_dir())
self.assertIn(str(scratch), self.context(again))
self.assertEqual(self.launch_of(s, TANK)["key"], launch["key"])
self.assertEqual(self.step(s, "api")["owner"], owner)
self.assertEqual(sum(1 for v in self.session_doc(s)["launches"].values() if v.get("agent_id") == TANK), 1)
class CodexLaunchLimits(CodexCrew):
"""A Codex launch over the crew's limits cannot be refused before it starts: devkit records it, marks its lane,
gives its step back to the tech lead, and tells the member to stop and report."""
def test_a_launch_over_the_slot_limit_is_marked_and_the_member_told_to_stop(self):
s = self.lead(max_parallel=1)
self.spawn(s, TANK, "tank", "api")
told = self.context(self.spawn(s, TRINITY, "trinity", "ui"))
self.assertIn("1 of 1 crew slots are in use (Backend engineer (Tank))", told)
self.assertIn("stop now and report", told)
lane = s.run_doc()["agents"][TRINITY]
self.assertIn("1 of 1 crew slots are in use", lane["over_limit"]["why"])
self.assertEqual((self.step(s, "ui")["owner"], self.step(s, "ui")["state"]), ("main", "pending"))
notice = [m["text"] for m in s.messages() if m.get("to") == "main" and "over the crew's limit" in m["text"]]
self.assertEqual(len(notice), 1, s.messages())
self.assertIn("Frontend engineer (Trinity)", notice[0])
self.assertEqual([r["target"] for r in self.audit("crew.over-limit")], ["Trinity"])
def test_the_notice_of_a_launch_out_of_order_says_why_in_whole_sentences(self):
s = self.lead(max_parallel=1)
s.prompt("Carry on with the plan") # a later turn: the plan's steps are no longer this turn's request
self.spawn(s, TRINITY, "trinity", "ui") # “api” comes first in the plan, and one slot is all there is
notice = [m["text"] for m in s.messages() if m.get("to") == "main" and "over the crew's limit" in m["text"]]
self.assertEqual(len(notice), 1, s.messages())
self.assertIn("which devkit cannot refuse for a Codex launch before its agent starts: “api” comes first",
notice[0])
self.assertIn('--why "…". It was told to stop and report', notice[0])
def test_an_over_limit_members_edit_is_told_to_stop_and_report(self):
s = self.lead(max_parallel=1)
self.spawn(s, TANK, "tank", "api")
self.spawn(s, TRINITY, "trinity", "ui")
patch = "*** Begin Patch\n*** Add File: ui/view.ts\n+export {};\n*** End Patch\n"
g = s.hook("pre-tool", s.payload("PreToolUse", tool_name="apply_patch", tool_use_id="exec-patch-1",
tool_input={"command": patch}, agent_id=TRINITY, agent_type="trinity"))
spec = g.get("hookSpecificOutput") or {}
self.assertNotIn("permissionDecision", spec)
self.assertIn("over the crew's limit", spec.get("additionalContext", ""))
self.assertEqual(s.sh("git status --short", member=TRINITY, member_type="trinity")["denied"], "")
def test_a_member_within_the_limit_is_advised_only_outside_its_steps_scope(self):
s = self.lead(max_parallel=1)
self.spawn(s, TANK, "tank", "api")
verdicts = {}
for path in ("api/view.ts", "ui/view.ts"):
patch = f"*** Begin Patch\n*** Add File: {path}\n+export {{}};\n*** End Patch\n"
g = s.hook("pre-tool", s.payload("PreToolUse", tool_name="apply_patch", tool_use_id=f"exec-{path}",
tool_input={"command": patch}, agent_id=TANK, agent_type="tank"))
spec = g.get("hookSpecificOutput") or {}
verdicts[path] = (spec.get("permissionDecision"), spec.get("additionalContext") or "")
self.assertEqual(verdicts["api/view.ts"], (None, ""), verdicts)
self.assertEqual(verdicts["ui/view.ts"][0], None, verdicts)
self.assertIn("ui/view.ts is outside Backend engineer (Tank)'s scope (api/**)", verdicts["ui/view.ts"][1])
def test_a_nested_spawn_below_the_depth_limit_is_marked(self):
s = self.lead(max_depth=1)
self.spawn(s, TANK, "tank", "api")
told = self.context(self.spawn(s, HELPER, "sparks", "find_callers", parent=TANK, depth=2))
self.assertIn("2 levels below the tech lead; the limit is 1", told)
lane = s.run_doc()["agents"][HELPER]
self.assertEqual((lane["parent"], lane["depth"]), (TANK, 2))
self.assertIn("progress.max_depth", lane["over_limit"]["why"])
class CodexMemberContext(CodexCrew):
"""A Codex brief is encrypted, so the member's required skills, known pitfalls and report format reach it as
SubagentStart context: the text a Claude Code member gets appended to its brief."""
def setUp(self):
super().setUp()
for name in ("backend", "testing", "devsecops"): # installed for Codex on this Mac
f = self.home / ".agents" / "skills" / name / "SKILL.md"
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(f"---\nname: {name}\ndescription: {name}\n---\n# {name}\n")
def test_the_members_skills_and_report_format_arrive_as_subagent_start_context(self):
s = self.lead()
out = self.spawn(s, TANK, "tank", "api")
self.assertEqual(set(out) - SUBAGENT_START_KEYS, set(), out) # Codex refuses any other key
self.assertEqual(out["hookSpecificOutput"]["hookEventName"], "SubagentStart")
told = self.context(out)
self.assertIn("## devkit · required skills", told)
self.assertIn("by reading its SKILL.md", told)
for name in ("backend", "testing", "devsecops"):
self.assertIn(f"- `{name}` — ", told)
self.assertIn("## devkit · your report", told)
self.assertIn("**[Firefly> DevKit · Backend engineer (Tank)]**", told)
def test_a_reviewer_launched_for_one_review_gets_the_context_of_that_review(self):
# the Code reviewer's lane also takes an older waiting review (reviews share a lane), which comes first in the
# plan: the child's start context is the step its launch names, never the first one its lane holds
s = self.lead(plan="review-api=20m; review-ui=20m")
s.ok("progress", "assign", "review-api", "--to", "Seraph", "--activity", "security", "--why", "a second look")
s.ok("progress", "assign", "review-ui", "--to", "Seraph", "--activity", "review")
told = self.context(self.spawn(s, REVIEWER, "seraph", "review_ui"))
self.assertEqual(self.step(s, "review-ui")["owner"], REVIEWER)
self.assertIn("- `testing` — ", told)
self.assertNotIn("`devsecops`", told) # the security review's, which this launch did not name
def test_a_helper_no_crew_member_runs_gets_only_the_report_format(self):
s = self.lead()
out = self.spawn(s, HELPER, "worker", "list_files")
told = self.context(out)
self.assertNotIn("required skills", told)
self.assertIn("## devkit · your report", told)
class ClaudeLaunchUnchanged(CodexCrew):
"""A Claude Code launch keeps its PreToolUse path: the record, the brief's skills, nothing at SubagentStart. Only
a Codex start carries the member's context."""
def test_a_claude_launch_is_recorded_at_its_agent_call_and_only_a_codex_start_prints_context(self):
x = self.lead()
self.assertIn("## devkit · your report", self.context(self.spawn(x, TANK, "tank", "api")))
c = self.claude(CLAUDE_LEAD, self.api)
c.ok("progress", "start", "Invoice export", "--plan", "api=30m [backend]")
c.ok("progress", "assign", "api", "--to", "Tank", "--scope", "api/**")
call = dict(tool_name="Agent", tool_use_id="toolu_claude_1",
tool_input={"description": "Tank: api", "subagent_type": "devkit:tank", "prompt": "Build the API."})
g = c.hook("pre-tool", c.payload("PreToolUse", **call))
self.assertIn("## devkit · your report", g["hookSpecificOutput"]["updatedInput"]["prompt"])
out = c.hook("subagent-start", c.payload("SubagentStart", agent_id="claude-tank-1", agent_type="devkit:tank"))
self.assertEqual(out, {})
c.hook("post-tool", c.payload("PostToolUse", tool_response={"agentId": "claude-tank-1"}, **call))
self.assertEqual(self.launch_of(c, "claude-tank-1")["key"], "toolu_claude_1")
self.assertEqual(self.step(c, "api")["owner"], "claude-tank-1")
class NativeEvidenceSnapshotTests(unittest.TestCase):
def setUp(self):
from devkit import codexlaunch
self.reader = codexlaunch
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.path = Path(folder.name) / "parent.jsonl"
self.meta = self.line("session_meta", {"id": "parent", "session_id": "parent"})
self.call = self.line("response_item", {"type": "function_call", "name": "spawn_agent",
"namespace": "collaboration", "call_id": "exact", "arguments": json.dumps({
"task_name": "review", "agent_type": "seraph"})})
self.event = self.line("event_msg", {"type": "item_completed", "thread_id": "parent", "item": {
"type": "SubAgentActivity", "kind": "started", "id": "exact",
"agent_thread_id": "child", "agent_path": "/root/review"}})
self.path.write_bytes(self.meta + self.call + self.event)
@staticmethod
def line(kind, payload):
return (_line({"timestamp": "2026-11-14T18:00:00Z", "type": kind, "payload": payload})).encode()
def large_parent(self):
# Real-shaped bounded message records; the exact pair appears beyond the former 64 MiB cutoff.
row = self.line("response_item", {"type": "message", "role": "assistant", "content": [{
"type": "output_text", "text": "x" * 16000}]})
with self.path.open("wb") as stream:
stream.write(self.meta)
while stream.tell() < 68 * 1024 * 1024:
stream.write(row)
stream.write(self.call + self.event)
def test_recovery_consumes_a_large_parent_with_the_pair_beyond_the_old_cutoff(self):
self.large_parent()
for extra in (b"", b"\n"):
with self.subTest(extra_newline=bool(extra)):
with self.path.open("ab") as stream:
stream.write(extra)
began = time.monotonic()
calls, started = self.reader.spawn_calls(self.path)
elapsed = time.monotonic() - began
self.assertEqual([c["call_id"] for c in calls], ["exact"])
self.assertEqual(started["exact"][0]["agent"], "child")
self.assertLess(elapsed, 2.0)
def test_recovery_rejects_evidence_when_the_deadline_expires(self):
with mock.patch.object(time, "monotonic", side_effect=[0.0] + [3.0] * 20):
self.assertEqual(self.reader.spawn_calls(self.path), ([], {}))
def test_recovery_rejects_an_oversized_authority_record(self):
huge = self.line("response_item", {"type": "function_call", "name": "spawn_agent",
"namespace": "collaboration", "call_id": "huge", "arguments": json.dumps({
"task_name": "review", "agent_type": "seraph", "message": "x" * (8 * 1024 * 1024)})})
self.path.write_bytes(self.meta + self.call + self.event + huge)
self.assertEqual(self.reader.spawn_calls(self.path), ([], {}))
def test_exhausted_evidence_retention_never_authorizes_an_earlier_pair(self):
for count, task in ((4097, "review"), (40, "x" * (256 * 1024))):
with self.subTest(records=count):
with self.path.open("wb") as stream:
stream.write(self.meta + self.call + self.event)
for index in range(count):
stream.write(self.line("response_item", {"type": "function_call", "name": "spawn_agent",
"namespace": "collaboration", "call_id": "extra-" + str(index),
"arguments": json.dumps({"task_name": task, "agent_type": "seraph"})}))
self.assertEqual(self.reader.spawn_calls(self.path), ([], {}))
def changing_open(self, change):
"""An open() whose stream runs `change` once, right after its first read, like a writer racing the reader."""
class ChangingFile:
def __init__(self, *args, **kwargs):
self.stream = builtins.open(*args, **kwargs)
self.changed = False
def __enter__(self):
return self
def __exit__(self, *args):
self.stream.close()
def fileno(self):
return self.stream.fileno()
def read(self, size):
data = self.stream.read(size)
if not self.changed:
self.changed = True
change()
return data
return mock.patch.object(self.reader, "open", ChangingFile, create=True)
def test_recovery_rejects_a_parent_shrunk_rewritten_or_replaced_during_reading(self):
original = self.meta + self.call + self.event
path = self.path
def replace():
path.unlink()
path.write_bytes(original)
changes = {"truncate": lambda: path.write_bytes(self.meta),
"rewrite": lambda: path.write_bytes(original.replace(b"review", b"rework")),
"replace": replace}
for mutation, change in changes.items():
with self.subTest(mutation=mutation):
path.write_bytes(original)
with self.changing_open(change):
self.assertEqual(self.reader.spawn_calls(path), ([], {}))
def test_recovery_keeps_its_snapshot_while_codex_appends_to_the_parent(self):
original = self.meta + self.call + self.event
later = self.line("event_msg", {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 9}}})
def append():
with self.path.open("ab") as stream:
stream.write(later * 3)
self.path.write_bytes(original)
with self.changing_open(append):
calls, started = self.reader.spawn_calls(self.path)
self.assertEqual([c["call_id"] for c in calls], ["exact"])
self.assertEqual(started["exact"][0]["agent"], "child")
def test_recovery_reads_a_growing_parent_of_varied_record_sizes(self):
import random
rng = random.Random(20261115)
def record():
# The shapes and spread of sizes a Codex rollout holds: token counts, reasoning, tool calls and outputs.
kind = rng.choice(("tokens", "reasoning", "call", "output", "message"))
if kind == "tokens":
return self.line("event_msg", {"type": "token_count", "info": {"total_token_usage": {
"input_tokens": rng.randint(1, 10 ** 6), "output_tokens": rng.randint(1, 10 ** 5)}}})
if kind == "reasoning":
return self.line("response_item", {"type": "reasoning", "summary": [],
"encrypted_content": "g" * rng.randint(200, 40_000)})
if kind == "call":
return self.line("response_item", {"type": "function_call", "name": "exec_command",
"call_id": "call_%d" % rng.randint(0, 10 ** 9),
"arguments": json.dumps({"cmd": "dev test run tests/test_x.py " + "y" * rng.randint(0, 600)})})
if kind == "output":
return self.line("response_item", {"type": "function_call_output", "call_id": "call_out",
"output": "line\n" * rng.randint(1, 30_000)})
return self.line("response_item", {"type": "message", "role": "assistant", "content": [{
"type": "output_text", "text": "z" * rng.randint(1, 300_000)}]})
with self.path.open("wb") as stream:
stream.write(self.meta)
while stream.tell() < 6 * 1024 * 1024:
stream.write(record())
stream.write(self.call)
for _ in range(rng.randint(5, 40)):
stream.write(record())
stream.write(self.event)
for _ in range(rng.randint(5, 40)):
stream.write(record())
def grow():
with self.path.open("ab") as stream:
for _ in range(50):
stream.write(record())
with self.changing_open(grow):
calls, started = self.reader.spawn_calls(self.path)
self.assertEqual([c["call_id"] for c in calls], ["exact"])
self.assertEqual([s["agent"] for s in started["exact"]], ["child"])
def test_recovery_checks_duplicates_near_the_end_and_never_accepts_partial_evidence(self):
self.large_parent()
for suffix in (self.call, self.event, b'{"type":"response_item","payload":', b'{"spawn_agent":oops}\n'):
with self.subTest(suffix=suffix[:30]):
valid_calls, valid_started = self.reader.spawn_calls(self.path)
self.assertEqual([c["call_id"] for c in valid_calls], ["exact"])
self.assertEqual(len(valid_started["exact"]), 1)
size = self.path.stat().st_size
with self.path.open("ab") as stream:
stream.write(suffix)
calls, started = self.reader.spawn_calls(self.path)
seen = {"spawn": {"task": "review", "type": "seraph", "parent": "main"},
"path": "/root/review", "calls": calls, "started": started}
self.assertIsNone(self.reader.find({"agent_id": "child"}, seen, {}))
with self.path.open("r+b") as stream:
stream.truncate(size)
if __name__ == "__main__":
unittest.main()