Repository navigation
Expand file tree
/
Copy pathcodex_workdir_migrate.py
More file actions
executable file
·2033 lines (1782 loc) · 89.2 KB
/
Copy pathcodex_workdir_migrate.py
File metadata and controls
executable file
·2033 lines (1782 loc) · 89.2 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
#!/usr/bin/env python3
"""
Codex Session Working Directory Migration Tool
Safely migrates a Codex session from one working directory to another.
Supports local migration and cross-machine bundle export/import.
"""
import argparse
import copy
import hashlib
import json
import os
import platform
import re
import shutil
import socket
import sqlite3
import stat
import subprocess
import sys
import uuid
import zipfile
from contextlib import closing
from dataclasses import dataclass, field, asdict
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from urllib.parse import quote
ENV_CWD_RE = re.compile(r"<cwd>(.*?)</cwd>", re.DOTALL)
JSONL_CATEGORIES = (
"session_meta.cwd",
"turn_context.cwd",
"function_call.workdir",
"environment_context.cwd",
)
SQLITE_FIELDS = ("threads.cwd", "threads.sandbox_policy")
TOOL_VERSION = "0.2.1"
SENSITIVE_FILES = {
"auth.json",
"cookies",
"credentials",
"tokens",
"keychain",
".netrc",
".pypirc",
".npmrc",
".git-credentials",
"id_rsa",
"id_ed25519",
".env",
".env.local",
}
SENSITIVE_DIRS = {
"backups",
"reports",
"node_modules",
".git",
"__pycache__",
}
SENSITIVE_PATTERNS = [
re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"),
re.compile(r"sk-[a-zA-Z0-9]{20,}"),
re.compile(r"pk_[a-zA-Z0-9]{20,}"),
re.compile(r"AKIA[0-9A-Z]{16}"),
re.compile(r"AIza[0-9A-Za-z_-]{35}"),
re.compile(r"-----BEGIN (RSA|EC|DSA|OPENSSH) PRIVATE KEY-----"),
re.compile(r"-----BEGIN DSA PRIVATE KEY-----"),
re.compile(r"-----BEGIN EC PRIVATE KEY-----"),
re.compile(r"ghp_[a-zA-Z0-9]{36}"),
re.compile(r"gho_[a-zA-Z0-9]{36}"),
re.compile(r"glpat-[a-zA-Z0-9]{20}"),
]
@dataclass(frozen=True)
class MigrationPolicy:
include_function_workdir: bool = False
include_environment_context: bool = False
rewrite_prefix_paths: bool = False
@dataclass
class BundleManifest:
tool_version: str
export_time: str
source_hostname: str
source_os: str
codex_version: Optional[str] = None
session_id: str = ""
detected_cwd: Optional[str] = None
included_files: List[str] = field(default_factory=list)
sqlite_rows: List[Dict] = field(default_factory=list)
excluded_sensitive_files: List[str] = field(default_factory=list)
bundle_structure: Dict = field(default_factory=dict)
checksums: Dict[str, str] = field(default_factory=dict)
def to_dict(self):
return asdict(self)
class TargetInspectionError(RuntimeError):
"""Target ownership or stored state could not be established safely."""
class CodexSessionMigrator:
@staticmethod
def _valid_session_id(session_id):
# IDs become part of filenames; accept non-UUID IDs but never paths.
return isinstance(session_id, str) and re.fullmatch(
r"[A-Za-z0-9][A-Za-z0-9._-]*", session_id
) is not None
def __init__(self, codex_home=None):
self.codex_home = codex_home or os.path.expanduser("~/.codex")
self.sessions_dir = os.path.join(self.codex_home, "sessions")
self.archived_sessions_dir = os.path.join(self.codex_home, "archived_sessions")
self.state_db_path = os.path.join(self.codex_home, "state_5.sqlite")
self.session_index_path = os.path.join(self.codex_home, "session_index.jsonl")
@staticmethod
def _target_path_present(path):
try:
os.stat(path)
return True
except FileNotFoundError as e:
if os.path.lexists(path):
raise TargetInspectionError(f"Cannot inspect target {path}: dangling symlink") from e
return False
except OSError as e:
raise TargetInspectionError(f"Cannot inspect target {path}: {e}") from e
def find_session_file(self, session_id):
"""Select JSONL only by exact session_meta identity, never filename text."""
candidates = []
def walk_error(error):
raise TargetInspectionError(f"Cannot inspect session directory: {error}") from error
for base_dir in [self.sessions_dir, self.archived_sessions_dir]:
if not self._target_path_present(base_dir):
continue
for root, dirs, files in os.walk(base_dir, onerror=walk_error):
dirs.sort()
# os.walk does not descend directory links, including links
# to sessions with irregular filenames. Skipping is unknown
# ownership, not authoritative absence. Dangling links can
# appear in files instead of dirs and must also block.
for entry in dirs + files:
full_path = os.path.join(root, entry)
try:
linked = stat.S_ISLNK(os.lstat(full_path).st_mode)
except OSError as e:
raise TargetInspectionError(f"Cannot inspect session entry {full_path}: {e}") from e
if linked and (entry in dirs or not entry.endswith(".jsonl")):
raise TargetInspectionError(f"Unsupported session directory link: {full_path}")
for file in sorted(files):
if not file.endswith(".jsonl"):
continue
full_path = os.path.join(root, file)
identity = None
try:
with open(full_path, "r", encoding="utf-8") as f:
for line_num, line in enumerate(f, 1):
if not line.strip():
continue
try:
data = json.loads(line)
except json.JSONDecodeError as e:
raise TargetInspectionError(
f"Malformed session JSONL {full_path} line {line_num}: {e}"
) from e
if not isinstance(data, dict):
raise TargetInspectionError(
f"Invalid session record {full_path} line {line_num}"
)
if data.get("type") == "session_meta":
payload = data.get("payload")
record_id = payload.get("id") if isinstance(payload, dict) else None
if not isinstance(record_id, str) or not record_id:
raise TargetInspectionError(
f"Missing session_meta identity {full_path} line {line_num}"
)
if identity is not None and identity != record_id:
raise TargetInspectionError(f"Ambiguous session identity in {full_path}")
identity = record_id
except (OSError, UnicodeError) as e:
raise TargetInspectionError(f"Cannot read session JSONL {full_path}: {e}") from e
if identity is None:
raise TargetInspectionError(f"Missing session_meta identity in {full_path}")
if identity == session_id:
candidates.append(full_path)
return candidates
def _read_target_index(self):
"""Validate the entire index, including unrelated rows and interrupted tails."""
records = {}
lines = []
if not self._target_path_present(self.session_index_path):
return records, lines
try:
with open(self.session_index_path, "r", encoding="utf-8", newline="") as f:
for line_num, line in enumerate(f, 1):
lines.append(line)
if not line.strip():
continue
try:
record = json.loads(line)
except json.JSONDecodeError as e:
raise TargetInspectionError(
f"Malformed target index {self.session_index_path} line {line_num}: {e}"
) from e
if not isinstance(record, dict) or not isinstance(record.get("id"), str) or not record["id"]:
raise TargetInspectionError(
f"Invalid target index record {self.session_index_path} line {line_num}: expected object with nonempty string id"
)
if record["id"] in records:
raise TargetInspectionError(
f"Ambiguous target index ID {record['id']} at line {line_num}"
)
records[record["id"]] = record
except (OSError, UnicodeError) as e:
raise TargetInspectionError(f"Cannot read target index {self.session_index_path}: {e}") from e
return records, lines
def _rewrite_path_value(
self, value: Optional[str], old_cwd: str, new_cwd: str, rewrite_prefix_paths: bool
) -> Tuple[Optional[str], bool]:
if not isinstance(value, str):
return value, False
if value == old_cwd:
return new_cwd, True
if rewrite_prefix_paths and value.startswith(old_cwd + os.sep):
suffix = value[len(old_cwd):]
return new_cwd + suffix, True
return value, False
def _empty_jsonl_counts(self):
return {category: 0 for category in JSONL_CATEGORIES}
def _empty_sqlite_counts(self):
return {field: 0 for field in SQLITE_FIELDS}
def _policy_dict(self, policy: MigrationPolicy):
return {
"mode": "structured-only",
"include_function_workdir": policy.include_function_workdir,
"include_environment_context": policy.include_environment_context,
"rewrite_prefix_paths": policy.rewrite_prefix_paths,
}
def _rewrite_sandbox_policy(self, value, old_cwd, new_cwd, policy: MigrationPolicy):
if not isinstance(value, str):
return value, False
try:
parsed = json.loads(value)
except json.JSONDecodeError:
return self._rewrite_path_value(
value, old_cwd, new_cwd, policy.rewrite_prefix_paths
)
def rewrite_node(node):
if isinstance(node, str):
return self._rewrite_path_value(
node, old_cwd, new_cwd, policy.rewrite_prefix_paths
)
if isinstance(node, list):
changed = False
updated = []
for item in node:
new_item, item_changed = rewrite_node(item)
updated.append(new_item)
changed = changed or item_changed
return updated, changed
if isinstance(node, dict):
changed = False
updated = {}
for key, item in node.items():
new_item, item_changed = rewrite_node(item)
updated[key] = new_item
changed = changed or item_changed
return updated, changed
return node, False
rewritten, changed = rewrite_node(parsed)
if not changed:
return value, False
return json.dumps(rewritten, ensure_ascii=False, separators=(",", ":")), True
def _connect_state_db(self, readonly=False):
if readonly:
db_uri = "file:" + quote(os.path.abspath(self.state_db_path)) + "?mode=ro"
return sqlite3.connect(db_uri, uri=True)
return sqlite3.connect(self.state_db_path)
def _extract_refs(self, data, line_num):
refs = []
payload = data.get("payload", {})
if data.get("type") == "session_meta" and "cwd" in payload:
refs.append(
{
"line": line_num,
"category": "session_meta.cwd",
"value": payload.get("cwd"),
"updatable": True,
}
)
if data.get("type") == "turn_context" and "cwd" in payload:
refs.append(
{
"line": line_num,
"category": "turn_context.cwd",
"value": payload.get("cwd"),
"updatable": True,
}
)
if data.get("type") == "response_item" and payload.get("type") == "function_call":
args_raw = payload.get("arguments", "{}")
try:
args = json.loads(args_raw)
if "workdir" in args:
refs.append(
{
"line": line_num,
"category": "function_call.workdir",
"value": args.get("workdir"),
"updatable": False,
}
)
except json.JSONDecodeError:
pass
if data.get("type") == "response_item" and payload.get("type") == "message":
for item in payload.get("content", []):
if item.get("type") != "input_text":
continue
text = item.get("text", "")
for env_cwd in ENV_CWD_RE.findall(text):
refs.append(
{
"line": line_num,
"category": "environment_context.cwd",
"value": env_cwd,
"updatable": False,
"text_preview": text[:200],
}
)
return refs
def _update_json_line(self, data, old_cwd, new_cwd, policy: MigrationPolicy):
"""Return (updated_data, changes) without relying on object equality checks."""
updated = copy.deepcopy(data)
payload = updated.get("payload", {})
changes = []
if updated.get("type") == "session_meta":
new_val, changed = self._rewrite_path_value(
payload.get("cwd"), old_cwd, new_cwd, policy.rewrite_prefix_paths
)
if changed:
payload["cwd"] = new_val
changes.append("session_meta.cwd")
if updated.get("type") == "turn_context":
new_val, changed = self._rewrite_path_value(
payload.get("cwd"), old_cwd, new_cwd, policy.rewrite_prefix_paths
)
if changed:
payload["cwd"] = new_val
changes.append("turn_context.cwd")
if (
policy.include_function_workdir
and updated.get("type") == "response_item"
and payload.get("type") == "function_call"
):
try:
args = json.loads(payload.get("arguments", "{}"))
new_val, changed = self._rewrite_path_value(
args.get("workdir"), old_cwd, new_cwd, policy.rewrite_prefix_paths
)
if changed:
args["workdir"] = new_val
payload["arguments"] = json.dumps(args, ensure_ascii=False)
changes.append("function_call.workdir")
except json.JSONDecodeError:
pass
if (
policy.include_environment_context
and updated.get("type") == "response_item"
and payload.get("type") == "message"
):
for item in payload.get("content", []):
if item.get("type") != "input_text":
continue
text = item.get("text", "")
if not text:
continue
did_change = False
def _replace(match):
nonlocal did_change
original = match.group(1)
new_val, changed = self._rewrite_path_value(
original, old_cwd, new_cwd, policy.rewrite_prefix_paths
)
if changed:
did_change = True
return f"<cwd>{new_val}</cwd>"
updated_text = ENV_CWD_RE.sub(_replace, text)
if did_change:
item["text"] = updated_text
changes.append("environment_context.cwd")
return updated, changes
def _classify_jsonl_would_change(self, ref, old_cwd, policy: MigrationPolicy):
value = ref.get("value")
_, match = self._rewrite_path_value(value, old_cwd, "__NEW__", policy.rewrite_prefix_paths)
if not match:
return False
return self._jsonl_ref_in_policy_scope(ref, policy)
def _jsonl_ref_in_policy_scope(self, ref, policy: MigrationPolicy):
category = ref["category"]
if category in {"session_meta.cwd", "turn_context.cwd"}:
return True
if category == "function_call.workdir":
return policy.include_function_workdir
if category == "environment_context.cwd":
return policy.include_environment_context
return False
def _jsonl_ref_matches(self, ref, cwd, policy: MigrationPolicy):
_, match = self._rewrite_path_value(
ref.get("value"), cwd, "__REWRITE_SENTINEL__", policy.rewrite_prefix_paths
)
return match
def inspect_session(self, session_id):
result = {
"session_id": session_id,
"jsonl_files": [],
"session_index": {},
"sqlite_thread": {},
}
jsonl_files = self.find_session_file(session_id)
for jsonl_path in jsonl_files:
file_info = {"path": jsonl_path, "cwd_references": []}
try:
with open(jsonl_path, "r", encoding="utf-8") as f:
for line_num, line in enumerate(f, 1):
stripped = line.strip()
if not stripped:
continue
try:
data = json.loads(stripped)
refs = self._extract_refs(data, line_num)
if refs:
file_info["cwd_references"].extend(refs)
except json.JSONDecodeError:
continue
except Exception as e:
file_info["error"] = str(e)
result["jsonl_files"].append(file_info)
try:
records, _ = self._read_target_index()
result["session_index"] = records.get(session_id, {})
except TargetInspectionError as e:
result["session_index"]["error"] = str(e)
try:
if os.path.exists(self.state_db_path):
db = self._connect_state_db(readonly=True)
cursor = db.cursor()
cursor.execute("SELECT * FROM threads WHERE id = ?", (session_id,))
row = cursor.fetchone()
if row:
cursor.execute("PRAGMA table_info(threads)")
col_names = [c[1] for c in cursor.fetchall()]
result["sqlite_thread"] = dict(zip(col_names, row))
db.close()
except Exception as e:
result["sqlite_thread"]["error"] = str(e)
return result
def plan(self, session_id, old_cwd, new_cwd, policy: MigrationPolicy):
inspection = self.inspect_session(session_id)
detected_jsonl = self._empty_jsonl_counts()
summary = self._empty_jsonl_counts()
files_with_changes = []
for file_info in inspection["jsonl_files"]:
file_counts = self._empty_jsonl_counts()
for ref in file_info.get("cwd_references", []):
if self._jsonl_ref_matches(ref, old_cwd, policy):
detected_jsonl[ref["category"]] += 1
if self._classify_jsonl_would_change(ref, old_cwd, policy):
category = ref["category"]
summary[category] += 1
file_counts[category] += 1
if any(v > 0 for v in file_counts.values()):
files_with_changes.append({"path": file_info["path"], "counts": file_counts})
sqlite_changes = {field: False for field in SQLITE_FIELDS}
sqlite_detected = {field: False for field in SQLITE_FIELDS}
thread = inspection.get("sqlite_thread", {})
thread_cwd = thread.get("cwd")
_, sqlite_cwd_change = self._rewrite_path_value(
thread_cwd, old_cwd, new_cwd, policy.rewrite_prefix_paths
)
sqlite_detected["threads.cwd"] = sqlite_cwd_change
sqlite_changes["threads.cwd"] = sqlite_cwd_change
sandbox_policy = thread.get("sandbox_policy")
_, sandbox_change = self._rewrite_sandbox_policy(
sandbox_policy, old_cwd, new_cwd, policy
)
sqlite_detected["threads.sandbox_policy"] = sandbox_change
sqlite_changes["threads.sandbox_policy"] = sandbox_change
return {
"session_id": session_id,
"old_cwd": old_cwd,
"new_cwd": new_cwd,
"policy": self._policy_dict(policy),
"inspection": inspection,
"detected": {
"jsonl": detected_jsonl,
"sqlite": sqlite_detected,
},
"summary": {
"jsonl": summary,
"sqlite": sqlite_changes,
},
"files_with_changes": files_with_changes,
}
def _sha256_file(self, file_path):
hash_sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
def _scan_sensitive_content(self, content, file_name):
"""Scan content for sensitive patterns. Returns list of findings."""
findings = []
if not isinstance(content, str):
content = content.decode("utf-8", errors="ignore")
for pattern in SENSITIVE_PATTERNS:
matches = pattern.findall(content)
for match in matches[:3]:
findings.append({
"file": file_name,
"pattern": pattern.pattern[:50] + "..." if len(pattern.pattern) > 50 else pattern.pattern,
"match": match[:80] + "..." if len(match) > 80 else match,
})
if len(matches) > 3:
findings.append({
"file": file_name,
"pattern": pattern.pattern[:50] + "..." if len(pattern.pattern) > 50 else pattern.pattern,
"match": f"{len(matches) - 3} more matches",
})
return findings
def _rewrite_session_id_in_json(self, data, old_id, new_id):
"""Rewrite session ID in JSON data conservatively.
Only replaces string values that exactly match the old session ID.
Does not modify text fields like messages, prompts, or descriptions.
"""
text_field_names = {"message", "text", "content", "summary", "description", "title"}
def rewrite(node):
if isinstance(node, str):
if node == old_id:
return new_id
return node
if isinstance(node, list):
return [rewrite(item) for item in node]
if isinstance(node, dict):
result = {}
for key, value in node.items():
key_lower = key.lower()
if key_lower in text_field_names:
result[key] = value
else:
result[key] = rewrite(value)
return result
return node
return rewrite(data)
def create_backup(self, backup_dir, files_to_backup):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
backup_path = os.path.join(backup_dir, f"backup_{timestamp}")
os.makedirs(backup_path, exist_ok=True)
manifest = {"timestamp": timestamp, "files": []}
for src_path in sorted(set(files_to_backup)):
if not os.path.exists(src_path):
continue
dst_path = os.path.join(backup_path, os.path.basename(src_path))
shutil.copy2(src_path, dst_path)
manifest["files"].append(
{
"original_path": src_path,
"backup_path": dst_path,
"size": os.path.getsize(src_path),
"sha256": self._sha256_file(src_path),
}
)
manifest_path = os.path.join(backup_path, "MANIFEST.json")
with open(manifest_path, "w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2, ensure_ascii=False)
return backup_path
def _backup_file_list(self, session_id, backup_mode, plan_result):
jsonl_files = [entry["path"] for entry in plan_result.get("files_with_changes", [])]
sqlite_files = []
if plan_result["summary"]["sqlite"]["threads.cwd"] or plan_result["summary"]["sqlite"]["threads.sandbox_policy"]:
sqlite_files.extend([
self.state_db_path,
self.state_db_path + "-shm",
self.state_db_path + "-wal",
])
if backup_mode == "minimal":
return jsonl_files + sqlite_files
full = []
full.extend(self.find_session_file(session_id))
if os.path.exists(self.session_index_path):
full.append(self.session_index_path)
full.extend([
self.state_db_path,
self.state_db_path + "-shm",
self.state_db_path + "-wal",
])
return full
def _scan_jsonl_updates(self, jsonl_path, old_cwd, new_cwd, policy: MigrationPolicy):
changes_made = 0
per_category = self._empty_jsonl_counts()
updated_lines = []
with open(jsonl_path, "r", encoding="utf-8") as f_in:
for line in f_in:
stripped = line.strip()
if not stripped:
updated_lines.append(line)
continue
try:
data = json.loads(stripped)
updated_data, categories = self._update_json_line(
data, old_cwd, new_cwd, policy
)
if categories:
changes_made += 1
for category in categories:
per_category[category] += 1
updated_lines.append(json.dumps(updated_data, ensure_ascii=False) + "\n")
except json.JSONDecodeError:
updated_lines.append(line)
return updated_lines, changes_made, per_category
def migrate(
self,
session_id,
old_cwd,
new_cwd,
backup_dir,
policy: MigrationPolicy,
backup_mode="minimal",
dry_run=True,
):
result = {
"dry_run": dry_run,
"backup": None,
"backup_mode": backup_mode,
"policy": self._policy_dict(policy),
"modified_files": [],
"errors": [],
"summary": {
"jsonl": self._empty_jsonl_counts(),
"sqlite": self._empty_sqlite_counts(),
},
}
if not os.path.exists(new_cwd):
result["errors"].append(f"New working directory does not exist: {new_cwd}")
return result
plan_result = self.plan(session_id, old_cwd, new_cwd, policy)
if not dry_run and backup_dir:
files_to_backup = self._backup_file_list(session_id, backup_mode, plan_result)
result["backup"] = self.create_backup(backup_dir, files_to_backup)
jsonl_files = self.find_session_file(session_id)
for jsonl_path in jsonl_files:
temp_path = jsonl_path + ".tmp"
try:
updated_lines, changes_made, per_category = self._scan_jsonl_updates(
jsonl_path, old_cwd, new_cwd, policy
)
if changes_made > 0:
if not dry_run:
with open(temp_path, "w", encoding="utf-8") as f_out:
f_out.writelines(updated_lines)
os.replace(temp_path, jsonl_path)
result["modified_files"].append(
{"path": jsonl_path, "line_changes": changes_made, "counts": per_category}
)
for category, count in per_category.items():
result["summary"]["jsonl"][category] += count
except Exception as e:
result["errors"].append(f"Failed to update {jsonl_path}: {e}")
if os.path.exists(temp_path):
os.unlink(temp_path)
if os.path.exists(self.state_db_path):
try:
db = self._connect_state_db(readonly=dry_run)
cursor = db.cursor()
cursor.execute(
"SELECT id, cwd, sandbox_policy FROM threads WHERE id = ?",
(session_id,),
)
row = cursor.fetchone()
if row:
_, current_cwd, sandbox_policy = row
sqlite_changed = []
new_sqlite_cwd, cwd_changed = self._rewrite_path_value(
current_cwd, old_cwd, new_cwd, policy.rewrite_prefix_paths
)
if cwd_changed:
if not dry_run:
cursor.execute(
"UPDATE threads SET cwd = ? WHERE id = ?",
(new_sqlite_cwd, session_id),
)
sqlite_changed.append("threads.cwd")
result["summary"]["sqlite"]["threads.cwd"] += 1
new_policy, policy_changed = self._rewrite_sandbox_policy(
sandbox_policy, old_cwd, new_cwd, policy
)
if policy_changed:
if not dry_run:
cursor.execute(
"UPDATE threads SET sandbox_policy = ? WHERE id = ?",
(new_policy, session_id),
)
sqlite_changed.append("threads.sandbox_policy")
result["summary"]["sqlite"]["threads.sandbox_policy"] += 1
if sqlite_changed:
if not dry_run:
db.commit()
result["modified_files"].append(
{"path": self.state_db_path, "changes": sqlite_changed}
)
db.close()
except Exception as e:
result["errors"].append(f"Failed to update SQLite: {e}")
return result
def verify(self, session_id, old_cwd, new_cwd, policy: MigrationPolicy):
inspection = self.inspect_session(session_id)
result = {
"success": True,
"issues": [],
"old_cwd_refs": [],
"new_cwd_refs": [],
"policy": self._policy_dict(policy),
"summary": {
"jsonl": self._empty_jsonl_counts(),
"sqlite": self._empty_sqlite_counts(),
},
}
for file_info in inspection["jsonl_files"]:
for ref in file_info.get("cwd_references", []):
category = ref["category"]
value = ref.get("value")
_, old_match = self._rewrite_path_value(
value, old_cwd, "__NEW__", policy.rewrite_prefix_paths
)
_, new_match = self._rewrite_path_value(
value, new_cwd, "__OLD__", policy.rewrite_prefix_paths
)
in_scope = self._jsonl_ref_in_policy_scope(ref, policy)
if old_match and in_scope:
result["old_cwd_refs"].append({"file": file_info["path"], "ref": ref})
result["summary"]["jsonl"][category] += 1
result["success"] = False
if new_match and in_scope:
result["new_cwd_refs"].append({"file": file_info["path"], "ref": ref})
thread = inspection.get("sqlite_thread", {})
cwd_val = thread.get("cwd")
_, old_sqlite_cwd = self._rewrite_path_value(
cwd_val, old_cwd, "__NEW__", policy.rewrite_prefix_paths
)
_, new_sqlite_cwd = self._rewrite_path_value(
cwd_val, new_cwd, "__OLD__", policy.rewrite_prefix_paths
)
if old_sqlite_cwd:
result["old_cwd_refs"].append({"source": "sqlite.cwd", "cwd": cwd_val})
result["summary"]["sqlite"]["threads.cwd"] += 1
result["success"] = False
if new_sqlite_cwd:
result["new_cwd_refs"].append({"source": "sqlite.cwd", "cwd": cwd_val})
sandbox_policy = thread.get("sandbox_policy", "")
_, old_sandbox_policy = self._rewrite_sandbox_policy(
sandbox_policy, old_cwd, "__NEW__", policy
)
_, new_sandbox_policy = self._rewrite_sandbox_policy(
sandbox_policy, new_cwd, "__OLD__", policy
)
if old_sandbox_policy:
result["old_cwd_refs"].append(
{"source": "sqlite.sandbox_policy", "preview": sandbox_policy[:200]}
)
result["summary"]["sqlite"]["threads.sandbox_policy"] += 1
result["success"] = False
if new_sandbox_policy:
result["new_cwd_refs"].append(
{"source": "sqlite.sandbox_policy", "preview": sandbox_policy[:200]}
)
return result
def _get_codex_version(self):
"""Attempt to get Codex CLI version."""
try:
result = subprocess.run(
["codex", "--version"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
return None
def export_bundle(self, session_id, output_path, allow_sensitive_content=False):
"""Export session bundle for cross-machine migration."""
result = {
"success": False,
"bundle_path": None,
"manifest": None,
"errors": [],
"sensitive_findings": [],
}
manifest = BundleManifest(
tool_version=TOOL_VERSION,
export_time=datetime.now().isoformat(),
source_hostname=socket.gethostname(),
source_os=f"{platform.system()} {platform.release()}",
codex_version=self._get_codex_version(),
session_id=session_id,
)
inspection = self.inspect_session(session_id)
if not inspection["jsonl_files"] and not inspection["sqlite_thread"]:
result["errors"].append(f"Session {session_id} not found")
return result
manifest.detected_cwd = inspection["sqlite_thread"].get("cwd")
bundle_dir = os.path.dirname(output_path) or "."
os.makedirs(bundle_dir, exist_ok=True)
included_files = []
excluded_files = []
try:
bundle_structure = {
"inspection": {},
"sessions": {"raw_jsonl": []},
"index": {},
"sqlite": {},
"checksums": {},
}
all_content_for_scan = []
for jsonl_file_info in inspection["jsonl_files"]:
jsonl_path = jsonl_file_info["path"]
if os.path.exists(jsonl_path):
arcname = f"sessions/raw_jsonl/{os.path.basename(jsonl_path)}"
with open(jsonl_path, "r", encoding="utf-8") as f:
content = f.read()
all_content_for_scan.append((arcname, content))
if inspection["session_index"]:
idx_path = self.session_index_path
if os.path.exists(idx_path):
arcname = "index/session_index_records.jsonl"
with open(idx_path, "r", encoding="utf-8") as f:
filtered_lines = []
for line in f:
try:
data = json.loads(line.strip())
if data.get("id") == session_id:
filtered_lines.append(line)
except json.JSONDecodeError:
continue
content = "".join(filtered_lines)
all_content_for_scan.append((arcname, content))
if inspection["sqlite_thread"]:
arcname = "sqlite/state_db_matching_rows.json"
content = json.dumps({
"schema_summary": "threads(id, cwd, sandbox_policy, ...)",
"matching_rows": [inspection["sqlite_thread"]],
}, indent=2, ensure_ascii=False)
all_content_for_scan.append((arcname, content))
arcname = "inspection/inspect_report.json"
content = json.dumps(inspection, indent=2, ensure_ascii=False)
all_content_for_scan.append((arcname, content))
for arcname, content in all_content_for_scan:
sensitive = self._scan_sensitive_content(content, arcname)
if sensitive:
result["sensitive_findings"].extend(sensitive)
if result["sensitive_findings"] and not allow_sensitive_content:
result["errors"].append(
f"Sensitive content detected in bundle. Use --allow-sensitive-content to export anyway. "
f"Found {len(result['sensitive_findings'])} potential sensitive patterns."
)
return result
with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zf:
for jsonl_file_info in inspection["jsonl_files"]:
jsonl_path = jsonl_file_info["path"]
if os.path.exists(jsonl_path):
arcname = f"sessions/raw_jsonl/{os.path.basename(jsonl_path)}"
zf.write(jsonl_path, arcname)
included_files.append(arcname)
bundle_structure["sessions"]["raw_jsonl"].append(arcname)
bundle_structure["checksums"][arcname] = self._sha256_file(jsonl_path)
if inspection["session_index"]:
idx_path = self.session_index_path
if os.path.exists(idx_path):
arcname = "index/session_index_records.jsonl"
with open(idx_path, "r", encoding="utf-8") as f:
filtered_lines = []
for line in f:
try:
data = json.loads(line.strip())
if data.get("id") == session_id:
filtered_lines.append(line)
except json.JSONDecodeError:
continue
temp_idx = f"{bundle_dir}/.tmp_session_index.jsonl"
with open(temp_idx, "w", encoding="utf-8") as tmp:
tmp.writelines(filtered_lines)
if filtered_lines:
zf.write(temp_idx, arcname)
included_files.append(arcname)
bundle_structure["index"]["session_index_records"] = arcname
bundle_structure["checksums"][arcname] = self._sha256_file(temp_idx)
os.unlink(temp_idx)
if inspection["sqlite_thread"]:
sqlite_info = {
"schema_summary": "threads(id, cwd, sandbox_policy, ...)",
"matching_rows": [inspection["sqlite_thread"]],