ghostkeep 0.7.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.
- ghostkeep/__init__.py +2 -0
- ghostkeep/__main__.py +3 -0
- ghostkeep/check.py +207 -0
- ghostkeep/cli.py +345 -0
- ghostkeep/decisions.py +49 -0
- ghostkeep/gitio.py +129 -0
- ghostkeep/handoff.py +173 -0
- ghostkeep/health.py +170 -0
- ghostkeep/ledger.py +196 -0
- ghostkeep/setup.py +253 -0
- ghostkeep/sources.py +543 -0
- ghostkeep/state.py +287 -0
- ghostkeep/sync.py +69 -0
- ghostkeep/verify.py +146 -0
- ghostkeep-0.7.0.dist-info/METADATA +222 -0
- ghostkeep-0.7.0.dist-info/RECORD +19 -0
- ghostkeep-0.7.0.dist-info/WHEEL +4 -0
- ghostkeep-0.7.0.dist-info/entry_points.txt +2 -0
- ghostkeep-0.7.0.dist-info/licenses/LICENSE +21 -0
ghostkeep/sources.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
"""Read the session logs that AI tools already keep on disk. No agent cooperation needed.
|
|
2
|
+
|
|
3
|
+
Formats were mapped from real files on Windows (10 Nov 2026):
|
|
4
|
+
- Claude Code: ~/.claude/projects/<repo-path-slug>/<session>.jsonl
|
|
5
|
+
- Antigravity: ~/.gemini/antigravity/brain/<id>/.system_generated/logs/transcript.jsonl (IDE agent)
|
|
6
|
+
~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript.jsonl (CLI)
|
|
7
|
+
These are internal formats and can change in any update, so every reader is defensive.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import difflib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path, PureWindowsPath, PurePosixPath
|
|
18
|
+
|
|
19
|
+
MAX_TEXT = 500
|
|
20
|
+
|
|
21
|
+
# --- small helpers -----------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
_SECRET_RES = [
|
|
24
|
+
re.compile(r"\b(sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}"
|
|
25
|
+
r"|AIza[0-9A-Za-z_-]{30,}|xox[abpr]-[A-Za-z0-9-]{10,}|gsk_[A-Za-z0-9]{20,})"),
|
|
26
|
+
re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+"),
|
|
27
|
+
]
|
|
28
|
+
# Long opaque tokens are probably secrets, but pure hex of git/sha256 length is a commit or hash
|
|
29
|
+
# the next agent needs, so those are kept.
|
|
30
|
+
_LONG_TOKEN = re.compile(r"\b[A-Za-z0-9+_-]{40,}={0,2}\b")
|
|
31
|
+
_HASH = re.compile(r"[0-9a-fA-F]{40}|[0-9a-fA-F]{64}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def redact(text: str) -> str:
|
|
35
|
+
for rx in _SECRET_RES:
|
|
36
|
+
text = rx.sub("[redacted]", text)
|
|
37
|
+
return _LONG_TOKEN.sub(lambda m: m.group(0) if _HASH.fullmatch(m.group(0)) else "[redacted]", text)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def clip(text: str, n: int = MAX_TEXT) -> str:
|
|
41
|
+
text = redact(" ".join(text.split()))
|
|
42
|
+
return text if len(text) <= n else text[: n - 1] + "…"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def line_delta(old: str, new: str) -> tuple[int, int]:
|
|
46
|
+
"""(added, removed) lines when `old` is replaced by `new`, like git counts them."""
|
|
47
|
+
a, b = old.splitlines(), new.splitlines()
|
|
48
|
+
added = removed = 0
|
|
49
|
+
for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes():
|
|
50
|
+
if tag in ("replace", "delete"):
|
|
51
|
+
removed += i2 - i1
|
|
52
|
+
if tag in ("replace", "insert"):
|
|
53
|
+
added += j2 - j1
|
|
54
|
+
return added, removed
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def to_local(ts: str | None) -> str | None:
|
|
58
|
+
"""'2026-11-10T15:56:00.123Z' -> local ISO with offset, so ledger times sort and read consistently."""
|
|
59
|
+
if not ts:
|
|
60
|
+
return ts
|
|
61
|
+
from datetime import datetime
|
|
62
|
+
try:
|
|
63
|
+
return datetime.fromisoformat(ts.replace("Z", "+00:00")).astimezone().isoformat(timespec="seconds")
|
|
64
|
+
except ValueError:
|
|
65
|
+
return ts
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def count_lines(text: str) -> int:
|
|
69
|
+
return len(text.splitlines())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def relpath(path: str, root: Path) -> str | None:
|
|
73
|
+
"""Repo-relative POSIX path, or None if `path` is outside `root`."""
|
|
74
|
+
if not path:
|
|
75
|
+
return None
|
|
76
|
+
p = path.strip().strip('"')
|
|
77
|
+
win = PureWindowsPath(p)
|
|
78
|
+
if win.drive or p.startswith("\\"):
|
|
79
|
+
parts, rparts = win.parts, PureWindowsPath(str(root)).parts
|
|
80
|
+
if not PureWindowsPath(str(root)).drive: # root is posix (tests on linux)
|
|
81
|
+
return None
|
|
82
|
+
lower = [x.lower() for x in parts]
|
|
83
|
+
rlower = [x.lower() for x in rparts]
|
|
84
|
+
if lower[: len(rlower)] != rlower:
|
|
85
|
+
return None
|
|
86
|
+
return "/".join(parts[len(rparts):]) or None
|
|
87
|
+
pp = PurePosixPath(p.replace("\\", "/"))
|
|
88
|
+
if pp.is_absolute():
|
|
89
|
+
try:
|
|
90
|
+
return pp.relative_to(PurePosixPath(str(root).replace("\\", "/"))).as_posix()
|
|
91
|
+
except ValueError:
|
|
92
|
+
return None
|
|
93
|
+
return pp.as_posix() # already relative to the repo
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# --- the common session shape --------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Edit:
|
|
100
|
+
path: str
|
|
101
|
+
added: int | None
|
|
102
|
+
removed: int | None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class Session:
|
|
107
|
+
tool: str
|
|
108
|
+
session: str
|
|
109
|
+
source: str
|
|
110
|
+
rev: str
|
|
111
|
+
started: str | None = None
|
|
112
|
+
ended: str | None = None
|
|
113
|
+
model: str | None = None
|
|
114
|
+
prompts: list[tuple[str | None, str]] = field(default_factory=list)
|
|
115
|
+
final: str | None = None
|
|
116
|
+
edits: list[Edit] = field(default_factory=list)
|
|
117
|
+
interrupted: bool = False
|
|
118
|
+
status_note: str | None = None
|
|
119
|
+
touches_root: bool = False
|
|
120
|
+
base: str | None = None # Codex records the exact base commit; others leave it None
|
|
121
|
+
|
|
122
|
+
def files(self) -> list[tuple[str, int | None, int | None]]:
|
|
123
|
+
"""One entry per file. Counts only when the session made exactly one edit to it."""
|
|
124
|
+
by: dict[str, list[Edit]] = {}
|
|
125
|
+
for e in self.edits:
|
|
126
|
+
by.setdefault(e.path, []).append(e)
|
|
127
|
+
out = []
|
|
128
|
+
for path, es in by.items():
|
|
129
|
+
if (es[-1].added, es[-1].removed) == DELETED:
|
|
130
|
+
out.append((path, *DELETED)) # whatever happened before, the file ends up deleted
|
|
131
|
+
elif len(es) == 1:
|
|
132
|
+
out.append((path, es[0].added, es[0].removed))
|
|
133
|
+
else:
|
|
134
|
+
out.append((path, None, None))
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# --- Claude Code ---------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
def claude_dir() -> Path:
|
|
141
|
+
return Path(os.environ.get("GHOSTKEEP_CLAUDE_DIR", Path.home() / ".claude" / "projects"))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def claude_slug(root: Path) -> str:
|
|
145
|
+
return re.sub(r"[^A-Za-z0-9]", "-", str(root))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _claude_text(content) -> str:
|
|
149
|
+
if isinstance(content, str):
|
|
150
|
+
return content
|
|
151
|
+
if isinstance(content, list):
|
|
152
|
+
return "\n".join(x.get("text", "") for x in content
|
|
153
|
+
if isinstance(x, dict) and x.get("type") == "text")
|
|
154
|
+
return ""
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def read_claude(path: Path, root: Path) -> Session:
|
|
158
|
+
st = path.stat()
|
|
159
|
+
s = Session("claude-code", path.stem, str(path), f"{st.st_size}:{int(st.st_mtime)}")
|
|
160
|
+
s.touches_root = True # Claude keeps one folder per project, found by its path slug
|
|
161
|
+
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
162
|
+
try:
|
|
163
|
+
o = json.loads(line)
|
|
164
|
+
except json.JSONDecodeError:
|
|
165
|
+
continue
|
|
166
|
+
if not isinstance(o, dict):
|
|
167
|
+
continue # 'null', numbers, arrays: not an event
|
|
168
|
+
t, ts = o.get("type"), o.get("timestamp")
|
|
169
|
+
if t not in ("user", "assistant"):
|
|
170
|
+
continue
|
|
171
|
+
if ts:
|
|
172
|
+
s.started = s.started or ts
|
|
173
|
+
s.ended = ts
|
|
174
|
+
msg = o.get("message") if isinstance(o.get("message"), dict) else {}
|
|
175
|
+
if t == "user":
|
|
176
|
+
if o.get("toolUseResult") is not None:
|
|
177
|
+
continue
|
|
178
|
+
text = _claude_text(msg.get("content")).strip()
|
|
179
|
+
if o.get("interruptedMessageId") or text.startswith("[Request interrupted"):
|
|
180
|
+
s.interrupted = True
|
|
181
|
+
continue
|
|
182
|
+
human = (o.get("origin") or {}).get("kind") == "human" or isinstance(msg.get("content"), str)
|
|
183
|
+
if text and human and not text.startswith("<"):
|
|
184
|
+
s.prompts.append((ts, text))
|
|
185
|
+
s.interrupted = False # a new prompt after an interruption resumes the work
|
|
186
|
+
else:
|
|
187
|
+
s.model = msg.get("model") or s.model
|
|
188
|
+
for item in msg.get("content") or []:
|
|
189
|
+
if not isinstance(item, dict):
|
|
190
|
+
continue
|
|
191
|
+
if item.get("type") == "text" and item.get("text", "").strip():
|
|
192
|
+
s.final = item["text"]
|
|
193
|
+
if item.get("type") != "tool_use":
|
|
194
|
+
continue
|
|
195
|
+
name, inp = item.get("name"), item.get("input") or {}
|
|
196
|
+
if name == "Bash" and isinstance(inp.get("command"), str):
|
|
197
|
+
found = shell_edits(inp["command"], root) # rm, > redirects, Set-Content ...
|
|
198
|
+
if found:
|
|
199
|
+
s.touches_root = True
|
|
200
|
+
s.edits += found
|
|
201
|
+
continue
|
|
202
|
+
rel = relpath(inp.get("file_path") or inp.get("notebook_path") or "", root)
|
|
203
|
+
if not rel:
|
|
204
|
+
continue
|
|
205
|
+
s.touches_root = True
|
|
206
|
+
if name == "Edit":
|
|
207
|
+
a, r = line_delta(inp.get("old_string", ""), inp.get("new_string", ""))
|
|
208
|
+
s.edits.append(Edit(rel, a, r))
|
|
209
|
+
elif name == "MultiEdit":
|
|
210
|
+
s.edits.append(Edit(rel, None, None))
|
|
211
|
+
elif name == "Write":
|
|
212
|
+
s.edits.append(Edit(rel, None, None)) # can't tell new vs overwrite from the call
|
|
213
|
+
elif name == "NotebookEdit":
|
|
214
|
+
s.edits.append(Edit(rel, None, None))
|
|
215
|
+
return s
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def claude_sessions(root: Path, since: float) -> list[Session]:
|
|
219
|
+
try:
|
|
220
|
+
d = claude_dir() / claude_slug(root)
|
|
221
|
+
if not d.is_dir():
|
|
222
|
+
return []
|
|
223
|
+
out = []
|
|
224
|
+
for p in sorted(d.glob("*.jsonl")):
|
|
225
|
+
try:
|
|
226
|
+
if p.stat().st_mtime >= since:
|
|
227
|
+
out.append(read_claude(p, root))
|
|
228
|
+
except OSError:
|
|
229
|
+
continue
|
|
230
|
+
return out
|
|
231
|
+
except OSError:
|
|
232
|
+
return []
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# --- Antigravity (IDE agent and CLI share one format) ----------------------------------
|
|
236
|
+
|
|
237
|
+
def antigravity_dirs() -> list[tuple[str, Path]]:
|
|
238
|
+
env = os.environ.get("GHOSTKEEP_ANTIGRAVITY_DIRS")
|
|
239
|
+
if env: # "tool=path;tool=path"
|
|
240
|
+
return [(t, Path(p)) for t, p in (x.split("=", 1) for x in env.split(";") if "=" in x)]
|
|
241
|
+
g = Path.home() / ".gemini"
|
|
242
|
+
return [("antigravity-ide", g / "antigravity" / "brain"),
|
|
243
|
+
("antigravity-ide", g / "antigravity-ide" / "brain"),
|
|
244
|
+
("antigravity-cli", g / "antigravity-cli" / "brain")]
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
_REQ = re.compile(r"<USER_REQUEST>\s*(.*?)\s*</USER_REQUEST>", re.S)
|
|
248
|
+
_PATH_KEYS = ("Path", "TargetFile", "AbsolutePath", "FilePath", "file_path", "path")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _ag_arg(value) -> str:
|
|
252
|
+
"""Antigravity CLI stores each tool argument as a JSON-encoded string ('"a\\nb"'), the IDE as plain
|
|
253
|
+
text. Decode the first kind, or every multi-line edit reads as one line (seen on real data, 13 Nov)."""
|
|
254
|
+
v = str(value)
|
|
255
|
+
if len(v) >= 2 and v[0] == '"' and v[-1] == '"':
|
|
256
|
+
try:
|
|
257
|
+
out = json.loads(v)
|
|
258
|
+
if isinstance(out, str):
|
|
259
|
+
return out
|
|
260
|
+
except json.JSONDecodeError:
|
|
261
|
+
pass
|
|
262
|
+
return v
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# The edit tool's own result line: "Made 1 replacement in E:\\x\\a.py starting at line 1 (+36/-19 lines)."
|
|
266
|
+
_AG_RESULT = re.compile(r"Made \d+ replacements? in (.+?) starting at line \d+ \(\+(\d+)/-(\d+) lines\)")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _ag_request(content: str) -> str:
|
|
270
|
+
m = _REQ.search(content or "")
|
|
271
|
+
return (m.group(1) if m else content or "").strip()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def read_antigravity(path: Path, tool: str, root: Path) -> Session:
|
|
275
|
+
st = path.stat()
|
|
276
|
+
sid = path.parents[2].name # brain/<id>/.system_generated/logs/transcript.jsonl
|
|
277
|
+
s = Session(tool, sid, str(path), f"{st.st_size}:{int(st.st_mtime)}")
|
|
278
|
+
last_status = None
|
|
279
|
+
pending: list[Edit] = [] # edits from the last tool call, waiting for the tool's own result line
|
|
280
|
+
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
281
|
+
try:
|
|
282
|
+
o = json.loads(line)
|
|
283
|
+
except json.JSONDecodeError:
|
|
284
|
+
continue
|
|
285
|
+
if not isinstance(o, dict):
|
|
286
|
+
continue # 'null', numbers, arrays: not an event
|
|
287
|
+
t, ts = o.get("type"), o.get("created_at")
|
|
288
|
+
if ts:
|
|
289
|
+
s.started = s.started or ts
|
|
290
|
+
s.ended = ts
|
|
291
|
+
last_status = o.get("status") or last_status
|
|
292
|
+
if t == "USER_INPUT":
|
|
293
|
+
text = _ag_request(o.get("content", ""))
|
|
294
|
+
if text:
|
|
295
|
+
s.prompts.append((ts, text))
|
|
296
|
+
if str(root).lower() in (o.get("content") or "").lower():
|
|
297
|
+
s.touches_root = True
|
|
298
|
+
elif t == "GENERIC" and pending:
|
|
299
|
+
# The tool reports exact counts even when the logged arguments were cut short.
|
|
300
|
+
m = _AG_RESULT.search(o.get("content") or "")
|
|
301
|
+
if m:
|
|
302
|
+
rel = relpath(m.group(1).replace("\\\\", "\\"), root)
|
|
303
|
+
for e in pending:
|
|
304
|
+
if e.path == rel:
|
|
305
|
+
e.added, e.removed = int(m.group(2)), int(m.group(3))
|
|
306
|
+
pending = []
|
|
307
|
+
elif t == "PLANNER_RESPONSE":
|
|
308
|
+
if (o.get("content") or "").strip() and not o.get("tool_calls"):
|
|
309
|
+
s.final = o["content"]
|
|
310
|
+
pending = []
|
|
311
|
+
truncated = set(o.get("truncated_fields") or [])
|
|
312
|
+
if "tool_calls" in truncated: # real data: whole tool_calls cut at 2,048 chars
|
|
313
|
+
truncated |= {"Target", "Replacement", "Content"}
|
|
314
|
+
for tc in o.get("tool_calls") or []:
|
|
315
|
+
name = (tc.get("name") or "").lower()
|
|
316
|
+
args = {k: _ag_arg(v) for k, v in (tc.get("args") or {}).items()} \
|
|
317
|
+
if isinstance(tc.get("args"), dict) else {}
|
|
318
|
+
if not any(k in name for k in ("edit", "write", "replace", "create_file")):
|
|
319
|
+
continue
|
|
320
|
+
raw = next((args[k] for k in _PATH_KEYS if args.get(k)), "")
|
|
321
|
+
rel = relpath(str(raw), root)
|
|
322
|
+
if not rel:
|
|
323
|
+
continue
|
|
324
|
+
s.touches_root = True
|
|
325
|
+
if "Target" in args and "Replacement" in args and not truncated & {"Target", "Replacement"}:
|
|
326
|
+
a, r = line_delta(str(args["Target"]), str(args["Replacement"]))
|
|
327
|
+
s.edits.append(Edit(rel, a, r))
|
|
328
|
+
pending.append(s.edits[-1])
|
|
329
|
+
elif "Content" in args and "Content" not in truncated and str(args.get("Overwrite", "")).lower() != "true":
|
|
330
|
+
s.edits.append(Edit(rel, count_lines(str(args["Content"])), 0))
|
|
331
|
+
pending.append(s.edits[-1])
|
|
332
|
+
else:
|
|
333
|
+
s.edits.append(Edit(rel, None, None))
|
|
334
|
+
pending.append(s.edits[-1])
|
|
335
|
+
if last_status and last_status != "DONE":
|
|
336
|
+
s.interrupted = True
|
|
337
|
+
s.status_note = f"last step status {last_status}"
|
|
338
|
+
return s
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def antigravity_sessions(root: Path, since: float) -> list[Session]:
|
|
342
|
+
out, needle = [], root.name.lower()
|
|
343
|
+
for tool, base in antigravity_dirs():
|
|
344
|
+
try:
|
|
345
|
+
if not base.is_dir():
|
|
346
|
+
continue
|
|
347
|
+
for p in base.glob("*/.system_generated/logs/transcript.jsonl"):
|
|
348
|
+
try:
|
|
349
|
+
if p.stat().st_mtime < since:
|
|
350
|
+
continue
|
|
351
|
+
if needle not in p.read_text(encoding="utf-8", errors="replace").lower():
|
|
352
|
+
continue # cheap prefilter
|
|
353
|
+
s = read_antigravity(p, tool, root)
|
|
354
|
+
except OSError:
|
|
355
|
+
continue
|
|
356
|
+
if s.touches_root:
|
|
357
|
+
out.append(s)
|
|
358
|
+
except OSError:
|
|
359
|
+
continue
|
|
360
|
+
return out
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
# --- Codex CLI -----------------------------------------------------------------------
|
|
364
|
+
# ~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl (newest) or .jsonl.zst (older).
|
|
365
|
+
# session_meta carries cwd + git.commit_hash (the base commit, no git call needed).
|
|
366
|
+
# Codex edits via shell (exec_command {"cmd": "..."}), so files are sniffed from the
|
|
367
|
+
# command and line counts are usually unknown — the checker verifies changed-vs-git anyway.
|
|
368
|
+
|
|
369
|
+
def codex_dir() -> Path:
|
|
370
|
+
return Path(os.environ.get("GHOSTKEEP_CODEX_DIR", Path.home() / ".codex" / "sessions"))
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# apply_patch headers, and common PowerShell/shell writes to a path.
|
|
374
|
+
_CODEX_PATCH = re.compile(r"\*\*\*\s+(?:Update|Add|Delete)\s+File:\s+(.+)")
|
|
375
|
+
# Writers that name their target explicitly: safe to read from the raw command.
|
|
376
|
+
_CODEX_PATH_WRITES = [
|
|
377
|
+
re.compile(r"(?:Set-Content|Out-File|Add-Content)\b[^\n|]*?-(?:Path|FilePath)\s+(?P<p>\"[^\"]+\"|'[^']+'|\S+)", re.I),
|
|
378
|
+
]
|
|
379
|
+
# Writers found by syntax ('>' redirects, tee, sed -i). Only matched AFTER quoted strings are blanked,
|
|
380
|
+
# so text like rg "x > y.txt" or print(a > '3.10') is not mistaken for a write.
|
|
381
|
+
_CODEX_SYNTAX_WRITES = [
|
|
382
|
+
re.compile(r"\b(?:tee(?:\s+-a)?|sed\s+-i\S*(?:\s+\S+)?|dd\s+of=)\s+(?P<p>[^\s;|&]+)"),
|
|
383
|
+
re.compile(r"(?<![>\d&-])>>?\s*(?P<p>[^\s;|&]+)"),
|
|
384
|
+
]
|
|
385
|
+
_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'[^']*'")
|
|
386
|
+
# Deletes: rm / del / Remove-Item / git rm, then the paths until the next ; | & or newline.
|
|
387
|
+
_SHELL_DELETE = re.compile(r"(?:^|[;&|]\s*|\n\s*)(?:git\s+rm|rm|del|erase|unlink|Remove-Item)\b(?P<args>[^;&|\n]*)", re.I)
|
|
388
|
+
DELETED = (0, None) # marker counts for a file the session deleted: "+0 -?" means gone
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _shell_deletes(cmd: str, root: Path) -> list[Edit]:
|
|
392
|
+
out: list[Edit] = []
|
|
393
|
+
for m in _SHELL_DELETE.finditer(cmd):
|
|
394
|
+
for tok in re.findall(r"\"[^\"]+\"|'[^']+'|\S+", m.group("args")):
|
|
395
|
+
if tok.startswith("-"):
|
|
396
|
+
continue # flags: -f, -r, -Force, --cached
|
|
397
|
+
rel = relpath(tok.strip("\"'"), root)
|
|
398
|
+
if rel and "." in Path(rel).name and "*" not in rel:
|
|
399
|
+
out.append(Edit(rel, *DELETED))
|
|
400
|
+
return out
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def shell_edits(cmd: str, root: Path) -> list[Edit]:
|
|
404
|
+
"""Files a shell command writes or deletes (counts unknown for writes)."""
|
|
405
|
+
dels = _shell_deletes(cmd, root)
|
|
406
|
+
gone = {e.path for e in dels}
|
|
407
|
+
return [e for e in _codex_edits_from_cmd(cmd, root) if e.path not in gone] + dels
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _codex_edits_from_cmd(cmd: str, root: Path) -> list[Edit]:
|
|
411
|
+
edits: list[Edit] = []
|
|
412
|
+
# apply_patch: count +/- lines per file section.
|
|
413
|
+
if "apply_patch" in cmd:
|
|
414
|
+
cur, add, rem = None, 0, 0
|
|
415
|
+
for ln in cmd.splitlines():
|
|
416
|
+
m = _CODEX_PATCH.match(ln.strip())
|
|
417
|
+
if m:
|
|
418
|
+
if cur:
|
|
419
|
+
edits.append(Edit(cur, add, rem))
|
|
420
|
+
cur, add, rem = relpath(m.group(1).strip(), root), 0, 0
|
|
421
|
+
elif cur and ln[:1] == "+" and not ln.startswith("+++"):
|
|
422
|
+
add += 1
|
|
423
|
+
elif cur and ln[:1] == "-" and not ln.startswith("---"):
|
|
424
|
+
rem += 1
|
|
425
|
+
if cur:
|
|
426
|
+
edits.append(Edit(cur, add, rem))
|
|
427
|
+
if edits:
|
|
428
|
+
return [e for e in edits if e.path]
|
|
429
|
+
# shell writes: path known, counts unknown.
|
|
430
|
+
blanked = _QUOTED.sub('""', cmd)
|
|
431
|
+
found: list[str] = []
|
|
432
|
+
for rx, text in [(r, cmd) for r in _CODEX_PATH_WRITES] + [(r, blanked) for r in _CODEX_SYNTAX_WRITES]:
|
|
433
|
+
for m in rx.finditer(text):
|
|
434
|
+
rel = relpath(m.group("p").strip("\"'"), root)
|
|
435
|
+
if rel and "." in Path(rel).name and rel not in found: # a file, not /dev/null or a bare word
|
|
436
|
+
found.append(rel)
|
|
437
|
+
return [Edit(rel, None, None) for rel in found]
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _codex_text(content) -> str:
|
|
441
|
+
if isinstance(content, list):
|
|
442
|
+
return "\n".join(x.get("text", "") for x in content
|
|
443
|
+
if isinstance(x, dict) and x.get("type") in ("input_text", "output_text", "text"))
|
|
444
|
+
return content if isinstance(content, str) else ""
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _read_zst(path: Path) -> list[str]:
|
|
448
|
+
try:
|
|
449
|
+
import zstandard
|
|
450
|
+
except ImportError:
|
|
451
|
+
return [] # can't read compressed sessions without the optional dep
|
|
452
|
+
data = zstandard.ZstdDecompressor().decompress(path.read_bytes(), max_output_size=80_000_000)
|
|
453
|
+
return data.decode("utf-8", "replace").splitlines()
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def read_codex(path: Path, root: Path) -> Session | None:
|
|
457
|
+
st = path.stat()
|
|
458
|
+
lines = _read_zst(path) if path.suffix == ".zst" else \
|
|
459
|
+
path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
460
|
+
if not lines:
|
|
461
|
+
return None
|
|
462
|
+
s = Session("codex", path.name, str(path), f"{st.st_size}:{int(st.st_mtime)}")
|
|
463
|
+
had_task = done_task = cwd_match = False
|
|
464
|
+
for line in lines:
|
|
465
|
+
try:
|
|
466
|
+
o = json.loads(line)
|
|
467
|
+
except json.JSONDecodeError:
|
|
468
|
+
continue
|
|
469
|
+
if not isinstance(o, dict):
|
|
470
|
+
continue # 'null', numbers, arrays: not an event
|
|
471
|
+
p = o.get("payload") if isinstance(o.get("payload"), dict) else {}
|
|
472
|
+
ts = o.get("timestamp")
|
|
473
|
+
if ts:
|
|
474
|
+
s.started = s.started or ts
|
|
475
|
+
s.ended = ts
|
|
476
|
+
if o.get("type") == "session_meta":
|
|
477
|
+
cwd = p.get("cwd", "")
|
|
478
|
+
cwd_match = cwd == str(root) or relpath(cwd, root) in ("", ".")
|
|
479
|
+
if cwd_match:
|
|
480
|
+
s.touches_root = True
|
|
481
|
+
s.base = (p.get("git") or {}).get("commit_hash") or s.base
|
|
482
|
+
s.model = p.get("model") or s.model
|
|
483
|
+
elif p.get("type") == "message" and p.get("role") == "user":
|
|
484
|
+
text = _codex_text(p.get("content")).strip()
|
|
485
|
+
if text and not text.startswith(("<", "# AGENTS.md instructions")): # injected context, not the user
|
|
486
|
+
s.prompts.append((ts, text))
|
|
487
|
+
elif p.get("type") == "message" and p.get("role") == "assistant":
|
|
488
|
+
text = _codex_text(p.get("content")).strip()
|
|
489
|
+
if text:
|
|
490
|
+
s.final = text
|
|
491
|
+
elif cwd_match and p.get("type") == "function_call" and p.get("name") in ("exec_command", "shell", "local_shell"):
|
|
492
|
+
try:
|
|
493
|
+
a = json.loads(p.get("arguments") or "{}")
|
|
494
|
+
except json.JSONDecodeError:
|
|
495
|
+
a = {}
|
|
496
|
+
if not isinstance(a, dict):
|
|
497
|
+
a = {}
|
|
498
|
+
cmd = a.get("cmd") or a.get("command") or ""
|
|
499
|
+
if isinstance(cmd, list):
|
|
500
|
+
cmd = " ".join(str(x) for x in cmd)
|
|
501
|
+
s.edits.extend(shell_edits(cmd, root))
|
|
502
|
+
t = o.get("type")
|
|
503
|
+
if t == "event_msg" and p.get("type") == "task_started":
|
|
504
|
+
had_task = True
|
|
505
|
+
if t == "event_msg" and p.get("type") == "task_complete":
|
|
506
|
+
done_task = True
|
|
507
|
+
if had_task and not done_task:
|
|
508
|
+
s.interrupted = True
|
|
509
|
+
s.status_note = "no task_complete recorded"
|
|
510
|
+
return s
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def codex_sessions(root: Path, since: float) -> list[Session]:
|
|
514
|
+
try:
|
|
515
|
+
base = codex_dir()
|
|
516
|
+
if not base.is_dir():
|
|
517
|
+
return []
|
|
518
|
+
out, needle = [], str(root).lower()
|
|
519
|
+
for p in base.glob("*/*/*/rollout-*.jsonl*"):
|
|
520
|
+
if p.suffix not in (".jsonl", ".zst"):
|
|
521
|
+
continue
|
|
522
|
+
try:
|
|
523
|
+
if p.stat().st_mtime < since:
|
|
524
|
+
continue
|
|
525
|
+
s = read_codex(p, root)
|
|
526
|
+
except OSError:
|
|
527
|
+
continue
|
|
528
|
+
if s and s.touches_root:
|
|
529
|
+
out.append(s)
|
|
530
|
+
return out
|
|
531
|
+
except OSError:
|
|
532
|
+
return []
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def all_sessions(root: Path, days: float = 14) -> list[Session]:
|
|
536
|
+
since = time.time() - days * 86400
|
|
537
|
+
sessions = claude_sessions(root, since) + antigravity_sessions(root, since) + codex_sessions(root, since)
|
|
538
|
+
seen, unique = set(), []
|
|
539
|
+
for s in sessions: # the same Antigravity id can appear under two folders
|
|
540
|
+
if (s.tool, s.session) not in seen:
|
|
541
|
+
seen.add((s.tool, s.session))
|
|
542
|
+
unique.append(s)
|
|
543
|
+
return sorted(unique, key=lambda s: s.ended or "")
|