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.
@@ -0,0 +1,786 @@
1
+ """Codex: notify + lifecycle-hook handler, ``config.toml`` / ``hooks.json`` installation, and import of rollouts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import tomllib
9
+ from collections.abc import Iterable, Mapping
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from backfill import __version__
14
+ from backfill.agents import session_context
15
+ from backfill.capture import MEGABYTE, git_snapshot, snapshot_files
16
+ from backfill.config import CODEX_PROFILES, load_config
17
+ from backfill.core import (
18
+ Adapter,
19
+ ingest_session,
20
+ journal_event,
21
+ metadata_snapshot,
22
+ registry_touch,
23
+ session_lock,
24
+ turn_entry,
25
+ write_index,
26
+ )
27
+ from backfill.layout import Layout
28
+ from backfill.redact import Redactor, redactor_for
29
+ from backfill.roots import find_root, skip_reason
30
+ from backfill.runtime import (
31
+ INSTRUCTION_START,
32
+ command_line,
33
+ system_python,
34
+ with_instruction_block,
35
+ without_instruction_block,
36
+ )
37
+ from backfill.transcript import cut, fenced, preview
38
+ from backfill.util import (
39
+ Context,
40
+ append_jsonl,
41
+ backup_file,
42
+ iso_utc_now,
43
+ read_json,
44
+ same_path,
45
+ write_json,
46
+ write_text_atomic,
47
+ )
48
+
49
+ NAME = "codex"
50
+ CAPTURE_PROFILE_EVENTS: dict[str, tuple[str, ...]] = {
51
+ "minimal": ("SessionStart", "SessionEnd"),
52
+ "standard": ("SessionStart", "UserPromptSubmit", "PostToolUse", "PreCompact", "PostCompact", "SubagentStop", "Stop", "SessionEnd"),
53
+ "full": (
54
+ "SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact",
55
+ "PostCompact", "SubagentStart", "SubagentStop", "Stop", "Interrupt", "SessionEnd",
56
+ ),
57
+ }
58
+ SUPPORTED_EVENTS = set(CAPTURE_PROFILE_EVENTS["full"])
59
+ SYNC_EVENTS = {"Stop", "PreCompact", "PostCompact", "SubagentStop", "SessionEnd"}
60
+ LEGACY_NOTIFY_NAMES = {"codex_notify_router.py", "codex_notify_fanout.py", "codex_repo_router.py", "codex_notify.sh"} # loggers backfill replaces
61
+ LEGACY_HANDLER_FILES = ("codex_repo_router.py",)
62
+ MANAGED_DESCRIPTION = "backfill lifecycle hooks."
63
+ STATUS_PREFIX = "backfill: "
64
+
65
+
66
+ def instructions_path(home: Path) -> Path:
67
+ return home / "AGENTS.md"
68
+
69
+
70
+ # --- transcript (rollout) understanding -----------------------------------------------------------------------
71
+
72
+
73
+ def _payload(entry: Mapping[str, Any]) -> Mapping[str, Any]:
74
+ value = entry.get("payload")
75
+ return value if isinstance(value, dict) else {}
76
+
77
+
78
+ def _texts(content: Any) -> list[str]:
79
+ if isinstance(content, str):
80
+ return [content]
81
+ parts: list[str] = []
82
+ if isinstance(content, list):
83
+ for part in content:
84
+ if isinstance(part, dict) and isinstance(part.get("text"), str):
85
+ parts.append(part["text"])
86
+ return parts
87
+
88
+
89
+ def _is_real_user_text(text: str) -> bool:
90
+ stripped = text.lstrip()
91
+ return bool(stripped) and not stripped.startswith("<") # <environment_context>, <user_instructions>, ...
92
+
93
+
94
+ class CodexAdapter:
95
+ name = NAME
96
+
97
+ def summarize(self, entries: list[dict[str, Any]]) -> dict[str, Any]:
98
+ users: list[str] = []
99
+ assistants: list[str] = []
100
+ calls: list[dict[str, str]] = []
101
+ results = 0
102
+ models: list[str] = []
103
+ usage = {"input_tokens": 0, "output_tokens": 0, "cache_read_tokens": 0}
104
+ for entry in entries:
105
+ kind, payload = entry.get("type"), _payload(entry)
106
+ if kind == "turn_context" and payload.get("model"):
107
+ models.append(str(payload["model"]))
108
+ elif kind == "event_msg" and payload.get("type") == "token_count":
109
+ last = (payload.get("info") or {}).get("last_token_usage") or {}
110
+ cached = int(last.get("cached_input_tokens") or 0)
111
+ usage["input_tokens"] += max(int(last.get("input_tokens") or 0) - cached, 0)
112
+ usage["cache_read_tokens"] += cached
113
+ usage["output_tokens"] += int(last.get("output_tokens") or 0)
114
+ elif kind == "response_item":
115
+ item = payload.get("type")
116
+ if item == "message":
117
+ text = "\n".join(_texts(payload.get("content"))).strip()
118
+ if payload.get("role") == "user" and _is_real_user_text(text):
119
+ users.append(text[:2000])
120
+ elif payload.get("role") == "assistant" and text:
121
+ assistants.append(text[:2000])
122
+ elif item in ("function_call", "custom_tool_call", "local_shell_call"):
123
+ calls.append({"tool_name": str(payload.get("name") or item), "input_preview": preview(payload.get("arguments") or payload.get("input"))})
124
+ elif item in ("function_call_output", "custom_tool_call_output"):
125
+ results += 1
126
+ return {
127
+ "entry_count": len(entries),
128
+ "title": "",
129
+ "user_message_count": len(users),
130
+ "assistant_message_count": len(assistants),
131
+ "user_messages": users,
132
+ "assistant_messages": assistants,
133
+ "models": list(dict.fromkeys(models)),
134
+ "usage": usage,
135
+ "token_totals": usage,
136
+ "tools_used": sorted({c["tool_name"] for c in calls}),
137
+ "tool_calls": calls,
138
+ "tool_result_count": results,
139
+ "tool_error_count": 0,
140
+ }
141
+
142
+ def render(self, entries: list[dict[str, Any]], state: dict[str, Any], config: Mapping[str, Any]) -> str:
143
+ text_limit = int(config.get("markdown_text_limit", 20000))
144
+ input_limit = int(config.get("markdown_tool_input_limit", 2000))
145
+ output_limit = int(config.get("markdown_tool_output_limit", 4000))
146
+ excluded = set(config.get("exclude_tools") or [])
147
+ names: dict[str, str] = state.setdefault("tool_names", {})
148
+ parts: list[str] = []
149
+
150
+ def heading(role: str, entry: Mapping[str, Any]) -> None:
151
+ if state.get("role") == role:
152
+ return
153
+ state["role"] = role
154
+ stamp = str(entry.get("timestamp") or "")
155
+ parts.append(f"## {'User' if role == 'user' else 'Assistant'}{f' _({stamp})_' if stamp else ''}\n")
156
+
157
+ for entry in entries:
158
+ if entry.get("type") != "response_item":
159
+ continue
160
+ payload = _payload(entry)
161
+ kind = payload.get("type")
162
+ if kind == "message":
163
+ role = payload.get("role")
164
+ text = "\n".join(_texts(payload.get("content"))).strip()
165
+ if role == "user" and _is_real_user_text(text):
166
+ heading("user", entry)
167
+ parts.append(cut(text, text_limit) + "\n")
168
+ elif role == "assistant" and text:
169
+ heading("assistant", entry)
170
+ parts.append(cut(text, text_limit) + "\n")
171
+ elif kind == "reasoning":
172
+ summary = "\n".join(_texts(payload.get("summary"))).strip()
173
+ heading("assistant", entry)
174
+ if summary:
175
+ parts.append(f"<details><summary>Reasoning</summary>\n\n{cut(summary, text_limit)}\n\n</details>\n")
176
+ elif kind in ("function_call", "custom_tool_call", "local_shell_call"):
177
+ heading("assistant", entry)
178
+ name = str(payload.get("name") or kind)
179
+ call_id = str(payload.get("call_id") or "")
180
+ if call_id:
181
+ names[call_id] = name
182
+ while len(names) > 300:
183
+ names.pop(next(iter(names)))
184
+ body = payload.get("arguments") or payload.get("input") or payload.get("action") or ""
185
+ body = body if isinstance(body, str) else json.dumps(body, ensure_ascii=False, indent=2, default=str)
186
+ parts.append(f"**Tool call:** `{name}`\n\n{fenced(cut(body, input_limit))}\n")
187
+ elif kind in ("function_call_output", "custom_tool_call_output"):
188
+ name = names.get(str(payload.get("call_id") or ""), "tool")
189
+ output = payload.get("output")
190
+ body = output if isinstance(output, str) else "\n".join(_texts(output))
191
+ parts.append(f"**Tool result:** `{name}`\n")
192
+ if name in excluded:
193
+ parts.append("_(output omitted: exclude_tools)_\n")
194
+ elif body.strip():
195
+ parts.append(fenced(cut(body.strip(), output_limit)) + "\n")
196
+ return "\n".join(parts)
197
+
198
+ def sync_artifacts(
199
+ self, layout: Layout, session_id: str, ctx: Context, transcript: Path | None, config: Mapping[str, Any], redactor: Redactor
200
+ ) -> dict[str, int]:
201
+ """Generated images of the session (manifest or copy, per ``capture.scratchpad``)."""
202
+ capture = config["capture"]
203
+ images = ctx.codex_home / "generated_images" / session_id
204
+ return snapshot_files(images, layout.session_artifacts(session_id), "generated_images", capture["scratchpad"], int(capture["scratchpad_max_mb"]) * MEGABYTE, redactor)
205
+
206
+
207
+ ADAPTER: Adapter = CodexAdapter()
208
+
209
+
210
+ # --- locating rollouts -----------------------------------------------------------------------------------------
211
+
212
+
213
+ def rollout_dirs(ctx: Context) -> list[Path]:
214
+ return [ctx.codex_home / "sessions", ctx.codex_home / "archived_sessions"]
215
+
216
+
217
+ def read_session_meta(path: Path) -> dict[str, Any]:
218
+ """The ``session_meta`` payload (id, cwd, ...) from the first line of a rollout file."""
219
+ try:
220
+ with path.open("r", encoding="utf-8", errors="replace") as handle:
221
+ first = handle.readline()
222
+ value = json.loads(first)
223
+ except (OSError, ValueError):
224
+ return {}
225
+ if isinstance(value, dict) and value.get("type") == "session_meta" and isinstance(value.get("payload"), dict):
226
+ return value["payload"]
227
+ return {}
228
+
229
+
230
+ def find_rollout(ctx: Context, session_id: str) -> Path | None:
231
+ for base in rollout_dirs(ctx):
232
+ if base.is_dir():
233
+ matches = sorted(base.rglob(f"rollout-*{session_id}*.jsonl"))
234
+ if matches:
235
+ return matches[-1]
236
+ return None
237
+
238
+
239
+ def scan_rollouts(ctx: Context) -> list[tuple[Path, str, str]]:
240
+ """Every rollout Codex has stored: (file, session id, working directory)."""
241
+ found: list[tuple[Path, str, str]] = []
242
+ for base in rollout_dirs(ctx):
243
+ if not base.is_dir():
244
+ continue
245
+ for path in sorted(base.rglob("rollout-*.jsonl")):
246
+ meta = read_session_meta(path)
247
+ session_id, cwd = meta.get("id") or meta.get("session_id"), meta.get("cwd")
248
+ if isinstance(session_id, str) and isinstance(cwd, str) and cwd:
249
+ found.append((path, session_id, cwd))
250
+ return found
251
+
252
+
253
+ def rollouts_for(root: Path, ctx: Context, scanned: list[tuple[Path, str, str]] | None = None) -> list[tuple[Path, str, str]]:
254
+ result = []
255
+ for path, session_id, cwd in scanned if scanned is not None else scan_rollouts(ctx):
256
+ found = find_root(cwd, ctx.env, ctx.home) if Path(cwd).exists() else None
257
+ if found is not None and same_path(found, root):
258
+ result.append((path, session_id, cwd))
259
+ return result
260
+
261
+
262
+ def unlogged_sessions(layout: Layout, ctx: Context) -> list[str]:
263
+ return [sid for _, sid, _ in rollouts_for(layout.root, ctx) if not layout.state_path(sid).exists() and not layout.transcript_path(sid).exists()]
264
+
265
+
266
+ # --- handler ---------------------------------------------------------------------------------------------------
267
+
268
+
269
+ def event_name(payload: Mapping[str, Any]) -> str:
270
+ return str(payload.get("type") or payload.get("hook_event_name") or "unknown")
271
+
272
+
273
+ def session_identifier(payload: Mapping[str, Any], env: Mapping[str, str]) -> str:
274
+ for candidate in (
275
+ env.get("CODEX_THREAD_ID"), payload.get("thread-id"), payload.get("thread_id"), env.get("CODEX_SESSION_ID"),
276
+ payload.get("session_id"), payload.get("turn-id"), payload.get("turn_id"),
277
+ ):
278
+ if candidate:
279
+ return str(candidate)
280
+ return "session-unknown"
281
+
282
+
283
+ def handle_payload(payload: Mapping[str, Any], ctx: Context | None = None, *, source: str = "hook") -> dict[str, Any] | None:
284
+ """Process one Codex notify payload or lifecycle-hook event."""
285
+ ctx = ctx or Context.from_environment()
286
+ name = event_name(payload)
287
+ is_turn = name == "agent-turn-complete"
288
+ if not (is_turn or name in SUPPORTED_EVENTS):
289
+ return None
290
+ root = find_root(str(payload.get("cwd") or "") or None, ctx.env, ctx.home)
291
+ if root is None or skip_reason(root, ctx, NAME):
292
+ return None
293
+
294
+ config = load_config(ctx, root)
295
+ redactor = redactor_for(config)
296
+ layout = Layout(root, NAME, config)
297
+ try:
298
+ layout.ensure()
299
+ except PermissionError:
300
+ return None # e.g. a session started in C:\Program Files: nothing can be written there, and that is not an error
301
+ session_id = session_identifier(payload, ctx.env)
302
+ cwd = str(payload.get("cwd") or "") or None
303
+ with session_lock(layout, session_id): # async hooks and the notify command of one session take turns
304
+ return _process(payload, name, is_turn, source, ctx, root, config, redactor, layout, session_id, cwd)
305
+
306
+
307
+ def _process(payload, name, is_turn, source, ctx, root, config, redactor, layout, session_id, cwd): # noqa: ANN001
308
+ state = read_json(layout.state_path(session_id))
309
+ first_time = not state
310
+
311
+ transcript: Path | None = None
312
+ if payload.get("transcript_path"):
313
+ transcript = Path(str(payload["transcript_path"]))
314
+ elif state.get("transcript_path"):
315
+ transcript = Path(str(state["transcript_path"]))
316
+ if (transcript is None or not transcript.is_file()) and (is_turn or name in SYNC_EVENTS):
317
+ transcript = find_rollout(ctx, session_id)
318
+
319
+ if config["capture"]["journal_events"] and not is_turn and name not in ("SessionStart", "SessionEnd"):
320
+ journal_event(layout, {**payload, "session_id": session_id}, config, redactor)
321
+
322
+ if first_time:
323
+ write_json(
324
+ layout.state_path(session_id),
325
+ {
326
+ "agent": NAME, "session_id": session_id, "first_seen_at": iso_utc_now(), "last_seen_at": iso_utc_now(),
327
+ "turn_count": 0, "cwd": cwd, "model": payload.get("model"),
328
+ "transcript_path": str(transcript) if transcript else None,
329
+ },
330
+ )
331
+ append_jsonl(
332
+ layout.daily("sessions"),
333
+ {
334
+ "timestamp_utc": iso_utc_now(), "event_type": "session-start", "agent": NAME, "session_id": session_id,
335
+ "cwd": cwd, "source": source, "model": payload.get("model"), "metadata": metadata_snapshot(ctx.env, root), "repo": git_snapshot(root),
336
+ "logger_version": __version__,
337
+ },
338
+ )
339
+ elif payload.get("model") or transcript:
340
+ state.update({"model": payload.get("model") or state.get("model"), "transcript_path": str(transcript) if transcript else state.get("transcript_path")})
341
+ write_json(layout.state_path(session_id), state)
342
+
343
+ output: dict[str, Any] | None = None
344
+ if name == "SessionStart":
345
+ context = session_context(layout, config)
346
+ if context:
347
+ output = {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}}
348
+
349
+ entries: list[dict[str, Any]] = []
350
+ if is_turn or name in SYNC_EVENTS:
351
+ state, entries = ingest_session(
352
+ layout, ADAPTER, ctx, config, redactor, session_id, transcript, cwd=cwd,
353
+ extra_state={"model": payload["model"]} if payload.get("model") else None,
354
+ )
355
+
356
+ if is_turn:
357
+ turn_count = int(state.get("turn_count") or 0) + 1
358
+ state["turn_count"] = turn_count
359
+ write_json(layout.state_path(session_id), state)
360
+ messages = payload.get("input-messages", [])
361
+ messages = messages if isinstance(messages, list) else [messages]
362
+ assistant = payload.get("last-assistant-message", "")
363
+ assistant = assistant if isinstance(assistant, str) else str(assistant)
364
+ summary = ADAPTER.summarize(entries)
365
+ turn_entry(
366
+ layout, session_id, turn_count, cwd, summary, git_snapshot(root),
367
+ {
368
+ "turn_id": payload.get("turn-id") or payload.get("turn_id"),
369
+ "source": source,
370
+ "input_messages": redactor.obj(messages),
371
+ "last_assistant_message": redactor.text(assistant),
372
+ },
373
+ redactor,
374
+ )
375
+ elif name == "SessionEnd":
376
+ append_jsonl(
377
+ layout.daily("sessions"),
378
+ {
379
+ "timestamp_utc": iso_utc_now(), "event_type": "session-end", "agent": NAME, "session_id": session_id,
380
+ "reason": payload.get("reason"), "turn_count": state.get("turn_count"),
381
+ },
382
+ )
383
+ write_json(layout.log_dir / "latest-session.json", read_json(layout.state_path(session_id)))
384
+ write_index(layout)
385
+ registry_touch(ctx, root, NAME, session_id)
386
+ return output
387
+
388
+
389
+ def run_previous_notify(previous: list[str], payload_text: str) -> None:
390
+ """Hand the notify payload on to the command that was configured before backfill (best effort, detached)."""
391
+ import subprocess
392
+
393
+ try:
394
+ subprocess.Popen([*previous, payload_text], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
395
+ except OSError:
396
+ pass
397
+
398
+
399
+ # --- config.toml / hooks.json ----------------------------------------------------------------------------------
400
+
401
+
402
+ def discover_homes(ctx: Context, *, extra: Iterable[Path] = (), jetbrains: bool = True) -> list[Path]:
403
+ homes = [ctx.codex_home, *extra]
404
+ if jetbrains:
405
+ env = ctx.env
406
+ roots: list[Path] = []
407
+ if os.name == "nt":
408
+ roots += [Path(env[k]) / "JetBrains" for k in ("LOCALAPPDATA", "APPDATA") if env.get(k)]
409
+ elif os.uname().sysname == "Darwin":
410
+ roots.append(ctx.home / "Library" / "Caches" / "JetBrains")
411
+ else:
412
+ roots.append(ctx.home / ".cache" / "JetBrains")
413
+ for base in roots:
414
+ if base.is_dir():
415
+ homes += [p for p in sorted(base.glob("*/aia/codex")) if p.is_dir()]
416
+ unique: list[Path] = []
417
+ for home in homes:
418
+ resolved = home.expanduser().resolve()
419
+ if not any(same_path(resolved, other) for other in unique):
420
+ unique.append(resolved)
421
+ return unique
422
+
423
+
424
+ def notify_command(ctx: Context, python_exe: str, previous: list[str] | None = None) -> list[str]:
425
+ command = [python_exe, str(ctx.launcher), "notify"]
426
+ if previous:
427
+ command += ["--previous-notify", json.dumps(previous, separators=(",", ":"))]
428
+ return command
429
+
430
+
431
+ def _base_name(part: str) -> str:
432
+ """File name of a path written with either separator (a Windows config can be read on any OS)."""
433
+ return re.split(r"[\\/]", part)[-1]
434
+
435
+
436
+ def is_backfill_notify(command: list[str]) -> bool:
437
+ return "notify" in command and any(_base_name(part) == "run.py" for part in command)
438
+
439
+
440
+ def is_legacy_notify(command: list[str]) -> bool:
441
+ return bool({_base_name(part).lower() for part in command} & LEGACY_NOTIFY_NAMES)
442
+
443
+
444
+ def parse_previous(command: list[str]) -> list[str] | None:
445
+ if "--previous-notify" not in command:
446
+ return None
447
+ index = command.index("--previous-notify")
448
+ try:
449
+ value = json.loads(command[index + 1])
450
+ except (IndexError, ValueError):
451
+ return None
452
+ return value if isinstance(value, list) and all(isinstance(v, str) for v in value) else None
453
+
454
+
455
+ def chain_links(command: list[str]) -> list[list[str]]:
456
+ """``[outer, inner, ...]``: a notify command and the commands nested through ``--previous-notify``.
457
+
458
+ Codex's own Computer Use plugin writes ``[exe, "turn-ended", "--previous-notify", "<json>"]``, so loggers sit
459
+ *inside* a wrapper they must keep.
460
+ """
461
+ links, current = [], command
462
+ while len(links) < 8:
463
+ links.append(current)
464
+ nested = parse_previous(current)
465
+ if nested is None:
466
+ break
467
+ current = nested
468
+ return links
469
+
470
+
471
+ def with_previous(command: list[str], previous: list[str] | None) -> list[str]:
472
+ """``command`` with its ``--previous-notify`` argument set to ``previous`` (or removed when None)."""
473
+ if "--previous-notify" in command:
474
+ index = command.index("--previous-notify")
475
+ head, tail = command[:index], command[index + 2:]
476
+ else:
477
+ head, tail = list(command), []
478
+ return [*head, "--previous-notify", json.dumps(previous, separators=(",", ":")), *tail] if previous else [*head, *tail]
479
+
480
+
481
+ def rebuild_chain(links: list[list[str]]) -> list[str]:
482
+ result = links[-1]
483
+ for outer in reversed(links[:-1]):
484
+ result = with_previous(outer, result)
485
+ return result
486
+
487
+
488
+ def managed_index(links: list[list[str]]) -> int | None:
489
+ for index, link in enumerate(links):
490
+ if is_backfill_notify(link) or is_legacy_notify(link):
491
+ return index
492
+ return None
493
+
494
+
495
+ def unwrap_legacy(command: list[str]) -> list[str] | None:
496
+ """The foreign command kept behind a (backfill or old-logger) link of the chain, if any."""
497
+ links = chain_links(command)
498
+ index = managed_index(links)
499
+ return links[index + 1] if index is not None and index + 1 < len(links) else None
500
+
501
+
502
+ def parse_notify(content: str) -> tuple[list[str] | None, re.Match[str] | None]:
503
+ match = re.search(r"(?m)^notify[ \t]*=[ \t]*(\[[^\r\n]*\])[ \t]*$", content)
504
+ if not match:
505
+ return None, None
506
+ try:
507
+ parsed = tomllib.loads(f"notify = {match.group(1)}\n").get("notify")
508
+ except tomllib.TOMLDecodeError as exc:
509
+ raise ValueError(f"cannot parse the existing notify setting: {exc}") from exc
510
+ if not isinstance(parsed, list) or not all(isinstance(v, str) for v in parsed):
511
+ raise ValueError("the existing notify setting is not an array of strings")
512
+ return parsed, match
513
+
514
+
515
+ def merge_notify(content: str, ctx: Context, python_exe: str) -> tuple[str, str, list[str] | None]:
516
+ """New config.toml text, a status word, and the foreign command that is kept chained (or None)."""
517
+ existing, match = parse_notify(content)
518
+ if existing is None or match is None:
519
+ line = f"notify = {json.dumps(notify_command(ctx, python_exe))}"
520
+ return line + ("\n\n" + content.lstrip() if content.strip() else "\n"), "added", None
521
+ links = chain_links(existing)
522
+ index = managed_index(links)
523
+ if index is None: # a foreign command: keep it, chain it behind backfill
524
+ previous, status = existing, "chained-after-existing"
525
+ desired = notify_command(ctx, python_exe, previous)
526
+ else: # replace our (or an old logger's) link in place; wrappers around it stay outermost
527
+ status = "updated" if is_backfill_notify(links[index]) else "replaced-old-logger"
528
+ previous = links[index + 1] if index + 1 < len(links) else None
529
+ replacement = notify_command(ctx, python_exe, previous)
530
+ desired = rebuild_chain([*links[:index], replacement])
531
+ if existing == desired:
532
+ return content, "already-configured", previous
533
+ return content[: match.start()] + f"notify = {json.dumps(desired)}" + content[match.end():], status, previous
534
+
535
+
536
+ def lifecycle_handler(ctx: Context, python_exe: str, event: str) -> dict[str, Any]:
537
+ command = command_line([python_exe, str(ctx.launcher), "hook", NAME])
538
+ handler: dict[str, Any] = {
539
+ "type": "command", "command": command, "commandWindows": command, "timeout": 30,
540
+ "statusMessage": f"{STATUS_PREFIX}{event}",
541
+ }
542
+ if event not in {"SessionStart", "SessionEnd"}:
543
+ handler["async"] = True
544
+ return handler
545
+
546
+
547
+ def _is_managed_handler(handler: Any) -> bool:
548
+ if not isinstance(handler, dict):
549
+ return False
550
+ command = str(handler.get("commandWindows") or handler.get("command") or "").replace("/", "\\").lower()
551
+ status = str(handler.get("statusMessage") or "")
552
+ ours = status.startswith(STATUS_PREFIX) and "run.py" in command and " hook codex" in command
553
+ legacy = any(name in command for name in LEGACY_HANDLER_FILES) and (
554
+ status == "Attaching repository logger" or status.startswith("Logging Codex ")
555
+ )
556
+ return ours or legacy
557
+
558
+
559
+ def merge_lifecycle_hooks(existing: dict[str, Any], ctx: Context, python_exe: str, profile: str) -> tuple[dict[str, Any], str]:
560
+ if profile not in CODEX_PROFILES:
561
+ raise ValueError(f"unknown capture profile: {profile}")
562
+ result = json.loads(json.dumps(existing))
563
+ hooks = result.setdefault("hooks", {})
564
+ if not isinstance(hooks, dict):
565
+ raise ValueError("hooks.json: 'hooks' must be an object")
566
+ selected = set(CAPTURE_PROFILE_EVENTS[profile])
567
+ for event in sorted(SUPPORTED_EVENTS):
568
+ groups = hooks.get(event, [])
569
+ if not isinstance(groups, list):
570
+ raise ValueError(f"hooks.json: {event} must be an array")
571
+ kept = [
572
+ g for g in groups
573
+ if not (isinstance(g, dict) and isinstance(g.get("hooks"), list) and any(_is_managed_handler(h) for h in g["hooks"]))
574
+ ]
575
+ if event in selected:
576
+ group: dict[str, Any] = {"hooks": [lifecycle_handler(ctx, python_exe, event)]}
577
+ if event == "SessionStart":
578
+ group["matcher"] = "startup|resume|clear|compact"
579
+ kept.append(group)
580
+ if kept:
581
+ hooks[event] = kept
582
+ else:
583
+ hooks.pop(event, None)
584
+ if not hooks:
585
+ result.pop("hooks", None)
586
+ elif not result.get("description"):
587
+ result["description"] = MANAGED_DESCRIPTION
588
+ return result, "updated" if result != existing else "already-configured"
589
+
590
+
591
+ def strip_lifecycle_hooks(existing: dict[str, Any]) -> tuple[dict[str, Any], int]:
592
+ result = json.loads(json.dumps(existing))
593
+ hooks = result.get("hooks")
594
+ removed = 0
595
+ if isinstance(hooks, dict):
596
+ for event in list(hooks):
597
+ groups = hooks[event]
598
+ if not isinstance(groups, list):
599
+ continue
600
+ kept = [
601
+ g for g in groups
602
+ if not (isinstance(g, dict) and isinstance(g.get("hooks"), list) and any(_is_managed_handler(h) for h in g["hooks"]))
603
+ ]
604
+ removed += len(groups) - len(kept)
605
+ if kept:
606
+ hooks[event] = kept
607
+ else:
608
+ del hooks[event]
609
+ if not hooks:
610
+ result.pop("hooks", None)
611
+ if result.get("description") == MANAGED_DESCRIPTION:
612
+ result.pop("description")
613
+ return result, removed
614
+
615
+
616
+ def _load_hooks(path: Path) -> dict[str, Any]:
617
+ if not path.exists() or not path.read_bytes().strip():
618
+ return {}
619
+ try:
620
+ value = json.loads(path.read_text(encoding="utf-8"))
621
+ except (UnicodeDecodeError, ValueError) as exc:
622
+ raise ValueError(f"cannot parse {path}: {exc}") from exc
623
+ if not isinstance(value, dict):
624
+ raise ValueError(f"{path} must contain a JSON object")
625
+ return value
626
+
627
+
628
+ def install(
629
+ ctx: Context, *, python_exe: str | None = None, instructions: bool = True, profile: str = "standard",
630
+ homes: list[Path] | None = None, dry_run: bool = False,
631
+ ) -> dict[str, Any]:
632
+ python_exe = python_exe or system_python()
633
+ targets = homes or discover_homes(ctx)
634
+ report: dict[str, Any] = {"agent": NAME, "profile": profile, "homes": []}
635
+ manifest = read_json(ctx.shared_root / "install.json")
636
+ for home in targets:
637
+ config_path, hooks_path = home / "config.toml", home / "hooks.json"
638
+ content = config_path.read_text(encoding="utf-8") if config_path.exists() else ""
639
+ new_content, notify_status, previous = merge_notify(content, ctx, python_exe)
640
+ existing_hooks = _load_hooks(hooks_path)
641
+ new_hooks, hooks_status = merge_lifecycle_hooks(existing_hooks, ctx, python_exe, profile)
642
+ entry = {"home": str(home), "notify": notify_status, "lifecycle_hooks": hooks_status, "chained_command": previous}
643
+ if not dry_run:
644
+ home.mkdir(parents=True, exist_ok=True)
645
+ if new_content != content:
646
+ entry["config_backup"] = str(backup_file(config_path) or "")
647
+ write_text_atomic(config_path, new_content)
648
+ if new_hooks != existing_hooks:
649
+ entry["hooks_backup"] = str(backup_file(hooks_path) or "")
650
+ write_text_atomic(hooks_path, json.dumps(new_hooks, ensure_ascii=False, indent=2) + "\n")
651
+ if instructions:
652
+ path = instructions_path(home)
653
+ current = path.read_text(encoding="utf-8") if path.exists() else ""
654
+ updated = with_instruction_block(current)
655
+ if updated != current:
656
+ entry["instructions_backup"] = str(backup_file(path) or "")
657
+ write_text_atomic(path, updated)
658
+ report["homes"].append(entry)
659
+ if not dry_run:
660
+ manifest["codex"] = {"homes": [str(h) for h in targets], "profile": profile, "installed_at": iso_utc_now()}
661
+ write_json(ctx.shared_root / "install.json", {**manifest, "version": __version__, "python": python_exe})
662
+ return report
663
+
664
+
665
+ def uninstall(ctx: Context) -> dict[str, Any]:
666
+ """Remove the notify entry (restoring any chained command), lifecycle hooks and the instruction block from every home."""
667
+ recorded = [Path(p) for p in (read_json(ctx.shared_root / "install.json").get("codex") or {}).get("homes", [])]
668
+ report: dict[str, Any] = {"agent": NAME, "homes": []}
669
+ for home in discover_homes(ctx, extra=recorded):
670
+ entry: dict[str, Any] = {"home": str(home), "notify_removed": False, "hooks_removed": 0, "instructions_removed": False}
671
+ config_path = home / "config.toml"
672
+ if config_path.exists():
673
+ content = config_path.read_text(encoding="utf-8")
674
+ existing, match = parse_notify(content)
675
+ links = chain_links(existing) if existing is not None else []
676
+ index = next((i for i, link in enumerate(links) if is_backfill_notify(link)), None)
677
+ if existing is not None and match is not None and index is not None:
678
+ kept = links[index + 1] if index + 1 < len(links) else None
679
+ restored = kept # wrappers around our link lose their --previous-notify (or get what we had chained)
680
+ for outer in reversed(links[:index]):
681
+ restored = with_previous(outer, restored)
682
+ replacement = f"notify = {json.dumps(restored)}" if restored else ""
683
+ new = content[: match.start()] + replacement + content[match.end():]
684
+ backup_file(config_path)
685
+ write_text_atomic(config_path, new.lstrip("\n") if not restored else new)
686
+ entry["notify_removed"] = True
687
+ hooks_path = home / "hooks.json"
688
+ if hooks_path.exists():
689
+ existing_hooks = _load_hooks(hooks_path)
690
+ stripped, removed = strip_lifecycle_hooks(existing_hooks)
691
+ if removed:
692
+ backup_file(hooks_path)
693
+ write_text_atomic(hooks_path, json.dumps(stripped, ensure_ascii=False, indent=2) + "\n")
694
+ entry["hooks_removed"] = removed
695
+ path = instructions_path(home)
696
+ if path.exists():
697
+ text = path.read_text(encoding="utf-8")
698
+ cleaned = without_instruction_block(text)
699
+ if cleaned != text:
700
+ backup_file(path)
701
+ write_text_atomic(path, cleaned)
702
+ entry["instructions_removed"] = True
703
+ report["homes"].append(entry)
704
+ return report
705
+
706
+
707
+ def installation(ctx: Context) -> dict[str, Any]:
708
+ homes = []
709
+ for home in discover_homes(ctx):
710
+ info: dict[str, Any] = {"home": str(home), "exists": home.is_dir(), "notify": "missing", "hooks_registered": [], "error": None}
711
+ try:
712
+ config_path = home / "config.toml"
713
+ existing, _ = parse_notify(config_path.read_text(encoding="utf-8")) if config_path.exists() else (None, None)
714
+ if existing is not None:
715
+ links = chain_links(existing)
716
+ ours = next((link for link in links if is_backfill_notify(link)), None)
717
+ info["notify"] = "backfill" if ours else ("old-logger" if any(is_legacy_notify(link) for link in links) else "other")
718
+ info["chained_command"] = parse_previous(ours) if ours else None
719
+ hooks = _load_hooks(home / "hooks.json").get("hooks", {})
720
+ if isinstance(hooks, dict):
721
+ info["hooks_registered"] = [
722
+ e for e in CAPTURE_PROFILE_EVENTS["full"]
723
+ if isinstance(hooks.get(e), list)
724
+ and any(isinstance(g, dict) and any(_is_managed_handler(h) for h in g.get("hooks", [])) for g in hooks[e])
725
+ ]
726
+ path = instructions_path(home)
727
+ info["instructions_present"] = path.exists() and INSTRUCTION_START in path.read_text(encoding="utf-8")
728
+ except (OSError, ValueError) as exc:
729
+ info["error"] = str(exc)
730
+ homes.append(info)
731
+ return {"agent": NAME, "homes": homes}
732
+
733
+
734
+ # --- existing history ------------------------------------------------------------------------------------------
735
+
736
+
737
+ def backfill(root: Path, ctx: Context, rollouts: list[tuple[Path, str, str]] | None = None) -> dict[str, Any]:
738
+ """Save the existing Codex sessions of ``root`` into its log folder."""
739
+ config = load_config(ctx, root)
740
+ layout = Layout(root, NAME, config)
741
+ redactor = redactor_for(config)
742
+ items = rollouts if rollouts is not None else rollouts_for(root, ctx)
743
+ summary: dict[str, Any] = {"agent": NAME, "root": str(root), "log_dir": str(layout.log_dir), "sessions": []}
744
+ if not items:
745
+ summary["note"] = "no Codex history found for this project"
746
+ return summary
747
+ layout.ensure()
748
+ for path, session_id, cwd in items:
749
+ previous_turns = int(read_json(layout.state_path(session_id)).get("turn_count") or 0)
750
+ state, entries = ingest_session(
751
+ layout, ADAPTER, ctx, config, redactor, session_id, path, full=True, cwd=cwd,
752
+ extra_state={"backfilled": True, "turn_count": previous_turns},
753
+ )
754
+ stats = ADAPTER.summarize(entries)
755
+ if not previous_turns: # Codex notifies per turn; a backfilled session has no live count, so use its prompts
756
+ state["turn_count"] = stats["user_message_count"]
757
+ write_json(layout.state_path(session_id), state)
758
+ append_jsonl(
759
+ layout.daily("sessions"),
760
+ {
761
+ "timestamp_utc": iso_utc_now(), "event_type": "backfill", "agent": NAME, "session_id": session_id,
762
+ "transcript_bytes": state.get("processed_bytes"), "user_message_count": stats["user_message_count"],
763
+ "assistant_message_count": stats["assistant_message_count"], "tools_used": stats["tools_used"],
764
+ },
765
+ )
766
+ summary["sessions"].append({"session_id": session_id, "user_messages": stats["user_message_count"]})
767
+ write_index(layout)
768
+ registry_touch(ctx, root, NAME)
769
+ return summary
770
+
771
+
772
+ def backfill_all(ctx: Context) -> dict[str, Any]:
773
+ grouped: dict[Path, list[tuple[Path, str, str]]] = {}
774
+ skipped: list[dict[str, str]] = []
775
+ for item in scan_rollouts(ctx):
776
+ cwd = item[2]
777
+ if not Path(cwd).is_dir():
778
+ skipped.append({"source": str(item[0]), "reason": "working directory missing"})
779
+ continue
780
+ root = find_root(cwd, ctx.env, ctx.home)
781
+ reason = skip_reason(root, ctx, NAME) if root else "no project root"
782
+ if root is None or reason:
783
+ skipped.append({"source": str(item[0]), "reason": reason})
784
+ continue
785
+ grouped.setdefault(root, []).append(item)
786
+ return {"projects": [backfill(root, ctx, items) for root, items in grouped.items()], "skipped": skipped}