agent-manifesto-kit 1.2.0 → 1.5.0
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.
- package/README.md +101 -1
- package/collection/bundles/blender-3d/README.md +138 -0
- package/collection/bundles/blender-3d/agents/visual-reviewer.md +58 -0
- package/collection/bundles/blender-3d/skills/blender-asset/SKILL.md +75 -0
- package/collection/bundles/blender-3d/skills/blender-asset/scripts/record_run.py +175 -0
- package/collection/bundles/blender-3d/skills/blender-asset/scripts/task_state.py +199 -0
- package/collection/bundles/blender-3d/skills/blender-asset/workflows/asset.yml +105 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/SKILL.md +115 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/check_motion.py +244 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/export_gltf_clip.py +71 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/godot_verify.py +87 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/inspect_motion_source.py +107 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/render_frames.py +117 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/verify_gltf.py +117 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/SKILL.md +110 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/colors.py +50 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/compare.py +77 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/contact_sheet.py +51 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/diff_renders.py +58 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/edges.py +54 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/measure_ref.py +137 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/mesh_report.py +67 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/refspec.py +91 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/render_views.py +99 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/zoom.py +47 -0
- package/collection/bundles/kit-adopt/README.md +1 -1
- package/collection/bundles/kit-adopt/skills/kit-adopt/SKILL.md +2 -2
- package/collection/bundles/session-retro/README.md +64 -0
- package/collection/bundles/session-retro/agents/retro-analyst.md +77 -0
- package/collection/bundles/session-retro/skills/session-retro/SKILL.md +74 -0
- package/collection/bundles/session-retro/skills/session-retro/scripts/install_hooks.py +114 -0
- package/collection/bundles/session-retro/skills/session-retro/scripts/retro_hook.py +117 -0
- package/collection/bundles/session-retro/skills/session-retro/scripts/session_digest.py +457 -0
- package/dist/agent-format.js +218 -0
- package/dist/catalog.js +13 -13
- package/dist/cli.js +95 -4
- package/dist/commands/adopt.js +13 -3
- package/dist/commands/ingest.js +120 -0
- package/dist/commands/sync.js +201 -0
- package/dist/commands/update.js +36 -0
- package/dist/portability.js +19 -2
- package/dist/providers.js +12 -2
- package/package.json +1 -1
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"""Summarize a Claude Code or Codex session log into a compact digest for a retro.
|
|
2
|
+
|
|
3
|
+
python3 session_digest.py --latest [--provider claude|codex] [--cwd DIR] [--json] [--out FILE]
|
|
4
|
+
python3 session_digest.py --transcript PATH [--provider claude|codex] [--json] [--out FILE]
|
|
5
|
+
|
|
6
|
+
The digest keeps what a retro needs and drops the rest: requests and how long each took,
|
|
7
|
+
failed commands grouped by signature, commands and inline scripts repeated across the session
|
|
8
|
+
(candidates for a reusable script), files edited many times, likely user corrections, skills
|
|
9
|
+
and agents used, models, tokens and duration. Raw logs run to tens of megabytes; the digest stays
|
|
10
|
+
a few kilobytes. Standard library only.
|
|
11
|
+
|
|
12
|
+
Log locations (override the roots with CLAUDE_CONFIG_DIR and CODEX_HOME):
|
|
13
|
+
Claude Code: ~/.claude/projects/<cwd with non-alphanumerics as '-'>/<session-id>.jsonl
|
|
14
|
+
Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<session-id>.jsonl
|
|
15
|
+
"""
|
|
16
|
+
import argparse
|
|
17
|
+
import glob
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import shlex
|
|
22
|
+
import sys
|
|
23
|
+
from collections import Counter
|
|
24
|
+
|
|
25
|
+
LIMITS = {"requests": 40, "failures": 40, "inline": 30, "text": 400, "error": 300}
|
|
26
|
+
# Phrases that correct the agent, not ordinary sentences that happen to start with "no" or "not".
|
|
27
|
+
CORRECTION = re.compile(
|
|
28
|
+
r"^\s*(no[,.!]|nope\b|wrong\b|that'?s (not|wrong)\b|not what i\b|don'?t do\b|stop (doing|that)\b|"
|
|
29
|
+
r"revert\b|undo\b|why did you\b|i (said|told you|asked)\b|"
|
|
30
|
+
r"нет[,.!]|не так\b|неправильно|я же (сказал|просил)|зачем ты\b|верни\b)", re.I)
|
|
31
|
+
SETUP_WORDS = {"cd", "export", "set", "mkdir", "echo", "source", "true", "clear", "sleep", "pwd"}
|
|
32
|
+
RUNNERS = {"python", "python3", "node", "bash", "sh", "zsh", "npx", "uv", "deno", "ruby", "tsx", "ts-node"}
|
|
33
|
+
SCRIPT_EXT = (".py", ".js", ".mjs", ".ts", ".sh", ".gd", ".rb")
|
|
34
|
+
HEREDOC = re.compile(r"<<-?\s*['\"]?(\w+)['\"]?[^\n]*\n(.*?)\n\s*\1\b", re.S)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ── command classification ──────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
def _segments(cmd):
|
|
40
|
+
body = HEREDOC.sub(" ", cmd)
|
|
41
|
+
return [s.strip() for s in re.split(r"&&|\|\||;|\n|\|", body) if s.strip()]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def signature(cmd):
|
|
45
|
+
"""A short stable label for a shell command: program plus script or subcommand."""
|
|
46
|
+
for seg in _segments(cmd):
|
|
47
|
+
try:
|
|
48
|
+
tokens = shlex.split(seg)
|
|
49
|
+
except ValueError:
|
|
50
|
+
tokens = seg.split()
|
|
51
|
+
while tokens and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", tokens[0]):
|
|
52
|
+
tokens = tokens[1:]
|
|
53
|
+
if not tokens or tokens[0] in SETUP_WORDS:
|
|
54
|
+
continue
|
|
55
|
+
prog = os.path.basename(tokens[0])
|
|
56
|
+
rest = tokens[1:]
|
|
57
|
+
if "--python" in rest:
|
|
58
|
+
i = rest.index("--python")
|
|
59
|
+
if i + 1 < len(rest):
|
|
60
|
+
return f"{prog} --python {os.path.basename(rest[i + 1])}"
|
|
61
|
+
if prog in RUNNERS or prog.lower().startswith("python"):
|
|
62
|
+
for t in rest:
|
|
63
|
+
if t in ("-", "-c", "-e"):
|
|
64
|
+
return f"{prog} {t} (inline)"
|
|
65
|
+
if t.endswith(SCRIPT_EXT):
|
|
66
|
+
return f"{prog} {os.path.basename(t)}"
|
|
67
|
+
if not t.startswith("-"):
|
|
68
|
+
return f"{prog} {t}"
|
|
69
|
+
return prog
|
|
70
|
+
sub = next((t for t in rest if not t.startswith("-") and "/" not in t and len(t) < 30), "")
|
|
71
|
+
return f"{prog} {sub}".strip()
|
|
72
|
+
return "(setup command)"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
INLINE = re.compile(r"\b(python\d?(?:\.\d+)?|node|ruby|bash|sh)\s+(-\s*<<|-c\s|-e\s|-\s*$|<<)|\bcat\s*>\s*\S+\.(py|js|ts|sh|gd)\s*<<", re.M)
|
|
76
|
+
WRITES = re.compile(r"open\(\s*(?:['\"]([^'\"]+)['\"]|(\w+))\s*,\s*['\"][wa]")
|
|
77
|
+
ASSIGN = re.compile(r"\b(\w+)\s*=\s*['\"]([^'\"\s]+\.\w{1,5})['\"]")
|
|
78
|
+
SED = re.compile(r"\bsed\s+-i(?:\s+''|\s+\"\")?\s+.*?\s(\S+\.\w{1,5})\s*(?:$|&&|;|\|)", re.M)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def inline_script(cmd):
|
|
82
|
+
"""Label of an inline script (heredoc or -c/-e body), or None."""
|
|
83
|
+
m = INLINE.search(cmd)
|
|
84
|
+
if not m:
|
|
85
|
+
return None
|
|
86
|
+
here = HEREDOC.search(cmd, m.start())
|
|
87
|
+
body = here.group(2) if here else cmd[m.end():].strip().strip("'\"")
|
|
88
|
+
for line in body.splitlines():
|
|
89
|
+
line = line.strip()
|
|
90
|
+
if line and not re.match(r"^(import |from |#|\"\"\"|\'\'\'|const |require\()", line):
|
|
91
|
+
return line[:60]
|
|
92
|
+
first = body.strip().splitlines()
|
|
93
|
+
return first[0][:60] if first else "(empty)"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def written_files(cmd):
|
|
97
|
+
"""Files a command edits in place: open(..., 'w') in inline scripts, or sed -i."""
|
|
98
|
+
names = dict(ASSIGN.findall(cmd))
|
|
99
|
+
out = []
|
|
100
|
+
for literal, var in WRITES.findall(cmd):
|
|
101
|
+
path = literal or names.get(var)
|
|
102
|
+
if path:
|
|
103
|
+
out.append(path)
|
|
104
|
+
out += SED.findall(cmd)
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def command_signals(cmd):
|
|
109
|
+
"""Metadata needed across a hook boundary, without the command or inline-script body."""
|
|
110
|
+
return {"signature": signature(cmd), "inline": bool(inline_script(cmd)),
|
|
111
|
+
"edits": written_files(cmd), "skills": re.findall(r"([\w.-]+)/SKILL\.md", cmd)}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _clip(text, n):
|
|
115
|
+
text = " ".join(str(text).split())
|
|
116
|
+
return text if len(text) <= n else text[: n - 1] + "…"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ── digest ──────────────────────────────────────────────────────────────────
|
|
120
|
+
|
|
121
|
+
class Digest:
|
|
122
|
+
def __init__(self, provider):
|
|
123
|
+
self.provider = provider
|
|
124
|
+
self.session_id = None
|
|
125
|
+
self.cwd = None
|
|
126
|
+
self.start = None
|
|
127
|
+
self.end = None
|
|
128
|
+
self.models = Counter()
|
|
129
|
+
self.output_tokens = 0
|
|
130
|
+
self.tools = Counter()
|
|
131
|
+
self.cmd_sig = Counter()
|
|
132
|
+
self.cmd_fail = Counter()
|
|
133
|
+
self.tool_fail = Counter()
|
|
134
|
+
self.failures = []
|
|
135
|
+
self.inline = []
|
|
136
|
+
self.inline_count = 0
|
|
137
|
+
self.edits = Counter()
|
|
138
|
+
self.requests = []
|
|
139
|
+
self.request_count = 0
|
|
140
|
+
self.corrections = 0
|
|
141
|
+
self.seen_messages = []
|
|
142
|
+
self.skills = Counter()
|
|
143
|
+
self.agents = Counter()
|
|
144
|
+
self.pending = {}
|
|
145
|
+
|
|
146
|
+
# state round trip for the incremental hook
|
|
147
|
+
def to_state(self):
|
|
148
|
+
return {k: (dict(v) if isinstance(v, Counter) else v) for k, v in self.__dict__.items()}
|
|
149
|
+
|
|
150
|
+
def slim_state(self):
|
|
151
|
+
"""Counters only, for the hook's cache: no request text, excerpts or labels."""
|
|
152
|
+
keep = {"provider", "session_id", "tools", "cmd_fail", "tool_fail", "inline_count", "edits",
|
|
153
|
+
"request_count", "corrections", "seen_messages"}
|
|
154
|
+
state = {k: v for k, v in self.to_state().items() if k in keep}
|
|
155
|
+
state["pending"] = {
|
|
156
|
+
k: [v[0], command_signals(v[1]) if isinstance(v[1], str) else v[1], None]
|
|
157
|
+
if v[0] == "Bash" else [v[0], "", None] for k, v in self.pending.items()
|
|
158
|
+
}
|
|
159
|
+
return state
|
|
160
|
+
|
|
161
|
+
@classmethod
|
|
162
|
+
def from_state(cls, state):
|
|
163
|
+
d = cls(state["provider"])
|
|
164
|
+
for k, v in state.items():
|
|
165
|
+
setattr(d, k, Counter(v) if isinstance(getattr(d, k, None), Counter) else v)
|
|
166
|
+
return d
|
|
167
|
+
|
|
168
|
+
def _time(self, ts):
|
|
169
|
+
if ts:
|
|
170
|
+
self.start = self.start or ts
|
|
171
|
+
self.end = ts
|
|
172
|
+
|
|
173
|
+
def _command(self, cmd, ok, error, ts):
|
|
174
|
+
metadata = cmd if isinstance(cmd, dict) else command_signals(cmd)
|
|
175
|
+
sig = metadata["signature"]
|
|
176
|
+
self.cmd_sig[sig] += 1
|
|
177
|
+
if metadata["inline"]:
|
|
178
|
+
self.inline_count += 1
|
|
179
|
+
if isinstance(cmd, str) and len(self.inline) < LIMITS["inline"]:
|
|
180
|
+
self.inline.append({"label": inline_script(cmd), "time": ts})
|
|
181
|
+
for m in metadata["skills"]:
|
|
182
|
+
self.skills[m] += 1
|
|
183
|
+
for path in metadata["edits"]:
|
|
184
|
+
self.edits[path] += 1
|
|
185
|
+
if not ok:
|
|
186
|
+
self.cmd_fail[sig] += 1
|
|
187
|
+
self._failure(sig, sig if isinstance(cmd, dict) else cmd, error, ts)
|
|
188
|
+
|
|
189
|
+
def _failure(self, sig, what, error, ts):
|
|
190
|
+
if len(self.failures) < LIMITS["failures"]:
|
|
191
|
+
self.failures.append({"signature": sig, "command": _clip(what, 200),
|
|
192
|
+
"error": _clip(error or "", LIMITS["error"]), "time": ts})
|
|
193
|
+
|
|
194
|
+
def _request(self, text, ts):
|
|
195
|
+
text = text.strip()
|
|
196
|
+
if not text or text.startswith("<") or text.startswith("[Request interrupted"):
|
|
197
|
+
return
|
|
198
|
+
if self.request_count and CORRECTION.search(text):
|
|
199
|
+
self.corrections += 1
|
|
200
|
+
self.request_count += 1
|
|
201
|
+
if len(self.requests) < LIMITS["requests"]:
|
|
202
|
+
self.requests.append({"time": ts, "text": _clip(text, LIMITS["text"])})
|
|
203
|
+
|
|
204
|
+
# Claude Code: {"type": "user"|"assistant", "message": {...}, "timestamp": ...}
|
|
205
|
+
def feed_claude(self, o):
|
|
206
|
+
ts = o.get("timestamp")
|
|
207
|
+
self._time(ts)
|
|
208
|
+
self.session_id = self.session_id or o.get("sessionId")
|
|
209
|
+
self.cwd = self.cwd or o.get("cwd")
|
|
210
|
+
m = o.get("message") or {}
|
|
211
|
+
content = m.get("content")
|
|
212
|
+
if o.get("type") == "assistant":
|
|
213
|
+
# one log line per content block repeats the message's model and usage: count each message once
|
|
214
|
+
mid = m.get("id")
|
|
215
|
+
if not mid or mid not in self.seen_messages:
|
|
216
|
+
if mid:
|
|
217
|
+
self.seen_messages = (self.seen_messages + [mid])[-50:]
|
|
218
|
+
if m.get("model"):
|
|
219
|
+
self.models[m["model"]] += 1
|
|
220
|
+
self.output_tokens += (m.get("usage") or {}).get("output_tokens", 0) or 0
|
|
221
|
+
for b in content if isinstance(content, list) else []:
|
|
222
|
+
if b.get("type") != "tool_use":
|
|
223
|
+
continue
|
|
224
|
+
name, inp = b.get("name", "?"), b.get("input") or {}
|
|
225
|
+
self.tools[name] += 1
|
|
226
|
+
if name == "Skill" and inp.get("skill"):
|
|
227
|
+
self.skills[inp["skill"]] += 1
|
|
228
|
+
if name in ("Agent", "Task"):
|
|
229
|
+
self.agents[inp.get("subagent_type") or "general-purpose"] += 1
|
|
230
|
+
path = inp.get("file_path") or inp.get("notebook_path")
|
|
231
|
+
if name in ("Edit", "Write", "MultiEdit", "NotebookEdit") and path:
|
|
232
|
+
self.edits[path] += 1
|
|
233
|
+
if name == "Read" and str(path or "").endswith("SKILL.md"):
|
|
234
|
+
self.skills[os.path.basename(os.path.dirname(path))] += 1
|
|
235
|
+
what = inp.get("command") if name == "Bash" else (path or inp.get("description") or name)
|
|
236
|
+
self.pending[b.get("id")] = [name, what or name, ts]
|
|
237
|
+
elif o.get("type") == "user" and not o.get("isMeta"):
|
|
238
|
+
if isinstance(content, str):
|
|
239
|
+
self._request(content, ts)
|
|
240
|
+
return
|
|
241
|
+
for b in content if isinstance(content, list) else []:
|
|
242
|
+
if b.get("type") == "text":
|
|
243
|
+
self._request(b.get("text", ""), ts)
|
|
244
|
+
elif b.get("type") == "tool_result":
|
|
245
|
+
name, what, t0 = self.pending.pop(b.get("tool_use_id"), ["?", "?", ts])
|
|
246
|
+
err = b.get("is_error") is True
|
|
247
|
+
out = b.get("content")
|
|
248
|
+
text = out if isinstance(out, str) else " ".join(x.get("text", "") for x in out or [] if isinstance(x, dict))
|
|
249
|
+
if name == "Bash":
|
|
250
|
+
self._command(what, not err, text, t0)
|
|
251
|
+
elif err:
|
|
252
|
+
self.tool_fail[name] += 1
|
|
253
|
+
self._failure(name, what, text, t0)
|
|
254
|
+
|
|
255
|
+
# Codex: {"type": "session_meta"|"event_msg"|"response_item"|..., "payload": {...}}
|
|
256
|
+
def feed_codex(self, o):
|
|
257
|
+
ts = o.get("timestamp")
|
|
258
|
+
self._time(ts)
|
|
259
|
+
p = o.get("payload") or {}
|
|
260
|
+
t = o.get("type")
|
|
261
|
+
if t == "session_meta":
|
|
262
|
+
self.session_id = self.session_id or p.get("session_id") or p.get("id")
|
|
263
|
+
self.cwd = self.cwd or p.get("cwd")
|
|
264
|
+
elif t == "event_msg" and p.get("type") == "thread_settings_applied":
|
|
265
|
+
model = (p.get("thread_settings") or {}).get("model")
|
|
266
|
+
if model:
|
|
267
|
+
self.models[model] += 1
|
|
268
|
+
elif t == "event_msg" and p.get("type") == "token_count":
|
|
269
|
+
usage = ((p.get("info") or {}).get("total_token_usage") or {})
|
|
270
|
+
self.output_tokens = max(self.output_tokens, usage.get("output_tokens", 0) or 0)
|
|
271
|
+
elif t == "event_msg" and p.get("type") == "item_completed":
|
|
272
|
+
it = p.get("item") or {}
|
|
273
|
+
kind = it.get("type")
|
|
274
|
+
if kind == "UserMessage":
|
|
275
|
+
for c in it.get("content") or []:
|
|
276
|
+
if c.get("type") == "text":
|
|
277
|
+
self._request(c.get("text", ""), ts)
|
|
278
|
+
return
|
|
279
|
+
if kind in (None, "Reasoning", "AgentMessage", "ContextCompaction"):
|
|
280
|
+
return
|
|
281
|
+
self.tools[kind] += 1
|
|
282
|
+
if kind == "CommandExecution":
|
|
283
|
+
cmd = it.get("command")
|
|
284
|
+
cmd = cmd[-1] if isinstance(cmd, list) and cmd else str(cmd or "")
|
|
285
|
+
ok = it.get("status") != "failed" and it.get("exit_code") in (0, None)
|
|
286
|
+
self._command(cmd, ok, it.get("stderr") or it.get("stdout") or "", ts)
|
|
287
|
+
elif kind == "FileChange":
|
|
288
|
+
for path in (it.get("changes") or {}):
|
|
289
|
+
self.edits[path] += 1
|
|
290
|
+
elif t == "response_item" and p.get("type") == "function_call" and p.get("name") == "spawn_agent":
|
|
291
|
+
try:
|
|
292
|
+
self.agents[json.loads(p.get("arguments") or "{}").get("agent_type") or "default"] += 1
|
|
293
|
+
except ValueError:
|
|
294
|
+
self.agents["default"] += 1
|
|
295
|
+
|
|
296
|
+
def feed(self, o):
|
|
297
|
+
(self.feed_claude if self.provider == "claude" else self.feed_codex)(o)
|
|
298
|
+
|
|
299
|
+
# signals the hook thresholds and the analyst both use
|
|
300
|
+
def signals(self):
|
|
301
|
+
repeated_fail = self.cmd_fail.most_common(1)
|
|
302
|
+
churn = self.edits.most_common(1)
|
|
303
|
+
return {
|
|
304
|
+
"tool_calls": sum(self.tools.values()),
|
|
305
|
+
"failed": sum(self.cmd_fail.values()) + sum(self.tool_fail.values()),
|
|
306
|
+
"repeat_fail": repeated_fail[0] if repeated_fail else ["", 0],
|
|
307
|
+
"inline_scripts": self.inline_count,
|
|
308
|
+
"churn": churn[0] if churn else ["", 0],
|
|
309
|
+
"corrections": self.corrections,
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
def to_json(self):
|
|
313
|
+
s = self.to_state()
|
|
314
|
+
s.pop("pending", None)
|
|
315
|
+
s.pop("seen_messages", None)
|
|
316
|
+
for key, value in self.__dict__.items():
|
|
317
|
+
if isinstance(value, Counter):
|
|
318
|
+
s[key] = dict(value.most_common(40))
|
|
319
|
+
s["signals"] = self.signals()
|
|
320
|
+
s["repeated_commands"] = [[k, v] for k, v in self.cmd_sig.most_common(15) if v >= 3]
|
|
321
|
+
return s
|
|
322
|
+
|
|
323
|
+
def markdown(self):
|
|
324
|
+
s = self.signals()
|
|
325
|
+
out = [f"# Session digest ({self.provider})", "",
|
|
326
|
+
f"- session: `{self.session_id}` cwd: `{self.cwd}`",
|
|
327
|
+
f"- time: {self.start} → {self.end}",
|
|
328
|
+
f"- models: {', '.join(f'{k} ×{v}' for k, v in self.models.most_common()) or 'unknown'}"
|
|
329
|
+
f"; output tokens: {self.output_tokens}",
|
|
330
|
+
f"- tool calls: {s['tool_calls']} ({', '.join(f'{k} {v}' for k, v in self.tools.most_common(8))})",
|
|
331
|
+
f"- signals: failed {s['failed']}, inline scripts {s['inline_scripts']}, "
|
|
332
|
+
f"top repeated failure `{s['repeat_fail'][0]}` ×{s['repeat_fail'][1]}, "
|
|
333
|
+
f"most edited `{s['churn'][0]}` ×{s['churn'][1]}, likely corrections {s['corrections']}", ""]
|
|
334
|
+
out += ["## Requests", ""] + [f"- {r['time']}: {r['text']}" for r in self.requests] + [""]
|
|
335
|
+
if self.failures:
|
|
336
|
+
out += ["## Failures (by signature)", ""]
|
|
337
|
+
groups = {}
|
|
338
|
+
for f in self.failures:
|
|
339
|
+
groups.setdefault(f["signature"], []).append(f)
|
|
340
|
+
total = Counter(self.cmd_fail) + Counter(self.tool_fail)
|
|
341
|
+
for sig, items in sorted(groups.items(), key=lambda kv: -total.get(kv[0], len(kv[1]))):
|
|
342
|
+
out.append(f"- `{sig}` ×{total.get(sig, len(items))}")
|
|
343
|
+
for f in items[:2]:
|
|
344
|
+
out.append(f" - {f['time']}: `{f['command']}` → {f['error']}")
|
|
345
|
+
out.append("")
|
|
346
|
+
rep = [(k, v) for k, v in self.cmd_sig.most_common(15) if v >= 3]
|
|
347
|
+
if rep:
|
|
348
|
+
out += ["## Repeated commands", ""] + [f"- `{k}` ×{v}" for k, v in rep] + [""]
|
|
349
|
+
if self.inline:
|
|
350
|
+
out += [f"## Inline scripts ({self.inline_count})", ""] + [f"- {i['time']}: {i['label']}" for i in self.inline] + [""]
|
|
351
|
+
churn = [(k, v) for k, v in self.edits.most_common(10) if v >= 3]
|
|
352
|
+
if churn:
|
|
353
|
+
out += ["## Files edited 3+ times", ""] + [f"- `{k}` ×{v}" for k, v in churn] + [""]
|
|
354
|
+
if self.skills or self.agents:
|
|
355
|
+
out += ["## Skills and agents used", ""]
|
|
356
|
+
out += [f"- skill `{k}` ×{v}" for k, v in self.skills.most_common(40)]
|
|
357
|
+
out += [f"- agent `{k}` ×{v}" for k, v in self.agents.most_common(40)] + [""]
|
|
358
|
+
return "\n".join(out)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# ── reading and locating logs ───────────────────────────────────────────────
|
|
362
|
+
|
|
363
|
+
def detect_provider(path):
|
|
364
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
365
|
+
for line in f:
|
|
366
|
+
try:
|
|
367
|
+
o = json.loads(line)
|
|
368
|
+
except ValueError:
|
|
369
|
+
continue
|
|
370
|
+
return "codex" if "payload" in o else "claude"
|
|
371
|
+
return "claude"
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def read_from(path, digest, offset=0):
|
|
375
|
+
"""Feed complete lines after offset; return the new offset (a trailing partial line is left)."""
|
|
376
|
+
size = os.path.getsize(path)
|
|
377
|
+
if offset > size:
|
|
378
|
+
offset = 0
|
|
379
|
+
with open(path, "rb") as f:
|
|
380
|
+
f.seek(offset)
|
|
381
|
+
for raw in f:
|
|
382
|
+
if not raw.endswith(b"\n"):
|
|
383
|
+
break
|
|
384
|
+
offset += len(raw)
|
|
385
|
+
try:
|
|
386
|
+
digest.feed(json.loads(raw))
|
|
387
|
+
except (ValueError, AttributeError, TypeError):
|
|
388
|
+
continue
|
|
389
|
+
return offset
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def claude_root():
|
|
393
|
+
return os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude")
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def codex_root():
|
|
397
|
+
return os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def locate(provider, cwd=None, session_id=None):
|
|
401
|
+
"""Newest log for a session id, or for a project directory."""
|
|
402
|
+
if provider == "claude":
|
|
403
|
+
if session_id:
|
|
404
|
+
hits = glob.glob(os.path.join(claude_root(), "projects", "*", f"{session_id}.jsonl"))
|
|
405
|
+
else:
|
|
406
|
+
folder = re.sub(r"[^A-Za-z0-9]", "-", os.path.abspath(cwd or os.getcwd()))
|
|
407
|
+
hits = glob.glob(os.path.join(claude_root(), "projects", folder, "*.jsonl"))
|
|
408
|
+
return max(hits, key=os.path.getmtime) if hits else None
|
|
409
|
+
pattern = f"*{session_id}.jsonl" if session_id else "rollout-*.jsonl"
|
|
410
|
+
hits = sorted(glob.glob(os.path.join(codex_root(), "sessions", "**", pattern), recursive=True),
|
|
411
|
+
key=os.path.getmtime, reverse=True)
|
|
412
|
+
if session_id:
|
|
413
|
+
return hits[0] if hits else None
|
|
414
|
+
want = os.path.abspath(cwd or os.getcwd())
|
|
415
|
+
for path in hits[:300]:
|
|
416
|
+
try:
|
|
417
|
+
with open(path, encoding="utf-8") as f:
|
|
418
|
+
meta = json.loads(f.readline()).get("payload") or {}
|
|
419
|
+
except (ValueError, OSError):
|
|
420
|
+
continue
|
|
421
|
+
if os.path.abspath(meta.get("cwd") or "") == want:
|
|
422
|
+
return path
|
|
423
|
+
return None
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def main():
|
|
427
|
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
428
|
+
p.add_argument("--transcript")
|
|
429
|
+
p.add_argument("--latest", action="store_true", help="newest session for --cwd (default: current directory)")
|
|
430
|
+
p.add_argument("--session-id")
|
|
431
|
+
p.add_argument("--provider", choices=["claude", "codex"])
|
|
432
|
+
p.add_argument("--cwd")
|
|
433
|
+
p.add_argument("--json", action="store_true")
|
|
434
|
+
p.add_argument("--out")
|
|
435
|
+
args = p.parse_args()
|
|
436
|
+
path = args.transcript
|
|
437
|
+
if not path:
|
|
438
|
+
if not (args.latest or args.session_id):
|
|
439
|
+
p.error("pass --transcript, --latest or --session-id")
|
|
440
|
+
providers = [args.provider] if args.provider else ["claude", "codex"]
|
|
441
|
+
found = [x for x in (locate(pr, args.cwd, args.session_id) for pr in providers) if x]
|
|
442
|
+
if not found:
|
|
443
|
+
raise SystemExit("no session log found; pass --transcript")
|
|
444
|
+
path = max(found, key=os.path.getmtime)
|
|
445
|
+
digest = Digest(args.provider or detect_provider(path))
|
|
446
|
+
read_from(path, digest)
|
|
447
|
+
text = json.dumps(digest.to_json(), indent=2) if args.json else digest.markdown()
|
|
448
|
+
if args.out:
|
|
449
|
+
with open(args.out, "w", encoding="utf-8") as f:
|
|
450
|
+
f.write(text + "\n")
|
|
451
|
+
print(f"digest of {path} -> {args.out}")
|
|
452
|
+
else:
|
|
453
|
+
print(text)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
if __name__ == "__main__":
|
|
457
|
+
sys.exit(main())
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical agents are Claude-style Markdown: YAML frontmatter (`name`, `description`, optional
|
|
3
|
+
* Claude keys such as `tools`, optional `codex:` block) followed by the instruction body.
|
|
4
|
+
* Codex reads custom agents as TOML with `name`, `description` and `developer_instructions`.
|
|
5
|
+
*/
|
|
6
|
+
const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
|
|
7
|
+
function unquote(raw) {
|
|
8
|
+
const v = raw.trim();
|
|
9
|
+
if (v.length >= 2 && v.startsWith('"') && v.endsWith('"')) {
|
|
10
|
+
return v.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\");
|
|
11
|
+
}
|
|
12
|
+
if (v.length >= 2 && v.startsWith("'") && v.endsWith("'"))
|
|
13
|
+
return v.slice(1, -1).replace(/''/g, "'");
|
|
14
|
+
return v;
|
|
15
|
+
}
|
|
16
|
+
function indentOf(line) {
|
|
17
|
+
return line.length - line.trimStart().length;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Minimal frontmatter reader: scalar keys, quoted values, `>`/`|` block scalars, and one level of
|
|
21
|
+
* nested `key:` mappings. Enough for capability metadata; not a general YAML parser.
|
|
22
|
+
*/
|
|
23
|
+
export function parseMarkdown(text) {
|
|
24
|
+
const m = FRONTMATTER.exec(text);
|
|
25
|
+
if (!m)
|
|
26
|
+
return { frontmatter: {}, body: text };
|
|
27
|
+
const lines = m[1].split(/\r?\n/);
|
|
28
|
+
const fm = {};
|
|
29
|
+
let i = 0;
|
|
30
|
+
while (i < lines.length) {
|
|
31
|
+
const line = lines[i];
|
|
32
|
+
const kv = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(line);
|
|
33
|
+
if (!kv || indentOf(line) > 0) {
|
|
34
|
+
i++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const [, key, rest] = kv;
|
|
38
|
+
i++;
|
|
39
|
+
if (/^[>|][+-]?$/.test(rest)) {
|
|
40
|
+
const folded = rest.startsWith(">");
|
|
41
|
+
const block = [];
|
|
42
|
+
while (i < lines.length && (lines[i].trim() === "" || indentOf(lines[i]) > 0)) {
|
|
43
|
+
block.push(lines[i].trim());
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
fm[key] = folded ? block.join(" ").replace(/\s+/g, " ").trim() : block.join("\n").trim();
|
|
47
|
+
}
|
|
48
|
+
else if (rest === "") {
|
|
49
|
+
const nested = {};
|
|
50
|
+
while (i < lines.length && (lines[i].trim() === "" || indentOf(lines[i]) > 0)) {
|
|
51
|
+
const sub = /^\s+([A-Za-z0-9_.-]+):\s*(.*)$/.exec(lines[i]);
|
|
52
|
+
if (sub)
|
|
53
|
+
nested[sub[1]] = unquote(sub[2]);
|
|
54
|
+
i++;
|
|
55
|
+
}
|
|
56
|
+
fm[key] = nested;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
fm[key] = unquote(rest);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { frontmatter: fm, body: text.slice(m[0].length) };
|
|
63
|
+
}
|
|
64
|
+
function tomlString(value) {
|
|
65
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, "\\n").replace(/\t/g, "\\t")}"`;
|
|
66
|
+
}
|
|
67
|
+
function tomlMultiline(value) {
|
|
68
|
+
const escaped = value.replace(/\\/g, "\\\\").replace(/"""/g, '""\\"');
|
|
69
|
+
return `"""\n${escaped}${escaped.endsWith("\n") ? "" : "\n"}"""`;
|
|
70
|
+
}
|
|
71
|
+
function tomlValue(raw) {
|
|
72
|
+
if (/^(true|false)$/.test(raw) || /^-?\d+(\.\d+)?$/.test(raw))
|
|
73
|
+
return raw;
|
|
74
|
+
return tomlString(raw);
|
|
75
|
+
}
|
|
76
|
+
/** Claude tools that let an agent change files. Their absence means the agent is read-only. */
|
|
77
|
+
const WRITE_TOOLS = ["Edit", "Write", "MultiEdit", "NotebookEdit"];
|
|
78
|
+
/** Render a canonical Markdown agent as a Codex custom-agent TOML file. */
|
|
79
|
+
export function markdownAgentToCodexToml(markdown, fallbackName) {
|
|
80
|
+
const { frontmatter, body } = parseMarkdown(markdown);
|
|
81
|
+
const str = (k) => (typeof frontmatter[k] === "string" ? frontmatter[k] : "");
|
|
82
|
+
const name = str("name") || fallbackName;
|
|
83
|
+
const codex = typeof frontmatter.codex === "object" ? frontmatter.codex : {};
|
|
84
|
+
const extras = { ...codex };
|
|
85
|
+
const tools = str("tools");
|
|
86
|
+
if (tools && extras.sandbox_mode === undefined) {
|
|
87
|
+
const list = tools.split(",").map((t) => t.trim());
|
|
88
|
+
if (!list.some((t) => WRITE_TOOLS.includes(t)))
|
|
89
|
+
extras.sandbox_mode = "read-only";
|
|
90
|
+
}
|
|
91
|
+
// A read-only tool list survives as sandbox_mode, so it is translated rather than dropped.
|
|
92
|
+
const translated = extras.sandbox_mode === "read-only" && codex.sandbox_mode === undefined ? ["tools"] : [];
|
|
93
|
+
const dropped = Object.keys(frontmatter).filter((k) => !["name", "description", "codex", ...translated].includes(k));
|
|
94
|
+
const reserved = new Set(["name", "description", "developer_instructions"]);
|
|
95
|
+
const lines = [`name = ${tomlString(name)}`, `description = ${tomlString(str("description"))}`];
|
|
96
|
+
for (const [k, v] of Object.entries(extras)) {
|
|
97
|
+
if (!reserved.has(k))
|
|
98
|
+
lines.push(`${k} = ${tomlValue(v)}`);
|
|
99
|
+
}
|
|
100
|
+
lines.push(`developer_instructions = ${tomlMultiline(body.replace(/^\s*\n/, ""))}`);
|
|
101
|
+
return { toml: lines.join("\n") + "\n", dropped };
|
|
102
|
+
}
|
|
103
|
+
function unescapeBasic(raw) {
|
|
104
|
+
return raw.replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_, e) => {
|
|
105
|
+
if (e[0] === "u" || e[0] === "U")
|
|
106
|
+
return String.fromCodePoint(parseInt(e.slice(1), 16));
|
|
107
|
+
return { n: "\n", t: "\t", r: "\r", b: "\b", f: "\f", '"': '"', "\\": "\\" }[e] ?? e;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Read the top-level scalar keys of a Codex agent TOML file. Tables and arrays (for example
|
|
112
|
+
* `[mcp_servers]`) are reported as skipped; they are tool configuration, not agent intent.
|
|
113
|
+
*/
|
|
114
|
+
export function parseAgentToml(text) {
|
|
115
|
+
const values = {};
|
|
116
|
+
const skipped = [];
|
|
117
|
+
let rest = text.replace(/\r\n/g, "\n");
|
|
118
|
+
let inTable = false;
|
|
119
|
+
while (rest.length > 0) {
|
|
120
|
+
const nl = rest.indexOf("\n");
|
|
121
|
+
const line = (nl === -1 ? rest : rest.slice(0, nl)).trim();
|
|
122
|
+
if (line === "" || line.startsWith("#")) {
|
|
123
|
+
rest = nl === -1 ? "" : rest.slice(nl + 1);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (line.startsWith("[")) {
|
|
127
|
+
inTable = true;
|
|
128
|
+
skipped.push(line.replace(/^\[+|\]+$/g, ""));
|
|
129
|
+
rest = nl === -1 ? "" : rest.slice(nl + 1);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const kv = /^\s*([A-Za-z0-9_-]+|"[^"]+")\s*=\s*/.exec(rest);
|
|
133
|
+
if (!kv)
|
|
134
|
+
throw new Error(`cannot parse TOML line: ${line}`);
|
|
135
|
+
const key = kv[1].replace(/^"|"$/g, "");
|
|
136
|
+
rest = rest.slice(kv[0].length);
|
|
137
|
+
let value;
|
|
138
|
+
let consumed;
|
|
139
|
+
if (rest.startsWith('"""') || rest.startsWith("'''")) {
|
|
140
|
+
const q = rest.slice(0, 3);
|
|
141
|
+
let end = 3;
|
|
142
|
+
for (;;) {
|
|
143
|
+
end = rest.indexOf(q, end);
|
|
144
|
+
if (end === -1)
|
|
145
|
+
throw new Error(`unterminated multi-line string for "${key}"`);
|
|
146
|
+
if (q === '"""' && rest[end - 1] === "\\" && rest[end - 2] !== "\\") {
|
|
147
|
+
end += 1;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
while (rest[end + 3] === q[0])
|
|
151
|
+
end++;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
const raw = rest.slice(3, end).replace(/^\n/, "");
|
|
155
|
+
value = q === '"""' ? unescapeBasic(raw.replace(/\\\n\s*/g, "")) : raw;
|
|
156
|
+
consumed = end + 3;
|
|
157
|
+
}
|
|
158
|
+
else if (rest.startsWith('"')) {
|
|
159
|
+
const m = /^"((?:[^"\\\n]|\\.)*)"/.exec(rest);
|
|
160
|
+
if (!m)
|
|
161
|
+
throw new Error(`unterminated string for "${key}"`);
|
|
162
|
+
value = unescapeBasic(m[1]);
|
|
163
|
+
consumed = m[0].length;
|
|
164
|
+
}
|
|
165
|
+
else if (rest.startsWith("'")) {
|
|
166
|
+
const m = /^'([^'\n]*)'/.exec(rest);
|
|
167
|
+
if (!m)
|
|
168
|
+
throw new Error(`unterminated string for "${key}"`);
|
|
169
|
+
value = m[1];
|
|
170
|
+
consumed = m[0].length;
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
const m = /^([^\n#]*)/.exec(rest);
|
|
174
|
+
const token = m[1].trim();
|
|
175
|
+
if (token === "true" || token === "false")
|
|
176
|
+
value = token === "true";
|
|
177
|
+
else if (/^[+-]?\d+(\.\d+)?$/.test(token))
|
|
178
|
+
value = Number(token);
|
|
179
|
+
else
|
|
180
|
+
skipped.push(key);
|
|
181
|
+
consumed = m[0].length;
|
|
182
|
+
}
|
|
183
|
+
if (value !== undefined && !inTable)
|
|
184
|
+
values[key] = value;
|
|
185
|
+
rest = rest.slice(consumed);
|
|
186
|
+
const eol = rest.indexOf("\n");
|
|
187
|
+
rest = eol === -1 ? "" : rest.slice(eol + 1);
|
|
188
|
+
}
|
|
189
|
+
return { values, skipped };
|
|
190
|
+
}
|
|
191
|
+
function yamlScalar(value) {
|
|
192
|
+
return /^[\w .,/()'-]*$/.test(value) && !/^[\s'-]/.test(value) && !value.includes(": ")
|
|
193
|
+
? value
|
|
194
|
+
: `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
195
|
+
}
|
|
196
|
+
/** Claude tools granted to an ingested Codex agent whose sandbox is read-only. */
|
|
197
|
+
const READ_ONLY_TOOLS = "Read, Grep, Glob, Bash";
|
|
198
|
+
/** Convert a Codex agent TOML file into a canonical Markdown agent. */
|
|
199
|
+
export function codexTomlAgentToMarkdown(text) {
|
|
200
|
+
const { values, skipped } = parseAgentToml(text);
|
|
201
|
+
for (const key of ["name", "description", "developer_instructions"]) {
|
|
202
|
+
if (typeof values[key] !== "string" || values[key].trim() === "") {
|
|
203
|
+
throw new Error(`Codex agent is missing required string "${key}"`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const lines = ["---", `name: ${yamlScalar(values.name)}`, `description: ${yamlScalar(values.description)}`];
|
|
207
|
+
if (values.sandbox_mode === "read-only")
|
|
208
|
+
lines.push(`tools: ${READ_ONLY_TOOLS}`);
|
|
209
|
+
const extras = Object.entries(values).filter(([k]) => !["name", "description", "developer_instructions"].includes(k));
|
|
210
|
+
if (extras.length > 0) {
|
|
211
|
+
lines.push("codex:");
|
|
212
|
+
for (const [k, v] of extras)
|
|
213
|
+
lines.push(` ${k}: ${typeof v === "string" ? yamlScalar(v) : String(v)}`);
|
|
214
|
+
}
|
|
215
|
+
lines.push("---", "");
|
|
216
|
+
const body = values.developer_instructions.replace(/^\n+/, "");
|
|
217
|
+
return { markdown: lines.join("\n") + "\n" + body + (body.endsWith("\n") ? "" : "\n"), skipped };
|
|
218
|
+
}
|