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 ADDED
@@ -0,0 +1,6 @@
1
+ """backfill: keeps every Claude Code and Codex session of a project in the project itself.
2
+
3
+ Standard library only. ``backfill --help`` lists the commands.
4
+ """
5
+
6
+ __version__ = "0.3.0"
backfill/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from backfill.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,28 @@
1
+ """Per-agent code: hook handling, installation into the agent's config, and importing existing history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from backfill.layout import Layout
8
+
9
+
10
+ def session_context(layout: Layout, config: dict[str, Any]) -> str:
11
+ """Text handed to the agent at session start (``[context]`` in the project config)."""
12
+ section = config["context"]
13
+ parts: list[str] = []
14
+ if section["announce"]:
15
+ parts.append(
16
+ f"Session logging is active: this session is saved automatically by backfill to {layout.log_dir}, and "
17
+ f"earlier sessions of this project are listed in {layout.log_dir / 'INDEX.md'} with readable histories under "
18
+ f"{layout.log_dir} (history/ folders). Do not delete, edit or commit that folder (it ignores itself in git)."
19
+ )
20
+ if section["resume"]:
21
+ from backfill.ops import resume_digest
22
+
23
+ digest = resume_digest(layout)
24
+ if digest:
25
+ parts.append("Where the previous session stopped (from backfill):\n" + digest)
26
+ if section["notes"].strip():
27
+ parts.append(section["notes"].strip())
28
+ return "\n\n".join(parts)
@@ -0,0 +1,551 @@
1
+ """Claude Code: hook handler, ``~/.claude/settings.json`` installation, and import of existing history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from backfill import __version__
12
+ from backfill import transcript as tr
13
+ from backfill.agents import session_context
14
+ from backfill.capture import MEGABYTE, git_snapshot, mirror_tree, scratch_dirs, snapshot_files
15
+ from backfill.config import load_config
16
+ from backfill.core import (
17
+ Adapter,
18
+ ingest_session,
19
+ journal_event,
20
+ metadata_snapshot,
21
+ registry_touch,
22
+ session_lock,
23
+ turn_entry,
24
+ write_index,
25
+ )
26
+ from backfill.layout import Layout
27
+ from backfill.redact import Redactor, redactor_for
28
+ from backfill.roots import find_root, skip_reason
29
+ from backfill.runtime import (
30
+ INSTRUCTION_START,
31
+ command_line,
32
+ hook_parts,
33
+ system_python,
34
+ with_instruction_block,
35
+ without_instruction_block,
36
+ )
37
+ from backfill.util import (
38
+ Context,
39
+ append_jsonl,
40
+ backup_file,
41
+ iso_utc_now,
42
+ read_json,
43
+ same_path,
44
+ write_json,
45
+ write_text_atomic,
46
+ )
47
+
48
+ NAME = "claude"
49
+ HOOK_EVENTS = (
50
+ "SessionStart",
51
+ "UserPromptSubmit",
52
+ "PostToolUse",
53
+ "Notification",
54
+ "Stop",
55
+ "SubagentStop",
56
+ "PreCompact",
57
+ "SessionEnd",
58
+ )
59
+ SYNC_EVENTS = ("Stop", "SubagentStop", "PreCompact", "SessionEnd") # transcript copied, history extended
60
+ HOOK_TIMEOUT_SECONDS = 30
61
+ LEGACY_COMMAND_MARKERS = ("claude_logger_launcher.py", "claude_repo_logger.py") # the loggers backfill replaces
62
+ UNSET = "<unset>"
63
+ CLAUDE_DEFAULT_CLEANUP_DAYS = 30
64
+ CWD_SCAN_LINES = 80
65
+
66
+
67
+ def settings_path(ctx: Context) -> Path:
68
+ return ctx.claude_home / "settings.json"
69
+
70
+
71
+ def memory_path(ctx: Context) -> Path:
72
+ return ctx.claude_home / "CLAUDE.md"
73
+
74
+
75
+ def project_dir_name(path: Path) -> str:
76
+ """How Claude Code names a project's folder under ``~/.claude/projects``."""
77
+ import re
78
+
79
+ return re.sub(r"[^A-Za-z0-9]", "-", str(path))
80
+
81
+
82
+ # --- adapter ---------------------------------------------------------------------------------------------------
83
+
84
+
85
+ class ClaudeAdapter:
86
+ name = NAME
87
+
88
+ def summarize(self, entries: list[dict[str, Any]]) -> dict[str, Any]:
89
+ stats = tr.summarize_entries(entries)
90
+ usage = stats["usage"]
91
+ stats["token_totals"] = {
92
+ "input_tokens": usage.get("input_tokens", 0) + usage.get("cache_creation_input_tokens", 0),
93
+ "output_tokens": usage.get("output_tokens", 0),
94
+ "cache_read_tokens": usage.get("cache_read_input_tokens", 0),
95
+ }
96
+ return stats
97
+
98
+ def render(self, entries: list[dict[str, Any]], state: dict[str, Any], config: Mapping[str, Any]) -> str:
99
+ return tr.render_markdown(entries, state, config)
100
+
101
+ def sync_artifacts(
102
+ self, layout: Layout, session_id: str, ctx: Context, transcript: Path | None, config: Mapping[str, Any], redactor: Redactor
103
+ ) -> dict[str, int]:
104
+ """Edit backups, todo lists, the folder next to the transcript (subagents) and the scratchpad (manifest or copy)."""
105
+ copied: dict[str, int] = {}
106
+ target = layout.session_artifacts(session_id)
107
+ sources: list[tuple[str, Path]] = [("file-history", ctx.claude_home / "file-history" / session_id)]
108
+ if transcript is not None:
109
+ sources.append(("session", transcript.with_suffix("")))
110
+ for name, source in sources:
111
+ if source.is_dir():
112
+ count = mirror_tree(source, target / name)
113
+ if count:
114
+ copied[name] = count
115
+ todos = ctx.claude_home / "todos"
116
+ if todos.is_dir():
117
+ count = 0
118
+ for item in todos.glob(f"{session_id}*.json"):
119
+ destination = target / "todos" / item.name
120
+ try:
121
+ if not destination.exists() or destination.stat().st_size != item.stat().st_size:
122
+ destination.parent.mkdir(parents=True, exist_ok=True)
123
+ shutil.copy2(item, destination)
124
+ count += 1
125
+ except OSError:
126
+ continue
127
+ if count:
128
+ copied["todos"] = count
129
+ capture = config["capture"]
130
+ for scratch in scratch_dirs(ctx.env, session_id):
131
+ copied.update(snapshot_files(scratch, target, "scratchpad", capture["scratchpad"], int(capture["scratchpad_max_mb"]) * MEGABYTE, redactor))
132
+ return copied
133
+
134
+
135
+ ADAPTER: Adapter = ClaudeAdapter()
136
+
137
+
138
+ # --- hook ------------------------------------------------------------------------------------------------------
139
+
140
+
141
+ def handle_event(payload: Mapping[str, Any], ctx: Context | None = None) -> dict[str, Any] | None:
142
+ """Process one hook event; returns the JSON Claude Code should read on stdout, if any."""
143
+ ctx = ctx or Context.from_environment()
144
+ event = str(payload.get("hook_event_name") or "")
145
+ if event not in HOOK_EVENTS:
146
+ return None
147
+ root = find_root(str(payload.get("cwd") or "") or None, ctx.env, ctx.home)
148
+ if root is None or skip_reason(root, ctx, NAME):
149
+ return None
150
+
151
+ config = load_config(ctx, root)
152
+ redactor = redactor_for(config)
153
+ layout = Layout(root, NAME, config)
154
+ try:
155
+ layout.ensure()
156
+ except PermissionError:
157
+ return None # e.g. a session started in C:\Program Files: nothing can be written there, and that is not an error
158
+ session_id = str(payload.get("session_id") or "session-unknown")
159
+ transcript = Path(str(payload["transcript_path"])) if payload.get("transcript_path") else None
160
+ cwd = str(payload.get("cwd") or "") or None
161
+ with session_lock(layout, session_id): # async/overlapping hooks of one session take turns
162
+ return _process(payload, event, ctx, root, config, redactor, layout, session_id, transcript, cwd)
163
+
164
+
165
+ def _process(payload, event, ctx, root, config, redactor, layout, session_id, transcript, cwd): # noqa: ANN001
166
+
167
+ if config["capture"]["journal_events"] and event not in ("SessionStart", "SessionEnd"):
168
+ journal_event(layout, payload, config, redactor)
169
+
170
+ if event == "SessionStart":
171
+ first_time = not layout.state_path(session_id).exists()
172
+ append_jsonl(
173
+ layout.daily("sessions"),
174
+ {
175
+ "timestamp_utc": iso_utc_now(),
176
+ "event_type": "session-start",
177
+ "agent": NAME,
178
+ "session_id": session_id,
179
+ "source": payload.get("source"),
180
+ "model": payload.get("model"),
181
+ "cwd": cwd,
182
+ "transcript_path": payload.get("transcript_path"),
183
+ "first_seen": first_time,
184
+ "metadata": metadata_snapshot(ctx.env, root),
185
+ "repo": git_snapshot(root),
186
+ "logger_version": __version__,
187
+ },
188
+ )
189
+ context = session_context(layout, config) # computed before this session joins the index
190
+ if first_time:
191
+ write_json(
192
+ layout.state_path(session_id),
193
+ {
194
+ "agent": NAME,
195
+ "session_id": session_id,
196
+ "first_seen_at": iso_utc_now(),
197
+ "last_seen_at": iso_utc_now(),
198
+ "turn_count": 0,
199
+ "cwd": cwd,
200
+ "transcript_path": payload.get("transcript_path"),
201
+ },
202
+ )
203
+ registry_touch(ctx, root, NAME, session_id)
204
+ write_index(layout)
205
+ if not context:
206
+ return None
207
+ return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}}
208
+
209
+ if event not in SYNC_EVENTS:
210
+ return None
211
+
212
+ state, entries = ingest_session(layout, ADAPTER, ctx, config, redactor, session_id, transcript, cwd=cwd)
213
+ if event == "Stop":
214
+ turn_count = int(state.get("turn_count") or 0) + 1
215
+ state["turn_count"] = turn_count
216
+ write_json(layout.state_path(session_id), state)
217
+ turn_entry(
218
+ layout,
219
+ session_id,
220
+ turn_count,
221
+ cwd,
222
+ ADAPTER.summarize(entries),
223
+ git_snapshot(root),
224
+ {"permission_mode": payload.get("permission_mode")},
225
+ redactor,
226
+ )
227
+ elif event == "SessionEnd":
228
+ append_jsonl(
229
+ layout.daily("sessions"),
230
+ {
231
+ "timestamp_utc": iso_utc_now(),
232
+ "event_type": "session-end",
233
+ "agent": NAME,
234
+ "session_id": session_id,
235
+ "reason": payload.get("reason"),
236
+ "turn_count": state.get("turn_count"),
237
+ },
238
+ )
239
+ write_json(layout.log_dir / "latest-session.json", read_json(layout.state_path(session_id)))
240
+ if event in ("Stop", "SessionEnd"):
241
+ write_index(layout)
242
+ registry_touch(ctx, root, NAME, session_id)
243
+ return None
244
+
245
+
246
+ # --- settings.json ---------------------------------------------------------------------------------------------
247
+
248
+
249
+ def hook_command(ctx: Context, python_exe: str) -> str:
250
+ return command_line(hook_parts(ctx, python_exe, "hook", NAME), bash_style=True)
251
+
252
+
253
+ def is_backfill_command(command: str, ctx: Context | None = None) -> bool:
254
+ return " hook claude" in command and "run.py" in command
255
+
256
+
257
+ def is_legacy_command(command: str) -> bool:
258
+ return any(marker in command for marker in LEGACY_COMMAND_MARKERS)
259
+
260
+
261
+ def _group_has(group: Any, predicate) -> bool:
262
+ hooks = group.get("hooks") if isinstance(group, dict) else None
263
+ return isinstance(hooks, list) and any(isinstance(h, dict) and predicate(str(h.get("command", ""))) for h in hooks)
264
+
265
+
266
+ def load_settings(path: Path) -> dict[str, Any]:
267
+ if not path.exists():
268
+ return {}
269
+ value = json.loads(path.read_text(encoding="utf-8")) # invalid JSON must stop the install, not be overwritten
270
+ if not isinstance(value, dict):
271
+ raise ValueError(f"{path} does not contain a JSON object")
272
+ return value
273
+
274
+
275
+ def merge_hooks(settings: dict[str, Any], command: str) -> dict[str, Any]:
276
+ hooks = settings.setdefault("hooks", {})
277
+ if not isinstance(hooks, dict):
278
+ raise ValueError("settings.json: 'hooks' must be an object")
279
+ for event in HOOK_EVENTS:
280
+ groups = [
281
+ g
282
+ for g in hooks.get(event, [])
283
+ if not _group_has(g, is_backfill_command) and not _group_has(g, is_legacy_command)
284
+ ]
285
+ groups.append({"matcher": "", "hooks": [{"type": "command", "command": command, "timeout": HOOK_TIMEOUT_SECONDS}]})
286
+ hooks[event] = groups
287
+ return settings
288
+
289
+
290
+ def strip_hooks(settings: dict[str, Any]) -> int:
291
+ removed = 0
292
+ hooks = settings.get("hooks")
293
+ if not isinstance(hooks, dict):
294
+ return 0
295
+ for event in list(hooks):
296
+ groups = hooks[event]
297
+ if not isinstance(groups, list):
298
+ continue
299
+ kept = [g for g in groups if not _group_has(g, is_backfill_command) and not _group_has(g, is_legacy_command)]
300
+ removed += len(groups) - len(kept)
301
+ if kept:
302
+ hooks[event] = kept
303
+ else:
304
+ del hooks[event]
305
+ if not hooks:
306
+ del settings["hooks"]
307
+ return removed
308
+
309
+
310
+ def registered_events(settings: dict[str, Any]) -> list[str]:
311
+ hooks = settings.get("hooks", {})
312
+ if not isinstance(hooks, dict):
313
+ return []
314
+ return [
315
+ e for e in HOOK_EVENTS if isinstance(hooks.get(e), list) and any(_group_has(g, is_backfill_command) for g in hooks[e])
316
+ ]
317
+
318
+
319
+ def has_legacy_hooks(settings: dict[str, Any]) -> bool:
320
+ hooks = settings.get("hooks", {})
321
+ return isinstance(hooks, dict) and any(
322
+ isinstance(groups, list) and any(_group_has(g, is_legacy_command) for g in groups) for groups in hooks.values()
323
+ )
324
+
325
+
326
+ def install(
327
+ ctx: Context, *, python_exe: str | None = None, instructions: bool = True, retain_days: int | None = None, dry_run: bool = False
328
+ ) -> dict[str, Any]:
329
+ command = hook_command(ctx, python_exe or system_python())
330
+ settings = load_settings(settings_path(ctx))
331
+ migrated_legacy = has_legacy_hooks(settings)
332
+ settings = merge_hooks(settings, command)
333
+ manifest = read_json(ctx.shared_root / "install.json")
334
+ if retain_days is not None:
335
+ if retain_days < 1:
336
+ raise ValueError("--retain-days must be a positive number of days")
337
+ saved = manifest.setdefault("claude", {})
338
+ if "previous_cleanup_period_days" not in saved:
339
+ saved["previous_cleanup_period_days"] = load_settings(settings_path(ctx)).get("cleanupPeriodDays", UNSET)
340
+ settings["cleanupPeriodDays"] = retain_days
341
+ report: dict[str, Any] = {
342
+ "agent": NAME,
343
+ "settings": str(settings_path(ctx)),
344
+ "events": list(HOOK_EVENTS),
345
+ "command": command,
346
+ "instructions": str(memory_path(ctx)) if instructions else None,
347
+ "replaced_legacy_logger": migrated_legacy,
348
+ "cleanup_period_days": settings.get("cleanupPeriodDays"),
349
+ }
350
+ if dry_run:
351
+ return report
352
+ ctx.claude_home.mkdir(parents=True, exist_ok=True)
353
+ report["settings_backup"] = str(backup_file(settings_path(ctx)) or "")
354
+ write_json(settings_path(ctx), settings)
355
+ if instructions:
356
+ current = memory_path(ctx).read_text(encoding="utf-8") if memory_path(ctx).exists() else ""
357
+ updated = with_instruction_block(current)
358
+ if updated != current:
359
+ report["instructions_backup"] = str(backup_file(memory_path(ctx)) or "")
360
+ write_text_atomic(memory_path(ctx), updated)
361
+ write_json(ctx.shared_root / "install.json", {**manifest, **_manifest_update(ctx, manifest, command, python_exe)})
362
+ return report
363
+
364
+
365
+ def _manifest_update(ctx: Context, manifest: dict[str, Any], command: str, python_exe: str | None) -> dict[str, Any]:
366
+ claude = dict(manifest.get("claude") or {})
367
+ claude.update({"command": command, "installed_at": iso_utc_now()})
368
+ return {"version": __version__, "python": python_exe or system_python(), "claude": claude}
369
+
370
+
371
+ def uninstall(ctx: Context) -> dict[str, Any]:
372
+ report: dict[str, Any] = {"agent": NAME, "hooks_removed": 0, "instructions_removed": False}
373
+ manifest = read_json(ctx.shared_root / "install.json")
374
+ saved = manifest.get("claude") or {}
375
+ if settings_path(ctx).exists():
376
+ settings = load_settings(settings_path(ctx))
377
+ removed = strip_hooks(settings)
378
+ restored = "previous_cleanup_period_days" in saved
379
+ if restored:
380
+ previous = saved["previous_cleanup_period_days"]
381
+ if previous == UNSET:
382
+ settings.pop("cleanupPeriodDays", None)
383
+ else:
384
+ settings["cleanupPeriodDays"] = previous
385
+ report["cleanup_period_restored"] = previous
386
+ if removed or restored:
387
+ backup_file(settings_path(ctx))
388
+ write_json(settings_path(ctx), settings)
389
+ report["hooks_removed"] = removed
390
+ if memory_path(ctx).exists():
391
+ text = memory_path(ctx).read_text(encoding="utf-8")
392
+ cleaned = without_instruction_block(text)
393
+ if cleaned != text:
394
+ backup_file(memory_path(ctx))
395
+ write_text_atomic(memory_path(ctx), cleaned)
396
+ report["instructions_removed"] = True
397
+ return report
398
+
399
+
400
+ def installation(ctx: Context) -> dict[str, Any]:
401
+ try:
402
+ settings, error = load_settings(settings_path(ctx)), None
403
+ except (OSError, ValueError) as exc:
404
+ settings, error = {}, str(exc)
405
+ events = registered_events(settings)
406
+ cleanup = settings.get("cleanupPeriodDays")
407
+ memory = memory_path(ctx)
408
+ return {
409
+ "agent": NAME,
410
+ "home": str(ctx.claude_home),
411
+ "home_exists": ctx.claude_home.is_dir(),
412
+ "hooks_registered": events,
413
+ "all_hooks_registered": events == list(HOOK_EVENTS),
414
+ "legacy_hooks": has_legacy_hooks(settings),
415
+ "instructions_present": memory.exists() and INSTRUCTION_START in memory.read_text(encoding="utf-8"),
416
+ "cleanup_period_days": cleanup if cleanup is not None else f"{CLAUDE_DEFAULT_CLEANUP_DAYS} (Claude Code default)",
417
+ "settings_error": error,
418
+ }
419
+
420
+
421
+ # --- existing history ------------------------------------------------------------------------------------------
422
+
423
+
424
+ def recover_cwd(source_dir: Path) -> str | None:
425
+ """The working directory a project folder of ``~/.claude/projects`` belongs to (its name is lossy)."""
426
+ for transcript in sorted(source_dir.glob("*.jsonl")):
427
+ try:
428
+ with transcript.open("r", encoding="utf-8", errors="replace") as handle:
429
+ for index, raw in enumerate(handle):
430
+ if index >= CWD_SCAN_LINES:
431
+ break
432
+ try:
433
+ value = json.loads(raw)
434
+ except ValueError:
435
+ continue
436
+ if isinstance(value, dict) and isinstance(value.get("cwd"), str) and value["cwd"]:
437
+ return value["cwd"]
438
+ except OSError:
439
+ continue
440
+ return None
441
+
442
+
443
+ def source_dirs_for(root: Path, ctx: Context) -> list[Path]:
444
+ """History folders of ``root``: its own, plus those of sub-folders where sessions were started."""
445
+ projects = ctx.claude_home / "projects"
446
+ exact = projects / project_dir_name(root)
447
+ found: list[Path] = [exact] if exact.is_dir() else []
448
+ if projects.is_dir():
449
+ prefix = project_dir_name(root) + "-"
450
+ for candidate in sorted(projects.iterdir()):
451
+ if not candidate.is_dir() or candidate == exact or not candidate.name.startswith(prefix):
452
+ continue
453
+ cwd = recover_cwd(candidate)
454
+ if cwd and same_path(find_root(cwd, ctx.env, ctx.home) or Path(cwd), root):
455
+ found.append(candidate)
456
+ return found
457
+
458
+
459
+ def unlogged_sessions(layout: Layout, ctx: Context) -> list[str]:
460
+ """Session ids Claude Code still has for this project that are not saved yet."""
461
+ missing = []
462
+ for source_dir in source_dirs_for(layout.root, ctx):
463
+ for transcript in source_dir.glob("*.jsonl"):
464
+ if not layout.state_path(transcript.stem).exists() and not layout.transcript_path(transcript.stem).exists():
465
+ missing.append(transcript.stem)
466
+ return missing
467
+
468
+
469
+ def backfill(root: Path, ctx: Context, source_dirs: list[Path] | None = None) -> dict[str, Any]:
470
+ """Save the existing Claude Code history of ``root`` into its log folder."""
471
+ config = load_config(ctx, root)
472
+ layout = Layout(root, NAME, config)
473
+ redactor = redactor_for(config)
474
+ dirs = source_dirs if source_dirs is not None else source_dirs_for(root, ctx)
475
+ summary: dict[str, Any] = {"agent": NAME, "root": str(root), "log_dir": str(layout.log_dir), "sessions": [], "memory_files": 0}
476
+ if not dirs:
477
+ summary["note"] = "no Claude Code history found for this project"
478
+ return summary
479
+ layout.ensure()
480
+ for source_dir in dirs:
481
+ for transcript in sorted(source_dir.glob("*.jsonl")):
482
+ session_id = transcript.stem
483
+ previous_turns = int(read_json(layout.state_path(session_id)).get("turn_count") or 0)
484
+ state, entries = ingest_session(
485
+ layout, ADAPTER, ctx, config, redactor, session_id, transcript,
486
+ full=True, cwd=recover_cwd(source_dir), extra_state={"backfilled": True, "turn_count": previous_turns},
487
+ )
488
+ stats = ADAPTER.summarize(entries)
489
+ if not previous_turns: # no live turn count for history that predates the hooks: use the prompts
490
+ state["turn_count"] = stats["user_message_count"]
491
+ write_json(layout.state_path(session_id), state)
492
+ append_jsonl(
493
+ layout.daily("sessions"),
494
+ {
495
+ "timestamp_utc": iso_utc_now(),
496
+ "event_type": "backfill",
497
+ "agent": NAME,
498
+ "session_id": session_id,
499
+ "transcript_bytes": state.get("processed_bytes"),
500
+ "user_message_count": stats["user_message_count"],
501
+ "assistant_message_count": stats["assistant_message_count"],
502
+ "tools_used": stats["tools_used"],
503
+ },
504
+ )
505
+ summary["sessions"].append({"session_id": session_id, "user_messages": stats["user_message_count"]})
506
+ memory_dir = source_dir / "memory"
507
+ if memory_dir.is_dir():
508
+ target = layout.log_dir / "project-memory"
509
+ shutil.copytree(memory_dir, target, dirs_exist_ok=True)
510
+ summary["memory_files"] = sum(1 for item in target.rglob("*") if item.is_file())
511
+ prompts = ctx.claude_home / "history.jsonl"
512
+ if prompts.is_file():
513
+ kept = 0
514
+ lines: list[str] = []
515
+ for raw in prompts.read_text(encoding="utf-8", errors="replace").splitlines():
516
+ try:
517
+ item = json.loads(raw)
518
+ except ValueError:
519
+ continue
520
+ if isinstance(item, dict) and item.get("project") and same_path(Path(str(item["project"])), root):
521
+ lines.append(json.dumps(redactor.obj(item), ensure_ascii=False))
522
+ kept += 1
523
+ write_text_atomic(layout.log_dir / "prompt-history.jsonl", "".join(line + "\n" for line in lines))
524
+ summary["prompt_history_entries"] = kept
525
+ write_index(layout)
526
+ registry_touch(ctx, root, NAME)
527
+ return summary
528
+
529
+
530
+ def backfill_all(ctx: Context) -> dict[str, Any]:
531
+ """Backfill every project that has history under ``~/.claude/projects`` and may be logged."""
532
+ projects = ctx.claude_home / "projects"
533
+ grouped: dict[Path, list[Path]] = {}
534
+ skipped: list[dict[str, str]] = []
535
+ if projects.is_dir():
536
+ for source_dir in sorted(projects.iterdir()):
537
+ if not source_dir.is_dir() or not any(source_dir.glob("*.jsonl")):
538
+ continue
539
+ cwd = recover_cwd(source_dir)
540
+ if not cwd or not Path(cwd).is_dir():
541
+ skipped.append({"source": str(source_dir), "reason": "working directory unknown or missing"})
542
+ continue
543
+ root = find_root(cwd, ctx.env, ctx.home)
544
+ reason = skip_reason(root, ctx, NAME) if root else "no project root"
545
+ if root is None or reason:
546
+ skipped.append({"source": str(source_dir), "reason": reason})
547
+ continue
548
+ grouped.setdefault(root, []).append(source_dir)
549
+ return {"projects": [backfill(root, ctx, dirs) for root, dirs in grouped.items()], "skipped": skipped}
550
+
551
+