File size: 3,290 Bytes
2e7f744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Post-hoc spec audit of a Harbor job: flag trials whose agent tried to reach the network, solved end to end
or looked outside /app/context (e.g. curl/wget/pip/git/python requests, WebFetch/WebSearch,
HF dataset names). Bash already runs in an empty network namespace, so attempts should fail;
any flagged trial is listed and excluded from the headline numbers.

python -I scripts/audit_network.py <job_dir> [--out audit.json]
"""
import glob, json, os, re, sys

NET = re.compile(r'(?<![\\\w])(curl|wget|pip3?\s+install|uv\s+pip|git\s+clone|apt-get|nc\s|ncat|ssh\s|scp\s|requests\.|urllib|http\.client|'
                 r'socket\.|aiohttp|httpx|huggingface|hf_hub|FrontierCS2|FrontierCS-2-runs|datasets\.load|'
                 r'https?://)', re.I)
WEBTOOLS = {'WebFetch', 'WebSearch', 'web_search', 'web_fetch'}
# End-to-end solving (forbidden by the predictor spec): building, applying or running task code
E2E = re.compile(r'(?<![\\\w])(git\s+apply|patch\s+-p|nvcc|g\+\+|gcc|clang|cmake|make\b|ninja|cargo|pytest|'
                 r'python3?\s+\S*(submissions|solution|bench|kernel|setup)\S*\.py|'
                 r'import\s+(torch|triton|cupy|vllm|jax)|bash\s+\S*submissions/)', re.I)


def tool_calls(trial):
    """Yield (tool_name, input_text) from Claude Code session logs under the trial's agent dir."""
    for f in glob.glob(os.path.join(trial, 'agent', '**', '*.jsonl'), recursive=True) + \
             glob.glob(os.path.join(trial, 'agent', '**', '*.txt'), recursive=True):
        for line in open(f, errors='replace'):
            try:
                e = json.loads(line)
            except Exception:
                continue
            msg = e.get('message') if isinstance(e, dict) else None
            for b in (msg or {}).get('content') or [] if isinstance(msg, dict) else []:
                if isinstance(b, dict) and b.get('type') in ('tool_use', 'server_tool_use'):
                    yield b.get('name', ''), json.dumps(b.get('input'), ensure_ascii=False)


def main():
    job = sys.argv[1]
    out = sys.argv[sys.argv.index('--out') + 1] if '--out' in sys.argv else None
    flagged, n = {}, 0
    for trial in sorted(glob.glob(os.path.join(job, '*/'))):
        if not os.path.exists(os.path.join(trial, 'config.json')):
            continue
        n += 1
        hits = []
        for name, inp in tool_calls(trial):
            if name in WEBTOOLS:
                hits.append(f'{name}: {inp[:200]}')
            elif name == 'Bash' and NET.search(inp):
                hits.append(f'Bash (network): {inp[:300]}')
            elif name in ('Bash', 'Write') and E2E.search(inp):
                hits.append(f'{name} (end-to-end solving): {inp[:300]}')
            elif name in ('Read', 'Glob', 'Grep') and re.search(r'"(/(?!app\b|tmp\b)[^"]*)"', inp) and '/app' not in inp:
                hits.append(f'{name} outside /app: {inp[:200]}')
        if hits:
            tid = os.path.basename(json.load(open(os.path.join(trial, 'config.json')))['task']['path'].rstrip('/'))
            flagged[tid] = hits
    print(f'trials {n}; flagged {len(flagged)}')
    for k, v in list(flagged.items())[:20]:
        print(k, v[:3])
    if out:
        json.dump({'trials': n, 'flagged': flagged}, open(out, 'w'), indent=1)


if __name__ == '__main__':
    main()