agent-manifesto-kit 1.3.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.
@@ -0,0 +1,117 @@
1
+ """Stop hook for Claude Code and Codex: suggest a retro when a session shows improvement signals.
2
+
3
+ Registered by install_hooks.py as: python3 <this file> --provider claude|codex
4
+
5
+ Both tools send the same JSON on stdin (session_id, transcript_path, cwd, stop_hook_active) and
6
+ accept {"systemMessage": ...} as a non-blocking notice to the user. The hook:
7
+ - never blocks the agent and never runs a model; every failure, including bad flags, exits 0
8
+ - caches only counters (no prompt text) with owner-only permissions
9
+ - reads only the log lines added since its last call (state in the user cache directory)
10
+ - stays quiet until the session is significant (--min-tool-calls), then nudges at most once per
11
+ session when a threshold is crossed
12
+
13
+ Thresholds are flags so a project can tune them in its hook command. Stop fires after every
14
+ agent turn, which is why the state and the once-per-session rule matter.
15
+ """
16
+ import argparse
17
+ import contextlib
18
+ import io
19
+ import json
20
+ import os
21
+ import sys
22
+ import time
23
+
24
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
25
+ from session_digest import Digest, locate, read_from # noqa: E402
26
+
27
+
28
+ def state_dir():
29
+ base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
30
+ return os.path.join(base, "agentkit-retro")
31
+
32
+
33
+ def prune(folder, days=14):
34
+ """Drop state for sessions untouched for two weeks; one small file per session otherwise piles up."""
35
+ cutoff = time.time() - days * 86400
36
+ for name in os.listdir(folder):
37
+ path = os.path.join(folder, name)
38
+ if name.endswith(".json") and os.path.getmtime(path) < cutoff:
39
+ os.remove(path)
40
+
41
+
42
+ def crossed(sig, args):
43
+ reasons = []
44
+ if sig["failed"] >= args.failed:
45
+ reasons.append(f"{sig['failed']} failed commands or tool calls")
46
+ if sig["repeat_fail"][1] >= args.repeat_fail:
47
+ reasons.append(f"`{sig['repeat_fail'][0]}` failed {sig['repeat_fail'][1]} times")
48
+ if sig["inline_scripts"] >= args.inline:
49
+ reasons.append(f"{sig['inline_scripts']} ad-hoc inline scripts")
50
+ if sig["churn"][1] >= args.churn:
51
+ reasons.append(f"`{os.path.basename(sig['churn'][0])}` edited {sig['churn'][1]} times")
52
+ if sig["corrections"] >= args.corrections:
53
+ reasons.append(f"{sig['corrections']} likely corrections from you")
54
+ return reasons
55
+
56
+
57
+ def run(args, payload):
58
+ session = payload.get("session_id")
59
+ if payload.get("stop_hook_active") or not session:
60
+ return None
61
+ os.makedirs(state_dir(), mode=0o700, exist_ok=True)
62
+ prune(state_dir())
63
+ state_file = os.path.join(state_dir(), f"{args.provider}-{session}.json")
64
+ state = {}
65
+ if os.path.exists(state_file):
66
+ with open(state_file, encoding="utf-8") as f:
67
+ state = json.load(f)
68
+ if state.get("nudged"):
69
+ return None
70
+ path = payload.get("transcript_path") or state.get("transcript") or locate(args.provider, payload.get("cwd"), session)
71
+ if not path or not os.path.exists(path):
72
+ return None
73
+ reset = state.get("transcript") != path or os.path.getsize(path) < state.get("offset", 0)
74
+ digest = Digest.from_state(state["digest"]) if state.get("digest") and not reset else Digest(args.provider)
75
+ offset = read_from(path, digest, 0 if reset else state.get("offset", 0))
76
+ sig = digest.signals()
77
+ reasons = crossed(sig, args) if sig["tool_calls"] >= args.min_tool_calls else []
78
+ state = {"transcript": path, "offset": offset, "digest": digest.slim_state(), "nudged": bool(reasons),
79
+ "updated": time.time()}
80
+ tmp = state_file + ".tmp"
81
+ with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w", encoding="utf-8") as f:
82
+ json.dump(state, f)
83
+ os.replace(tmp, state_file)
84
+ if not reasons:
85
+ return None
86
+ return ("Retro suggested for this session: " + "; ".join(reasons) +
87
+ '. When the task is done, ask for a retro (session-retro skill) to turn this into scripts or skill fixes.')
88
+
89
+
90
+ def build_parser():
91
+ p = argparse.ArgumentParser(prog="retro_hook.py", allow_abbrev=False)
92
+ p.add_argument("--provider", choices=["claude", "codex"], required=True)
93
+ p.add_argument("--min-tool-calls", type=int, default=40)
94
+ p.add_argument("--failed", type=int, default=10)
95
+ p.add_argument("--repeat-fail", type=int, default=4)
96
+ p.add_argument("--inline", type=int, default=8)
97
+ p.add_argument("--churn", type=int, default=8)
98
+ p.add_argument("--corrections", type=int, default=2)
99
+ return p
100
+
101
+
102
+ def main():
103
+ # Exit 2 from a Stop hook means "block and continue" in both tools, so no path may exit non-zero:
104
+ # bad flags, bad input and internal errors all end silently with 0.
105
+ try:
106
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
107
+ args = build_parser().parse_args()
108
+ message = run(args, json.load(sys.stdin))
109
+ except BaseException:
110
+ return 0
111
+ if message:
112
+ print(json.dumps({"systemMessage": message}))
113
+ return 0
114
+
115
+
116
+ if __name__ == "__main__":
117
+ sys.exit(main())
@@ -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())
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ import { adopt, isSupportedCli, SUPPORTED_CLIS } from "./commands/adopt.js";
6
6
  import { runLint } from "./commands/lint.js";
7
7
  import { ingest } from "./commands/ingest.js";
8
8
  import { sync, SYNC_PROVIDERS } from "./commands/sync.js";
9
+ import { update } from "./commands/update.js";
9
10
  import { isProvider } from "./providers.js";
10
11
  import { packageRoot } from "./catalog.js";
11
12
  function version() {
@@ -19,24 +20,40 @@ function version() {
19
20
  }
20
21
  /** Flags that never take a value, so a following positional is not swallowed. */
21
22
  const BOOLEAN_FLAGS = new Set(["force", "replace", "dry-run", "help", "version"]);
23
+ const VALUE_FLAGS = new Set(["provider", "dest", "cli", "bundle", "kit", "remove"]);
22
24
  function parseArgs(args) {
23
25
  const positionals = [];
24
26
  const flags = {};
25
27
  for (let i = 0; i < args.length; i++) {
26
28
  const arg = args[i];
27
29
  if (arg.startsWith("--")) {
28
- const key = arg.slice(2);
30
+ const equal = arg.indexOf("=");
31
+ const key = arg.slice(2, equal === -1 ? undefined : equal);
32
+ if (equal !== -1) {
33
+ const value = arg.slice(equal + 1);
34
+ if (BOOLEAN_FLAGS.has(key))
35
+ throw new Error(`--${key} does not take a value.`);
36
+ if (!value)
37
+ throw new Error(`--${key} needs a value.`);
38
+ flags[key] = value;
39
+ continue;
40
+ }
29
41
  const next = args[i + 1];
30
42
  if (!BOOLEAN_FLAGS.has(key) && next !== undefined && !next.startsWith("-")) {
31
43
  flags[key] = next;
32
44
  i++;
33
45
  }
34
46
  else {
47
+ if (VALUE_FLAGS.has(key))
48
+ throw new Error(`--${key} needs a value.`);
35
49
  flags[key] = true;
36
50
  }
37
51
  }
38
52
  else if (arg.length > 1 && arg.startsWith("-")) {
39
- flags[arg.slice(1)] = true;
53
+ const key = arg.slice(1);
54
+ if (VALUE_FLAGS.has(key))
55
+ throw new Error(`Unknown option "${arg}". Use "--${key} <value>".`);
56
+ flags[key] = true;
40
57
  }
41
58
  else {
42
59
  positionals.push(arg);
@@ -48,6 +65,7 @@ function help() {
48
65
  console.log(`agentkit - discover and adopt Agent Manifesto Kit capabilities
49
66
 
50
67
  Usage:
68
+ agentkit update
51
69
  agentkit list [skills|agents|bundles]
52
70
  agentkit lint [name]
53
71
  agentkit adopt <name> [--provider claude|codex|agnostic] [--dest <dir>] [--force] [--cli <cli>]
@@ -59,6 +77,9 @@ Usage:
59
77
 
60
78
  list accepts one exact lowercase selector. Without a selector it shows the full catalog.
61
79
 
80
+ update installs agent-manifesto-kit@latest globally using npm. Run sync separately
81
+ in each project to refresh installed skills and agents.
82
+
62
83
  ingest imports a skill folder (SKILL.md), a Claude agent .md, or a Codex agent .toml
63
84
  into the kit's collection/ as a canonical Claude-style capability.
64
85
 
@@ -102,11 +123,26 @@ async function main() {
102
123
  case "help":
103
124
  help();
104
125
  return 0;
126
+ case "update":
127
+ if (positionals.length !== 1 || Object.keys(flags).length !== 0) {
128
+ console.error('update takes no arguments or options. Run "agentkit update".');
129
+ return 1;
130
+ }
131
+ return update();
105
132
  case "list":
106
133
  return list(positionals.slice(1), flags);
107
134
  case "lint":
108
135
  return runLint(positionals[1]);
109
136
  case "adopt": {
137
+ const unknown = Object.keys(flags).find((key) => !["provider", "dest", "force", "cli"].includes(key));
138
+ if (unknown) {
139
+ console.error(`adopt: unknown option "--${unknown}". Use "--help" for help.`);
140
+ return 1;
141
+ }
142
+ if (positionals.length > 2) {
143
+ console.error('adopt requires exactly one <name>. Use "--provider codex" or "--provider=codex" to select Codex.');
144
+ return 1;
145
+ }
110
146
  const name = positionals[1];
111
147
  if (!name) {
112
148
  console.error('adopt requires a <name>. Run "agentkit list" to see options.');