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/runtime.py ADDED
@@ -0,0 +1,135 @@
1
+ """The machine-level runtime: a copy of this package under the shared root plus a launcher the hooks call.
2
+
3
+ Hooks must keep working after a package manager moves, upgrades or removes its own copy of backfill, so every
4
+ install copies the package to ``<shared_root>/runtime`` and the agents are pointed at ``<shared_root>/run.py``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from backfill.util import Context, same_path
16
+
17
+ LAUNCHER_NAME = "run.py"
18
+ INSTRUCTION_START = "<!-- backfill:start -->"
19
+ INSTRUCTION_END = "<!-- backfill:end -->"
20
+ LEGACY_INSTRUCTION_MARKERS = (("<!-- claude-repo-logger:start -->", "<!-- claude-repo-logger:end -->"),)
21
+
22
+ INSTRUCTIONS = f"""{INSTRUCTION_START}
23
+ ## Session logging (automatic)
24
+
25
+ backfill saves every session of a project into that project's own log folder (`.claude-logs/` for Claude Code,
26
+ `.codex-logs/` for Codex, unless the project's `.agents/backfill.toml` says otherwise): the raw transcript, a readable
27
+ history (`history/*.md`) with every prompt, answer and tool call, an event journal and one summary per turn. It starts
28
+ by itself with each session. Do not delete, edit or commit those folders (they ignore themselves in git) and do not
29
+ paste their contents into replies. When asked what was done in an earlier session of the project, read `INDEX.md`
30
+ and `history/` in the log folder first.
31
+ {INSTRUCTION_END}
32
+ """
33
+
34
+ LAUNCHER_TEXT = '''#!/usr/bin/env python3
35
+ """Written by `backfill install`. Agents run this file for every hook event; it must never fail a session."""
36
+ import sys
37
+ from pathlib import Path
38
+
39
+ HERE = Path(__file__).resolve().parent
40
+ HOOKISH = len(sys.argv) > 1 and sys.argv[1] in ("hook", "notify")
41
+ sys.path.insert(0, str(HERE / "runtime"))
42
+ try:
43
+ from backfill.cli import main
44
+ code = main(sys.argv[1:])
45
+ except SystemExit as stop:
46
+ code = stop.code if isinstance(stop.code, int) else 0
47
+ except Exception as exc: # noqa: BLE001
48
+ try:
49
+ with (HERE / "hook-errors.log").open("a", encoding="utf-8") as handle:
50
+ handle.write("launcher: %s: %s\\n" % (type(exc).__name__, exc))
51
+ except OSError:
52
+ pass
53
+ code = 1
54
+ sys.exit(0 if HOOKISH else code)
55
+ '''
56
+
57
+
58
+ def package_source() -> Path:
59
+ return Path(__file__).resolve().parent
60
+
61
+
62
+ def system_python() -> str:
63
+ """Interpreter for the hooks: the base interpreter (not a project's virtualenv), via a stable path where possible."""
64
+ if os.name == "nt":
65
+ candidate = Path(sys.base_prefix) / "python.exe"
66
+ return str(candidate if candidate.exists() else Path(sys.executable))
67
+ base = Path(sys.base_prefix) / "bin" / "python3"
68
+ on_path = shutil.which("python3")
69
+ try:
70
+ if on_path and base.exists() and same_path(Path(on_path).resolve(), base.resolve()):
71
+ return on_path # e.g. /opt/homebrew/bin/python3 survives a Python upgrade; the Cellar path does not
72
+ except OSError:
73
+ pass
74
+ return str(base if base.exists() else Path(sys.executable))
75
+
76
+
77
+ def command_line(parts: list[str], *, bash_style: bool = False) -> str:
78
+ """One shell-ready command string.
79
+
80
+ POSIX quoting on macOS/Linux. On Windows: ``cmd``-style quoting, or with ``bash_style`` (Claude Code runs hooks
81
+ through a bash-like shell there) double-quoted paths with forward slashes, which survive both shells.
82
+ """
83
+ if os.name == "nt":
84
+ if bash_style:
85
+ return " ".join(f'"{Path(p).as_posix()}"' if ("\\" in p or "/" in p or " " in p) else p for p in parts)
86
+ return subprocess.list2cmdline(parts)
87
+ import shlex
88
+
89
+ return shlex.join(parts)
90
+
91
+
92
+ def hook_parts(ctx: Context, python_exe: str, *args: str) -> list[str]:
93
+ return [python_exe, str(ctx.launcher), *args]
94
+
95
+
96
+ def install_runtime(ctx: Context) -> None:
97
+ source = package_source()
98
+ target = ctx.runtime_dir / "backfill"
99
+ ctx.shared_root.mkdir(parents=True, exist_ok=True)
100
+ if not same_path(source, target):
101
+ if target.exists():
102
+ shutil.rmtree(target)
103
+ shutil.copytree(source, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
104
+ ctx.launcher.write_text(LAUNCHER_TEXT, encoding="utf-8")
105
+ for name in ("allowlist.txt", "denylist.txt"):
106
+ (ctx.shared_root / name).touch(exist_ok=True)
107
+ config = ctx.shared_root / "config.toml"
108
+ if not config.exists():
109
+ config.write_text(
110
+ '# Machine-wide backfill settings. Per-project settings live in <project>/.agents/backfill.toml.\n'
111
+ '# mode = "all" # log every project (default)\n'
112
+ '# mode = "opt-in" # log only projects that have a .agents/backfill.toml\n'
113
+ 'mode = "all"\n',
114
+ encoding="utf-8",
115
+ )
116
+
117
+
118
+ def with_instruction_block(text: str) -> str:
119
+ block = INSTRUCTIONS.strip() + "\n"
120
+ text = without_instruction_block(text, keep_trailing=True)
121
+ separator = "" if not text.strip() else ("\n" if text.endswith("\n") else "\n\n")
122
+ return text + separator + ("\n" if text.strip() else "") + block
123
+
124
+
125
+ def without_instruction_block(text: str, *, keep_trailing: bool = False) -> str:
126
+ changed = False
127
+ for start, end in ((INSTRUCTION_START, INSTRUCTION_END), *LEGACY_INSTRUCTION_MARKERS):
128
+ while start in text and end in text:
129
+ before, _, rest = text.partition(start)
130
+ _, _, after = rest.partition(end)
131
+ text = before.rstrip("\n") + ("\n" if before.strip() else "") + after.lstrip("\n")
132
+ changed = True
133
+ if not changed:
134
+ return text
135
+ return text if keep_trailing else (text.strip("\n") + "\n" if text.strip() else "")
backfill/status.py ADDED
@@ -0,0 +1,237 @@
1
+ """Looking at the installation and at each project's log folders: ``status`` and ``doctor``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from backfill import __version__
11
+ from backfill.agents import claude, codex
12
+ from backfill.config import AGENTS, config_problems, load_config
13
+ from backfill.core import registered_projects
14
+ from backfill.layout import Layout
15
+ from backfill.legacy import legacy_dirs
16
+ from backfill.roots import skip_reason
17
+ from backfill.util import Context, folder_size, read_json
18
+
19
+ RUNTIME_VERSION_FILE = "__init__.py"
20
+
21
+
22
+ def runtime_version(ctx: Context) -> str | None:
23
+ init = ctx.runtime_dir / "backfill" / RUNTIME_VERSION_FILE
24
+ if init.is_file():
25
+ for line in init.read_text(encoding="utf-8").splitlines():
26
+ if line.startswith("__version__"):
27
+ return line.split("=", 1)[1].strip().strip("\"'")
28
+ return None
29
+
30
+
31
+ def installation(ctx: Context) -> dict[str, Any]:
32
+ manifest = read_json(ctx.shared_root / "install.json")
33
+ errors = ctx.errors_log
34
+ python = manifest.get("python")
35
+ return {
36
+ "version": __version__,
37
+ "shared_root": str(ctx.shared_root),
38
+ "runtime_version": runtime_version(ctx),
39
+ "launcher_present": ctx.launcher.is_file(),
40
+ "python": python,
41
+ "python_exists": bool(python) and Path(python).exists(),
42
+ "claude": claude.installation(ctx),
43
+ "codex": codex.installation(ctx),
44
+ "agent_commands": {"claude": shutil.which("claude"), "codex": shutil.which("codex")},
45
+ "errors_log": str(errors) if errors.exists() and errors.stat().st_size else None,
46
+ }
47
+
48
+
49
+ def project_report(root: Path, ctx: Context) -> dict[str, Any]:
50
+ config = load_config(ctx, root)
51
+ report: dict[str, Any] = {
52
+ "root": str(root),
53
+ "config": config["_project_config"],
54
+ "config_problems": config_problems(Path(config["_project_config"])) if config["_project_config"] else [],
55
+ "agents": {},
56
+ }
57
+ for agent in AGENTS:
58
+ reason = skip_reason(root, ctx, agent)
59
+ layout = Layout(root, agent, config)
60
+ module = claude if agent == "claude" else codex
61
+ item: dict[str, Any] = {"log_dir": str(layout.log_dir), "exists": layout.log_dir.is_dir(), "skipped": reason or None}
62
+ item["available_to_backfill"] = len(module.unlogged_sessions(layout, ctx))
63
+ item["legacy_dirs"] = [p.relative_to(root).as_posix() for p in legacy_dirs(root, agent)]
64
+ if layout.log_dir.is_dir():
65
+ states = [read_json(p) for p in layout.state.glob("*.json")] if layout.state.is_dir() else []
66
+ states = [s for s in states if s.get("session_id")]
67
+ behind = []
68
+ for state in states:
69
+ source, sid = state.get("transcript_path"), str(state["session_id"])
70
+ copy = layout.transcript_path(sid)
71
+ try:
72
+ if source and Path(source).is_file() and (not copy.exists() or Path(source).stat().st_size > copy.stat().st_size):
73
+ behind.append(sid)
74
+ except OSError:
75
+ continue
76
+ item.update(
77
+ {
78
+ "sessions": len(states),
79
+ "turns": sum(int(s.get("turn_count") or 0) for s in states),
80
+ "last_activity": max((str(s.get("last_seen_at") or "") for s in states), default="") or None,
81
+ "size_bytes": folder_size(layout.log_dir),
82
+ "sessions_behind_agent_copy": behind if config["capture"]["transcripts"] == "raw" else [],
83
+ }
84
+ )
85
+ report["agents"][agent] = item
86
+ return report
87
+
88
+
89
+ def status(ctx: Context, root: Path | None = None, *, all_projects: bool = False) -> dict[str, Any]:
90
+ report: dict[str, Any] = {"installation": installation(ctx)}
91
+ if root is not None:
92
+ report["project"] = project_report(root, ctx)
93
+ if all_projects:
94
+ report["projects"] = [project_report(p, ctx) for p in registered_projects(ctx) if p.is_dir()]
95
+ return report
96
+
97
+
98
+ def doctor(ctx: Context, root: Path | None = None) -> dict[str, Any]:
99
+ """Checks that logging will really happen; ``ok`` is False when any check fails."""
100
+ info = installation(ctx)
101
+ checks: list[dict[str, str]] = []
102
+
103
+ def check(name: str, ok: bool, detail: str, *, warn: bool = False, fix: str = "") -> None:
104
+ checks.append({"name": name, "status": "ok" if ok else ("warn" if warn else "fail"), "detail": detail, "fix": "" if ok else fix})
105
+
106
+ check("runtime installed", info["launcher_present"] and info["runtime_version"] is not None, str(ctx.shared_root), fix="run `backfill install`")
107
+ check(
108
+ "runtime is current", info["runtime_version"] == __version__,
109
+ f"installed {info['runtime_version']}, this is {__version__}", warn=True, fix="run `backfill install` to update the hooks' copy",
110
+ )
111
+ check("hook interpreter exists", info["python_exists"], str(info["python"]), fix="run `backfill install` (the Python it used was moved or removed)")
112
+ if info["launcher_present"] and info["python_exists"]:
113
+ try:
114
+ result = subprocess.run([info["python"], str(ctx.launcher), "version"], capture_output=True, timeout=20, text=True)
115
+ check("hook launcher runs", result.returncode == 0, result.stdout.strip() or result.stderr.strip()[:200], fix="see hook-errors.log; try `backfill install`")
116
+ except (OSError, subprocess.SubprocessError) as exc:
117
+ check("hook launcher runs", False, str(exc), fix="run `backfill install`")
118
+ check("no hook errors recorded", info["errors_log"] is None, info["errors_log"] or "clean", warn=True, fix="read the log, then delete it once handled")
119
+
120
+ claude_info = info["claude"]
121
+ if claude_info["home_exists"] or info["agent_commands"]["claude"]:
122
+ check("claude: settings.json readable", claude_info["settings_error"] is None, claude_info["settings_error"] or str(ctx.claude_home / "settings.json"))
123
+ check("claude: hooks registered", claude_info["all_hooks_registered"], ", ".join(claude_info["hooks_registered"]) or "none", fix="run `backfill install`")
124
+ check("claude: old claude-logger hooks gone", not claude_info["legacy_hooks"], "none left" if not claude_info["legacy_hooks"] else "old hooks still present", warn=True, fix="run `backfill install` (replaces them)")
125
+ check("claude: instruction block", claude_info["instructions_present"], str(ctx.claude_home / "CLAUDE.md"), warn=True, fix="run `backfill install`")
126
+ cleanup = claude_info["cleanup_period_days"]
127
+ check(
128
+ "claude: keeps its own transcripts long", isinstance(cleanup, int) and cleanup >= 365,
129
+ f"cleanupPeriodDays = {cleanup}; copies in .claude-logs are unaffected", warn=True,
130
+ fix="optional: `backfill install --retain-days 3650`",
131
+ )
132
+ else:
133
+ checks.append({"name": "claude", "status": "skip", "detail": "Claude Code not found on this machine", "fix": ""})
134
+
135
+ codex_homes = [h for h in info["codex"]["homes"] if h["exists"]]
136
+ if codex_homes or info["agent_commands"]["codex"]:
137
+ for home in codex_homes:
138
+ label = f"codex ({Path(home['home']).name}): "
139
+ check(label + "notify hook", home["notify"] == "backfill", home["notify"], fix="run `backfill install`")
140
+ check(label + "lifecycle hooks", bool(home["hooks_registered"]), ", ".join(home["hooks_registered"]) or "none", warn=True, fix="run `backfill install`; then review with /hooks in Codex")
141
+ if home["error"]:
142
+ check(label + "config readable", False, home["error"])
143
+ else:
144
+ checks.append({"name": "codex", "status": "skip", "detail": "Codex not found on this machine", "fix": ""})
145
+
146
+ if root is not None:
147
+ report = project_report(root, ctx)
148
+ if report["config"]:
149
+ check("project config valid", not report["config_problems"], "; ".join(report["config_problems"]) or report["config"], fix="edit .agents/backfill.toml")
150
+ for agent, item in report["agents"].items():
151
+ if item["skipped"] and "not enabled" not in item["skipped"]:
152
+ checks.append({"name": f"project: {agent}", "status": "skip", "detail": f"not logged here: {item['skipped']}", "fix": ""})
153
+ elif item.get("sessions_behind_agent_copy"):
154
+ check(f"project: {agent} copies current", False, f"{len(item['sessions_behind_agent_copy'])} session(s) behind", warn=True, fix="run `backfill sync`")
155
+ if root is not None:
156
+ checks += [{"name": f"covers: {name}", "status": "info", "detail": detail, "fix": hint} for name, detail, hint in coverage(ctx, root)]
157
+ return {"ok": all(c["status"] != "fail" for c in checks), "checks": checks}
158
+
159
+
160
+ def coverage(ctx: Context, root: Path) -> list[tuple[str, str, str]]:
161
+ """(what, how it is handled, how to change it) for the things an agent produces, per the project's effective config."""
162
+ config = load_config(ctx, root)
163
+ capture = config["capture"]
164
+ scratch = capture["scratchpad"]
165
+ rows = [
166
+ ("transcripts", {"raw": "kept byte for byte", "redacted": "kept, secrets removed", "off": "NOT kept"}[capture["transcripts"]], "capture.transcripts"),
167
+ ("readable history", f"kept (output of {', '.join(capture['exclude_tools'])} left out)" if capture["exclude_tools"] else "kept, every tool call included", "capture.exclude_tools, capture.session_max_mb"),
168
+ ("event journal", "kept" if capture["journal_events"] else "NOT kept", "capture.journal_events"),
169
+ ("edit backups, todos, subagents (Claude)", "copied" if capture["copy_artifacts"] else "NOT copied", "capture.copy_artifacts"),
170
+ ("scratchpad files (Claude) and generated images (Codex)", {"off": "NOT recorded", "manifest": "listed with sizes and hashes", "copy": "listed and copied"}[scratch], "capture.scratchpad"),
171
+ ("layout", f"{config['logs']['layout']} ({'YYYY-MM folders' if config['logs']['layout'] == 'monthly' else 'one folder'})", "logs.layout"),
172
+ ("Codex hook coverage", f"profile {capture['codex_profile']} (set at install time)", "backfill install --codex-profile"),
173
+ ("not captured at all", "agent databases (Codex *.sqlite), memories, pasted images", "see `backfill clean` for their size"),
174
+ ]
175
+ return rows
176
+
177
+
178
+ # --- plain-text rendering --------------------------------------------------------------------------------------
179
+
180
+ MARK = {"ok": "ok ", "warn": "warn", "fail": "FAIL", "skip": "skip", "info": "info"}
181
+
182
+
183
+ def render_doctor(report: dict[str, Any]) -> str:
184
+ lines = []
185
+ for item in report["checks"]:
186
+ lines.append(f"[{MARK[item['status']]}] {item['name']}: {item['detail']}")
187
+ if item["fix"]:
188
+ lines.append(f" {'setting' if item['status'] == 'info' else '->'}: {item['fix']}" if item["status"] == "info" else f" -> {item['fix']}")
189
+ failed = sum(1 for c in report["checks"] if c["status"] == "fail")
190
+ warned = sum(1 for c in report["checks"] if c["status"] == "warn")
191
+ lines.append("")
192
+ lines.append("Everything needed for logging is in place." if report["ok"] and not warned else (
193
+ f"{failed} failing, {warned} warning(s)." if failed or warned else "ok"))
194
+ return "\n".join(lines)
195
+
196
+
197
+ def render_status(report: dict[str, Any]) -> str:
198
+ from backfill.util import human_bytes
199
+
200
+ inst = report["installation"]
201
+ lines = [f"backfill {inst['version']} runtime: {inst['runtime_version'] or 'NOT INSTALLED'} data: {inst['shared_root']}"]
202
+ claude_info, codex_info = inst["claude"], inst["codex"]
203
+ lines.append(
204
+ f" Claude Code: {'hooks ' + str(len(claude_info['hooks_registered'])) + '/8' if claude_info['hooks_registered'] else 'not hooked'}"
205
+ f"{'' if claude_info['home_exists'] else ' (not found)'}"
206
+ )
207
+ for home in codex_info["homes"]:
208
+ if home["exists"]:
209
+ lines.append(f" Codex ({home['home']}): notify={home['notify']}, lifecycle hooks={len(home['hooks_registered'])}")
210
+ if not any(h["exists"] for h in codex_info["homes"]):
211
+ lines.append(" Codex: not found")
212
+ projects = [report["project"]] if "project" in report else []
213
+ projects += report.get("projects", [])
214
+ for project in projects:
215
+ lines += ["", f"Project {project['root']}", f" config: {project['config'] or 'none (defaults; run `backfill init`)'}"]
216
+ for problem in project["config_problems"]:
217
+ lines.append(f" config problem: {problem}")
218
+ for agent, item in project["agents"].items():
219
+ if item["skipped"]:
220
+ lines.append(f" {agent}: not logged ({item['skipped']})")
221
+ continue
222
+ if not item["exists"]:
223
+ extra = f", {item['available_to_backfill']} earlier session(s) can be imported (`backfill sync`)" if item["available_to_backfill"] else ""
224
+ extra += f", older logs in {', '.join(item['legacy_dirs'])} (`backfill sync` imports them)" if item.get("legacy_dirs") else ""
225
+ lines.append(f" {agent}: no logs yet{extra}")
226
+ continue
227
+ behind = f", {len(item['sessions_behind_agent_copy'])} behind" if item["sessions_behind_agent_copy"] else ""
228
+ waiting = f", {item['available_to_backfill']} waiting for `backfill sync`" if item["available_to_backfill"] else ""
229
+ waiting += f", older logs in {', '.join(item['legacy_dirs'])} (`backfill sync` imports them)" if item.get("legacy_dirs") else ""
230
+ lines.append(
231
+ f" {agent}: {item['sessions']} sessions, {item['turns']} turns, {human_bytes(item['size_bytes'])}, "
232
+ f"last {str(item['last_activity'] or '-')[:16].replace('T', ' ')}{behind}{waiting}"
233
+ )
234
+ if inst["errors_log"]:
235
+ lines += ["", f"Hook errors were recorded: {inst['errors_log']}"]
236
+ return "\n".join(lines)
237
+
backfill/transcript.py ADDED
@@ -0,0 +1,269 @@
1
+ """Reading Claude Code transcripts (JSON lines) and turning them into summaries and readable markdown."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterable, Mapping
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ TEXT_LIMIT = 2000
11
+ PREVIEW_LIMIT = 300
12
+ TOOL_NAME_MEMORY = 300 # tool_use ids remembered between hook runs so that results can be labelled
13
+
14
+
15
+ # --- reading ---------------------------------------------------------------------------------------------------
16
+
17
+
18
+ def read_entries(path: Path, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
19
+ """Parsed transcript lines that start at byte ``offset``, and the offset to continue from.
20
+
21
+ A trailing line that is not finished yet (no newline and not valid JSON) is left for the next call. A file
22
+ that became smaller than ``offset`` is read from the start.
23
+ """
24
+ try:
25
+ with path.open("rb") as handle:
26
+ handle.seek(0, 2)
27
+ if handle.tell() < offset:
28
+ offset = 0
29
+ handle.seek(offset)
30
+ data = handle.read()
31
+ except OSError:
32
+ return [], offset
33
+ end = data.rfind(b"\n") + 1
34
+ complete, tail = data[:end], data[end:]
35
+ consumed = end
36
+ chunks = [line for line in complete.split(b"\n") if line.strip()]
37
+ if tail.strip():
38
+ try:
39
+ json.loads(tail)
40
+ except ValueError:
41
+ pass
42
+ else:
43
+ chunks.append(tail)
44
+ consumed = len(data)
45
+ entries: list[dict[str, Any]] = []
46
+ for raw in chunks:
47
+ try:
48
+ value = json.loads(raw.decode("utf-8", errors="replace"))
49
+ except ValueError:
50
+ continue
51
+ if isinstance(value, dict):
52
+ entries.append(value)
53
+ return entries, offset + consumed
54
+
55
+
56
+ def offset_after_lines(path: Path, lines: int) -> int:
57
+ """Byte offset just after the first ``lines`` raw lines (used to migrate version 1 bookkeeping)."""
58
+ offset = 0
59
+ try:
60
+ with path.open("rb") as handle:
61
+ for index, raw in enumerate(handle):
62
+ if index >= lines:
63
+ break
64
+ offset += len(raw)
65
+ except OSError:
66
+ return 0
67
+ return offset
68
+
69
+
70
+ # --- blocks ----------------------------------------------------------------------------------------------------
71
+
72
+
73
+ def message_blocks(entry: Mapping[str, Any]) -> tuple[str, list[dict[str, Any]]]:
74
+ message = entry.get("message")
75
+ if not isinstance(message, dict):
76
+ return "", []
77
+ role = str(message.get("role") or entry.get("type") or "")
78
+ content = message.get("content")
79
+ if isinstance(content, str):
80
+ return role, [{"type": "text", "text": content}]
81
+ if isinstance(content, list):
82
+ return role, [block for block in content if isinstance(block, dict)]
83
+ return role, []
84
+
85
+
86
+ def preview(value: Any, limit: int = PREVIEW_LIMIT) -> str:
87
+ try:
88
+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
89
+ except (TypeError, ValueError):
90
+ text = str(value)
91
+ return text if len(text) <= limit else text[:limit] + "..."
92
+
93
+
94
+ def result_text(block: Mapping[str, Any]) -> str:
95
+ """Text of a ``tool_result`` block (a string, or a list of text/image parts)."""
96
+ content = block.get("content")
97
+ if isinstance(content, str):
98
+ return content
99
+ if isinstance(content, list):
100
+ parts = []
101
+ for part in content:
102
+ if not isinstance(part, dict):
103
+ continue
104
+ if part.get("type") == "text":
105
+ parts.append(str(part.get("text") or ""))
106
+ else:
107
+ parts.append(f"[{part.get('type', 'content')}]")
108
+ return "\n".join(parts)
109
+ return "" if content is None else str(content)
110
+
111
+
112
+ def is_real_user_text(entry: Mapping[str, Any], text: str) -> bool:
113
+ """A prompt typed by the user (not a tool result, command caveat or other injected meta message)."""
114
+ return not entry.get("isMeta") and not text.lstrip().startswith("<")
115
+
116
+
117
+ # --- summaries -------------------------------------------------------------------------------------------------
118
+
119
+
120
+ def summarize_entries(entries: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
121
+ user_messages: list[str] = []
122
+ assistant_messages: list[str] = []
123
+ tool_calls: list[dict[str, str]] = []
124
+ tool_results = tool_errors = entry_count = thinking_blocks = thinking_chars = 0
125
+ models: set[str] = set()
126
+ usage: dict[str, int] = {}
127
+ title = ""
128
+ for entry in entries:
129
+ entry_count += 1
130
+ if entry.get("type") == "ai-title" and entry.get("aiTitle"):
131
+ title = str(entry["aiTitle"])
132
+ role, blocks = message_blocks(entry)
133
+ message = entry.get("message")
134
+ if role == "assistant" and isinstance(message, dict):
135
+ if message.get("model"):
136
+ models.add(str(message["model"]))
137
+ if isinstance(message.get("usage"), dict):
138
+ for key, value in message["usage"].items():
139
+ if isinstance(value, int) and not isinstance(value, bool):
140
+ usage[key] = usage.get(key, 0) + value
141
+ for block in blocks:
142
+ kind = block.get("type")
143
+ if kind == "text":
144
+ text = str(block.get("text") or "")
145
+ if text and role == "user" and is_real_user_text(entry, text):
146
+ user_messages.append(text[:TEXT_LIMIT])
147
+ elif text and role == "assistant":
148
+ assistant_messages.append(text[:TEXT_LIMIT])
149
+ elif kind == "thinking":
150
+ thinking_blocks += 1
151
+ thinking_chars += len(str(block.get("thinking") or ""))
152
+ elif kind == "tool_use":
153
+ tool_calls.append({"tool_name": str(block.get("name") or ""), "input_preview": preview(block.get("input"))})
154
+ elif kind == "tool_result":
155
+ tool_results += 1
156
+ if block.get("is_error"):
157
+ tool_errors += 1
158
+ return {
159
+ "entry_count": entry_count,
160
+ "title": title,
161
+ "user_message_count": len(user_messages),
162
+ "assistant_message_count": len(assistant_messages),
163
+ "user_messages": user_messages,
164
+ "assistant_messages": assistant_messages,
165
+ "models": sorted(models),
166
+ "usage": usage,
167
+ "thinking_blocks": thinking_blocks,
168
+ "thinking_chars": thinking_chars,
169
+ "tools_used": sorted({call["tool_name"] for call in tool_calls if call["tool_name"]}),
170
+ "tool_calls": tool_calls,
171
+ "tool_result_count": tool_results,
172
+ "tool_error_count": tool_errors,
173
+ }
174
+
175
+
176
+ # --- markdown --------------------------------------------------------------------------------------------------
177
+
178
+
179
+ def cut(text: str, limit: int) -> str:
180
+ if len(text) <= limit:
181
+ return text
182
+ return f"{text[:limit]}\n[... {len(text) - limit} more characters; the full text is in transcripts/]"
183
+
184
+
185
+ def fenced(text: str, language: str = "") -> str:
186
+ fence = "```"
187
+ while fence in text:
188
+ fence += "`"
189
+ return f"{fence}{language}\n{text}\n{fence}"
190
+
191
+
192
+ def render_markdown(
193
+ entries: Iterable[Mapping[str, Any]], state: dict[str, Any] | None = None, limits: Mapping[str, int] | None = None
194
+ ) -> str:
195
+ """Readable conversation: prompts, answers, reasoning, and every tool call with its (capped) input and output.
196
+
197
+ ``state`` carries ``role`` (last heading written) and ``tool_names`` across calls so that an incremental
198
+ rendering continues seamlessly; it is updated in place.
199
+ """
200
+ state = state if state is not None else {}
201
+ limits = limits or {}
202
+ text_limit = int(limits.get("markdown_text_limit", 20000))
203
+ input_limit = int(limits.get("markdown_tool_input_limit", 2000))
204
+ output_limit = int(limits.get("markdown_tool_output_limit", 4000))
205
+ excluded = set(limits.get("exclude_tools") or [])
206
+ tool_names: dict[str, str] = state.setdefault("tool_names", {})
207
+ parts: list[str] = []
208
+
209
+ def heading(role: str, entry: Mapping[str, Any], extra: str = "") -> None:
210
+ if state.get("role") == role:
211
+ return
212
+ state["role"] = role
213
+ stamp = str(entry.get("timestamp") or "")
214
+ label = {"user": "User", "assistant": "Assistant"}[role]
215
+ side = " (subagent)" if entry.get("isSidechain") else ""
216
+ parts.append(f"## {label}{side}{f' _({stamp})_' if stamp else ''}{extra}\n")
217
+
218
+ for entry in entries:
219
+ role, blocks = message_blocks(entry)
220
+ if role not in {"user", "assistant"} or not blocks:
221
+ continue
222
+ if entry.get("isSidechain") and state.get("role") != role:
223
+ state["role"] = None # a subagent switch always opens a new heading
224
+ message = entry.get("message") if isinstance(entry.get("message"), dict) else {}
225
+ for block in blocks:
226
+ kind = block.get("type")
227
+ if kind == "text":
228
+ text = str(block.get("text") or "").strip()
229
+ if not text:
230
+ continue
231
+ if role == "user" and not is_real_user_text(entry, text):
232
+ heading("user", entry)
233
+ parts.append(f"_(injected message)_\n\n{fenced(cut(text, 1500))}\n")
234
+ continue
235
+ heading(role, entry, f" · {message['model']}" if role == "assistant" and message.get("model") else "")
236
+ parts.append(cut(text, text_limit) + "\n")
237
+ elif kind == "thinking":
238
+ thinking = str(block.get("thinking") or "").strip()
239
+ heading("assistant", entry)
240
+ if thinking:
241
+ parts.append(f"<details><summary>Reasoning</summary>\n\n{cut(thinking, text_limit)}\n\n</details>\n")
242
+ else:
243
+ parts.append("_(reasoning block: Claude Code did not store its text)_\n")
244
+ elif kind == "redacted_thinking":
245
+ heading("assistant", entry)
246
+ parts.append("_(reasoning block: redacted)_\n")
247
+ elif kind == "tool_use":
248
+ heading("assistant", entry)
249
+ name = str(block.get("name") or "tool")
250
+ identifier = str(block.get("id") or "")
251
+ if identifier:
252
+ tool_names[identifier] = name
253
+ while len(tool_names) > TOOL_NAME_MEMORY:
254
+ tool_names.pop(next(iter(tool_names)))
255
+ payload = block.get("input")
256
+ body = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False, indent=2, default=str)
257
+ parts.append(f"**Tool call:** `{name}`\n\n{fenced(cut(body, input_limit), 'json')}\n")
258
+ elif kind == "tool_result":
259
+ name = tool_names.get(str(block.get("tool_use_id") or ""), "tool")
260
+ status = "error" if block.get("is_error") else "ok"
261
+ output = result_text(block).strip()
262
+ parts.append(f"**Tool result:** `{name}` ({status})\n")
263
+ if name in excluded:
264
+ parts.append("_(output omitted: exclude_tools)_\n")
265
+ elif output:
266
+ parts.append(fenced(cut(output, output_limit)) + "\n")
267
+ elif kind == "image":
268
+ parts.append("_(image)_\n")
269
+ return "\n".join(parts)