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/cli.py ADDED
@@ -0,0 +1,445 @@
1
+ """Command line: ``backfill <command>``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from backfill import __version__, clean, legacy, ops
14
+ from backfill import status as status_mod
15
+ from backfill.agents import claude, codex
16
+ from backfill.config import AGENTS, CODEX_PROFILES, PROJECT_CONFIG_NAMES, TEMPLATE, find_project_config, load_config, set_project_enabled
17
+ from backfill.core import registered_projects
18
+ from backfill.roots import find_root
19
+ from backfill.runtime import install_runtime, system_python
20
+ from backfill.util import Context, record_error
21
+
22
+
23
+ def build_parser() -> argparse.ArgumentParser:
24
+ parser = argparse.ArgumentParser(
25
+ prog="backfill",
26
+ description="Keeps every Claude Code and Codex session of a project in the project itself (.claude-logs / .codex-logs).",
27
+ )
28
+ parser.add_argument("--claude-home", type=Path, help="Claude config directory (default ~/.claude)")
29
+ parser.add_argument("--codex-home", type=Path, help="Codex home (default ~/.codex)")
30
+ parser.add_argument("--shared-root", type=Path, help="backfill data directory (default ~/.backfill)")
31
+ commands = parser.add_subparsers(dest="command", required=True, metavar="command")
32
+
33
+ def add(name: str, help_text: str, *, project: bool = False, as_json: bool = False) -> argparse.ArgumentParser:
34
+ sub = commands.add_parser(name, help=help_text, description=help_text)
35
+ if project:
36
+ sub.add_argument("--project", type=Path, help="project folder (default: the current directory's project)")
37
+ if as_json:
38
+ sub.add_argument("--json", action="store_true", dest="as_json", help="machine-readable output")
39
+ return sub
40
+
41
+ hook = commands.add_parser("hook", help="handle one agent hook event from stdin (used by the installed hooks)")
42
+ hook.add_argument("agent", choices=AGENTS)
43
+ notify = commands.add_parser("notify", help="Codex notify entry point (used by the installed config)")
44
+ notify.add_argument("--previous-notify", default=None, help="JSON array: command to hand the payload on to")
45
+ notify.add_argument("payload", nargs="?")
46
+ commands.add_parser("version", help="print the version")
47
+
48
+ install = add("install", "install the hooks for Claude Code and Codex on this machine (every project, automatically)")
49
+ install.add_argument("--agent", choices=("auto", "all", *AGENTS), default="auto", help="auto: those found on this machine")
50
+ install.add_argument("--no-instructions", action="store_true", help="do not add the instruction block to ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md")
51
+ install.add_argument("--dry-run", action="store_true", help="show what would change, write nothing")
52
+ install.add_argument("--python", help="interpreter for the hooks (default: the base interpreter)")
53
+ install.add_argument("--retain-days", type=int, help="also set Claude Code's cleanupPeriodDays so it keeps its own transcripts that long")
54
+ install.add_argument("--codex-profile", choices=CODEX_PROFILES, help="Codex lifecycle coverage (default: standard)")
55
+ install.add_argument("--codex-home-extra", type=Path, action="append", default=[], help="another Codex home to hook (repeatable)")
56
+ install.add_argument("--no-sync", action="store_true", help="do not import this project's existing history")
57
+
58
+ uninstall = add("uninstall", "remove the hooks (logs are never touched)")
59
+ uninstall.add_argument("--purge", action="store_true", help="also delete the backfill data directory")
60
+
61
+ status = add("status", "installation state and what is logged for the project", project=True, as_json=True)
62
+ status.add_argument("--all", action="store_true", dest="all_projects", help="every project logged on this machine")
63
+ add("doctor", "check that logging will really happen (exit status 1 when a check fails)", project=True, as_json=True)
64
+
65
+ init = add("init", "create .agents/backfill.toml for this project", project=True)
66
+ init.add_argument("--force", action="store_true", help="overwrite an existing config")
67
+ init.add_argument("--preset", choices=("minimal", "standard", "everything"), help="how much to capture (default: standard)")
68
+ init.add_argument("--layout", choices=("flat", "monthly"), help="monthly: journals, histories and transcripts in YYYY-MM folders")
69
+ add("on", "turn logging on for this project", project=True)
70
+ add("off", "turn logging off for this project", project=True)
71
+ add("config", "show the settings in effect for this project", project=True)
72
+
73
+ sync = add("sync", "save the history agents already have for this project (safe to repeat)", project=True, as_json=True)
74
+ sync.add_argument("--all", action="store_true", dest="all_projects", help="every project the agents know")
75
+ sync.add_argument("--agent", choices=AGENTS)
76
+
77
+ add("list", "projects logged on this machine", as_json=True)
78
+ summary = add("summary", "sessions, turns, tool calls and tokens of this project", project=True, as_json=True)
79
+ summary.add_argument("--days", type=int, default=14)
80
+ search = add("search", "find text in the readable histories", project=True, as_json=True)
81
+ search.add_argument("query")
82
+ search.add_argument("--agent", choices=AGENTS)
83
+ search.add_argument("--limit", type=int, default=30)
84
+ show = add("show", "print a session's readable history (latest by default)", project=True)
85
+ show.add_argument("session", nargs="?", help="session id or its first characters")
86
+ show.add_argument("--path", action="store_true", help="print only the file path")
87
+ digest = add("digest", "markdown hand-off of the latest sessions (paste it into a new session)", project=True)
88
+ digest.add_argument("--sessions", type=int, default=3)
89
+ export = add("export", "zip this project's logs", project=True)
90
+ export.add_argument("--output", type=Path, required=True)
91
+ retain = add("retain", "delete old journals (dry run unless --apply)", project=True)
92
+ retain.add_argument("--days", type=int, help="default: [retention] days from the project config")
93
+ retain.add_argument("--include-sessions", action="store_true", help="also remove whole old sessions (history, transcript, state)")
94
+ retain.add_argument("--apply", action="store_true")
95
+ recap = add("recap", "what happened since a time, across projects (markdown)", project=True)
96
+ recap.add_argument("--since", default="1d", help="today, yesterday, 36h, 7d, 2w or YYYY-MM-DD (default 1d)")
97
+ recap.add_argument("--all", action="store_true", dest="all_projects", help="every project logged on this machine")
98
+ cleaner = add("clean", "map what the agents keep on this machine and prune it safely (dry run unless --apply)", as_json=True)
99
+ cleaner.add_argument("--older-than", type=int, default=30, metavar="DAYS", help="only things older than this (default 30)")
100
+ cleaner.add_argument("--only", help="comma list of: " + ", ".join(clean.CATEGORIES) + " (default: all)")
101
+ cleaner.add_argument("--scan", type=Path, action="append", default=[], metavar="DIR", help="also look for project log folders under DIR (repeatable)")
102
+ cleaner.add_argument("--apply", action="store_true", help="move the candidates to the trash folder inside the backfill data directory")
103
+ cleaner.add_argument("--delete", action="store_true", help="with --apply: delete for good instead of moving to the trash")
104
+ cleaner.add_argument("--empty-trash", action="store_true", help="delete what earlier runs moved to the trash")
105
+ cleaner.add_argument("--restore", metavar="BATCH", help="move a trash batch (folder name under the trash) back")
106
+ audit = add("audit", "look for secrets in the logs", project=True, as_json=True)
107
+ audit.add_argument("--fix", action="store_true", help="redact them in journals and histories")
108
+ audit.add_argument("--include-transcripts", action="store_true", help="with --fix: also edit the raw transcript copies")
109
+ return parser
110
+
111
+
112
+ def project_root(project: Path | None, ctx: Context) -> Path | None:
113
+ return find_root(str((project or Path.cwd()).resolve()), ctx.env, ctx.home)
114
+
115
+
116
+ def emit(report: Any) -> None:
117
+ print(json.dumps(report, indent=2, ensure_ascii=False))
118
+
119
+
120
+ def run_hook(agent: str, ctx: Context) -> None:
121
+ raw = sys.stdin.buffer.read()
122
+ try:
123
+ payload = json.loads(raw.decode("utf-8", errors="replace") or "{}")
124
+ if not isinstance(payload, dict):
125
+ return
126
+ output = claude.handle_event(payload, ctx) if agent == "claude" else codex.handle_payload(payload, ctx, source="hook")
127
+ except Exception as exc: # noqa: BLE001 - a logger must never break a session
128
+ record_error(ctx, exc)
129
+ return
130
+ if output:
131
+ sys.stdout.write(json.dumps(output, ensure_ascii=False) + "\n")
132
+
133
+
134
+ def run_notify(args: argparse.Namespace, ctx: Context) -> None:
135
+ try:
136
+ payload = json.loads(args.payload) if args.payload else None
137
+ if isinstance(payload, dict):
138
+ codex.handle_payload(payload, ctx, source="notify")
139
+ except Exception as exc: # noqa: BLE001
140
+ record_error(ctx, exc)
141
+ if args.previous_notify and args.payload:
142
+ try:
143
+ previous = json.loads(args.previous_notify)
144
+ if isinstance(previous, list) and all(isinstance(v, str) for v in previous):
145
+ codex.run_previous_notify(previous, args.payload)
146
+ except ValueError:
147
+ pass
148
+
149
+
150
+ def agents_to_install(ctx: Context, choice: str) -> list[str]:
151
+ if choice in AGENTS:
152
+ return [choice]
153
+ if choice == "all":
154
+ return list(AGENTS)
155
+ found = []
156
+ if ctx.claude_home.is_dir() or shutil.which("claude"):
157
+ found.append("claude")
158
+ if ctx.codex_home.is_dir() or shutil.which("codex") or codex.discover_homes(ctx)[1:]:
159
+ found.append("codex")
160
+ return found
161
+
162
+
163
+ def do_install(args: argparse.Namespace, ctx: Context) -> dict[str, Any]:
164
+ chosen = agents_to_install(ctx, args.agent)
165
+ report: dict[str, Any] = {
166
+ "version": __version__, "shared_root": str(ctx.shared_root), "dry_run": args.dry_run,
167
+ "agents": {}, "skipped": [a for a in AGENTS if a not in chosen],
168
+ }
169
+ if not chosen:
170
+ report["note"] = "neither Claude Code nor Codex was found; use --agent claude|codex to install anyway"
171
+ return report
172
+ python_exe = args.python or system_python()
173
+ # Validate everything before writing anything, so a broken config stops the install without half a result.
174
+ if "claude" in chosen:
175
+ claude.install(ctx, python_exe=python_exe, instructions=not args.no_instructions, retain_days=args.retain_days, dry_run=True)
176
+ if "codex" in chosen:
177
+ codex.install(ctx, python_exe=python_exe, instructions=not args.no_instructions, profile=args.codex_profile or "standard",
178
+ homes=codex.discover_homes(ctx, extra=args.codex_home_extra), dry_run=True)
179
+ if not args.dry_run:
180
+ install_runtime(ctx)
181
+ if "claude" in chosen:
182
+ report["agents"]["claude"] = claude.install(
183
+ ctx, python_exe=python_exe, instructions=not args.no_instructions, retain_days=args.retain_days, dry_run=args.dry_run)
184
+ if "codex" in chosen:
185
+ report["agents"]["codex"] = codex.install(
186
+ ctx, python_exe=python_exe, instructions=not args.no_instructions, profile=args.codex_profile or "standard",
187
+ homes=codex.discover_homes(ctx, extra=args.codex_home_extra), dry_run=args.dry_run)
188
+ if not args.dry_run and not args.no_sync:
189
+ root = project_root(None, ctx)
190
+ if root is not None:
191
+ report["synced"] = do_sync(root, ctx, None)
192
+ return report
193
+
194
+
195
+ def do_sync(root: Path, ctx: Context, agent: str | None) -> list[dict[str, Any]]:
196
+ from backfill.roots import skip_reason
197
+
198
+ out = []
199
+ for name, module in (("claude", claude), ("codex", codex)):
200
+ if agent and agent != name:
201
+ continue
202
+ reason = skip_reason(root, ctx, name)
203
+ out.append({"agent": name, "root": str(root), "skipped": reason} if reason else module.backfill(root, ctx))
204
+ out.extend({**item, "note": "legacy logs imported", "sessions": item.get("sessions", []), "log_dir": item.get("log_dir", "")} for item in legacy.migrate(root, ctx, agent) if not item.get("skipped"))
205
+ return out
206
+
207
+
208
+ def do_uninstall(ctx: Context, purge: bool) -> dict[str, Any]:
209
+ report = {"claude": claude.uninstall(ctx), "codex": codex.uninstall(ctx), "purged": False}
210
+ if purge and ctx.shared_root.is_dir():
211
+ shutil.rmtree(ctx.shared_root)
212
+ report["purged"] = True
213
+ return report
214
+
215
+
216
+ def main(argv: list[str] | None = None) -> int:
217
+ args = build_parser().parse_args(argv)
218
+ ctx = Context.from_environment(os.environ, claude_home=args.claude_home, codex_home=args.codex_home, shared_root=args.shared_root)
219
+ command = args.command
220
+
221
+ if command == "hook":
222
+ run_hook(args.agent, ctx)
223
+ return 0
224
+ if command == "notify":
225
+ run_notify(args, ctx)
226
+ return 0
227
+ if command == "version":
228
+ print(__version__)
229
+ return 0
230
+
231
+ as_json = getattr(args, "as_json", False)
232
+ try:
233
+ return dispatch(command, args, ctx, as_json)
234
+ except (ValueError, FileNotFoundError, FileExistsError) as exc:
235
+ print(f"backfill: {exc}", file=sys.stderr)
236
+ return 2
237
+
238
+
239
+ def dispatch(command: str, args: argparse.Namespace, ctx: Context, as_json: bool) -> int:
240
+ if command == "install":
241
+ report = do_install(args, ctx)
242
+ emit(report) if as_json or args.dry_run else print_install(report)
243
+ return 0
244
+ if command == "uninstall":
245
+ emit(do_uninstall(ctx, args.purge))
246
+ return 0
247
+ if command == "list":
248
+ rows = [status_mod.project_report(p, ctx) for p in registered_projects(ctx) if p.is_dir()]
249
+ if as_json:
250
+ emit(rows)
251
+ for row in rows if not as_json else []:
252
+ parts = [f"{a}={i.get('sessions', 0)}" for a, i in row["agents"].items() if i["exists"]]
253
+ print(f"{row['root']} {' '.join(parts) or '-'}")
254
+ return 0
255
+
256
+ root = project_root(getattr(args, "project", None), ctx)
257
+ needs_project = command not in {"status", "doctor", "sync", "clean"} or (command == "sync" and not args.all_projects)
258
+ if command == "recap" and args.all_projects:
259
+ needs_project = False
260
+ if root is None and needs_project:
261
+ print("backfill: no project found here (run it inside a project folder, or pass --project)", file=sys.stderr)
262
+ return 2
263
+
264
+ if command == "status":
265
+ report = status_mod.status(ctx, None if args.all_projects and args.project is None else root, all_projects=args.all_projects)
266
+ emit(report) if as_json else print(status_mod.render_status(report))
267
+ elif command == "doctor":
268
+ report = status_mod.doctor(ctx, root)
269
+ emit(report) if as_json else print(status_mod.render_doctor(report))
270
+ return 0 if report["ok"] else 1
271
+ elif command == "init":
272
+ existing = find_project_config(root)
273
+ if existing and not args.force:
274
+ print(f"already configured: {existing}")
275
+ return 0
276
+ target = existing or root / PROJECT_CONFIG_NAMES[0]
277
+ target.parent.mkdir(parents=True, exist_ok=True)
278
+ text = TEMPLATE
279
+ if args.preset:
280
+ text = text.replace('preset = "standard"', f'preset = "{args.preset}"')
281
+ if args.layout:
282
+ text = text.replace('layout = "flat"', f'layout = "{args.layout}"')
283
+ target.write_text(text, encoding="utf-8")
284
+ print(f"created {target}\nCommit it to share the settings with your team; the log folders stay out of git by themselves.")
285
+ elif command in ("on", "off"):
286
+ path = set_project_enabled(root, command == "on")
287
+ print(f"logging {'enabled' if command == 'on' else 'disabled'} for {root} ({path})")
288
+ elif command == "config":
289
+ config = load_config(ctx, root)
290
+ emit(config)
291
+ elif command == "sync":
292
+ if args.all_projects:
293
+ report = {a: m.backfill_all(ctx) for a, m in (("claude", claude), ("codex", codex)) if not args.agent or args.agent == a}
294
+ else:
295
+ report = do_sync(root, ctx, args.agent)
296
+ if as_json:
297
+ emit(report)
298
+ else:
299
+ print_sync(report)
300
+ elif command == "summary":
301
+ report = ops.summary(root, ctx, args.days)
302
+ emit(report) if as_json else print(render_summary(report))
303
+ elif command == "search":
304
+ hits = ops.search(root, ctx, args.query, limit=args.limit, agent=args.agent)
305
+ if as_json:
306
+ emit(hits)
307
+ for hit in hits if not as_json else []:
308
+ print(f"{hit['agent']}:{hit['session'][:8]}:{hit['line']}: {hit['text']}")
309
+ if not hits and not as_json:
310
+ print("no matches")
311
+ elif command == "show":
312
+ path = ops.find_history(root, ctx, args.session)
313
+ if path is None:
314
+ print("backfill: no such session", file=sys.stderr)
315
+ return 2
316
+ print(path if args.path else path.read_text(encoding="utf-8"))
317
+ elif command == "digest":
318
+ print(ops.digest(root, ctx, args.sessions))
319
+ elif command == "export":
320
+ emit(ops.export_project(root, ctx, args.output))
321
+ elif command == "retain":
322
+ days = args.days or load_config(ctx, root)["retention"]["days"]
323
+ if not days:
324
+ print("backfill: pass --days N or set [retention] days in .agents/backfill.toml", file=sys.stderr)
325
+ return 2
326
+ doomed = ops.retention_candidates(root, ctx, days, include_sessions=args.include_sessions)
327
+ if args.apply:
328
+ print(f"removed {ops.apply_retention(doomed, root)} item(s) older than {days} days")
329
+ else:
330
+ for path in doomed:
331
+ print(f"would remove {path}")
332
+ print(f"{len(doomed)} item(s) older than {days} days; run again with --apply to delete them")
333
+ elif command == "recap":
334
+ try:
335
+ since = ops.parse_since(args.since)
336
+ except ValueError as exc:
337
+ print(f"backfill: {exc}", file=sys.stderr)
338
+ return 2
339
+ roots = [p for p in registered_projects(ctx) if p.is_dir()] if args.all_projects else [root]
340
+ print(ops.recap(ctx, roots, since))
341
+ elif command == "clean":
342
+ return do_clean(args, ctx, as_json)
343
+ elif command == "audit":
344
+ report = ops.audit(root, ctx, fix=args.fix, include_transcripts=args.include_transcripts)
345
+ if as_json:
346
+ emit(report)
347
+ else:
348
+ print_audit(report, args.fix)
349
+ return 0
350
+
351
+
352
+ def do_clean(args: argparse.Namespace, ctx: Context, as_json: bool) -> int:
353
+ if args.restore:
354
+ print(f"restored {clean.restore(ctx, args.restore)} item(s)")
355
+ return 0
356
+ if args.empty_trash:
357
+ from backfill.util import human_bytes
358
+
359
+ print(f"trash emptied, {human_bytes(clean.empty_trash(ctx)['bytes'])} freed")
360
+ return 0
361
+ only = tuple(part.strip() for part in args.only.split(",")) if args.only else clean.CATEGORIES
362
+ unknown = [part for part in only if part not in clean.CATEGORIES]
363
+ if unknown:
364
+ print(f"backfill: unknown category {', '.join(unknown)} (choose from {', '.join(clean.CATEGORIES)})", file=sys.stderr)
365
+ return 2
366
+ report = clean.scan(ctx, older_than_days=max(args.older_than, 1), scan_roots=args.scan)
367
+ if args.apply:
368
+ result = clean.apply(report, ctx, only=only, delete=args.delete)
369
+ if as_json:
370
+ emit(result)
371
+ else:
372
+ from backfill.util import human_bytes
373
+
374
+ where = "deleted" if result["deleted"] else f"moved to {result['trash']} (free the space with `backfill clean --empty-trash`)"
375
+ print(f"{result['removed']} item(s), {human_bytes(result['bytes'])} {where}" + (f"; {result['errors']} could not be removed" if result["errors"] else ""))
376
+ return 0
377
+ emit(clean.to_json(report)) if as_json else print(clean.render(report, only=only))
378
+ return 0
379
+
380
+
381
+ def print_install(report: dict[str, Any]) -> None:
382
+ if report.get("note"):
383
+ print(report["note"])
384
+ return
385
+ print(f"backfill {report['version']} installed (data: {report['shared_root']})")
386
+ for name, item in report["agents"].items():
387
+ if name == "claude":
388
+ print(f" Claude Code: {len(item['events'])} hooks in {item['settings']}" + (" (replaced the old claude-logger hooks)" if item["replaced_legacy_logger"] else ""))
389
+ else:
390
+ for home in item["homes"]:
391
+ chained = " (your existing notify command stays chained)" if home.get("chained_command") else ""
392
+ print(f" Codex {home['home']}: notify {home['notify']}{chained}, lifecycle hooks {home['lifecycle_hooks']}")
393
+ for name in report["skipped"]:
394
+ print(f" {name}: not found on this machine, skipped")
395
+ for item in report.get("synced", []):
396
+ if item.get("sessions"):
397
+ print(f" saved {len(item['sessions'])} earlier {item['agent']} session(s) of this project")
398
+ print("Restart running agent sessions; new sessions are logged automatically. Check anytime with `backfill status`.")
399
+ if "codex" in report["agents"]:
400
+ print("Codex may ask you to review the new lifecycle hooks: type /hooks in Codex.")
401
+
402
+
403
+ def print_sync(report: Any) -> None:
404
+ items = report if isinstance(report, list) else [p for part in report.values() for p in part["projects"]]
405
+ for item in items:
406
+ if item.get("skipped"):
407
+ print(f"{item['agent']}: skipped ({item['skipped']})")
408
+ elif item.get("note"):
409
+ print(f"{item['agent']}: {item['note']}")
410
+ else:
411
+ print(f"{item['agent']}: {len(item['sessions'])} session(s) saved in {item['log_dir']}")
412
+
413
+
414
+ def render_summary(report: dict[str, Any]) -> str:
415
+ from backfill.util import human_bytes
416
+
417
+ lines = [f"Project {report['root']}"]
418
+ if not report["agents"]:
419
+ return lines[0] + "\n nothing logged yet"
420
+ for agent, t in report["agents"].items():
421
+ lines.append(
422
+ f" {agent}: {t['sessions']} sessions, {t['turns']} turns, {t['tool_calls']} tool calls, "
423
+ f"tokens in/out/cached {t['input_tokens']:,}/{t['output_tokens']:,}/{t['cache_read_tokens']:,}, {human_bytes(t['size_bytes'])}"
424
+ )
425
+ if report["models"]:
426
+ lines.append(" models: " + ", ".join(f"{m} ({n})" for m, n in report["models"].items()))
427
+ if report["sessions_per_day"]:
428
+ lines.append(f" active days (last {report['days']}): " + ", ".join(f"{d} x{n}" for d, n in report["sessions_per_day"].items()))
429
+ return "\n".join(lines)
430
+
431
+
432
+ def print_audit(report: dict[str, Any], fixed: bool) -> None:
433
+ if not report["files_with_findings"]:
434
+ print("no secrets found in the logs")
435
+ return
436
+ for item in report["files"]:
437
+ kinds = ", ".join(f"{k} x{v}" for k, v in item["findings"].items())
438
+ note = "redacted" if item["fixed"] else ("raw transcript, left alone" if item["raw_transcript"] and fixed else "")
439
+ print(f"{item['file']}: {kinds}{' [' + note + ']' if note else ''}")
440
+ print(f"{report['total']} finding(s) in {report['files_with_findings']} file(s)." + ("" if fixed else " Run `backfill audit --fix` to redact journals and histories."))
441
+
442
+
443
+
444
+ if __name__ == "__main__":
445
+ raise SystemExit(main())