agent-manifesto-kit 1.5.0 → 1.7.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 +38 -0
- package/collection/NOTICE.md +8 -0
- package/collection/bundles/blender-3d/README.md +7 -2
- package/collection/bundles/blender-3d/agents/visual-reviewer.md +8 -2
- package/collection/bundles/blender-3d/skills/blender-asset/SKILL.md +23 -1
- package/collection/bundles/blender-3d/skills/blender-asset/workflows/asset.yml +5 -0
- package/collection/bundles/blender-3d/skills/blender-mocap-retarget/SKILL.md +25 -0
- package/collection/bundles/blender-3d/skills/blender-reference-model/SKILL.md +52 -8
- package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/mesh_report.py +62 -8
- package/collection/skills/astro-preview/SKILL.md +60 -0
- package/collection/skills/kimodo-motion/SKILL.md +101 -0
- package/collection/skills/kimodo-motion/agents/openai.yaml +4 -0
- package/collection/skills/kimodo-motion/patches/kimodo-cpp-keyposes.patch +398 -0
- package/collection/skills/kimodo-motion/scripts/kimodo_motion.py +459 -0
- package/collection/skills/kimodo-motion/scripts/kimodo_retarget.py +280 -0
- package/collection/skills/kimodo-motion/tests/blender_roundtrip.py +105 -0
- package/collection/skills/kimodo-motion/tests/test_kimodo_motion.py +183 -0
- package/collection/skills/self-reflection/SKILL.md +121 -0
- package/collection/skills/self-reflection/agents/openai.yaml +4 -0
- package/collection/skills/self-reflection/assets/report-template.json +8 -0
- package/collection/skills/self-reflection/assets/report.html +64 -0
- package/collection/skills/self-reflection/references/report-format.md +42 -0
- package/collection/skills/self-reflection/scripts/export_claude.py +59 -0
- package/collection/skills/self-reflection/scripts/reflect.py +320 -0
- package/collection/skills/self-reflection/scripts/report.py +322 -0
- package/collection/skills/self-reflection/tests/test_export_claude.py +83 -0
- package/collection/skills/self-reflection/tests/test_reflect.py +189 -0
- package/collection/skills/self-reflection/tests/test_report.py +250 -0
- package/package.json +1 -1
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Local Codex JSONL inventory of unreviewed content; only finish advances reviewed byte offsets."""
|
|
3
|
+
import argparse
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
import fcntl
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import re
|
|
12
|
+
import tempfile
|
|
13
|
+
import uuid
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def atomic_json(path, data):
|
|
17
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent)
|
|
18
|
+
try:
|
|
19
|
+
with os.fdopen(fd, 'w') as f:
|
|
20
|
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
|
21
|
+
f.flush()
|
|
22
|
+
os.fsync(f.fileno())
|
|
23
|
+
os.replace(tmp, path)
|
|
24
|
+
finally:
|
|
25
|
+
if os.path.exists(tmp):
|
|
26
|
+
os.unlink(tmp)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@contextmanager
|
|
30
|
+
def locked(state_dir):
|
|
31
|
+
state_dir = Path(state_dir).resolve()
|
|
32
|
+
state_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
33
|
+
with (state_dir / 'lock').open('a') as lock:
|
|
34
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
35
|
+
yield state_dir
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_state(directory, project=None):
|
|
39
|
+
path = directory / 'state.json'
|
|
40
|
+
state = json.loads(path.read_text()) if path.exists() else {
|
|
41
|
+
'version': 1, 'project': str(project), 'sessions': {}, 'reports': []}
|
|
42
|
+
if state['version'] != 1 or (project and state['project'] != str(project)):
|
|
43
|
+
raise ValueError('State belongs to another project or unsupported version')
|
|
44
|
+
return state
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def digest(path, end):
|
|
48
|
+
h = hashlib.sha256()
|
|
49
|
+
with Path(path).open('rb') as f:
|
|
50
|
+
left = end
|
|
51
|
+
while left:
|
|
52
|
+
chunk = f.read(min(left, 1024 * 1024))
|
|
53
|
+
if not chunk:
|
|
54
|
+
raise ValueError('Log was truncated: ' + str(path))
|
|
55
|
+
h.update(chunk)
|
|
56
|
+
left -= len(chunk)
|
|
57
|
+
return h.hexdigest()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def records(path, start=0, end=None):
|
|
61
|
+
with Path(path).open('rb') as f:
|
|
62
|
+
f.seek(start)
|
|
63
|
+
while end is None or f.tell() < end:
|
|
64
|
+
offset = f.tell()
|
|
65
|
+
line = f.readline() if end is None else f.readline(end - offset)
|
|
66
|
+
if not line or not line.endswith(b'\n'):
|
|
67
|
+
break # A live writer may not have completed this record yet.
|
|
68
|
+
try:
|
|
69
|
+
value = json.loads(line)
|
|
70
|
+
if not isinstance(value, dict) or not isinstance(value.get('payload'), dict):
|
|
71
|
+
raise ValueError('Expected an event object with payload')
|
|
72
|
+
except (ValueError, UnicodeError) as error:
|
|
73
|
+
raise ValueError(f'Invalid record at {path}:{offset}: {error}') from error
|
|
74
|
+
yield offset, f.tell(), value
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def metadata(path):
|
|
78
|
+
first = next(records(path), None)
|
|
79
|
+
if not first or first[2].get('type') != 'session_meta':
|
|
80
|
+
raise ValueError('Missing complete Codex session_meta: ' + str(path))
|
|
81
|
+
meta = first[2]['payload']
|
|
82
|
+
if not meta.get('id') or not meta.get('cwd'):
|
|
83
|
+
raise ValueError('Session metadata needs id and cwd: ' + str(path))
|
|
84
|
+
return meta
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def parent_id(meta):
|
|
88
|
+
direct = meta.get('parent_thread_id') or meta.get('forked_from_id')
|
|
89
|
+
source = meta.get('source')
|
|
90
|
+
subagent = source.get('subagent') if isinstance(source, dict) else None
|
|
91
|
+
spawn = subagent.get('thread_spawn') if isinstance(subagent, dict) else None
|
|
92
|
+
return direct or (spawn.get('parent_thread_id') if isinstance(spawn, dict) else None)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def belongs(cwd, project):
|
|
96
|
+
return Path(cwd).resolve().is_relative_to(project)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def prepare(project, roots, state_dir, limit=None, session=None):
|
|
100
|
+
"""Freeze every not-yet-reviewed complete record of the project's sessions.
|
|
101
|
+
|
|
102
|
+
A session whose reviewed prefix already reaches its end contributes no range; a partly reviewed one
|
|
103
|
+
contributes only the bytes after its checkpoint. `limit` (records) and `session` (id or list of ids)
|
|
104
|
+
are deliberate narrowing, not the default."""
|
|
105
|
+
project = Path(project).resolve()
|
|
106
|
+
if not project.is_dir() or (limit is not None and limit < 1):
|
|
107
|
+
raise ValueError('Existing project and positive event limit required')
|
|
108
|
+
wanted = {session} if isinstance(session, str) else set(session or [])
|
|
109
|
+
with locked(state_dir) as directory:
|
|
110
|
+
state = load_state(directory, project)
|
|
111
|
+
found, warnings = {}, []
|
|
112
|
+
for root in roots:
|
|
113
|
+
root = Path(root).expanduser().resolve()
|
|
114
|
+
if not root.is_dir():
|
|
115
|
+
warnings.append('Unavailable log directory: ' + str(root))
|
|
116
|
+
continue
|
|
117
|
+
for path in sorted(root.rglob('*.jsonl')):
|
|
118
|
+
try:
|
|
119
|
+
meta = metadata(path)
|
|
120
|
+
except ValueError:
|
|
121
|
+
# A previously reviewed file must never silently disappear on corruption.
|
|
122
|
+
if any(s.get('path') == str(path) for s in state['sessions'].values()):
|
|
123
|
+
raise
|
|
124
|
+
warnings.append('Unrecognized/incomplete log: ' + str(path))
|
|
125
|
+
continue
|
|
126
|
+
if not belongs(meta['cwd'], project):
|
|
127
|
+
continue
|
|
128
|
+
sid = meta['id']
|
|
129
|
+
if sid in found and found[sid][0] != path:
|
|
130
|
+
raise ValueError('Duplicate session id; use non-overlapping log roots: ' + sid)
|
|
131
|
+
found[sid] = (path, meta)
|
|
132
|
+
ranges, inventory = [], []
|
|
133
|
+
remaining = limit # None: no cap
|
|
134
|
+
for sid, (path, meta) in sorted(found.items(), key=lambda pair: (pair[1][1].get('timestamp', ''), pair[0])):
|
|
135
|
+
old = state['sessions'].get(sid, {})
|
|
136
|
+
start = old.get('end', 0)
|
|
137
|
+
if old and digest(path, start) != old['sha256']:
|
|
138
|
+
raise ValueError('Reviewed prefix changed; preserve state and investigate: ' + sid)
|
|
139
|
+
size = path.stat().st_size
|
|
140
|
+
entry = {'session': sid, 'parent': parent_id(meta), 'created': meta.get('timestamp'),
|
|
141
|
+
'reviewed_bytes': start, 'available_bytes': size,
|
|
142
|
+
'status': 'reviewed' if start == size else 'pending'}
|
|
143
|
+
inventory.append(entry)
|
|
144
|
+
if (remaining is not None and remaining <= 0) or (wanted and sid not in wanted):
|
|
145
|
+
continue
|
|
146
|
+
end, count = start, 0
|
|
147
|
+
for _, stop, _ in records(path, start, size):
|
|
148
|
+
end, count = stop, count + 1
|
|
149
|
+
if remaining is not None and count >= remaining:
|
|
150
|
+
break
|
|
151
|
+
if count:
|
|
152
|
+
ranges.append({'session': sid, 'path': str(path), 'start': start, 'end': end,
|
|
153
|
+
'events': count, 'sha256': digest(path, end),
|
|
154
|
+
'parent': parent_id(meta),
|
|
155
|
+
'created': meta.get('timestamp')})
|
|
156
|
+
if remaining is not None:
|
|
157
|
+
remaining -= count
|
|
158
|
+
elif start < size:
|
|
159
|
+
entry['status'] = 'incomplete_tail' # only an unfinished last line is new; retried next time
|
|
160
|
+
missing = sorted(set(state['sessions']) - set(found))
|
|
161
|
+
warnings.extend('Previously reviewed session not found: ' + sid for sid in missing)
|
|
162
|
+
absent = sorted(wanted - set(found))
|
|
163
|
+
if absent:
|
|
164
|
+
raise ValueError('Requested session not found in project: ' + ', '.join(absent))
|
|
165
|
+
summary = {'sessions': len(inventory),
|
|
166
|
+
'with_new_content': len(ranges),
|
|
167
|
+
'already_reviewed': sum(1 for e in inventory if e['status'] == 'reviewed'),
|
|
168
|
+
'new_records': sum(r['events'] for r in ranges),
|
|
169
|
+
'new_bytes': sum(r['end'] - r['start'] for r in ranges),
|
|
170
|
+
'capped': limit is not None or bool(wanted)}
|
|
171
|
+
batch = {'version': 1, 'id': uuid.uuid4().hex, 'project': str(project),
|
|
172
|
+
'created': datetime.now(timezone.utc).isoformat(), 'summary': summary, 'ranges': ranges,
|
|
173
|
+
'inventory': inventory, 'warnings': warnings}
|
|
174
|
+
path = directory / ('batch-' + batch['id'] + '.json')
|
|
175
|
+
atomic_json(path, batch)
|
|
176
|
+
if not (directory / 'state.json').exists():
|
|
177
|
+
atomic_json(directory / 'state.json', state)
|
|
178
|
+
return {'batch': str(path), **batch}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def finish(state_dir, batch_path, report_path):
|
|
182
|
+
report = Path(report_path).read_text()
|
|
183
|
+
batch = json.loads(Path(batch_path).read_text())
|
|
184
|
+
structured = None
|
|
185
|
+
is_json = Path(report_path).suffix.lower() == '.json'
|
|
186
|
+
if is_json:
|
|
187
|
+
from report import validate
|
|
188
|
+
structured = json.loads(report)
|
|
189
|
+
elif not report.strip() or '|' not in report:
|
|
190
|
+
raise ValueError('A nonempty Markdown table report is required')
|
|
191
|
+
with locked(state_dir) as directory:
|
|
192
|
+
state = load_state(directory, batch['project'])
|
|
193
|
+
if is_json:
|
|
194
|
+
validate(structured, batch, state)
|
|
195
|
+
if batch.get('version') != 1 or not batch['ranges']:
|
|
196
|
+
raise ValueError('No review ranges or unsupported batch version')
|
|
197
|
+
for row in batch['ranges']:
|
|
198
|
+
old = state['sessions'].get(row['session'], {})
|
|
199
|
+
if old.get('end', 0) != row['start']:
|
|
200
|
+
raise ValueError('Stale batch; prepare again without overwriting newer review')
|
|
201
|
+
if row['end'] <= row['start'] or digest(row['path'], row['end']) != row['sha256']:
|
|
202
|
+
raise ValueError('Log changed since prepare; no checkpoint advanced')
|
|
203
|
+
# Report and all checkpoints share one atomic state write.
|
|
204
|
+
state['reports'].append({'batch': batch['id'], 'created': datetime.now(timezone.utc).isoformat(),
|
|
205
|
+
'ranges': batch['ranges'], **({'report': structured} if is_json else {'markdown': report})})
|
|
206
|
+
for row in batch['ranges']:
|
|
207
|
+
state['sessions'][row['session']] = {k: row[k] for k in ('end', 'sha256', 'path')}
|
|
208
|
+
atomic_json(directory / 'state.json', state)
|
|
209
|
+
return {'reviewed_ranges': len(batch['ranges']), 'state': str(directory / 'state.json')}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def redact(text):
|
|
213
|
+
text = re.sub(r'(?i)(bearer\s+)[\w.\-]+', r'\1[REDACTED]', text)
|
|
214
|
+
text = re.sub(r'\b(?:sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]{12,})\b', '[REDACTED]', text)
|
|
215
|
+
text = re.sub(r"""(?i)((?:["']?(?:api[_-]?key|access[_-]?token|password|secret)["']?)\s*[=:]\s*)("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;}]+)""", r'\1[REDACTED]', text)
|
|
216
|
+
text = re.sub(r'gAAAAA[A-Za-z0-9_=-]{60,}', '[OPAQUE ENCRYPTED VALUE]', text)
|
|
217
|
+
return re.sub(r'data:[^\s;]+;base64,[A-Za-z0-9+/=]+', '[BINARY DATA]', text)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def content_text(content):
|
|
221
|
+
if isinstance(content, list):
|
|
222
|
+
return '\n'.join(c.get('text', '') for c in content if isinstance(c, dict) and isinstance(c.get('text'), str))
|
|
223
|
+
return content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def evidence(batch_path, session, offset=None, limit=50, chars=2500, output_chars=None):
|
|
228
|
+
batch = json.loads(Path(batch_path).read_text())
|
|
229
|
+
row = next((r for r in batch['ranges'] if r['session'] == session), None)
|
|
230
|
+
if output_chars is None:
|
|
231
|
+
output_chars = chars
|
|
232
|
+
if row is None or limit < 1 or chars < 1 or output_chars < 1:
|
|
233
|
+
raise ValueError('Select a batch session and positive limits')
|
|
234
|
+
if digest(row['path'], row['end']) != row['sha256']:
|
|
235
|
+
raise ValueError('Log changed since prepare')
|
|
236
|
+
start = row['start'] if offset is None else offset
|
|
237
|
+
if not row['start'] <= start < row['end']:
|
|
238
|
+
raise ValueError('Offset is outside this batch range')
|
|
239
|
+
items, count, stop = [], 0, start
|
|
240
|
+
for begin, stop, event in records(row['path'], start, row['end']):
|
|
241
|
+
count += 1
|
|
242
|
+
payload, kind = event['payload'], event.get('type')
|
|
243
|
+
subtype = payload.get('type')
|
|
244
|
+
item = {'offset': begin, 'end': stop, 'timestamp': event.get('timestamp'), 'kind': kind,
|
|
245
|
+
'type': subtype}
|
|
246
|
+
# Copied pre-spawn history is context, not additional child work.
|
|
247
|
+
item['inherited_context'] = bool(row['parent'] and event.get('timestamp', '') < (row['created'] or ''))
|
|
248
|
+
if kind == 'response_item' and subtype in ('message', 'agent_message'):
|
|
249
|
+
item['role'] = payload.get('role', payload.get('author'))
|
|
250
|
+
item['channel'] = payload.get('channel')
|
|
251
|
+
content = payload.get('content', [])
|
|
252
|
+
text = content_text(content)
|
|
253
|
+
text = redact(text)
|
|
254
|
+
item['text'] = text[:chars]
|
|
255
|
+
item['truncated'] = len(text) > chars
|
|
256
|
+
elif kind == 'response_item' and subtype in ('function_call', 'custom_tool_call'):
|
|
257
|
+
item['tool'] = '.'.join(filter(None, [payload.get('namespace'), payload.get('name')]))
|
|
258
|
+
item['call_id'] = payload.get('call_id')
|
|
259
|
+
text = str(payload.get('arguments', payload.get('input', '')))
|
|
260
|
+
text = redact(text)
|
|
261
|
+
item['text'] = text[:chars]
|
|
262
|
+
item['truncated'] = len(text) > chars
|
|
263
|
+
elif kind == 'response_item' and subtype in ('function_call_output', 'custom_tool_call_output'):
|
|
264
|
+
item['call_id'] = payload.get('call_id')
|
|
265
|
+
text = content_text(payload.get('output', ''))
|
|
266
|
+
text = redact(text)
|
|
267
|
+
item['text'] = text[:output_chars]
|
|
268
|
+
item['truncated'] = len(text) > output_chars
|
|
269
|
+
elif kind == 'turn_context':
|
|
270
|
+
item['model'] = payload.get('model')
|
|
271
|
+
item['effort'] = payload.get('effort')
|
|
272
|
+
elif kind == 'event_msg' and subtype in ('task_started', 'task_complete'):
|
|
273
|
+
item['duration_ms'] = payload.get('duration_ms')
|
|
274
|
+
else:
|
|
275
|
+
# Do not emit instruction blobs, duplicate item_completed, reasoning or credentials.
|
|
276
|
+
continue
|
|
277
|
+
items.append(item)
|
|
278
|
+
if len(items) >= limit:
|
|
279
|
+
break
|
|
280
|
+
return {'session': session, 'start': start, 'next_offset': stop,
|
|
281
|
+
'done': stop == row['end'], 'records_scanned': count, 'items': items}
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def main():
|
|
285
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
286
|
+
sub = parser.add_subparsers(dest='command', required=True)
|
|
287
|
+
prep = sub.add_parser('prepare')
|
|
288
|
+
prep.add_argument('--project', type=Path, required=True)
|
|
289
|
+
prep.add_argument('--logs', type=Path, action='append', help='Codex JSONL directory; repeat for archives')
|
|
290
|
+
prep.add_argument('--state-dir', type=Path)
|
|
291
|
+
prep.add_argument('--limit', type=int, help='Deliberate cap on complete records (default: all unreviewed)')
|
|
292
|
+
prep.add_argument('--session', action='append', help='Restrict to this session id; repeatable (default: all)')
|
|
293
|
+
show = sub.add_parser('evidence')
|
|
294
|
+
show.add_argument('--batch', type=Path, required=True)
|
|
295
|
+
show.add_argument('--session', required=True)
|
|
296
|
+
show.add_argument('--offset', type=int)
|
|
297
|
+
show.add_argument('--limit', type=int, default=50)
|
|
298
|
+
show.add_argument('--chars', type=int, default=2500)
|
|
299
|
+
show.add_argument('--output-chars', type=int, help='Separate, usually smaller cap for tool outputs')
|
|
300
|
+
done = sub.add_parser('finish')
|
|
301
|
+
done.add_argument('--state-dir', type=Path, required=True)
|
|
302
|
+
done.add_argument('--batch', type=Path, required=True)
|
|
303
|
+
done.add_argument('--report', type=Path, required=True)
|
|
304
|
+
args = parser.parse_args()
|
|
305
|
+
try:
|
|
306
|
+
if args.command == 'prepare':
|
|
307
|
+
home = Path(os.environ.get('CODEX_HOME', Path.home() / '.codex'))
|
|
308
|
+
result = prepare(args.project, args.logs or [home / 'sessions', home / 'archived_sessions'],
|
|
309
|
+
args.state_dir or args.project / '.cache/self-reflection', args.limit, args.session)
|
|
310
|
+
elif args.command == 'evidence':
|
|
311
|
+
result = evidence(args.batch, args.session, args.offset, args.limit, args.chars, args.output_chars)
|
|
312
|
+
else:
|
|
313
|
+
result = finish(args.state_dir, args.batch, args.report)
|
|
314
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
315
|
+
except (ValueError, OSError, KeyError) as error:
|
|
316
|
+
parser.exit(1, f'Reflection stopped: {error}\n')
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
if __name__ == '__main__':
|
|
320
|
+
main()
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Deterministic metrics and offline HTML history for Self Reflection."""
|
|
3
|
+
import argparse
|
|
4
|
+
import copy
|
|
5
|
+
import hashlib
|
|
6
|
+
from datetime import datetime, timezone as utc
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import tempfile
|
|
11
|
+
from zoneinfo import ZoneInfo
|
|
12
|
+
|
|
13
|
+
from reflect import atomic_json, digest, load_state, locked, metadata, parent_id, records
|
|
14
|
+
|
|
15
|
+
ASSETS = Path(__file__).resolve().parents[1] / 'assets'
|
|
16
|
+
TOKEN_KEYS = ('input_tokens', 'cached_input_tokens', 'cache_write_input_tokens',
|
|
17
|
+
'output_tokens', 'reasoning_output_tokens', 'total_tokens')
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def timestamp(value):
|
|
21
|
+
parsed = datetime.fromisoformat(value.replace('Z', '+00:00'))
|
|
22
|
+
if parsed.tzinfo is None:
|
|
23
|
+
raise ValueError('Timestamp requires an explicit UTC offset')
|
|
24
|
+
return parsed
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def metrics(batch):
|
|
28
|
+
groups = {name: {'sessions': 0, 'tool_calls': None, 'tools': {}, 'usage_records': 0,
|
|
29
|
+
'tokens': None, 'ignored_usage_records': 0} for name in ('main', 'subagents')}
|
|
30
|
+
calls, usages = set(), {}
|
|
31
|
+
spawned = 0
|
|
32
|
+
for row in batch['ranges']:
|
|
33
|
+
if digest(row['path'], row['end']) != row['sha256']:
|
|
34
|
+
raise ValueError('Log changed since prepare')
|
|
35
|
+
meta = metadata(row['path'])
|
|
36
|
+
child = bool(meta.get('parent_thread_id') or isinstance(meta.get('source'), dict) and meta['source'].get('subagent'))
|
|
37
|
+
group = groups['subagents' if child else 'main']
|
|
38
|
+
group['sessions'] += 1
|
|
39
|
+
group['tool_calls'] = group['tool_calls'] or 0
|
|
40
|
+
# Seed IDs from the reviewed prefix without counting its work again.
|
|
41
|
+
for offset, _, event in records(row['path'], 0, row['end']):
|
|
42
|
+
p = event['payload']
|
|
43
|
+
if row.get('parent') or parent_id(meta) or child:
|
|
44
|
+
if not event.get('timestamp') or not row.get('created'):
|
|
45
|
+
continue
|
|
46
|
+
if timestamp(event['timestamp']) < timestamp(row['created']):
|
|
47
|
+
continue
|
|
48
|
+
if event.get('type') == 'response_item' and p.get('type') in ('function_call', 'custom_tool_call'):
|
|
49
|
+
key = (row['session'], p.get('call_id') or offset)
|
|
50
|
+
if key in calls:
|
|
51
|
+
continue
|
|
52
|
+
calls.add(key)
|
|
53
|
+
if offset < row['start']:
|
|
54
|
+
continue
|
|
55
|
+
name = '.'.join(filter(None, [p.get('namespace'), p.get('name')])) or 'unknown'
|
|
56
|
+
group['tool_calls'] += 1
|
|
57
|
+
group['tools'][name] = group['tools'].get(name, 0) + 1
|
|
58
|
+
spawned += name == 'collaboration.spawn_agent'
|
|
59
|
+
if event.get('type') != 'token_usage_record':
|
|
60
|
+
continue
|
|
61
|
+
usage = p.get('usage')
|
|
62
|
+
if p.get('thread_id') != row['session']:
|
|
63
|
+
continue
|
|
64
|
+
if not p.get('response_id') or not isinstance(usage, dict) or any(
|
|
65
|
+
type(usage.get(k)) is not int or usage[k] < 0 for k in TOKEN_KEYS):
|
|
66
|
+
group['ignored_usage_records'] += offset >= row['start']
|
|
67
|
+
continue
|
|
68
|
+
key = (row['session'], p['response_id'])
|
|
69
|
+
if key in usages:
|
|
70
|
+
if usages[key] != usage:
|
|
71
|
+
raise ValueError('Conflicting usage records for one response')
|
|
72
|
+
continue
|
|
73
|
+
usages[key] = usage
|
|
74
|
+
if offset < row['start']:
|
|
75
|
+
continue
|
|
76
|
+
group['usage_records'] += 1
|
|
77
|
+
if group['tokens'] is None:
|
|
78
|
+
group['tokens'] = dict.fromkeys(TOKEN_KEYS, 0)
|
|
79
|
+
for k in TOKEN_KEYS:
|
|
80
|
+
group['tokens'][k] += usage[k]
|
|
81
|
+
return {**groups, 'subagent_starts': spawned}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def coverage(batch):
|
|
85
|
+
return {'ranges': [{k: r.get(k) for k in ('session', 'start', 'end', 'events', 'parent')} for r in batch['ranges']],
|
|
86
|
+
'records': sum(r['events'] for r in batch['ranges']),
|
|
87
|
+
'inventory_sessions': len(batch.get('inventory', [])), 'warnings': batch.get('warnings', [])}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def preceding_state(state, batch):
|
|
91
|
+
reports = (state or {}).get('reports', [])
|
|
92
|
+
position = next((i for i, entry in enumerate(reports) if entry['batch'] == batch['id']), len(reports))
|
|
93
|
+
return {'reports': reports[:position]}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def continuity(state):
|
|
97
|
+
"""Derive pending review context from the archive, without a second task store."""
|
|
98
|
+
reports = (state or {}).get('reports', [])
|
|
99
|
+
episodes, recommendations = {}, {}
|
|
100
|
+
for entry in reports:
|
|
101
|
+
value = entry.get('report', {})
|
|
102
|
+
for episode in value.get('episodes', []):
|
|
103
|
+
episodes[episode['id']] = episode
|
|
104
|
+
for i, rec in enumerate(value.get('recommendations', []), 1):
|
|
105
|
+
identity = rec.get('id', f"{value['id']}:r{i}")
|
|
106
|
+
recommendations[identity] = {**rec, 'id': identity, 'report_id': value['id'],
|
|
107
|
+
'status': 'proposed', 'effect': 'not_checked', 'note': '',
|
|
108
|
+
'evidence': [], 'task_ref': None}
|
|
109
|
+
for check in value.get('followups', []):
|
|
110
|
+
identity = check['recommendation_id']
|
|
111
|
+
if identity not in recommendations:
|
|
112
|
+
raise ValueError('Unknown historical followup: ' + identity)
|
|
113
|
+
recommendations[identity].update({key: check[key] for key in ('status', 'effect', 'note', 'evidence', 'task_ref')})
|
|
114
|
+
unresolved = [r for r in recommendations.values() if r['status'] != 'dismissed' and not (
|
|
115
|
+
r['status'] == 'implemented' and r['effect'] in ('improved', 'unchanged', 'worsened'))]
|
|
116
|
+
return copy.deepcopy({'history_sha256': hashlib.sha256(json.dumps(reports, sort_keys=True).encode()).hexdigest(),
|
|
117
|
+
'open_episodes': [e for e in episodes.values() if e['status'] == 'open'],
|
|
118
|
+
'pending_recommendations': unresolved})
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def draft(batch, timezone='UTC', state=None):
|
|
122
|
+
ZoneInfo(timezone)
|
|
123
|
+
context = continuity(preceding_state(state, batch))
|
|
124
|
+
value = {'version': 2, 'id': batch['id'], 'created_at': datetime.now(utc.utc).isoformat(),
|
|
125
|
+
'timezone': timezone, 'project': batch['project'], 'coverage': coverage(batch),
|
|
126
|
+
'metrics': metrics(batch), 'continuity': context,
|
|
127
|
+
**json.loads((ASSETS / 'report-template.json').read_text())}
|
|
128
|
+
value['episodes'] = copy.deepcopy(context['open_episodes'])
|
|
129
|
+
value['followups'] = [{'recommendation_id': r['id'], 'status': r['status'], 'effect': 'not_checked',
|
|
130
|
+
'note': '', 'evidence': [], 'task_ref': r['task_ref']}
|
|
131
|
+
for r in context['pending_recommendations']]
|
|
132
|
+
return value
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def text_fields(item, fields, label):
|
|
136
|
+
if not isinstance(item, dict) or any(not isinstance(item.get(k), str) or not item[k].strip() for k in fields):
|
|
137
|
+
raise ValueError('Incomplete ' + label)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def evidence_list(item, required=False):
|
|
141
|
+
evidence = item.get('evidence')
|
|
142
|
+
if not isinstance(evidence, list) or any(not isinstance(x, str) or not x.strip() for x in evidence) or (required and not evidence):
|
|
143
|
+
raise ValueError('Expected evidence locators')
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def identities(items, key, label):
|
|
147
|
+
if not isinstance(items, list):
|
|
148
|
+
raise ValueError('Expected list: ' + label)
|
|
149
|
+
for item in items:
|
|
150
|
+
text_fields(item, [key], label)
|
|
151
|
+
keys = [item[key] for item in items]
|
|
152
|
+
if len(keys) != len(set(keys)):
|
|
153
|
+
raise ValueError('Duplicate ' + label + ' identity')
|
|
154
|
+
return set(keys)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def validate_continuity(value, state):
|
|
158
|
+
context = value.get('continuity')
|
|
159
|
+
if not isinstance(context, dict) or not isinstance(context.get('history_sha256'), str):
|
|
160
|
+
raise ValueError('Missing continuity snapshot')
|
|
161
|
+
expected_episodes = identities(context.get('open_episodes'), 'id', 'episode context')
|
|
162
|
+
expected_checks = identities(context.get('pending_recommendations'), 'id', 'followup context')
|
|
163
|
+
episodes = identities(value.get('episodes'), 'id', 'episode')
|
|
164
|
+
checks = identities(value.get('followups'), 'recommendation_id', 'followup')
|
|
165
|
+
recs = identities(value['recommendations'], 'id', 'recommendation')
|
|
166
|
+
if not expected_episodes <= episodes:
|
|
167
|
+
raise ValueError('Every open episode needs an explicit update')
|
|
168
|
+
if checks != expected_checks:
|
|
169
|
+
raise ValueError('Every pending recommendation needs exactly one followup')
|
|
170
|
+
if recs & expected_checks:
|
|
171
|
+
raise ValueError('Use followups for previous recommendations, not new proposals')
|
|
172
|
+
for item in value['episodes']:
|
|
173
|
+
text_fields(item, ['title', 'status', 'outcome'], 'episode')
|
|
174
|
+
if item['status'] not in ('open', 'closed') or not isinstance(item.get('next_review'), str):
|
|
175
|
+
raise ValueError('Invalid episode status or next_review')
|
|
176
|
+
if item['status'] == 'open' and not item['next_review'].strip():
|
|
177
|
+
raise ValueError('Open episode needs next_review')
|
|
178
|
+
evidence_list(item, required=True)
|
|
179
|
+
for item in value['recommendations']:
|
|
180
|
+
text_fields(item, ['target', 'proposed_change'], 'concrete recommendation')
|
|
181
|
+
for item in value['followups']:
|
|
182
|
+
if set(item) != {'recommendation_id', 'status', 'effect', 'note', 'evidence', 'task_ref'}:
|
|
183
|
+
raise ValueError('Unexpected or missing followup fields')
|
|
184
|
+
text_fields(item, ['status', 'effect', 'note'], 'followup')
|
|
185
|
+
if item['status'] not in ('proposed', 'accepted', 'implemented', 'dismissed') or item['effect'] not in (
|
|
186
|
+
'not_checked', 'insufficient_data', 'improved', 'unchanged', 'worsened'):
|
|
187
|
+
raise ValueError('Invalid followup status or effect')
|
|
188
|
+
if item.get('task_ref') is not None and (not isinstance(item['task_ref'], str) or not item['task_ref'].strip()):
|
|
189
|
+
raise ValueError('task_ref must be a tracker reference or null')
|
|
190
|
+
evidence_list(item, required=item['status'] != 'proposed' or item['effect'] in ('improved', 'unchanged', 'worsened'))
|
|
191
|
+
if item['effect'] in ('improved', 'unchanged', 'worsened') and item['status'] != 'implemented':
|
|
192
|
+
raise ValueError('Measured effect requires implemented status')
|
|
193
|
+
if state is not None:
|
|
194
|
+
if context != continuity(state):
|
|
195
|
+
raise ValueError('Stale or changed continuity snapshot; regenerate draft')
|
|
196
|
+
for entry in state.get('reports', []):
|
|
197
|
+
prior = entry.get('report', {})
|
|
198
|
+
prior_recs = {r.get('id', f"{prior['id']}:r{i}") for i, r in enumerate(prior.get('recommendations', []), 1)}
|
|
199
|
+
if recs & prior_recs:
|
|
200
|
+
raise ValueError('Recommendation identity already exists in history')
|
|
201
|
+
closed = {e['id'] for e in prior.get('episodes', [])} - expected_episodes
|
|
202
|
+
if episodes & closed:
|
|
203
|
+
raise ValueError('Closed episode identity cannot be reused')
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def validate(value, batch=None, state=None):
|
|
207
|
+
if not isinstance(value, dict) or value.get('version') not in (1, 2):
|
|
208
|
+
raise ValueError('Expected report version 1 or 2')
|
|
209
|
+
for key in ('id', 'created_at', 'timezone', 'project', 'summary'):
|
|
210
|
+
if not isinstance(value.get(key), str) or not value[key].strip():
|
|
211
|
+
raise ValueError('Required nonempty report text: ' + key)
|
|
212
|
+
timestamp(value['created_at'])
|
|
213
|
+
ZoneInfo(value['timezone'])
|
|
214
|
+
if not isinstance(value.get('coverage'), dict) or not isinstance(value.get('metrics'), dict):
|
|
215
|
+
raise ValueError('Coverage and metrics are required')
|
|
216
|
+
for key in ('coverage_notes', 'findings', 'recommendations'):
|
|
217
|
+
if not isinstance(value.get(key), list):
|
|
218
|
+
raise ValueError('Required report list: ' + key)
|
|
219
|
+
if any(not isinstance(x, str) or not x.strip() for x in value['coverage_notes']):
|
|
220
|
+
raise ValueError('Coverage notes must be nonempty strings')
|
|
221
|
+
for kind, fields in [('findings', ('priority', 'area', 'observation', 'effect', 'confidence')),
|
|
222
|
+
('recommendations', ('priority', 'action', 'validation'))]:
|
|
223
|
+
for item in value[kind]:
|
|
224
|
+
if not isinstance(item, dict) or any(not isinstance(item.get(k), str) or not item[k].strip() for k in fields):
|
|
225
|
+
raise ValueError('Incomplete ' + kind + ' entry')
|
|
226
|
+
if item['priority'] not in ('P1', 'P2', 'P3', 'keep'):
|
|
227
|
+
raise ValueError('Priority must be P1, P2, P3 or keep')
|
|
228
|
+
if kind == 'findings':
|
|
229
|
+
if item['confidence'] not in ('high', 'medium', 'low'):
|
|
230
|
+
raise ValueError('Confidence must be high, medium or low')
|
|
231
|
+
if not isinstance(item.get('evidence'), list) or not item['evidence'] or any(
|
|
232
|
+
not isinstance(x, str) or not x.strip() for x in item['evidence']):
|
|
233
|
+
raise ValueError('Each finding needs evidence locators')
|
|
234
|
+
if value['version'] == 2:
|
|
235
|
+
validate_continuity(value, state)
|
|
236
|
+
if batch is not None:
|
|
237
|
+
expected = {'id': batch['id'], 'project': batch['project'], 'coverage': coverage(batch), 'metrics': metrics(batch)}
|
|
238
|
+
for key, content in expected.items():
|
|
239
|
+
if value.get(key) != content:
|
|
240
|
+
raise ValueError('Generated report field changed: ' + key)
|
|
241
|
+
return value
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def build(state_dir):
|
|
245
|
+
with locked(state_dir) as directory:
|
|
246
|
+
if not (directory / 'state.json').is_file():
|
|
247
|
+
raise ValueError('No reflection state found')
|
|
248
|
+
state = load_state(directory)
|
|
249
|
+
history = []
|
|
250
|
+
for entry in state['reports']:
|
|
251
|
+
if 'report' in entry:
|
|
252
|
+
history.append(validate(entry['report']))
|
|
253
|
+
else:
|
|
254
|
+
history.append({'id': entry['batch'], 'created_at': entry['created'], 'timezone': 'UTC',
|
|
255
|
+
'project': state['project'], 'legacy': entry['markdown']})
|
|
256
|
+
history.sort(key=lambda r: (timestamp(r['created_at']), r['id']), reverse=True)
|
|
257
|
+
payload = json.dumps(history, ensure_ascii=False).replace('<', '\\u003c').replace('>', '\\u003e').replace('&', '\\u0026')
|
|
258
|
+
html = (ASSETS / 'report.html').read_text().replace('<!--REPORT_DATA-->', payload)
|
|
259
|
+
output = directory / 'site/index.html'
|
|
260
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
261
|
+
fd, tmp = tempfile.mkstemp(dir=output.parent)
|
|
262
|
+
try:
|
|
263
|
+
with os.fdopen(fd, 'w') as f:
|
|
264
|
+
f.write(html)
|
|
265
|
+
os.replace(tmp, output)
|
|
266
|
+
finally:
|
|
267
|
+
if os.path.exists(tmp):
|
|
268
|
+
os.unlink(tmp)
|
|
269
|
+
return output
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def attach(state_dir, batch_path, report_path):
|
|
273
|
+
"""Add a structured rendition to an already acknowledged report without moving cursors."""
|
|
274
|
+
batch = json.loads(Path(batch_path).read_text())
|
|
275
|
+
value = json.loads(Path(report_path).read_text())
|
|
276
|
+
with locked(state_dir) as directory:
|
|
277
|
+
state = load_state(directory, batch['project'])
|
|
278
|
+
entry = next((r for r in state['reports'] if r['batch'] == batch['id']), None)
|
|
279
|
+
if entry is None or entry['ranges'] != batch['ranges']:
|
|
280
|
+
raise ValueError('Only an already reviewed matching batch can be attached')
|
|
281
|
+
if 'report' in entry:
|
|
282
|
+
raise ValueError('Structured report already exists; preserve it')
|
|
283
|
+
validate(value, batch, preceding_state(state, batch))
|
|
284
|
+
entry['report'] = value
|
|
285
|
+
atomic_json(directory / 'state.json', state)
|
|
286
|
+
return build(state_dir)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def main():
|
|
290
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
291
|
+
sub = parser.add_subparsers(dest='command', required=True)
|
|
292
|
+
d = sub.add_parser('draft')
|
|
293
|
+
d.add_argument('--batch', type=Path, required=True)
|
|
294
|
+
d.add_argument('--timezone', default='UTC')
|
|
295
|
+
d.add_argument('--state-dir', type=Path, help='Existing archive; defaults to the batch directory')
|
|
296
|
+
d.add_argument('--output', type=Path, required=True)
|
|
297
|
+
b = sub.add_parser('build')
|
|
298
|
+
b.add_argument('--state-dir', type=Path, required=True)
|
|
299
|
+
a = sub.add_parser('attach')
|
|
300
|
+
a.add_argument('--state-dir', type=Path, required=True)
|
|
301
|
+
a.add_argument('--batch', type=Path, required=True)
|
|
302
|
+
a.add_argument('--report', type=Path, required=True)
|
|
303
|
+
args = parser.parse_args()
|
|
304
|
+
try:
|
|
305
|
+
if args.command == 'draft':
|
|
306
|
+
batch = json.loads(args.batch.read_text())
|
|
307
|
+
with locked(args.state_dir or args.batch.parent) as directory:
|
|
308
|
+
state = load_state(directory, batch['project'])
|
|
309
|
+
value = draft(batch, args.timezone, state)
|
|
310
|
+
with args.output.open('x') as f:
|
|
311
|
+
json.dump(value, f, ensure_ascii=False, indent=2)
|
|
312
|
+
print(args.output.resolve())
|
|
313
|
+
elif args.command == 'attach':
|
|
314
|
+
print(attach(args.state_dir, args.batch, args.report))
|
|
315
|
+
else:
|
|
316
|
+
print(build(args.state_dir))
|
|
317
|
+
except (ValueError, OSError, KeyError) as error:
|
|
318
|
+
parser.exit(1, f'Report stopped: {error}\n')
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
if __name__ == '__main__':
|
|
322
|
+
main()
|