-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_claude_contexts.py
More file actions
768 lines (631 loc) · 28.6 KB
/
Copy pathsync_claude_contexts.py
File metadata and controls
768 lines (631 loc) · 28.6 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
#!/usr/bin/env python3
"""
sync_claude_contexts.py
Fetches company AI context files and installs them into Claude Code's context
hierarchy (~/.claude/).
Two modes — configure ONE in ~/.claude/context-sync.conf:
MODE 1 — Cloudflare Worker (recommended, no GitHub account needed):
SOURCE_URL=https://claude-contexts.akka.io
CONTEXT_API_KEY=<shared key from IT>
MODE 2 — Direct GitHub access (admin / fallback):
GITHUB_TOKEN=<bot PAT with contents:read>
# GITHUB_REPO=akka/org-ai-contexts
# GITHUB_BRANCH=main
MODE 3 — Local copy (cowork / hook mode):
Pass --local-copy to mirror ~/.claude/ into a project .claude/ directory
without any network calls. Intended for use via a UserPromptSubmit hook
so cowork sessions get org context at session start and refreshed every
--cooldown minutes during long-lived sessions.
Installed layout:
~/.claude/
CLAUDE.md ← managed @import block prepended by this script
contexts/
index.md ← navigation guide (what's available and when to use it)
context/
company.md
platform.md
...
skills/
engineering/
SKILL.md ← activatable via /engineering
infosec/
...
commands/
support-triage.md ← slash command /support-triage
The script is idempotent — safe to run repeatedly via a scheduler.
"""
import argparse
import json
import logging
import os
import pathlib
import re
import shutil
import sys
import urllib.error
import urllib.request
from typing import Optional
# ── Defaults ───────────────────────────────────────────────────────────────────
DEFAULT_GITHUB_REPO = "akka/org-ai-contexts"
DEFAULT_GITHUB_BRANCH = "main"
DEFAULT_COOLDOWN_MINS = 360 # 6 hours — matches cron cadence
SCRIPT_REPO = "akka/ai-context-sync"
SCRIPT_BRANCH = "main"
SCRIPT_NAME = "sync_claude_contexts.py"
WATCHER_NAME = "watch_cowork_sessions.py"
SCRIPT_URL = f"https://raw.githubusercontent.com/{SCRIPT_REPO}/{SCRIPT_BRANCH}/{SCRIPT_NAME}"
WATCHER_URL = f"https://raw.githubusercontent.com/{SCRIPT_REPO}/{SCRIPT_BRANCH}/{WATCHER_NAME}"
CLAUDE_DIR = pathlib.Path.home() / ".claude"
CONTEXTS_DIR = CLAUDE_DIR / "contexts"
SKILLS_DIR = CLAUDE_DIR / "skills"
COMMANDS_DIR = CLAUDE_DIR / "commands"
CLAUDE_MD = CLAUDE_DIR / "CLAUDE.md"
CONFIG_FILE = CLAUDE_DIR / "context-sync.conf"
LOG_FILE = CLAUDE_DIR / "context-sync.log"
BACKUPS_DIR = CLAUDE_DIR / "backups"
MAX_BACKUPS = 5
CONTEXTS_SUBDIR = "contexts"
TIMESTAMP_FILE = ".sync-timestamp"
SYNC_BLOCK_START = "<!-- claude-context-sync:start -->"
SYNC_BLOCK_END = "<!-- claude-context-sync:end -->"
# ── Logging ────────────────────────────────────────────────────────────────────
def configure_logging(verbose: bool = False) -> None:
level = logging.DEBUG if verbose else logging.INFO
handlers: list[logging.Handler] = [logging.StreamHandler()]
try:
CLAUDE_DIR.mkdir(parents=True, exist_ok=True)
handlers.append(logging.FileHandler(LOG_FILE, encoding="utf-8"))
except OSError:
pass
logging.basicConfig(
level=level,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
handlers=handlers,
)
log = logging.getLogger(__name__)
# ── Config file parsing ────────────────────────────────────────────────────────
def read_config() -> dict[str, str]:
"""Read key=value pairs from ~/.claude/context-sync.conf."""
config: dict[str, str] = {}
if not CONFIG_FILE.exists():
return config
# 'utf-8-sig' strips a leading BOM if present. Windows PowerShell 5.1's
# Set-Content -Encoding UTF8 writes a UTF-8 BOM, which would otherwise be
# read as part of the first key name (the BOM prefixes "SOURCE_URL") and never match.
for line in CONFIG_FILE.read_text(encoding="utf-8-sig").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
key, _, val = line.partition("=")
config[key.strip()] = val.strip()
return config
def resolve(key: str, cli_val: Optional[str], config: dict) -> Optional[str]:
"""Priority: CLI arg > environment variable > config file."""
if cli_val:
return cli_val
env = os.environ.get(key)
if env:
return env
return config.get(key)
# ── HTTP helper ────────────────────────────────────────────────────────────────
def http_get(url: str, headers: dict[str, str]) -> bytes:
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.read()
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
raise SystemExit(f"[ERROR] HTTP {exc.code} for {url}\n {body[:400]}") from exc
except urllib.error.URLError as exc:
raise SystemExit(f"[ERROR] Network error: {exc.reason}") from exc
# ── File install ───────────────────────────────────────────────────────────────
# Top-level directories under ~/.claude/ that we manage.
MANAGED_TOPS = {"contexts", "skills", "commands"}
def dest_for(path: str) -> Optional[pathlib.Path]:
"""
Map a manifest path (relative to ~/.claude/) to its install destination.
Returns None for paths that should be skipped:
- not under a managed top-level directory (contexts/, skills/, commands/)
- README files (repo navigation, not content)
The source repo stores content under .claude/ already structured to mirror
~/.claude/ — no transformation needed:
contexts/index.md → ~/.claude/contexts/index.md
contexts/context/company.md → ~/.claude/contexts/context/company.md
skills/ciso/SKILL.md → ~/.claude/skills/ciso/SKILL.md
commands/support-triage.md → ~/.claude/commands/support-triage.md
"""
top = path.split("/")[0]
if top not in MANAGED_TOPS:
return None
stem = pathlib.Path(path).stem.lower()
if stem == "readme":
return None
return CLAUDE_DIR / path
# ── Backup ─────────────────────────────────────────────────────────────────────
def backup_existing_files(dry_run: bool) -> None:
"""
Snapshot all files that this script manages into a timestamped backup dir,
keeping the last MAX_BACKUPS snapshots.
Covers: CLAUDE.md, contexts/, skills/, commands/
"""
import datetime
managed: list[pathlib.Path] = []
if CLAUDE_MD.exists():
managed.append(CLAUDE_MD)
for managed_dir in (CONTEXTS_DIR, SKILLS_DIR, COMMANDS_DIR):
if managed_dir.exists():
managed.extend(p for p in managed_dir.rglob("*") if p.is_file())
if not managed:
log.debug("Nothing to back up.")
return
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_root = BACKUPS_DIR / timestamp
if dry_run:
log.info("DRY RUN — would back up %d file(s) to %s", len(managed), backup_root)
return
backup_root.mkdir(parents=True, exist_ok=True)
for src in managed:
# Preserve relative path under ~/.claude/
rel = src.relative_to(CLAUDE_DIR)
dest = backup_root / rel
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
log.debug("Backed up %d file(s) → %s", len(managed), backup_root)
# Prune oldest backups, keep only MAX_BACKUPS (entries may be dirs or stray files)
snapshots = sorted(BACKUPS_DIR.iterdir())
for old in snapshots[:-MAX_BACKUPS]:
if old.is_dir():
shutil.rmtree(old)
else:
old.unlink()
log.debug("Removed old backup %s", old)
# ── Install helpers ────────────────────────────────────────────────────────────
def install_file(path: str, content: str, dry_run: bool) -> Optional[pathlib.Path]:
"""Write a single file to ~/.claude/<path>. Returns dest or None if skipped."""
dest = dest_for(path)
if dest is None:
log.debug(" skipping %s (not a managed path)", path)
return None
log.info(" %s → %s", path, dest)
if not dry_run:
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(content, encoding="utf-8")
return dest
# ── Mode 1: Cloudflare Worker ──────────────────────────────────────────────────
def sync_from_worker(source_url: str, api_key: str, dry_run: bool) -> None:
"""Download manifest from the Cloudflare Worker and install contexts."""
url = source_url.rstrip("/") + "/manifest.json"
log.info("Fetching manifest from %s…", url)
raw = http_get(url, {
"Authorization": f"Bearer {api_key}",
"User-Agent": "claude-context-sync/1.0",
})
manifest = json.loads(raw.decode("utf-8"))
files: dict[str, dict] = manifest.get("files", {})
if not files:
log.warning("Manifest is empty — nothing to install.")
return
log.info("Manifest contains %d file(s), synced at %s", len(files), manifest.get("synced_at", "?"))
backup_existing_files(dry_run)
context_paths: list[str] = []
for path, meta in files.items():
content: str = meta["content"]
dest = install_file(path, content, dry_run)
if dest and path.startswith("contexts/"):
context_paths.append(path)
update_claude_md(context_paths, dry_run)
ensure_cowork_hook(dry_run)
log.info("✓ Sync complete.")
# ── Mode 2: Direct GitHub ──────────────────────────────────────────────────────
def sync_from_github(
token: str,
repo: str,
branch: str,
dry_run: bool,
) -> None:
"""Fetch directly from GitHub API — for admins / fallback only."""
gh_headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github.v3+json",
"User-Agent": "claude-context-sync/1.0",
}
log.info("Fetching file tree from github.com/%s (branch: %s)…", repo, branch)
raw = http_get(
f"https://api.github.com/repos/{repo}/git/trees/{branch}?recursive=1",
gh_headers,
)
tree_data = json.loads(raw.decode("utf-8"))
if tree_data.get("truncated"):
log.warning("GitHub tree response was truncated — some files may be missing.")
md_blobs = [
item for item in tree_data["tree"]
if item["type"] == "blob"
and item["path"].endswith(".md")
and item["path"].split("/")[0] in MANAGED_TOPS
]
if not md_blobs:
log.warning("No managed .md files found in repository — nothing to sync.")
return
log.info("Found %d .md file(s)", len(md_blobs))
backup_existing_files(dry_run)
context_paths: list[str] = []
for blob in md_blobs:
path: str = blob["path"]
raw_url = f"https://raw.githubusercontent.com/{repo}/{branch}/{path}"
log.info(" downloading %s", path)
content = http_get(raw_url, {
"Authorization": f"Bearer {token}",
"User-Agent": "claude-context-sync/1.0",
}).decode("utf-8")
dest = install_file(path, content, dry_run)
if dest and path.startswith("contexts/"):
context_paths.append(path)
update_claude_md(context_paths, dry_run)
ensure_cowork_hook(dry_run)
log.info("✓ Sync complete.")
# ── CLAUDE.md management ───────────────────────────────────────────────────────
def build_sync_block(context_paths: list[str]) -> str:
"""
Build the managed @import block for CLAUDE.md.
context_paths are already relative to ~/.claude/ (e.g. contexts/index.md,
contexts/context/company.md) so they are used as @import paths directly.
"""
lines = [
SYNC_BLOCK_START,
"# Company AI Contexts (auto-synced — do not edit this section manually)",
"",
]
# index.md first if present
index = "contexts/index.md"
if index in context_paths:
lines.append(f"@{index}")
# Group remaining by subdirectory under contexts/
subdir_map: dict[str, list[str]] = {}
for path in sorted(context_paths):
if path == index:
continue
parts = path.split("/")
subdir = parts[1] if len(parts) > 2 else ""
subdir_map.setdefault(subdir, []).append(path)
for subdir in sorted(subdir_map):
if subdir:
lines.append(f"\n## {subdir.replace('-', ' ').replace('_', ' ').title()}")
for path in sorted(subdir_map[subdir]):
lines.append(f"@{path}")
lines.append("")
lines.append(SYNC_BLOCK_END)
return "\n".join(lines) + "\n"
def update_claude_md(context_paths: list[str], dry_run: bool = False) -> None:
block = build_sync_block(context_paths)
if CLAUDE_MD.exists():
existing = CLAUDE_MD.read_text(encoding="utf-8")
if SYNC_BLOCK_START in existing:
new_content = re.sub(
rf"{re.escape(SYNC_BLOCK_START)}.*?{re.escape(SYNC_BLOCK_END)}\n?",
block,
existing,
flags=re.DOTALL,
)
action = "Updated"
else:
new_content = block + "\n" + existing
action = "Prepended to"
else:
new_content = block
action = "Created"
if dry_run:
log.info("DRY RUN — would write %s:\n%s", CLAUDE_MD, new_content)
else:
CLAUDE_MD.write_text(new_content, encoding="utf-8")
log.info("%s %s", action, CLAUDE_MD)
# ── Self-update ────────────────────────────────────────────────────────────────
def self_update(dry_run: bool = False) -> None:
"""
Fetch the canonical script from GitHub and replace the running file if the
content has changed. Re-execs with the same arguments so the new version
handles the rest of the sync run.
"""
this_file = pathlib.Path(__file__).resolve()
log.debug("Checking for script update from %s …", SCRIPT_URL)
try:
latest = http_get(SCRIPT_URL, {"User-Agent": "claude-context-sync/1.0"})
except SystemExit as exc:
log.warning("Self-update check failed: %s — continuing with current version.", exc)
return
current = this_file.read_bytes()
if latest == current:
log.debug("Script is up to date.")
return
log.info("New version of %s available — updating…", SCRIPT_NAME)
if dry_run:
log.info("DRY RUN — would replace %s with latest version.", this_file)
return
# Write atomically via a temp file alongside the target
tmp = this_file.with_suffix(".tmp")
try:
tmp.write_bytes(latest)
tmp.replace(this_file)
except OSError as exc:
log.warning("Self-update failed writing %s: %s — continuing with current version.", this_file, exc)
tmp.unlink(missing_ok=True)
return
log.info("Script updated — restarting with new version…")
os.execv(sys.executable, [sys.executable, str(this_file)] + sys.argv[1:])
def self_update_watcher() -> None:
"""Update the cowork watcher script if a newer version is available."""
watcher_file = CLAUDE_DIR / WATCHER_NAME
if not watcher_file.exists():
return
log.debug("Checking for watcher update from %s …", WATCHER_URL)
try:
latest = http_get(WATCHER_URL, {"User-Agent": "claude-context-sync/1.0"})
except SystemExit as exc:
log.warning("Watcher update check failed: %s — skipping.", exc)
return
if latest == watcher_file.read_bytes():
log.debug("Watcher script is up to date.")
return
log.info("New version of %s available — updating…", WATCHER_NAME)
tmp = watcher_file.with_suffix(".tmp")
try:
tmp.write_bytes(latest)
tmp.replace(watcher_file)
log.info("Watcher script updated.")
except OSError as exc:
log.warning("Watcher update failed: %s", exc)
tmp.unlink(missing_ok=True)
# ── Cowork hook self-healing ───────────────────────────────────────────────────
SETTINGS_FILE = CLAUDE_DIR / "settings.json"
HOOK_MARKER = "--local-copy"
def ensure_cowork_hook(dry_run: bool = False) -> None:
"""
Ensure ~/.claude/settings.json contains a UserPromptSubmit hook that runs
this script in --local-copy mode. Idempotent — skips if already present.
Called at the end of every normal sync so existing users get the hook
automatically on their next cron run without any manual steps.
"""
import sys
hook_cmd = f'{sys.executable} {__file__} --local-copy --target-dir "$PWD/.claude"'
hook_entry = {
"type": "command",
"command": hook_cmd,
}
matcher = {"hooks": [hook_entry]}
if SETTINGS_FILE.exists():
try:
settings = json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
log.warning("Could not parse %s: %s — skipping hook injection.", SETTINGS_FILE, exc)
return
# Remove any old UserPromptSubmit hook entry we may have written previously
hooks = settings.setdefault("hooks", {})
submit_hooks = hooks.get("UserPromptSubmit", [])
cleaned = []
for entry in submit_hooks:
inner = [h for h in entry.get("hooks", []) if HOOK_MARKER not in h.get("command", "")]
if inner:
cleaned.append({"hooks": inner})
if cleaned != submit_hooks:
hooks["UserPromptSubmit"] = cleaned
log.info("Removed legacy UserPromptSubmit cowork hook from %s", SETTINGS_FILE)
# Already present in SessionStart?
session_hooks = hooks.get("SessionStart", [])
for entry in session_hooks:
hooks_list = entry.get("hooks", []) if isinstance(entry, dict) else []
if any(HOOK_MARKER in h.get("command", "") for h in hooks_list):
log.debug("Cowork hook already present in %s — skipping.", SETTINGS_FILE)
return
# Merge into SessionStart
session = hooks.setdefault("SessionStart", [])
if session and isinstance(session[0], dict) and "hooks" in session[0]:
session[0]["hooks"].append(hook_entry)
else:
session.append(matcher)
else:
settings = {"hooks": {"SessionStart": [matcher]}}
if dry_run:
log.info("DRY RUN — would write cowork hook to %s", SETTINGS_FILE)
return
SETTINGS_FILE.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
log.info("Cowork hook added to %s", SETTINGS_FILE)
# ── Mode 3: Local copy (cowork hook) ──────────────────────────────────────────
def _is_within_cooldown(target_dir: pathlib.Path, cooldown_mins: int) -> bool:
"""Return True if a sync has already run within the cooldown window."""
import time
ts_file = target_dir / TIMESTAMP_FILE
if not ts_file.exists():
return False
age_mins = (time.time() - ts_file.stat().st_mtime) / 60
return age_mins < cooldown_mins
def _write_timestamp(target_dir: pathlib.Path) -> None:
import time
ts_file = target_dir / TIMESTAMP_FILE
ts_file.write_text(str(time.time()), encoding="utf-8")
def sync_local_copy(target_dir: pathlib.Path, cooldown_mins: int, dry_run: bool) -> None:
"""
Mirror ~/.claude/contexts/, ~/.claude/skills/, and ~/.claude/commands/ into
<target_dir>/ and inject a managed @import block into <target_dir>/CLAUDE.md.
Uses a cooldown timestamp so repeated hook invocations within a session are
cheap (no-ops after the first copy until the cooldown expires).
"""
if _is_within_cooldown(target_dir, cooldown_mins):
log.info("Local copy skipped — within %d-minute cooldown window.", cooldown_mins)
return
if not CLAUDE_DIR.exists():
raise SystemExit(
f"[ERROR] ~/.claude/ not found. Run the full sync first to populate it."
)
log.info("Copying org context from %s → %s …", CLAUDE_DIR, target_dir)
dirs_to_copy = [
(CONTEXTS_DIR, target_dir / "contexts"),
(SKILLS_DIR, target_dir / "skills"),
(COMMANDS_DIR, target_dir / "commands"),
]
context_paths: list[str] = []
for src_dir, dest_dir in dirs_to_copy:
if not src_dir.exists():
log.debug(" skipping %s (not present in ~/.claude/)", src_dir.name)
continue
for src_file in src_dir.rglob("*"):
if not src_file.is_file():
continue
rel = src_file.relative_to(CLAUDE_DIR)
dest_file = target_dir / rel
log.info(" %s", rel)
if not dry_run:
dest_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src_file, dest_file)
# Collect context paths for CLAUDE.md import block
if src_dir == CONTEXTS_DIR:
# rel is like contexts/context/company.md — strip the leading "contexts/"
context_rel = src_file.relative_to(CONTEXTS_DIR)
path_str = str(context_rel).replace("\\", "/")
if path_str == "index.md":
context_paths.append("index.md")
else:
context_paths.append(f"context/{context_rel.name}" if len(context_rel.parts) == 2 else str(context_rel).replace("\\", "/"))
# Rebuild CLAUDE.md import block in the target dir
_update_target_claude_md(target_dir, context_paths, dry_run)
if not dry_run:
_write_timestamp(target_dir)
log.info("✓ Local copy complete.")
def _update_target_claude_md(target_dir: pathlib.Path, context_paths: list[str], dry_run: bool) -> None:
"""Write the managed sync block into <target_dir>/CLAUDE.md."""
target_claude_md = target_dir / "CLAUDE.md"
# Rebuild import paths relative to the target .claude/ dir
block_lines = [
SYNC_BLOCK_START,
"# Company AI Contexts (auto-synced — do not edit this section manually)",
"",
]
if "index.md" in context_paths:
block_lines.append(f"@contexts/index.md")
subdir_map: dict[str, list[str]] = {}
for path in sorted(context_paths):
if path == "index.md":
continue
top = path.split("/")[0]
subdir_map.setdefault(top, []).append(path)
for subdir in sorted(subdir_map):
block_lines.append(f"\n## {subdir.replace('-', ' ').replace('_', ' ').title()}")
for path in sorted(subdir_map[subdir]):
block_lines.append(f"@contexts/{path}")
block_lines += ["", SYNC_BLOCK_END, ""]
block = "\n".join(block_lines)
if target_claude_md.exists():
existing = target_claude_md.read_text(encoding="utf-8")
if SYNC_BLOCK_START in existing:
new_content = re.sub(
rf"{re.escape(SYNC_BLOCK_START)}.*?{re.escape(SYNC_BLOCK_END)}\n?",
block,
existing,
flags=re.DOTALL,
)
action = "Updated"
else:
new_content = block + "\n" + existing
action = "Prepended to"
else:
new_content = block
action = "Created"
if dry_run:
log.info("DRY RUN — would write %s:\n%s", target_claude_md, new_content)
else:
target_claude_md.parent.mkdir(parents=True, exist_ok=True)
target_claude_md.write_text(new_content, encoding="utf-8")
log.info("%s %s", action, target_claude_md)
# ── Entry point ────────────────────────────────────────────────────────────────
def main() -> None:
parser = argparse.ArgumentParser(
description="Sync company Claude context files to ~/.claude/.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
parser.add_argument(
"--source-url", metavar="URL",
help="Cloudflare Worker URL (e.g. https://claude-contexts.akka.io). "
"Overrides env SOURCE_URL / config file.",
)
parser.add_argument(
"--api-key", metavar="KEY",
help="API key for the Worker endpoint. Overrides env CONTEXT_API_KEY / config file.",
)
parser.add_argument(
"--github-token", metavar="TOKEN",
help="GitHub PAT — only needed for direct GitHub mode. "
"Overrides env GITHUB_TOKEN / config file.",
)
parser.add_argument(
"--repo", metavar="OWNER/REPO", default=None,
help=f"GitHub repo (direct mode, default: {DEFAULT_GITHUB_REPO})",
)
parser.add_argument(
"--branch", metavar="BRANCH", default=None,
help=f"GitHub branch (direct mode, default: {DEFAULT_GITHUB_BRANCH})",
)
parser.add_argument(
"--local-copy", action="store_true",
help="Copy from ~/.claude/ into --target-dir without any network calls. "
"Intended for use in a SessionStart hook for non-cowork sessions.",
)
parser.add_argument(
"--target-dir", metavar="DIR", default=".claude",
help="Destination directory for --local-copy (default: .claude in CWD).",
)
parser.add_argument(
"--cooldown", metavar="MINS", type=int, default=DEFAULT_COOLDOWN_MINS,
help=f"Skip copy if last run was within this many minutes (default: {DEFAULT_COOLDOWN_MINS}). "
"Use 0 to always copy.",
)
parser.add_argument(
"--dry-run", action="store_true",
help="Show what would be done without writing any files",
)
parser.add_argument(
"-v", "--verbose", action="store_true",
help="Enable debug logging",
)
args = parser.parse_args()
configure_logging(args.verbose)
# Self-update before doing anything else so the rest of the run uses the
# new version. Skipped in --local-copy mode (no network, hook path).
if not args.local_copy and not args.dry_run:
self_update()
self_update_watcher()
config = read_config()
if args.local_copy:
target_dir = pathlib.Path(args.target_dir).expanduser().resolve()
sync_local_copy(target_dir, cooldown_mins=args.cooldown, dry_run=args.dry_run)
return
source_url = resolve("SOURCE_URL", args.source_url, config)
api_key = resolve("CONTEXT_API_KEY", args.api_key, config)
gh_token = resolve("GITHUB_TOKEN", args.github_token, config)
repo = resolve("GITHUB_REPO", args.repo, config) or DEFAULT_GITHUB_REPO
branch = resolve("GITHUB_BRANCH", args.branch, config) or DEFAULT_GITHUB_BRANCH
if not args.dry_run:
for d in (CONTEXTS_DIR, SKILLS_DIR, COMMANDS_DIR):
d.mkdir(parents=True, exist_ok=True)
if source_url:
if not api_key:
raise SystemExit(
f"\n[ERROR] CONTEXT_API_KEY not set.\n"
f" Add CONTEXT_API_KEY=<key> to {CONFIG_FILE}\n"
f" or pass --api-key <key>\n"
)
sync_from_worker(source_url, api_key, dry_run=args.dry_run)
elif gh_token:
log.warning(
"Using direct GitHub mode. For employees, configure SOURCE_URL + CONTEXT_API_KEY instead."
)
sync_from_github(gh_token, repo, branch, dry_run=args.dry_run)
else:
raise SystemExit(
f"\n[ERROR] No sync source configured.\n"
f" Add to {CONFIG_FILE}:\n"
f" SOURCE_URL=https://claude-contexts.akka.io\n"
f" CONTEXT_API_KEY=<key from IT>\n"
)
if __name__ == "__main__":
main()