backfill 0.3.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.
- backfill/__init__.py +6 -0
- backfill/__main__.py +3 -0
- backfill/agents/__init__.py +28 -0
- backfill/agents/claude.py +551 -0
- backfill/agents/codex.py +786 -0
- backfill/capture.py +174 -0
- backfill/clean.py +365 -0
- backfill/cli.py +445 -0
- backfill/config.py +272 -0
- backfill/core.py +266 -0
- backfill/layout.py +110 -0
- backfill/legacy.py +146 -0
- backfill/ops.py +307 -0
- backfill/redact.py +89 -0
- backfill/roots.py +84 -0
- backfill/runtime.py +135 -0
- backfill/status.py +237 -0
- backfill/transcript.py +269 -0
- backfill/util.py +276 -0
- backfill-0.3.0.dist-info/METADATA +231 -0
- backfill-0.3.0.dist-info/RECORD +25 -0
- backfill-0.3.0.dist-info/WHEEL +5 -0
- backfill-0.3.0.dist-info/entry_points.txt +2 -0
- backfill-0.3.0.dist-info/licenses/LICENSE +21 -0
- backfill-0.3.0.dist-info/top_level.txt +1 -0
backfill/capture.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Copying what an agent keeps for a session into the project's log folder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import tempfile
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from backfill.layout import Layout
|
|
17
|
+
from backfill.redact import Redactor
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def sync_transcript(
|
|
21
|
+
layout: Layout, session_id: str, source: Path, mode: str, redactor: Redactor, state: dict[str, Any]
|
|
22
|
+
) -> bool:
|
|
23
|
+
"""Make ``transcripts/<session>.jsonl`` follow the live transcript. True when a copy is present afterwards.
|
|
24
|
+
|
|
25
|
+
``raw``: byte-for-byte; normally only the new bytes are appended. ``redacted``: the same, line by line, with
|
|
26
|
+
secrets removed (``state['copy_offset']`` remembers how much of the source was consumed). ``off``: no copy.
|
|
27
|
+
"""
|
|
28
|
+
destination = layout.transcript_path(session_id)
|
|
29
|
+
if mode == "off" or not source.is_file():
|
|
30
|
+
return destination.exists()
|
|
31
|
+
try:
|
|
32
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
source_size = source.stat().st_size
|
|
34
|
+
if mode == "redacted":
|
|
35
|
+
return _sync_redacted(source, destination, source_size, redactor, state)
|
|
36
|
+
have = destination.stat().st_size if destination.exists() else -1
|
|
37
|
+
if have == source_size:
|
|
38
|
+
return True
|
|
39
|
+
if 0 < have < source_size:
|
|
40
|
+
with source.open("rb") as reader:
|
|
41
|
+
reader.seek(have)
|
|
42
|
+
chunk = reader.read(source_size - have)
|
|
43
|
+
with destination.open("ab") as writer:
|
|
44
|
+
writer.write(chunk)
|
|
45
|
+
if destination.stat().st_size == source_size:
|
|
46
|
+
return True
|
|
47
|
+
if have > source_size: # the source shrank or was rewritten: keep what we had instead of overwriting it
|
|
48
|
+
shutil.copyfile(destination, destination.with_name(f"{destination.stem}.prev-{time.strftime('%Y%m%dT%H%M%S')}.jsonl"))
|
|
49
|
+
temporary = destination.with_name(destination.name + ".tmp")
|
|
50
|
+
shutil.copyfile(source, temporary)
|
|
51
|
+
os.replace(temporary, destination)
|
|
52
|
+
except OSError:
|
|
53
|
+
return destination.exists()
|
|
54
|
+
return True
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _sync_redacted(source: Path, destination: Path, source_size: int, redactor: Redactor, state: dict[str, Any]) -> bool:
|
|
58
|
+
offset = int(state.get("copy_offset") or 0)
|
|
59
|
+
if offset > source_size or not destination.exists():
|
|
60
|
+
offset = 0 # source shrank (or the copy vanished): start over
|
|
61
|
+
destination.unlink(missing_ok=True)
|
|
62
|
+
if offset == source_size:
|
|
63
|
+
return True
|
|
64
|
+
with source.open("rb") as reader:
|
|
65
|
+
reader.seek(offset)
|
|
66
|
+
data = reader.read()
|
|
67
|
+
end = data.rfind(b"\n") + 1 # only whole lines; a half-written last line waits for the next call
|
|
68
|
+
if end == 0:
|
|
69
|
+
return destination.exists()
|
|
70
|
+
text = data[:end].decode("utf-8", errors="replace")
|
|
71
|
+
with destination.open("ab") as writer:
|
|
72
|
+
writer.write(redactor.text(text).encode("utf-8"))
|
|
73
|
+
state["copy_offset"] = offset + end
|
|
74
|
+
return True
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def mirror_tree(source: Path, destination: Path) -> int:
|
|
78
|
+
"""Copy files that are missing or changed from ``source`` into ``destination``; returns how many were copied."""
|
|
79
|
+
copied = 0
|
|
80
|
+
for item in source.rglob("*"):
|
|
81
|
+
try:
|
|
82
|
+
if not item.is_file():
|
|
83
|
+
continue
|
|
84
|
+
target = destination / item.relative_to(source)
|
|
85
|
+
if target.exists() and target.stat().st_size == item.stat().st_size:
|
|
86
|
+
continue
|
|
87
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
88
|
+
shutil.copy2(item, target)
|
|
89
|
+
copied += 1
|
|
90
|
+
except OSError:
|
|
91
|
+
continue
|
|
92
|
+
return copied
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def git_snapshot(root: Path) -> dict[str, Any]:
|
|
96
|
+
def run(*args: str) -> str | None:
|
|
97
|
+
try:
|
|
98
|
+
result = subprocess.run(
|
|
99
|
+
["git", *args], cwd=root, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5
|
|
100
|
+
)
|
|
101
|
+
except (OSError, subprocess.SubprocessError):
|
|
102
|
+
return None
|
|
103
|
+
return result.stdout.strip() if result.returncode == 0 else None
|
|
104
|
+
|
|
105
|
+
status = run("status", "--short")
|
|
106
|
+
return {
|
|
107
|
+
"branch": run("rev-parse", "--abbrev-ref", "HEAD"),
|
|
108
|
+
"head": run("rev-parse", "HEAD"),
|
|
109
|
+
"changed_files": len(status.splitlines()) if status else 0,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
TEXT_SUFFIXES = {
|
|
114
|
+
".txt", ".md", ".json", ".jsonl", ".csv", ".tsv", ".log", ".py", ".js", ".ts", ".tsx", ".jsx", ".html", ".css", ".xml", ".yml", ".yaml",
|
|
115
|
+
".toml", ".ini", ".cfg", ".sh", ".ps1", ".bat", ".sql", ".rb", ".go", ".rs", ".java", ".kt", ".c", ".h", ".cpp", ".swift", ".diff", ".patch",
|
|
116
|
+
}
|
|
117
|
+
MEGABYTE = 1024 * 1024
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def scratch_dirs(env: Mapping[str, str], session_id: str) -> list[Path]:
|
|
121
|
+
"""Claude Code's scratchpad folders of a session: ``<tmp>/claude-<uid>/<project>/<session>/scratchpad`` (``<tmp>/claude/...`` on Windows)."""
|
|
122
|
+
configured = env.get("BACKFILL_TMP_DIRS", "")
|
|
123
|
+
bases = [Path(p) for p in configured.split(os.pathsep) if p] if configured else [Path("/tmp"), Path(tempfile.gettempdir())]
|
|
124
|
+
uid = os.getuid() if hasattr(os, "getuid") else None
|
|
125
|
+
names = ["claude"] + ([f"claude-{uid}"] if uid is not None else [])
|
|
126
|
+
found: dict[str, Path] = {}
|
|
127
|
+
for base in bases:
|
|
128
|
+
for name in names:
|
|
129
|
+
try:
|
|
130
|
+
for candidate in (base / name).glob(f"*/{session_id}/scratchpad"):
|
|
131
|
+
if candidate.is_dir():
|
|
132
|
+
found[str(candidate.resolve())] = candidate
|
|
133
|
+
except OSError:
|
|
134
|
+
continue
|
|
135
|
+
return list(found.values())
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def snapshot_files(source: Path, target: Path, label: str, mode: str, max_bytes: int, redactor: Redactor) -> dict[str, int]:
|
|
139
|
+
"""``manifest``: ``<label>-manifest.json`` (names, sizes, times, hashes). ``copy``: also keep the files of at most ``max_bytes``
|
|
140
|
+
(text with secrets removed). Returns counts for the session state."""
|
|
141
|
+
if mode == "off" or not source.is_dir():
|
|
142
|
+
return {}
|
|
143
|
+
files: list[dict[str, object]] = []
|
|
144
|
+
copied = 0
|
|
145
|
+
for item in sorted(source.rglob("*")):
|
|
146
|
+
try:
|
|
147
|
+
if not item.is_file() or item.name.startswith("._"):
|
|
148
|
+
continue
|
|
149
|
+
info = item.stat()
|
|
150
|
+
relative = item.relative_to(source).as_posix()
|
|
151
|
+
entry: dict[str, object] = {"path": relative, "bytes": info.st_size, "modified": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(info.st_mtime))}
|
|
152
|
+
if info.st_size <= max_bytes:
|
|
153
|
+
entry["sha256"] = hashlib.sha256(item.read_bytes()).hexdigest()
|
|
154
|
+
files.append(entry)
|
|
155
|
+
if mode == "copy" and info.st_size <= max_bytes:
|
|
156
|
+
destination = target / label / relative
|
|
157
|
+
if destination.exists() and destination.stat().st_mtime >= info.st_mtime:
|
|
158
|
+
continue
|
|
159
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
160
|
+
if item.suffix.lower() in TEXT_SUFFIXES:
|
|
161
|
+
destination.write_text(redactor.text(item.read_text(encoding="utf-8", errors="replace")), encoding="utf-8")
|
|
162
|
+
else:
|
|
163
|
+
shutil.copy2(item, destination)
|
|
164
|
+
copied += 1
|
|
165
|
+
except OSError:
|
|
166
|
+
continue
|
|
167
|
+
if not files:
|
|
168
|
+
return {}
|
|
169
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
manifest = target / f"{label}-manifest.json"
|
|
171
|
+
text = json.dumps({"source": str(source), "files": files}, ensure_ascii=False, indent=1)
|
|
172
|
+
if not manifest.exists() or manifest.read_text(encoding="utf-8") != text:
|
|
173
|
+
manifest.write_text(text, encoding="utf-8")
|
|
174
|
+
return {f"{label}_files": len(files), f"{label}_copied": copied} if copied else {f"{label}_files": len(files)}
|
backfill/clean.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""``backfill clean``: a map of what the agents keep on this machine, and a safe way to prune it.
|
|
2
|
+
|
|
3
|
+
Rules that make it safe:
|
|
4
|
+
* a dry run unless ``--apply``; applied removals go to ``<backfill data>/trash/<time>/`` first (``--delete`` removes for good);
|
|
5
|
+
* an agent's own transcript is only offered for removal when backfill has verified a complete copy of that session in a project;
|
|
6
|
+
* only things older than ``--older-than`` days are touched (a running session is never that old);
|
|
7
|
+
* databases, credentials, config, memory, skills and plugins are never candidates, at most listed as "report only".
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from backfill.capture import scratch_dirs
|
|
23
|
+
from backfill.config import AGENTS, load_config
|
|
24
|
+
from backfill.core import registered_projects
|
|
25
|
+
from backfill.layout import Layout
|
|
26
|
+
from backfill.util import Context, folder_size, read_json
|
|
27
|
+
|
|
28
|
+
SESSION_ID_TAIL = re.compile(r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$")
|
|
29
|
+
SKIP_SCAN_DIRS = {"node_modules", ".git", ".venv", "venv", "__pycache__", "Library", "AppData", ".Trash", "dist", "build", "target"}
|
|
30
|
+
LOG_DIR_NAMES = {"claude": (".claude-logs", "_claude_logs"), "codex": (".codex-logs", "_codex_logs")}
|
|
31
|
+
LOG_NAMES = {name for names in LOG_DIR_NAMES.values() for name in names}
|
|
32
|
+
CATEGORIES = ("transcripts", "caches", "scratchpads")
|
|
33
|
+
PROTECTED = {"auth.json", "config.toml", "settings.json", "CLAUDE.md", "AGENTS.md", "hooks.json", "memories", "skills", "plugins", "rules"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Item:
|
|
38
|
+
category: str # transcripts | caches | scratchpads | databases | project-logs
|
|
39
|
+
label: str
|
|
40
|
+
path: Path
|
|
41
|
+
bytes: int
|
|
42
|
+
files: int
|
|
43
|
+
newest: float
|
|
44
|
+
prune: bool # True: a candidate for removal (old enough and, for transcripts, saved)
|
|
45
|
+
note: str = ""
|
|
46
|
+
session: str | None = None
|
|
47
|
+
agent: str | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class Report:
|
|
52
|
+
items: list[Item] = field(default_factory=list)
|
|
53
|
+
older_than_days: int = 30
|
|
54
|
+
saved_index_size: int = 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _tree_stats(path: Path) -> tuple[int, int, float]:
|
|
58
|
+
"""(bytes, file count, newest mtime) of a file or folder; symbolic links count as links, not as what they point to."""
|
|
59
|
+
try:
|
|
60
|
+
info = path.lstat()
|
|
61
|
+
if not path.is_dir() or path.is_symlink():
|
|
62
|
+
return (0 if path.is_symlink() else info.st_size), 1, info.st_mtime
|
|
63
|
+
total = count = 0
|
|
64
|
+
newest = info.st_mtime
|
|
65
|
+
for current, _dirs, files in os.walk(path, followlinks=False):
|
|
66
|
+
for name in files:
|
|
67
|
+
try:
|
|
68
|
+
stat = (Path(current) / name).lstat()
|
|
69
|
+
except OSError:
|
|
70
|
+
continue
|
|
71
|
+
count += 1
|
|
72
|
+
newest = max(newest, stat.st_mtime)
|
|
73
|
+
if not (stat.st_mode & 0o170000) == 0o120000: # not a symlink
|
|
74
|
+
total += stat.st_size
|
|
75
|
+
return total, count, newest
|
|
76
|
+
except OSError:
|
|
77
|
+
return 0, 0, time.time()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# --- which sessions backfill has saved ---------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def log_folders(root: Path) -> Iterator[tuple[str, Path]]:
|
|
84
|
+
for agent, names in LOG_DIR_NAMES.items():
|
|
85
|
+
for name in names:
|
|
86
|
+
if (root / name).is_dir():
|
|
87
|
+
yield agent, root / name
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def discover_projects(ctx: Context, scan: list[Path], depth: int = 4) -> list[Path]:
|
|
91
|
+
"""Registered projects plus any folder under ``scan`` that holds log folders (bounded walk)."""
|
|
92
|
+
found: dict[str, Path] = {str(p): p for p in registered_projects(ctx) if p.is_dir()}
|
|
93
|
+
for base in scan:
|
|
94
|
+
base = base.expanduser().resolve()
|
|
95
|
+
if not base.is_dir():
|
|
96
|
+
continue
|
|
97
|
+
for current, dirs, _ in os.walk(base):
|
|
98
|
+
here = Path(current)
|
|
99
|
+
if LOG_NAMES & set(dirs):
|
|
100
|
+
found.setdefault(str(here), here)
|
|
101
|
+
dirs[:] = [d for d in dirs if d not in SKIP_SCAN_DIRS and not d.startswith(".") and d not in LOG_NAMES]
|
|
102
|
+
if len(here.relative_to(base).parts) >= depth:
|
|
103
|
+
dirs[:] = []
|
|
104
|
+
return list(found.values())
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def saved_index(ctx: Context, projects: list[Path]) -> dict[tuple[str, str], dict[str, Any]]:
|
|
108
|
+
"""(agent, session id) -> where backfill keeps its copy of that session."""
|
|
109
|
+
index: dict[tuple[str, str], dict[str, Any]] = {}
|
|
110
|
+
for root in projects:
|
|
111
|
+
config = load_config(ctx, root)
|
|
112
|
+
for agent in AGENTS:
|
|
113
|
+
layout = Layout(root, agent, config)
|
|
114
|
+
if not layout.state.is_dir():
|
|
115
|
+
continue
|
|
116
|
+
for state_file in layout.state.glob("*.json"):
|
|
117
|
+
state = read_json(state_file)
|
|
118
|
+
sid = str(state.get("session_id") or "")
|
|
119
|
+
if sid:
|
|
120
|
+
index[(agent, sid)] = {"layout": layout, "mode": config["capture"]["transcripts"], "state": state}
|
|
121
|
+
return index
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def is_saved(entry: dict[str, Any] | None, source: Path) -> bool:
|
|
125
|
+
"""True when backfill's copy holds the whole of ``source`` (raw: same or larger size; redacted: consumed to the end)."""
|
|
126
|
+
if not entry or entry["mode"] == "off":
|
|
127
|
+
return False
|
|
128
|
+
layout: Layout = entry["layout"]
|
|
129
|
+
sid = str(entry["state"]["session_id"])
|
|
130
|
+
try:
|
|
131
|
+
size = source.stat().st_size
|
|
132
|
+
copy = layout.transcript_path(sid)
|
|
133
|
+
if not copy.is_file():
|
|
134
|
+
return False
|
|
135
|
+
if entry["mode"] == "raw":
|
|
136
|
+
return copy.stat().st_size >= size
|
|
137
|
+
return int(entry["state"].get("copy_offset") or 0) >= size
|
|
138
|
+
except OSError:
|
|
139
|
+
return False
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# --- scanning ----------------------------------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _old(newest: float, days: int) -> bool:
|
|
146
|
+
return newest < time.time() - days * 86400
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _session_of(path: Path) -> str | None:
|
|
150
|
+
match = SESSION_ID_TAIL.search(path.stem)
|
|
151
|
+
return match.group(1) if match else None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def scan(ctx: Context, *, older_than_days: int = 30, scan_roots: list[Path] | None = None) -> Report:
|
|
155
|
+
report = Report(older_than_days=older_than_days)
|
|
156
|
+
projects = discover_projects(ctx, scan_roots or [])
|
|
157
|
+
index = saved_index(ctx, projects)
|
|
158
|
+
report.saved_index_size = len(index)
|
|
159
|
+
add = report.items.append
|
|
160
|
+
|
|
161
|
+
def transcript(agent: str, path: Path, sid: str | None, label: str) -> None:
|
|
162
|
+
size, count, newest = _tree_stats(path)
|
|
163
|
+
old = _old(newest, older_than_days)
|
|
164
|
+
saved = bool(sid) and is_saved(index.get((agent, sid or "")), path)
|
|
165
|
+
note = "" if saved else ("not saved in any project yet: `backfill sync --all`" if old else "")
|
|
166
|
+
add(Item("transcripts", label, path, size, count, newest, old and saved, note, sid, agent))
|
|
167
|
+
|
|
168
|
+
# Claude: ~/.claude/projects/<project>/<session>.jsonl (+ <session>/ for subagents and tool results)
|
|
169
|
+
projects_dir = ctx.claude_home / "projects"
|
|
170
|
+
if projects_dir.is_dir():
|
|
171
|
+
for folder in sorted(p for p in projects_dir.iterdir() if p.is_dir()):
|
|
172
|
+
for file in sorted(folder.glob("*.jsonl")):
|
|
173
|
+
transcript("claude", file, file.stem, f"claude {folder.name}/{file.name}")
|
|
174
|
+
for extra in sorted(p for p in folder.iterdir() if p.is_dir()): # <session>/: subagent transcripts and tool results
|
|
175
|
+
main = folder / f"{extra.name}.jsonl"
|
|
176
|
+
if main.is_file():
|
|
177
|
+
size, count, newest = _tree_stats(extra)
|
|
178
|
+
saved = is_saved(index.get(("claude", extra.name)), main)
|
|
179
|
+
add(Item("transcripts", f"claude {folder.name}/{extra.name}/ (subagents, tool results)", extra, size, count, newest,
|
|
180
|
+
_old(newest, older_than_days) and saved, "", extra.name, "claude"))
|
|
181
|
+
# Codex: rollouts, also in archived_sessions
|
|
182
|
+
for base in (ctx.codex_home / "sessions", ctx.codex_home / "archived_sessions"):
|
|
183
|
+
if base.is_dir():
|
|
184
|
+
for file in sorted(base.rglob("rollout-*.jsonl")):
|
|
185
|
+
transcript("codex", file, _session_of(file), f"codex {file.relative_to(ctx.codex_home).as_posix()}")
|
|
186
|
+
|
|
187
|
+
def cache(label: str, path: Path, note: str = "", *, session: str | None = None, agent: str | None = None, need_saved: bool = False) -> None:
|
|
188
|
+
size, count, newest = _tree_stats(path)
|
|
189
|
+
old = _old(newest, older_than_days)
|
|
190
|
+
saved = True
|
|
191
|
+
if need_saved:
|
|
192
|
+
saved = bool(session) and (agent or "", session or "") in index
|
|
193
|
+
note = note or ("" if saved else "session not logged by backfill")
|
|
194
|
+
add(Item("caches", label, path, size, count, newest, old and saved, note, session, agent))
|
|
195
|
+
|
|
196
|
+
# Claude: edit backups, todos, shell snapshots, pasted content, per-session env
|
|
197
|
+
for name, keyed in (("file-history", True), ("todos", False), ("shell-snapshots", False), ("paste-cache", False), ("session-env", True)):
|
|
198
|
+
folder = ctx.claude_home / name
|
|
199
|
+
if folder.is_dir():
|
|
200
|
+
for entry in sorted(folder.iterdir()):
|
|
201
|
+
sid = entry.name.split("-agent-")[0] if name == "todos" else entry.name
|
|
202
|
+
cache(f"claude {name}/{entry.name}", entry, session=sid if keyed or name == "todos" else None, agent="claude", need_saved=keyed)
|
|
203
|
+
# Codex: shell snapshots and the cache folder (rebuilt on demand)
|
|
204
|
+
for name in ("shell_snapshots", "cache", "tmp"):
|
|
205
|
+
folder = ctx.codex_home / name
|
|
206
|
+
if folder.is_dir():
|
|
207
|
+
for entry in sorted(folder.iterdir()):
|
|
208
|
+
# tmp/arg0*/ holds one throw-away folder per Codex launch: judge each by its own age
|
|
209
|
+
children = sorted(entry.iterdir()) if name == "tmp" and entry.is_dir() and not entry.is_symlink() else [entry]
|
|
210
|
+
for child in children:
|
|
211
|
+
cache(f"codex {child.relative_to(ctx.codex_home).as_posix()}", child, agent="codex")
|
|
212
|
+
images = ctx.codex_home / "generated_images"
|
|
213
|
+
if images.is_dir():
|
|
214
|
+
for entry in sorted(images.iterdir()):
|
|
215
|
+
owner = index.get(("codex", entry.name))
|
|
216
|
+
kept = owner is not None and (owner["layout"].session_artifacts(entry.name) / "generated_images").is_dir()
|
|
217
|
+
size, count, newest = _tree_stats(entry)
|
|
218
|
+
add(Item("caches", f"codex generated_images/{entry.name}", entry, size, count, newest, _old(newest, older_than_days) and kept,
|
|
219
|
+
"" if kept else "images not copied (set capture.scratchpad = \"copy\")", entry.name, "codex"))
|
|
220
|
+
|
|
221
|
+
# scratchpads of Claude Code sessions: <tmp>/claude-<uid>/<project>/<session>/
|
|
222
|
+
seen: set[str] = set()
|
|
223
|
+
for sid_folder in _scratch_session_folders(ctx):
|
|
224
|
+
if str(sid_folder) in seen:
|
|
225
|
+
continue
|
|
226
|
+
seen.add(str(sid_folder))
|
|
227
|
+
size, count, newest = _tree_stats(sid_folder)
|
|
228
|
+
entry = index.get(("claude", sid_folder.name))
|
|
229
|
+
kept = "manifest" if entry and (entry["layout"].session_artifacts(sid_folder.name) / "scratchpad-manifest.json").is_file() else "not recorded"
|
|
230
|
+
add(Item("scratchpads", f"scratchpad {sid_folder.parent.name}/{sid_folder.name}", sid_folder, size, count, newest,
|
|
231
|
+
_old(newest, older_than_days), f"files {kept}", sid_folder.name, "claude"))
|
|
232
|
+
|
|
233
|
+
# report only: databases and project log folders
|
|
234
|
+
for home, agent in ((ctx.codex_home, "codex"), (ctx.claude_home, "claude")):
|
|
235
|
+
if home.is_dir():
|
|
236
|
+
for db in sorted(home.glob("*.sqlite")):
|
|
237
|
+
size, count, newest = _tree_stats(db)
|
|
238
|
+
if size >= 10 * 1024 * 1024:
|
|
239
|
+
add(Item("databases", f"{agent} {db.name}", db, size, count, newest, False, "not pruned: the agent's own database", None, agent))
|
|
240
|
+
for root in projects:
|
|
241
|
+
for agent, folder in log_folders(root):
|
|
242
|
+
size, count, newest = _tree_stats(folder)
|
|
243
|
+
add(Item("project-logs", f"{root.name}/{folder.name}", folder, size, count, newest, False,
|
|
244
|
+
f"prune with `backfill retain --project {root} --days N`", None, agent))
|
|
245
|
+
return report
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _scratch_session_folders(ctx: Context) -> list[Path]:
|
|
249
|
+
folders: list[Path] = []
|
|
250
|
+
for scratch in scratch_dirs(ctx.env, "*"):
|
|
251
|
+
folders.append(scratch.parent)
|
|
252
|
+
return folders
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# --- applying ----------------------------------------------------------------------------------------------------
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def candidates(report: Report, only: tuple[str, ...] = CATEGORIES) -> list[Item]:
|
|
259
|
+
return [item for item in report.items if item.prune and item.category in only]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _guard(item: Item, ctx: Context) -> None:
|
|
263
|
+
"""Last line of defence: only agent folders, and scratchpad folders shaped ``<tmp>/claude[-uid]/<project>/<session>``."""
|
|
264
|
+
resolved = item.path.resolve()
|
|
265
|
+
inside_agent_home = any(home.resolve() in resolved.parents for home in (ctx.claude_home, ctx.codex_home) if home.exists())
|
|
266
|
+
uid = os.getuid() if hasattr(os, "getuid") else None
|
|
267
|
+
scratch = item.category == "scratchpads" and resolved.parent.parent.name in {"claude", f"claude-{uid}"}
|
|
268
|
+
if item.path.name in PROTECTED or not (scratch or (inside_agent_home and item.category != "scratchpads")):
|
|
269
|
+
raise ValueError(f"refusing to remove {item.path}")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def apply(report: Report, ctx: Context, *, only: tuple[str, ...] = CATEGORIES, delete: bool = False) -> dict[str, Any]:
|
|
273
|
+
chosen = candidates(report, only)
|
|
274
|
+
stamp = time.strftime("%Y%m%dT%H%M%S")
|
|
275
|
+
trash = ctx.shared_root / "trash" / stamp
|
|
276
|
+
moved: list[dict[str, str]] = []
|
|
277
|
+
freed = errors = 0
|
|
278
|
+
for item in chosen:
|
|
279
|
+
try:
|
|
280
|
+
_guard(item, ctx)
|
|
281
|
+
if delete:
|
|
282
|
+
shutil.rmtree(item.path) if item.path.is_dir() else item.path.unlink(missing_ok=True)
|
|
283
|
+
else:
|
|
284
|
+
target = trash / item.category / re.sub(r"[^\w.-]+", "_", item.label)
|
|
285
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
286
|
+
shutil.move(str(item.path), str(target))
|
|
287
|
+
moved.append({"from": str(item.path), "to": str(target)})
|
|
288
|
+
freed += item.bytes
|
|
289
|
+
except (OSError, ValueError):
|
|
290
|
+
errors += 1
|
|
291
|
+
if moved:
|
|
292
|
+
(trash / "manifest.json").write_text(json.dumps({"moved": moved}, indent=1), encoding="utf-8")
|
|
293
|
+
return {"removed": len(chosen) - errors, "errors": errors, "bytes": freed, "trash": str(trash) if moved else None, "deleted": delete}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def empty_trash(ctx: Context) -> dict[str, Any]:
|
|
297
|
+
trash = ctx.shared_root / "trash"
|
|
298
|
+
size = folder_size(trash) if trash.is_dir() else 0
|
|
299
|
+
if trash.is_dir():
|
|
300
|
+
shutil.rmtree(trash)
|
|
301
|
+
return {"bytes": size}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def restore(ctx: Context, stamp: str) -> int:
|
|
305
|
+
"""Move the items of one trash batch back to where they came from (never overwrites)."""
|
|
306
|
+
manifest = read_json(ctx.shared_root / "trash" / stamp / "manifest.json")
|
|
307
|
+
count = 0
|
|
308
|
+
for entry in manifest.get("moved", []):
|
|
309
|
+
source, target = Path(entry["to"]), Path(entry["from"])
|
|
310
|
+
if source.exists() and not target.exists():
|
|
311
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
312
|
+
shutil.move(str(source), str(target))
|
|
313
|
+
count += 1
|
|
314
|
+
return count
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
# --- text ----------------------------------------------------------------------------------------------------------
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def render(report: Report, *, only: tuple[str, ...] = CATEGORIES, top: int = 8) -> str:
|
|
321
|
+
from backfill.util import human_bytes
|
|
322
|
+
|
|
323
|
+
lines = [f"What the agents keep on this machine (prune candidates are older than {report.older_than_days} days"
|
|
324
|
+
f"{' and already saved by backfill' if 'transcripts' in only else ''}):", ""]
|
|
325
|
+
titles = {
|
|
326
|
+
"transcripts": "Agent transcripts (Claude, Codex)",
|
|
327
|
+
"caches": "Caches, snapshots, edit backups, images",
|
|
328
|
+
"scratchpads": "Scratchpads in the temp folder",
|
|
329
|
+
"databases": "Agent databases (report only)",
|
|
330
|
+
"project-logs": "Project log folders (report only)",
|
|
331
|
+
}
|
|
332
|
+
total_free = 0
|
|
333
|
+
for category, title in titles.items():
|
|
334
|
+
if category in CATEGORIES and category not in only:
|
|
335
|
+
continue
|
|
336
|
+
items = [i for i in report.items if i.category == category]
|
|
337
|
+
if not items:
|
|
338
|
+
continue
|
|
339
|
+
size = sum(i.bytes for i in items)
|
|
340
|
+
prunable = [i for i in items if i.prune and category in only]
|
|
341
|
+
free = sum(i.bytes for i in prunable)
|
|
342
|
+
total_free += free
|
|
343
|
+
lines.append(f"{title}: {len(items)} items, {human_bytes(size)}" + (f"; prunable {len(prunable)} items, {human_bytes(free)}" if category in CATEGORIES else ""))
|
|
344
|
+
for item in sorted(items, key=lambda i: i.bytes, reverse=True)[:top]:
|
|
345
|
+
mark = "prune" if item.prune and category in only else "keep "
|
|
346
|
+
lines.append(f" [{mark}] {human_bytes(item.bytes):>9} {item.label}" + (f" ({item.note})" if item.note else ""))
|
|
347
|
+
if len(items) > top:
|
|
348
|
+
lines.append(f" ... and {len(items) - top} more")
|
|
349
|
+
lines.append("")
|
|
350
|
+
waiting = sum(1 for i in report.items if i.category == "transcripts" and i.note.startswith("not saved"))
|
|
351
|
+
if waiting:
|
|
352
|
+
lines.append(f"{waiting} old transcript(s) are not saved by backfill yet and are kept: run `backfill sync --all`, then clean again.")
|
|
353
|
+
lines.append(f"Would free {human_bytes(total_free)}. Dry run: add --apply to move it to the trash (--delete removes for good).")
|
|
354
|
+
return "\n".join(lines)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def to_json(report: Report) -> dict[str, Any]:
|
|
358
|
+
return {
|
|
359
|
+
"older_than_days": report.older_than_days,
|
|
360
|
+
"items": [
|
|
361
|
+
{"category": i.category, "label": i.label, "path": str(i.path), "bytes": i.bytes, "files": i.files, "prune": i.prune, "note": i.note}
|
|
362
|
+
for i in report.items
|
|
363
|
+
],
|
|
364
|
+
"prunable_bytes": sum(i.bytes for i in candidates(report)),
|
|
365
|
+
}
|