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
|
#!/usr/bin/env python3
"""
Compare and sync skill folders between Codex and Claude.
Default behavior is report-only. Use --apply to perform sync.
"""
from __future__ import annotations
import argparse
import hashlib
import os
from datetime import datetime
from pathlib import Path
import shutil
import sys
DEFAULT_CODEX = Path("这里写你的电脑的地址")
DEFAULT_CLAUDE = Path("这里写你的电脑的地址")
IGNORE_DIR_NAMES = {".git", ".idea", ".vscode", "__pycache__", ".pytest_cache", ".mypy_cache"}
IGNORE_FILE_NAMES = {".DS_Store"}
TIME_EPSILON = 1.0
def format_time(timestamp: float) -> str:
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
def list_skill_dirs(root: Path) -> tuple[dict[str, Path], list[str]]:
if not root.exists():
raise FileNotFoundError(f"Root path does not exist: {root}")
if not root.is_dir():
raise NotADirectoryError(f"Root path is not a directory: {root}")
skills: dict[str, Path] = {}
ignored: list[str] = []
for entry in sorted(root.iterdir(), key=lambda p: p.name):
if not entry.is_dir():
continue
if entry.name.startswith("."):
ignored.append(entry.name)
continue
if not (entry / "SKILL.md").is_file():
continue
skills[entry.name] = entry
return skills, ignored
def dir_state(path: Path) -> tuple[str, float, int]:
hasher = hashlib.sha256()
latest_mtime = path.stat().st_mtime
file_count = 0
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if d not in IGNORE_DIR_NAMES]
dirs.sort()
files = sorted(f for f in files if f not in IGNORE_FILE_NAMES)
rel_dir = os.path.relpath(root, path)
if rel_dir == ".":
rel_dir = ""
hasher.update(f"D|{rel_dir}\n".encode())
try:
latest_mtime = max(latest_mtime, os.stat(root).st_mtime)
except FileNotFoundError:
continue
for name in files:
file_path = Path(root) / name
rel_path = os.path.relpath(file_path, path)
if file_path.is_symlink():
try:
target = os.readlink(file_path)
except OSError:
target = ""
hasher.update(f"L|{rel_path}\n{target}\n".encode())
try:
latest_mtime = max(latest_mtime, file_path.lstat().st_mtime)
except FileNotFoundError:
pass
continue
if not file_path.is_file():
continue
stat = file_path.stat()
latest_mtime = max(latest_mtime, stat.st_mtime)
file_count += 1
hasher.update(f"F|{rel_path}\n{stat.st_size}\n".encode())
with open(file_path, "rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
hasher.update(chunk)
return hasher.hexdigest(), latest_mtime, file_count
def build_plan(
codex_skills: dict[str, Path],
claude_skills: dict[str, Path],
codex_root: Path,
claude_root: Path,
prefer: str | None,
) -> tuple[list[dict], list[str], list[dict]]:
actions: list[dict] = []
identical: list[str] = []
conflicts: list[dict] = []
all_names = sorted(set(codex_skills) | set(claude_skills))
for name in all_names:
codex_path = codex_skills.get(name)
claude_path = claude_skills.get(name)
if codex_path and not claude_path:
actions.append(
{
"name": name,
"src": codex_path,
"dst": claude_root / name,
"reason": "only in codex",
"direction": "codex -> claude",
}
)
continue
if claude_path and not codex_path:
actions.append(
{
"name": name,
"src": claude_path,
"dst": codex_root / name,
"reason": "only in claude",
"direction": "claude -> codex",
}
)
continue
if not codex_path or not claude_path:
continue
codex_hash, codex_mtime, _ = dir_state(codex_path)
claude_hash, claude_mtime, _ = dir_state(claude_path)
if codex_hash == claude_hash:
identical.append(name)
continue
time_delta = codex_mtime - claude_mtime
if abs(time_delta) <= TIME_EPSILON:
if prefer == "codex":
actions.append(
{
"name": name,
"src": codex_path,
"dst": claude_path,
"reason": "same mtime, prefer codex",
"direction": "codex -> claude",
"codex_mtime": codex_mtime,
"claude_mtime": claude_mtime,
}
)
elif prefer == "claude":
actions.append(
{
"name": name,
"src": claude_path,
"dst": codex_path,
"reason": "same mtime, prefer claude",
"direction": "claude -> codex",
"codex_mtime": codex_mtime,
"claude_mtime": claude_mtime,
}
)
else:
conflicts.append(
{
"name": name,
"codex_mtime": codex_mtime,
"claude_mtime": claude_mtime,
}
)
continue
if time_delta > 0:
actions.append(
{
"name": name,
"src": codex_path,
"dst": claude_path,
"reason": "codex newer",
"direction": "codex -> claude",
"codex_mtime": codex_mtime,
"claude_mtime": claude_mtime,
}
)
else:
actions.append(
{
"name": name,
"src": claude_path,
"dst": codex_path,
"reason": "claude newer",
"direction": "claude -> codex",
"codex_mtime": codex_mtime,
"claude_mtime": claude_mtime,
}
)
return actions, identical, conflicts
def print_report(
actions: list[dict],
identical: list[str],
conflicts: list[dict],
codex_root: Path,
claude_root: Path,
apply: bool,
ignored_codex: list[str],
ignored_claude: list[str],
) -> None:
print("Skill sync report")
print(f"Codex: {codex_root}")
print(f"Claude: {claude_root}")
if ignored_codex:
print(f"Ignored in Codex: {', '.join(sorted(ignored_codex))}")
if ignored_claude:
print(f"Ignored in Claude: {', '.join(sorted(ignored_claude))}")
print("\nPlanned sync actions:")
if not actions:
print("- none")
else:
for item in actions:
codex_mtime = item.get("codex_mtime")
claude_mtime = item.get("claude_mtime")
details = []
if codex_mtime is not None:
details.append(f"codex mtime: {format_time(codex_mtime)}")
if claude_mtime is not None:
details.append(f"claude mtime: {format_time(claude_mtime)}")
detail_text = f" ({', '.join(details)})" if details else ""
print(f"- {item['name']}: {item['direction']} [{item['reason']}]" + detail_text)
print("\nConflicts:")
if not conflicts:
print("- none")
else:
for item in conflicts:
print(
f"- {item['name']}: same mtime but different content "
f"(codex {format_time(item['codex_mtime'])}, claude {format_time(item['claude_mtime'])})"
)
print(f"\nUp-to-date skills: {len(identical)}")
if not apply:
print("\nDry run only. Re-run with --apply to sync.")
def apply_actions(actions: list[dict]) -> None:
for item in actions:
src = Path(item["src"])
dst = Path(item["dst"])
if dst.exists():
if dst.is_dir():
shutil.rmtree(dst)
else:
dst.unlink()
shutil.copytree(src, dst, symlinks=True)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Sync Codex and Claude skill folders")
parser.add_argument("--codex", type=Path, default=DEFAULT_CODEX, help="Codex skill root")
parser.add_argument("--claude", type=Path, default=DEFAULT_CLAUDE, help="Claude skill root")
parser.add_argument("--apply", action="store_true", help="Apply sync actions")
parser.add_argument(
"--prefer",
choices=["codex", "claude"],
help="Break ties when mtimes are equal",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
try:
codex_skills, ignored_codex = list_skill_dirs(args.codex)
claude_skills, ignored_claude = list_skill_dirs(args.claude)
except (FileNotFoundError, NotADirectoryError) as exc:
print(str(exc), file=sys.stderr)
return 2
actions, identical, conflicts = build_plan(
codex_skills,
claude_skills,
args.codex,
args.claude,
args.prefer,
)
print_report(
actions,
identical,
conflicts,
args.codex,
args.claude,
args.apply,
ignored_codex,
ignored_claude,
)
if args.apply and actions:
apply_actions(actions)
print("\nSync complete.")
elif args.apply and not actions:
print("\nNo changes to apply.")
if conflicts and not args.prefer:
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
|