claude-migrate 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cm_import.py ADDED
@@ -0,0 +1,560 @@
1
+ """Import: verify a bundle, propose a path mapping, and plan (or apply) the move."""
2
+ import datetime
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import tarfile
10
+ import tempfile
11
+
12
+ from cm_layout import Layout
13
+ from cm_paths import PathMapper, encode_path
14
+ from cm_secrets import _is_reference
15
+ from cm_rewrite import (rebase_claude_json_home, rebase_home_in_strings, rewrite_claude_json_projects, rewrite_home, rewrite_jsonl,
16
+ rewrite_plugin_files, rewrite_sessions_index)
17
+
18
+ ZSH_BEGIN = "# >>> claude-migrate >>>"
19
+ ZSH_END = "# <<< claude-migrate <<<"
20
+
21
+ MAPPING_HELP = (
22
+ "Edit 'default' (old prefix -> new prefix) to move many projects at once, and add entries to "
23
+ "'projects' (exact old path -> new path) to override single ones. An exact project entry beats the "
24
+ "longest matching prefix; paths matching nothing stay as they are. '_preview' only shows the "
25
+ "result of the current rules and is ignored."
26
+ )
27
+
28
+
29
+ class BundleError(Exception):
30
+ pass
31
+
32
+
33
+ class PlanError(Exception):
34
+ pass
35
+
36
+
37
+ class RunningError(Exception):
38
+ pass
39
+
40
+
41
+ def _bad_component(name):
42
+ """A history folder name must be one plain path component."""
43
+ return (not name or name in (".", "..") or "/" in name or "\\" in name or "\x00" in name)
44
+
45
+
46
+ def _unsafe(rel):
47
+ parts = rel.replace("\\", "/").split("/")
48
+ return os.path.isabs(rel) or ".." in parts or rel == ""
49
+
50
+
51
+ def verify_bundle(bundle):
52
+ """Check every file against the manifest checksums; return the manifest."""
53
+ try:
54
+ tar = tarfile.open(bundle)
55
+ except (OSError, tarfile.TarError) as e:
56
+ raise BundleError("cannot read bundle %s: %s" % (bundle, e))
57
+ with tar:
58
+ try:
59
+ manifest = json.load(tar.extractfile("manifest.json"))
60
+ except (KeyError, ValueError):
61
+ raise BundleError("%s is not a claude-migrate bundle (no valid manifest.json)" % bundle)
62
+ for rel in list(manifest.get("files", {})) + list(manifest.get("symlinks", {})):
63
+ if _unsafe(rel):
64
+ raise BundleError("unsafe path in bundle: %s" % rel)
65
+ if "zsh_sha256" in manifest:
66
+ try:
67
+ snippet = tar.extractfile("zsh-snippet.txt").read()
68
+ except (KeyError, AttributeError):
69
+ raise BundleError("bundle is missing zsh-snippet.txt")
70
+ if hashlib.sha256(snippet).hexdigest() != manifest["zsh_sha256"]:
71
+ raise BundleError("checksum mismatch for zsh-snippet.txt (bundle corrupted or tampered with)")
72
+ for folder in manifest.get("project_folders", {}):
73
+ if _bad_component(folder):
74
+ raise BundleError("unsafe history folder name in bundle: %r" % folder)
75
+ for rel, digest in manifest.get("files", {}).items():
76
+ try:
77
+ f = tar.extractfile("home/" + rel)
78
+ except KeyError:
79
+ raise BundleError("bundle is missing %s" % rel)
80
+ if f is None:
81
+ raise BundleError("bundle entry %s is not a regular file" % rel)
82
+ h = hashlib.sha256()
83
+ for chunk in iter(lambda: f.read(1 << 20), b""):
84
+ h.update(chunk)
85
+ if h.hexdigest() != digest:
86
+ raise BundleError("checksum mismatch for %s (bundle corrupted?)" % rel)
87
+ try:
88
+ Layout.from_manifest(manifest)
89
+ except ValueError as e:
90
+ raise BundleError(str(e))
91
+ return manifest
92
+
93
+
94
+ def propose_mapping(manifest, target_home):
95
+ src_home = manifest["source_home"]
96
+ default = {} if os.path.normpath(src_home) == os.path.normpath(target_home) else {src_home: target_home}
97
+ mapper = PathMapper(default, {})
98
+ return {
99
+ "_help": MAPPING_HELP,
100
+ "default": default,
101
+ "projects": {},
102
+ "_preview": {p: mapper.map(p) for p in manifest.get("projects", [])},
103
+ }
104
+
105
+
106
+ def default_mapping_path(bundle):
107
+ stem = bundle[: -len(".tar.gz")] if bundle.endswith(".tar.gz") else bundle
108
+ return stem + ".mapping.json"
109
+
110
+
111
+ def _name_prefix_map(folder, mapper):
112
+ """Fallback for folders whose original path is unknown: rewrite the encoded name by prefix."""
113
+ best = None
114
+ for table in (mapper.projects, mapper.default):
115
+ for src, dst in table.items():
116
+ s = encode_path(src)
117
+ if (folder == s or folder.startswith(s + "-")) and (best is None or len(s) > len(best[0])):
118
+ best = (s, encode_path(dst))
119
+ if best:
120
+ break
121
+ return folder if best is None else best[1] + folder[len(best[0]):]
122
+
123
+
124
+ def _collisions(pairs, label):
125
+ seen, errors = {}, []
126
+ for old, new in pairs:
127
+ seen.setdefault(new, [])
128
+ if old not in seen[new]:
129
+ seen[new].append(old)
130
+ for new, olds in seen.items():
131
+ if len(olds) > 1:
132
+ errors.append("collision: %s %s all map to %s" % (label, ", ".join(sorted(olds)), new))
133
+ return errors
134
+
135
+
136
+ def build_plan(manifest, mapper, target_home):
137
+ plan = {"projects": [], "folders": [], "errors": [], "warnings": [], "layout": Layout.from_manifest(manifest)}
138
+ for old in manifest.get("projects", []):
139
+ new = mapper.map(old)
140
+ exists = os.path.isdir(new)
141
+ plan["projects"].append({"old": old, "new": new, "exists": exists})
142
+ if not exists:
143
+ plan["warnings"].append("target folder does not exist yet: %s (history is still imported)" % new)
144
+ plan["errors"] += _collisions([(p["old"], p["new"]) for p in plan["projects"]], "projects")
145
+
146
+ for folder, orig in manifest.get("project_folders", {}).items():
147
+ if orig:
148
+ new_folder = encode_path(mapper.map(orig))
149
+ else:
150
+ new_folder = _name_prefix_map(folder, mapper)
151
+ plan["warnings"].append("unresolved project folder %s mapped by name prefix" % folder)
152
+ plan["folders"].append({"old_folder": folder, "new_folder": new_folder, "original_path": orig})
153
+ plan["errors"] += _collisions([(f["old_folder"], f["new_folder"]) for f in plan["folders"]], "history folders")
154
+ return plan
155
+
156
+
157
+ def format_plan(plan, manifest, target_home, mapping_path):
158
+ lines = [
159
+ "Source home: %s" % manifest["source_home"],
160
+ "Target home: %s" % target_home,
161
+ "Mapping: %s" % mapping_path,
162
+ "",
163
+ "Projects (%d):" % len(plan["projects"]),
164
+ ]
165
+ for p in plan["projects"]:
166
+ mark = "ok " if p["exists"] else "warn"
167
+ lines.append(" [%s] %s -> %s" % (mark, p["old"], p["new"]))
168
+ renamed = [f for f in plan["folders"] if f["old_folder"] != f["new_folder"]]
169
+ lines.append("")
170
+ lines.append("History folders: %d total, %d renamed" % (len(plan["folders"]), len(renamed)))
171
+ for w in plan["warnings"]:
172
+ lines.append("warning: " + w)
173
+ for e in plan["errors"]:
174
+ lines.append("ERROR: " + e)
175
+ return "\n".join(lines)
176
+
177
+
178
+ # ---------------------------------------------------------------- shell snippet
179
+
180
+ # The snippet ends up in ~/.zshrc, which runs on every new shell, so only plain definitions are accepted:
181
+ # alias NAME=<one word>, [export] NAME=<one word>, source/. PATH, and comments. A "word" may use quotes and
182
+ # $VAR / ${VAR}, but no command substitution, pipes, semicolons or backticks.
183
+ _ZSH_WORD = (r"""(?:'[^']*'|"(?:[^"\\`$]|\\.|\$[A-Za-z_]\w*|\$\{[A-Za-z_]\w*\})*"|\$[A-Za-z_]\w*"""
184
+ r"""|\$\{[A-Za-z_]\w*\}|[A-Za-z0-9_@%+=:,./~\-])+""")
185
+ _ZSH_ALIAS_RE = re.compile(r"alias\s+([A-Za-z0-9_.:+\-]+)=(" + _ZSH_WORD + ")")
186
+ _ZSH_ASSIGN_RE = re.compile(r"(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)")
187
+ _ZSH_SOURCE_RE = re.compile(r"(?:source|\.)\s+([A-Za-z0-9_@%+=:,./~\-]+)")
188
+ # Claude lines never need to redefine these, and redefining them hijacks everyday commands.
189
+ _ZSH_SHADOWED = {"cd", "ls", "sudo", "su", "doas", "git", "ssh", "scp", "sftp", "curl", "wget", "sh", "bash", "zsh",
190
+ "fish", "rm", "mv", "cp", "ln", "cat", "grep", "find", "open", "brew", "npm", "npx", "node", "yarn",
191
+ "pnpm", "python", "python3", "pip", "pip3", "make", "which", "command", "builtin", "eval", "exec",
192
+ "source", "alias", "unalias", "export", "unset", "set", "env", "kill", "chmod", "chown", "tar",
193
+ "echo", "printf", "test", "type", "sh", "login", "passwd", "gpg", "security", "defaults"}
194
+ # Variables that change how the shell or the dynamic loader finds and runs code.
195
+ _ZSH_FORBIDDEN_VAR = re.compile(
196
+ r"^(DYLD_.*|LD_.*|ZDOTDIR|FPATH|fpath|PROMPT_COMMAND|PROMPT|RPROMPT|PS[0-9]|BASH_ENV|ENV|IFS|SHELL|HOME|"
197
+ r"PERL5OPT|PERL5LIB|PYTHONSTARTUP|PYTHONPATH|NODE_OPTIONS|RUBYOPT|GIT_SSH_COMMAND|GIT_ASKPASS|SSH_ASKPASS|"
198
+ r"EDITOR|VISUAL|PAGER|BROWSER)$")
199
+ # The bundle itself writes these folders, so sourcing from them would run bundle-supplied code.
200
+ _ZSH_BUNDLE_WRITTEN_RE = re.compile(r"(^|/)\.claude")
201
+
202
+
203
+ def safe_zsh_line(line):
204
+ if "\n" in line or "\r" in line or "\x00" in line:
205
+ return False
206
+ s = line.strip()
207
+ if not s or s.startswith("#"):
208
+ return True
209
+ m = _ZSH_ALIAS_RE.fullmatch(s)
210
+ if m:
211
+ return m.group(1) not in _ZSH_SHADOWED
212
+ m = _ZSH_SOURCE_RE.fullmatch(s)
213
+ if m:
214
+ path = m.group(1)
215
+ return ".." not in path.split("/") and not _ZSH_BUNDLE_WRITTEN_RE.search(path)
216
+ m = _ZSH_ASSIGN_RE.fullmatch(s)
217
+ if not m or _ZSH_FORBIDDEN_VAR.match(m.group(1)):
218
+ return False
219
+ value = m.group(2)
220
+ if "$(" in value:
221
+ return _is_reference(value)
222
+ return re.fullmatch(_ZSH_WORD, value) is not None
223
+
224
+
225
+ def _snippet_lines(tar):
226
+ try:
227
+ text = tar.extractfile("zsh-snippet.txt").read().decode("utf-8")
228
+ except (KeyError, AttributeError):
229
+ return []
230
+ return [l for l in text.splitlines() if l.strip()]
231
+
232
+
233
+ def zsh_lines_from_bundle(bundle):
234
+ """(lines that are safe to install, lines that were rejected) after verifying the bundle."""
235
+ verify_bundle(bundle)
236
+ with tarfile.open(bundle) as tar:
237
+ lines = _snippet_lines(tar)
238
+ return [l for l in lines if safe_zsh_line(l)], [l for l in lines if not safe_zsh_line(l)]
239
+
240
+
241
+ # ---------------------------------------------------------------- apply
242
+
243
+ def is_claude_running():
244
+ try:
245
+ out = subprocess.run(["ps", "-axo", "pid=,comm="], capture_output=True, text=True, timeout=10).stdout
246
+ except (OSError, subprocess.SubprocessError):
247
+ return False
248
+ me = str(os.getpid())
249
+ for line in out.splitlines():
250
+ pid, _, comm = line.strip().partition(" ")
251
+ if pid != me and os.path.basename(comm.strip()) == "claude":
252
+ return True
253
+ return False
254
+
255
+
256
+ def merge_claude_json(existing, incoming):
257
+ """Bundle content wins for config; dict sections are unioned; target-only keys (identity) stay."""
258
+ out = dict(existing)
259
+ for k, v in incoming.items():
260
+ if isinstance(v, dict) and isinstance(existing.get(k), dict):
261
+ merged = dict(existing[k])
262
+ merged.update(v)
263
+ out[k] = merged
264
+ else:
265
+ out[k] = v
266
+ return out
267
+
268
+
269
+ def _json_load(path):
270
+ with open(path, encoding="utf-8") as f:
271
+ return json.load(f)
272
+
273
+
274
+ def _json_dump(obj, path):
275
+ with open(path, "w", encoding="utf-8") as f:
276
+ json.dump(obj, f, indent=2)
277
+
278
+
279
+ def _read_bytes(path):
280
+ with open(path, "rb") as f:
281
+ return f.read()
282
+
283
+
284
+ def _extract(bundle, manifest, stage):
285
+ with tarfile.open(bundle) as tar:
286
+ for rel in manifest["files"]:
287
+ member = tar.getmember("home/" + rel)
288
+ dest = os.path.join(stage, rel)
289
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
290
+ with open(dest, "wb") as out:
291
+ shutil.copyfileobj(tar.extractfile(member), out)
292
+ os.chmod(dest, member.mode & 0o777 or 0o600)
293
+ os.utime(dest, (member.mtime, member.mtime))
294
+ lines = _snippet_lines(tar)
295
+ return lines
296
+
297
+
298
+ def _config_dirs(stage, layout):
299
+ return [os.path.join(stage, c) for c in layout.config_dirs if os.path.isdir(os.path.join(stage, c))]
300
+
301
+
302
+ def _replace_file(tmp_path, final_path):
303
+ shutil.copymode(final_path, tmp_path)
304
+ os.replace(tmp_path, final_path)
305
+
306
+
307
+ def _rewrite_claude_json(path, mapper, old_home, new_home, home_changed):
308
+ data = rewrite_claude_json_projects(_json_load(path), mapper)
309
+ if home_changed:
310
+ data = rebase_claude_json_home(data, old_home, new_home)
311
+ _json_dump(data, path)
312
+
313
+
314
+ def _remap_folders(path, folder_map):
315
+ """Rename a history-folder component (the one right after 'projects') inside a path."""
316
+ parts = path.split("/")
317
+ for i in range(1, len(parts)):
318
+ if parts[i - 1] == "projects" and parts[i] in folder_map:
319
+ parts[i] = folder_map[parts[i]]
320
+ return "/".join(parts)
321
+
322
+
323
+ def _rewrite_stage(stage, plan, mapper, old_home, new_home):
324
+ folder_map = {f["old_folder"]: f["new_folder"] for f in plan["folders"] if f["old_folder"] != f["new_folder"]}
325
+ home_changed = os.path.normpath(old_home) != os.path.normpath(new_home)
326
+ layout = plan["layout"]
327
+ for cdir in _config_dirs(stage, layout):
328
+ pdir = os.path.join(cdir, "projects")
329
+ if os.path.isdir(pdir):
330
+ # two-phase rename so swapped/overlapping names cannot clobber each other
331
+ moved = []
332
+ for i, (old, new) in enumerate(folder_map.items()):
333
+ if _bad_component(old) or _bad_component(new):
334
+ raise BundleError("unsafe history folder name: %r -> %r" % (old, new))
335
+ if os.path.isdir(os.path.join(pdir, old)):
336
+ tmp = os.path.join(pdir, ".mig-%d" % i)
337
+ os.rename(os.path.join(pdir, old), tmp)
338
+ moved.append((tmp, os.path.join(pdir, new)))
339
+ for tmp, final in moved:
340
+ os.rename(tmp, final)
341
+ for dp, _dn, fn in os.walk(pdir):
342
+ for f in fn:
343
+ p = os.path.join(dp, f)
344
+ if f.endswith(".jsonl"):
345
+ rewrite_jsonl(p, p + ".mig", mapper)
346
+ _replace_file(p + ".mig", p)
347
+ elif f == "sessions-index.json":
348
+ _json_dump(rewrite_sessions_index(_json_load(p), mapper, old_home, new_home, folder_map), p)
349
+ hist = os.path.join(cdir, "history.jsonl")
350
+ if os.path.isfile(hist):
351
+ rewrite_jsonl(hist, hist + ".mig", mapper, keys=("project",))
352
+ _replace_file(hist + ".mig", hist)
353
+ cj = os.path.join(cdir, ".claude.json")
354
+ if os.path.isfile(cj):
355
+ _rewrite_claude_json(cj, mapper, old_home, new_home, home_changed)
356
+ if home_changed:
357
+ for name in os.listdir(cdir):
358
+ if name.startswith("settings") and name.endswith(".json") and os.path.isfile(os.path.join(cdir, name)):
359
+ p = os.path.join(cdir, name)
360
+ _json_dump(rebase_home_in_strings(_json_load(p), old_home, new_home), p)
361
+ if os.path.isdir(os.path.join(cdir, "plugins")):
362
+ rewrite_plugin_files(os.path.join(cdir, "plugins"), old_home, new_home)
363
+ top_cj = os.path.join(stage, ".claude.json")
364
+ if os.path.isfile(top_cj):
365
+ _rewrite_claude_json(top_cj, mapper, old_home, new_home, home_changed)
366
+ if home_changed:
367
+ for d in layout.tool_dirs:
368
+ base = os.path.join(stage, d)
369
+ for dp, _dn, fn in os.walk(base):
370
+ for f in fn:
371
+ if f.endswith(".json"):
372
+ p = os.path.join(dp, f)
373
+ _json_dump(rebase_home_in_strings(_json_load(p), old_home, new_home), p)
374
+
375
+
376
+ def _hardcoded_home_warnings(stage, old_home, layout):
377
+ out = []
378
+ for cdir in _config_dirs(stage, layout):
379
+ for sub in ("hooks", "commands"):
380
+ for dp, _dn, fn in os.walk(os.path.join(cdir, sub)):
381
+ for f in fn:
382
+ p = os.path.join(dp, f)
383
+ try:
384
+ if old_home in _read_bytes(p).decode("utf-8"):
385
+ out.append("%s still mentions the old home %s (edit it by hand)"
386
+ % (os.path.relpath(p, stage), old_home))
387
+ except UnicodeDecodeError:
388
+ pass
389
+ return out
390
+
391
+
392
+ class _Installer:
393
+ def __init__(self, target_home, backup_root):
394
+ self.home, self.backup_root = target_home, backup_root
395
+ self.written = 0
396
+
397
+ def backup(self, dest):
398
+ rel = os.path.relpath(dest, self.home)
399
+ b = os.path.join(self.backup_root, rel)
400
+ os.makedirs(os.path.dirname(b), exist_ok=True)
401
+ if os.path.islink(dest):
402
+ os.symlink(os.readlink(dest), b)
403
+ elif os.path.isdir(dest):
404
+ shutil.copytree(dest, b, symlinks=True)
405
+ else:
406
+ shutil.copy2(dest, b)
407
+
408
+ def clear(self, dest):
409
+ if os.path.islink(dest) or os.path.isfile(dest):
410
+ os.remove(dest)
411
+ elif os.path.isdir(dest):
412
+ shutil.rmtree(dest)
413
+
414
+ def install_file(self, src, rel):
415
+ dest = os.path.join(self.home, rel)
416
+ if os.path.basename(rel) == ".claude.json" and os.path.isfile(dest) and not os.path.islink(dest):
417
+ try:
418
+ existing = _json_load(dest)
419
+ except ValueError:
420
+ existing = None
421
+ if existing is not None:
422
+ merged = merge_claude_json(existing, _json_load(src))
423
+ if merged == existing:
424
+ return
425
+ self.backup(dest)
426
+ _json_dump(merged, dest)
427
+ self.written += 1
428
+ return
429
+ if os.path.isfile(dest) and not os.path.islink(dest) and _read_bytes(dest) == _read_bytes(src):
430
+ return
431
+ if os.path.lexists(dest):
432
+ self.backup(dest)
433
+ self.clear(dest)
434
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
435
+ shutil.copy2(src, dest)
436
+ self.written += 1
437
+ # a database arrives complete; a write-ahead log left by an older one would be replayed onto it
438
+ for side in ("-wal", "-shm"):
439
+ if os.path.lexists(dest + side):
440
+ self.backup(dest + side)
441
+ self.clear(dest + side)
442
+
443
+ def install_link(self, rel, target):
444
+ dest = os.path.join(self.home, rel)
445
+ if os.path.islink(dest) and os.readlink(dest) == target:
446
+ return
447
+ if os.path.lexists(dest):
448
+ self.backup(dest)
449
+ self.clear(dest)
450
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
451
+ os.symlink(target, dest)
452
+ self.written += 1
453
+
454
+
455
+ def _install_zsh(inst, lines, old_home, new_home):
456
+ """Install/replace the marked block. Returns a warning if an existing block differed (user edits)."""
457
+ rebased = [rebase_home_in_strings(l, old_home, new_home) for l in lines]
458
+ body = [("# TODO(claude-migrate): set the secret, then uncomment: " + l) if "<MASKED>" in l else l
459
+ for l in rebased]
460
+ block = "\n".join([ZSH_BEGIN] + body + [ZSH_END]) + "\n"
461
+ path = os.path.join(inst.home, ".zshrc")
462
+ old = _read_bytes(path).decode("utf-8", "replace") if os.path.isfile(path) else ""
463
+ existing = re.search(re.escape(ZSH_BEGIN) + r".*?" + re.escape(ZSH_END), old, flags=re.S)
464
+ warning = None
465
+ if existing and existing.group(0).strip() != block.strip():
466
+ warning = ("the claude-migrate block in ~/.zshrc differed from the bundle's (edits such as filled-in "
467
+ "keys are replaced); your previous ~/.zshrc is in the backup folder")
468
+ stripped = re.sub(re.escape(ZSH_BEGIN) + r".*?" + re.escape(ZSH_END) + r"\n?", "", old, flags=re.S)
469
+ if stripped and not stripped.endswith("\n"):
470
+ stripped += "\n"
471
+ new = stripped + block
472
+ if new == old:
473
+ return warning
474
+ if os.path.isfile(path):
475
+ inst.backup(path)
476
+ with open(path, "w", encoding="utf-8") as f:
477
+ f.write(new)
478
+ inst.written += 1
479
+ return warning
480
+
481
+
482
+ def post_checks(target_home, plan):
483
+ """Return (problems, warnings) about the state of target_home after an import."""
484
+ problems, warnings = [], []
485
+ config_dirs = (plan.get("layout") or Layout.from_manifest({})).config_dirs
486
+ for f in plan.get("folders", []):
487
+ if not any(os.path.isdir(os.path.join(target_home, c, "projects", f["new_folder"])) for c in config_dirs):
488
+ problems.append("history folder missing after import: %s" % f["new_folder"])
489
+ jsons = [os.path.join(target_home, ".claude.json")]
490
+ for c in config_dirs:
491
+ base = os.path.join(target_home, c)
492
+ jsons += [os.path.join(base, ".claude.json"), os.path.join(base, "settings.json"),
493
+ os.path.join(base, "plugins", "installed_plugins.json"),
494
+ os.path.join(base, "plugins", "known_marketplaces.json")]
495
+ for f in plan.get("folders", []):
496
+ jsons.append(os.path.join(base, "projects", f["new_folder"], "sessions-index.json"))
497
+ if os.path.isdir(base):
498
+ for name in os.listdir(base):
499
+ p = os.path.join(base, name)
500
+ if os.path.islink(p) and not os.path.exists(p):
501
+ warnings.append("dangling symlink %s -> %s" % (p, os.readlink(p)))
502
+ for p in jsons:
503
+ if os.path.isfile(p):
504
+ try:
505
+ _json_load(p)
506
+ except ValueError:
507
+ problems.append("invalid JSON after import: %s" % p)
508
+ return problems, warnings
509
+
510
+
511
+ def apply_import(bundle, mapper, target_home, force=False, zsh=False, now=None):
512
+ manifest = verify_bundle(bundle)
513
+ plan = build_plan(manifest, mapper, target_home)
514
+ if plan["errors"]:
515
+ raise PlanError("; ".join(plan["errors"]))
516
+ if not force and is_claude_running():
517
+ raise RunningError("Claude Code is running; quit it first (or pass --force)")
518
+ os.makedirs(target_home, exist_ok=True)
519
+ old_home, new_home = manifest["source_home"], target_home
520
+ stamp = (now or datetime.datetime.now()).strftime("%Y%m%d-%H%M%S")
521
+ backup_root = os.path.join(target_home, ".claude-migrate-backup-" + stamp)
522
+ stage = tempfile.mkdtemp(prefix=".claude-migrate-stage-", dir=target_home)
523
+ inst = _Installer(target_home, backup_root)
524
+ warnings = []
525
+ try:
526
+ raw_zsh = _extract(bundle, manifest, stage)
527
+ zsh_lines = [l for l in raw_zsh if safe_zsh_line(l)]
528
+ for l in raw_zsh:
529
+ if not safe_zsh_line(l):
530
+ warnings.append("skipped a line of the bundle's ~/.zshrc snippet that is not a plain "
531
+ "alias/export/source definition: %r" % l[:80])
532
+ if os.path.normpath(old_home) != os.path.normpath(new_home):
533
+ warnings += _hardcoded_home_warnings(stage, old_home, plan["layout"])
534
+ _rewrite_stage(stage, plan, mapper, old_home, new_home)
535
+ for dp, _dn, fn in os.walk(stage):
536
+ for f in sorted(fn):
537
+ p = os.path.join(dp, f)
538
+ inst.install_file(p, os.path.relpath(p, stage))
539
+ folder_map = {f["old_folder"]: f["new_folder"] for f in plan["folders"] if f["old_folder"] != f["new_folder"]}
540
+ for rel, target in manifest.get("symlinks", {}).items():
541
+ inst.install_link(_remap_folders(rel, folder_map),
542
+ _remap_folders(rewrite_home(target, old_home, new_home), folder_map))
543
+ zsh_installed = False
544
+ if zsh:
545
+ zsh_warning = _install_zsh(inst, zsh_lines, old_home, new_home)
546
+ if zsh_warning:
547
+ warnings.append(zsh_warning)
548
+ zsh_installed = True
549
+ finally:
550
+ shutil.rmtree(stage, ignore_errors=True)
551
+ problems, post_warnings = post_checks(target_home, plan)
552
+ return {
553
+ "backup": backup_root if os.path.isdir(backup_root) else None,
554
+ "written": inst.written,
555
+ "problems": problems,
556
+ "warnings": warnings + post_warnings + plan["warnings"],
557
+ "zsh_lines": [rebase_home_in_strings(l, old_home, new_home) for l in zsh_lines],
558
+ "zsh_installed": zsh_installed,
559
+ "plan": plan,
560
+ }
package/cm_layout.py ADDED
@@ -0,0 +1,122 @@
1
+ """Work out which folders in a home directory belong to Claude Code, instead of assuming their names."""
2
+ import os
3
+ import re
4
+
5
+ # A folder is a Claude Code config dir when it holds conversations, or settings next to other config.
6
+ _STRONG_MARKERS = ("projects", "history.jsonl")
7
+ _CONFIG_MARKERS = ("skills", "commands", "agents", "hooks", "plugins", "CLAUDE.md")
8
+ # Left behind by this tool itself or by archiving; never a setup of its own.
9
+ _IGNORED_RE = re.compile(r"^\.claude-migrate-|\.(zip|bak|tmp|backup|tar|gz)$|^\.claude\.json", re.I)
10
+ # Dot-folders in home that belong to Claude tooling: Claude's own, and routers that sit in front of it.
11
+ _TOOL_NAME_RE = re.compile(r"^\.(claude-|omniroute)", re.I)
12
+ _CONFIG_DIR_VAR_RE = re.compile(r"CLAUDE_CONFIG_DIR=[\"']?(?:~|\$HOME|\$\{HOME\})/(\.[\w.\-]+)")
13
+ _ID_RE = re.compile(r"^[a-z][a-z0-9_]*$")
14
+ _NAME_RE = re.compile(r"^\.[\w.\-]+$")
15
+
16
+ # Friendly ids and labels for tools we recognise; anything else still gets a checkbox of its own.
17
+ _TOOL_IDS = {"claude_code_router": "router"}
18
+ _TOOL_LABELS = {
19
+ "claude_mem": "claude-mem data",
20
+ "router": "Claude Code Router config",
21
+ "omniroute": "OmniRoute settings and usage",
22
+ }
23
+ _LEGACY = ((".claude", ".claude-work"), {".claude-mem": "claude_mem", ".claude-code-router": "router"})
24
+
25
+ PRIMARY = ".claude"
26
+ # Ids the fixed checkboxes already use; a tool folder that slugs to one of them is prefixed.
27
+ _RESERVED_IDS = {"settings", "claude_md", "skills", "commands", "agents", "hooks", "mcp", "plugins", "marketplaces",
28
+ "history", "memory", "prompt_history", "file_history", "shell", "work_account", "other"}
29
+
30
+
31
+ def default_layout():
32
+ """The two accounts and two tools older bundles and callers without a home to inspect assume."""
33
+ return Layout(*_LEGACY)
34
+
35
+
36
+ def _slug(name):
37
+ return re.sub(r"[^a-z0-9]+", "_", name.lstrip(".").lower()).strip("_") or "tool"
38
+
39
+
40
+ def _has(base, name):
41
+ return os.path.exists(os.path.join(base, name))
42
+
43
+
44
+ def _looks_like_config_dir(base):
45
+ if any(_has(base, m) for m in _STRONG_MARKERS):
46
+ return True
47
+ return _has(base, "settings.json") and any(_has(base, m) for m in _CONFIG_MARKERS)
48
+
49
+
50
+ class Layout:
51
+ def __init__(self, config_dirs, tool_dirs):
52
+ self.config_dirs = tuple(config_dirs)
53
+ self.tool_dirs = dict(tool_dirs)
54
+
55
+ @property
56
+ def root_dirs(self):
57
+ return self.config_dirs + tuple(self.tool_dirs)
58
+
59
+ def is_extra_account(self, name):
60
+ return name in self.config_dirs and name != PRIMARY
61
+
62
+ def components(self):
63
+ from cm_bundle import CORE_COMPONENTS # late: cm_bundle imports this module
64
+ extra = [d for d in self.config_dirs if d != PRIMARY]
65
+ tools = [(cid, _TOOL_LABELS.get(cid, "~/%s files" % name), "~/" + name)
66
+ for name, cid in sorted(self.tool_dirs.items(), key=lambda kv: kv[1])]
67
+ out = []
68
+ for cid, label, hint in CORE_COMPONENTS:
69
+ if cid == "shell":
70
+ out += tools # tools sit between the Claude parts and the machine-level extras
71
+ if cid == "work_account":
72
+ hint = ", ".join("~/" + d for d in extra) or "another CLAUDE_CONFIG_DIR"
73
+ out.append((cid, label, hint))
74
+ return out
75
+
76
+ def to_manifest(self):
77
+ return {"config_dirs": list(self.config_dirs), "tool_dirs": dict(self.tool_dirs)}
78
+
79
+ @classmethod
80
+ def from_manifest(cls, manifest):
81
+ raw = manifest.get("layout")
82
+ if raw is None:
83
+ return default_layout()
84
+ dirs, tools = raw.get("config_dirs", []), raw.get("tool_dirs", {})
85
+ for name in list(dirs) + list(tools):
86
+ if not isinstance(name, str) or not _NAME_RE.match(name) or name in (".", ".."):
87
+ raise ValueError("bundle names an unsafe folder: %r" % (name,))
88
+ for cid in tools.values():
89
+ if not isinstance(cid, str) or not _ID_RE.match(cid):
90
+ raise ValueError("bundle has an invalid component id: %r" % (cid,))
91
+ return cls(dirs, tools)
92
+
93
+
94
+ def _zshrc_config_dirs(home):
95
+ try:
96
+ with open(os.path.join(home, ".zshrc"), encoding="utf-8", errors="replace") as f:
97
+ return set(_CONFIG_DIR_VAR_RE.findall(f.read()))
98
+ except OSError:
99
+ return set()
100
+
101
+
102
+ def discover(home):
103
+ """Look at `home` and report its Claude config dirs and Claude-related tool dirs."""
104
+ named = _zshrc_config_dirs(home)
105
+ configs, tools, taken = [], {}, set()
106
+ for name in sorted(os.listdir(home)):
107
+ base = os.path.join(home, name)
108
+ if not _NAME_RE.match(name) or _IGNORED_RE.search(name):
109
+ continue
110
+ declared = name == PRIMARY or name in named # kept even when broken, so the export can say so
111
+ if not os.path.isdir(base) and not (declared and os.path.islink(base)):
112
+ continue
113
+ if declared or (name.startswith(".claude") and _looks_like_config_dir(base)):
114
+ configs.append(name)
115
+ elif _TOOL_NAME_RE.match(name):
116
+ cid = _slug(name)
117
+ cid = _TOOL_IDS.get(cid, cid)
118
+ if cid in taken or cid in _RESERVED_IDS:
119
+ cid = "tool_" + cid
120
+ taken.add(cid)
121
+ tools[name] = cid
122
+ return Layout(configs, tools)