#!/usr/bin/env python3 """dispatch-data-check.py: inventory and back up Claude Dispatch data before it turns off. Reads the local folder Anthropic documents for Dispatch data (local-agent-mode-sessions///agent) or the zip that "Download files" saves, and reports: - memory notes: count, size, and notes over 100 KB ("Copy to project" puts those in the project's Library only, not in its memory); - chat logs (folders starting with local_ditto_): size, and logs over 20 MiB (copy keeps only the newest messages) or 64 MiB (download keeps only the newest); - with --team, lines in memory notes that read like team rules or decisions, so you can move them somewhere your teammates' agents read. With --backup DIR it COPIES memory and chat logs into DIR with a SHA-256 manifest. It never moves, changes or deletes anything in the source. Standard library only. Nothing leaves your machine. Usage: python3 dispatch-data-check.py # look in the default folder python3 dispatch-data-check.py PATH # a folder or the downloaded .zip python3 dispatch-data-check.py PATH --team python3 dispatch-data-check.py PATH --backup ~/dispatch-backup """ import argparse, datetime, hashlib, json, os, re, shutil, sys, zipfile from pathlib import Path, PurePosixPath KB, MIB = 1024, 1024 * 1024 NOTE_LIBRARY_ONLY = 100 * KB # "A note over 100 KB goes to the Library only." CHAT_COPY_CAP = 20 * MIB # "up to 20 MiB when you copy" CHAT_DOWNLOAD_CAP = 64 * MIB # "and 64 MiB when you download" TEAM_HINTS = re.compile( r"\b(we decided|decided|decision|always|never|must|convention|rule|policy|" r"deploy|release|production|prod|staging|repo(sitory)?|branch|migration|" r"the team|our team|client|customer|on-call|owner)\b", re.I) OPAQUE = re.compile(r"[A-Za-z0-9_\-+/=]{20,}") def default_roots(): home = Path.home() cands = [home / "Library/Application Support/Claude/local-agent-mode-sessions", home / ".config/Claude/local-agent-mode-sessions"] for env in ("APPDATA", "LOCALAPPDATA"): if os.environ.get(env): cands.append(Path(os.environ[env]) / "Claude/local-agent-mode-sessions") return [c for c in cands if c.is_dir()] class Source: """A folder or a zip, seen as a list of (posix relative path, size, opener).""" def __init__(self, path): self.path = Path(path).expanduser() self.zip = zipfile.ZipFile(self.path) if self.path.is_file() and zipfile.is_zipfile(self.path) else None if not self.zip and not self.path.is_dir(): sys.exit(f"not a folder or a zip: {self.path}") def files(self): if self.zip: for info in self.zip.infolist(): if not info.is_dir(): yield PurePosixPath(info.filename), info.file_size, (lambda i=info: self.zip.open(i)) else: for root, _dirs, names in os.walk(self.path): for n in names: p = Path(root) / n if p.is_symlink(): continue rel = PurePosixPath(p.relative_to(self.path).as_posix()) yield rel, p.stat().st_size, (lambda p=p: open(p, "rb")) def safe_parts(rel): """Path parts that stay inside the backup folder, or None. A zip entry can be named /etc/x, ../../x or C:/x; copying it as-is would write outside the backup folder, so those entries are skipped.""" parts = rel.parts if not parts or rel.is_absolute() or ":" in parts[0] or any(x in ("", ".", "..") for x in parts): return None return parts def classify(rel): parts = [x.lower() for x in rel.parts] for i, part in enumerate(parts[:-1]): if part.startswith("local_ditto_"): return "chat", "/".join(rel.parts[: i + 1]) if "memory" in parts[:-1]: return "memory", None name = parts[-1] if name.startswith("local_ditto_"): return "chat", str(rel) if "schedul" in name: return "schedule", None return "other", None def human(n): for unit, size in (("MiB", MIB), ("KB", KB)): if n >= size: return f"{n / size:.1f} {unit}" return f"{n} B" def scan(src, team=False): rep = {"memory": [], "chats": {}, "schedule": [], "other": 0, "team_lines": []} for rel, size, opener in src.files(): kind, key = classify(rel) if kind == "memory": rep["memory"].append((str(rel), size)) if team and size <= 2 * MIB: with opener() as fh: text = fh.read().decode("utf-8", "replace") for no, line in enumerate(text.splitlines(), 1): m = TEAM_HINTS.search(line) if m and len(line.strip()) > 12: shown = OPAQUE.sub(lambda x: f"[{len(x.group(0))} chars hidden]", line.strip()) rep["team_lines"].append((str(rel), no, m.group(0).lower(), shown[:140])) elif kind == "chat": rep["chats"][key] = rep["chats"].get(key, 0) + size elif kind == "schedule": rep["schedule"].append((str(rel), size)) else: rep["other"] += 1 return rep def report(src, rep, team): mem = rep["memory"] print(f"source: {src.path}{' (zip)' if src.zip else ''}") print(f"\nmemory notes: {len(mem)} file(s), {human(sum(s for _, s in mem))}") big = [(p, s) for p, s in mem if s > NOTE_LIBRARY_ONLY] for p, s in big: print(f" OVER 100 KB, Library only on copy: {p} ({human(s)})") print(f"\nchat logs: {len(rep['chats'])} folder(s), {human(sum(rep['chats'].values()))}") for k, s in sorted(rep["chats"].items(), key=lambda x: -x[1]): flag = "" if s > CHAT_DOWNLOAD_CAP: flag = " OVER 64 MiB: copy AND download keep only the newest messages" elif s > CHAT_COPY_CAP: flag = " OVER 20 MiB: copy keeps only the newest messages; download keeps it whole" print(f" {k} ({human(s)}){flag}") if rep["schedule"]: print("\nfiles that look like the scheduled-task list:") for p, s in rep["schedule"]: print(f" {p} ({human(s)})") else: print("\nscheduled tasks: no list found here (Anthropic: the list usually isn't in this folder;" " it comes in the copy/download, as a list that does not run anything)") if team: print(f"\nlines that read like team rules or decisions: {len(rep['team_lines'])}") for p, no, hint, line in rep["team_lines"]: print(f" {p}:{no} [{hint}] {line}") print(f"\nother files: {rep['other']}") def backup(src, dest): dest = Path(dest).expanduser().resolve() if not src.zip: s = src.path.resolve() if dest == s or s in dest.parents: sys.exit("refusing: backup folder is inside the source folder") stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") out, n = dest / f"dispatch-backup-{stamp}", 1 while out.exists(): n += 1 out = dest / f"dispatch-backup-{stamp}-{n}" out.mkdir(parents=True) manifest, skipped = [], [] for rel, size, opener in src.files(): kind, _ = classify(rel) if kind not in ("memory", "chat", "schedule"): continue parts = safe_parts(rel) target = out / Path(*parts) if parts else None if target is None or out not in target.resolve().parents: skipped.append(str(rel)) continue target.parent.mkdir(parents=True, exist_ok=True) h = hashlib.sha256() with opener() as fi, open(target, "wb") as fo: for chunk in iter(lambda: fi.read(1 << 20), b""): h.update(chunk) fo.write(chunk) if not src.zip: shutil.copystat(src.path / Path(*rel.parts), target) manifest.append({"path": str(rel), "kind": kind, "bytes": size, "sha256": h.hexdigest()}) (out / "MANIFEST.json").write_text(json.dumps( {"source": str(src.path), "copied_at": stamp, "files": manifest, "skipped": skipped}, indent=2)) print(f"\ncopied {len(manifest)} file(s) to {out} (MANIFEST.json has a SHA-256 per file);" " the source was not changed") for name in skipped: print(f" skipped, path would leave the backup folder: {name}") def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("path", nargs="?", help="local-agent-mode-sessions folder, an agent folder, or the downloaded zip") ap.add_argument("--team", action="store_true", help="list memory lines that read like team rules or decisions") ap.add_argument("--backup", metavar="DIR", help="copy memory, chat logs and schedule files into DIR") a = ap.parse_args() paths = [Path(a.path)] if a.path else default_roots() if not paths: sys.exit("no local-agent-mode-sessions folder in the default places; pass the folder or the zip") for p in paths: src = Source(p) rep = scan(src, a.team) report(src, rep, a.team) if a.backup: backup(src, a.backup) if __name__ == "__main__": main()