Repository navigation
Expand file tree
/
Copy pathtest_commands.py
More file actions
5935 lines (5664 loc) · 241 KB
/
Copy pathtest_commands.py
File metadata and controls
5935 lines (5664 loc) · 241 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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import hashlib
import fcntl
import json
import os
from pathlib import Path
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import unittest
from tests.support import REPO, run
sys.path.insert(0, str(REPO / "lib"))
from sessionkit_inventory import lifecycle # noqa: E402
SP = REPO / "bin" / "sp"
REAPER = REPO / "bin" / "shpool_reaper"
COMMON = REPO / "bin" / "session_kit_common"
BASHRC = REPO / "bashrc" / "shpool.bashrc"
RESET = b"\x1b[?1049l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?1004l\x1b[0m"
def write_executable(path: Path, text: str) -> None:
path.write_text(text, encoding="utf-8")
path.chmod(0o755)
def session_row(
shpool_id: str,
*,
row: int = 1,
started: int = 1_700_000_000_001,
provider: str = "codex",
uuid: str = "00000000-0000-4000-8000-000000000001",
status: str = "Disconnected",
) -> dict:
return {
"row": row,
"shpool_id": shpool_id,
"shpool_id_raw": shpool_id,
"display_shpool_id": shpool_id,
"mutation_allowed": True,
"mutation_rejection_reason": None,
"shpool_shell": {
"pid": 1001,
"process_start_ticks": 10010,
},
"started_at_unix_ms": started,
"shpool_status": status,
"availability": "ready" if status == "Disconnected" else "attached",
"provider": provider,
"identity": {
"uuid": uuid,
"pid": 2001,
"process_start_ticks": 20010,
"provenance": "fixture",
"confidence": "exact",
},
"title": f"{provider.title()} fixture",
"native_title": f"{provider.title()} fixture",
"cwd": "/srv/project",
"process_age_seconds": 60,
"agent_status": "working",
"needs_you": False,
"subagents": [],
"recovery": {
"available": True,
"provider": provider,
"uuid": uuid,
"cwd": "/srv/project",
"argv": ["codex", "resume", uuid],
"command": f"codex resume {uuid}",
},
"diagnostics": [],
}
def inventory_document(*rows: dict) -> dict:
return {
"schema_version": 1,
"generated_at": "2026-07-28T00:00:00Z",
"source": "live",
"stale": False,
"warnings": [],
"daemon_generation": {
"boot_id": "fixture",
"pid": 10,
"process_start_ticks": 100,
},
"sessions": list(rows),
"outside_agents": [],
}
def unknown_session_row(shpool_id: str = "main9", *, row: int = 9) -> dict:
result = session_row(shpool_id, row=row, provider="unknown", uuid="")
result["identity"] = {
"uuid": None,
"pid": 2909,
"process_start_ticks": 29090,
"provenance": "process-tree",
"confidence": "partial",
}
result["title"] = "Unknown exact shell"
result["native_title"] = None
result["recovery"] = {"available": False}
return result
def write_picker_proof(path: Path, row: dict, *, daemon_pid: int = 10) -> Path:
identity = row["identity"]
shell = row["shpool_shell"]
proof = {
"schema_version": 1,
"proof_type": "session-kit-picker-session-v1",
"shpool_id": row["shpool_id_raw"],
"started_at_unix_ms": row["started_at_unix_ms"],
"provider": row["provider"],
"uuid": identity.get("uuid") or "",
"provider_pid": identity["pid"],
"provider_process_start_ticks": identity["process_start_ticks"],
"shell_pid": shell["pid"],
"shell_process_start_ticks": shell["process_start_ticks"],
"daemon_pid": daemon_pid,
"daemon_process_start_ticks": 100,
}
path.write_text(
json.dumps(
proof, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
+ "\n",
encoding="utf-8",
)
path.chmod(0o600)
return path
def run_queued_creator_after_marker_switch(
fixture: "CommandFixture",
command: list[object],
env: dict[str, str],
) -> tuple[subprocess.Popen[str], str, str]:
real_flock = shutil.which("flock")
if real_flock is None:
raise AssertionError("flock is required for the concurrency test")
fake_bin = fixture.base / "marker-switch-bin"
fake_bin.mkdir()
entered = fixture.base / "marker-switch-entered"
write_executable(
fake_bin / "flock",
"""#!/usr/bin/env bash
if [[ ${1:-} == -x && ${*: -1} == 9 ]]; then
: > "$TEST_FLOCK_ENTERED"
fi
exec "$TEST_REAL_FLOCK" "$@"
""",
)
process_env = {
**os.environ,
**env,
"PATH": f"{fake_bin}:{os.environ['PATH']}",
"TEST_FLOCK_ENTERED": str(entered),
"TEST_REAL_FLOCK": real_flock,
}
lock_path = fixture.state / "create.lock"
marker = fixture.state / "integration-ready-v1"
with lock_path.open("a+") as held:
fcntl.flock(held, fcntl.LOCK_EX)
proc = subprocess.Popen(
[str(part) for part in command],
env=process_env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
deadline = time.monotonic() + 5
while not entered.exists() and proc.poll() is None:
if time.monotonic() >= deadline:
proc.kill()
raise AssertionError("creator did not reach the held creation lock")
time.sleep(0.01)
if proc.poll() is not None:
stdout, stderr = proc.communicate()
raise AssertionError(
f"creator exited before queuing on creation lock: {(stdout, stderr)}"
)
marker.write_text(
f"session-kit-integration-v1 {'b' * 40}\n",
encoding="utf-8",
)
marker.chmod(0o600)
fcntl.flock(held, fcntl.LOCK_UN)
stdout, stderr = proc.communicate(timeout=5)
return proc, stdout, stderr
class CommandFixture:
def __init__(self) -> None:
self.temp = tempfile.TemporaryDirectory(prefix=".commands-", dir=REPO)
self.base = Path(self.temp.name)
self.home = self.base / "home"
self.home.mkdir()
self.state = self.base / "state"
# The real core refuses a state directory that is not owner-private,
# and the recovery list is served by it, so the fixture has to hold
# the same contract a real install does.
self.state.mkdir(mode=0o700)
self.boot_id = self.base / "boot-id"
self.boot_id.write_text("fixture-boot\n", encoding="utf-8")
self.release_id = "a" * 40
integration_marker = self.state / "integration-ready-v1"
integration_marker.write_text(
f"session-kit-integration-v1 {self.release_id}\n", encoding="utf-8"
)
integration_marker.chmod(0o600)
self.start = self.base / "shpool-start"
self.journals = self.base / "journals"
self.archives = self.base / "archives"
self.recovery = self.base / "recovery"
self.project = self.base / "project"
self.project.mkdir()
self.shpool_state = self.base / "shpool.json"
self.shpool_state.write_text('{"sessions":[]}\n', encoding="utf-8")
self.shpool_log = self.base / "shpool.log"
self.inventory = self.base / "inventory.json"
self.inventory.write_text(
json.dumps(inventory_document()), encoding="utf-8"
)
self.snapshot_count = self.base / "snapshot-count"
self.projects = self.base / "projects.tsv"
self.projects.write_text(
f"fixture\tshell\t{self.project}\n", encoding="utf-8"
)
self.config = self.base / "session-kit.json"
self.config.write_text(
'{"schema_version":1,"aliases":{}}\n', encoding="utf-8"
)
self.config.chmod(0o600)
self.fake_shpool = self.base / "fake-shpool"
self.fake_core = self.base / "fake-inventory"
home_bin = self.home / ".local" / "bin"
home_bin.mkdir(parents=True, mode=0o700)
write_executable(
home_bin / "shpool",
"#!/usr/bin/env bash\nexec \"$SESSION_KIT_SHPOOL_CMD\" \"$@\"\n",
)
self.close_intent_log = self.base / "close-intent.log"
self.worktree_log = self.base / "worktree.log"
self.origin_log = self.base / "origin.log"
self.origin_instance_log = self.base / "origin-instance.log"
self.closed_log = self.base / "closed-sessions.log"
self.name_push_log = self.base / "name-push.log"
write_executable(
self.fake_shpool,
"""#!/usr/bin/env python3
import fcntl, json, os, pathlib, shutil, sys, tempfile, time
state=pathlib.Path(os.environ["FAKE_SHPOOL_STATE"])
log=pathlib.Path(os.environ["FAKE_SHPOOL_LOG"])
lock=state.with_suffix(".lock")
lock.parent.mkdir(parents=True, exist_ok=True)
with lock.open("a+") as held:
fcntl.flock(held, fcntl.LOCK_EX)
try: data=json.loads(state.read_text())
except (OSError, ValueError): data={"sessions":[]}
args=sys.argv[1:]
if args == ["list", "--json"]:
print(json.dumps(data))
raise SystemExit(0)
if args and args[0] == "attach":
expected_lock=os.environ.get("FAKE_EXPECT_CREATE_LOCK")
if expected_lock:
create_lock=pathlib.Path(os.environ["SESSION_KIT_STATE_DIR"])/"create.lock"
with create_lock.open("a+") as create_held:
try:
fcntl.flock(create_held,fcntl.LOCK_EX|fcntl.LOCK_NB)
observed_lock="unlocked"
except BlockingIOError:
observed_lock="locked"
if observed_lock != expected_lock:
raise SystemExit(88)
if os.environ.get("FAKE_ATTACH_FAIL") == "1":
raise SystemExit(5)
name=args[-1]
collision_marker=os.environ.get("FAKE_CREATE_COLLISION_ONCE")
if collision_marker and not pathlib.Path(collision_marker).exists():
pathlib.Path(collision_marker).write_text(name)
if not any(row.get("name") == name for row in data["sessions"]):
data["sessions"].append({
"name":name,
"status":"Disconnected",
"started_at_unix_ms":int(time.time()*1000)-1000,
})
fd,tmp=tempfile.mkstemp(prefix=".state.",dir=state.parent)
with os.fdopen(fd,"w") as out: json.dump(data,out)
os.replace(tmp,state)
with log.open("a") as out: out.write("collision "+name+"\\n")
raise SystemExit(17)
target=next(
(row for row in data["sessions"] if row.get("name") == name),
None,
)
force="--force" in args
if os.environ.get("FAKE_ATTACH_BECOMES_BUSY") == "1" and not force:
if target is not None:
target["status"]="Attached"
action="busy"
elif (
os.environ.get("FAKE_BUSY_IF_ATTACHED") == "1"
and target is not None
and target.get("status") == "Attached"
and not force
):
action="busy"
elif os.environ.get("FAKE_BUSY_IF_ATTACHED") == "1" and force:
if target is not None:
target["status"]="Attached"
action="force-attach"
else:
action="attach"
if os.environ.get("FAKE_DROP_BEFORE_ATTACH") == "1":
data["sessions"]=[row for row in data["sessions"] if row.get("name") != name]
immediate_command=(
args[args.index("--cmd")+1] if "--cmd" in args else ""
)
exits_immediately=immediate_command in {"/bin/false", "/bin/true"}
if immediate_command == "/bin/true":
data["sessions"]=[
row for row in data["sessions"] if row.get("name") != name
]
action="attach-exit"
if not exits_immediately and not any(row.get("name") == name for row in data["sessions"]):
data["sessions"].append({"name":name,"status":"Disconnected","started_at_unix_ms":int(time.time()*1000)})
elif len(args) == 2 and args[0] == "kill":
required_signal=os.environ.get("FAKE_REQUIRE_EXACT_SIGNAL")
if required_signal and not pathlib.Path(required_signal).is_file():
raise SystemExit(89)
expected_lock=os.environ.get(
"FAKE_EXPECT_KILL_LOCK",
os.environ.get("FAKE_EXPECT_CREATE_LOCK"),
)
if expected_lock:
create_lock=pathlib.Path(os.environ["SESSION_KIT_STATE_DIR"])/"create.lock"
with create_lock.open("a+") as create_held:
try:
fcntl.flock(create_held,fcntl.LOCK_EX|fcntl.LOCK_NB)
observed_lock="unlocked"
except BlockingIOError:
observed_lock="locked"
if observed_lock != expected_lock:
raise SystemExit(88)
name=args[1]
before=len(data["sessions"])
data["sessions"]=[row for row in data["sessions"] if row.get("name") != name]
if len(data["sessions"]) == before:
raise SystemExit(4)
proc_pid=os.environ.get("FAKE_KILL_PROC_PID","")
proc_root=os.environ.get("SESSION_KIT_PROC_ROOT","")
if proc_pid.isdigit() and proc_root:
shutil.rmtree(pathlib.Path(proc_root)/proc_pid, ignore_errors=True)
inventory_path=os.environ.get("FAKE_DROP_INVENTORY_ROW")
if inventory_path:
inventory_file=pathlib.Path(inventory_path)
inventory=json.loads(inventory_file.read_text())
inventory["sessions"]=[
row for row in inventory.get("sessions",[])
if row.get("shpool_id_raw") != name and row.get("shpool_id") != name
]
inventory_file.write_text(json.dumps(inventory))
action="kill"
else:
raise SystemExit(2)
fd,tmp=tempfile.mkstemp(prefix=".state.",dir=state.parent)
with os.fdopen(fd,"w") as out: json.dump(data,out)
os.replace(tmp,state)
with log.open("a") as out: out.write(action+" "+name+"\\n")
""",
)
write_executable(
self.fake_core,
"""#!/usr/bin/env python3
import json, os, pathlib, sys, tempfile, unicodedata
args=sys.argv[1:]
if args[:2] in (["account", "launch-profile"], ["account", "resume-profile"]) and len(args) == 4:
# This branch came from the profile-enrolment fixture while the account
# switch branch added the ordered call log below. A merged fixture must do
# both: returning here before logging made the real launch-profile step
# disappear from five ordering tests even though production ran it.
log=os.environ.get("STUB_ACCOUNT_LOG")
if log:
with open(log, "a") as handle:
handle.write(json.dumps(args)+"\\n")
if args[1] == "launch-profile" and os.environ.get("STUB_ACCOUNT_LAUNCH_FAILS") == "1":
sys.stderr.write("account "+args[3]+" is not selectable: blocked\\n")
raise SystemExit(1)
# Enrollment is stubbed by naming a directory. With none named the
# account is simply not enrolled, which is what the real core reports.
profile=os.environ.get("STUB_ACCOUNT_PROFILE")
if not profile:
sys.stderr.write("no such enrolled account\\n")
raise SystemExit(1)
marker=os.environ.get("STUB_ACCOUNT_LAUNCH_MARKER")
if args[1] == "launch-profile" and marker:
pathlib.Path(marker).write_text(json.dumps({"provider":args[2],"alias":args[3]}))
print(json.dumps({"provider": args[2], "alias": args[3], "profile_dir": profile}))
raise SystemExit(0)
if args[:2] == ["account", "bind"]:
print(json.dumps({"bound": True}))
raise SystemExit(0)
if args[:2] == ["platform", "terminate-exact-process"] and not os.environ.get(
"SESSION_KIT_PROC_ROOT"
):
if os.environ.get("STUB_EXACT_ALREADY_GONE") == "1":
raise SystemExit(1)
log=os.environ.get("SESSION_KIT_TEST_EXACT_SIGNAL_LOG")
if log:
with open(log,"a",encoding="utf-8") as handle:
handle.write(f"{args[2]}\\t{args[3]}\\t15\\n")
drop_name=os.environ.get("FAKE_DROP_EXACT_SESSION")
inventory_path=os.environ.get("FAKE_DROP_INVENTORY_ROW")
if drop_name and inventory_path:
inventory_file=pathlib.Path(inventory_path)
inventory=json.loads(inventory_file.read_text())
inventory["sessions"]=[
row for row in inventory.get("sessions",[])
if row.get("shpool_id_raw") != drop_name and row.get("shpool_id") != drop_name
]
inventory_file.write_text(json.dumps(inventory))
print("terminated")
raise SystemExit(0)
if args[:2] == ["platform", "exact-shell-gone"] and not os.environ.get(
"SESSION_KIT_PROC_ROOT"
):
print("gone")
raise SystemExit(0)
if args[:2] == ["platform", "shpool-holder-generation"] and not os.environ.get(
"SESSION_KIT_PROC_ROOT"
):
inventory=json.loads(pathlib.Path(os.environ["STUB_INVENTORY"]).read_text())
daemon=inventory["daemon_generation"]
print(f"{daemon['pid']}\t{daemon['process_start_ticks']}")
raise SystemExit(0)
if args[:2] in (
["platform", "shpool-holder-generation"],
["platform", "exact-shell-gone"],
["platform", "terminate-exact-process"],
):
os.execvp("python3", ["python3", os.environ["STUB_REAL_CORE"], *args])
if args[:2] == ["platform", "process-table"] and len(args) == 2:
table=os.environ.get("STUB_PROCESS_TABLE")
if not table:
raise SystemExit(2)
print(table)
raise SystemExit(0)
if args[:2] == ["worktree", "lookup"]:
# Answered by the real core against the fixture's own registry: a restore
# that has to find the repository a released copy came from is exactly the
# path a stub would hide.
os.execv(sys.executable, [sys.executable, os.environ["STUB_REAL_CORE"], *args])
if args[:1] in (["model-availability"], ["model-served"]):
# The one gate that decides whether a launch may happen at all. The stub
# hands it to the real core rather than answering for it: a fixture that
# says yes to every model would test nothing.
os.execv(sys.executable, [sys.executable, os.environ["STUB_REAL_CORE"], *args])
if args[:1] == ["worktree"]:
# Delegated work gets its own copy of the code, so the create path asks
# for one. The stub answers with a directory under the fixture's state so
# the launch is exercised end to end, and logs every call it is given.
log=os.environ.get("STUB_WORKTREE_LOG")
if log:
with open(log,"a",encoding="utf-8") as handle:
handle.write(json.dumps(args)+"\\n")
if len(args) > 1 and args[1] == "copy-check":
# Three answers, and the launcher must tell them apart. Exit 0 with a
# reason: do not copy this one. Exit 1: copying it is fine, the
# ordinary answer. Anything else: the check itself broke, which is not
# a pass -- STUB_COPY_CHECK_BROKEN makes it break.
if os.environ.get("STUB_COPY_CHECK_BROKEN"):
print("Traceback (most recent call last): simulated", file=sys.stderr)
raise SystemExit(70)
shared=os.environ.get("STUB_SHARED_REPO","")
if shared and shared in args:
print(f"{shared} carries a .session-kit-shared marker")
raise SystemExit(0)
raise SystemExit(1)
if len(args) > 1 and args[1] == "materialize":
options=dict(zip(args[2::2], args[3::2]))
branch=options.get("--branch","")
root=pathlib.Path(os.environ["SESSION_KIT_STATE_DIR"])/"worktrees"/"trees"
path=root/branch.replace("/","-")
path.mkdir(parents=True, exist_ok=True)
print(json.dumps({
"path":str(path),
"branch":branch,
"repo":options.get("--repo",""),
"auto":"--auto" in args,
"created":True,
},sort_keys=True))
raise SystemExit(0)
print("{}")
raise SystemExit(0)
if args[:2] == ["platform", "codex-refresh-target"] and len(args) == 6:
print("\t".join((
os.environ.get("STUB_REFRESH_PID", args[4]),
os.environ.get("STUB_REFRESH_START", args[5]),
)))
raise SystemExit(0)
if args[:2] == ["platform", "process-is"] and len(args) == 5:
if os.environ.get("STUB_PROCESS_IS_TRUE") == "1":
raise SystemExit(0)
pid=int(args[2]); generation=int(args[3]); executable=args[4]
try:
stat_text=pathlib.Path(f"/proc/{pid}/stat").read_text()
current=int(stat_text.rsplit(")",1)[1].split()[19])
argv=pathlib.Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\\0")
actual=pathlib.Path(argv[0].decode("utf-8","replace")).name
except (OSError,ValueError,IndexError):
raise SystemExit(1)
raise SystemExit(0 if current == generation and actual == executable else 1)
if args[:1] == ["account"] and len(args) >= 2:
# Every account verb the automatic handoff calls, answered from fixtures
# and logged in call order. No real profile, feed or login is touched.
log=os.environ.get("STUB_ACCOUNT_LOG")
if log:
with open(log, "a") as handle:
handle.write(json.dumps(args)+"\\n")
verb=args[1]
if verb == "auto-plan":
print(os.environ.get("STUB_ACCOUNT_PLAN") or json.dumps({"action":"hold","reason":"no fixture plan","source_alias":"","target_alias":""}))
raise SystemExit(0)
if verb == "auto-begin":
if os.environ.get("STUB_ACCOUNT_BEGIN_FAILS") == "1":
sys.stderr.write("this conversation has already had its 1 automatic move\\n")
raise SystemExit(1)
print(os.environ.get("STUB_ACCOUNT_HOP_TOKEN", "b"*32))
raise SystemExit(0)
if verb in ("auto-commit","auto-release"):
raise SystemExit(0)
if verb == "auto-target-ok":
if os.environ.get("STUB_ACCOUNT_TARGET_GONE") == "1":
print(json.dumps({"alias":args[3],"eligible":False,"reason":"it was switched off"}))
raise SystemExit(1)
print(json.dumps({"alias":args[3],"eligible":True,"reason":""}))
raise SystemExit(0)
if verb == "switch-prepare":
print(json.dumps({"txid":os.environ.get("STUB_ACCOUNT_TXID","0"*32)}))
raise SystemExit(0)
if verb == "switch-commit" and os.environ.get("STUB_ACCOUNT_COMMIT_FAILS") == "1":
raise SystemExit(1)
if verb in ("sync-ui","switch-commit","switch-rollback"):
print(json.dumps({"ok":True}))
raise SystemExit(0)
raise SystemExit(2)
if args[:1] == ["codex-bounce-title"] and len(args) == 2:
title=os.environ.get("STUB_CODEX_BOUNCE_TITLE", "")
if title:
print(title)
raise SystemExit(0)
raise SystemExit(1)
if args[:1] == ["claude-bounce-title"] and len(args) == 2:
if os.environ.get("STUB_CLAUDE_BOUNCE_CLEAR") == "1":
raise SystemExit(3)
title=os.environ.get("STUB_CLAUDE_BOUNCE_TITLE", "")
if title:
print(title)
raise SystemExit(0)
raise SystemExit(1)
if args[:2] == ["automatic-title", "self-name"] and len(args) == 3:
print(json.dumps({
"schema_version":1,
"automatic_name_state":"ready",
"title":args[2],
},sort_keys=True))
raise SystemExit(0)
if args[:2] == ["alias", "set"] or args[:2] == ["alias", "delete"]:
action=args[1]
tail=args[2:]
if action == "set" and len(tail) == 4 and tail[2] == "--":
provider,uuid,title=tail[0],tail[1],tail[3]
elif action == "delete" and len(tail) == 2:
provider,uuid=tail
title=None
else:
raise SystemExit(2)
if provider not in {"claude","codex"}:
raise SystemExit(2)
config=pathlib.Path(os.environ["SESSION_KIT_CONFIG"])
data=json.loads(config.read_text())
aliases=dict(data.get("aliases",{}))
key=f"{provider}:{uuid.lower()}"
if action == "set":
safe="".join(
" " if unicodedata.category(character).startswith("C") else character
for character in title
)
safe=" ".join(safe.split())[:100]
if not safe:
raise SystemExit(2)
aliases[key]=safe
else:
aliases.pop(key,None)
data["aliases"]=aliases
descriptor,temporary=tempfile.mkstemp(prefix=".config.",dir=config.parent)
with os.fdopen(descriptor,"w",encoding="utf-8") as handle:
json.dump(data,handle,sort_keys=True)
handle.write("\\n")
handle.flush()
os.fsync(handle.fileno())
os.chmod(temporary,0o600)
os.replace(temporary,config)
alias_log=os.environ.get("STUB_ALIAS_LOG")
if alias_log:
with pathlib.Path(alias_log).open("a",encoding="utf-8") as handle:
handle.write(json.dumps(args)+"\\n")
print(json.dumps({"schema_version":1,"aliases":aliases},sort_keys=True))
raise SystemExit(0)
if args[:2] == ["color", "conversation-pick"] and len(args) == 4:
color_log=os.environ.get("STUB_COLOR_LOG")
if color_log:
with pathlib.Path(color_log).open("a",encoding="utf-8") as handle:
handle.write(json.dumps(args)+"\\n")
print(json.dumps({"schema_version":1,"color":"orange"},sort_keys=True))
raise SystemExit(0)
if args[:2] in (["color", "set"], ["color", "delete"]):
action=args[1]
tail=args[2:]
if action == "set" and len(tail) == 3:
provider,uuid,color=tail
elif action == "delete" and len(tail) == 2:
provider,uuid=tail
color=None
else:
raise SystemExit(2)
if provider not in {"claude","codex"}:
raise SystemExit(2)
config=pathlib.Path(os.environ["SESSION_KIT_CONFIG"])
data=json.loads(config.read_text())
stored=dict(data.get("colors",{}))
key=f"{provider}:{uuid.lower()}"
if action == "set":
stored[key]=color
else:
stored.pop(key,None)
data["colors"]=stored
fd,tmp=tempfile.mkstemp(prefix=".config.",dir=config.parent)
with os.fdopen(fd,"w") as out: json.dump(data,out)
os.replace(tmp,config)
print(json.dumps({"schema_version":1,"colors":stored},sort_keys=True))
raise SystemExit(0)
if args[:2] == ["color", "propagate"] and len(args) == 4:
color_log=os.environ.get("STUB_COLOR_LOG")
if color_log:
with pathlib.Path(color_log).open("a",encoding="utf-8") as handle:
handle.write(json.dumps(args)+"\\n")
if os.environ.get("STUB_COLOR_PROPAGATE_FAIL") == "1":
raise SystemExit(1)
print(json.dumps({"schema_version":1,"provider_color_pushes":[],"provider_color_warnings":[]},sort_keys=True))
raise SystemExit(0)
if args[:2] == ["alias", "push"] and len(args) == 4:
name_log=os.environ.get("STUB_NAME_PUSH_LOG")
if name_log:
with pathlib.Path(name_log).open("a",encoding="utf-8") as handle:
handle.write(json.dumps(args)+"\\n")
if os.environ.get("STUB_ALIAS_PUSH_FAIL") == "1":
raise SystemExit(1)
if os.environ.get("STUB_ALIAS_PUSH_PARTIAL") == "1":
print(json.dumps({"schema_version":1,"title":"fixture name","provider_title_pushes":["codex-session-index"],"provider_title_warnings":["Codex thread row not found; thread title not set"]},sort_keys=True))
raise SystemExit(3)
print(json.dumps({"schema_version":1,"title":"fixture name","provider_title_pushes":["claude-nameintent"],"provider_title_warnings":[]},sort_keys=True))
raise SystemExit(0)
if args and args[0] == "snapshot":
dynamic_provider=os.environ.get("STUB_DYNAMIC_PROVIDER")
dynamic_status=os.environ.get("STUB_DYNAMIC_AGENT_STATUS", "working")
dynamic_count=0
if dynamic_provider and any(os.environ.get(name) for name in (
"STUB_DYNAMIC_AGENT_STATUS_AFTER_FIRST",
"STUB_DYNAMIC_ACCOUNT_ALIAS_AFTER_FIRST",
"STUB_DYNAMIC_ACCOUNT_MISMATCH_AFTER_FIRST",
)):
counter=pathlib.Path(os.environ["STUB_SNAPSHOT_COUNT"])
try: dynamic_count=int(counter.read_text())
except (OSError,ValueError): dynamic_count=0
dynamic_count += 1
counter.write_text(str(dynamic_count))
if dynamic_count > 1 and os.environ.get("STUB_DYNAMIC_AGENT_STATUS_AFTER_FIRST"):
dynamic_status=os.environ["STUB_DYNAMIC_AGENT_STATUS_AFTER_FIRST"]
if dynamic_provider and os.environ.get("STUB_DYNAMIC_AFTER_SESSIONS"):
current_state=json.loads(pathlib.Path(os.environ["FAKE_SHPOOL_STATE"]).read_text())
if len(current_state.get("sessions",[])) <= int(os.environ["STUB_DYNAMIC_AFTER_SESSIONS"]):
dynamic_provider=None
if dynamic_provider:
state=json.loads(pathlib.Path(os.environ["FAKE_SHPOOL_STATE"]).read_text())
rows=[]
for index,item in enumerate(state.get("sessions",[]),1):
name=item["name"]
skip_name_file=os.environ.get("STUB_DYNAMIC_SKIP_NAME_FILE")
if (skip_name_file and pathlib.Path(skip_name_file).is_file()
and pathlib.Path(skip_name_file).read_text() == name):
continue
gone_pid=os.environ.get("FAKE_KILL_PROC_PID")
exact_log=os.environ.get("SESSION_KIT_TEST_EXACT_SIGNAL_LOG")
gone_name=os.environ.get("STUB_DYNAMIC_SKIP_NAME_AFTER_SIGNAL")
proc_root=os.environ.get("SESSION_KIT_PROC_ROOT")
exact_gone=(
bool(exact_log and pathlib.Path(exact_log).is_file())
or bool(gone_pid and proc_root and not (pathlib.Path(proc_root)/gone_pid).exists())
)
if ((gone_pid == str(1000 + index) or gone_name == name) and exact_gone):
continue
if os.environ.get("STUB_CONSUME_ARMED_LAUNCH") == "1":
start=pathlib.Path(os.environ["SESSION_KIT_START_DIR"])/name
expected=start.with_name(start.name+".expected")
if start.is_file() and expected.is_file():
start.unlink()
expected.unlink()
uuid_overrides=json.loads(os.environ.get("STUB_DYNAMIC_UUID_OVERRIDES","{}"))
rows.append({
"row":index,
"shpool_id":name,
"shpool_id_raw":name,
"display_shpool_id":name,
"mutation_allowed":True,
"mutation_rejection_reason":None,
"shpool_shell":{"pid":1000+index,"process_start_ticks":10000+index},
"started_at_unix_ms":int(os.environ.get("STUB_DYNAMIC_STARTED",item["started_at_unix_ms"])),
"shpool_status":item["status"],
"availability":"ready",
"provider":dynamic_provider,
"identity":{"uuid":uuid_overrides.get(name,os.environ.get("STUB_DYNAMIC_UUID")),"pid":int(os.environ.get("STUB_DYNAMIC_PROVIDER_PID") or 2000+index),"process_start_ticks":int(os.environ.get("STUB_DYNAMIC_PROVIDER_START") or 20000+index),"confidence":"exact"},
"title":"dynamic proof",
"native_title":"dynamic proof",
"cwd":os.environ.get("STUB_DYNAMIC_CWD","/srv/project"),
"process_age_seconds":1,
"agent_status":dynamic_status,
"model":os.environ.get("STUB_DYNAMIC_MODEL",""),
# A real snapshot carries the stamp beside what the row IS, and
# only where a stamp exists. STUB_DYNAMIC_ORIGIN asks for a
# STAMPED session, so the stub writes both.
# STUB_DYNAMIC_ORIGIN_INFERRED asks for the other kind: a row
# that reads as a machine's with no stamp behind it, which is
# what an unstamped App Server looks like the moment its window
# is gone.
"origin":os.environ.get(
"STUB_DYNAMIC_ORIGIN",
os.environ.get("STUB_DYNAMIC_ORIGIN_INFERRED", "human"),
),
**({"origin_recorded":os.environ["STUB_DYNAMIC_ORIGIN"]}
if os.environ.get("STUB_DYNAMIC_ORIGIN") else {}),
"model_handoff_capable":os.environ.get("STUB_DYNAMIC_MODEL_HANDOFF","1") == "1",
"needs_you":False,
"subagents":[],
# An account switch is not instant: the request file is written,
# the managed shell consumes it, and only then does the row
# report the new account. AFTER_REQUEST stands in for that shell
# so the wait-for-the-new-alias step can actually be exercised.
"account_alias":(
os.environ["STUB_DYNAMIC_ACCOUNT_ALIAS_AFTER_REQUEST"]
if os.environ.get("STUB_DYNAMIC_ACCOUNT_ALIAS_AFTER_REQUEST")
and (pathlib.Path(os.environ.get("SESSION_KIT_STATE_DIR","/nonexistent"))/"account-switch-requests"/name).exists()
else os.environ["STUB_DYNAMIC_ACCOUNT_ALIAS_AFTER_FIRST"]
if dynamic_count > 1 and os.environ.get("STUB_DYNAMIC_ACCOUNT_ALIAS_AFTER_FIRST")
else os.environ.get("STUB_DYNAMIC_ACCOUNT_ALIAS","")
),
"account_binding_mismatch":(
dynamic_count > 1
and os.environ.get("STUB_DYNAMIC_ACCOUNT_MISMATCH_AFTER_FIRST") == "1"
),
"account_switch_capable":os.environ.get("STUB_DYNAMIC_ACCOUNT_CAPABLE","0") == "1",
"recovery":{"available":False},
"diagnostics":[],
})
if os.environ.get("STUB_DYNAMIC_INCLUDE_UNKNOWN") == "1":
rows.append({
"row":len(rows)+1,
"shpool_id":"main9",
"shpool_id_raw":"main9",
"display_shpool_id":"main9",
"mutation_allowed":True,
"mutation_rejection_reason":None,
"shpool_shell":{"pid":9009,"process_start_ticks":99009},
"started_at_unix_ms":1700000009000,
"shpool_status":"Disconnected",
"availability":"ready",
"provider":"unknown",
"identity":{"uuid":None,"pid":None,"process_start_ticks":None,"confidence":"none"},
"title":"unknown exact shell",
"native_title":None,
"cwd":"/srv/unknown",
"process_age_seconds":1,
"agent_status":"unknown",
"needs_you":False,
"subagents":[],
"recovery":{"available":False},
"diagnostics":[],
})
outside_agents=json.loads(os.environ.get("STUB_DYNAMIC_OUTSIDE_AGENTS","[]"))
document={"schema_version":1,"generated_at":"2026-07-28T00:00:00Z","source":"live","stale":False,"warnings":[],"daemon_generation":{"pid":10,"process_start_ticks":100},"sessions":rows,"outside_agents":outside_agents}
if "--strict-live" in args and any(row.get("provider") == "unknown" for row in rows):
raise SystemExit(3)
if "--guard-live" in args and os.environ.get("STUB_GUARD_FAIL") == "1":
raise SystemExit(3)
print(json.dumps(document))
raise SystemExit(0)
counter=pathlib.Path(os.environ["STUB_SNAPSHOT_COUNT"])
try: count=int(counter.read_text())
except (OSError, ValueError): count=0
count += 1
counter.write_text(str(count))
source=os.environ.get("STUB_SECOND_INVENTORY") if count > 1 else None
source=source or os.environ["STUB_INVENTORY"]
document=json.loads(pathlib.Path(source).read_text())
if "--strict-live" in args and any(row.get("provider") == "unknown" for row in document.get("sessions",[])):
raise SystemExit(3)
if "--guard-live" in args and os.environ.get("STUB_GUARD_FAIL") == "1":
raise SystemExit(3)
print(json.dumps(document))
elif args[:1] == ["validate-worker-model"] and len(args) == 3:
import re as _re
provider, model = args[1], args[2]
if _re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", model):
print(model)
else:
raise SystemExit(1)
elif args[:2] == ["closed-sessions", "record"]:
with open(os.environ["STUB_CLOSED_LOG"], "a") as handle:
handle.write(json.dumps(args)+"\\n")
print(json.dumps({"recorded": True}))
elif args[:2] == ["closed-sessions", "forget"]:
with open(os.environ["STUB_CLOSED_LOG"], "a") as handle:
handle.write(json.dumps(args)+"\\n")
print(json.dumps({"forgotten": 1}))
elif args[:2] == ["recovery-pending", "list"] or args[:1] == ["recovery-selectors"]:
# Delegated to the real core on purpose. This list is the one projection
# both recovery surfaces read, and what a screen printed beside each row is
# how a restore knows the word it was handed still means that row, so a
# stub reimplementation here would test the stub. The fixture already owns
# every store either of them reads.
import subprocess
# sys.executable is empty under this stub's shebang, so name the
# interpreter rather than borrowing one that is not there.
real=os.environ["STUB_REAL_INVENTORY_CORE"]
raise SystemExit(subprocess.run(["python3", real, *args]).returncode)
elif args[:2] == ["closed-sessions", "list"]:
payload=os.environ.get("STUB_CLOSED_LIST")
print(payload if payload else json.dumps({"closed": []}))
elif args[:2] == ["closed-sessions", "stream"]:
payload=os.environ.get("STUB_CLOSED_LIST")
document=json.loads(payload) if payload else {"closed": []}
for row in document.get("closed") or []:
print(json.dumps(row))
elif args[:2] == ["origin", "record"] and len(args) == 4:
with open(os.environ["STUB_ORIGIN_LOG"], "a") as handle:
handle.write(json.dumps(args[2:])+"\\n")
with open(os.environ["STUB_ORIGIN_INSTANCE_LOG"], "a") as handle:
handle.write(json.dumps({
"shell_pid":os.environ.get("SESSION_KIT_ORIGIN_SHELL_PID"),
"shell_start_ticks":os.environ.get("SESSION_KIT_ORIGIN_SHELL_START_TICKS"),
"started_at_unix_ms":os.environ.get("SESSION_KIT_ORIGIN_STARTED_AT_UNIX_MS"),
},sort_keys=True)+"\\n")
print(json.dumps({"recorded": True}))
elif args and args[0] == "close-intent":
with open(os.environ["STUB_CLOSE_INTENT_LOG"], "a") as handle:
handle.write(json.dumps(args)+"\\n")
if os.environ.get("STUB_CLOSE_INTENT_FAIL") == "1":
print(json.dumps({"recorded": False, "reason": "injected ledger failure"}))
raise SystemExit(1)
print(json.dumps({"recorded": True}))
elif args and args[0] == "render":
print("fixture renderer")
elif args and args[0] == "waiting-count":
print("0")
else:
raise SystemExit(2)
""",
)
def close(self) -> None:
self.temp.cleanup()
def env(self) -> dict[str, str]:
return {
"HOME": str(self.home),
"XDG_STATE_HOME": str(self.home / ".local" / "state"),
"XDG_DATA_HOME": str(self.home / ".local" / "share"),
"SESSION_KIT_STATE_DIR": str(self.state),
"SESSION_KIT_JOURNAL_DIR": str(self.journals),
"SESSION_KIT_ARCHIVE_DIR": str(self.archives),
"SESSION_KIT_JOURNAL_RECOVERY_DIR": str(self.recovery),
"SESSION_KIT_START_DIR": str(self.start),
"SESSION_KIT_PROJECTS_FILE": str(self.projects),
"SESSION_KIT_CONFIG": str(self.config),
"SESSION_KIT_SHPOOL_CMD": str(self.fake_shpool),
"SESSION_KIT_INVENTORY_CORE": str(self.fake_core),
"STUB_REAL_INVENTORY_CORE": str(REPO / "lib" / "session_inventory.py"),
"SESSION_KIT_NONINTERACTIVE": "1",
"SESSION_KIT_NO_COLOR": "1",
"SESSION_KIT_RELEASE_ID": self.release_id,
"SESSION_KIT_BOOT_ID_FILE": str(self.boot_id),
"FAKE_SHPOOL_STATE": str(self.shpool_state),
"FAKE_SHPOOL_LOG": str(self.shpool_log),
"STUB_INVENTORY": str(self.inventory),
"STUB_SNAPSHOT_COUNT": str(self.snapshot_count),
"STUB_CLOSE_INTENT_LOG": str(self.close_intent_log),
"STUB_WORKTREE_LOG": str(self.worktree_log),
"STUB_REAL_CORE": str(REPO / "lib" / "session_inventory.py"),
# A delegated session now cuts a worktree without being asked, and
# this sandbox sits inside a checkout. Pin the root so nothing a
# test starts can ever materialize a worktree into a real
# repository's metadata, whichever core answers the call.
"SESSION_KIT_WORKTREE_ROOT": str(self.base / "worktrees"),
"STUB_ORIGIN_LOG": str(self.origin_log),
"STUB_ORIGIN_INSTANCE_LOG": str(self.origin_instance_log),
"STUB_CLOSED_LOG": str(self.closed_log),
"STUB_NAME_PUSH_LOG": str(self.name_push_log),
"PYTHONDONTWRITEBYTECODE": "1",
}
class CommandTests(unittest.TestCase):
def setUp(self) -> None:
self.fixture = CommandFixture()
def tearDown(self) -> None:
self.fixture.close()
def test_concurrent_create_allocates_unique_unbounded_ids_and_list_is_safe(self) -> None:
env = {**os.environ, **self.fixture.env()}
env.update(
{
"STUB_DYNAMIC_PROVIDER": "shell",
"STUB_DYNAMIC_CWD": str(self.fixture.project),
}
)
processes = [
subprocess.Popen(
[SP, "new", "shell", "fixture"],
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
for _ in range(10)
]
for proc in processes:
stdout, stderr = proc.communicate(timeout=20)
self.assertEqual(0, proc.returncode, (stdout, stderr))
state = json.loads(self.fixture.shpool_state.read_text())
names = [row["name"] for row in state["sessions"]]
self.assertEqual(10, len(names))
self.assertEqual(10, len(set(names)))
listed = run([SP, "list"], env=self.fixture.env())
self.assertEqual("fixture renderer\n", listed.stdout)
def test_every_selector_verb_refuses_a_wrong_number_the_same_way(self) -> None:
"""One message, one status, whichever verb typed it.
Nine verbs used to answer "no unique session matches that selection"
with status 1 while `sp detail` answered a different sentence with
status 2, and `sp repair` echoed the number back.
"""
env = self.fixture.env()
for argv in (
["go", "999"],
["close", "999"],
["takeover", "999"],
["history", "999"],
["name", "999", "x"],
["name", "reset", "999"],
["color", "999", "red"],
["color", "reset", "999"],
["verify-start", "999"],
["teardown", "999"],
["repair", "999"],
):
with self.subTest(verb=argv[0]):
refused = run([SP, *argv], env=env, check=False)
self.assertEqual(2, refused.returncode)
self.assertEqual(
"session-kit: no session matches that selector\n",
refused.stderr,
)
self.assertNotIn("999", refused.stderr)
def test_a_wrong_argument_count_says_what_was_wrong_first(self) -> None:
"""`usage:` alone named the shape of the command, never the mistake."""
env = self.fixture.env()
refused = run([SP, "close"], env=env, check=False)
self.assertEqual(2, refused.returncode)
self.assertTrue(
refused.stderr.startswith("session-kit: sp close takes one session"),
refused.stderr,
)
self.assertIn("usage: sp <command>", refused.stderr)
def test_an_unknown_account_command_never_answers_in_pythons_voice(self) -> None: