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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
OpenClaw Full Directory Persistence for Hugging Face Spaces
========================================================

This script provides atomic, complete persistence of the entire ~/.openclaw directory.
It implements the comprehensive persistence plan:

- Config & Credentials (openclaw.json, credentials/)
- Workspace (workspace/ with AGENTS.md, SOUL.md, TOOLS.md, MEMORY.md, skills/, memory/)
- Sessions (agents/*/sessions/*.jsonl)
- Memory Index (memory/*.sqlite)
- QMD Backend (agents/*/qmd/)
- Extensions (extensions/)
- All other state in ~/.openclaw

Usage:
    # Backup (save)
    python3 openclaw_persist.py save

    # Restore (load)
    python3 openclaw_persist.py load

Environment Variables:
    HF_TOKEN - Hugging Face access token with write permissions
    OPENCLAW_DATASET_REPO - Dataset repo ID (e.g., "username/openclaw-state")
    OPENCLAW_HOME - OpenClaw home directory (default: ~/.openclaw)
"""

import os
import sys
import json
import tarfile
import tempfile
import shutil
import hashlib
import time
import signal
from datetime import datetime
from pathlib import Path
from typing import Optional, List, Set, Dict, Any

from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError


# ============================================================================
# Configuration
# ============================================================================

class Config:
    """Configuration for persistence system"""

    # Paths
    OPENCLAW_HOME = Path(os.environ.get("OPENCLAW_HOME", "~/.openclaw")).expanduser()
    BACKUP_FILENAME = "openclaw-full.tar.gz"
    BACKUP_STATE_FILE = ".persistence-state.json"
    LOCK_FILE = ".persistence.lock"

    # Backup rotation settings
    MAX_BACKUPS = 5
    BACKUP_PREFIX = "backup-"

    # Patterns to exclude from backup
    EXCLUDE_PATTERNS = [
        "*.lock",
        "*.tmp",
        "*.pyc",
        "*__pycache__*",
        "*.socket",
        "*.pid",
        "node_modules",
        ".DS_Store",
        ".git",
    ]

    # Directories to skip entirely (relative to OPENCLAW_HOME)
    SKIP_DIRS = {
        ".cache",
        "logs",
        "temp",
        "tmp",
    }


# ============================================================================
# Utility Functions
# ============================================================================

def log(level: str, message: str, **kwargs):
    """Structured logging"""
    timestamp = datetime.now().isoformat()
    log_entry = {
        "timestamp": timestamp,
        "level": level,
        "message": message,
        **kwargs
    }
    print(json.dumps(log_entry), flush=True)


def calculate_file_hash(filepath: Path) -> str:
    """Calculate SHA256 hash of a file"""
    sha256 = hashlib.sha256()
    try:
        with open(filepath, "rb") as f:
            for chunk in iter(lambda: f.read(65536), b""):
                sha256.update(chunk)
        return sha256.hexdigest()
    except Exception:
        return ""


def get_directory_size(directory: Path) -> int:
    """Calculate total size of directory in bytes"""
    total_size = 0
    try:
        for dirpath, dirnames, filenames in os.walk(directory):
            for filename in filenames:
                filepath = Path(dirpath) / filename
                try:
                    total_size += filepath.stat().st_size
                except Exception:
                    pass
    except Exception:
        pass
    return total_size


def should_exclude(path: str, exclude_patterns: List[str]) -> bool:
    """Check if a path should be excluded based on patterns"""
    path_normalized = path.replace("\\", "/")

    for pattern in exclude_patterns:
        pattern = pattern.lstrip("/")
        if pattern.startswith("*"):
            suffix = pattern[1:]
            if path_normalized.endswith(suffix):
                return True
        elif pattern in path_normalized:
            return True

    return False


# ============================================================================
# Persistence Manager
# ============================================================================

class OpenClawPersistence:
    """
    Manages persistence of OpenClaw state to Hugging Face Dataset

    Features:
    - Atomic full-directory backup/restore
    - Proper exclusion of lock files and temporary data
    - Safe handling of SQLite databases
    - Backup rotation
    - Integrity verification
    """

    def __init__(self):
        self.api = None
        self.repo_id = os.environ.get("OPENCLAW_DATASET_REPO")
        self.token = os.environ.get("HF_TOKEN")
        self.home_dir = Config.OPENCLAW_HOME
        self.lock_file = self.home_dir / Config.LOCK_FILE
        self.state_file = self.home_dir / Config.BACKUP_STATE_FILE

        # Validate configuration
        if not self.repo_id:
            log("ERROR", "OPENCLAW_DATASET_REPO not set")
            raise ValueError("OPENCLAW_DATASET_REPO environment variable required")

        if not self.token:
            log("ERROR", "HF_TOKEN not set")
            raise ValueError("HF_TOKEN environment variable required")

        # Initialize API
        self.api = HfApi(token=self.token)

        log("INFO", "Initialized persistence manager",
            repo_id=self.repo_id,
            home_dir=str(self.home_dir))

    # -----------------------------------------------------------------------
    # Backup Operations
    # -----------------------------------------------------------------------

    def save(self) -> Dict[str, Any]:
        """
        Save current state to Hugging Face Dataset

        Creates a complete backup of ~/.openclaw directory as a tar.gz file.
        """
        operation_id = f"save-{int(time.time())}"
        start_time = time.time()

        log("INFO", "Starting save operation", operation_id=operation_id)

        # Check if home directory exists
        if not self.home_dir.exists():
            log("WARNING", "OpenClaw home directory does not exist, creating")
            self.home_dir.mkdir(parents=True, exist_ok=True)

        # Check for existing lock
        if self.lock_file.exists():
            log("WARNING", "Lock file exists, another operation may be in progress")
            # Continue anyway, but log warning

        # Create lock file
        try:
            self.lock_file.write_text(str(os.getpid()))
        except Exception as e:
            log("WARNING", "Could not create lock file", error=str(e))

        try:
            # Get directory info
            dir_size = get_directory_size(self.home_dir)
            log("INFO", "Directory size calculated",
                size_bytes=dir_size,
                size_mb=f"{dir_size / (1024*1024):.2f}")

            # Create tar archive
            with tempfile.TemporaryDirectory() as tmpdir:
                tar_path = Path(tmpdir) / Config.BACKUP_FILENAME
                manifest = self._create_tar_archive(tar_path)

                # Read archive info
                tar_size = tar_path.stat().st_size
                log("INFO", "Archive created",
                    size_bytes=tar_size,
                    size_mb=f"{tar_size / (1024*1024):.2f}",
                    files_count=manifest["file_count"])

                # Upload to dataset
                remote_path = f"{Config.BACKUP_PREFIX}{datetime.now().strftime('%Y%m%d_%H%M%S')}.tar.gz"
                upload_result = self._upload_archive(tar_path, remote_path)

                # Update state file
                self._update_state({
                    "last_save_time": datetime.now().isoformat(),
                    "last_save_operation": operation_id,
                    "last_save_remote_path": remote_path,
                    "last_save_commit": upload_result.get("commit_id"),
                    "last_save_manifest": manifest,
                })

                # Rotate old backups
                self._rotate_backups()

            duration = time.time() - start_time
            log("INFO", "Save completed successfully",
                operation_id=operation_id,
                duration_seconds=f"{duration:.2f}")

            return {
                "success": True,
                "operation_id": operation_id,
                "remote_path": remote_path,
                "commit_id": upload_result.get("commit_id"),
                "duration": duration,
                "manifest": manifest
            }

        except Exception as e:
            log("ERROR", "Save operation failed",
                operation_id=operation_id,
                error=str(e),
                exc_info=True)
            return {
                "success": False,
                "operation_id": operation_id,
                "error": str(e)
            }
        finally:
            # Remove lock file
            if self.lock_file.exists():
                try:
                    self.lock_file.unlink()
                except Exception:
                    pass

    def _create_tar_archive(self, tar_path: Path) -> Dict[str, Any]:
        """Create tar.gz archive of OpenClaw home directory"""
        manifest = {
            "created_at": datetime.now().isoformat(),
            "version": "1.0",
            "file_count": 0,
            "excluded_patterns": [],
            "included_dirs": [],
            "skipped_dirs": [],
        }

        excluded_count = 0

        def tar_filter(tarinfo: tarfile.TarInfo) -> Optional[tarfile.TarInfo]:
            nonlocal excluded_count, manifest

            # Skip lock file itself
            if tarinfo.name.endswith(Config.LOCK_FILE):
                excluded_count += 1
                return None

            # Skip state file (will be written after backup)
            if tarinfo.name.endswith(Config.BACKUP_STATE_FILE):
                return None

            # Get relative path
            rel_path = tarinfo.name
            if rel_path.startswith("./"):
                rel_path = rel_path[2:]

            # Check exclusion patterns
            if should_exclude(rel_path, Config.EXCLUDE_PATTERNS):
                excluded_count += 1
                manifest["excluded_patterns"].append(rel_path)
                return None

            # Check if parent directory should be skipped
            path_parts = Path(rel_path).parts
            if path_parts and path_parts[0] in Config.SKIP_DIRS:
                excluded_count += 1
                return None

            # Track included
            manifest["file_count"] += 1
            if path_parts and path_parts[0] not in manifest["included_dirs"]:
                manifest["included_dirs"].append(path_parts[0])

            return tarinfo

        # Create archive
        with tarfile.open(tar_path, "w:gz") as tar:
            tar.add(self.home_dir, arcname=".", filter=tar_filter)

        manifest["excluded_count"] = excluded_count
        manifest["skipped_dirs"] = list(Config.SKIP_DIRS)

        return manifest

    def _upload_archive(self, local_path: Path, remote_path: str) -> Dict[str, Any]:
        """Upload archive to Hugging Face Dataset"""
        try:
            # Ensure repo exists
            try:
                self.api.repo_info(repo_id=self.repo_id, repo_type="dataset")
            except RepositoryNotFoundError:
                log("INFO", "Creating new dataset repository")
                self.api.create_repo(
                    repo_id=self.repo_id,
                    repo_type="dataset",
                    private=True
                )

            # Upload file
            commit_info = self.api.upload_file(
                path_or_fileobj=str(local_path),
                path_in_repo=remote_path,
                repo_id=self.repo_id,
                repo_type="dataset",
                commit_message=f"OpenClaw state backup - {datetime.now().isoformat()}"
            )

            log("INFO", "File uploaded successfully",
                remote_path=remote_path,
                commit_url=commit_info.commit_url)

            return {
                "success": True,
                "commit_id": commit_info.oid,
                "commit_url": commit_info.commit_url
            }

        except Exception as e:
            log("ERROR", "Upload failed", error=str(e))
            raise

    def _update_state(self, state_update: Dict[str, Any]):
        """Update persistence state file"""
        try:
            current_state = {}
            if self.state_file.exists():
                with open(self.state_file, 'r') as f:
                    current_state = json.load(f)

            current_state.update(state_update)

            self.state_file.parent.mkdir(parents=True, exist_ok=True)
            with open(self.state_file, 'w') as f:
                json.dump(current_state, f, indent=2)

        except Exception as e:
            log("WARNING", "Could not update state file", error=str(e))

    def _rotate_backups(self):
        """Rotate old backups, keeping only MAX_BACKUPS most recent"""
        try:
            files = self.api.list_repo_files(
                repo_id=self.repo_id,
                repo_type="dataset"
            )

            # Get backup files
            backups = [
                f for f in files
                if f.startswith(Config.BACKUP_PREFIX) and f.endswith(".tar.gz")
            ]

            # Sort by name (which includes timestamp)
            backups = sorted(backups)

            # Delete old backups
            if len(backups) > Config.MAX_BACKUPS:
                to_delete = backups[:-Config.MAX_BACKUPS]
                log("INFO", "Rotating backups",
                    total=len(backups),
                    keeping=Config.MAX_BACKUPS,
                    deleting=len(to_delete))

                for old_backup in to_delete:
                    try:
                        self.api.delete_file(
                            path_in_repo=old_backup,
                            repo_id=self.repo_id,
                            repo_type="dataset"
                        )
                        log("INFO", "Deleted old backup", file=old_backup)
                    except Exception as e:
                        log("WARNING", "Could not delete backup",
                            file=old_backup,
                            error=str(e))

        except Exception as e:
            log("WARNING", "Backup rotation failed", error=str(e))

    # -----------------------------------------------------------------------
    # Restore Operations
    # -----------------------------------------------------------------------

    def load(self, force: bool = False) -> Dict[str, Any]:
        """
        Load state from Hugging Face Dataset

        Restores the most recent backup. If force is False and local state
        exists, it will create a backup before restoring.
        """
        operation_id = f"load-{int(time.time())}"
        start_time = time.time()

        log("INFO", "Starting load operation",
            operation_id=operation_id,
            force=force)

        try:
            # Get latest backup
            backup_info = self._find_latest_backup()

            if not backup_info:
                log("WARNING", "No backups found, starting fresh")
                # Ensure home directory exists
                self.home_dir.mkdir(parents=True, exist_ok=True)
                return {
                    "success": True,
                    "operation_id": operation_id,
                    "restored": False,
                    "message": "No backups found, starting fresh"
                }

            log("INFO", "Found backup to restore",
                backup_file=backup_info["filename"],
                timestamp=backup_info.get("timestamp"))

            # Create local backup if state exists
            if self.home_dir.exists() and not force:
                backup_dir = self._create_local_backup()
                log("INFO", "Created local backup", backup_dir=str(backup_dir))

            # Download and extract
            with tempfile.TemporaryDirectory() as tmpdir:
                tar_path = Path(tmpdir) / "backup.tar.gz"

                # Download backup
                log("INFO", "Downloading backup...")
                downloaded_path = hf_hub_download(
                    repo_id=self.repo_id,
                    filename=backup_info["filename"],
                    repo_type="dataset",
                    token=self.token,
                    local_dir=tmpdir,
                    local_dir_use_symlinks=False
                )

                # Extract archive
                log("INFO", "Extracting archive...")
                self._extract_archive(downloaded_path)

            duration = time.time() - start_time
            log("INFO", "Load completed successfully",
                operation_id=operation_id,
                duration_seconds=f"{duration:.2f}")

            return {
                "success": True,
                "operation_id": operation_id,
                "restored": True,
                "backup_file": backup_info["filename"],
                "duration": duration
            }

        except Exception as e:
            log("ERROR", "Load operation failed",
                operation_id=operation_id,
                error=str(e),
                exc_info=True)
            return {
                "success": False,
                "operation_id": operation_id,
                "error": str(e)
            }

    def _find_latest_backup(self) -> Optional[Dict[str, Any]]:
        """Find the latest backup file in the dataset"""
        try:
            files = self.api.list_repo_files(
                repo_id=self.repo_id,
                repo_type="dataset"
            )

            # Get backup files sorted by name (timestamp)
            backups = sorted(
                [f for f in files if f.startswith(Config.BACKUP_PREFIX) and f.endswith(".tar.gz")],
                reverse=True
            )

            if not backups:
                return None

            latest = backups[0]

            # Extract timestamp from filename
            timestamp_str = latest.replace(Config.BACKUP_PREFIX, "").replace(".tar.gz", "")
            try:
                timestamp = datetime.strptime(timestamp_str, "%Y%m%d_%H%M%S").isoformat()
            except ValueError:
                timestamp = None

            return {
                "filename": latest,
                "timestamp": timestamp
            }

        except Exception as e:
            log("ERROR", "Could not find latest backup", error=str(e))
            return None

    def _create_local_backup(self) -> Optional[Path]:
        """Create a backup of local state before restore"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_dir = self.home_dir.parent / f"{self.home_dir.name}_backup_{timestamp}"

        try:
            if self.home_dir.exists():
                shutil.copytree(self.home_dir, backup_dir)
                return backup_dir
        except Exception as e:
            log("WARNING", "Could not create local backup", error=str(e))

        return None

    def _extract_archive(self, tar_path: Path):
        """Extract tar.gz archive to home directory"""
        # Ensure home directory exists
        self.home_dir.mkdir(parents=True, exist_ok=True)

        # Extract archive
        with tarfile.open(tar_path, "r:gz") as tar:
            tar.extractall(self.home_dir)

        log("INFO", "Archive extracted successfully",
            destination=str(self.home_dir))


# ============================================================================
# CLI Interface
# ============================================================================

def main():
    if len(sys.argv) < 2:
        print("Usage: python openclaw_persist.py [save|load|status]", file=sys.stderr)
        print("", file=sys.stderr)
        print("Commands:", file=sys.stderr)
        print("  save    - Save current state to dataset", file=sys.stderr)
        print("  load    - Load state from dataset", file=sys.stderr)
        print("  status  - Show persistence status", file=sys.stderr)
        sys.exit(1)

    command = sys.argv[1].lower()

    try:
        manager = OpenClawPersistence()

        if command == "save":
            result = manager.save()
            print(json.dumps(result, indent=2))
            sys.exit(0 if result.get("success") else 1)

        elif command == "load":
            force = "--force" in sys.argv or "-f" in sys.argv
            result = manager.load(force=force)
            print(json.dumps(result, indent=2))
            sys.exit(0 if result.get("success") else 1)

        elif command == "status":
            # Show status information
            status = {
                "configured": True,
                "repo_id": manager.repo_id,
                "home_dir": str(manager.home_dir),
                "home_exists": manager.home_dir.exists(),
            }

            # Load state file
            if manager.state_file.exists():
                with open(manager.state_file, 'r') as f:
                    state = json.load(f)
                    status["state"] = state

            # List backups
            backups = manager._find_latest_backup()
            status["latest_backup"] = backups

            print(json.dumps(status, indent=2))
            sys.exit(0)

        else:
            print(f"Unknown command: {command}", file=sys.stderr)
            sys.exit(1)

    except Exception as e:
        print(json.dumps({
            "success": False,
            "error": str(e)
        }, indent=2))
        sys.exit(1)


if __name__ == "__main__":
    main()