oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Equipo's pinned Copy adapter. JSON on stdin and stdout."""
3import ast
4import hashlib
5import json
6from pathlib import Path
7import re
8import sys
9import subprocess
10import tempfile
11import shutil
12
13COPY = 'internal/equipo/copy.go'
14INVENTORY = 'docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md'
15HEADING = "## Plan 3 copy inventory (for Paul's review)"
16LITERAL = r'"(?:[^"\\\n]|\\.)*"|`[^`]*`'
17ENTRY = re.compile(r'(?m)^\s*(?:(?P<map>"[^"\n]+")\s*:|(?:const[ \t]+)?(?P<const>[A-Za-z_]\w*)\s*=)\s*(?P<value>' + LITERAL + r')')
18MARKER = re.compile(r'\s*// COPY (?:ACCEPTED|APPROVED|REVIEW)[^\n]*')
19
20
21def decode(raw):
22 return raw[1:-1] if raw.startswith('`') else ast.literal_eval(raw)
23
24
25def map_ranges(text):
26 return [(m.end(), text.find('\n}', m.end()), m[1]) for m in
27 re.finditer(r'(?m)^var ([A-Za-z_]\w*)\s*=\s*map\[string\]string\{', text)]
28
29
30def qualify(ranges, key, offset):
31 for start, end, name in ranges:
32 if start <= offset < end:
33 return key if name == 'pageCopy' else name + '.' + key
34 return key
35
36
37def entries(text):
38 out = {}
39 ranges = map_ranges(text)
40 for m in ENTRY.finditer(text):
41 key = qualify(ranges, json.loads(m['map']), m.start()) if m['map'] else m['const']
42 if key in out:
43 raise ValueError('duplicate copy key: ' + key)
44 out[key] = (m, decode(m['value']))
45 return out
46
47
48def read(root):
49 p = Path(root) / COPY
50 if p.is_symlink():
51 raise ValueError('symlink copy file')
52 return p.read_text() if p.exists() else ''
53
54
55def extract(v):
56 old_text, text = read(v['base']), read(v['candidate'])
57 old, new = entries(old_text), entries(text)
58 key_lines = re.compile(r'(?m)^\s*("[^"\n]+")\s*:\s*([^\n]+)')
59 old_ranges, new_ranges = map_ranges(old_text), map_ranges(text)
60 before_lines = {qualify(old_ranges, json.loads(m[1]), m.start()): m[2] for m in key_lines.finditer(old_text)}
61 for match in key_lines.finditer(text):
62 key = qualify(new_ranges, json.loads(match[1]), match.start())
63 if key not in new and before_lines.get(key) != match[2]:
64 raise ValueError('changed computed copy needs an explicit literal: ' + key)
65 for key, (match, value) in new.items():
66 tail = text[match.end():].split('\n', 1)[0].lstrip()
67 if tail and not tail.startswith((',', '//', ')')):
68 raise ValueError('composed copy needs an explicit literal: ' + key)
69 strings = []
70 for key, (m, value) in new.items():
71 before = old.get(key, (None, None))[1]
72 if before == value:
73 continue
74 strings.append(dict(key=key, path=COPY, start=len(text[:m.start('value') + 1].encode()),
75 end=len(text[:m.end('value') - 1].encode()), old=before or '',
76 text=value, context=key))
77 return dict(version=1, strings=strings)
78
79
80def recover(root):
81 journal = root / '.equipo/copy-journal.json'
82 if journal.exists():
83 values = json.loads(journal.read_text())
84 if set(values) - {COPY, INVENTORY}:
85 raise ValueError('invalid journal')
86 for name, text in values.items():
87 target = root / name
88 if target.is_symlink():
89 raise ValueError('symlink output')
90 target.write_text(text)
91 journal.unlink()
92
93
94def replace_files(root, values):
95 journal = root / '.equipo/copy-journal.json'
96 journal.parent.mkdir(parents=True, exist_ok=True)
97 journal.write_text(json.dumps(values, ensure_ascii=False))
98 recover(root)
99
100
101def format_go(paths):
102 binary = '/opt/go/bin/gofmt' if Path('/opt/go/bin/gofmt').exists() else shutil.which('gofmt')
103 if not binary:
104 raise ValueError('gofmt unavailable')
105 subprocess.run([binary, '-w', *map(str, paths)], check=True, capture_output=True, timeout=20)
106
107
108def apply(v):
109 root = Path(v['candidate'])
110 text = read(root)
111 found = entries(text)
112 changed = {s['key']: s for s in v['extraction']['strings']}
113 reviewed = v['review']['strings']
114 if len(reviewed) != len(changed) or len({w['key'] for w in reviewed}) != len(reviewed):
115 raise ValueError('incomplete review')
116 replacements = []
117 pairs = {}
118 for w in reviewed:
119 key = w['key']
120 if key not in changed or key not in found or w['action'] != 'accept':
121 raise ValueError('unreviewed key or question')
122 m, before = found[key]
123 if before != changed[key]['text']:
124 raise ValueError('stale text')
125 replacements.append((m.start('value'), m.end('value'), json.dumps(w['text'], ensure_ascii=False)))
126 if before in pairs and pairs[before] != w['text']:
127 raise ValueError('conflicting test replacements')
128 pairs[before] = w['text']
129 for start, end, value in sorted(replacements, reverse=True):
130 text = text[:start] + value + text[end:]
131 (root / COPY).write_text(text)
132 formatted = [root / COPY]
133 # Match complete quoted literals; never replace substrings in assertions.
134 for path in root.rglob('*_test.go'):
135 if path.is_symlink() or any(p in ('vendor', '.git') for p in path.parts):
136 continue
137 before = path.read_text()
138 after = re.sub(r'//[^\n]*|/\*[\s\S]*?\*/|' + LITERAL,
139 lambda m: m[0] if m[0].startswith(('//', '/*')) else
140 json.dumps(pairs[decode(m[0])], ensure_ascii=False) if decode(m[0]) in pairs else m[0], before)
141 if before != after:
142 path.write_text(after)
143 formatted.append(path)
144 format_go(formatted)
145 return dict(version=1)
146
147
148def status(v, mode):
149 root = Path(v['candidate'])
150 if mode == 'pending' and 'recovery' in v:
151 recovery = v['recovery']
152 if 'old_path' in recovery:
153 recovery = {name: Path(recovery[name + '_path']).read_text() for name in ('old', 'tooling', 'candidate')}
154 def clean(text):
155 return MARKER.sub('', text)
156 with tempfile.TemporaryDirectory(dir=root) as scratch:
157 paths = []
158 for name in ('tooling', 'old', 'candidate'):
159 file = Path(scratch) / name
160 file.write_text(clean(recovery[name]))
161 paths.append(str(file))
162 result = subprocess.run(['/usr/bin/git', 'merge-file', '-p', *paths], capture_output=True, timeout=10)
163 if result.returncode:
164 raise ValueError('copy meaning conflict needs owner')
165 merged = result.stdout.decode()
166 # Restore unchanged human provenance from the trusted tooling revision.
167 original = entries(recovery['tooling'])
168 for key, (m, value) in sorted(entries(merged).items(), key=lambda item: item[1][0].start(), reverse=True):
169 if key not in original or original[key][1] != value:
170 continue
171 old_match = original[key][0]
172 old_end = recovery['tooling'].find('\n', old_match.end())
173 annotation = MARKER.search(recovery['tooling'][old_match.start():old_end])
174 if annotation:
175 end = merged.find('\n', m.end())
176 merged = merged[:end] + annotation[0] + merged[end:]
177 (root / COPY).write_text(merged)
178 v['keys'] = [key for key, (_, value) in entries(merged).items()
179 if key not in original or original[key][1] != value]
180
181 if mode == 'verify':
182 text = read(root)
183 inventory = (root / INVENTORY).read_text()
184 valid = not (root / '.equipo/copy-journal.json').exists()
185 valid = valid and not re.search(r'COPY REVIEW (?:PENDING|REQUIRED)', text)
186 for key, (m, value) in entries(text).items():
187 end = text.find('\n', m.end())
188 if 'COPY ACCEPTED BY DELEGATION (Copy, record-bound)' not in text[m.start():end]:
189 continue
190 rows = [line for line in inventory.splitlines() if line.startswith('| `' + key + '` |')]
191 digest = hashlib.sha256(value.encode()).hexdigest()
192 valid = valid and len(rows) == 1 and rows[0].endswith('sha256:' + digest + ' |')
193 return dict(version=1, valid=bool(valid))
194 recover(root)
195 text = read(root)
196 found = entries(text)
197 keys = v.get('keys', [])
198 if len(set(keys)) != len(keys) or any(k not in found for k in keys):
199 raise ValueError('unknown or duplicate keys')
200 records = {r['key']: r for r in v.get('records', [])}
201 changed = set(v.get('changed', []))
202 marker = 'COPY REVIEW PENDING'
203 if mode == 'accept':
204 if not keys or not set(keys) <= changed or not set(keys) <= set(records):
205 raise ValueError('acceptance is outside reviewed changed set')
206 for key in keys:
207 r = records[key]
208 if r.get('hash') != hashlib.sha256(found[key][1].encode()).hexdigest() or not r.get('owner') or not r.get('candidate') or not r.get('revision'):
209 raise ValueError('stale acceptance')
210 marker = 'COPY ACCEPTED BY DELEGATION (Copy, record-bound)'
211 inv_path = root / INVENTORY
212 inventory = inv_path.read_text()
213 if HEADING not in inventory:
214 raise ValueError('inventory missing')
215 prefix, section = inventory.split(HEADING, 1)
216 section, sep, suffix = section.partition('\n## ')
217 for key in keys:
218 m, value = found[key]
219 raw_key = '`' + key + '`'
220 lines = section.splitlines()
221 matches = [i for i, line in enumerate(lines) if line.startswith('| ' + raw_key + ' |')]
222 if len(matches) > 1:
223 raise ValueError('conflicting inventory rows')
224 provenance = marker
225 if mode == 'accept':
226 provenance += ' sha256:' + records[key]['hash']
227 row = '| ' + raw_key + ' | ' + value.replace('&', '&amp;').replace('|', '&#124;').replace('\n', '<br>') + ' | Copy specialist | ' + provenance + ' |'
228 if matches:
229 lines[matches[0]] = row
230 else:
231 lines.append(row)
232 section = '\n'.join(lines) + '\n'
233 for key in sorted(keys, key=lambda k: found[k][0].start(), reverse=True):
234 m, _ = found[key]
235 end = text.find('\n', m.end())
236 if end < 0:
237 end = len(text)
238 line = MARKER.sub('', text[m.start():end])
239 text = text[:m.start()] + line.rstrip() + ' // ' + marker + text[end:]
240 values = {COPY: text, INVENTORY: prefix + HEADING + section + sep + suffix}
241 if mode == 'verify':
242 return dict(version=1, valid=all((root / p).read_text() == t for p, t in values.items()))
243 if not v.get("dry_run", False):
244 replace_files(root, values)
245 format_go([root / COPY])
246 return dict(version=1)
247
248
249def reference(v):
250 root = Path(v['candidate'])
251 inventory = root / 'scripts/runner-reference-allowlist.json'
252 records = json.loads(inventory.read_text())
253 pattern = re.compile(r'node|npm|\.mjs|paseo|equipo-runner|trial', re.I)
254 for item in v['references']:
255 path = Path(item['path'])
256 reason = item['reason'].strip()
257 if path.is_absolute() or '..' in path.parts or len(reason) < 12 or len(reason) > 500:
258 raise ValueError('invalid explicit reference')
259 target = root / path
260 if target.is_symlink() or str(path) == 'scripts/runner-reference-allowlist.json':
261 raise ValueError('invalid reference path')
262 lines = target.read_text().splitlines()
263 for number in item['lines']:
264 if not isinstance(number, int) or number < 1 or number > len(lines):
265 raise ValueError('invalid reference line')
266 line = lines[number - 1]
267 tokens = pattern.findall(line)
268 if not tokens:
269 raise ValueError('line contains no references')
270 digest = hashlib.sha256(line.encode()).hexdigest()
271 for token in sorted(set(tokens)):
272 entry = dict(path=str(path), line_sha256=digest, match=token, count=tokens.count(token), reason=reason)
273 previous = [r for r in records if (r['path'], r['line_sha256'], r['match']) == (str(path), digest, token)]
274 if previous and previous != [entry]:
275 raise ValueError('conflicting explicit allowance')
276 if not previous:
277 records.append(entry)
278 if not v.get('dry_run', False):
279 inventory.write_text(json.dumps(records, indent=2, ensure_ascii=False) + '\n')
280 return dict(version=1)
281
282
283def classify(v):
284 units = v.get('units', [])
285 log = v.get('log', '')
286 failures = []
287 if len(units) > 1:
288 headers = list(re.finditer(r'(?m)^=== (' + '|'.join(re.escape(u) for u in units) + r')$', log))
289 sections = {}
290 for i, header in enumerate(headers):
291 sections.setdefault(header[1], []).append(log[header.end():headers[i + 1].start() if i + 1 < len(headers) else len(log)])
292 complete = not v.get('truncated', True)
293 for unit in units:
294 blocks = sections.get(unit, [])
295 result = classify(dict(version=1, units=[unit], log=blocks[0] if len(blocks) == 1 else '', truncated=not complete or len(blocks) != 1))
296 failures.extend(result['failures'])
297 complete = complete and result['complete']
298 return dict(version=1, complete=complete, failures=failures)
299 names = re.findall(r'--- FAIL: ([^ \n]+)', log)
300 known = {'TestPlan3ReleaseBoundaries/inventory': 'copy',
301 'TestReleaseCopyReviewed': 'copy',
302 'TestDirectDeadReferencesRepository': 'bookkeeping'}
303 complete = bool(units) and not v.get('truncated', True)
304 references = re.findall(r'([^\s:]+):[0-9]+:[0-9]+: unclassified ([^\s]+)', log)
305 scan = re.search(r'reference scan: [0-9]+ text files, [0-9]+ matches, ([0-9]+) failures', log)
306 if (len(units) == 1 and not names and references and scan and int(scan[1]) == len(references)
307 and 'python3 scripts/runner-dead-references.py' in log
308 and re.search(r'(?m)^make\[1\]: \*\*\* \[Makefile:[0-9]+: runner-dead-references\] Error 1$', log)
309 and not re.search(r'panic:|build failed|undefined:', log)):
310 return dict(version=1, complete=complete, failures=[dict(unit=units[0], test='reference-scan', code='failed',
311 subject=','.join(sorted(set(p + ':' + token for p, token in references))), category='bookkeeping')])
312 # A single unit's complete Go result can classify its failed subtests.
313 if len(units) == 1 and names and re.search(r'(?m)^FAIL(?:\s|$)', log):
314 for name in names:
315 if name == 'TestPlan3ReleaseBoundaries' and 'TestPlan3ReleaseBoundaries/inventory' in names:
316 continue
317 category = known.get(name, 'other')
318 subjects = re.findall(r'pending copy omitted or changed in review inventory ([^\s]+)', log) if category == 'copy' else []
319 if category == 'bookkeeping':
320 subjects = [p + ':' + token for p, token in re.findall(r'([^\s:]+):[0-9]+:[0-9]+: unclassified ([^\s]+)', log)]
321 if not subjects:
322 stable = re.sub(r'\b[0-9a-f]{40,64}\b', '<commit>', log)
323 stable = re.sub(r'\b[0-9]+(?:\.[0-9]+)?(?:ms|s)\b', '<duration>', stable)
324 stable = re.sub(r'\d{4}-\d{2}-\d{2}[T ][0-9:.Z+-]+', '<time>', stable)
325 stable = re.sub(r':\d+(?::\d+)?:', ':<line>:', stable)
326 stable = re.sub(r'/(?:tmp|private/tmp)/[^\s:]+', '<scratch>', stable)
327 subjects = [hashlib.sha256(stable.encode()).hexdigest()]
328 failures.append(dict(unit=units[0], test=name, code='failed',
329 subject=','.join(sorted(set(subjects))), category=category))
330 explained, pending, current_package = set(), False, None
331 for line in log.splitlines():
332 explicit = re.match(r'--- FAIL (\S+) (Test\S+)', line)
333 if explicit:
334 explained.add(explicit[1])
335 current_package = explicit[1]
336 if current_package is None and re.search(r'--- FAIL: Test\S+', line):
337 pending = True
338 package = re.match(r'\s*FAIL[ \t]+(\S+)', line)
339 if package:
340 if not pending and package[1] not in explained:
341 failures.append(dict(unit=units[0], test='package', code='failed', subject=package[1], category='other'))
342 if pending:
343 explained.add(package[1])
344 pending = False
345 if current_package == package[1]:
346 current_package = None
347 if re.search(r'panic:|build failed|undefined:', log):
348 failures.append(dict(unit=units[0], test='unclassified', code='other', subject='', category='other'))
349 else:
350 for unit in units:
351 category = 'other'
352 failures.append(dict(unit=unit, test=unit, code='failed', subject='', category=category))
353 complete = complete and all(f['category'] != 'other' for f in failures)
354 return dict(version=1, complete=complete, failures=failures)
355
356
357if __name__ == '__main__':
358 try:
359 payload = sys.stdin.buffer.read(2 * 1024 * 1024 + 1)
360 if len(payload) > 2 * 1024 * 1024:
361 raise ValueError('input too large')
362 value = json.loads(payload)
363 mode = sys.argv[1]
364 if mode == 'extract':
365 result = extract(value)
366 elif mode == 'apply':
367 result = apply(value)
368 elif mode == 'reference':
369 result = reference(value)
370 elif mode == 'classify':
371 result = classify(value)
372 elif mode in ('pending', 'accept', 'regenerate', 'verify'):
373 result = status(value, 'pending' if mode == 'regenerate' else mode)
374 else:
375 raise ValueError('unknown mode')
376 print(json.dumps(result, ensure_ascii=False))
377 except (ValueError, KeyError, OSError) as exc:
378 print(str(exc), file=sys.stderr)
379 sys.exit(1)
380