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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Hackoak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # claude-migrate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Move your [Claude Code](https://claude.com/claude-code) setup to a new Mac: settings, skills, commands, hooks, MCP servers, plugins, and (if you want them) your **conversation history and project memory**, with project paths re-mapped when your folders live somewhere else on the new machine.
4
+
5
+ ```sh
6
+ npx claude-migrate
7
+ ```
8
+
9
+ Run it on the old Mac and choose **Export**. Copy the `claude-migrate-<date>.tar.gz` it writes to the new Mac, run `npx claude-migrate` again and choose **Import**.
10
+
11
+ ## Requirements
12
+
13
+ - macOS
14
+ - Node.js 16 or newer (only to launch the tool)
15
+ - Python 3.9 or newer, which Apple's command line tools already include (`xcode-select --install`). The tool itself is Python with no dependencies.
16
+
17
+ ## Export
18
+
19
+ Every part is its own checkbox, shown with its size: settings, `CLAUDE.md`, skills, slash commands, subagents, hooks, MCP servers and per-project settings, plugins, plugin marketplaces, conversation history, project memory, prompt history, file edit history, shell aliases, other accounts, and other files.
20
+
21
+ Nothing is hard-coded to your folder names. The tool looks at your home folder and offers what it finds:
22
+
23
+ - **Accounts.** Any `~/.claude*` folder that holds conversations or settings with skills, commands, hooks or plugins, plus any folder named by `CLAUDE_CONFIG_DIR` in your `~/.zshrc`. `~/.claude` is the main account; the rest share the **Second account** checkbox.
24
+ - **Tools.** Any `~/.claude-*` or `~/.omniroute` folder gets a checkbox of its own, such as `claude-mem`, Claude Code Router and OmniRoute.
25
+
26
+ Tools, shell aliases, other accounts and other files start unticked.
27
+
28
+ OmniRoute (and every other tool folder) is copied without logs, backups, caches or pid files. Its SQLite database is copied as a consistent snapshot with provider tokens and API keys blanked, so you sign in to those providers again on the new Mac.
29
+
30
+ For scripts:
31
+
32
+ ```sh
33
+ npx claude-migrate export --list-components
34
+ npx claude-migrate export --out ~/claude.tar.gz --exclude history,plugins
35
+ npx claude-migrate export --out ~/claude.tar.gz --only settings,memory
36
+ ```
37
+
38
+ ## Import
39
+
40
+ The wizard verifies the bundle, then asks where your projects live now: the same places, moved under a different folder (one prefix rule re-points every project), or individually. It shows the full plan before changing anything, and copies every file it would replace to `~/.claude-migrate-backup-<timestamp>/` first.
41
+
42
+ ```sh
43
+ npx claude-migrate import ~/claude.tar.gz # dry run, writes a mapping file you can edit
44
+ npx claude-migrate import ~/claude.tar.gz --apply --zsh # perform it
45
+ ```
46
+
47
+ Nothing is written until you confirm, or pass `--apply`.
48
+
49
+ ## What does not travel
50
+
51
+ - **Logins.** Sign in again with `/login` on the new Mac.
52
+ - **Secrets.** API keys found in settings, MCP configs and shell aliases are replaced with `<MASKED>`; credential files (`.credentials.json`, `.env*`, keys) are left out. The export report lists what to re-enter.
53
+ - Caches, logs and other machine-local state.
54
+
55
+ ## Only import bundles you made
56
+
57
+ A bundle carries your hooks, slash commands, skills and MCP server commands, and those run code on the machine you import to. Treat a bundle like a script: import only ones you exported yourself, from a place you control. The tool checks the bundle's checksums (that catches corruption, not a malicious author) and refuses path tricks, but it cannot make an untrusted bundle safe.
58
+
59
+ The optional `~/.zshrc` step is held to the same standard: it is off unless you tick it, it shows you the exact lines first, and it only adds plain `alias`, `export` and `source` definitions. It refuses aliases that shadow everyday commands (`ls`, `git`, `sudo`, ...), variables that change how the shell loads code (`DYLD_*`, `ZDOTDIR`, `PROMPT_COMMAND`, ...), and `source` of anything under `~/.claude*`.
60
+
61
+ ## Keep the bundle safe
62
+
63
+ The bundle holds your conversation history and is saved readable only by you (`0600`). Anything you ever pasted into a conversation, including a secret, is inside it. Keep it off shared drives and delete it after the move.
64
+
65
+ ## Without Node
66
+
67
+ The tool is plain Python. If you'd rather not use npm, clone this repo and run `./claude-migrate.sh` (or `python3 migrate.py`); it behaves identically.
68
+
69
+ ## Development
70
+
71
+ ```sh
72
+ npm test # Python unit tests (python3 -m unittest) plus the Node launcher tests
73
+ ```
74
+
75
+ The Python code uses only the standard library and must keep working on the Python 3.9 that macOS ships. Tests build a fake home directory, so they never touch your real `~/.claude`.
76
+
77
+ ## License
78
+
79
+ MIT
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // Thin launcher: claude-migrate is a Python 3 tool (stdlib only), so this just finds a
4
+ // suitable python3 and hands over the terminal and the arguments untouched.
5
+
6
+ const { spawn, spawnSync } = require("node:child_process");
7
+ const path = require("node:path");
8
+
9
+ const MIN_MAJOR = 3;
10
+ const MIN_MINOR = 9; // what macOS ships with the Command Line Tools
11
+ const script = path.join(__dirname, "..", "migrate.py");
12
+
13
+ function pythonVersion(cmd) {
14
+ const r = spawnSync(cmd, ["-c", "import sys; print('%d.%d' % sys.version_info[:2])"], { encoding: "utf8" });
15
+ if (r.error || r.status !== 0) return null;
16
+ const [major, minor] = r.stdout.trim().split(".").map(Number);
17
+ return Number.isInteger(major) && Number.isInteger(minor) ? { major, minor } : null;
18
+ }
19
+
20
+ function findPython() {
21
+ let tooOld = null;
22
+ for (const cmd of ["python3", "python"]) {
23
+ const v = pythonVersion(cmd);
24
+ if (!v) continue;
25
+ if (v.major > MIN_MAJOR || (v.major === MIN_MAJOR && v.minor >= MIN_MINOR)) return { cmd };
26
+ tooOld = tooOld || `${cmd} is ${v.major}.${v.minor}`;
27
+ }
28
+ return { tooOld };
29
+ }
30
+
31
+ const found = findPython();
32
+ if (!found.cmd) {
33
+ const why = found.tooOld ? `Found ${found.tooOld}, but ` : "";
34
+ console.error(`${why}claude-migrate needs Python ${MIN_MAJOR}.${MIN_MINOR} or newer.`);
35
+ console.error("On a Mac, install Apple's command line tools (they include Python 3): xcode-select --install");
36
+ process.exit(1);
37
+ }
38
+
39
+ const child = spawn(found.cmd, [script, ...process.argv.slice(2)], {
40
+ stdio: "inherit",
41
+ // keep the npx cache free of __pycache__ files
42
+ env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" },
43
+ });
44
+
45
+ // Ctrl-C reaches the whole foreground process group. Let Python decide what to do with it, so it can
46
+ // restore the terminal and clean up; this process exits when the child does.
47
+ process.on("SIGINT", () => {});
48
+ process.on("SIGTERM", () => child.kill("SIGTERM"));
49
+
50
+ child.on("error", (err) => {
51
+ console.error(`Could not start ${found.cmd}: ${err.message}`);
52
+ process.exit(1);
53
+ });
54
+ child.on("exit", (code, signal) => {
55
+ if (signal) {
56
+ process.removeAllListeners(signal);
57
+ process.kill(process.pid, signal);
58
+ return;
59
+ }
60
+ process.exit(code === null ? 1 : code);
61
+ });
package/cm_bundle.py ADDED
@@ -0,0 +1,398 @@
1
+ """Export: collect the portable parts of a Claude Code setup into one archive."""
2
+ import datetime
3
+ import getpass
4
+ import hashlib
5
+ import io
6
+ import json
7
+ import os
8
+ import re
9
+ import tarfile
10
+
11
+ from cm_layout import default_layout, discover
12
+ from cm_paths import encode_path
13
+ from cm_sqlite import is_sqlite, sanitized_copy
14
+ from cm_secrets import extract_zsh_claude_lines, find_secret_shapes, mask_secrets
15
+
16
+ TOOL_VERSION = "1.0.0"
17
+ EXCLUDE_TOP = {
18
+ "security", "debug", "shell-snapshots", "cache", "session-env", "paste-cache",
19
+ "backups", "sessions", "telemetry", "ide", ".cc-writes", "jobs",
20
+ }
21
+ EXCLUDE_TOP_PREFIX = ("daemon", "policy-limits", "remote-settings", ".last-")
22
+ HISTORY_TOP = {"projects", "history.jsonl", "file-history"}
23
+ _IDENTITY_KEYS = {
24
+ "userID", "machineID", "anonymousId", "oauthAccount", "customApiKeyResponses", "primaryApiKey",
25
+ "hasAvailableSubscription", "isQualifiedForDataSharing", "subscriptionNoticeCount",
26
+ "penguinModeOrgEnabled", "claudeAiMcpEverConnected", "mcpNeedsAuthNoticed", "claudeCodeFirstTokenDate",
27
+ }
28
+ # Files that are credentials by nature: never exported, always reported.
29
+ _SENSITIVE_NAME_RE = re.compile(
30
+ r"^(\.?credentials\.json|\.env(\..*)?|.*\.(pem|key|p12|pfx)|id_(rsa|ed25519|ecdsa)(\.pub)?|.*\.keychain(-db)?)$",
31
+ re.I,
32
+ )
33
+ # Inside a tool's folder: logs, backups and caches are regenerable, pid files and SQLite sidecars are live state.
34
+ TOOL_EXCLUDE_DIRS = {"logs", "log", "backups", "db_backups", "call_logs", "cache", "tmp", "server", "supervisor"}
35
+ _TOOL_STATE_SUFFIXES = (".pid", "-wal", "-shm", "-journal")
36
+ SCAN_SKIP_TOP = {"plugins", "projects", "file-history", "history.jsonl"}
37
+ SCAN_MAX_BYTES = 1 << 20
38
+ _CACHE_KEY_RE = re.compile(r"^cached|Cache($|Slots|By)")
39
+
40
+
41
+ # What can be switched on or off, one checkbox each. Nothing is bundled together.
42
+ CORE_COMPONENTS = [
43
+ ("settings", "Settings", "settings.json"),
44
+ ("claude_md", "CLAUDE.md instructions", ""),
45
+ ("skills", "Skills", ""),
46
+ ("commands", "Slash commands", ""),
47
+ ("agents", "Subagents", ""),
48
+ ("hooks", "Hooks", ""),
49
+ ("mcp", "MCP servers and per-project settings", "~/.claude.json"),
50
+ ("plugins", "Plugins", ""),
51
+ ("marketplaces", "Plugin marketplaces", ""),
52
+ ("history", "Conversation history", ""),
53
+ ("memory", "Project memory", ""),
54
+ ("prompt_history", "Prompt history", "history.jsonl"),
55
+ ("file_history", "File edit history", "file-history/"),
56
+ ("shell", "Shell aliases", "claude lines from ~/.zshrc"),
57
+ ("work_account", "Second account", ""),
58
+ ("other", "Other files in ~/.claude", "tasks, state and the like"),
59
+ ]
60
+ HISTORY_COMPONENTS = {"history", "memory", "prompt_history", "file_history"}
61
+ PLUGIN_COMPONENTS = {"plugins", "marketplaces"}
62
+ _CONFIG_TOP = {"skills": "skills", "commands": "commands", "agents": "agents", "hooks": "hooks",
63
+ "CLAUDE.md": "claude_md", "history.jsonl": "prompt_history", "file-history": "file_history"}
64
+
65
+
66
+ def component_of(rel, layout=None):
67
+ """Which single checkbox a file belongs to. (Extra-account files are also gated by 'work_account'.)"""
68
+ layout = layout or default_layout()
69
+ parts = rel.split(os.sep)
70
+ root = parts[0]
71
+ if rel == ".claude.json":
72
+ return "mcp"
73
+ if root in layout.tool_dirs:
74
+ return layout.tool_dirs[root]
75
+ if root not in layout.config_dirs or len(parts) < 2:
76
+ return "other"
77
+ top = parts[1]
78
+ if top == ".claude.json":
79
+ return "mcp"
80
+ if top.startswith("settings") and top.endswith(".json"):
81
+ return "settings"
82
+ if top in _CONFIG_TOP:
83
+ return _CONFIG_TOP[top]
84
+ if top == "plugins":
85
+ sub = parts[2] if len(parts) > 2 else ""
86
+ return "marketplaces" if sub in ("marketplaces", "known_marketplaces.json") else "plugins"
87
+ if top == "projects" and len(parts) >= 4:
88
+ return "memory" if parts[3] == "memory" else "history"
89
+ if top == "projects":
90
+ return "history"
91
+ return "other"
92
+
93
+
94
+ def is_selected(rel, selected, layout=None):
95
+ layout = layout or default_layout()
96
+ if component_of(rel, layout) not in selected:
97
+ return False
98
+ return not (layout.is_extra_account(rel.split(os.sep)[0]) and "work_account" not in selected)
99
+
100
+
101
+ def should_exclude(rel, no_history, no_plugins, layout=None):
102
+ layout = layout or default_layout()
103
+ parts = rel.split(os.sep)
104
+ name = parts[-1]
105
+ if name == ".DS_Store" or name.endswith((".zip", ".lock", ".log")) or ".tmp." in name:
106
+ return True
107
+ if parts[0] in layout.tool_dirs and len(parts) > 1:
108
+ if parts[1] in TOOL_EXCLUDE_DIRS or name.endswith(_TOOL_STATE_SUFFIXES):
109
+ return True
110
+ if parts[0].startswith(".claude.json."):
111
+ return True
112
+ if parts[0] in layout.config_dirs and len(parts) > 1:
113
+ top = parts[1]
114
+ if top in EXCLUDE_TOP or top.startswith(EXCLUDE_TOP_PREFIX):
115
+ return True
116
+ if len(parts) == 2 and top.startswith(".claude.json."):
117
+ return True
118
+ if no_history and top in HISTORY_TOP:
119
+ return True
120
+ if no_plugins and top == "plugins":
121
+ return True
122
+ return False
123
+
124
+
125
+ def is_sensitive_file(rel):
126
+ return bool(_SENSITIVE_NAME_RE.match(os.path.basename(rel)))
127
+
128
+
129
+ # Third-party or conversation data we copy as it is: plugin manifests (tsconfig-style JSON with comments,
130
+ # keywords/author fields) must stay byte-identical, and transcripts are the user's own conversations.
131
+ PASSTHROUGH_JSON_TOP = {"projects", "file-history"}
132
+ # inside plugins/: code and catalogues fetched from elsewhere. plugins/config.json, plugins/data/ and the
133
+ # *.json state files are the user's own settings and are masked like any other config.
134
+ PLUGIN_CODE_DIRS = {"cache", "marketplaces", "repos", "store", "synced"}
135
+
136
+
137
+ def _masks_json(rel, layout=None):
138
+ """Every JSON config file gets its secrets masked, except third-party plugin files and history."""
139
+ name = os.path.basename(rel)
140
+ if not (name.endswith(".json") or ".json." in name):
141
+ return False
142
+ return not _is_passthrough_json(rel, layout)
143
+
144
+
145
+ def _is_passthrough_json(rel, layout=None):
146
+ layout = layout or default_layout()
147
+ parts = rel.split(os.sep)
148
+ if parts[0] not in layout.config_dirs or len(parts) < 2:
149
+ return False
150
+ if parts[1] in PASSTHROUGH_JSON_TOP:
151
+ return True
152
+ return parts[1] == "plugins" and len(parts) > 3 and parts[2] in PLUGIN_CODE_DIRS
153
+
154
+
155
+ def _should_scan(rel, size, layout=None):
156
+ layout = layout or default_layout()
157
+ parts = rel.split(os.sep)
158
+ if size > SCAN_MAX_BYTES:
159
+ return False
160
+ if parts[0] in layout.config_dirs and len(parts) > 1 and parts[1] in SCAN_SKIP_TOP:
161
+ # plugin code is skipped for speed, but JSON copied through unmasked is still checked for credentials
162
+ name = os.path.basename(rel)
163
+ return parts[1] == "plugins" and (name.endswith(".json") or ".json." in name)
164
+ return True
165
+
166
+
167
+ def strip_identity(data):
168
+ return {k: v for k, v in data.items() if k not in _IDENTITY_KEYS and not _CACHE_KEY_RE.search(k)}
169
+
170
+
171
+ def _walk_home(home, selected, layout=None):
172
+ """Yield (rel, kind) for kind in file|symlink under the migrated roots, limited to `selected` components."""
173
+ layout = layout or default_layout()
174
+ entries = [".claude.json"] if os.path.lexists(os.path.join(home, ".claude.json")) else []
175
+ for root in layout.root_dirs:
176
+ base = os.path.join(home, root)
177
+ # isdir() follows a symlinked root (e.g. ~/.claude -> /Volumes/X/.claude), so its content is
178
+ # exported; os.walk lists a symlinked top directory but never follows links below it.
179
+ if not os.path.isdir(base):
180
+ continue
181
+ for dp, dn, fn in os.walk(base):
182
+ keep = []
183
+ for d in dn:
184
+ rel = os.path.relpath(os.path.join(dp, d), home)
185
+ if os.path.islink(os.path.join(dp, d)):
186
+ if is_selected(rel, selected, layout):
187
+ yield rel, "symlink"
188
+ elif not should_exclude(rel, False, False, layout):
189
+ keep.append(d)
190
+ dn[:] = sorted(keep)
191
+ for f in sorted(fn):
192
+ p = os.path.join(dp, f)
193
+ rel = os.path.relpath(p, home)
194
+ if should_exclude(rel, False, False, layout) or not is_selected(rel, selected, layout):
195
+ continue
196
+ yield rel, ("symlink" if os.path.islink(p) else "file")
197
+ for rel in entries:
198
+ if is_selected(rel, selected, layout):
199
+ yield rel, "file"
200
+
201
+
202
+ def _first_cwds(path, limit=30):
203
+ out = []
204
+ try:
205
+ with open(path, encoding="utf-8", errors="replace") as f:
206
+ for i, line in enumerate(f):
207
+ if i >= limit:
208
+ break
209
+ if '"cwd"' in line:
210
+ try:
211
+ c = json.loads(line).get("cwd")
212
+ except ValueError:
213
+ continue
214
+ if isinstance(c, str):
215
+ out.append(c)
216
+ except OSError:
217
+ pass
218
+ return out
219
+
220
+
221
+ def resolve_project_folders(home, known_paths, layout=None):
222
+ """Map each real projects/<folder> to the original project path (or None)."""
223
+ layout = layout or default_layout()
224
+ folders = {}
225
+ for cdir in layout.config_dirs:
226
+ base = os.path.join(home, cdir, "projects")
227
+ if os.path.islink(base) or not os.path.isdir(base):
228
+ continue
229
+ for folder in sorted(os.listdir(base)):
230
+ fdir = os.path.join(base, folder)
231
+ if not os.path.isdir(fdir):
232
+ continue
233
+ cands = {p for p in known_paths if encode_path(p) == folder}
234
+ if not cands:
235
+ files = sorted(
236
+ (f for f in os.listdir(fdir) if f.endswith(".jsonl")),
237
+ key=lambda f: os.path.getmtime(os.path.join(fdir, f)), reverse=True,
238
+ )[:5]
239
+ for f in files:
240
+ cands |= {c for c in _first_cwds(os.path.join(fdir, f)) if encode_path(c) == folder}
241
+ folders[folder] = sorted(cands)[0] if cands else None
242
+ return folders
243
+
244
+
245
+ def _add_bytes(tar, name, data, mode=0o600, mtime=None):
246
+ info = tarfile.TarInfo(name)
247
+ info.size = len(data)
248
+ info.mtime = int(datetime.datetime.now().timestamp()) if mtime is None else int(mtime)
249
+ info.mode = mode
250
+ tar.addfile(info, io.BytesIO(data))
251
+
252
+
253
+ def _resolve_components(components, no_history, no_plugins, all_ids):
254
+ selected = set(all_ids if components is None else components)
255
+ unknown = selected - set(all_ids)
256
+ if unknown:
257
+ raise ValueError("unknown component(s): %s" % ", ".join(sorted(unknown)))
258
+ if no_history:
259
+ selected -= HISTORY_COMPONENTS
260
+ if no_plugins:
261
+ selected -= PLUGIN_COMPONENTS
262
+ return selected
263
+
264
+
265
+ def scan_components(home, layout=None):
266
+ """{component: {"files": n, "bytes": n}} for everything that could be exported (for size hints)."""
267
+ layout = layout or discover(home)
268
+ ids = [c[0] for c in layout.components()]
269
+ out = {c: {"files": 0, "bytes": 0} for c in ids}
270
+ everything = set(ids)
271
+ for rel, kind in _walk_home(home, everything, layout):
272
+ if kind != "file":
273
+ continue
274
+ try:
275
+ size = os.lstat(os.path.join(home, rel)).st_size
276
+ except OSError:
277
+ continue
278
+ for cid in {component_of(rel, layout)} | ({"work_account"} if layout.is_extra_account(rel.split(os.sep)[0]) else set()):
279
+ out[cid]["files"] += 1
280
+ out[cid]["bytes"] += size
281
+ zrc = os.path.join(home, ".zshrc")
282
+ if os.path.isfile(zrc):
283
+ with open(zrc, encoding="utf-8", errors="replace") as f:
284
+ lines, _ = extract_zsh_claude_lines(f.read())
285
+ out["shell"] = {"files": 1 if lines else 0, "bytes": sum(len(l) + 1 for l in lines)}
286
+ return out
287
+
288
+
289
+ def export_bundle(home, out_path, no_history=False, no_plugins=False, components=None, layout=None):
290
+ layout = layout or discover(home)
291
+ all_ids = [c[0] for c in layout.components()]
292
+ selected = _resolve_components(components, no_history, no_plugins, all_ids)
293
+ files, symlinks, masked_all, skipped = {}, {}, [], []
294
+ excluded_sensitive, warnings = [], []
295
+ known_paths = set()
296
+ out_abs = os.path.abspath(out_path)
297
+
298
+ # The bundle holds history and config: owner-only from the first byte, even over an old file.
299
+ fd = os.open(out_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
300
+ os.fchmod(fd, 0o600)
301
+ with os.fdopen(fd, "wb") as raw, tarfile.open(fileobj=raw, mode="w:gz") as tar:
302
+ for rel, kind in _walk_home(home, selected, layout):
303
+ src = os.path.join(home, rel)
304
+ if os.path.abspath(src) == out_abs:
305
+ continue
306
+ if kind == "symlink":
307
+ symlinks[rel] = os.readlink(src)
308
+ continue
309
+ name = os.path.basename(rel)
310
+ if is_sensitive_file(rel):
311
+ excluded_sensitive.append(rel)
312
+ continue
313
+ if rel.split(os.sep)[0] in layout.tool_dirs and is_sqlite(src):
314
+ try:
315
+ blob, masked = sanitized_copy(src)
316
+ except Exception as e: # a database we cannot read safely stays behind
317
+ skipped.append("%s (%s)" % (rel, type(e).__name__))
318
+ continue
319
+ masked_all += ["%s: %s" % (rel, m) for m in masked]
320
+ elif _masks_json(rel, layout):
321
+ try:
322
+ with open(src, encoding="utf-8") as f:
323
+ data = json.load(f)
324
+ except (ValueError, OSError):
325
+ skipped.append(rel)
326
+ continue
327
+ if name == ".claude.json":
328
+ known_paths |= set(data.get("projects", {}))
329
+ data = strip_identity(data)
330
+ data, masked = mask_secrets(data)
331
+ masked_all += ["%s: %s" % (rel, m) for m in masked]
332
+ blob = json.dumps(data, indent=2).encode()
333
+ else:
334
+ with open(src, "rb") as f:
335
+ blob = f.read()
336
+ if _should_scan(rel, len(blob), layout):
337
+ try:
338
+ if find_secret_shapes(blob.decode("utf-8")):
339
+ warnings.append("possible credential in %s (kept as-is, review before sharing)" % rel)
340
+ except UnicodeDecodeError:
341
+ pass
342
+ files[rel] = hashlib.sha256(blob).hexdigest()
343
+ st = os.stat(src)
344
+ _add_bytes(tar, "home/" + rel, blob, mode=st.st_mode & 0o777, mtime=st.st_mtime)
345
+
346
+ wants_config_dir = bool(selected - {"mcp", "shell", "work_account"} - set(layout.tool_dirs.values()))
347
+ for root in layout.config_dirs:
348
+ base = os.path.join(home, root)
349
+ if layout.is_extra_account(root) and "work_account" not in selected:
350
+ continue
351
+ if wants_config_dir and (root == ".claude" or os.path.lexists(base)) \
352
+ and not any(r.startswith(root + os.sep) for r in files):
353
+ why = "is a broken symlink" if os.path.islink(base) and not os.path.exists(base) else "had nothing to export"
354
+ warnings.append("~/%s %s: the bundle is empty for it" % (root, why))
355
+
356
+ zsh_lines, zsh_notes = [], []
357
+ zrc = os.path.join(home, ".zshrc")
358
+ if "shell" in selected and os.path.isfile(zrc):
359
+ with open(zrc, encoding="utf-8", errors="replace") as f:
360
+ zsh_lines, zsh_notes = extract_zsh_claude_lines(f.read())
361
+ masked_all += ["~/.zshrc: " + n for n in zsh_notes]
362
+ snippet_blob = ("\n".join(zsh_lines) + "\n").encode()
363
+ _add_bytes(tar, "zsh-snippet.txt", snippet_blob)
364
+
365
+ wants_folders = bool(selected & {"history", "memory"})
366
+ folders = resolve_project_folders(home, known_paths, layout) if wants_folders else {}
367
+ projects = sorted(known_paths | {p for p in folders.values() if p})
368
+ manifest = {
369
+ "tool_version": TOOL_VERSION,
370
+ "created": datetime.datetime.now().isoformat(timespec="seconds"),
371
+ "source_home": home,
372
+ "username": getpass.getuser(),
373
+ "components": [c for c in all_ids if c in selected],
374
+ "layout": layout.to_manifest(),
375
+ "options": {"no_history": not (selected & HISTORY_COMPONENTS),
376
+ "no_plugins": not (selected & PLUGIN_COMPONENTS)},
377
+ "projects": projects,
378
+ "project_folders": folders,
379
+ "zsh_sha256": hashlib.sha256(snippet_blob).hexdigest(),
380
+ "files": files,
381
+ "symlinks": symlinks,
382
+ "masked": masked_all,
383
+ "skipped": skipped,
384
+ "excluded_sensitive": excluded_sensitive,
385
+ }
386
+ _add_bytes(tar, "manifest.json", json.dumps(manifest, indent=2).encode())
387
+
388
+ return {
389
+ "out": out_path,
390
+ "files": len(files),
391
+ "bytes": os.path.getsize(out_path),
392
+ "projects": len(projects),
393
+ "components": [c for c in all_ids if c in selected],
394
+ "masked": masked_all,
395
+ "skipped": skipped,
396
+ "excluded_sensitive": excluded_sensitive,
397
+ "warnings": warnings,
398
+ }