File size: 8,275 Bytes
bd4559b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""Offline integrity and coverage checks; does not run a model or make requests."""
from pathlib import Path
from collections import Counter, defaultdict
import csv
import hashlib
import itertools
import json
import re
import wave

ROOT = Path(__file__).resolve().parents[1]
ARMS = ('serial', 'serial_identity', 'serial_identity_semantics')
TASK_FIELDS = ('users', 'goal_relations', 'expected_tool_actions', 'state_assertions',
               'final_success_conditions', 'environment', 'seed', 'task_contract_revision')

def digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
                                    separators=(',', ':')).encode()).hexdigest()

def file_sha(p):
    return hashlib.sha256(p.read_bytes()).hexdigest()

def read(p):
    return json.loads(p.read_text())

def ignored(p):
    return any(x in {'.git', '.cache', '.venv', '__pycache__'} for x in p.parts) or p.name in {'.DS_Store'} or p.suffix == '.pyc'

def verify(root=ROOT):
    root = Path(root).resolve()
    manifest = read(root / 'metadata/file_manifest.json')
    expected = {r['path']: r for r in manifest['files']}
    assert len(expected) == len(manifest['files']), 'Duplicate manifest path'
    actual = {p.relative_to(root).as_posix() for p in root.rglob('*')
              if p.is_file() and not ignored(p.relative_to(root))}
    assert actual == set(expected) | {'metadata/file_manifest.json'}, sorted(actual ^ (set(expected) | {'metadata/file_manifest.json'}))
    credentials = re.compile(rb'\b(?:(?:sk-|xai-)[A-Za-z0-9_-]{24,}|hf_[A-Za-z0-9]{30,})')
    for name, entry in expected.items():
        rel = Path(name)
        assert not rel.is_absolute() and '..' not in rel.parts, name
        p = root / rel
        assert not p.is_symlink(), name
        raw = p.read_bytes()
        assert len(raw) == entry['bytes'] and hashlib.sha256(raw).hexdigest() == entry['sha256'], name
        if p.suffix in {'.json', '.jsonl', '.md', '.py', '.txt', '.csv', '.cff'}:
            assert not credentials.search(raw), ('credential-shaped string', name)
            assert (b'-----BEGIN ' + b'OPENSSH PRIVATE KEY-----') not in raw, name
            assert not re.search(rb'/(?:mnt/shared-storage-(?:user|gpfs2)|Users/linqihao)/[A-Za-z0-9_]', raw), ('private deployment path', name)
    for name, expected_sha in read(root / 'metadata/source_files.json').items():
        assert file_sha(root / name) == expected_sha, name

    code_files = read(root / 'metadata/runtime_files.json')['expected_code_files']
    for name, expected_sha in code_files.items():
        assert file_sha(root / name) == expected_sha, name

    # HF tables and original playbooks must contain the same 1,976 records.
    records = []
    by_config = {}
    for config in ('tool_free', 'tool_augmented') + ARMS:
        rs = [json.loads(s) for s in (root / 'data' / config / 'test.jsonl').read_text().splitlines()]
        assert len(rs) == (408 if config == 'tool_augmented' else 392), config
        by_config[config] = rs
        for row in rs:
            p = root / row['case_path']
            c = read(p)
            assert c == json.loads(row['case_json']), row['case_id']
            assert file_sha(p) == row['case_sha256'], p.name
            assert c['case_id'] == row['case_id']
            assert c['variant']['scenario_id'] == row['scenario_id']
            assert row['participant_count'] == len(c['users'])
            assert row['event_count'] == len(c['events'])
            assert row['tool_names'] == c['environment']['tool_names']
            assert bool(row['tool_names']) == (row['track'] == 'tool_augmented')
            assert row['condition'] == (config if config in ARMS else 'baseline')
            assert row['track'] == (config if config not in ARMS else 'tool_free')
            event_ids = {e['event_id'] for e in c['events']}
            assert len(event_ids) == len(c['events'])
            users = {u['user_id'] for u in c['users']}
            assert len(users) == len(c['users'])
            assert all(e['actor_id'] in users for e in c['events'])
        records.extend(rs)
    assert len(records) == 1976
    assert len({(r['condition'], r['track'], r['case_id']) for r in records}) == 1976
    grid = set(itertools.product(('small', 'large'), ('clean', 'realistic'), ('strong', 'weak')))
    scenes = defaultdict(list)
    for r in records:
        scenes[(r['condition'], r['scenario_id'])].append(r)
    for key, rs in scenes.items():
        assert len(rs) == 8 and {(r['population'], r['acoustics'], r['follow_up']) for r in rs} == grid, key
    assert len({r['scenario_id'] for r in by_config['tool_free']}) == 49
    assert len({r['scenario_id'] for r in by_config['tool_augmented']}) == 51
    assert {r['scenario_id'] for r in by_config['tool_free']}.isdisjoint({r['scenario_id'] for r in by_config['tool_augmented']})
    with (root / 'case_index.csv').open() as f:
        index = list(csv.DictReader(f))
    assert len(index) == 1976
    indexed = {(r['condition'], r['track'], r['case_id']): r for r in index}
    assert len(indexed) == 1976
    for r in records:
        indexed_r = indexed[r['condition'], r['track'], r['case_id']]
        for k, v in r.items():
            if k == 'case_json':
                continue
            assert indexed_r[k] == (json.dumps(v, ensure_ascii=False) if isinstance(v, list) else str(v)), (r['case_id'], k)
    baseline = {r['case_id']: read(root / r['case_path']) for r in by_config['tool_free']}
    for arm in ARMS:
        for row in by_config[arm]:
            c = read(root / row['case_path'])
            m = read(root / row['manifest_path'])
            source = baseline[row['case_id']]
            assert m['source_case_sha256'] == digest(source), row['manifest_path']
            assert m['transformed_case_sha256'] == digest(c), row['manifest_path']
            assert m['task_contract_sha256'] == digest({k: source.get(k) for k in TASK_FIELDS})
            assert {k: source.get(k) for k in TASK_FIELDS} == {k: c.get(k) for k in TASK_FIELDS}
            assert m['arm'] == arm and m['task_contract_unchanged'] is True

    catalog_path = root / 'assets/voices/catalog/voice_catalog.json'
    voices = read(catalog_path)['voices']
    bindings = read(root / 'assets/voices/bindings.json')
    assert len(voices) == len(bindings['bindings']) == 3200
    assert bindings['catalog_sha256'] == file_sha(catalog_path)
    voice_map = {v['voice_catalog_id']: v for v in voices}
    assert len(voice_map) == 3200
    for v in voices:
        p = (catalog_path.parent / v['reference_audio_path']).resolve()
        assert p.is_relative_to(root / 'assets/voices/references')
        assert file_sha(p) == v['source_sha256']
        assert v['license_id'] == 'CC0-1.0'
        with wave.open(str(p), 'rb') as audio:
            assert audio.getnchannels() == 1 and audio.getnframes() > 0 and audio.getframerate() > 0
    all_base = {r['case_id']: read(root / r['case_path']) for k in ('tool_free', 'tool_augmented') for r in by_config[k]}
    binding_keys = set()
    for b in bindings['bindings']:
        key = (b['case_id'], b['oracle_user_id'])
        assert key not in binding_keys
        binding_keys.add(key)
        c = all_base[b['case_id']]
        users = c['users']
        idx = next(i for i, u in enumerate(users) if u['user_id'] == b['oracle_user_id'])
        user = users[idx]
        assert b['public_participant_id'] == f'p{idx+1:02d}'
        assert b['display_name'] == user['display_name'] and b['voice_id'] == user['voice']['voice_id']
        assert b['reference_audio_sha256'] == voice_map[b['voice_catalog_id']]['source_sha256']
    assert binding_keys == {(c['case_id'], u['user_id']) for c in all_base.values() for u in c['users']}
    return dict(passed=True, baseline_cases=len(all_base), ablation_cases=1176,
        original_case_bytes_preserved=True, all_case_conditions=1976,
        baseline_scenarios=100, factorial_grid_complete=True,
        voice_recordings=3200, voice_bindings=3200,
        ablation_fingerprints_valid=True, integrated_runtime_files=len(code_files),
        checksummed_files=len(expected),
        private_paths_or_credential_patterns_found=False)

if __name__ == '__main__':
    print(json.dumps(verify(), indent=2))