#!/usr/bin/env python3 """Content-driven TermiGen compatibility patches; never edit the source checkout. Source: ucsb-mlsec/terminal-bench-env, 03bddac74ada2fa344df0e93b4a3ace2034294d1. Evidence: environment-compat.md in the TermiGen audit workspace and the installed Harbor worker's _apply_dockerfile_copies / _bake_deferred_overlay. No Harbor code is changed. Rules (all detected from each archive; no task IDs or prior selections): * tmp-fixture: move only COPY fixture roots, literal initial cp/touch paths and nested /tmp WORKDIRs to /opt/task-data; rewrite references in textual task files. /tmp scratch and unrelated output paths stay unchanged. * workspace-copy: a literal file destination becomes its parent with a slash. When replay would copy a file onto itself, or COPY renames it, add a byte/mode identical alias at environment/.termigen-copy//. Every aliased source, alias path, target, mode and hash is recorded in the output report. Original context files are retained unchanged unless a path reference inside them needs relocation. * wildcard-copy: expand existing build-context glob matches into literal COPYs. * initial-file: realize a literal RUN cp from a known, unchanged COPY payload, or an initial RUN touch, as a COPY. This retains their original bytes and avoids image /tmp mounts and workdir binds hiding the generated file. * deferred-helper: a copied script subsequently executed by RUN is also reconstructed from its exact bytes in that RUN, preserving mode, because the deferred builder does not stage COPY payloads. Only /tmp-relocated scripts are eligible; no new helper program is introduced. * env-expansion: resolve Docker ENV variable references at their declaration, using earlier ENV values and the shipped base image's PATH. The inherited PATH was read from its 10-docker2singularity.sh during pilot 948548; the bridge otherwise exports ${PATH} literally and loses mkdir/python/apt commands. Preflight leaves the WHOLE task byte-identical on missing literal COPY sources, ambiguous COPY semantics, target-root/alias collisions, or bridge-metadata COPY collisions. These decisions are reported, never silently dropped. Archives with no trigger are returned as their original compressed bytes. The per-file audit hashes content, entry type and mode and asserts that no undeclared file differs. The CLI outputs every input task. Unpatchable conditions are predictions only: the JSON report records each task ID, rule and reason while its exact input blob remains in the candidate Parquet. Archiving belongs to publish.py using stage reports. Missing verifier dependencies and NOP findings remain dataset-quality questions for the unchanged validation/publishing stages. """ from __future__ import annotations import argparse import base64 from collections import Counter import difflib import fnmatch import gzip import hashlib import io import json import os from pathlib import Path, PurePosixPath import posixpath as pp import re import shlex import tarfile VERSION = 'termigen-environment-v3' SOURCE = 'https://github.com/ucsb-mlsec/terminal-bench-env/tree/03bddac74ada2fa344df0e93b4a3ace2034294d1' TARGET = '/opt/task-data' ALIAS = '.termigen-copy' METADATA = {'/workspace/Dockerfile', '/workspace/environment/Dockerfile'} BASE_IMAGE = 'ghcr.io/laude-institute/t-bench/ubuntu-24-04:20250624' BASE_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' def sha(data): return hashlib.sha256(data).hexdigest() def prediction_rule(reason): """Classify the detected condition, independently of task names.""" if reason.startswith('missing COPY source:'): return 'missing-copy-source' if 'bridge metadata' in reason: return 'bridge-metadata-collision' if reason.startswith('unknown inherited ENV variable:'): return 'unresolved-env-reference' if 'collision' in reason or 'namespace' in reason: return 'path-collision' return 'unsupported-conversion' def unpack(blob): entries = {} with tarfile.open(fileobj=io.BytesIO(blob), mode='r:*') as archive: for m in archive: name = pp.normpath(m.name) if PurePosixPath(name).is_absolute() or '..' in PurePosixPath(name).parts or name in entries: raise ValueError(f'unsafe/duplicate archive member: {m.name}') if not (m.isfile() or m.isdir()): raise ValueError(f'unsupported archive member: {m.name}') entries[name] = (archive.extractfile(m).read() if m.isfile() else None, m.mode) return entries def pack(entries): buf = io.BytesIO() with gzip.GzipFile(fileobj=buf, mode='wb', filename='', mtime=0) as gz: with tarfile.open(fileobj=gz, mode='w|', format=tarfile.PAX_FORMAT) as archive: for name, (data, mode) in sorted(entries.items()): m = tarfile.TarInfo(name) m.mode = mode if data is None: m.type = tarfile.DIRTYPE archive.addfile(m) else: m.size = len(data) archive.addfile(m, io.BytesIO(data)) return buf.getvalue() def logical_lines(text): """Keep spans so unchanged Dockerfile instructions retain their exact bytes.""" lines = text.splitlines(keepends=True) i = 0 while i < len(lines): start = i parts = [] while i < len(lines): s = lines[i].strip() i += 1 parts.append(s[:-1] if s.endswith('\\') else s) if not s.endswith('\\'): break yield start, i, ' '.join(parts) def instructions(text): cwd = '/' out = [] for start, end, line in logical_lines(text): op, _, arg = line.partition(' ') op = op.upper() if op == 'FROM': cwd = '/' if op == 'WORKDIR': if '$' in arg: raise ValueError('variable WORKDIR requires review') cwd = pp.normpath(pp.join(cwd, arg)) rec = dict(start=start, end=end, op=op, arg=arg, line=line, cwd=cwd) if op in ('COPY', 'ADD'): if op != 'COPY' or arg.startswith('['): raise ValueError('ADD/JSON COPY requires review') p = shlex.split(arg) if len(p) != 2 or p[0].startswith('--') or '$' in arg: raise ValueError('nonliteral/flagged/multisource COPY requires review') rec.update(src=pp.normpath(p[0]), dest=pp.normpath(pp.join(cwd, p[1])), slash=p[1].endswith('/')) out.append(rec) return out def under(path, root): return path == root or path.startswith(root + '/') def rewrite_paths(text, mapping): for old, new in sorted(mapping.items(), key=lambda x: -len(x[0])): # /tmp itself is an exact directory reference; it must not consume all # scratch/output descendants. Other fixture roots include descendants. end = r'(?![\w./-])' if old == '/tmp' else r'(?![\w.-])' text = re.sub(r'(? {shlex.quote(target)} && chmod {mode:o} {shlex.quote(target)}') if prefixes: replacements.append((rec['start'], rec['end'], 'RUN ' + ' && '.join(prefixes + [rec['arg']]))) rewrite_rules.add('deferred-helper') if 'deferred-helper' not in report['rules']: report['rules'].append('deferred-helper') if replacements: df = replace_spans(df, replacements) # Each transformed span is attributed individually as well as in # aliases; the Dockerfile records all rules touching it. change('environment/Dockerfile', df.encode(), sorted(rewrite_rules)[0]) changes['environment/Dockerfile'].update(rewrite_rules) for rule in sorted(rewrite_rules): if rule not in report['rules']: report['rules'].append(rule) # Expected payload tree is derived from ORIGINAL Dockerfile COPYs, with # only documented path/content relocation. Hashes never come from the # running container. Later original COPYs overwrite earlier ones. expected = {} for rec in instructions(original['environment/Dockerfile'][0].decode()): if rec['op'] != 'COPY': continue if any(c in rec['src'] for c in '*?['): matching = [n.removeprefix('environment/') for n, (v, _) in original.items() if v is not None and n.startswith('environment/') and fnmatch.fnmatchcase(n.removeprefix('environment/'), rec['src'])] recs = [dict(rec, src=s) for s in sorted(matching)] else: recs = [rec] for each in recs: for source, target in copy_files(original, each): target = rewrite_paths(target, mapping) data, mode = entries[source] expected[target] = dict(path=target, original_path=pp.join(each['dest'], pp.basename(each['src'])) if each['slash'] else each['dest'], source=source, sha256=sha(data), original_sha256=sha(original[source][0]), mode=oct(mode), origin='COPY') for item in initial: expected[item['path']] = dict(item, origin='RUN initializer') report['expected_files'] = list(expected.values()) report['initial_files'] = initial report['collision_checks'].append(dict(alias_namespace=ALIAS, conflicts=[])) except (ValueError, KeyError, UnicodeError) as exc: report.update(rules=[], aliases=[], relocations={}, expected_files=[], unpatchable=[str(exc)]) entries = original changes = {} unchanged = hashlib.sha256() for name in sorted(original): data, mode = original[name] if entries[name] != original[name]: if name not in changes: raise AssertionError(f'undeclared change: {name}') report['changed_files'].append(dict(path=name, rules=sorted(changes[name]), before=sha(data) if data is not None else None, after=sha(entries[name][0]) if entries[name][0] is not None else None, mode_before=mode, mode_after=entries[name][1])) else: header = json.dumps([name, 'dir' if data is None else 'file', mode], separators=(',', ':')).encode() unchanged.update(len(header).to_bytes(8, 'big') + header) if data is not None: unchanged.update(hashlib.sha256(data).digest()) for name in sorted(set(entries) - set(original)): if name not in changes: raise AssertionError(f'undeclared addition: {name}') data, mode = entries[name] report['added_files'].append(dict(path=name, rules=sorted(changes[name]), sha256=sha(data) if data is not None else None, mode=mode)) report['unchanged_files_sha256'] = unchanged.hexdigest() report['unchanged_entries'] = len(original) - len(report['changed_files']) report['status'] = 'unpatchable' if report['unpatchable'] else 'patched' if changes else 'no-op' report['predictions'] = [dict(rule=prediction_rule(reason), reason=reason) for reason in report['unpatchable']] output = pack(entries) if changes else blob report['input_sha256'] = sha(blob) report['output_sha256'] = sha(output) if report['status'] in ('no-op', 'unpatchable'): assert output == blob return output, report def write_json(path, value): path.parent.mkdir(parents=True, exist_ok=True) with path.open('w') as f: json.dump(value, f, indent=2) f.write('\n') f.flush() os.fsync(f.fileno()) def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('--input', type=Path, required=True) ap.add_argument('--output', type=Path, required=True) ap.add_argument('--report', type=Path) ap.add_argument('--diff', type=Path, help='workspace-only prototype diff') a = ap.parse_args() if a.input.resolve() == a.output.resolve() or a.output.exists(): ap.error('output must be new and distinct from input') import pyarrow as pa import pyarrow.parquet as pq rows, results = [], [] diff = [] for batch in pq.ParquetFile(a.input).iter_batches(batch_size=32): for row in batch.to_pylist(): blob, record = patch_task(row['task_binary']) rows.append(dict(path=row['path'], task_binary=blob)) record['task_id'] = row['path'] results.append(record) if a.diff and record['changed_files']: before, after = unpack(row['task_binary']), unpack(blob) for item in record['changed_files']: name = item['path'] try: old, new = before[name][0].decode(), after[name][0].decode() except (UnicodeError, AttributeError): continue diff.extend(difflib.unified_diff(old.splitlines(True), new.splitlines(True), fromfile=f'a/{row["path"]}/{name}', tofile=f'b/{row["path"]}/{name}')) a.output.parent.mkdir(parents=True, exist_ok=True) schema = pa.schema([pa.field('path', pa.string(), nullable=False), pa.field('task_binary', pa.binary(), nullable=False)]) temp = a.output.with_suffix('.tmp.parquet') pq.write_table(pa.Table.from_pylist(rows, schema=schema), temp, compression=None, use_dictionary=False, write_statistics=False, row_group_size=32) temp.replace(a.output) report = dict(version=VERSION, source=SOURCE, input=str(a.input.resolve()), input_sha256=sha(a.input.read_bytes()), patcher_sha256=sha(Path(__file__).read_bytes()), counts=dict(Counter(r['status'] for r in results)), tasks=results, candidate_count=len(rows), unpatchable_predictions=[dict(task_id=r['task_id'], **prediction) for r in results for prediction in r['predictions']], validation='Not runtime-validated; patched counts are not passing counts.') write_json(a.report or a.output.with_suffix('.report.json'), report) if a.diff: a.diff.write_text(''.join(diff)) print(json.dumps(report['counts']), flush=True) if __name__ == '__main__': main()