Repository navigation
Expand file tree
/
Copy pathtest_install.py
More file actions
3751 lines (3366 loc) · 162 KB
/
Copy pathtest_install.py
File metadata and controls
3751 lines (3366 loc) · 162 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 base64
import grp
import hashlib
import json
import os
import pwd
from pathlib import Path
import plistlib
import re
import signal
import shutil
import sqlite3
import importlib.util
import stat
import subprocess
import sys
import tempfile
import threading
import time
import unittest
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, os.fspath(REPO / "lib"))
from tests.support import THEME_COLORS # noqa: E402
from tests.sweep_sandboxes import PREFIXES as SANDBOX_PREFIXES # noqa: E402
from sessionkit_inventory.common import CollectionError # noqa: E402
from sessionkit_inventory.state_io import StateLock # noqa: E402
# What a copy of this repository's source must leave behind. The build caches
# are obvious; the sandbox prefixes are not. The fixtures build their sandboxes
# inside the checkout on purpose, to keep AF_UNIX paths short, and they come and
# go in seconds -- so copying the tree while a sibling test removed one made
# copytree list an entry and then fail to open it, a real error about a file
# that was never part of the source. Serial runs never saw it; one sharded run
# found it immediately.
SOURCE_COPY_IGNORES = (
".git",
".mypy_cache",
".ruff_cache",
"__pycache__",
"*.pyc",
*(f"{prefix}*" for prefix in SANDBOX_PREFIXES),
)
RELEASE_A = "1" * 40
RELEASE_B = "2" * 40
RELEASE_C = "3" * 40
# Launchers are compared byte for byte to prove which release a rollback took
# them from. A fixture release built out of this checkout would otherwise carry
# launchers identical to the release under test, and the comparison would hold
# no matter which one the code picked.
LEGACY_LAUNCHER_STAMP = "# Session Kit legacy generation fixture.\n"
# A unit name no release carries, so a fixture release that adds it reproduces
# the one state that breaks a rollback: a running kit whose unit list names a
# file the release it is activating never had.
FIXTURE_UNIT = "session-kit-fixture-sweep.service"
def host_group_is_private() -> bool:
"""Report whether this host gives the test account a private group.
A group-writable provider directory is installable only where the group
belongs to one account, which is how a private-group distribution creates
it. Hosts with a shared primary group cannot stage that fixture.
"""
try:
account = pwd.getpwuid(os.geteuid())
group = grp.getgrgid(os.getegid())
accounts = pwd.getpwall()
except (KeyError, OSError): # pragma: no cover - directory service failure
return False
return bool(
os.getegid() == account.pw_gid
and group.gr_name == account.pw_name
and not group.gr_mem
and accounts
and all(
other.pw_gid != account.pw_gid or other.pw_name == account.pw_name
for other in accounts
)
)
class InstallerTests(unittest.TestCase):
def setUp(self) -> None:
# GitHub's macOS workspace carries an inherited ACL that denies
# renaming sealed 0555 directories. Real installs live under HOME, so
# keep Darwin fixtures in the normal per-user temporary directory.
# Managed worktrees may expose the checkout's parent read-only. /tmp is
# writable in that environment and also avoids copying a source tree
# into one of its own descendants in tests that stage a release.
isolated_test_parent = os.environ.get("SESSION_KIT_TEST_TMPDIR")
temp_parent = (
Path(isolated_test_parent)
if isolated_test_parent
else None if sys.platform == "darwin" else Path("/tmp")
)
self.temp = Path(
tempfile.mkdtemp(
prefix="session-kit-install-test.",
dir=temp_parent,
)
).resolve()
self.home = self.temp / "home"
self.home.mkdir()
self.fake_bin = self.temp / "bin"
self.fake_bin.mkdir()
for command in ("shpool", "claude", "codex", "launchctl", "plutil", "sw_vers"):
executable = self.fake_bin / command
body = "#!/usr/bin/env bash\nexit 0\n"
if command == "shpool":
body = (
"#!/usr/bin/env bash\n"
"if [[ ${1:-} == version ]]; then echo 'shpool 0.11.0'; exit 0; fi\n"
"echo 'test shpool: refusing non-version command' >&2\n"
"exit 97\n"
)
elif command == "claude":
body = "#!/usr/bin/env bash\necho '2.1.221 (Claude Code)'\n"
elif command == "codex":
body = "#!/usr/bin/env bash\necho 'codex-cli 0.145.0'\n"
executable.write_text(
body, encoding="utf-8"
)
executable.chmod(0o755)
self.env = os.environ.copy()
self.env.update(
{
"HOME": str(self.home),
# A managed session exports the real profile here, and the
# transcript checks honour it; the fixture must own its
# ambient profile or foreground runs read the real estate.
"CLAUDE_CONFIG_DIR": str(self.home / ".claude"),
"PATH": f"{self.fake_bin}:{self.env['PATH']}",
"SESSION_KIT_RELEASE_ID": RELEASE_A,
"XDG_CONFIG_HOME": str(self.home / ".config"),
"XDG_DATA_HOME": str(self.home / ".local/share"),
"XDG_STATE_HOME": str(self.home / ".local/state"),
"SESSION_KIT_STATE_DIR": str(
self.home / ".local/state/session-kit"
),
"SESSION_KIT_CONFIG": str(
self.home / ".config/session-kit/inventory.json"
),
"SESSION_KIT_SYSTEMD_ROOT": str(self.temp / "systemd"),
"SESSION_KIT_TESTING": "1",
}
)
real_data_home = (Path.home() / ".local/share").resolve()
isolated_paths = (
Path(self.env["HOME"]),
Path(self.env["XDG_CONFIG_HOME"]),
Path(self.env["XDG_DATA_HOME"]),
Path(self.env["XDG_STATE_HOME"]),
)
for path in isolated_paths:
self.assertFalse(
path.resolve().is_relative_to(real_data_home),
f"installer test path escapes into operator data: {path}",
)
def tearDown(self) -> None:
# The tree is walked to restore search permission on directories the
# installer deliberately locked, then removed. A test's own git
# subprocess can still be pruning objects underneath that walk, and
# rglob raises when a directory disappears mid-scan — a cleanup that
# failed the run over work it was about to delete anyway. Both the
# walk and each chmod tolerate a vanished entry.
try:
paths = list(self.temp.rglob("*"))
except OSError:
paths = []
for path in paths:
try:
if path.is_dir() and not path.is_symlink():
path.chmod(path.stat().st_mode | 0o700)
except OSError:
continue
shutil.rmtree(self.temp, ignore_errors=True)
def run_installer(
self, *args: str, check: bool = True
) -> subprocess.CompletedProcess[str]:
result = subprocess.run(
[str(REPO / "install.sh"), *args],
cwd=REPO,
env=self.env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if check and result.returncode:
self.fail(
f"command failed ({result.returncode}): {args}\n"
f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}"
)
return result
def run_installer_on_a_terminal(
self, keystrokes: str, *args: str
) -> subprocess.CompletedProcess[str]:
"""Run the installer with a terminal on stdin, the way a person runs
it. It asks nothing there: it takes the marked defaults and reports
them."""
import pty
parent, child = pty.openpty()
try:
process = subprocess.Popen(
[str(REPO / "install.sh"), *args],
cwd=REPO,
env=self.env,
stdin=child,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
os.close(child)
child = -1
os.write(parent, keystrokes.encode())
output, _ = process.communicate(timeout=180)
finally:
if child >= 0:
os.close(child)
os.close(parent)
return subprocess.CompletedProcess(
args, process.returncode, output, ""
)
def test_installer_asks_nothing_and_reports_the_defaults_it_took(self) -> None:
"""The installer never asks. It takes the marked defaults on a
terminal, installs, and states what it chose with the way back."""
completed = self.run_installer_on_a_terminal("")
self.assertEqual(0, completed.returncode, completed.stdout)
for banned in ("[Y/n]", "[y/N]", "Answer y or n", "cancelled"):
self.assertNotIn(banned, completed.stdout)
self.assertIn(
"Login integration is on. Turn it off with: session-kit disable-login",
completed.stdout,
)
self.assertIn(
"History recording is off. Turn it on with: "
"session-kit update --journal on",
completed.stdout,
)
self.assertTrue(
(self.home / ".local/lib/session-kit/current").is_symlink(),
completed.stdout,
)
self.assertIn(
"session-kit managed integration",
(self.home / ".bashrc").read_text(encoding="utf-8"),
)
self.assertTrue((self.home / ".no_shpool_journal").is_file())
def test_fresh_install_seeds_collection_floor(self) -> None:
self.run_installer("--non-interactive")
floor = self.home / ".local/state/session-kit/collection-sequence-floor.json"
self.assertEqual(
{"schema_version": 1, "last_collection_start": 1},
json.loads(floor.read_text(encoding="utf-8")),
)
self.assertEqual(0o600, stat.S_IMODE(floor.stat().st_mode))
def test_install_never_overwrites_existing_collection_floor(self) -> None:
state = self.home / ".local/state/session-kit"
state.mkdir(parents=True, mode=0o700)
floor = state / "collection-sequence-floor.json"
original = b'{ "schema_version" : 1, "last_collection_start" : 41 }\n'
floor.write_bytes(original)
floor.chmod(0o600)
self.run_installer("--non-interactive")
self.assertEqual(original, floor.read_bytes())
def test_install_refuses_underivable_collection_floor_with_exact_remedy(
self,
) -> None:
state = self.home / ".local/state/session-kit"
state.mkdir(parents=True, mode=0o700)
inventory = state / "inventory.json"
inventory.write_text('{"sessions":[]}\n', encoding="utf-8")
inventory.chmod(0o600)
command = (
f"env SESSION_KIT_STATE_DIR={state} python3 "
f"{REPO / 'tools/reset-collection-order.py'}"
)
expected = (
"session-kit-release: collection allocation floor cannot be derived "
"from existing state; restart the machine and, before starting a "
"picker, sp, shpool_status, or any Session Kit user service, run "
f"exactly:\n {command}\n"
)
refused = self.run_installer("--non-interactive", check=False)
self.assertNotEqual(0, refused.returncode)
self.assertEqual(expected, refused.stderr)
self.assertFalse((state / "collection-sequence-floor.json").exists())
self.assertFalse((self.home / ".local/lib/session-kit/current").exists())
def test_interrupted_install_journals_provider_config_preimages_and_commits_backups(
self,
) -> None:
"""The operator's provider config is preimaged before anything runs.
The installer now owns exact Claude registrations, so an interrupted
install must first restore what it found before the retry applies the
release again. This proves the journal captured the real preimage --
content for the file that was there, `absent` for the one that was not
-- and that the committed backup carries the same record.
"""
claude = self.home / ".claude"
claude.mkdir()
settings = claude / "settings.json"
original = b'{"existing":"claude-setting"}\n'
settings.write_bytes(original)
settings.chmod(0o600)
codex_hooks = self.home / ".codex" / "hooks.json"
self.env["SESSION_KIT_TEST_FAILPOINT"] = "themes"
self.env["SESSION_KIT_TEST_FAILPOINT_MODE"] = "kill"
failed = self.run_installer("--non-interactive", check=False)
self.assertEqual(-signal.SIGKILL, failed.returncode)
journal_path = self.home / ".local/state/session-kit/lifecycle-transaction.json"
journal = json.loads(journal_path.read_text(encoding="utf-8"))
entries = {item["path"]: item for item in journal["entries"]}
self.assertEqual("file", entries[str(settings)]["kind"])
self.assertEqual(original, base64.b64decode(entries[str(settings)]["content"]))
self.assertEqual("absent", entries[str(codex_hooks)]["kind"])
self.assertFalse(codex_hooks.exists())
self.env.pop("SESSION_KIT_TEST_FAILPOINT")
self.env.pop("SESSION_KIT_TEST_FAILPOINT_MODE")
recovered = self.run_installer("--non-interactive")
self.assertIn(
"Recovered interrupted Session Kit install transaction", recovered.stdout
)
self.assertFalse(journal_path.exists())
restored = json.loads(settings.read_text(encoding="utf-8"))
self.assertEqual("claude-setting", restored["existing"])
self.assertEqual(
"~/.claude/statusline.sh", restored["statusLine"]["command"]
)
self.assertFalse(codex_hooks.exists())
backups = sorted(
(self.home / ".local/state/session-kit/backups").glob("lifecycle-*.json")
)
committed = json.loads(backups[-1].read_text(encoding="utf-8"))
committed_entries = {item["path"]: item for item in committed["entries"]}
self.assertEqual(
original, base64.b64decode(committed_entries[str(settings)]["content"])
)
self.assertEqual("absent", committed_entries[str(codex_hooks)]["kind"])
def installed(
self,
*args: str,
check: bool = True,
env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
command = self.home / ".local/bin/session-kit"
result = subprocess.run(
[str(command), *args],
env=env if env is not None else self.env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if check and result.returncode:
self.fail(
f"installed command failed ({result.returncode}): {args}\n"
f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}"
)
return result
def clean_source_fixture(self) -> Path:
source = self.temp / "clean-source"
shutil.copytree(
REPO,
source,
ignore=shutil.ignore_patterns(*SOURCE_COPY_IGNORES),
)
subprocess.run(["git", "init", "-q", source], check=True)
subprocess.run(["git", "-C", source, "add", "."], check=True)
subprocess.run(
[
"git",
"-C",
source,
"-c",
"user.name=Session Kit Tests",
"-c",
"user.email=session-kit-tests@invalid.example",
"commit",
"-q",
"-m",
"fixture",
],
check=True,
)
return source
def changed_claude_source_fixture(self) -> Path:
source = self.clean_source_fixture()
for relative in (
"config/claude/nameintent_title.sh",
"config/claude/statusline.sh",
):
path = source / relative
path.write_text(
path.read_text(encoding="utf-8") + "\n# distinct fixture payload\n",
encoding="utf-8",
)
subprocess.run(["git", "-C", source, "add", "."], check=True)
subprocess.run(
[
"git", "-C", source,
"-c", "user.name=Session Kit Tests",
"-c", "user.email=session-kit-tests@invalid.example",
"commit", "-q", "--amend", "--no-edit",
],
check=True,
)
return source
def stage_legacy_release(self, source_release: str, target_release: str) -> None:
root = self.home / ".local/lib/session-kit/releases"
target = root / target_release
shutil.copytree(root / source_release, target)
self.unseal_release(target)
metadata = target / "RELEASE.json"
metadata.chmod(0o644)
value = json.loads(metadata.read_text(encoding="utf-8"))
value["commit"] = target_release
metadata.write_text(json.dumps(value) + "\n", encoding="utf-8")
shutil.rmtree(target / "config/claude")
self.seal_release(target)
def make_release_fence_unaware(self, release_id: str) -> Path:
"""Give one retained release the real legacy lock contract.
Its status command takes only inventory.lock and emits the retained
inventory. The target's StateLock source deliberately contains no
generation-2 path, so rollback must decide from code evidence rather
than from the synthetic release id.
"""
release = self.home / ".local/lib/session-kit/releases" / release_id
self.unseal_release(release)
state_io = release / "lib/sessionkit_inventory/state_io.py"
state_io.chmod(0o644)
state_io.write_text(
'"""Pre-generation-2 StateLock fixture."""\n\n'
'_PUBLISHING_LOCK_NAME = "inventory.lock"\n\n'
"class StateLock:\n"
" pass\n",
encoding="utf-8",
)
status_command = release / "bin/shpool_status"
status_command.chmod(0o755)
status_command.write_text(
"""#!/usr/bin/env python3
import fcntl
import os
from pathlib import Path
import stat
import sys
if sys.argv[1:] != ["--json"]:
raise SystemExit(2)
root = Path(os.environ["SESSION_KIT_STATE_DIR"])
lock = root / "inventory.lock"
flags = os.O_RDWR | os.O_CREAT
if hasattr(os, "O_CLOEXEC"):
flags |= os.O_CLOEXEC
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
descriptor = os.open(lock, flags, 0o600)
try:
opened = os.fstat(descriptor)
before = lock.lstat()
if (
not stat.S_ISREG(opened.st_mode)
or stat.S_IMODE(opened.st_mode) != 0o600
or opened.st_uid != os.geteuid()
or (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino)
):
raise SystemExit(1)
fcntl.flock(descriptor, fcntl.LOCK_EX)
after = lock.lstat()
if (opened.st_dev, opened.st_ino) != (after.st_dev, after.st_ino):
raise SystemExit(1)
sys.stdout.write((root / "inventory.json").read_text(encoding="utf-8"))
finally:
os.close(descriptor)
""",
encoding="utf-8",
)
self.seal_release(release)
return release
def install_mixed_modern_legacy_history(self) -> None:
self.run_installer("--non-interactive")
self.stage_legacy_release(RELEASE_A, RELEASE_C)
changed = self.changed_claude_source_fixture()
self.env["SESSION_KIT_RELEASE_ID"] = RELEASE_B
self.installed("update", "--source", str(changed))
self.installed("rollback", "--to", RELEASE_A)
self.installed("rollback", "--to", RELEASE_C)
def helper_launcher_names(self) -> list[str]:
"""The helper commands the installer keeps, read from the source."""
source = (REPO / "bin/session-kit").read_text(encoding="utf-8")
match = re.search(r"^helpers=\((?P<names>[^)]*)\)$", source, re.MULTILINE)
assert match is not None, "bin/session-kit no longer declares helpers"
return match.group("names").split()
def unseal_release(self, release: Path) -> None:
for directory in sorted(
(path for path in release.rglob("*") if path.is_dir()), reverse=True
):
directory.chmod(0o755)
release.chmod(0o755)
def seal_release(self, release: Path) -> None:
"""Restore the modes and manifest `write_release_manifest` leaves.
`verify_release` recomputes every digest and refuses a release whose
directories are writable, so a fixture that edits a sealed release has
to leave it exactly as the installer would have.
"""
manifest = release / "MANIFEST.sha256"
manifest.chmod(0o644)
lines = [
f"{hashlib.sha256(path.read_bytes()).hexdigest()} "
f"{path.relative_to(release).as_posix()}"
for path in sorted(release.rglob("*"))
if path.is_file() and path != manifest
]
manifest.write_text("\n".join(lines) + "\n", encoding="utf-8")
for path in sorted(release.rglob("*")):
if path.is_file():
path.chmod(0o555 if path.stat().st_mode & 0o111 else 0o444)
for directory in sorted(
(path for path in release.rglob("*") if path.is_dir()), reverse=True
):
directory.chmod(0o555)
release.chmod(0o555)
def install_legacy_generation(self) -> None:
"""Leave the installation an older release left behind.
The rollback proofs below all begin from an installation created by a
release older than the release-anchored manager. That generation
differed in two ways this installer still has to cope with: nothing
anchors management to a release, and the management command is a copy
of the release's own `bin/session-kit` rather than the stable launcher.
The fixture reproduces that state instead of installing the old source
tree, which is reachable from no public clone, so the proofs run
everywhere. Every property the later assertions depend on is checked
here, so a future change to the installer cannot quietly turn these
into tests of an ordinary modern installation.
"""
self.run_installer("--non-interactive")
root = self.home / ".local/lib/session-kit"
release = root / "releases" / RELEASE_A
self.unseal_release(release)
# An older release also carries older launchers. Stamping them keeps
# the byte comparisons that prove which release a launcher came from
# able to tell the two releases apart.
for relative in ("bin/session-kit", "deploy/session-kit-launcher"):
stamped = release / relative
stamped.chmod(0o755)
shebang, _, body = stamped.read_text(encoding="utf-8").partition("\n")
stamped.write_text(
f"{shebang}\n{LEGACY_LAUNCHER_STAMP}{body}", encoding="utf-8"
)
self.seal_release(release)
(root / "manager").unlink()
launcher = self.home / ".local/bin/session-kit"
launcher.write_bytes((release / "bin/session-kit").read_bytes())
launcher.chmod(0o755)
for helper in self.helper_launcher_names():
helper_path = self.home / ".local/bin" / helper
if not helper_path.exists():
continue
helper_path.write_bytes(
(release / "deploy/session-kit-launcher").read_bytes()
)
helper_path.chmod(0o755)
for directory in (self.home / ".claude", self.home / ".codex"):
if directory.is_dir() and not any(directory.iterdir()):
directory.rmdir()
# The state the rollback proofs are written against, asserted rather
# than assumed.
self.assertFalse((root / "manager").exists())
self.assertEqual(RELEASE_A, (root / "current").resolve().name)
self.assertEqual(
(release / "bin/session-kit").read_bytes(), launcher.read_bytes()
)
self.assertNotEqual(
(release / "deploy/session-kit-launcher").read_bytes(),
(REPO / "deploy/session-kit-launcher").read_bytes(),
)
def write_systemctl_probe_fixture(self) -> Path:
log = self.temp / "systemctl-probes.log"
systemctl = self.fake_bin / "systemctl"
systemctl.write_text(
"#!/usr/bin/env bash\n"
"printf '%s\\n' \"$*\" >> \"$SESSION_KIT_SYSTEMCTL_LOG\"\n"
"case \"$*\" in\n"
" '--user show-environment') exit \"${SESSION_KIT_DIRECT_RC:-0}\" ;;\n"
" '--user --machine=@.host show-environment') exit \"${SESSION_KIT_MACHINE_RC:-1}\" ;;\n"
" *) exit 64 ;;\n"
"esac\n",
encoding="utf-8",
)
systemctl.chmod(0o755)
return log
def test_check_is_read_only(self) -> None:
result = self.run_installer("--check")
self.assertIn("OK source installable", result.stdout)
self.assertEqual(list(self.home.iterdir()), [])
def test_check_reports_direct_and_fallback_systemd_transports(self) -> None:
source = self.clean_source_fixture()
log = self.write_systemctl_probe_fixture()
env = self.env.copy()
env.pop("SESSION_KIT_TESTING")
env.pop("SESSION_KIT_RELEASE_ID")
env["SESSION_KIT_SYSTEMCTL_LOG"] = str(log)
cases = (
(
"0",
"1",
0,
"OK services systemd user manager is available",
["--user show-environment"],
),
(
"1",
"0",
0,
"WARN services systemd user manager is available through "
"local-machine transport; direct user socket is unavailable",
["--user show-environment", "--user --machine=@.host show-environment"],
),
(
"1",
"1",
1,
"FAIL services systemd user manager is unavailable",
["--user show-environment", "--user --machine=@.host show-environment"],
),
)
for direct_rc, machine_rc, expected_rc, message, calls in cases:
with self.subTest(direct_rc=direct_rc, machine_rc=machine_rc):
log.unlink(missing_ok=True)
env["SESSION_KIT_DIRECT_RC"] = direct_rc
env["SESSION_KIT_MACHINE_RC"] = machine_rc
result = subprocess.run(
[str(source / "install.sh"), "--check"],
cwd=source,
env=env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
self.assertEqual(result.returncode, expected_rc, result.stdout + result.stderr)
self.assertIn(message, result.stdout)
self.assertEqual(log.read_text(encoding="utf-8").splitlines(), calls)
def test_check_rejects_partial_inventory_package(self) -> None:
source = self.temp / "source"
shutil.copytree(
REPO,
source,
ignore=shutil.ignore_patterns(*SOURCE_COPY_IGNORES),
)
subprocess.run(["git", "init", "-q", source], check=True)
for relative in (
"lib/sessionkit_inventory/__init__.py",
"lib/sessionkit_inventory/common.py",
"lib/sessionkit_inventory/lifecycle.py",
"lib/sessionkit_inventory/projects.py",
"lib/sessionkit_inventory/providers.py",
"lib/sessionkit_inventory/reaper.py",
"lib/sessionkit_inventory/state_io.py",
):
with self.subTest(relative=relative):
path = source / relative
payload = path.read_bytes()
path.unlink()
result = subprocess.run(
[str(source / "install.sh"), "--check"],
cwd=source,
env=self.env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
self.assertNotEqual(result.returncode, 0)
self.assertIn(
f"FAIL source-files missing from the source: {relative}",
result.stdout,
)
path.write_bytes(payload)
# The Codex version this branch's finding was measured against. If Codex
# is upgraded, the test below fails ON PURPOSE: someone has to re-measure
# rather than assume the finding still holds.
MEASURED_CODEX_VERSION = "0.145.0"
def test_codex_gets_no_kit_file_because_codex_cannot_use_one(self) -> None:
"""Codex has no `/kit`, and installing a file that pretends otherwise
is worse than installing none.
Measured 2026-08-15 against codex-cli 0.145.0, three ways:
* its app-server protocol has 54 client methods and NO channel for a
custom command -- `skills/list` is the only invoke-by-name surface;
* `skills/list` against a home holding a full `prompts/` directory
returned 28 skills, none of them from `prompts/`;
* with a `skills/kit/SKILL.md` present and reported by `skills/list`
as enabled, the real TUI driven in remote mode drew a slash menu of
built-ins only -- `/model /fast /ide /permissions /keymap /vim
/experimental /approve` -- and `/ki` rendered `no matches`.
So `~/.codex/prompts/kit.md` was a file nothing ever read, and the docs
repeated its existence as a capability. Ctrl-q is the Codex answer and
needs no file at all. An older Codex did honour `prompts/`, which is
why this used to be true.
"""
claude = self.home / ".claude"
claude.mkdir()
codex = self.home / ".codex"
codex.mkdir()
accounts = self.home / ".local/share/session-kit/accounts"
(accounts / "codex" / "wren").mkdir(parents=True)
self.run_installer("--non-interactive")
# Claude still gets the verb; Codex gets nothing, anywhere.
self.assertTrue((claude / "commands" / "kit.md").is_file())
self.assertFalse((codex / "prompts" / "kit.md").exists())
self.assertFalse((codex / "prompts").exists())
self.assertFalse(
(accounts / "codex" / "wren" / "prompts" / "kit.md").exists()
)
def test_the_codex_finding_is_pinned_to_the_version_it_was_measured_on(
self,
) -> None:
"""A version bump must force a re-measurement, not an assumption.
The test above encodes a fact about codex-cli 0.145.0's behaviour, not
a law. If Codex ever restores custom slash commands, the right response
is to measure it again -- protocol methods, then the menu the real
client draws -- and give the verb back. This is the tripwire that makes
someone look.
"""
codex = shutil.which("codex")
if codex is None:
self.skipTest("no codex on this machine to measure")
result = subprocess.run(
[codex, "--version"], capture_output=True, text=True, timeout=60
)
if result.returncode != 0:
self.skipTest(f"codex --version failed: {result.stderr.strip()}")
version = result.stdout.strip()
self.assertIn(
self.MEASURED_CODEX_VERSION,
version,
"Codex changed version since the /kit finding was measured "
f"({version!r} is not {self.MEASURED_CODEX_VERSION}). Re-measure "
"before trusting test_codex_gets_no_kit_file_because_codex_cannot_"
"use_one: check whether the app-server protocol has gained a "
"custom-command channel, and drive the real TUI to read its slash "
"menu. If /kit works again, restore the verb and this pin.",
)
def test_only_the_typed_kit_verb_may_ever_detach(self) -> None:
"""The bare word `kit` must do nothing.
Claude Code merged custom commands into skills, so a file in
`commands/` is model-invocable by default. This one's body opens with
an injected `!`shpool detach``, which runs when the skill content is
RENDERED -- before the model reads any of it -- and `allowed-tools`
pre-approves the command, so nothing prompts. An operator typed the
bare word `kit` as an ordinary message, the model matched it against
the description, and their terminal detached mid-turn while output was
still painting (2026-08-15).
`disable-model-invocation: true` is the documented field that keeps
`/kit` working while removing the description from the model's context
entirely, so there is nothing left to match. Asserted on the INSTALLED
file, because that is the one a provider reads.
"""
claude = self.home / ".claude"
claude.mkdir()
accounts = self.home / ".local/share/session-kit/accounts"
(accounts / "claude" / "work").mkdir(parents=True)
self.run_installer("--non-interactive")
for path in (
claude / "commands" / "kit.md",
accounts / "claude" / "work" / "commands" / "kit.md",
):
with self.subTest(path=str(path)):
body = path.read_text(encoding="utf-8")
front = body.split("---")[1]
self.assertIn("disable-model-invocation: true", front)
# The injected command is still there -- the fix is the gate
# on WHO may fire it, not the removal of what it does.
self.assertIn("!`shpool detach`", body)
# And the typed verb still works: the file is still a command
# named kit, with its tool grant intact.
self.assertEqual("kit.md", path.name)
self.assertIn("allowed-tools: Bash(shpool detach:*)", front)
def test_the_kit_verb_reaches_every_enrolled_account_profile(self) -> None:
"""A session the kit launches on an account reads that account's
commands, not ~/.claude's: CLAUDE_CONFIG_DIR replaces the config root
rather than adding to it. A verb installed only in the home directory
is invisible in exactly the sessions it exists for — which is what the
live drill found, with /kit unknown inside a managed session."""
(self.home / ".claude").mkdir()
accounts = self.home / ".local/share/session-kit/accounts"
for alias in ("work", "spare"):
(accounts / "claude" / alias).mkdir(parents=True)
(accounts / "codex" / "wren").mkdir(parents=True)
self.run_installer("--non-interactive")
for alias in ("work", "spare"):
path = accounts / "claude" / alias / "commands" / "kit.md"
with self.subTest(alias=alias):
self.assertTrue(path.is_file(), path)
self.assertIn("shpool detach", path.read_text(encoding="utf-8"))
self.assertEqual(0o600, path.stat().st_mode & 0o777)
# Codex profiles get nothing: measured 2026-08-15, codex-cli 0.145.0
# never reads prompts/ and has no custom slash namespace, so a file
# here would be a claim rather than a capability. See
# test_codex_gets_no_kit_file_because_codex_cannot_use_one.
self.assertFalse((accounts / "codex" / "wren" / "prompts").exists())
def test_the_kit_verb_skips_a_provider_that_is_not_installed(self) -> None:
# No provider home is not a failure to report: it is a provider that
# is not on this machine. (The Codex home is not a fair test of this:
# the kit creates it itself for the window themes.)
self.run_installer("--non-interactive")
self.assertFalse((self.home / ".claude" / "commands").exists())
def test_the_kit_verb_ignores_the_account_profile_of_the_running_session(
self,
) -> None:
"""An install run from inside a managed session inherits that
session's account profile in CLAUDE_CONFIG_DIR. A machine-wide verb
installed into one rotating profile is invisible to the next account,
and writes into a directory the installer was never asked to touch."""
claude = self.home / ".claude"
claude.mkdir()
profile = self.home / "account-profile"
(profile / "commands").mkdir(parents=True)
environment = dict(self.env, CLAUDE_CONFIG_DIR=str(profile))
result = subprocess.run(
[str(REPO / "install.sh"), "--non-interactive"],
cwd=REPO,
env=environment,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
self.assertEqual(0, result.returncode, result.stderr)
self.assertTrue((claude / "commands" / "kit.md").is_file())
self.assertFalse((profile / "commands" / "kit.md").exists())
def test_the_kit_verb_never_writes_through_a_symlink(self) -> None:
claude = self.home / ".claude"
claude.mkdir()
commands = claude / "commands"
commands.mkdir(mode=0o700)
elsewhere = self.home / "not-a-command.md"
elsewhere.write_text("untouched\n", encoding="utf-8")
(commands / "kit.md").symlink_to(elsewhere)
self.run_installer("--non-interactive")
self.assertTrue((commands / "kit.md").is_symlink())
self.assertEqual("untouched\n", elsewhere.read_text(encoding="utf-8"))
@unittest.skipUnless(
host_group_is_private(), "this host does not give the account a private group"
)
def test_install_accepts_a_group_writable_provider_directory(self) -> None:
# A private-group distribution with a 002 umask leaves the provider
# config directory at 0775, which exposes it to no other account. The
# install still writes through it -- the /kit verb is the write that
# remains -- and leaves the operator's own mode alone.
claude = self.home / ".claude"
claude.mkdir(mode=0o775)
claude.chmod(0o775)
checked = self.run_installer("--check")
self.assertIn("OK source installable", checked.stdout)
self.run_installer("--non-interactive")
self.assertTrue((claude / "commands" / "kit.md").is_file())
self.assertEqual(0o775, claude.stat().st_mode & 0o777)
@unittest.skipUnless(
host_group_is_private(), "this host does not give the account a private group"
)
def test_install_accepts_a_group_writable_codex_home(self) -> None:
# The Codex CLI leaves ~/.codex group-writable on the same
# private-group distributions, and the theme layout owns that path.
codex = self.home / ".codex"
codex.mkdir(mode=0o700)
codex.chmod(0o775)
checked = self.run_installer("--check")
self.assertIn(
"OK codex-home the theme layout is owner-controlled",
checked.stdout,
)
self.run_installer("--non-interactive")
self.assertTrue((codex / "themes/sk-red.tmTheme").is_file())
self.assertFalse((codex / "prompts").exists())
self.assertEqual(0o775, codex.stat().st_mode & 0o777)
@unittest.skipUnless(
host_group_is_private(), "this host does not give the account a private group"
)
def test_interrupted_install_recovers_through_group_writable_directories(
self,
) -> None:
# Recovery revalidates every recorded provider-config and theme
# ancestor, so it has to accept the same directories the install
# accepted or an interrupted install can never be finished.
claude = self.home / ".claude"
claude.mkdir(mode=0o700)
claude.chmod(0o775)
codex = self.home / ".codex"
codex.mkdir(mode=0o700)
codex.chmod(0o775)
journal = self.home / ".local/state/session-kit/lifecycle-transaction.json"
self.env["SESSION_KIT_TEST_FAILPOINT"] = "themes"
self.env["SESSION_KIT_TEST_FAILPOINT_MODE"] = "kill"
interrupted = self.run_installer("--non-interactive", check=False)
self.assertEqual(-signal.SIGKILL, interrupted.returncode)
self.assertTrue(journal.is_file())
self.env.pop("SESSION_KIT_TEST_FAILPOINT")
self.env.pop("SESSION_KIT_TEST_FAILPOINT_MODE")
recovered = self.run_installer("--non-interactive")
self.assertIn(
"Recovered interrupted Session Kit install transaction", recovered.stdout
)
self.assertFalse(journal.exists())
self.assertTrue((self.home / ".local/lib/session-kit/current").is_symlink())
self.assertTrue((claude / "commands" / "kit.md").is_file())
self.assertEqual(0o775, claude.stat().st_mode & 0o777)
self.assertEqual(0o775, codex.stat().st_mode & 0o777)
def test_world_writable_provider_directory_is_never_written_through(
self,
) -> None:
"""A directory any account can write is never a write target.
Provider commands still treat an unavailable provider as absent, but
the required Claude status line and hook may not be silently skipped.
The overall install therefore refuses and names the unsafe directory.
"""
claude = self.home / ".claude"
claude.mkdir(mode=0o700)
claude.chmod(0o777)