claudeshift-cli 0.1.0__py3-none-any.whl
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.
- claudeshift/__init__.py +3 -0
- claudeshift/cli.py +634 -0
- claudeshift/config/__init__.py +0 -0
- claudeshift/config/paths.py +73 -0
- claudeshift/core/__init__.py +0 -0
- claudeshift/core/inspector.py +113 -0
- claudeshift/core/models.py +98 -0
- claudeshift/core/vault.py +723 -0
- claudeshift/licensing/__init__.py +0 -0
- claudeshift/licensing/entitlements.py +60 -0
- claudeshift/licensing/gumroad.py +291 -0
- claudeshift/providers/__init__.py +0 -0
- claudeshift/providers/base.py +136 -0
- claudeshift/providers/plan_detector.py +249 -0
- claudeshift/telemetry/__init__.py +0 -0
- claudeshift/telemetry/analytics.py +200 -0
- claudeshift/telemetry/dashboard.py +157 -0
- claudeshift/telemetry/exporter.py +93 -0
- claudeshift/telemetry/parser.py +400 -0
- claudeshift/telemetry/pricing.py +362 -0
- claudeshift_cli-0.1.0.dist-info/METADATA +38 -0
- claudeshift_cli-0.1.0.dist-info/RECORD +26 -0
- claudeshift_cli-0.1.0.dist-info/WHEEL +5 -0
- claudeshift_cli-0.1.0.dist-info/entry_points.txt +3 -0
- claudeshift_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- claudeshift_cli-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import stat
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from claudeshift.config.paths import RuntimePaths
|
|
19
|
+
from claudeshift.core.inspector import inspect_identity
|
|
20
|
+
from claudeshift.core.models import (
|
|
21
|
+
BackupInfo,
|
|
22
|
+
ProfileDiff,
|
|
23
|
+
ProfileManifest,
|
|
24
|
+
SwitchResult,
|
|
25
|
+
)
|
|
26
|
+
from claudeshift.licensing.entitlements import (
|
|
27
|
+
ProFeatureRequiredError,
|
|
28
|
+
get_entitlements,
|
|
29
|
+
)
|
|
30
|
+
from claudeshift.providers.base import PROVIDERS, ProviderSpec
|
|
31
|
+
|
|
32
|
+
MANIFEST_SCHEMA_VERSION = 1
|
|
33
|
+
MAX_ROLLING_BACKUPS = 10
|
|
34
|
+
PROFILE_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]{0,47}$")
|
|
35
|
+
BACKUP_ID_RE = re.compile(r"^\d{8}_\d{6}_[a-f0-9]{6}$")
|
|
36
|
+
|
|
37
|
+
# Exclude heavy regenerable caches, lock files, and marketplace bundles from profile snapshots
|
|
38
|
+
IGNORED_PATTERNS = (
|
|
39
|
+
"*.lock",
|
|
40
|
+
"*.tmp",
|
|
41
|
+
"LOCK",
|
|
42
|
+
"SingletonLock",
|
|
43
|
+
"SingletonCookie",
|
|
44
|
+
"SingletonSocket",
|
|
45
|
+
"shell-snapshots",
|
|
46
|
+
"__pycache__",
|
|
47
|
+
"cache",
|
|
48
|
+
"Cache",
|
|
49
|
+
"Cache_Data",
|
|
50
|
+
"Code Cache",
|
|
51
|
+
"GPUCache",
|
|
52
|
+
"DawnCache",
|
|
53
|
+
"DawnGraphiteCache",
|
|
54
|
+
"DawnWebGPUCache",
|
|
55
|
+
"GrShaderCache",
|
|
56
|
+
"ShaderCache",
|
|
57
|
+
"Service Worker",
|
|
58
|
+
"blob_storage",
|
|
59
|
+
"Crashpad",
|
|
60
|
+
"marketplaces",
|
|
61
|
+
"node_modules",
|
|
62
|
+
"logs",
|
|
63
|
+
"Logs",
|
|
64
|
+
"tmp",
|
|
65
|
+
"temp",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
WINDOWS_RESERVED_NAMES = {
|
|
69
|
+
"con",
|
|
70
|
+
"prn",
|
|
71
|
+
"aux",
|
|
72
|
+
"nul",
|
|
73
|
+
*(f"com{i}" for i in range(1, 10)),
|
|
74
|
+
*(f"lpt{i}" for i in range(1, 10)),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class VaultError(RuntimeError):
|
|
79
|
+
"""Base error for vault operations."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _utc_now() -> str:
|
|
83
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _win_long_path(path: Path) -> str:
|
|
87
|
+
"""Bypass Windows 260-char MAX_PATH limit using extended-length path prefix."""
|
|
88
|
+
s = str(path.resolve())
|
|
89
|
+
if sys.platform == "win32" and not s.startswith("\\\\?\\"):
|
|
90
|
+
if s.startswith("\\\\"):
|
|
91
|
+
return "\\\\?\\UNC\\" + s[2:]
|
|
92
|
+
return "\\\\?\\" + s
|
|
93
|
+
return s
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _validate_profile_name(name: str) -> str:
|
|
97
|
+
cleaned = name.strip()
|
|
98
|
+
if not PROFILE_NAME_RE.match(cleaned):
|
|
99
|
+
raise VaultError(
|
|
100
|
+
f"Invalid profile name '{name}'. Use 1-48 chars: letters, numbers, '.', '_', '-'."
|
|
101
|
+
)
|
|
102
|
+
base_name = cleaned.split(".")[0].lower()
|
|
103
|
+
if (
|
|
104
|
+
cleaned.lower() in {"default", "all", "none", "backup", "backups"}
|
|
105
|
+
or base_name in WINDOWS_RESERVED_NAMES
|
|
106
|
+
):
|
|
107
|
+
raise VaultError(
|
|
108
|
+
f"Profile name '{cleaned}' is reserved. Choose a descriptive name like 'work' or 'personal'."
|
|
109
|
+
)
|
|
110
|
+
return cleaned
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _validate_backup_id(backup_id: str) -> str:
|
|
114
|
+
cleaned = backup_id.strip()
|
|
115
|
+
if not BACKUP_ID_RE.match(cleaned):
|
|
116
|
+
raise VaultError(f"Invalid backup ID '{backup_id}'.")
|
|
117
|
+
return cleaned
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _assert_within_root(root: Path, candidate: Path, label: str) -> Path:
|
|
121
|
+
resolved_root = root.resolve()
|
|
122
|
+
resolved_candidate = candidate.resolve()
|
|
123
|
+
if not resolved_candidate.is_relative_to(resolved_root):
|
|
124
|
+
raise VaultError(f"Security violation: {label} escapes allowed directory.")
|
|
125
|
+
return resolved_candidate
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _validate_no_escaping_symlinks(src: Path, allowed_root: Path) -> None:
|
|
129
|
+
"""Reject any symlink inside src whose resolved target escapes allowed_root."""
|
|
130
|
+
resolved_root = allowed_root.resolve()
|
|
131
|
+
|
|
132
|
+
def _check(p: Path) -> None:
|
|
133
|
+
if p.is_symlink():
|
|
134
|
+
target = p.resolve()
|
|
135
|
+
if not target.is_relative_to(resolved_root):
|
|
136
|
+
raise VaultError(
|
|
137
|
+
f"Security violation: symlink '{p.name}' escapes target home directory."
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
_check(src)
|
|
141
|
+
if src.is_dir() and not src.is_symlink():
|
|
142
|
+
for dirpath, dirnames, filenames in os.walk(src, followlinks=False):
|
|
143
|
+
# Skip ignored cache directories during symlink traversal as well
|
|
144
|
+
dirnames[:] = [d for d in dirnames if d not in IGNORED_PATTERNS]
|
|
145
|
+
base = Path(dirpath)
|
|
146
|
+
for name in dirnames:
|
|
147
|
+
_check(base / name)
|
|
148
|
+
for name in filenames:
|
|
149
|
+
_check(base / name)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _get_provider(provider_id: str) -> ProviderSpec:
|
|
153
|
+
pid = provider_id.strip().lower()
|
|
154
|
+
if pid not in PROVIDERS:
|
|
155
|
+
valid = ", ".join(PROVIDERS.keys())
|
|
156
|
+
raise VaultError(f"Unknown provider '{provider_id}'. Supported providers: {valid}")
|
|
157
|
+
return PROVIDERS[pid]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _handle_remove_readonly(func, path, exc_info) -> None:
|
|
161
|
+
with contextlib.suppress(Exception):
|
|
162
|
+
os.chmod(path, stat.S_IWRITE | stat.S_IREAD)
|
|
163
|
+
func(path)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _force_rmtree(path: Path) -> None:
|
|
167
|
+
if not path.exists() and not path.is_symlink():
|
|
168
|
+
return
|
|
169
|
+
if path.is_file() or path.is_symlink():
|
|
170
|
+
with contextlib.suppress(Exception):
|
|
171
|
+
os.chmod(path, stat.S_IWRITE | stat.S_IREAD)
|
|
172
|
+
path.unlink(missing_ok=True)
|
|
173
|
+
return
|
|
174
|
+
shutil.rmtree(_win_long_path(path), onerror=_handle_remove_readonly)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _atomic_write_json(path: Path, payload: dict) -> None:
|
|
178
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
179
|
+
tmp_path = path.with_suffix(f".{uuid.uuid4().hex[:8]}.tmp")
|
|
180
|
+
tmp_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
181
|
+
os.replace(tmp_path, path)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _sha256_file(path: Path) -> str:
|
|
185
|
+
h = hashlib.sha256()
|
|
186
|
+
with open(_win_long_path(path), "rb") as f:
|
|
187
|
+
for chunk in iter(lambda: f.read(65536), b""):
|
|
188
|
+
h.update(chunk)
|
|
189
|
+
return h.hexdigest()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _copy_entry(src: Path, dst: Path) -> None:
|
|
193
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
if src.is_dir():
|
|
195
|
+
shutil.copytree(
|
|
196
|
+
_win_long_path(src),
|
|
197
|
+
_win_long_path(dst),
|
|
198
|
+
symlinks=True,
|
|
199
|
+
ignore=shutil.ignore_patterns(*IGNORED_PATTERNS),
|
|
200
|
+
dirs_exist_ok=False,
|
|
201
|
+
)
|
|
202
|
+
else:
|
|
203
|
+
shutil.copy2(_win_long_path(src), _win_long_path(dst))
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _scan_payload(payload_dir: Path) -> tuple[int, int, dict[str, str]]:
|
|
207
|
+
"""Return (file_count, total_bytes, checksums_map) for all regular files under payload_dir."""
|
|
208
|
+
file_count = 0
|
|
209
|
+
total_bytes = 0
|
|
210
|
+
checksums: dict[str, str] = {}
|
|
211
|
+
if not payload_dir.exists():
|
|
212
|
+
return 0, 0, {}
|
|
213
|
+
|
|
214
|
+
for p in sorted(payload_dir.rglob("*")):
|
|
215
|
+
if p.is_file() and not p.is_symlink():
|
|
216
|
+
rel = p.relative_to(payload_dir).as_posix()
|
|
217
|
+
size = p.stat().st_size
|
|
218
|
+
file_count += 1
|
|
219
|
+
total_bytes += size
|
|
220
|
+
checksums[rel] = _sha256_file(p) if size <= 5 * 1024 * 1024 else f"size:{size}"
|
|
221
|
+
return file_count, total_bytes, checksums
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _verify_checksums(payload_dir: Path, checksums: dict[str, str], label: str) -> None:
|
|
225
|
+
for rel, expected in checksums.items():
|
|
226
|
+
if not isinstance(rel, str) or not rel or rel.startswith("/") or ".." in Path(rel).parts:
|
|
227
|
+
raise VaultError(f"Security violation: illegal path '{rel}' inside {label} manifest.")
|
|
228
|
+
fpath = _assert_within_root(payload_dir, payload_dir / rel, f"{label} checksum path '{rel}'")
|
|
229
|
+
if not fpath.is_file():
|
|
230
|
+
raise VaultError(f"Integrity check failed: missing file '{rel}' in {label}.")
|
|
231
|
+
if expected.startswith("size:"):
|
|
232
|
+
if f"size:{fpath.stat().st_size}" != expected:
|
|
233
|
+
raise VaultError(f"Integrity check failed: size mismatch for '{rel}' in {label}.")
|
|
234
|
+
else:
|
|
235
|
+
actual = _sha256_file(fpath)
|
|
236
|
+
if actual != expected:
|
|
237
|
+
raise VaultError(f"Integrity check failed: SHA-256 mismatch for '{rel}' in {label}.")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class VaultEngine:
|
|
241
|
+
"""Atomic, crash-safe, multi-provider profile vault."""
|
|
242
|
+
|
|
243
|
+
def __init__(self, paths: RuntimePaths) -> None:
|
|
244
|
+
self.paths = paths
|
|
245
|
+
self.vault_root = paths.vault_dir
|
|
246
|
+
self.profiles_root = self.vault_root / "profiles"
|
|
247
|
+
self.backups_root = self.vault_root / "backups"
|
|
248
|
+
self.state_file = self.vault_root / "state.json"
|
|
249
|
+
self.lock_file = self.vault_root / ".vault.lock"
|
|
250
|
+
|
|
251
|
+
@contextmanager
|
|
252
|
+
def _locked(self, timeout_sec: float = 5.0) -> Iterator[None]:
|
|
253
|
+
self.vault_root.mkdir(parents=True, exist_ok=True)
|
|
254
|
+
deadline = time.monotonic() + timeout_sec
|
|
255
|
+
while True:
|
|
256
|
+
try:
|
|
257
|
+
fd = os.open(str(self.lock_file), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
258
|
+
os.write(fd, f"pid={os.getpid()} ts={_utc_now()}\n".encode())
|
|
259
|
+
os.close(fd)
|
|
260
|
+
break
|
|
261
|
+
except FileExistsError:
|
|
262
|
+
try:
|
|
263
|
+
age = time.time() - self.lock_file.stat().st_mtime
|
|
264
|
+
if age > 60:
|
|
265
|
+
self.lock_file.unlink(missing_ok=True)
|
|
266
|
+
continue
|
|
267
|
+
except FileNotFoundError:
|
|
268
|
+
continue
|
|
269
|
+
if time.monotonic() > deadline:
|
|
270
|
+
raise VaultError(
|
|
271
|
+
"Vault is currently locked by another claudeshift process. Try again in a moment."
|
|
272
|
+
) from None
|
|
273
|
+
time.sleep(0.05)
|
|
274
|
+
try:
|
|
275
|
+
yield
|
|
276
|
+
finally:
|
|
277
|
+
self.lock_file.unlink(missing_ok=True)
|
|
278
|
+
|
|
279
|
+
def _read_state(self) -> dict:
|
|
280
|
+
if not self.state_file.is_file():
|
|
281
|
+
return {"active": {}}
|
|
282
|
+
with contextlib.suppress(Exception):
|
|
283
|
+
data = json.loads(self.state_file.read_text(encoding="utf-8"))
|
|
284
|
+
if isinstance(data, dict) and isinstance(data.get("active"), dict):
|
|
285
|
+
return data
|
|
286
|
+
return {"active": {}}
|
|
287
|
+
|
|
288
|
+
def _write_state(self, state: dict) -> None:
|
|
289
|
+
_atomic_write_json(self.state_file, state)
|
|
290
|
+
|
|
291
|
+
def get_active_profile(self, provider: str = "claude") -> str | None:
|
|
292
|
+
spec = _get_provider(provider)
|
|
293
|
+
state = self._read_state()
|
|
294
|
+
return state.get("active", {}).get(spec.id)
|
|
295
|
+
|
|
296
|
+
def _profile_dir(self, provider_id: str, name: str) -> Path:
|
|
297
|
+
return self.profiles_root / provider_id / name
|
|
298
|
+
|
|
299
|
+
def list_profiles(self, provider: str = "claude") -> list[ProfileManifest]:
|
|
300
|
+
spec = _get_provider(provider)
|
|
301
|
+
pdir = self.profiles_root / spec.id
|
|
302
|
+
if not pdir.is_dir():
|
|
303
|
+
return []
|
|
304
|
+
manifests: list[ProfileManifest] = []
|
|
305
|
+
for child in sorted(pdir.iterdir()):
|
|
306
|
+
mfile = child / "manifest.json"
|
|
307
|
+
if child.is_dir() and mfile.is_file():
|
|
308
|
+
with contextlib.suppress(Exception):
|
|
309
|
+
data = json.loads(mfile.read_text(encoding="utf-8"))
|
|
310
|
+
manifests.append(ProfileManifest.from_dict(data))
|
|
311
|
+
return manifests
|
|
312
|
+
|
|
313
|
+
def _verify_profile_integrity(self, profile_dir: Path) -> ProfileManifest:
|
|
314
|
+
mfile = profile_dir / "manifest.json"
|
|
315
|
+
payload_dir = profile_dir / "payload"
|
|
316
|
+
if not mfile.is_file() or not payload_dir.is_dir():
|
|
317
|
+
raise VaultError(f"Profile storage at '{profile_dir.name}' is corrupted or incomplete.")
|
|
318
|
+
|
|
319
|
+
manifest = ProfileManifest.from_dict(json.loads(mfile.read_text(encoding="utf-8")))
|
|
320
|
+
_verify_checksums(payload_dir, manifest.checksums, f"profile '{manifest.name}'")
|
|
321
|
+
return manifest
|
|
322
|
+
|
|
323
|
+
def _capture_live_to_dir(
|
|
324
|
+
self,
|
|
325
|
+
spec: ProviderSpec,
|
|
326
|
+
dest_payload: Path,
|
|
327
|
+
name: str,
|
|
328
|
+
note: str = "",
|
|
329
|
+
existing_created_at: str | None = None,
|
|
330
|
+
) -> ProfileManifest:
|
|
331
|
+
found_targets: list[str] = []
|
|
332
|
+
dest_payload.mkdir(parents=True, exist_ok=True)
|
|
333
|
+
|
|
334
|
+
for rel in spec.targets:
|
|
335
|
+
src = self.paths.target_home / rel
|
|
336
|
+
if src.exists() or src.is_symlink():
|
|
337
|
+
_validate_no_escaping_symlinks(src, self.paths.target_home)
|
|
338
|
+
_copy_entry(src, dest_payload / rel)
|
|
339
|
+
found_targets.append(rel)
|
|
340
|
+
|
|
341
|
+
if not found_targets:
|
|
342
|
+
raise VaultError(
|
|
343
|
+
f"No {spec.display_name} files found in '{self.paths.target_home}'. "
|
|
344
|
+
f"Expected one of: {', '.join(spec.targets)}"
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
file_count, total_bytes, checksums = _scan_payload(dest_payload)
|
|
348
|
+
identity = inspect_identity(spec.id, dest_payload)
|
|
349
|
+
now = _utc_now()
|
|
350
|
+
return ProfileManifest(
|
|
351
|
+
schema_version=MANIFEST_SCHEMA_VERSION,
|
|
352
|
+
name=name,
|
|
353
|
+
provider=spec.id,
|
|
354
|
+
created_at=existing_created_at or now,
|
|
355
|
+
updated_at=now,
|
|
356
|
+
targets=found_targets,
|
|
357
|
+
file_count=file_count,
|
|
358
|
+
total_bytes=total_bytes,
|
|
359
|
+
checksums=checksums,
|
|
360
|
+
identity=identity,
|
|
361
|
+
note=note,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
def save_profile(
|
|
365
|
+
self,
|
|
366
|
+
name: str,
|
|
367
|
+
provider: str = "claude",
|
|
368
|
+
overwrite: bool = False,
|
|
369
|
+
note: str = "",
|
|
370
|
+
set_active: bool = True,
|
|
371
|
+
) -> ProfileManifest:
|
|
372
|
+
spec = _get_provider(provider)
|
|
373
|
+
clean_name = _validate_profile_name(name)
|
|
374
|
+
entitlements = get_entitlements(self.paths.config_dir)
|
|
375
|
+
|
|
376
|
+
with self._locked():
|
|
377
|
+
existing_profiles = self.list_profiles(spec.id)
|
|
378
|
+
target_dir = self._profile_dir(spec.id, clean_name)
|
|
379
|
+
already_exists = target_dir.exists()
|
|
380
|
+
|
|
381
|
+
if already_exists and not overwrite:
|
|
382
|
+
raise VaultError(
|
|
383
|
+
f"Profile '{clean_name}' already exists for {spec.id}. Use --overwrite to update it."
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
if (
|
|
387
|
+
not already_exists
|
|
388
|
+
and entitlements.max_profiles_per_provider is not None
|
|
389
|
+
and len(existing_profiles) >= entitlements.max_profiles_per_provider
|
|
390
|
+
):
|
|
391
|
+
raise ProFeatureRequiredError(
|
|
392
|
+
feature="unlimited_profiles",
|
|
393
|
+
detail=(
|
|
394
|
+
f"Free tier supports up to {entitlements.max_profiles_per_provider} profiles "
|
|
395
|
+
f"per provider. Upgrade to claudeshift Pro for unlimited profiles, rolling backups, "
|
|
396
|
+
f"and live quota alerts."
|
|
397
|
+
),
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
created_at: str | None = None
|
|
401
|
+
if already_exists and (target_dir / "manifest.json").is_file():
|
|
402
|
+
with contextlib.suppress(Exception):
|
|
403
|
+
prev = json.loads((target_dir / "manifest.json").read_text(encoding="utf-8"))
|
|
404
|
+
created_at = prev.get("created_at")
|
|
405
|
+
|
|
406
|
+
tmp_profile_dir = self.profiles_root / spec.id / f".tmp_{clean_name}_{uuid.uuid4().hex[:8]}"
|
|
407
|
+
try:
|
|
408
|
+
manifest = self._capture_live_to_dir(
|
|
409
|
+
spec=spec,
|
|
410
|
+
dest_payload=tmp_profile_dir / "payload",
|
|
411
|
+
name=clean_name,
|
|
412
|
+
note=note,
|
|
413
|
+
existing_created_at=created_at,
|
|
414
|
+
)
|
|
415
|
+
_atomic_write_json(tmp_profile_dir / "manifest.json", manifest.to_dict())
|
|
416
|
+
|
|
417
|
+
if target_dir.exists():
|
|
418
|
+
_force_rmtree(target_dir)
|
|
419
|
+
target_dir.parent.mkdir(parents=True, exist_ok=True)
|
|
420
|
+
tmp_profile_dir.rename(target_dir)
|
|
421
|
+
except Exception:
|
|
422
|
+
_force_rmtree(tmp_profile_dir)
|
|
423
|
+
raise
|
|
424
|
+
|
|
425
|
+
if set_active:
|
|
426
|
+
state = self._read_state()
|
|
427
|
+
state.setdefault("active", {})[spec.id] = clean_name
|
|
428
|
+
self._write_state(state)
|
|
429
|
+
|
|
430
|
+
return manifest
|
|
431
|
+
|
|
432
|
+
def _create_backup_snapshot(self, spec: ProviderSpec, reason: str) -> BackupInfo | None:
|
|
433
|
+
has_live = any((self.paths.target_home / rel).exists() for rel in spec.targets)
|
|
434
|
+
if not has_live:
|
|
435
|
+
return None
|
|
436
|
+
|
|
437
|
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
|
|
438
|
+
backup_id = f"{stamp}_{uuid.uuid4().hex[:6]}"
|
|
439
|
+
bdir = self.backups_root / spec.id / backup_id
|
|
440
|
+
payload_dir = bdir / "payload"
|
|
441
|
+
payload_dir.mkdir(parents=True, exist_ok=True)
|
|
442
|
+
|
|
443
|
+
targets_copied: list[str] = []
|
|
444
|
+
for rel in spec.targets:
|
|
445
|
+
src = self.paths.target_home / rel
|
|
446
|
+
if src.exists() or src.is_symlink():
|
|
447
|
+
_validate_no_escaping_symlinks(src, self.paths.target_home)
|
|
448
|
+
_copy_entry(src, payload_dir / rel)
|
|
449
|
+
targets_copied.append(rel)
|
|
450
|
+
|
|
451
|
+
_, total_bytes, checksums = _scan_payload(payload_dir)
|
|
452
|
+
meta = {
|
|
453
|
+
"backup_id": backup_id,
|
|
454
|
+
"provider": spec.id,
|
|
455
|
+
"created_at": _utc_now(),
|
|
456
|
+
"reason": reason,
|
|
457
|
+
"targets": targets_copied,
|
|
458
|
+
"total_bytes": total_bytes,
|
|
459
|
+
"checksums": checksums,
|
|
460
|
+
}
|
|
461
|
+
_atomic_write_json(bdir / "backup.json", meta)
|
|
462
|
+
|
|
463
|
+
provider_backups = sorted(
|
|
464
|
+
[p for p in (self.backups_root / spec.id).iterdir() if p.is_dir()],
|
|
465
|
+
key=lambda p: p.name,
|
|
466
|
+
reverse=True,
|
|
467
|
+
)
|
|
468
|
+
for stale in provider_backups[MAX_ROLLING_BACKUPS:]:
|
|
469
|
+
_force_rmtree(stale)
|
|
470
|
+
|
|
471
|
+
return BackupInfo(
|
|
472
|
+
backup_id=backup_id,
|
|
473
|
+
provider=spec.id,
|
|
474
|
+
created_at=meta["created_at"],
|
|
475
|
+
reason=reason,
|
|
476
|
+
total_bytes=total_bytes,
|
|
477
|
+
path=str(bdir),
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
def _atomic_apply_payload(self, spec: ProviderSpec, payload_dir: Path) -> None:
|
|
481
|
+
"""
|
|
482
|
+
Transactional swap on target_home (supports both top-level and nested targets like AppData/Roaming/Claude):
|
|
483
|
+
1. Copy payload to staging folder on target_home (same filesystem).
|
|
484
|
+
2. Move current live targets into rollback folder.
|
|
485
|
+
3. Move staged targets into live positions.
|
|
486
|
+
4. On ANY error (e.g., locked file on Windows), restore rollback automatically.
|
|
487
|
+
"""
|
|
488
|
+
token = uuid.uuid4().hex[:8]
|
|
489
|
+
stage_dir = self.paths.target_home / f".claudeshift_stage_{token}"
|
|
490
|
+
rollback_dir = self.paths.target_home / f".claudeshift_rollback_{token}"
|
|
491
|
+
|
|
492
|
+
moved_to_rollback: list[str] = []
|
|
493
|
+
applied_live: list[str] = []
|
|
494
|
+
|
|
495
|
+
try:
|
|
496
|
+
stage_dir.mkdir(parents=True, exist_ok=True)
|
|
497
|
+
rollback_dir.mkdir(parents=True, exist_ok=True)
|
|
498
|
+
|
|
499
|
+
staged_targets: list[str] = []
|
|
500
|
+
for rel in spec.targets:
|
|
501
|
+
src = payload_dir / rel
|
|
502
|
+
if src.exists():
|
|
503
|
+
_validate_no_escaping_symlinks(src, payload_dir)
|
|
504
|
+
_copy_entry(src, stage_dir / rel)
|
|
505
|
+
staged_targets.append(rel)
|
|
506
|
+
|
|
507
|
+
if not staged_targets:
|
|
508
|
+
raise VaultError("Target profile payload contains no files to restore.")
|
|
509
|
+
|
|
510
|
+
for rel in spec.targets:
|
|
511
|
+
live = self.paths.target_home / rel
|
|
512
|
+
if live.exists():
|
|
513
|
+
rb_dest = rollback_dir / rel
|
|
514
|
+
rb_dest.parent.mkdir(parents=True, exist_ok=True)
|
|
515
|
+
live.rename(rb_dest)
|
|
516
|
+
moved_to_rollback.append(rel)
|
|
517
|
+
|
|
518
|
+
for rel in staged_targets:
|
|
519
|
+
live_dest = self.paths.target_home / rel
|
|
520
|
+
live_dest.parent.mkdir(parents=True, exist_ok=True)
|
|
521
|
+
(stage_dir / rel).rename(live_dest)
|
|
522
|
+
applied_live.append(rel)
|
|
523
|
+
|
|
524
|
+
except Exception as exc:
|
|
525
|
+
for rel in applied_live:
|
|
526
|
+
live = self.paths.target_home / rel
|
|
527
|
+
if live.exists():
|
|
528
|
+
_force_rmtree(live)
|
|
529
|
+
for rel in moved_to_rollback:
|
|
530
|
+
rb = rollback_dir / rel
|
|
531
|
+
if rb.exists():
|
|
532
|
+
with contextlib.suppress(Exception):
|
|
533
|
+
live_dest = self.paths.target_home / rel
|
|
534
|
+
live_dest.parent.mkdir(parents=True, exist_ok=True)
|
|
535
|
+
rb.rename(live_dest)
|
|
536
|
+
raise VaultError(
|
|
537
|
+
f"Atomic swap aborted and safely rolled back (your files are untouched). "
|
|
538
|
+
f"Close {spec.display_name} if it is running and retry. Details: {exc}"
|
|
539
|
+
) from exc
|
|
540
|
+
finally:
|
|
541
|
+
_force_rmtree(stage_dir)
|
|
542
|
+
_force_rmtree(rollback_dir)
|
|
543
|
+
|
|
544
|
+
def use_profile(
|
|
545
|
+
self,
|
|
546
|
+
name: str,
|
|
547
|
+
provider: str = "claude",
|
|
548
|
+
sync_current: bool = True,
|
|
549
|
+
) -> SwitchResult:
|
|
550
|
+
t0 = time.perf_counter()
|
|
551
|
+
spec = _get_provider(provider)
|
|
552
|
+
clean_name = _validate_profile_name(name)
|
|
553
|
+
entitlements = get_entitlements(self.paths.config_dir)
|
|
554
|
+
|
|
555
|
+
with self._locked():
|
|
556
|
+
target_dir = self._profile_dir(spec.id, clean_name)
|
|
557
|
+
if not target_dir.is_dir():
|
|
558
|
+
raise VaultError(f"Profile '{clean_name}' not found for {spec.id}.")
|
|
559
|
+
|
|
560
|
+
self._verify_profile_integrity(target_dir)
|
|
561
|
+
|
|
562
|
+
state = self._read_state()
|
|
563
|
+
prev_active = state.get("active", {}).get(spec.id)
|
|
564
|
+
synced_previous = False
|
|
565
|
+
|
|
566
|
+
if sync_current and prev_active and prev_active != clean_name:
|
|
567
|
+
prev_dir = self._profile_dir(spec.id, prev_active)
|
|
568
|
+
if prev_dir.is_dir() and any((self.paths.target_home / r).exists() for r in spec.targets):
|
|
569
|
+
tmp_sync = self.profiles_root / spec.id / f".tmp_sync_{prev_active}_{uuid.uuid4().hex[:6]}"
|
|
570
|
+
try:
|
|
571
|
+
prev_meta = json.loads((prev_dir / "manifest.json").read_text(encoding="utf-8"))
|
|
572
|
+
updated_manifest = self._capture_live_to_dir(
|
|
573
|
+
spec=spec,
|
|
574
|
+
dest_payload=tmp_sync / "payload",
|
|
575
|
+
name=prev_active,
|
|
576
|
+
note=prev_meta.get("note", ""),
|
|
577
|
+
existing_created_at=prev_meta.get("created_at"),
|
|
578
|
+
)
|
|
579
|
+
_atomic_write_json(tmp_sync / "manifest.json", updated_manifest.to_dict())
|
|
580
|
+
_force_rmtree(prev_dir)
|
|
581
|
+
tmp_sync.rename(prev_dir)
|
|
582
|
+
synced_previous = True
|
|
583
|
+
except Exception:
|
|
584
|
+
_force_rmtree(tmp_sync)
|
|
585
|
+
raise
|
|
586
|
+
|
|
587
|
+
backup_id: str | None = None
|
|
588
|
+
if entitlements.rolling_backups:
|
|
589
|
+
binfo = self._create_backup_snapshot(spec, reason=f"pre-switch -> {clean_name}")
|
|
590
|
+
if binfo:
|
|
591
|
+
backup_id = binfo.backup_id
|
|
592
|
+
|
|
593
|
+
self._atomic_apply_payload(spec, target_dir / "payload")
|
|
594
|
+
|
|
595
|
+
state.setdefault("active", {})[spec.id] = clean_name
|
|
596
|
+
self._write_state(state)
|
|
597
|
+
|
|
598
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
599
|
+
return SwitchResult(
|
|
600
|
+
provider=spec.id,
|
|
601
|
+
previous_profile=prev_active,
|
|
602
|
+
active_profile=clean_name,
|
|
603
|
+
synced_previous=synced_previous,
|
|
604
|
+
backup_id=backup_id,
|
|
605
|
+
elapsed_ms=round(elapsed_ms, 2),
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
def remove_profile(self, name: str, provider: str = "claude") -> None:
|
|
609
|
+
spec = _get_provider(provider)
|
|
610
|
+
clean_name = _validate_profile_name(name)
|
|
611
|
+
with self._locked():
|
|
612
|
+
target_dir = self._profile_dir(spec.id, clean_name)
|
|
613
|
+
if not target_dir.is_dir():
|
|
614
|
+
raise VaultError(f"Profile '{clean_name}' not found for {spec.id}.")
|
|
615
|
+
_force_rmtree(target_dir)
|
|
616
|
+
|
|
617
|
+
state = self._read_state()
|
|
618
|
+
if state.get("active", {}).get(spec.id) == clean_name:
|
|
619
|
+
state["active"].pop(spec.id, None)
|
|
620
|
+
self._write_state(state)
|
|
621
|
+
|
|
622
|
+
def list_backups(self, provider: str = "claude") -> list[BackupInfo]:
|
|
623
|
+
spec = _get_provider(provider)
|
|
624
|
+
entitlements = get_entitlements(self.paths.config_dir)
|
|
625
|
+
if not entitlements.rolling_backups:
|
|
626
|
+
raise ProFeatureRequiredError(
|
|
627
|
+
feature="rolling_backups",
|
|
628
|
+
detail="Rolling safety backups & time-machine restore require claudeshift Pro.",
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
broot = self.backups_root / spec.id
|
|
632
|
+
if not broot.is_dir():
|
|
633
|
+
return []
|
|
634
|
+
|
|
635
|
+
items: list[BackupInfo] = []
|
|
636
|
+
for child in sorted(broot.iterdir(), key=lambda p: p.name, reverse=True):
|
|
637
|
+
meta_file = child / "backup.json"
|
|
638
|
+
if child.is_dir() and meta_file.is_file():
|
|
639
|
+
with contextlib.suppress(Exception):
|
|
640
|
+
m = json.loads(meta_file.read_text(encoding="utf-8"))
|
|
641
|
+
items.append(
|
|
642
|
+
BackupInfo(
|
|
643
|
+
backup_id=m["backup_id"],
|
|
644
|
+
provider=m["provider"],
|
|
645
|
+
created_at=m["created_at"],
|
|
646
|
+
reason=m.get("reason", ""),
|
|
647
|
+
total_bytes=int(m.get("total_bytes", 0)),
|
|
648
|
+
path=str(child),
|
|
649
|
+
)
|
|
650
|
+
)
|
|
651
|
+
return items
|
|
652
|
+
|
|
653
|
+
def restore_backup(self, backup_id: str, provider: str = "claude") -> BackupInfo:
|
|
654
|
+
spec = _get_provider(provider)
|
|
655
|
+
clean_bid = _validate_backup_id(backup_id)
|
|
656
|
+
entitlements = get_entitlements(self.paths.config_dir)
|
|
657
|
+
if not entitlements.rolling_backups:
|
|
658
|
+
raise ProFeatureRequiredError(
|
|
659
|
+
feature="rolling_backups",
|
|
660
|
+
detail="Backup restore requires claudeshift Pro.",
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
with self._locked():
|
|
664
|
+
broot = self.backups_root / spec.id
|
|
665
|
+
bdir = _assert_within_root(broot, broot / clean_bid, "backup_id")
|
|
666
|
+
meta_file = bdir / "backup.json"
|
|
667
|
+
payload_dir = bdir / "payload"
|
|
668
|
+
if not meta_file.is_file() or not payload_dir.is_dir():
|
|
669
|
+
raise VaultError(f"Backup '{clean_bid}' not found for {spec.id}.")
|
|
670
|
+
|
|
671
|
+
m = json.loads(meta_file.read_text(encoding="utf-8"))
|
|
672
|
+
checksums = m.get("checksums")
|
|
673
|
+
if isinstance(checksums, dict):
|
|
674
|
+
_verify_checksums(payload_dir, checksums, f"backup '{clean_bid}'")
|
|
675
|
+
|
|
676
|
+
self._atomic_apply_payload(spec, payload_dir)
|
|
677
|
+
return BackupInfo(
|
|
678
|
+
backup_id=m["backup_id"],
|
|
679
|
+
provider=m["provider"],
|
|
680
|
+
created_at=m["created_at"],
|
|
681
|
+
reason=m.get("reason", ""),
|
|
682
|
+
total_bytes=int(m.get("total_bytes", 0)),
|
|
683
|
+
path=str(bdir),
|
|
684
|
+
)
|
|
685
|
+
|
|
686
|
+
def diff_profiles(self, profile_a: str, profile_b: str, provider: str = "claude") -> ProfileDiff:
|
|
687
|
+
spec = _get_provider(provider)
|
|
688
|
+
entitlements = get_entitlements(self.paths.config_dir)
|
|
689
|
+
if not entitlements.profile_diff:
|
|
690
|
+
raise ProFeatureRequiredError(
|
|
691
|
+
feature="profile_diff",
|
|
692
|
+
detail="Profile & MCP diffing requires claudeshift Pro.",
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
a_dir = self._profile_dir(spec.id, _validate_profile_name(profile_a))
|
|
696
|
+
b_dir = self._profile_dir(spec.id, _validate_profile_name(profile_b))
|
|
697
|
+
if not a_dir.is_dir():
|
|
698
|
+
raise VaultError(f"Profile '{profile_a}' not found.")
|
|
699
|
+
if not b_dir.is_dir():
|
|
700
|
+
raise VaultError(f"Profile '{profile_b}' not found.")
|
|
701
|
+
|
|
702
|
+
ma = self._verify_profile_integrity(a_dir)
|
|
703
|
+
mb = self._verify_profile_integrity(b_dir)
|
|
704
|
+
|
|
705
|
+
mcp_a = set(ma.identity.mcp_servers)
|
|
706
|
+
mcp_b = set(mb.identity.mcp_servers)
|
|
707
|
+
|
|
708
|
+
files_a = set(ma.checksums.keys())
|
|
709
|
+
files_b = set(mb.checksums.keys())
|
|
710
|
+
shared_files = files_a & files_b
|
|
711
|
+
changed = sorted(f for f in shared_files if ma.checksums[f] != mb.checksums[f])
|
|
712
|
+
|
|
713
|
+
return ProfileDiff(
|
|
714
|
+
provider=spec.id,
|
|
715
|
+
profile_a=ma.name,
|
|
716
|
+
profile_b=mb.name,
|
|
717
|
+
only_in_a_mcp=tuple(sorted(mcp_a - mcp_b)),
|
|
718
|
+
only_in_b_mcp=tuple(sorted(mcp_b - mcp_a)),
|
|
719
|
+
shared_mcp=tuple(sorted(mcp_a & mcp_b)),
|
|
720
|
+
changed_files=tuple(changed),
|
|
721
|
+
only_in_a_files=tuple(sorted(files_a - files_b)),
|
|
722
|
+
only_in_b_files=tuple(sorted(files_b - files_a)),
|
|
723
|
+
)
|