-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_session_skill_package.py
More file actions
1794 lines (1567 loc) · 70.2 KB
/
sync_session_skill_package.py
File metadata and controls
1794 lines (1567 loc) · 70.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
"""Inspect and reconcile incoming offline Codex session packages."""
from __future__ import annotations
import argparse
import copy
import hashlib
import importlib.util
import json
import shutil
import sqlite3
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
def now_utc() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def normalize_cwd(path: str) -> str:
if path.startswith("\\\\?\\"):
return path[4:]
return path
def read_jsonl(path: Path) -> list[dict]:
rows: list[dict] = []
if not path.exists():
return rows
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
rows.append(json.loads(line))
return rows
def write_jsonl(path: Path, rows: list[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), encoding="utf-8")
def load_manifest(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
def save_manifest(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
def ensure_threads_schema(con: sqlite3.Connection) -> None:
cur = con.cursor()
cur.execute(
"""
CREATE TABLE IF NOT EXISTS threads (
id TEXT PRIMARY KEY,
rollout_path TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
source TEXT NOT NULL,
model_provider TEXT NOT NULL,
cwd TEXT NOT NULL,
title TEXT NOT NULL,
sandbox_policy TEXT NOT NULL,
approval_mode TEXT NOT NULL,
tokens_used INTEGER NOT NULL DEFAULT 0,
has_user_event INTEGER NOT NULL DEFAULT 0,
archived INTEGER NOT NULL DEFAULT 0,
archived_at INTEGER,
git_sha TEXT,
git_branch TEXT,
git_origin_url TEXT,
cli_version TEXT NOT NULL DEFAULT '',
first_user_message TEXT NOT NULL DEFAULT '',
agent_nickname TEXT,
agent_role TEXT,
memory_mode TEXT NOT NULL DEFAULT 'enabled',
model TEXT,
reasoning_effort TEXT,
agent_path TEXT
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS thread_dynamic_tools (
thread_id TEXT NOT NULL,
position INTEGER NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
input_schema TEXT NOT NULL,
defer_loading INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (thread_id, position)
)
"""
)
con.commit()
def sha256_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def replace_embedded_cwd(text: str) -> str:
if "<cwd>" not in text or "</cwd>" not in text:
return text
start = text.find("<cwd>") + len("<cwd>")
end = text.find("</cwd>")
if end <= start:
return text
return text[:start] + "<cwd-normalized>" + text[end:]
def canonicalize_event(obj: dict) -> dict:
normalized = copy.deepcopy(obj)
payload = normalized.get("payload")
if not isinstance(payload, dict):
return normalized
if normalized.get("type") == "session_meta":
payload.pop("id", None)
payload.pop("timestamp", None)
payload["cwd"] = "<cwd-normalized>"
if normalized.get("type") == "turn_context":
payload["cwd"] = "<cwd-normalized>"
sandbox = payload.get("sandbox_policy")
if isinstance(sandbox, dict):
sandbox["writable_roots"] = ["<cwd-normalized>"]
if (
normalized.get("type") == "response_item"
and payload.get("type") == "message"
and payload.get("role") == "user"
):
for item in payload.get("content", []):
text_value = item.get("text")
if isinstance(text_value, str):
item["text"] = replace_embedded_cwd(text_value)
return normalized
def canonical_lines(rows: list[dict]) -> list[str]:
return [json.dumps(canonicalize_event(row), ensure_ascii=False, sort_keys=True, separators=(",", ":")) for row in rows]
def longest_common_prefix(left: list[str], right: list[str]) -> int:
length = min(len(left), len(right))
index = 0
while index < length and left[index] == right[index]:
index += 1
return index
def make_session_fingerprint(rows: list[dict]) -> dict[str, Any]:
lines = canonical_lines(rows)
full_fingerprint = sha256_text("\n".join(lines))
last_event_fingerprint = sha256_text(lines[-1]) if lines else ""
return {
"canonical_lines": lines,
"session_fingerprint": f"sess_{full_fingerprint}",
"event_count": len(lines),
"last_event_fingerprint": f"evt_{last_event_fingerprint}" if last_event_fingerprint else "",
}
def sync_root(codex_home: Path) -> Path:
return codex_home / "session-sync"
def sync_transactions_dir(codex_home: Path) -> Path:
return sync_root(codex_home) / "transactions"
def sidecar_path(codex_home: Path, name: str) -> Path:
return sync_root(codex_home) / name
def load_sidecar_rows(codex_home: Path, name: str) -> list[dict]:
return read_jsonl(sidecar_path(codex_home, name))
def upsert_sidecar_row(codex_home: Path, name: str, key_fields: list[str], new_row: dict) -> None:
rows = load_sidecar_rows(codex_home, name)
replaced = False
for index, row in enumerate(rows):
if all(row.get(field) == new_row.get(field) for field in key_fields):
rows[index] = new_row
replaced = True
break
if not replaced:
rows.append(new_row)
write_jsonl(sidecar_path(codex_home, name), rows)
def append_sidecar_row(codex_home: Path, name: str, row: dict) -> None:
rows = load_sidecar_rows(codex_home, name)
rows.append(row)
write_jsonl(sidecar_path(codex_home, name), rows)
def replace_or_append_index_row(index_path: Path, session_id: str, title: str, updated_at: str) -> None:
rows = read_jsonl(index_path)
replaced = False
for row in rows:
if str(row.get("id")) == session_id:
row["thread_name"] = title
row["updated_at"] = updated_at
replaced = True
break
if not replaced:
rows.append({"id": session_id, "thread_name": title, "updated_at": updated_at})
write_jsonl(index_path, rows)
def backup_file_if_exists(path: Path, backup_path: Path) -> None:
if path.exists():
backup_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, backup_path)
def sync_transaction_dir(codex_home: Path, transaction_id: str) -> Path:
return sync_transactions_dir(codex_home) / transaction_id
def backup_sidecar_files(codex_home: Path, backups_dir: Path) -> None:
for name in ["lineages.jsonl", "source-mappings.jsonl", "snapshots.jsonl", "imports.jsonl", "forks.jsonl"]:
backup_file_if_exists(sidecar_path(codex_home, name), backups_dir / "session-sync" / name)
def remove_sidecar_rows(codex_home: Path, name: str, predicate) -> int:
rows = load_sidecar_rows(codex_home, name)
kept = [row for row in rows if not predicate(row)]
removed = len(rows) - len(kept)
if removed:
write_jsonl(sidecar_path(codex_home, name), kept)
return removed
def restore_file_or_delete(target: Path, backup: Path) -> None:
if backup.exists():
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(backup, target)
elif target.exists():
if target.is_dir():
shutil.rmtree(target)
else:
target.unlink()
def load_thread_row_from_backup_db(backup_db: Path, session_id: str) -> tuple[dict | None, list[dict]]:
if not backup_db.exists():
return None, []
con = sqlite3.connect(backup_db)
con.row_factory = sqlite3.Row
row = con.execute("SELECT * FROM threads WHERE id = ?", (session_id,)).fetchone()
tool_rows: list[dict] = []
if row is not None:
try:
fetched = con.execute(
"SELECT thread_id, position, name, description, input_schema, defer_loading FROM thread_dynamic_tools WHERE thread_id = ? ORDER BY position",
(session_id,),
).fetchall()
tool_rows = [dict(item) for item in fetched]
except sqlite3.OperationalError:
tool_rows = []
con.close()
return (dict(row) if row is not None else None), tool_rows
def restore_thread_row_and_tools(codex_home: Path, backup_db: Path, session_id: str) -> bool:
row_dict, tool_rows = load_thread_row_from_backup_db(backup_db, session_id)
if row_dict is None:
return False
con = sqlite3.connect(codex_home / "state_5.sqlite")
ensure_threads_schema(con)
columns = list(row_dict.keys())
placeholders = ",".join("?" for _ in columns)
con.execute(
f"INSERT OR REPLACE INTO threads ({','.join(columns)}) VALUES ({placeholders})",
[row_dict[column] for column in columns],
)
try:
con.execute("DELETE FROM thread_dynamic_tools WHERE thread_id = ?", (session_id,))
except sqlite3.OperationalError:
pass
for tool_row in tool_rows:
con.execute(
"""
INSERT INTO thread_dynamic_tools (thread_id, position, name, description, input_schema, defer_loading)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
tool_row["thread_id"],
tool_row["position"],
tool_row["name"],
tool_row["description"],
tool_row["input_schema"],
tool_row["defer_loading"],
),
)
con.commit()
con.close()
return True
def load_index_row(index_path: Path, session_id: str) -> dict | None:
for row in read_jsonl(index_path):
if str(row.get("id")) == session_id:
return row
return None
def restore_index_row_from_backup(codex_home: Path, backup_index_path: Path, session_id: str) -> None:
backup_row = load_index_row(backup_index_path, session_id)
if backup_row is None:
delete_session_index_row(codex_home / "session_index.jsonl", session_id)
return
replace_or_append_index_row(
codex_home / "session_index.jsonl",
session_id,
str(backup_row.get("thread_name", "")),
str(backup_row.get("updated_at", "")),
)
def restore_sidecar_from_backup(codex_home: Path, backups: Path) -> None:
restore_file_or_delete(sidecar_path(codex_home, "lineages.jsonl"), backups / "session-sync" / "lineages.jsonl")
restore_file_or_delete(sidecar_path(codex_home, "source-mappings.jsonl"), backups / "session-sync" / "source-mappings.jsonl")
restore_file_or_delete(sidecar_path(codex_home, "snapshots.jsonl"), backups / "session-sync" / "snapshots.jsonl")
restore_file_or_delete(sidecar_path(codex_home, "imports.jsonl"), backups / "session-sync" / "imports.jsonl")
restore_file_or_delete(sidecar_path(codex_home, "forks.jsonl"), backups / "session-sync" / "forks.jsonl")
def delete_session_index_row(index_path: Path, session_id: str) -> None:
rows = read_jsonl(index_path)
kept = [row for row in rows if str(row.get("id")) != session_id]
if len(kept) != len(rows):
write_jsonl(index_path, kept)
def prune_orphan_lineages(codex_home: Path) -> int:
lineages = load_sidecar_rows(codex_home, "lineages.jsonl")
mappings = load_sidecar_rows(codex_home, "source-mappings.jsonl")
live_ids = {str(row.get("sync_lineage_id", "")) for row in mappings if row.get("sync_lineage_id")}
kept = [row for row in lineages if str(row.get("sync_lineage_id", "")) in live_ids]
removed = len(lineages) - len(kept)
if removed:
write_jsonl(sidecar_path(codex_home, "lineages.jsonl"), kept)
return removed
def prune_invalid_source_mappings(codex_home: Path) -> int:
return remove_sidecar_rows(
codex_home,
"source-mappings.jsonl",
lambda row: not local_session_exists(codex_home, str(row.get("local_session_id", ""))),
)
def read_sync_transaction_manifest(codex_home: Path, transaction_id: str) -> tuple[Path, dict]:
tx_dir = sync_transaction_dir(codex_home, transaction_id)
manifest_path = tx_dir / "manifest.json"
if not manifest_path.exists():
raise SystemExit(f"Sync transaction not found: {transaction_id}")
return tx_dir, load_manifest(manifest_path)
def select_sync_transaction(codex_home: Path, transaction_id: str | None, latest: bool) -> tuple[Path, dict]:
root = sync_transactions_dir(codex_home)
if not root.exists():
raise SystemExit("No session-sync transactions found.")
if transaction_id:
return read_sync_transaction_manifest(codex_home, transaction_id)
if latest:
manifests = []
for tx in root.iterdir():
manifest_path = tx / "manifest.json"
if manifest_path.exists():
manifest = load_manifest(manifest_path)
if manifest.get("status") == "completed":
manifests.append((manifest.get("created_at", ""), tx, manifest))
if not manifests:
raise SystemExit("No completed sync transactions available for rollback.")
manifests.sort(key=lambda item: item[0], reverse=True)
_, tx_dir, manifest = manifests[0]
return tx_dir, manifest
raise SystemExit("Provide --transaction-id or --latest.")
def execute_fast_forward_imports(
package_root: Path,
codex_home: Path,
source_env: str,
source_package: str,
decisions: list[SessionDecision],
localized_threads: list[dict],
index_rows: list[dict],
original_threads: dict[str, dict],
transfer: Any,
) -> dict:
transaction_id = f"sync_{uuid.uuid7()}"
tx_dir = sync_transaction_dir(codex_home, transaction_id)
backups_dir = tx_dir / "backups"
backups_dir.mkdir(parents=True, exist_ok=False)
created_at = now_utc()
backup_file_if_exists(codex_home / "state_5.sqlite", backups_dir / "codex-home" / "state_5.sqlite")
backup_file_if_exists(codex_home / "state_5.sqlite-wal", backups_dir / "codex-home" / "state_5.sqlite-wal")
backup_file_if_exists(codex_home / "state_5.sqlite-shm", backups_dir / "codex-home" / "state_5.sqlite-shm")
backup_file_if_exists(codex_home / "session_index.jsonl", backups_dir / "codex-home" / "session_index.jsonl")
backup_sidecar_files(codex_home, backups_dir)
localized_by_id = {str(row["id"]): row for row in localized_threads}
index_by_id = {str(row["id"]): row for row in index_rows}
results = []
con = sqlite3.connect(codex_home / "state_5.sqlite")
transfer.ensure_threads_schema(con)
for decision in decisions:
if decision.decision != "fast_forward_import":
continue
session_id = str(decision.matched_local_session_id)
localized_thread = localized_by_id[session_id]
source_meta = original_threads[session_id]
source_rollout = package_root / "sessions" / Path(str(source_meta["rollout_path"])).name
source_text = source_rollout.read_text(encoding="utf-8")
target_rollout = Path(str(localized_thread["rollout_path"]))
backup_file_if_exists(target_rollout, backups_dir / "sessions" / target_rollout.name)
target_rollout.parent.mkdir(parents=True, exist_ok=True)
target_rollout.write_text(transfer.update_rollout_text(source_text, str(localized_thread["cwd"])), encoding="utf-8")
thread_row = dict(localized_thread)
thread_row["updated_at"] = int(datetime.now(timezone.utc).timestamp())
columns = list(thread_row.keys())
placeholders = ",".join("?" for _ in columns)
con.execute(
f"INSERT OR REPLACE INTO threads ({','.join(columns)}) VALUES ({placeholders})",
[thread_row[column] for column in columns],
)
index_row = index_by_id.get(session_id)
replace_or_append_index_row(
codex_home / "session_index.jsonl",
session_id,
str(index_row["thread_name"]) if index_row and "thread_name" in index_row else str(localized_thread.get("title", "")),
now_utc(),
)
upsert_sidecar_row(
codex_home,
"source-mappings.jsonl",
["source_env_fingerprint", "source_session_id", "local_session_id"],
{
"sync_lineage_id": decision.sync_lineage_id,
"source_env_fingerprint": source_env,
"source_package_fingerprint": source_package,
"source_session_id": session_id,
"local_session_id": session_id,
"adoption_mode": "sync-fast-forward",
"created_at": created_at,
"updated_at": created_at,
"is_current_tip_mapping": True,
},
)
local_row, rollout_rows, _tools = load_local_session_rows(codex_home, session_id)
upsert_sidecar_row(
codex_home,
"snapshots.jsonl",
["local_session_id"],
snapshot_record(local_row, rollout_rows, str(decision.sync_lineage_id)),
)
append_sidecar_row(
codex_home,
"imports.jsonl",
{
"import_id": transaction_id,
"created_at": created_at,
"source_env_fingerprint": source_env,
"source_package_fingerprint": source_package,
"source_session_id": session_id,
"matched_local_session_id": session_id,
"sync_lineage_id": decision.sync_lineage_id,
"decision": "fast_forward_import",
"execute_mode": "execute",
"notes": decision.reason,
},
)
results.append(
{
"local_session_id": session_id,
"rollout_path": str(target_rollout),
"sync_lineage_id": decision.sync_lineage_id,
}
)
con.commit()
con.close()
save_manifest(
tx_dir / "manifest.json",
{
"transaction_id": transaction_id,
"created_at": created_at,
"status": "completed",
"package_root": str(package_root),
"codex_home": str(codex_home),
"decision_counts": {"fast_forward_import": len(results)},
"results": results,
},
)
return {"transaction_id": transaction_id, "results": results}
def source_env_fingerprint(package_root: Path, manifest: dict) -> str:
explicit = manifest.get("source_env_fingerprint")
if isinstance(explicit, str) and explicit.strip():
return explicit.strip()
seed = json.dumps(
{
"format_version": manifest.get("format_version"),
"package_kind": manifest.get("package_kind"),
"cwd_filter": manifest.get("cwd_filter"),
"preferred_installer_skill": manifest.get("preferred_installer_skill"),
"skills_included": manifest.get("skills_included", []),
"deferred_components": manifest.get("deferred_components", []),
},
ensure_ascii=False,
sort_keys=True,
)
return f"env_{sha256_text(seed)[:16]}"
def source_package_fingerprint(package_root: Path, manifest: dict) -> str:
seed = json.dumps({"package": str(package_root), "manifest": manifest}, ensure_ascii=False, sort_keys=True)
return f"pkg_{sha256_text(seed)[:16]}"
def load_transfer_module() -> Any:
script_path = Path(__file__).resolve().parents[2] / "codex-session-transfer" / "scripts" / "install_session_skill_package.py"
spec = importlib.util.spec_from_file_location("codex_session_transfer_install", script_path)
if spec is None or spec.loader is None:
raise SystemExit(f"Unable to load transfer module from {script_path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def ensure_threads_row(con: sqlite3.Connection, session_id: str) -> sqlite3.Row:
con.row_factory = sqlite3.Row
row = con.execute("SELECT * FROM threads WHERE id = ?", (session_id,)).fetchone()
if row is None:
raise SystemExit(f"Local session not found: {session_id}")
return row
def maybe_count_dynamic_tools(con: sqlite3.Connection, session_id: str) -> int:
try:
row = con.execute("SELECT COUNT(*) FROM thread_dynamic_tools WHERE thread_id = ?", (session_id,)).fetchone()
except sqlite3.OperationalError:
return 0
return int(row[0])
def load_local_session_rows(codex_home: Path, session_id: str) -> tuple[sqlite3.Row, list[dict], int]:
con = sqlite3.connect(codex_home / "state_5.sqlite")
row = ensure_threads_row(con, session_id)
tools_count = maybe_count_dynamic_tools(con, session_id)
con.close()
rollout_rows = read_jsonl(Path(row["rollout_path"]))
return row, rollout_rows, tools_count
def snapshot_record(local_row: sqlite3.Row, rows: list[dict], sync_lineage_id: str) -> dict:
fingerprint = make_session_fingerprint(rows)
return {
"local_session_id": str(local_row["id"]),
"sync_lineage_id": sync_lineage_id,
"rollout_path": str(local_row["rollout_path"]),
"cwd": normalize_cwd(str(local_row["cwd"])),
"session_fingerprint": fingerprint["session_fingerprint"],
"prefix_fingerprint": fingerprint["session_fingerprint"],
"event_count": fingerprint["event_count"],
"message_count": sum(1 for row in rows if row.get("type") == "response_item"),
"last_event_fingerprint": fingerprint["last_event_fingerprint"],
"updated_at": now_utc(),
}
def utc_iso_with_millis(dt: datetime) -> str:
return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{int(dt.microsecond / 1000):03d}Z"
def utc_iso_seconds(dt: datetime) -> str:
return dt.replace(microsecond=0).isoformat().replace("+00:00", "Z")
def create_local_session_identity(codex_home: Path) -> dict[str, Any]:
new_uuid = uuid.uuid7()
new_id = str(new_uuid)
created_ms = new_uuid.time
created_dt_utc = datetime.fromtimestamp(created_ms / 1000, tz=timezone.utc)
rollout_name = f"rollout-{created_dt_utc.strftime('%Y-%m-%dT%H-%M-%S')}-{new_id}.jsonl"
rollout_path = codex_home / "sessions" / created_dt_utc.strftime("%Y") / created_dt_utc.strftime("%m") / created_dt_utc.strftime("%d") / rollout_name
return {
"new_id": new_id,
"created_at_epoch": int(created_dt_utc.timestamp()),
"created_at_z": utc_iso_with_millis(created_dt_utc),
"updated_at_z": utc_iso_seconds(created_dt_utc),
"rollout_path": rollout_path,
}
def rewrite_rollout_for_new_session(rows: list[dict], new_id: str, target_cwd: str, created_at_z: str) -> list[dict]:
rewritten: list[dict] = []
for obj in rows:
cloned = copy.deepcopy(obj)
payload = cloned.get("payload")
if cloned.get("type") == "session_meta" and isinstance(payload, dict):
payload["id"] = new_id
payload["timestamp"] = created_at_z
payload["cwd"] = target_cwd
if cloned.get("type") == "turn_context" and isinstance(payload, dict):
payload["cwd"] = target_cwd
sandbox = payload.get("sandbox_policy")
if isinstance(sandbox, dict):
sandbox["writable_roots"] = [target_cwd]
if (
cloned.get("type") == "response_item"
and isinstance(payload, dict)
and payload.get("type") == "message"
and payload.get("role") == "user"
):
for item in payload.get("content", []):
text_value = item.get("text")
if isinstance(text_value, str):
item["text"] = replace_embedded_cwd(text_value).replace("<cwd-normalized>", target_cwd)
rewritten.append(cloned)
return rewritten
def clone_dynamic_tools(con: sqlite3.Connection, source_id: str, new_id: str) -> int:
try:
rows = con.execute(
"SELECT position, name, description, input_schema, defer_loading FROM thread_dynamic_tools WHERE thread_id = ? ORDER BY position",
(source_id,),
).fetchall()
except sqlite3.OperationalError:
return 0
for row in rows:
con.execute(
"""
INSERT INTO thread_dynamic_tools (thread_id, position, name, description, input_schema, defer_loading)
VALUES (?, ?, ?, ?, ?, ?)
""",
(new_id, row[0], row[1], row[2], row[3], row[4]),
)
return len(rows)
def execute_diverged_imports(
package_root: Path,
codex_home: Path,
source_env: str,
source_package: str,
decisions: list[SessionDecision],
localized_threads: list[dict],
original_threads: dict[str, dict],
) -> dict:
transaction_id = f"sync_{uuid.uuid7()}"
tx_dir = sync_transaction_dir(codex_home, transaction_id)
backups_dir = tx_dir / "backups"
backups_dir.mkdir(parents=True, exist_ok=False)
created_at = now_utc()
backup_file_if_exists(codex_home / "state_5.sqlite", backups_dir / "codex-home" / "state_5.sqlite")
backup_file_if_exists(codex_home / "state_5.sqlite-wal", backups_dir / "codex-home" / "state_5.sqlite-wal")
backup_file_if_exists(codex_home / "state_5.sqlite-shm", backups_dir / "codex-home" / "state_5.sqlite-shm")
backup_file_if_exists(codex_home / "session_index.jsonl", backups_dir / "codex-home" / "session_index.jsonl")
backup_sidecar_files(codex_home, backups_dir)
localized_by_id = {str(row["id"]): row for row in localized_threads}
results = []
con = sqlite3.connect(codex_home / "state_5.sqlite")
for decision in decisions:
if decision.decision != "diverged_lineage":
continue
parent_session_id = str(decision.matched_local_session_id)
localized_thread = localized_by_id[parent_session_id]
source_meta = original_threads[parent_session_id]
source_rollout = package_root / "sessions" / Path(str(source_meta["rollout_path"])).name
incoming_rows = read_jsonl(source_rollout)
new_identity = create_local_session_identity(codex_home)
new_session_id = str(new_identity["new_id"])
target_rollout = Path(str(new_identity["rollout_path"]))
rewritten_rows = rewrite_rollout_for_new_session(
incoming_rows,
new_session_id,
str(localized_thread["cwd"]),
str(new_identity["created_at_z"]),
)
target_rollout.parent.mkdir(parents=True, exist_ok=True)
write_jsonl(target_rollout, rewritten_rows)
parent_row, _parent_rows, _tools = load_local_session_rows(codex_home, parent_session_id)
row_dict = dict(parent_row)
row_dict["id"] = new_session_id
row_dict["rollout_path"] = str(target_rollout)
row_dict["created_at"] = int(new_identity["created_at_epoch"])
row_dict["updated_at"] = int(new_identity["created_at_epoch"])
row_dict["cwd"] = str(localized_thread["cwd"])
row_dict["title"] = f"{row_dict['title']} (sync fork)"
if "sandbox_policy" in row_dict:
row_dict["sandbox_policy"] = json.dumps(
{
"type": "workspace-write",
"writable_roots": [str(localized_thread["cwd"])],
"network_access": False,
"exclude_tmpdir_env_var": False,
"exclude_slash_tmp": False,
},
ensure_ascii=False,
separators=(",", ":"),
)
columns = list(row_dict.keys())
placeholders = ",".join("?" for _ in columns)
con.execute(f"INSERT INTO threads ({','.join(columns)}) VALUES ({placeholders})", [row_dict[column] for column in columns])
clone_dynamic_tools(con, parent_session_id, new_session_id)
replace_or_append_index_row(
codex_home / "session_index.jsonl",
new_session_id,
str(row_dict["title"]),
str(new_identity["updated_at_z"]),
)
upsert_sidecar_row(
codex_home,
"source-mappings.jsonl",
["source_env_fingerprint", "source_session_id", "local_session_id"],
{
"sync_lineage_id": decision.sync_lineage_id,
"source_env_fingerprint": source_env,
"source_package_fingerprint": source_package,
"source_session_id": parent_session_id,
"local_session_id": parent_session_id,
"adoption_mode": "sync-parent",
"created_at": created_at,
"updated_at": created_at,
"is_current_tip_mapping": False,
},
)
upsert_sidecar_row(
codex_home,
"source-mappings.jsonl",
["source_env_fingerprint", "source_session_id", "local_session_id"],
{
"sync_lineage_id": decision.sync_lineage_id,
"source_env_fingerprint": source_env,
"source_package_fingerprint": source_package,
"source_session_id": parent_session_id,
"local_session_id": new_session_id,
"adoption_mode": "sync-forked",
"created_at": created_at,
"updated_at": created_at,
"is_current_tip_mapping": True,
},
)
upsert_sidecar_row(
codex_home,
"snapshots.jsonl",
["local_session_id"],
snapshot_record(row_dict, rewritten_rows, str(decision.sync_lineage_id)),
)
append_sidecar_row(
codex_home,
"forks.jsonl",
{
"fork_id": f"fork_{uuid.uuid7()}",
"sync_lineage_id": decision.sync_lineage_id,
"parent_local_session_id": parent_session_id,
"child_local_session_id": new_session_id,
"fork_point_event_index": int(decision.common_prefix_events),
"fork_point_fingerprint": "",
"created_at": created_at,
"source": "incoming-package-divergence",
},
)
append_sidecar_row(
codex_home,
"imports.jsonl",
{
"import_id": transaction_id,
"created_at": created_at,
"source_env_fingerprint": source_env,
"source_package_fingerprint": source_package,
"source_session_id": parent_session_id,
"matched_local_session_id": new_session_id,
"sync_lineage_id": decision.sync_lineage_id,
"decision": "diverged_lineage",
"execute_mode": "execute",
"notes": decision.reason,
},
)
results.append(
{
"parent_local_session_id": parent_session_id,
"child_local_session_id": new_session_id,
"rollout_path": str(target_rollout),
"sync_lineage_id": decision.sync_lineage_id,
"fork_point_event_index": decision.common_prefix_events,
}
)
con.commit()
con.close()
save_manifest(
tx_dir / "manifest.json",
{
"transaction_id": transaction_id,
"created_at": created_at,
"status": "completed",
"package_root": str(package_root),
"codex_home": str(codex_home),
"decision_counts": {"diverged_lineage": len(results)},
"results": results,
},
)
return {"transaction_id": transaction_id, "results": results}
def existing_mapping_by_source(codex_home: Path) -> dict[tuple[str, str], dict]:
rows = load_sidecar_rows(codex_home, "source-mappings.jsonl")
result: dict[tuple[str, str], dict] = {}
for row in rows:
key = (str(row.get("source_env_fingerprint", "")), str(row.get("source_session_id", "")))
if key != ("", ""):
result[key] = row
return result
def existing_mappings_for_session_id(codex_home: Path, source_session_id: str) -> list[dict]:
rows = load_sidecar_rows(codex_home, "source-mappings.jsonl")
return [row for row in rows if str(row.get("source_session_id", "")) == source_session_id]
def local_session_exists(codex_home: Path, session_id: str) -> bool:
con = sqlite3.connect(codex_home / "state_5.sqlite")
row = con.execute("SELECT 1 FROM threads WHERE id = ?", (session_id,)).fetchone()
con.close()
return row is not None
def resolve_known_mapping(codex_home: Path, source_env: str, source_session_id: str) -> tuple[dict | None, str | None]:
mapping = existing_mapping_by_source(codex_home).get((source_env, source_session_id))
if mapping is not None and local_session_exists(codex_home, str(mapping.get("local_session_id", ""))):
return mapping, "exact-source-env"
legacy_candidates = [
row
for row in existing_mappings_for_session_id(codex_home, source_session_id)
if local_session_exists(codex_home, str(row.get("local_session_id", "")))
]
if len(legacy_candidates) == 1:
return legacy_candidates[0], "source-session-id-fallback"
if len(legacy_candidates) > 1:
current_tip = [row for row in legacy_candidates if bool(row.get("is_current_tip_mapping"))]
if len(current_tip) == 1:
return current_tip[0], "source-session-id-fallback-current-tip"
return None, None
def existing_snapshot_by_local(codex_home: Path) -> dict[str, dict]:
rows = load_sidecar_rows(codex_home, "snapshots.jsonl")
return {str(row["local_session_id"]): row for row in rows if "local_session_id" in row}
def create_lineage_id(seed: str) -> str:
return f"sl_{sha256_text(seed)[:16]}"
def adopt_local_session(codex_home: Path, local_session_id: str, source_env: str, source_session_id: str, adoption_mode: str) -> dict:
local_row, rollout_rows, _ = load_local_session_rows(codex_home, local_session_id)
existing_snapshots = existing_snapshot_by_local(codex_home)
if local_session_id in existing_snapshots:
return {
"status": "already-adopted",
"local_session_id": local_session_id,
"sync_lineage_id": existing_snapshots[local_session_id]["sync_lineage_id"],
}
sync_lineage_id = create_lineage_id(f"{source_env}:{source_session_id}:{local_session_id}")
created_at = now_utc()
upsert_sidecar_row(
codex_home,
"lineages.jsonl",
["sync_lineage_id"],
{
"sync_lineage_id": sync_lineage_id,
"lineage_version": 1,
"created_at": created_at,
"updated_at": created_at,
"origin_hint": {
"source_env_fingerprint": source_env,
"first_source_session_id": source_session_id,
},
"status": "active",
},
)
upsert_sidecar_row(
codex_home,
"source-mappings.jsonl",
["source_env_fingerprint", "source_session_id", "local_session_id"],
{
"sync_lineage_id": sync_lineage_id,
"source_env_fingerprint": source_env,
"source_package_fingerprint": "",
"source_session_id": source_session_id,
"local_session_id": local_session_id,
"adoption_mode": adoption_mode,
"created_at": created_at,
"updated_at": created_at,
"is_current_tip_mapping": True,
},
)
upsert_sidecar_row(
codex_home,
"snapshots.jsonl",
["local_session_id"],
snapshot_record(local_row, rollout_rows, sync_lineage_id),
)
return {
"status": "adopted",
"local_session_id": local_session_id,
"sync_lineage_id": sync_lineage_id,
}
@dataclass
class SessionDecision:
source_session_id: str
matched_local_session_id: str | None
sync_lineage_id: str | None
decision: str
reason: str
incoming_event_count: int
local_event_count: int | None
common_prefix_events: int
proposed_local_session_id: str | None
needs_adoption: bool
def classify_session(
codex_home: Path,
source_env: str,
incoming_thread: dict,
incoming_rows: list[dict],
) -> SessionDecision:
source_session_id = str(incoming_thread["id"])
incoming_fp = make_session_fingerprint(incoming_rows)
mapping, mapping_mode = resolve_known_mapping(codex_home, source_env, source_session_id)
local_candidate_id: str | None = None
sync_lineage_id: str | None = None
needs_adoption = False
if mapping is not None:
local_candidate_id = str(mapping["local_session_id"])
sync_lineage_id = str(mapping["sync_lineage_id"])
else:
con = sqlite3.connect(codex_home / "state_5.sqlite")
con.row_factory = sqlite3.Row
row = con.execute("SELECT id FROM threads WHERE id = ?", (source_session_id,)).fetchone()
con.close()
if row is not None:
local_candidate_id = str(row["id"])
needs_adoption = True
if local_candidate_id is None:
return SessionDecision(
source_session_id=source_session_id,
matched_local_session_id=None,
sync_lineage_id=None,
decision="new_lineage",
reason="No existing lineage mapping or local session id match was found.",
incoming_event_count=incoming_fp["event_count"],