Files
myfileagent-pipeline/ci/final_project.py
T

335 lines
15 KiB
Python
Raw Normal View History

"""Exact-bundle validation and immutable release tooling; standard library only."""
import argparse
import contextlib
import fcntl
import hashlib
import io
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
BASE = 'https://myfileagent.tech'
REPO = 'myfileagent/myfileagent-pipeline'
PAYLOAD = {'reviewed.py', 'review.json'}
FILES = PAYLOAD | {'bundle.json', 'SHA256SUMS'}
MAX_BYTES = 2 * 1024 * 1024
def digest(data):
return hashlib.sha256(data).hexdigest()
def write_json(path, data):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + '.tmp')
tmp.write_text(json.dumps(data, sort_keys=True, indent=2) + '\n', encoding='utf-8')
os.replace(tmp, path)
def identity(sha, run, attempt, mode):
if not re.fullmatch('[0-9a-f]{40}', str(sha)):
raise ValueError('Expected full lowercase SHA-1 source commit')
if any(not re.fullmatch('[1-9][0-9]*', str(x)) for x in (run, attempt)):
raise ValueError('Run ID and attempt must be positive integers')
if mode not in ('fixture', 'live'):
raise ValueError('Explicit fixture/live mode required')
return dict(schema_version=1, source_commit=sha, run_id=str(run), attempt=str(attempt), mode=mode)
def bundle_name(meta):
return f"review-{meta['run_id']}-attempt-{meta['attempt']}-{meta['source_commit']}"
def review_metadata(raw, expected):
data = json.loads(raw)
required = {'source_commit', 'model_id', 'status', 'summary', 'diff', 'input_tokens', 'output_tokens'}
if not isinstance(data, dict) or not required <= data.keys():
raise ValueError('Missing review metadata fields')
if data['source_commit'] != expected['source_commit'] or data['status'] not in ('corrected', 'unchanged'):
raise ValueError('Review identity/status does not permit a ready bundle')
if not all(isinstance(data[x], str) for x in ('summary', 'diff')):
raise ValueError('Review summary and diff must be strings')
if data.get('mode', expected['mode']) != expected['mode']:
raise ValueError('Review mode mismatch')
for key in ('input_tokens', 'output_tokens'):
value = data[key]
if value is not None and (type(value) is not int or value < 0):
raise ValueError('Invalid token count')
if data['status'] == 'corrected' and (not isinstance(data['model_id'], str) or not data['model_id']):
raise ValueError('Corrected review must identify its model')
if expected['mode'] == 'fixture' and data['model_id'] != 'fixture-model':
raise ValueError('Fixture model ID required')
if expected['mode'] == 'live' and data['model_id'] == 'fixture-model':
raise ValueError('Fixture data cannot be released in live mode')
return data
def zip_bytes(contents):
out = io.BytesIO()
with zipfile.ZipFile(out, 'w', compression=zipfile.ZIP_DEFLATED) as z:
for name, data in sorted(contents.items()):
info = zipfile.ZipInfo(name, date_time=(2020, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
z.writestr(info, data)
return out.getvalue()
def create_bundle(review_dir, output, expected):
output = Path(output)
if output.exists():
raise ValueError('Refuse to overwrite a bundle')
files = {}
for name in PAYLOAD:
path = Path(review_dir) / name
if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_BYTES:
raise ValueError('Invalid review file')
files[name] = path.read_bytes()
review_metadata(files['review.json'], expected)
files['bundle.json'] = (json.dumps(expected, sort_keys=True)+'\n').encode()
files['SHA256SUMS'] = ''.join(f'{digest(files[n])} {n}\n' for n in sorted(PAYLOAD)).encode()
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(zip_bytes(files))
def read_bundle(path, expected):
if Path(path).stat().st_size > MAX_BYTES:
raise ValueError('Bundle exceeds size limit')
with zipfile.ZipFile(path) as z:
entries = z.infolist()
if len(entries) != len(FILES) or {i.filename for i in entries} != FILES:
raise ValueError('Unexpected, duplicate or missing bundle files')
if sum(i.file_size for i in entries) > MAX_BYTES:
raise ValueError('Expanded bundle exceeds size limit')
for i in entries:
kind = stat.S_IFMT(i.external_attr >> 16)
if kind not in (0, stat.S_IFREG) or i.flag_bits & 1:
raise ValueError('Only unencrypted regular files are allowed')
files = {i.filename: z.read(i) for i in entries}
if json.loads(files['bundle.json']) != expected:
raise ValueError('Bundle SHA/run/attempt/mode mismatch')
required = ''.join(f'{digest(files[n])} {n}\n' for n in sorted(PAYLOAD)).encode()
if files['SHA256SUMS'] != required:
raise ValueError('Payload checksum mismatch')
review_metadata(files['review.json'], expected)
return files
def verify_bundle(path, destination, expected):
files = read_bundle(path, expected)
destination = Path(destination)
destination.mkdir(parents=True, exist_ok=False)
for name, data in files.items():
(destination / name).write_bytes(data)
write_json(destination / 'verified.json', dict(**expected, bundle_sha256=digest(Path(path).read_bytes())))
return files
class SameOrigin(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
from urllib.parse import urlsplit
if urlsplit(newurl).scheme != 'https' or urlsplit(newurl).netloc != 'myfileagent.tech':
raise ValueError('Refuse cross-origin artifact redirect')
return super().redirect_request(req, fp, code, msg, headers, newurl)
def fetch_bundle(output, expected):
token = os.environ.get('GITEA_TOKEN', '')
opener = urllib.request.build_opener(SameOrigin())
headers = {'Authorization': 'token '+token} if token else {}
def get(url, limit):
with opener.open(urllib.request.Request(url, headers=headers), timeout=60) as response:
raw = response.read(limit+1)
if len(raw) > limit:
raise ValueError('Response exceeds size limit')
return raw
# Server-side success is checked independently from client-supplied metadata.
run = json.loads(get(f'{BASE}/api/v1/repos/{REPO}/actions/runs/{expected["run_id"]}', MAX_BYTES))
if run.get('conclusion') != 'success' or run.get('head_sha') != expected['source_commit']:
raise ValueError('Selected Actions run is not successful on the expected SHA')
if str(run.get('run_attempt', '1')) != expected['attempt']:
raise ValueError('Actions run attempt mismatch')
name = bundle_name(expected)
raw = get(f'{BASE}/{REPO}/actions/runs/{expected["run_id"]}/artifacts/{name}', MAX_BYTES)
# upload-artifact wraps our canonical review-bundle.zip in its own ZIP.
with zipfile.ZipFile(io.BytesIO(raw)) as outer:
entries = outer.infolist()
if len(entries) != 1 or entries[0].filename != 'review-bundle.zip' or entries[0].file_size > MAX_BYTES:
raise ValueError('Unexpected Actions artifact wrapper')
content = outer.read(entries[0])
output = Path(output)
output.parent.mkdir(parents=True, exist_ok=True)
with output.open('xb') as target:
target.write(content)
read_bundle(output, expected)
return run
@contextlib.contextmanager
def locked(state):
state = Path(state)
state.mkdir(parents=True, exist_ok=True)
with (state / '.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield state
def release_key(meta):
# Mode separates simulated and live reservations. Model/runtime must be pinned in the commit.
return f"{meta['mode']}:{meta['source_commit']}"
def reserve(state, meta, baseline='1.0'):
if not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', baseline):
raise ValueError('Baseline must be Major.Minor')
with locked(state) as state:
path = state / 'versions.json'
registry = json.loads(path.read_text()) if path.exists() else {'baseline': baseline, 'next': 1, 'reservations': {}}
if registry['baseline'] != baseline:
raise ValueError('Baseline differs from durable registry')
key = release_key(meta)
if key not in registry['reservations']:
registry['reservations'][key] = f"{baseline}.{registry['next']}"
registry['next'] += 1
write_json(path, registry)
return registry['reservations'][key]
def smoke(path):
run = subprocess.run([sys.executable, str(path)], capture_output=True, text=True, timeout=10)
if run.returncode or run.stdout != 'hello\n':
raise ValueError('Reviewed-file smoke test failed')
def test_review(verified, receipt):
root = Path(verified)
subprocess.run([sys.executable, '-m', 'py_compile', str(root / 'reviewed.py')], check=True, timeout=10)
# Adopt Member 1's smoke entry point when integrated; retain the independent assertion.
member1 = ROOT / 'tests/smoke_demo.py'
if member1.exists():
subprocess.run([sys.executable, str(member1), str(root/'reviewed.py')], check=True, timeout=20)
smoke(root / 'reviewed.py')
write_json(receipt, {'reviewed_sha256': digest((root/'reviewed.py').read_bytes()), 'result': 'passed'})
def publish(bundle, expected, pdf, state, output, baseline, jenkins_build):
files = read_bundle(bundle, expected)
version = reserve(state, expected, baseline)
pdf = Path(pdf)
from pypdf import PdfReader
reader = PdfReader(pdf)
text = '\n'.join(p.extract_text() or '' for p in reader.pages)
for value in [version, expected['source_commit']]:
if value not in text:
raise ValueError('PDF is missing release identity')
build_meta = json.loads(pdf.with_name('build-manifest.json').read_text())
if (build_meta.get('release_version') != version or build_meta.get('commit') != expected['source_commit']
or build_meta.get('review_sha256') != digest(files['review.json'])
or build_meta.get('reviewed_sha256') != digest(files['reviewed.py'])
or build_meta.get('pdf_sha256') != digest(pdf.read_bytes())
or build_meta.get('run_id') != expected['run_id'] or build_meta.get('attempt') != expected['attempt']
or build_meta.get('mode') != expected['mode']):
raise ValueError('Report manifest does not match this verified bundle')
with tempfile.TemporaryDirectory() as temp:
candidate = Path(temp)/'reviewed.py'
candidate.write_bytes(files['reviewed.py'])
smoke(candidate) # Publication cannot bypass the behavior gate.
contents = {n: files[n] for n in PAYLOAD}
contents[f'report-{version}.pdf'] = pdf.read_bytes()
contents['README.txt'] = (f'SSW590 final project {version}\nMode: {expected["mode"]}\n'
f'Source: {expected["source_commit"]}\nPython 3 required (tested by CI).\n'
'Extract into a fresh directory; run: python3 reviewed.py\nExpected stdout: hello\n'
'Compare payload SHA-256 hashes with manifest.json; compare the ZIP with its companion .sha256.\n'
'Fixture mode is simulated evidence, not a real AI review.\n').encode()
manifest = dict(**expected, version=version, jenkins_build=str(jenkins_build),
payload_sha256={n:digest(b) for n,b in sorted(contents.items())})
contents['manifest.json'] = (json.dumps(manifest, sort_keys=True, indent=2)+'\n').encode()
archive = zip_bytes(contents)
name = f'ssw590-{expected["mode"]}-{version}.zip'
with locked(state) as state:
release = state/'releases'/name
release.parent.mkdir(exist_ok=True)
if release.exists():
# A published version is immutable. A new build identity/PDF cannot silently overwrite it.
if release.read_bytes() != archive:
previous = release.read_bytes()
with zipfile.ZipFile(io.BytesIO(previous)) as z:
old_manifest = json.loads(z.read('manifest.json'))
if (old_manifest['source_commit'] != expected['source_commit']
or old_manifest['mode'] != expected['mode']
or any(z.read(n) != files[n] for n in PAYLOAD)):
raise ValueError('Version already published with different reviewed payload')
archive = previous
manifest = old_manifest
print('Reusing immutable release and its original build identity', file=sys.stderr)
else:
tmp = release.with_suffix('.tmp')
tmp.write_bytes(archive)
os.replace(tmp, release)
out = Path(output)
out.mkdir(parents=True, exist_ok=True)
(out/name).write_bytes(archive)
(out/(name+'.sha256')).write_text(f'{digest(archive)} {name}\n')
write_json(out/'release.json', manifest)
return name
def metrics(review, output, completed_at):
data = json.loads(Path(review).read_text())
if data.get('mode') != 'live' or data.get('model_id') == 'fixture-model':
raise ValueError('Only explicitly live metadata may emit live metrics')
rows = []
for key in ('input_tokens', 'output_tokens'):
value = data.get(key)
known = type(value) is int and value >= 0
rows += [f'review_{key}_available{{mode="live"}} {int(known)}']
if known:
rows += [f'review_{key}{{mode="live"}} {value}']
if not re.fullmatch('[0-9]+', str(completed_at)):
raise ValueError('Completion timestamp must be measured epoch seconds')
rows += [f'review_completed_timestamp_seconds{{mode="live"}} {completed_at}']
output = Path(output)
output.parent.mkdir(parents=True, exist_ok=True)
tmp = output.with_suffix('.tmp')
tmp.write_text('\n'.join(rows)+'\n')
os.replace(tmp, output)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('action', choices=['bundle','fetch','verify','reserve','test','publish','metrics'])
p.add_argument('--sha'); p.add_argument('--run-id'); p.add_argument('--attempt', default='1')
p.add_argument('--mode', choices=['fixture','live'], default='fixture')
p.add_argument('--review-dir'); p.add_argument('--bundle'); p.add_argument('--output')
p.add_argument('--state'); p.add_argument('--baseline', default='1.0'); p.add_argument('--pdf')
p.add_argument('--jenkins-build', default='local'); p.add_argument('--completed-at')
a = p.parse_args()
if a.action == 'test':
test_review(a.review_dir, a.output); return
if a.action == 'metrics':
metrics(a.review_dir+'/review.json', a.output, a.completed_at); return
meta = identity(a.sha,a.run_id,a.attempt,a.mode)
if a.action == 'bundle': create_bundle(a.review_dir,a.output,meta)
elif a.action == 'fetch': print(json.dumps(fetch_bundle(a.output,meta)))
elif a.action == 'verify': verify_bundle(a.bundle,a.output,meta)
elif a.action == 'reserve': print(reserve(a.state,meta,a.baseline))
elif a.action == 'publish': print(publish(a.bundle,meta,a.pdf,a.state,a.output,a.baseline,a.jenkins_build))
if __name__ == '__main__':
try:
main()
except Exception as exc:
print(f'Final-project gate failed: {type(exc).__name__}: {exc}', file=sys.stderr)
raise SystemExit(1)