#!/usr/bin/env python3 """Equipo's pinned Copy adapter. JSON on stdin and stdout.""" import ast import hashlib import json from pathlib import Path import re import sys import subprocess import tempfile import shutil COPY = 'internal/equipo/copy.go' INVENTORY = 'docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md' HEADING = "## Plan 3 copy inventory (for Paul's review)" LITERAL = r'"(?:[^"\\\n]|\\.)*"|`[^`]*`' ENTRY = re.compile(r'(?m)^\s*(?:(?P"[^"\n]+")\s*:|(?:const[ \t]+)?(?P[A-Za-z_]\w*)\s*=)\s*(?P' + LITERAL + r')') MARKER = re.compile(r'\s*// COPY (?:ACCEPTED|APPROVED|REVIEW)[^\n]*') def decode(raw): return raw[1:-1] if raw.startswith('`') else ast.literal_eval(raw) def map_ranges(text): return [(m.end(), text.find('\n}', m.end()), m[1]) for m in re.finditer(r'(?m)^var ([A-Za-z_]\w*)\s*=\s*map\[string\]string\{', text)] def qualify(ranges, key, offset): for start, end, name in ranges: if start <= offset < end: return key if name == 'pageCopy' else name + '.' + key return key def entries(text): out = {} ranges = map_ranges(text) for m in ENTRY.finditer(text): key = qualify(ranges, json.loads(m['map']), m.start()) if m['map'] else m['const'] if key in out: raise ValueError('duplicate copy key: ' + key) out[key] = (m, decode(m['value'])) return out def read(root): p = Path(root) / COPY if p.is_symlink(): raise ValueError('symlink copy file') return p.read_text() if p.exists() else '' def extract(v): old_text, text = read(v['base']), read(v['candidate']) old, new = entries(old_text), entries(text) key_lines = re.compile(r'(?m)^\s*("[^"\n]+")\s*:\s*([^\n]+)') old_ranges, new_ranges = map_ranges(old_text), map_ranges(text) before_lines = {qualify(old_ranges, json.loads(m[1]), m.start()): m[2] for m in key_lines.finditer(old_text)} for match in key_lines.finditer(text): key = qualify(new_ranges, json.loads(match[1]), match.start()) if key not in new and before_lines.get(key) != match[2]: raise ValueError('changed computed copy needs an explicit literal: ' + key) for key, (match, value) in new.items(): tail = text[match.end():].split('\n', 1)[0].lstrip() if tail and not tail.startswith((',', '//', ')')): raise ValueError('composed copy needs an explicit literal: ' + key) strings = [] for key, (m, value) in new.items(): before = old.get(key, (None, None))[1] if before == value: continue strings.append(dict(key=key, path=COPY, start=len(text[:m.start('value') + 1].encode()), end=len(text[:m.end('value') - 1].encode()), old=before or '', text=value, context=key)) return dict(version=1, strings=strings) def recover(root): journal = root / '.equipo/copy-journal.json' if journal.exists(): values = json.loads(journal.read_text()) if set(values) - {COPY, INVENTORY}: raise ValueError('invalid journal') for name, text in values.items(): target = root / name if target.is_symlink(): raise ValueError('symlink output') target.write_text(text) journal.unlink() def replace_files(root, values): journal = root / '.equipo/copy-journal.json' journal.parent.mkdir(parents=True, exist_ok=True) journal.write_text(json.dumps(values, ensure_ascii=False)) recover(root) def format_go(paths): binary = '/opt/go/bin/gofmt' if Path('/opt/go/bin/gofmt').exists() else shutil.which('gofmt') if not binary: raise ValueError('gofmt unavailable') subprocess.run([binary, '-w', *map(str, paths)], check=True, capture_output=True, timeout=20) def apply(v): root = Path(v['candidate']) text = read(root) found = entries(text) changed = {s['key']: s for s in v['extraction']['strings']} reviewed = v['review']['strings'] if len(reviewed) != len(changed) or len({w['key'] for w in reviewed}) != len(reviewed): raise ValueError('incomplete review') replacements = [] pairs = {} for w in reviewed: key = w['key'] if key not in changed or key not in found or w['action'] != 'accept': raise ValueError('unreviewed key or question') m, before = found[key] if before != changed[key]['text']: raise ValueError('stale text') replacements.append((m.start('value'), m.end('value'), json.dumps(w['text'], ensure_ascii=False))) if before in pairs and pairs[before] != w['text']: raise ValueError('conflicting test replacements') pairs[before] = w['text'] for start, end, value in sorted(replacements, reverse=True): text = text[:start] + value + text[end:] (root / COPY).write_text(text) formatted = [root / COPY] # Match complete quoted literals; never replace substrings in assertions. for path in root.rglob('*_test.go'): if path.is_symlink() or any(p in ('vendor', '.git') for p in path.parts): continue before = path.read_text() after = re.sub(r'//[^\n]*|/\*[\s\S]*?\*/|' + LITERAL, lambda m: m[0] if m[0].startswith(('//', '/*')) else json.dumps(pairs[decode(m[0])], ensure_ascii=False) if decode(m[0]) in pairs else m[0], before) if before != after: path.write_text(after) formatted.append(path) format_go(formatted) return dict(version=1) def status(v, mode): root = Path(v['candidate']) if mode == 'pending' and 'recovery' in v: recovery = v['recovery'] if 'old_path' in recovery: recovery = {name: Path(recovery[name + '_path']).read_text() for name in ('old', 'tooling', 'candidate')} def clean(text): return MARKER.sub('', text) with tempfile.TemporaryDirectory(dir=root) as scratch: paths = [] for name in ('tooling', 'old', 'candidate'): file = Path(scratch) / name file.write_text(clean(recovery[name])) paths.append(str(file)) result = subprocess.run(['/usr/bin/git', 'merge-file', '-p', *paths], capture_output=True, timeout=10) if result.returncode: raise ValueError('copy meaning conflict needs owner') merged = result.stdout.decode() # Restore unchanged human provenance from the trusted tooling revision. original = entries(recovery['tooling']) for key, (m, value) in sorted(entries(merged).items(), key=lambda item: item[1][0].start(), reverse=True): if key not in original or original[key][1] != value: continue old_match = original[key][0] old_end = recovery['tooling'].find('\n', old_match.end()) annotation = MARKER.search(recovery['tooling'][old_match.start():old_end]) if annotation: end = merged.find('\n', m.end()) merged = merged[:end] + annotation[0] + merged[end:] (root / COPY).write_text(merged) v['keys'] = [key for key, (_, value) in entries(merged).items() if key not in original or original[key][1] != value] if mode == 'verify': text = read(root) inventory = (root / INVENTORY).read_text() valid = not (root / '.equipo/copy-journal.json').exists() valid = valid and not re.search(r'COPY REVIEW (?:PENDING|REQUIRED)', text) for key, (m, value) in entries(text).items(): end = text.find('\n', m.end()) if 'COPY ACCEPTED BY DELEGATION (Copy, record-bound)' not in text[m.start():end]: continue rows = [line for line in inventory.splitlines() if line.startswith('| `' + key + '` |')] digest = hashlib.sha256(value.encode()).hexdigest() valid = valid and len(rows) == 1 and rows[0].endswith('sha256:' + digest + ' |') return dict(version=1, valid=bool(valid)) recover(root) text = read(root) found = entries(text) keys = v.get('keys', []) if len(set(keys)) != len(keys) or any(k not in found for k in keys): raise ValueError('unknown or duplicate keys') records = {r['key']: r for r in v.get('records', [])} changed = set(v.get('changed', [])) marker = 'COPY REVIEW PENDING' if mode == 'accept': if not keys or not set(keys) <= changed or not set(keys) <= set(records): raise ValueError('acceptance is outside reviewed changed set') for key in keys: r = records[key] 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'): raise ValueError('stale acceptance') marker = 'COPY ACCEPTED BY DELEGATION (Copy, record-bound)' inv_path = root / INVENTORY inventory = inv_path.read_text() if HEADING not in inventory: raise ValueError('inventory missing') prefix, section = inventory.split(HEADING, 1) section, sep, suffix = section.partition('\n## ') for key in keys: m, value = found[key] raw_key = '`' + key + '`' lines = section.splitlines() matches = [i for i, line in enumerate(lines) if line.startswith('| ' + raw_key + ' |')] if len(matches) > 1: raise ValueError('conflicting inventory rows') provenance = marker if mode == 'accept': provenance += ' sha256:' + records[key]['hash'] row = '| ' + raw_key + ' | ' + value.replace('&', '&').replace('|', '|').replace('\n', '
') + ' | Copy specialist | ' + provenance + ' |' if matches: lines[matches[0]] = row else: lines.append(row) section = '\n'.join(lines) + '\n' for key in sorted(keys, key=lambda k: found[k][0].start(), reverse=True): m, _ = found[key] end = text.find('\n', m.end()) if end < 0: end = len(text) line = MARKER.sub('', text[m.start():end]) text = text[:m.start()] + line.rstrip() + ' // ' + marker + text[end:] values = {COPY: text, INVENTORY: prefix + HEADING + section + sep + suffix} if mode == 'verify': return dict(version=1, valid=all((root / p).read_text() == t for p, t in values.items())) if not v.get("dry_run", False): replace_files(root, values) format_go([root / COPY]) return dict(version=1) def reference(v): root = Path(v['candidate']) inventory = root / 'scripts/runner-reference-allowlist.json' records = json.loads(inventory.read_text()) pattern = re.compile(r'node|npm|\.mjs|paseo|equipo-runner|trial', re.I) for item in v['references']: path = Path(item['path']) reason = item['reason'].strip() if path.is_absolute() or '..' in path.parts or len(reason) < 12 or len(reason) > 500: raise ValueError('invalid explicit reference') target = root / path if target.is_symlink() or str(path) == 'scripts/runner-reference-allowlist.json': raise ValueError('invalid reference path') lines = target.read_text().splitlines() for number in item['lines']: if not isinstance(number, int) or number < 1 or number > len(lines): raise ValueError('invalid reference line') line = lines[number - 1] tokens = pattern.findall(line) if not tokens: raise ValueError('line contains no references') digest = hashlib.sha256(line.encode()).hexdigest() for token in sorted(set(tokens)): entry = dict(path=str(path), line_sha256=digest, match=token, count=tokens.count(token), reason=reason) previous = [r for r in records if (r['path'], r['line_sha256'], r['match']) == (str(path), digest, token)] if previous and previous != [entry]: raise ValueError('conflicting explicit allowance') if not previous: records.append(entry) if not v.get('dry_run', False): inventory.write_text(json.dumps(records, indent=2, ensure_ascii=False) + '\n') return dict(version=1) def classify(v): units = v.get('units', []) log = v.get('log', '') failures = [] if len(units) > 1: headers = list(re.finditer(r'(?m)^=== (' + '|'.join(re.escape(u) for u in units) + r')$', log)) sections = {} for i, header in enumerate(headers): sections.setdefault(header[1], []).append(log[header.end():headers[i + 1].start() if i + 1 < len(headers) else len(log)]) complete = not v.get('truncated', True) for unit in units: blocks = sections.get(unit, []) result = classify(dict(version=1, units=[unit], log=blocks[0] if len(blocks) == 1 else '', truncated=not complete or len(blocks) != 1)) failures.extend(result['failures']) complete = complete and result['complete'] return dict(version=1, complete=complete, failures=failures) names = re.findall(r'--- FAIL: ([^ \n]+)', log) known = {'TestPlan3ReleaseBoundaries/inventory': 'copy', 'TestReleaseCopyReviewed': 'copy', 'TestDirectDeadReferencesRepository': 'bookkeeping'} complete = bool(units) and not v.get('truncated', True) references = re.findall(r'([^\s:]+):[0-9]+:[0-9]+: unclassified ([^\s]+)', log) scan = re.search(r'reference scan: [0-9]+ text files, [0-9]+ matches, ([0-9]+) failures', log) if (len(units) == 1 and not names and references and scan and int(scan[1]) == len(references) and 'python3 scripts/runner-dead-references.py' in log and re.search(r'(?m)^make\[1\]: \*\*\* \[Makefile:[0-9]+: runner-dead-references\] Error 1$', log) and not re.search(r'panic:|build failed|undefined:', log)): return dict(version=1, complete=complete, failures=[dict(unit=units[0], test='reference-scan', code='failed', subject=','.join(sorted(set(p + ':' + token for p, token in references))), category='bookkeeping')]) # A single unit's complete Go result can classify its failed subtests. if len(units) == 1 and names and re.search(r'(?m)^FAIL(?:\s|$)', log): for name in names: if name == 'TestPlan3ReleaseBoundaries' and 'TestPlan3ReleaseBoundaries/inventory' in names: continue category = known.get(name, 'other') subjects = re.findall(r'pending copy omitted or changed in review inventory ([^\s]+)', log) if category == 'copy' else [] if category == 'bookkeeping': subjects = [p + ':' + token for p, token in re.findall(r'([^\s:]+):[0-9]+:[0-9]+: unclassified ([^\s]+)', log)] if not subjects: stable = re.sub(r'\b[0-9a-f]{40,64}\b', '', log) stable = re.sub(r'\b[0-9]+(?:\.[0-9]+)?(?:ms|s)\b', '', stable) stable = re.sub(r'\d{4}-\d{2}-\d{2}[T ][0-9:.Z+-]+', '