FWeindel commited on
Commit
2807130
·
verified ·
1 Parent(s): 27b3db2

Correct CalibForge stage-1 checks and record static exclusions

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ calibforge/ablations/evidence/stage1-corrected-report.json filter=lfs diff=lfs merge=lfs -text
calibforge/ablations/evidence/nproc-affinity-audit.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "job_id": "1017578",
3
+ "cluster": "helma",
4
+ "node": "h31-62",
5
+ "allocation_cpus": 48,
6
+ "node_logical_cpus": 384,
7
+ "method": "Actual five cached task SIFs; Apptainer exec in Slurm steps using trial (2 CPUs) and build (4 CPUs, cpu-bind=none) resource settings. No compilation workload rerun.",
8
+ "findings": [
9
+ {
10
+ "task": "contrastive_solver-security_20260508_045740_002",
11
+ "mode": "trial",
12
+ "requested_cpus": 2,
13
+ "nproc": 2,
14
+ "nproc_all": 384,
15
+ "cpu_affinity": "136-137"
16
+ },
17
+ {
18
+ "task": "contrastive_solver-security_20260508_045740_002",
19
+ "mode": "build",
20
+ "requested_cpus": 4,
21
+ "nproc": 4,
22
+ "nproc_all": 384,
23
+ "cpu_affinity": "136-139"
24
+ },
25
+ {
26
+ "task": "contrastive_solver-software-engineering_20260510_053611_008",
27
+ "mode": "trial",
28
+ "requested_cpus": 2,
29
+ "nproc": 2,
30
+ "nproc_all": 384,
31
+ "cpu_affinity": "136-137"
32
+ },
33
+ {
34
+ "task": "contrastive_solver-software-engineering_20260510_053611_008",
35
+ "mode": "build",
36
+ "requested_cpus": 4,
37
+ "nproc": 4,
38
+ "nproc_all": 384,
39
+ "cpu_affinity": "136-139"
40
+ },
41
+ {
42
+ "task": "contrastive_solver-software-engineering_20260611_210349_008",
43
+ "mode": "trial",
44
+ "requested_cpus": 2,
45
+ "nproc": 2,
46
+ "nproc_all": 384,
47
+ "cpu_affinity": "136-137"
48
+ },
49
+ {
50
+ "task": "contrastive_solver-software-engineering_20260611_210349_008",
51
+ "mode": "build",
52
+ "requested_cpus": 4,
53
+ "nproc": 4,
54
+ "nproc_all": 384,
55
+ "cpu_affinity": "136-139"
56
+ },
57
+ {
58
+ "task": "contrastive_solver-system-administration_20260604_004411_008",
59
+ "mode": "trial",
60
+ "requested_cpus": 2,
61
+ "nproc": 2,
62
+ "nproc_all": 384,
63
+ "cpu_affinity": "136-137"
64
+ },
65
+ {
66
+ "task": "contrastive_solver-system-administration_20260604_004411_008",
67
+ "mode": "build",
68
+ "requested_cpus": 4,
69
+ "nproc": 4,
70
+ "nproc_all": 384,
71
+ "cpu_affinity": "136-139"
72
+ },
73
+ {
74
+ "task": "contrastive_solver-system-administration_20260604_004411_009",
75
+ "mode": "trial",
76
+ "requested_cpus": 2,
77
+ "nproc": 2,
78
+ "nproc_all": 384,
79
+ "cpu_affinity": "136-137"
80
+ },
81
+ {
82
+ "task": "contrastive_solver-system-administration_20260604_004411_009",
83
+ "mode": "build",
84
+ "requested_cpus": 4,
85
+ "nproc": 4,
86
+ "nproc_all": 384,
87
+ "cpu_affinity": "136-139"
88
+ }
89
+ ],
90
+ "conclusion": "Bare nproc respects the Slurm step CPU affinity in all ten probes; no full-node CPU expansion observed. This is scoped to the tested Helma Slurm/Apptainer execution path."
91
+ }
calibforge/ablations/evidence/stage1-checker-final.py ADDED
@@ -0,0 +1,890 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run pinned Terminal-Bench checks with training-task defaults and optional GPTZero."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ import threading
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
21
+ from validation.data.selection import discover_tasks
22
+ from validation.checks.supplied_references import discoverable_references
23
+
24
+ TERMINAL_BENCH = Path(__file__).resolve().parents[1] / 'upstream/terminal_bench'
25
+ # These are policy decisions in our wrapper; upstream files remain unmodified.
26
+ POLICY = {
27
+ 'check-canary.sh': 'Terminal-Bench-specific canary GUID',
28
+ 'check-task-fields.sh': 'benchmark author metadata, taxonomy and README sections',
29
+ 'check-task-timeout.sh': 'benchmark timeout caps',
30
+ 'check-instruction-suffix.sh': 'benchmark-specific instruction suffix',
31
+ 'check-instruction-headings.sh': 'benchmark prose-only instruction style',
32
+ 'check-gpu-types.sh': 'Modal-specific GPU allowlist',
33
+ 'check-resource-sizes.sh': 'benchmark CPU/memory size allowlist',
34
+ 'check-allow-internet.sh': 'benchmark requires default internet access',
35
+ 'check-no-allow-internet-true.sh': 'benchmark forbids explicit internet opt-in',
36
+ 'check-task-slug.sh': 'benchmark limit of three slug tokens',
37
+ 'check-task-package-name.sh': 'requires terminal-bench/<task> package namespace',
38
+ 'check-separate-verifier.sh': 'requires separate verifier mode for every task',
39
+ 'check-pytest-version.sh': 'benchmark-wide exact pytest/CTRF versions',
40
+ }
41
+ PR_ONLY = {'check-task-changelog.sh': 'training tasks do not require Terminal-Bench PR changelogs'}
42
+ TRAINING_EXCLUSIONS = {
43
+ 'check-test-sh-sanity.sh': 'training permits shared system Python and image-installed verifier dependencies; uv is not required, and stages 4/5 check execution',
44
+ 'check-separate-verifier.sh': 'training permits grading in the agent environment, including installed packages and changed system state; separate verification is optional',
45
+ 'check-allow-internet.sh': 'network policy is declared by the task and checked at runtime',
46
+ 'check-no-allow-internet-true.sh': 'explicit task network policies are allowed',
47
+ 'check-pytest-version.sh': 'training tasks may use other pinned pytest/CTRF versions',
48
+ 'check-gpu-types.sh': 'Modal GPU naming conventions do not apply to the Helma execution profile',
49
+ 'check-canary.sh': 'training tasks do not require a benchmark canary string',
50
+ 'check-instruction-headings.sh': 'Markdown headings are allowed in training instructions',
51
+ 'check-task-fields.sh': 'training tasks do not require TB author GitHub metadata, taxonomy or explanation sections',
52
+ 'check-task-package-name.sh': 'training task package names need not use the terminal-bench namespace',
53
+ 'check-task-slug.sh': 'training task names may contain more than three hyphen-separated tokens',
54
+ }
55
+ CHECKER_UNIT_TESTS = ('test-author-github.py', 'test-instruction-headings.sh',
56
+ 'test-resource-sizes.sh', 'test-task-changelog.sh')
57
+ AI_CHECK = 'check_ai_detection.py'
58
+ LOCAL_CHECKS = {'check-task-toml-schema.py': Path(__file__).with_name('task_toml_schema.py')}
59
+
60
+
61
+
62
+ def load_checks(profile, upstream=None, exclude=()):
63
+ manifest = json.loads((TERMINAL_BENCH / 'UPSTREAM.json').read_text())
64
+ # Detect accidental edits or incomplete copies before executing anything.
65
+ for name, digest in manifest['files'].items():
66
+ if hashlib.sha256(((upstream or TERMINAL_BENCH) / name).read_bytes()).hexdigest() != digest:
67
+ raise ValueError(f'upstream file differs from pinned copy: {name}')
68
+ names = sorted(Path(p).name for p in manifest['files'] if p.startswith('scripts/checks/'))
69
+ names = sorted([*names, *LOCAL_CHECKS])
70
+ excluded = {**PR_ONLY, **(POLICY if profile == 'portable' else TRAINING_EXCLUSIONS if profile == 'training' else {}),
71
+ 'rubric_review.py': 'LLM rubric review is opt-in via stage 2, never a default static check'}
72
+ inactive = {'rubric_review.py', *CHECKER_UNIT_TESTS}
73
+ for value in exclude:
74
+ # NAME=reason records why; a reason may contain commas, so it is one item.
75
+ value, _, reason = value.partition('=')
76
+ for requested in value.split(','):
77
+ requested = requested.strip()
78
+ aliases = {'ai-detection': 'check_ai_detection.py', 'rubric-review': 'rubric_review.py',
79
+ 'task-toml-schema': 'check-task-toml-schema.py',
80
+ 'check-task-toml-schema': 'check-task-toml-schema.py'}
81
+ name = aliases.get(requested, requested)
82
+ if name not in inactive and name != AI_CHECK and name not in LOCAL_CHECKS:
83
+ name = name if name.endswith('.sh') else name + '.sh'
84
+ name = name if name.startswith('check-') else 'check-' + name
85
+ if name not in names and name not in inactive:
86
+ raise ValueError(f'unknown static check: {requested}; use --list')
87
+ excluded[name] = (reason.strip() or 'explicitly excluded' if name in names else
88
+ 'upstream checker unit test, not dataset validation' if name in CHECKER_UNIT_TESTS else
89
+ 'not part of the static suite (LLM review is opt-in)')
90
+ return manifest, [n for n in names if n not in excluded], excluded
91
+
92
+
93
+ def validate_input(task):
94
+ import tomllib
95
+ for name in ('instruction.md', 'task.toml', 'tests/test.sh'):
96
+ if not (task / name).is_file():
97
+ raise ValueError(f'missing {name}')
98
+ if not (task / 'environment').is_dir():
99
+ raise ValueError('missing environment/')
100
+ with (task / 'task.toml').open('rb') as stream:
101
+ tomllib.load(stream)
102
+ if any(c.isspace() or c in '*?[]' for c in str(task)):
103
+ raise ValueError(f'task directory path must not contain whitespace or glob characters: {task}')
104
+
105
+
106
+ UNSAFE = re.compile(r'[\s*?\[\]]')
107
+
108
+
109
+ def safe_copy(task, scratch):
110
+ """Several upstream scripts split paths as shell words and expand globs, so a file
111
+ named `Clase 4/[id].ts` would be skipped or misread and the check could pass wrongly.
112
+ Such tasks are checked on a copy whose offending names have those characters
113
+ replaced by '_'. The task itself is unchanged. Returns (copy, renamed) or (task, [])."""
114
+ renamed = sorted(str(p.relative_to(task)) for p in task.rglob('*') if UNSAFE.search(str(p.relative_to(task))))
115
+ if not renamed:
116
+ return task, []
117
+ copy = Path(scratch) / 'renamed' / task.name
118
+ if copy.exists():
119
+ shutil.rmtree(copy)
120
+ for path in task.rglob('*'):
121
+ target = copy / UNSAFE.sub('_', str(path.relative_to(task)))
122
+ if path.is_dir():
123
+ target.mkdir(parents=True, exist_ok=True)
124
+ else:
125
+ target.parent.mkdir(parents=True, exist_ok=True)
126
+ shutil.copyfile(path, target)
127
+ return copy, renamed
128
+
129
+
130
+ PATH_CHECK = 'check-task-absolute-path.sh'
131
+ SHELL_FENCES = {'', 'bash', 'sh', 'shell', 'zsh', 'console', 'text', 'txt'}
132
+ ADAPTATIONS = {PATH_CHECK: 'Relative-path findings are advisory warnings and do not fail stage 1. Runs on a copy of the task whose instruction.md has its source-code blocks removed '
133
+ '(fenced blocks tagged with a programming language); masks complete absolute paths '
134
+ 'and JavaScript console calls/sed substitutions so their substrings are not mistaken for paths; '
135
+ 'masks complete non-file URLs, quoted absolute paths with spaces, simple inline commands rooted by cd /absolute/path &&, '
136
+ 'and literal relative symlink targets with explicit absolute link locations; '
137
+ 'skips all Markdown fenced blocks, recognizes $HOME/${HOME}/~/ paths, and accepts adjacent literal cd and command lines; '
138
+ 'accepts explicit named-file-in-directory clauses, pure parent-navigation commands, and relative command tokens for uniquely absolute-named executables; '
139
+ 'unresolved relative file references outside fenced blocks are otherwise kept',
140
+ 'check-test-file-references.sh': 'masks complete non-file URLs, XML hostnames and excluded system paths; fixes full-token extraction and shell redirections, preserving basenames without inventing /app paths; accepts conventional boot artifacts, explicit numeric X filename ranges, explicit label filename templates resolved from supplied label:glob configurations, and references discovered through named supplied files/directories; reads literal writes and copies/moves in explicitly invoked local setup shell scripts without executing them, with source evidence',
141
+ 'check-pip-pinning.sh': 'recognizes SHA-256-pinned HTTP(S) requirements as single shell arguments; masks unquoted shell redirections and argument forwarding in generated offline installer heredocs, retaining actual package installations',
142
+ 'check-nproc.sh': 'training permits measurement-only variables and the exact audited InferredBugs Python 2.7.18 Dockerfile build on Maven Java 8/11/17 (Helma Slurm affinity probes 934209/934274); also permits four content-pinned SETA solutions tested with 1/2 CPUs (Helma probe 948213); other worker selection remains checked; not a Docker quota-only portability guarantee',
143
+ 'file names': 'a task with whitespace or *?[] in a file name is checked on a copy where those characters '
144
+ 'are replaced by _, because the upstream scripts split paths at spaces and expand globs; '
145
+ 'the renamed files are listed per task'}
146
+ ADAPTATIONS['check-dockerfile-references.sh'] = 'Ignore full-line Dockerfile comments; executable references remain checked on a scratch copy.'
147
+ ADAPTATIONS['check-dockerfile-sanity.sh'] = 'Inspect apt install arguments within RUN commands, including continuations and quoted pins; do not scan unrelated ENV assignments or embedded source following apt.'
148
+ ADAPTATIONS['check-nproc.sh'] += ' Also permits five content-pinned CalibForge image/script pairs measured at 2/4 CPUs in Helma job 1017578; nproc --all still saw 384 node CPUs.'
149
+ ADAPTATIONS['check-task-toml-schema.py'] = (
150
+ 'Local deterministic replacement for the task_toml_schema rubric: validates against pinned Harbor models '
151
+ 'and rejects unrecognized fields recursively; Harbor free-form metadata/env mappings remain allowed.')
152
+
153
+
154
+ def without_source_code(instruction):
155
+ """Drop fenced blocks tagged with a programming language: file names inside code
156
+ to read or complete are not paths the task tells the agent to use.
157
+
158
+ Source code can itself contain Markdown fences and '#' lines, so the first bare
159
+ fence is not always the end of the block. The block ends at the first bare fence
160
+ that is followed by a heading or by the end of the text; if there is none before
161
+ the next tagged block, it ends at the first bare fence."""
162
+ lines, kept, i = instruction.split('\n'), [], 0
163
+ fence = lambda line: re.fullmatch(r'\s*```\s*([A-Za-z0-9_+#.-]*)\s*', line)
164
+ def before_heading(j):
165
+ following = next((l for l in lines[j + 1:] if l.strip()), None)
166
+ return following is None or re.match(r'#{1,6} ', following) is not None
167
+ while i < len(lines):
168
+ match = fence(lines[i])
169
+ if not match or match.group(1).lower() in SHELL_FENCES:
170
+ kept.append(lines[i])
171
+ i += 1
172
+ continue
173
+ bare = []
174
+ for j in range(i + 1, len(lines)):
175
+ inner = fence(lines[j])
176
+ if inner and inner.group(1):
177
+ break # the next tagged block starts here
178
+ if inner:
179
+ bare.append(j)
180
+ closing = next((j for j in bare if before_heading(j)), bare[0] if bare else None)
181
+ if closing is None: # unterminated block: leave the text for the check to see
182
+ kept.append(lines[i])
183
+ i += 1
184
+ continue
185
+ kept.append(f'[{match.group(1)} source code removed for the path check]')
186
+ i = closing + 1
187
+ return '\n'.join(kept)
188
+
189
+
190
+ def without_urls(text):
191
+ # Mask whole tokens before upstream extracts filename-like suffixes.
192
+ text = re.sub(r'\b(?![Ff][Ii][Ll][Ee]://)[A-Za-z][A-Za-z0-9+.-]*://[^\s`\"\'<>]+', '[URL]', text)
193
+ # Bare host/path form, e.g. mirrors.ubuntu.com/mirrors.txt.
194
+ return re.sub(r'\b(?:[A-Za-z0-9-]+\.)+(?:com|org|net|edu|gov|io)/[^\s`\"\'<>]+', '[URL]', text)
195
+
196
+
197
+ def without_fenced_blocks(text):
198
+ """Skip Markdown fences of any language, including untagged and shell blocks."""
199
+ kept, opening = [], None
200
+ for line in text.splitlines(keepends=True):
201
+ match = re.match(r'^ {0,3}(`{3,}|~{3,})(.*)$', line.rstrip('\n'))
202
+ if opening is None:
203
+ if match:
204
+ opening = match[1]
205
+ kept.append('[fenced block omitted from path check]\n')
206
+ else:
207
+ kept.append(line)
208
+ elif (match and match[1][0] == opening[0]
209
+ and len(match[1]) >= len(opening) and not match[2].strip()):
210
+ opening = None
211
+ return ''.join(kept)
212
+
213
+
214
+ # Specific conventional interfaces, not an exemption for everything under /boot.
215
+ CONVENTIONAL_REFERENCE_PATHS = (
216
+ r'/boot/grub/grub\.cfg',
217
+ r'/boot/initrd\.img-[0-9][A-Za-z0-9_.+-]*',
218
+ )
219
+
220
+
221
+ def reference_check_script(source):
222
+ """Correct lexical extraction on a temporary copy of pinned upstream."""
223
+ old = "grep -E '^/(app|home|tests|tmp|usr|var|etc)/'"
224
+ if source.count(old) != 1 or source.count('/[a-zA-Z0-9_./]+\\.') != 1:
225
+ raise ValueError('upstream file-reference extractor changed')
226
+ source = source.replace(old, "grep -E '^/'")
227
+ # A quoted basename supplies no working directory. Keep it as a basename.
228
+ source = source.replace("sed 's|^|/app/|'", 'cat')
229
+ # Upstream uses optional quote markers (?) with basic sed regex syntax.
230
+ # Extended regex syntax is required to strip the redirection / -o prefix.
231
+ source = source.replace("sed 's/^>\\s*", "sed -E 's/^>\\s*")
232
+ source = source.replace("sed 's/^-o\\s*", "sed -E 's/^-o\\s*")
233
+ # Consume the full basename, including suffixes after .img (kernel versions).
234
+ lines = source.splitlines(keepends=True)
235
+ for i, line in enumerate(lines):
236
+ if '/[a-zA-Z0-9_./]+\\.' in line:
237
+ line = line.replace('/[a-zA-Z0-9_./]+\\.', '/[a-zA-Z0-9_./-]+\\.')
238
+ line = line.replace("grep -oE '/", "grep -oE '(^|[[:space:]=])/")
239
+ lines[i] = line.replace("wad)'", "wad)[a-zA-Z0-9_.+-]*'").rstrip('\n') + " | sed 's|^[^/]||'\n"
240
+ return ''.join(lines)
241
+
242
+
243
+ def reference_check_text(text):
244
+ text = without_urls(text)
245
+ text = re.sub(r'file://(?=/)', '', text)
246
+ text = re.sub(r'<host>[^<\n]+</host>', '<host>[hostname]</host>', text)
247
+ # Upstream deliberately excludes these system roots, but its second regex
248
+ # can truncate a hyphenated path into e.g. /xsettings.xml and flag it again.
249
+ text = re.sub(r'/(?:tests|tmp|usr|var|etc)/[^\s`\"\'<>;]+', '[system path]', text)
250
+ for path in CONVENTIONAL_REFERENCE_PATHS:
251
+ text = re.sub(r'(?<![\w/])' + path + r'(?![\w./+-])', '[conventional boot artifact]', text)
252
+ return text
253
+
254
+
255
+ def numeric_reference_patterns(instruction, sources):
256
+ """Accept an X filename template only with an explicit numeric X range."""
257
+ bounds = re.search(r'\b(?:where\s+)?X\s+is\s+(\d+)\s*[-–]\s*(\d+)\b', instruction)
258
+ if not bounds:
259
+ return {}
260
+ low, high = map(int, bounds.groups())
261
+ result = {}
262
+ for match in re.finditer(r'\b([A-Za-z0-9_.-]*_X(?:_[A-Za-z0-9_.-]+)?\.[A-Za-z0-9]+)\b', instruction):
263
+ template = match.group(1)
264
+ expression = re.escape(template).replace('_X', r'_(\d+)')
265
+ for candidate in re.finditer(r'(?<![\w.-])' + expression + r'(?![\w.-])', sources):
266
+ if low <= int(candidate.group(1)) <= high:
267
+ result[candidate.group(0)] = {'instruction_pattern': template, 'numeric_range': [low, high]}
268
+ return result
269
+
270
+
271
+ def pip_check_line(line):
272
+ """Adapt shell syntax on the check copy, never rewriting the installation."""
273
+ from packaging.requirements import Requirement, InvalidRequirement
274
+ from urllib.parse import urlsplit
275
+ # Keep quotes intact so quoted '>' and spaces inside requirements are not
276
+ # mistaken for shell operators or separate package arguments.
277
+ pattern = r'''(?:\d+)?(?:>>?|<<?)&?|&&|\|\||[;|&]|(?:[^\s'"\\<>;&|]+|\\[^\n]|'[^']*'|"(?:\\.|[^"\\])*")+'''
278
+ tokens = list(re.finditer(pattern, line))
279
+ cursor = 0
280
+ for token in tokens:
281
+ if line[cursor:token.start()].strip():
282
+ return line # Unsupported/malformed shell syntax: keep the finding.
283
+ cursor = token.end()
284
+ if line[cursor:].strip():
285
+ return line
286
+ edits, i = [], 0
287
+ while i < len(tokens):
288
+ token = tokens[i]
289
+ raw = token.group()
290
+ if raw.startswith('#'):
291
+ break
292
+ if re.fullmatch(r'(?:\d+)?(?:>>?|<)&?', raw) and i + 1 < len(tokens):
293
+ destination = tokens[i + 1]
294
+ if destination.group() not in ('&&', '||', ';', '|', '&'):
295
+ edits.append((token.start(), destination.end(), ' '))
296
+ i += 2
297
+ continue
298
+ try:
299
+ value, = shlex.split(raw)
300
+ except ValueError:
301
+ i += 1
302
+ continue
303
+ url = value
304
+ name = 'hash-pinned-artifact'
305
+ try:
306
+ requirement = Requirement(value)
307
+ if requirement.url and not requirement.marker:
308
+ url, name = requirement.url, requirement.name
309
+ except InvalidRequirement:
310
+ pass
311
+ try:
312
+ parsed = urlsplit(url)
313
+ except ValueError:
314
+ i += 1
315
+ continue
316
+ if (parsed.scheme in ('http', 'https') and parsed.netloc
317
+ and not any(c in url for c in '$`\\')
318
+ and re.fullmatch(r'sha256=[0-9a-fA-F]{64}', parsed.fragment)):
319
+ # Upstream understands == pins, but splits direct references at
320
+ # spaces. This placeholder exists only in its scratch input.
321
+ edits.append((token.start(), token.end(), name + '==0'))
322
+ i += 1
323
+ for start, end, replacement in reversed(edits):
324
+ line = line[:start] + replacement + line[end:]
325
+ return line
326
+
327
+
328
+ def pip_check_text(text):
329
+ # Generated offline installers are tools accepting user-specified packages,
330
+ # not an unpinned install into the task environment. Only exempt forwarding
331
+ # inside a quoted heredoc; retain concrete installs inside those heredocs.
332
+ lines, delimiter = [], None
333
+ for line in text.splitlines(keepends=True):
334
+ if delimiter and line.strip() == delimiter:
335
+ delimiter = None
336
+ elif delimiter and re.fullmatch(
337
+ r'\s*pip3? install --no-index --find-links="\$SCRIPT_DIR" "\$@"\s*', line):
338
+ line = '# generated offline installer forwards caller arguments\n'
339
+ if delimiter is None:
340
+ match = re.search(r"<<\s*['\"]([A-Za-z_][A-Za-z0-9_]*)['\"]", line)
341
+ if match:
342
+ delimiter = match.group(1)
343
+ lines.append(pip_check_line(line))
344
+ return ''.join(lines)
345
+
346
+
347
+ # Content-pinned CPU-affinity audit: Helma job 1017578, all five images at 2/4 CPUs.
348
+ CALIBFORGE_REVIEWED_NPROC = {'contrastive_solver-security_20260508_045740_002': {'file': 'environment/Dockerfile',
349
+ 'sha256': {'environment/Dockerfile': '8554c71778e6d80171e69483cafc1c53f016d16607b586eb8d259936c2996ad1'}},
350
+ 'contrastive_solver-software-engineering_20260510_053611_008': {'file': 'environment/Dockerfile',
351
+ 'sha256': {'environment/Dockerfile': 'fe371f2e4d5ccf5ac295269324bf2d7dbfb6d3e10377e84910f457f384f365cb'}},
352
+ 'contrastive_solver-software-engineering_20260611_210349_008': {'file': 'tests/test.sh',
353
+ 'sha256': {'environment/Dockerfile': '4f6194d3d652fd8cb9d9de5681211adf5ba57146718f2fc0db9d977d11f8d8b7',
354
+ 'tests/test.sh': 'b7f4a23eaffed3576d649078f6bb09f89b84e2a5573063b53552799af644560a'}},
355
+ 'contrastive_solver-system-administration_20260604_004411_008': {'file': 'environment/Dockerfile',
356
+ 'sha256': {'environment/Dockerfile': '47c7d9e917e98d3965d48a380c1d82a2fd774505857ccfdcc6bfdaacba388db9'}},
357
+ 'contrastive_solver-system-administration_20260604_004411_009': {'file': 'environment/Dockerfile',
358
+ 'sha256': {'environment/Dockerfile': 'bbe5c1425ac6323702e29c0faae4d27efa23de0c6202797491ed5343887a2373'}}}
359
+
360
+
361
+ def dockerfile_without_comments(text):
362
+ """Ignore full-line Dockerfile comments, retaining inline arguments/data."""
363
+ kept, heredocs = [], []
364
+ for line in text.splitlines(keepends=True):
365
+ if heredocs:
366
+ kept.append(line)
367
+ if line.strip() == heredocs[0]:
368
+ heredocs.pop(0)
369
+ continue
370
+ if line.lstrip().startswith('#'):
371
+ continue
372
+ kept.append(line)
373
+ # Heredoc payload is data, not Dockerfile comments.
374
+ heredocs.extend(re.findall(r"<<-?\s*['\"]?([A-Za-z_][A-Za-z0-9_]*)['\"]?", line))
375
+ return ''.join(kept)
376
+
377
+
378
+ def dockerfile_sanity_text(text):
379
+ """Give upstream only apt command arguments, not the next 20 source lines.
380
+
381
+ Shell tokenization preserves quoted pins and joins continued RUN commands.
382
+ Unparseable shell is kept for conservative upstream checking.
383
+ """
384
+ text = dockerfile_without_comments(text)
385
+ logical = re.sub(r'\\\n', ' ', text)
386
+ commands = []
387
+ for line in logical.splitlines():
388
+ if not re.match(r'^\s*RUN\s', line, re.I):
389
+ continue
390
+ if re.search(r'\bapt(?:-get)?\b', line) and ('<<' in line or re.match(r'^\s*RUN\s*\[', line, re.I) or re.search(r'\b(?:sh|bash)\s+-c', line)):
391
+ return text # Preserve conservative checking of unsupported shell forms.
392
+ try:
393
+ lexer = shlex.shlex(line, posix=True, punctuation_chars=';&|()<>' )
394
+ lexer.whitespace_split = True
395
+ tokens = list(lexer)
396
+ except ValueError:
397
+ return text
398
+ for i, token in enumerate(tokens):
399
+ if token.rsplit('/', 1)[-1] not in ('apt', 'apt-get'):
400
+ continue
401
+ args = []
402
+ for arg in tokens[i + 1:]:
403
+ if arg and all(c in ';&|()<>' for c in arg):
404
+ break
405
+ args.append(arg)
406
+ # Keep update/cleanup advisory behavior, but expose version pins
407
+ # only in install arguments. Epochs/integer pins count too.
408
+ if 'install' in args:
409
+ if (i and tokens[i - 1] not in ('RUN', 'run', '&&', '||', ';', '|', 'sudo', 'env', 'then', 'do', '{', '(', '!')
410
+ and not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', tokens[i - 1])):
411
+ return text # Do not silently exempt unknown command wrappers.
412
+ packages = args[args.index('install') + 1:]
413
+ pinned = [a for a in packages if re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9+.:_-]*=[^=\s]+', a)]
414
+ commands.append('RUN apt install ' + ('pinned-package=1.0' if pinned else 'packages'))
415
+ elif 'update' in args:
416
+ commands.append('RUN apt update')
417
+ if 'rm -rf /var/lib/apt/lists' in text:
418
+ commands.append('RUN rm -rf /var/lib/apt/lists/*')
419
+ return '\n'.join(commands) + '\n'
420
+
421
+
422
+ def calibforge_nproc_text(text, task, relative):
423
+ """Allow only the exact image/script pairs measured in Helma job 1017578."""
424
+ record = CALIBFORGE_REVIEWED_NPROC.get(task.name)
425
+ if not record or relative != record['file']:
426
+ return text
427
+ for filename, digest in record['sha256'].items():
428
+ path = task / filename
429
+ if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != digest:
430
+ return text
431
+ return text.replace('$(nproc)', 'VERIFIED_CPU_AFFINITY')
432
+
433
+
434
+ def nproc_check_text(text, *, dockerfile=False):
435
+ """Conservatively recognize measurement-only variables; not a shell parser.
436
+
437
+ Also recognize the exact Python 2 build audited under Slurm CPU affinity.
438
+ Other build flags and unknown uses retain the original check.
439
+ """
440
+ if dockerfile and re.search(r'^FROM maven:3\.9-eclipse-temurin-(?:8|11|17)$', text, re.M):
441
+ # Match the build context and complete command, not make/nproc generally.
442
+ # Mask only on the check's scratch copy; the actual task is unchanged.
443
+ reviewed = (
444
+ ' && tar -xzf "$d/python2.tgz" -C "$d" && cd "$d/Python-2.7.18" \\\n'
445
+ ' && ./configure --prefix=/opt/python2 --disable-shared --without-ensurepip >/dev/null '
446
+ '&& make -j"$(nproc)" >/dev/null && make install >/dev/null \\\n'
447
+ ' && cd / && rm -rf "$d" && /opt/python2/bin/python2.7 -c "import zlib"'
448
+ )
449
+ text = text.replace(reviewed, reviewed.replace('$(nproc)', 'VERIFIED_CPU_AFFINITY'))
450
+ lines = text.splitlines(keepends=True)
451
+ for i, line in enumerate(lines):
452
+ assignment = re.fullmatch(r'\s*([A-Za-z_]\w*)="?\$\(nproc\)"?\s*', line)
453
+ if not assignment:
454
+ continue
455
+ var = assignment.group(1)
456
+ refs = re.compile(r'\$(?:' + re.escape(var) + r'\b|\{' + re.escape(var) + r'\})')
457
+ uses = [s.strip() for s in lines if refs.search(s) and not s.lstrip().startswith('#')]
458
+ def measurement(s):
459
+ # JSON fields: no command substitutions, backticks or shell chains.
460
+ if s.startswith(('{"', '"')) and not re.search(r'\$\(|`|[;&|]', s):
461
+ return True
462
+ if re.fullmatch(r'if \(\( \$\(echo "\$\w+ > \$' + re.escape(var) + r'" \| bc -l\) \)\); then', s):
463
+ return True
464
+ return bool(re.fullmatch(r'alerts(?:\+)?=\(?"[^\n]*"\)?', s)) and not re.search(r'\$\(|`|[;&|]', s)
465
+ if uses and all(measurement(s) for s in uses):
466
+ lines[i] = line.replace('$(nproc)', 'CPU_MEASUREMENT')
467
+ return ''.join(lines)
468
+
469
+
470
+ def adapted_check_copy(task, scratch, name, profile):
471
+ transforms = {'check-test-file-references.sh': reference_check_text,
472
+ 'check-pip-pinning.sh': pip_check_text,
473
+ 'check-dockerfile-references.sh': dockerfile_without_comments,
474
+ 'check-dockerfile-sanity.sh': dockerfile_sanity_text}
475
+ if profile == 'training':
476
+ transforms['check-nproc.sh'] = nproc_check_text
477
+ if name not in transforms:
478
+ return task
479
+ copy = Path(scratch) / name / task.name
480
+ # Only files consumed by these checks. Avoid copying potentially large setup
481
+ # archives for each adaptation.
482
+ paths = ['instruction.md', 'task.toml', 'environment/Dockerfile',
483
+ 'tests/Dockerfile', 'tests/test.sh', 'solution/solve.sh']
484
+ paths.extend(str(p.relative_to(task)) for p in (task / 'tests').rglob('test_*.py'))
485
+ for relative in paths:
486
+ source = task / relative
487
+ if source.is_file():
488
+ target = copy / relative
489
+ target.parent.mkdir(parents=True, exist_ok=True)
490
+ text = source.read_text(errors='replace')
491
+ if name == 'check-nproc.sh' and relative not in ('instruction.md', 'task.toml'):
492
+ if profile == 'training' and relative == 'solution/solve.sh':
493
+ from data.seta.patch import reviewed_nproc_text
494
+ dockerfile = task / 'environment/Dockerfile'
495
+ text = reviewed_nproc_text(text, task.name,
496
+ dockerfile.read_bytes() if dockerfile.is_file() else b'')
497
+ text = calibforge_nproc_text(text, task, relative)
498
+ text = nproc_check_text(text, dockerfile=relative == 'environment/Dockerfile')
499
+ elif relative not in ('instruction.md', 'task.toml'):
500
+ text = transforms[name](text)
501
+ target.write_text(text)
502
+ if name == 'check-test-file-references.sh':
503
+ evidence = discoverable_references(task)
504
+ if (copy / 'instruction.md').is_file():
505
+ sources = '\n'.join((copy / p).read_text(errors='replace') for p in paths
506
+ if p not in ('instruction.md', 'task.toml') and (copy / p).is_file())
507
+ evidence.update(numeric_reference_patterns((copy / 'instruction.md').read_text(), sources))
508
+ (copy / 'discovered-references.json').write_text(json.dumps(evidence, indent=2))
509
+ if (copy / 'instruction.md').is_file():
510
+ with (copy / 'instruction.md').open('a') as stream:
511
+ stream.write('\nSupplied entry points reveal these references:\n' + '\n'.join(evidence) + '\n')
512
+ return copy
513
+
514
+
515
+ def named_path_examples(text):
516
+ """Recognize explicit location clauses and reuse unique executable locations."""
517
+ locations = {}
518
+ def remember(path):
519
+ if not any(c in path for c in '$*?[]{}'):
520
+ locations.setdefault(path.rsplit('/', 1)[-1], set()).add(path)
521
+ for match in re.finditer(r'''(?<![\w./])/(?!/)[A-Za-z0-9_.+@/-]+(?=$|[\s`"'<>|;,:!?)])''', text):
522
+ remember(match[0].rstrip('.,:'))
523
+
524
+ # Join only this explicit grammatical construction, never nearby paths.
525
+ clause = re.compile(
526
+ r'''\b(?:file|script|executable|utility|tool)\s+(?:named|called)\s+'''
527
+ r'''(?P<quote>[`"']?)(?P<name>[A-Za-z0-9_-][A-Za-z0-9_.+-]*)(?P=quote)'''
528
+ r'''\s+in\s+(?P<dirquote>[`"']?)(?P<directory>/[A-Za-z0-9_.+@/-]+)(?P=dirquote)(?=$|[\s.,:;!?])''', re.I)
529
+ def specified(match):
530
+ directory = match['directory'].rstrip('.,:')
531
+ remember(directory.rstrip('/') + '/' + match['name'])
532
+ start, end = match.span('name')
533
+ start, end = start - match.start(), end - match.start()
534
+ return match[0][:start] + '[explicitly located filename]' + match[0][end:]
535
+ text = clause.sub(specified, text)
536
+
537
+ def invocation(match):
538
+ value = match[1]
539
+ # Mask only ./NAME at command position. Arguments remain checked.
540
+ token = re.match(r'\./(?P<name>[A-Za-z0-9_-][A-Za-z0-9_.+-]*)(?=\s|$)', value)
541
+ if token and len(locations.get(token['name'], set())) == 1:
542
+ return '`[explicitly located executable]' + value[token.end():] + '`'
543
+ return match[0]
544
+ return re.sub(r'`([^`\n]+)`', invocation, text)
545
+
546
+
547
+ def explicit_path_examples(text):
548
+ """Mask locally specified command/link examples, without inferring global cwd."""
549
+ def literal(value):
550
+ return bool(value) and not any(c in value for c in '$`*?[]{}<>\n')
551
+
552
+ def inline(match):
553
+ value = match.group(1)
554
+ try:
555
+ tokens = list(shlex.shlex(value, posix=True, punctuation_chars=';&|<>'))
556
+ except ValueError:
557
+ return match.group(0)
558
+ if re.fullmatch(r'cd\s+(?:--\s+)?\.\.(?:/\.\.)*/?', value.strip()):
559
+ return '[parent navigation]'
560
+ # Only a single command after &&. Extra shell operators, dynamic
561
+ # expressions and another directory change remain review findings.
562
+ args = tokens[1:] if tokens[:1] == ['cd'] else []
563
+ if args[:1] == ['--']:
564
+ args = args[1:]
565
+ if (len(args) >= 3 and args[0].startswith('/') and args[1] == '&&'
566
+ and args[2] not in ('cd', 'pushd', 'popd', 'eval')
567
+ and '-c' not in args[2:]
568
+ and all(literal(t) and not any(c in t for c in ';&|()') for t in [args[0], *args[2:]])):
569
+ return '[command with explicit directory]'
570
+ # ln -s TARGET /absolute/LINK defines the relative target's base.
571
+ if (len(tokens) == 4 and tokens[:2] == ['ln', '-s']
572
+ and tokens[2].startswith(('./', '../')) and tokens[3].startswith('/')
573
+ and all(literal(t) for t in tokens[2:])):
574
+ return '[symlink with explicit location]'
575
+ return match.group(0)
576
+
577
+ # Two adjacent command lines can establish the same local base as &&.
578
+ # Do not carry that directory across paragraphs or unrelated prose.
579
+ def adjacent(match):
580
+ commands = [line.strip().strip('`') for line in match[0].splitlines()]
581
+ combined = '`' + commands[0] + ' && ' + commands[1] + '`'
582
+ result = inline(re.fullmatch(r'`([^`\n]+)`', combined))
583
+ return result if result != combined else match[0]
584
+ text = re.sub(r'(?m)^ {0,3}`?cd [^\n`]+`?\n {0,3}(?:`[^`\n]+`|[^`\n]+)$', adjacent, text)
585
+ text = re.sub(r'`([^`\n]+)`', inline, text)
586
+ absolute = r'''(?:`/[^`\n]+`|"/[^"\n]+"|'/[^'\n]+'|/[^\s`"'<>|;]+)'''
587
+ relative = r'''(?:`\.{1,2}/[^`\n]+`|"\.{1,2}/[^"\n]+"|'\.{1,2}/[^'\n]+'|\.{1,2}/[^\s`"'<>|;]+)'''
588
+ mapping = re.compile(r'(?P<link>' + absolute + r')\s*->\s*(?P<target>' + relative + r')')
589
+ paragraphs = re.split(r'(\n\s*\n)', text)
590
+ for i, paragraph in enumerate(paragraphs):
591
+ if not re.search(r'\b(?:symlink|symbolic\s+link)s?\b', paragraph, re.I):
592
+ continue
593
+ established = set()
594
+ def link(match):
595
+ location = match['link'].strip('`"\'')
596
+ target = match['target'].strip('`"\'')
597
+ if literal(location) and literal(target):
598
+ established.update((target, target.rsplit('/', 1)[0] + '/'))
599
+ return match['link'] + ' -> [relative symlink target]'
600
+ return match.group(0)
601
+ paragraph = mapping.sub(link, paragraph)
602
+ # The same paragraph may reiterate the literal target or its directory.
603
+ # Only these exact inline strings inherit the established link location.
604
+ paragraphs[i] = re.sub(r'`([^`\n]+)`',
605
+ lambda m: '[specified symlink reference]' if m[1] in established else m[0],
606
+ paragraph)
607
+ return ''.join(paragraphs)
608
+
609
+
610
+ def path_check_text(instruction):
611
+ """Adapt known lexical false positives without changing pinned upstream code."""
612
+ text = without_fenced_blocks(without_source_code(instruction))
613
+ text = without_urls(text)
614
+ text = named_path_examples(text)
615
+ text = explicit_path_examples(text)
616
+ # HOME is case-sensitive in shells. Unknown variables remain unresolved.
617
+ text = re.sub(r'''(?<![\w$])(?:\$HOME|\$\{HOME\}|~)/[^\s`"'<>|;]+''',
618
+ '[home-anchored path]', text)
619
+ # A relative command with an explicit working directory on the same line
620
+ # is unambiguous. Do not infer a global cwd from unrelated absolute paths.
621
+ text = re.sub(r'`(\./[^`\n]+)`(?= from `/[^`\n]+`)', '[rooted command]', text)
622
+ # Quoted absolute paths can contain spaces; consume before bare tokens.
623
+ text = re.sub(r'`/[^`\n]+`', '`[absolute path]`', text)
624
+ # Consume the WHOLE absolute token, including @ and hyphens in systemd units.
625
+ # Replacing tokens individually also prevents upstream's global substring
626
+ # filter from excusing a relative path merely because an absolute one exists.
627
+ text = re.sub(r'''(?<![\w./])/(?!/)[^\s`"'<>|;]+''', '[absolute path]', text)
628
+ lines = []
629
+ method = r'console\.(?:log|warn|error|info|debug|trace|table)'
630
+ for line in text.splitlines(keepends=True):
631
+ code_context = re.search(r'\b(?:JavaScript|regex|calls?|references?|strings?|literals?|statements?)\b', line, re.I)
632
+ def inline(match):
633
+ value = match.group(1)
634
+ # A sed substitution is an expression, not a directory reference.
635
+ if re.fullmatch(r's/[^\n]*/[^\n]*/[gip0-9]*', value):
636
+ return '`[sed expression]`'
637
+ if re.search(method + r'\s*\(', value) or (code_context and re.fullmatch(method, value)):
638
+ return '`' + re.sub(method, '[JavaScript method]', value) + '`'
639
+ return match.group(0)
640
+ line = re.sub(r'`([^`\n]+)`', inline, line)
641
+ if code_context:
642
+ line = re.sub(r'(["\'])(' + method + r')\1', '[JavaScript method]', line)
643
+ lines.append(line)
644
+ return ''.join(lines)
645
+
646
+
647
+ def path_check_copy(task, scratch):
648
+ copy = Path(scratch) / 'path-check' / task.name
649
+ (copy / 'environment').mkdir(parents=True, exist_ok=True)
650
+ (copy / 'instruction.md').write_text(path_check_text((task / 'instruction.md').read_text(errors='replace')))
651
+ for name in ('task.toml', 'environment/Dockerfile'):
652
+ if (task / name).is_file():
653
+ shutil.copyfile(task / name, copy / name)
654
+ return copy
655
+
656
+
657
+ def rebuild_summary(out):
658
+ """Reconstruct completed outcomes; ignore only an unfinished final journal line."""
659
+ out = Path(out)
660
+ summary = out / 'summary.json'
661
+ report = json.loads(summary.read_text())
662
+ expected = [Path(path).name for path in report['selected_tasks']]
663
+ expected_names = set(expected)
664
+ entries = {}
665
+ incomplete_tail = False
666
+ with (out / 'outcomes.jsonl').open() as stream:
667
+ for line in stream:
668
+ if not line.endswith('\n'):
669
+ incomplete_tail = True
670
+ break
671
+ entry = json.loads(line)
672
+ name = entry['task']
673
+ if name not in expected_names or name in entries:
674
+ raise ValueError(f'unknown or duplicate journal task: {name}')
675
+ entries[name] = entry
676
+ report['tasks'] = [entries[name] for name in expected if name in entries]
677
+ report['complete'] = len(entries) == len(expected) and not incomplete_tail
678
+ report['passed'] = report['complete'] and all(t['status'] == 'passed' for t in report['tasks'])
679
+ report['incomplete_journal_tail'] = incomplete_tail
680
+ pending = summary.with_suffix('.json.tmp')
681
+ pending.write_text(json.dumps(report, indent=2) + '\n')
682
+ pending.replace(summary)
683
+ return report
684
+
685
+
686
+ def run_checks(tasks, out, profile='training', timeout=300, upstream=None, exclude=(), concurrency=1,
687
+ resume=None, resume_record=None, accept_previous_path_check=False):
688
+ if concurrency < 1:
689
+ raise ValueError('concurrency must be positive')
690
+ if sys.version_info < (3, 11):
691
+ raise ValueError('Terminal-Bench checks require Python 3.11+; activate your prep environment')
692
+ manifest, checks, excluded = load_checks(profile, upstream, exclude)
693
+ if not checks:
694
+ raise ValueError('no static checks selected')
695
+ for command in ('bash', 'grep', 'sed', 'awk', 'find', 'sort', 'uniq', 'mktemp', 'dirname', 'basename', 'cat', 'tr', 'rm'):
696
+ if not shutil.which(command):
697
+ raise ValueError(f'missing required executable: {command}')
698
+ out.mkdir(parents=True, exist_ok=True)
699
+ if (out / 'outcomes.jsonl').exists():
700
+ raise ValueError('output already has task outcomes; use a new output directory or --rebuild-summary')
701
+ report = {'upstream': manifest['repository'], 'commit': manifest['commit'],
702
+ 'concurrency': concurrency, 'profile': profile, 'selected_tasks': [str(t) for t in tasks],
703
+ 'checks': checks, 'excluded_checks': excluded, 'tasks': [],
704
+ 'adaptations': {name: text for name, text in ADAPTATIONS.items() if name in checks or name == 'file names'},
705
+ 'checker_unit_tests_not_run': list(CHECKER_UNIT_TESTS),
706
+ 'conditional_checks': {AI_CHECK: 'runs only when GPTZERO_API_KEY is configured; missing key is a non-failing skip'},
707
+ 'complete': False, 'passed': False}
708
+ imported = {}
709
+ if resume:
710
+ from validation.checkpoints.static_resume import load
711
+ imported, report['resumed_from'] = load(resume, tasks, manifest, checks, profile, resume_record,
712
+ accept_previous_path_check)
713
+ print(f"Static checkpoint: importing {report['resumed_from']['imported_checks']} checks; "
714
+ f"rerunning changed checks {report['resumed_from']['rerun_changed_checks']}", flush=True)
715
+ for name, reason in excluded.items():
716
+ print(f'SKIP {name}: {reason}', flush=True)
717
+ if AI_CHECK in checks and not os.environ.get('GPTZERO_API_KEY', '').strip():
718
+ print('SKIP check_ai_detection.py: no GPTZERO_API_KEY configured (not a failure)', flush=True)
719
+ summary = out / 'summary.json'
720
+ summary.write_text(json.dumps(report, indent=2) + '\n')
721
+ log = out / 'checks.log'
722
+ log_lock = threading.Lock()
723
+ static_root = os.environ.get('ZIH_STATIC_TMPDIR')
724
+ with tempfile.TemporaryDirectory(prefix='tb-checks-', dir=static_root or '/tmp') as scratch, \
725
+ log.open('w') as combined_log, (out / 'outcomes.jsonl').open('x') as journal:
726
+ # Upstream invokes python3. Use this interpreter, not an unrelated
727
+ # system Python that may lack tomllib. No dependency installation needed.
728
+ bindir = Path(scratch) / 'bin'
729
+ bindir.mkdir()
730
+ check_python = os.environ.get('ZIH_STATIC_PYTHON', sys.executable)
731
+ (bindir / 'python3').symlink_to(check_python)
732
+ scripts = (upstream or TERMINAL_BENCH) / 'scripts/checks'
733
+ reference_script = Path(scratch) / 'adapted-scripts/check-test-file-references.sh'
734
+ if reference_script.name in checks:
735
+ reference_script.parent.mkdir()
736
+ reference_script.write_text(reference_check_script((scripts / reference_script.name).read_text()))
737
+ if static_root:
738
+ local_scripts = Path(scratch) / 'scripts'
739
+ shutil.copytree(scripts, local_scripts)
740
+ scripts = local_scripts
741
+ env = {**os.environ, 'PATH': str(bindir) + os.pathsep + os.environ.get('PATH', '')}
742
+ for key in ('FIX_DIRS', 'BASE_DIR', 'BASH_ENV', 'ENV'):
743
+ env.pop(key, None)
744
+ def check_task_body(task, scratch):
745
+ entry = {'task': task.name, 'path': str(task), 'checks': []}
746
+ try:
747
+ validate_input(task)
748
+ except (ValueError, OSError) as exc:
749
+ entry.update(status='error', error=str(exc))
750
+ else:
751
+ pending_checks = set(checks) - set(imported.get(task.name, {}))
752
+ if not pending_checks or (pending_checks <= {AI_CHECK} and not os.environ.get('GPTZERO_API_KEY', '').strip()):
753
+ # Complete checkpointed tasks need no staging copy or subprocesses.
754
+ # The optional AI check is still handled below using current credentials.
755
+ renamed = []
756
+ else:
757
+ if static_root:
758
+ staged = Path(scratch) / 'input' / task.name
759
+ shutil.copytree(task, staged)
760
+ task = staged
761
+ task, renamed = safe_copy(task, scratch)
762
+ if renamed:
763
+ entry['renamed_for_checks'] = renamed
764
+ for name in checks:
765
+ if name in imported.get(task.name, {}):
766
+ entry['checks'].append(imported[task.name][name])
767
+ continue
768
+ if name == AI_CHECK and not os.environ.get('GPTZERO_API_KEY', '').strip():
769
+ entry['checks'].append({'check': name, 'status': 'skipped', 'optional': True,
770
+ 'reason': 'no GPTZERO_API_KEY configured', 'exit_code': None, 'log': None})
771
+ continue
772
+ started = time.monotonic()
773
+ target = path_check_copy(task, scratch) if name == PATH_CHECK else adapted_check_copy(task, scratch, name, profile)
774
+ if name == 'check-test-file-references.sh':
775
+ evidence = json.loads((target / 'discovered-references.json').read_text())
776
+ if evidence:
777
+ entry['discoverable_reference_evidence'] = evidence
778
+ # Buffer each check separately so parallel outputs never interleave.
779
+ with tempfile.TemporaryFile(mode='w+', encoding='utf-8', errors='replace', dir=scratch) as stream:
780
+ # The scripts take under a second; a timeout means the node or the
781
+ # file system stalled (job 916252), so one more attempt is made.
782
+ for attempt in (1, 2):
783
+ try:
784
+ script = LOCAL_CHECKS.get(name) or (reference_script if name == reference_script.name else scripts / name)
785
+ interpreter = sys.executable if name in LOCAL_CHECKS else check_python if name.endswith('.py') else 'bash'
786
+ result = subprocess.run([interpreter, str(script), str(target)],
787
+ cwd=scratch, env=env, stdout=stream, stderr=subprocess.STDOUT, timeout=timeout)
788
+ status = 'passed' if result.returncode == 0 else 'failed'
789
+ rc = result.returncode
790
+ break
791
+ except subprocess.TimeoutExpired:
792
+ status, rc = 'error', None
793
+ stream.write(f'\nTimed out after {timeout} seconds (attempt {attempt})\n')
794
+ stream.flush()
795
+ stream.seek(0)
796
+ if name == PATH_CHECK and rc == 1:
797
+ if re.search(r'relative paths used \(should be absolute under /[^)]*\): ', stream.read()):
798
+ status = 'warning'
799
+ stream.seek(0)
800
+ if name == AI_CHECK and rc == 0:
801
+ text = stream.read()
802
+ if 'skipped' in text.lower() or 'No files to check' in text:
803
+ status = 'skipped'
804
+ stream.seek(0)
805
+ with log_lock:
806
+ combined_log.write(f'\n=== {entry["task"]} / {name} ===\n')
807
+ shutil.copyfileobj(stream, combined_log)
808
+ combined_log.write(f'\n=== result: {status}, exit_code: {rc} ===\n')
809
+ combined_log.flush()
810
+ entry['checks'].append({'check': name, 'status': status, 'optional': name == AI_CHECK, 'exit_code': rc,
811
+ 'log': str(log.resolve()), 'duration_seconds': round(time.monotonic() - started, 3)})
812
+ if status != 'passed':
813
+ print(f'{task.name}: {name}: {status} (see {log})', flush=True)
814
+ entry['warnings'] = [{'tag': 'relative-instruction-path', 'check': c['check'], 'log': c.get('log')} for c in entry['checks'] if c['status'] == 'warning']
815
+ entry['status'] = 'passed' if all(c['status'] in ('passed', 'warning') or (c['status'] == 'skipped' and c.get('optional')) for c in entry['checks']) else 'failed'
816
+ return entry
817
+ def check_task(task):
818
+ if not static_root:
819
+ return check_task_body(task, scratch)
820
+ # Bound live task copies in RAM; oversized tasks use durable scratch.
821
+ # Allow for staging plus renamed/path-check copies per concurrent task.
822
+ parent = scratch
823
+ try:
824
+ validate_input(task)
825
+ size = sum(p.stat().st_size for p in task.rglob('*') if p.is_file())
826
+ limit = int(os.environ.get('ZIH_STATIC_MAX_BYTES', '1073741824')) // (3 * concurrency)
827
+ if size > limit:
828
+ parent = os.environ['TMPDIR']
829
+ except (ValueError, OSError) as exc:
830
+ return {'task': task.name, 'path': str(task), 'checks': [], 'status': 'error', 'error': str(exc)}
831
+ # Delete only this task's temporary copies immediately after its checks.
832
+ with tempfile.TemporaryDirectory(prefix='static-task-', dir=parent) as task_scratch:
833
+ return check_task_body(task, task_scratch)
834
+ with ThreadPoolExecutor(max_workers=concurrency) as pool:
835
+ futures = [pool.submit(check_task, task) for task in tasks]
836
+ for future in as_completed(futures):
837
+ entry = future.result()
838
+ journal.write(json.dumps(entry) + '\n')
839
+ journal.flush()
840
+ print(f"{entry['task']}: {entry['status']}", flush=True)
841
+ report = rebuild_summary(out)
842
+ print(f'{len(checks)} upstream checks per task; {len(excluded)} explicitly excluded. Report: {summary}')
843
+ return 0 if report['passed'] else 1
844
+
845
+
846
+ def main():
847
+ ap = argparse.ArgumentParser(description=__doc__)
848
+ ap.add_argument('root', nargs='?', type=Path)
849
+ ap.add_argument('--profile', choices=('training', 'portable', 'terminal-bench'), default='training')
850
+ ap.add_argument('--out', type=Path, default=Path('verify-out/terminal-bench'))
851
+ ap.add_argument('--limit', type=int)
852
+ ap.add_argument('--concurrency', type=int, default=1, help='parallel static tasks')
853
+ ap.add_argument('--timeout', type=int, default=120, help='seconds per static script per task')
854
+ ap.add_argument('--list', action='store_true', help='list included and excluded checks')
855
+ ap.add_argument('--exclude', action='append', default=[], help='check ID or filename, optionally NAME=reason; repeat or comma-separate')
856
+ ap.add_argument('--dry-run', action='store_true')
857
+ ap.add_argument('--rebuild-summary', action='store_true', help='reconstruct --out/summary.json from saved task outcomes without rerunning checks')
858
+ a = ap.parse_args()
859
+ try:
860
+ if a.rebuild_summary:
861
+ report = rebuild_summary(a.out)
862
+ print(f"Recovered {len(report['tasks'])} task outcomes; complete={report['complete']}")
863
+ return 0 if report['passed'] else 1
864
+ if a.timeout <= 0 or (a.limit is not None and a.limit <= 0):
865
+ raise ValueError('--limit and --timeout must be positive')
866
+ manifest, checks, excluded = load_checks(a.profile, exclude=a.exclude)
867
+ if a.list or a.dry_run:
868
+ print(f"Terminal-Bench {manifest['commit']} ({a.profile})")
869
+ for name in checks:
870
+ print(('SKIP ' + name + ': no GPTZERO_API_KEY configured (not a failure)')
871
+ if name == AI_CHECK and not os.environ.get('GPTZERO_API_KEY', '').strip()
872
+ else f"{'CONDITIONAL' if name == AI_CHECK else 'RUN '} {name}")
873
+ for name, reason in excluded.items():
874
+ print(f'SKIP {name}: {reason}')
875
+ if a.list:
876
+ return 0
877
+ if a.root is None:
878
+ raise ValueError('provide a task or task directory')
879
+ tasks = discover_tasks(a.root)[:a.limit]
880
+ if a.dry_run:
881
+ for task in tasks:
882
+ print(f'Would check {task}')
883
+ return 0
884
+ return run_checks(tasks, a.out, a.profile, a.timeout, exclude=a.exclude, concurrency=a.concurrency)
885
+ except (ValueError, OSError) as exc:
886
+ ap.exit(1, f'{exc}\n')
887
+
888
+
889
+ if __name__ == '__main__':
890
+ raise SystemExit(main())
calibforge/ablations/evidence/stage1-checker.py ADDED
@@ -0,0 +1,889 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run pinned Terminal-Bench checks with training-task defaults and optional GPTZero."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ import threading
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
21
+ from validation.data.selection import discover_tasks
22
+ from validation.checks.supplied_references import discoverable_references
23
+
24
+ TERMINAL_BENCH = Path(__file__).resolve().parents[1] / 'upstream/terminal_bench'
25
+ # These are policy decisions in our wrapper; upstream files remain unmodified.
26
+ POLICY = {
27
+ 'check-canary.sh': 'Terminal-Bench-specific canary GUID',
28
+ 'check-task-fields.sh': 'benchmark author metadata, taxonomy and README sections',
29
+ 'check-task-timeout.sh': 'benchmark timeout caps',
30
+ 'check-instruction-suffix.sh': 'benchmark-specific instruction suffix',
31
+ 'check-instruction-headings.sh': 'benchmark prose-only instruction style',
32
+ 'check-gpu-types.sh': 'Modal-specific GPU allowlist',
33
+ 'check-resource-sizes.sh': 'benchmark CPU/memory size allowlist',
34
+ 'check-allow-internet.sh': 'benchmark requires default internet access',
35
+ 'check-no-allow-internet-true.sh': 'benchmark forbids explicit internet opt-in',
36
+ 'check-task-slug.sh': 'benchmark limit of three slug tokens',
37
+ 'check-task-package-name.sh': 'requires terminal-bench/<task> package namespace',
38
+ 'check-separate-verifier.sh': 'requires separate verifier mode for every task',
39
+ 'check-pytest-version.sh': 'benchmark-wide exact pytest/CTRF versions',
40
+ }
41
+ PR_ONLY = {'check-task-changelog.sh': 'training tasks do not require Terminal-Bench PR changelogs'}
42
+ TRAINING_EXCLUSIONS = {
43
+ 'check-test-sh-sanity.sh': 'training permits shared system Python and image-installed verifier dependencies; uv is not required, and stages 4/5 check execution',
44
+ 'check-separate-verifier.sh': 'training permits grading in the agent environment, including installed packages and changed system state; separate verification is optional',
45
+ 'check-allow-internet.sh': 'network policy is declared by the task and checked at runtime',
46
+ 'check-no-allow-internet-true.sh': 'explicit task network policies are allowed',
47
+ 'check-pytest-version.sh': 'training tasks may use other pinned pytest/CTRF versions',
48
+ 'check-gpu-types.sh': 'Modal GPU naming conventions do not apply to the Helma execution profile',
49
+ 'check-canary.sh': 'training tasks do not require a benchmark canary string',
50
+ 'check-instruction-headings.sh': 'Markdown headings are allowed in training instructions',
51
+ 'check-task-fields.sh': 'training tasks do not require TB author GitHub metadata, taxonomy or explanation sections',
52
+ 'check-task-package-name.sh': 'training task package names need not use the terminal-bench namespace',
53
+ 'check-task-slug.sh': 'training task names may contain more than three hyphen-separated tokens',
54
+ }
55
+ CHECKER_UNIT_TESTS = ('test-author-github.py', 'test-instruction-headings.sh',
56
+ 'test-resource-sizes.sh', 'test-task-changelog.sh')
57
+ AI_CHECK = 'check_ai_detection.py'
58
+ LOCAL_CHECKS = {'check-task-toml-schema.py': Path(__file__).with_name('task_toml_schema.py')}
59
+
60
+
61
+
62
+ def load_checks(profile, upstream=None, exclude=()):
63
+ manifest = json.loads((TERMINAL_BENCH / 'UPSTREAM.json').read_text())
64
+ # Detect accidental edits or incomplete copies before executing anything.
65
+ for name, digest in manifest['files'].items():
66
+ if hashlib.sha256(((upstream or TERMINAL_BENCH) / name).read_bytes()).hexdigest() != digest:
67
+ raise ValueError(f'upstream file differs from pinned copy: {name}')
68
+ names = sorted(Path(p).name for p in manifest['files'] if p.startswith('scripts/checks/'))
69
+ names = sorted([*names, *LOCAL_CHECKS])
70
+ excluded = {**PR_ONLY, **(POLICY if profile == 'portable' else TRAINING_EXCLUSIONS if profile == 'training' else {}),
71
+ 'rubric_review.py': 'LLM rubric review is opt-in via stage 2, never a default static check'}
72
+ inactive = {'rubric_review.py', *CHECKER_UNIT_TESTS}
73
+ for value in exclude:
74
+ # NAME=reason records why; a reason may contain commas, so it is one item.
75
+ value, _, reason = value.partition('=')
76
+ for requested in value.split(','):
77
+ requested = requested.strip()
78
+ aliases = {'ai-detection': 'check_ai_detection.py', 'rubric-review': 'rubric_review.py',
79
+ 'task-toml-schema': 'check-task-toml-schema.py',
80
+ 'check-task-toml-schema': 'check-task-toml-schema.py'}
81
+ name = aliases.get(requested, requested)
82
+ if name not in inactive and name != AI_CHECK and name not in LOCAL_CHECKS:
83
+ name = name if name.endswith('.sh') else name + '.sh'
84
+ name = name if name.startswith('check-') else 'check-' + name
85
+ if name not in names and name not in inactive:
86
+ raise ValueError(f'unknown static check: {requested}; use --list')
87
+ excluded[name] = (reason.strip() or 'explicitly excluded' if name in names else
88
+ 'upstream checker unit test, not dataset validation' if name in CHECKER_UNIT_TESTS else
89
+ 'not part of the static suite (LLM review is opt-in)')
90
+ return manifest, [n for n in names if n not in excluded], excluded
91
+
92
+
93
+ def validate_input(task):
94
+ import tomllib
95
+ for name in ('instruction.md', 'task.toml', 'tests/test.sh'):
96
+ if not (task / name).is_file():
97
+ raise ValueError(f'missing {name}')
98
+ if not (task / 'environment').is_dir():
99
+ raise ValueError('missing environment/')
100
+ with (task / 'task.toml').open('rb') as stream:
101
+ tomllib.load(stream)
102
+ if any(c.isspace() or c in '*?[]' for c in str(task)):
103
+ raise ValueError(f'task directory path must not contain whitespace or glob characters: {task}')
104
+
105
+
106
+ UNSAFE = re.compile(r'[\s*?\[\]]')
107
+
108
+
109
+ def safe_copy(task, scratch):
110
+ """Several upstream scripts split paths as shell words and expand globs, so a file
111
+ named `Clase 4/[id].ts` would be skipped or misread and the check could pass wrongly.
112
+ Such tasks are checked on a copy whose offending names have those characters
113
+ replaced by '_'. The task itself is unchanged. Returns (copy, renamed) or (task, [])."""
114
+ renamed = sorted(str(p.relative_to(task)) for p in task.rglob('*') if UNSAFE.search(str(p.relative_to(task))))
115
+ if not renamed:
116
+ return task, []
117
+ copy = Path(scratch) / 'renamed' / task.name
118
+ if copy.exists():
119
+ shutil.rmtree(copy)
120
+ for path in task.rglob('*'):
121
+ target = copy / UNSAFE.sub('_', str(path.relative_to(task)))
122
+ if path.is_dir():
123
+ target.mkdir(parents=True, exist_ok=True)
124
+ else:
125
+ target.parent.mkdir(parents=True, exist_ok=True)
126
+ shutil.copyfile(path, target)
127
+ return copy, renamed
128
+
129
+
130
+ PATH_CHECK = 'check-task-absolute-path.sh'
131
+ SHELL_FENCES = {'', 'bash', 'sh', 'shell', 'zsh', 'console', 'text', 'txt'}
132
+ ADAPTATIONS = {PATH_CHECK: 'Relative-path findings are advisory warnings and do not fail stage 1. Runs on a copy of the task whose instruction.md has its source-code blocks removed '
133
+ '(fenced blocks tagged with a programming language); masks complete absolute paths '
134
+ 'and JavaScript console calls/sed substitutions so their substrings are not mistaken for paths; '
135
+ 'masks complete non-file URLs, quoted absolute paths with spaces, simple inline commands rooted by cd /absolute/path &&, '
136
+ 'and literal relative symlink targets with explicit absolute link locations; '
137
+ 'skips all Markdown fenced blocks, recognizes $HOME/${HOME}/~/ paths, and accepts adjacent literal cd and command lines; '
138
+ 'accepts explicit named-file-in-directory clauses, pure parent-navigation commands, and relative command tokens for uniquely absolute-named executables; '
139
+ 'unresolved relative file references outside fenced blocks are otherwise kept',
140
+ 'check-test-file-references.sh': 'masks complete non-file URLs, XML hostnames and excluded system paths; fixes full-token extraction and shell redirections, preserving basenames without inventing /app paths; accepts conventional boot artifacts, explicit numeric X filename ranges, explicit label filename templates resolved from supplied label:glob configurations, and references discovered through named supplied files/directories; reads literal writes and copies/moves in explicitly invoked local setup shell scripts without executing them, with source evidence',
141
+ 'check-pip-pinning.sh': 'recognizes SHA-256-pinned HTTP(S) requirements as single shell arguments; masks unquoted shell redirections and argument forwarding in generated offline installer heredocs, retaining actual package installations',
142
+ 'check-nproc.sh': 'training permits measurement-only variables and the exact audited InferredBugs Python 2.7.18 Dockerfile build on Maven Java 8/11/17 (Helma Slurm affinity probes 934209/934274); also permits four content-pinned SETA solutions tested with 1/2 CPUs (Helma probe 948213); other worker selection remains checked; not a Docker quota-only portability guarantee',
143
+ 'file names': 'a task with whitespace or *?[] in a file name is checked on a copy where those characters '
144
+ 'are replaced by _, because the upstream scripts split paths at spaces and expand globs; '
145
+ 'the renamed files are listed per task'}
146
+ ADAPTATIONS['check-dockerfile-references.sh'] = 'Ignore full-line Dockerfile comments; executable references remain checked on a scratch copy.'
147
+ ADAPTATIONS['check-dockerfile-sanity.sh'] = 'Inspect apt install arguments within RUN commands, including continuations and quoted pins; do not scan unrelated ENV assignments or embedded source following apt.'
148
+ ADAPTATIONS['check-nproc.sh'] += ' Also permits five content-pinned CalibForge image/script pairs measured at 2/4 CPUs in Helma job 1017578; nproc --all still saw 384 node CPUs.'
149
+ ADAPTATIONS['check-task-toml-schema.py'] = (
150
+ 'Local deterministic replacement for the task_toml_schema rubric: validates against pinned Harbor models '
151
+ 'and rejects unrecognized fields recursively; Harbor free-form metadata/env mappings remain allowed.')
152
+
153
+
154
+ def without_source_code(instruction):
155
+ """Drop fenced blocks tagged with a programming language: file names inside code
156
+ to read or complete are not paths the task tells the agent to use.
157
+
158
+ Source code can itself contain Markdown fences and '#' lines, so the first bare
159
+ fence is not always the end of the block. The block ends at the first bare fence
160
+ that is followed by a heading or by the end of the text; if there is none before
161
+ the next tagged block, it ends at the first bare fence."""
162
+ lines, kept, i = instruction.split('\n'), [], 0
163
+ fence = lambda line: re.fullmatch(r'\s*```\s*([A-Za-z0-9_+#.-]*)\s*', line)
164
+ def before_heading(j):
165
+ following = next((l for l in lines[j + 1:] if l.strip()), None)
166
+ return following is None or re.match(r'#{1,6} ', following) is not None
167
+ while i < len(lines):
168
+ match = fence(lines[i])
169
+ if not match or match.group(1).lower() in SHELL_FENCES:
170
+ kept.append(lines[i])
171
+ i += 1
172
+ continue
173
+ bare = []
174
+ for j in range(i + 1, len(lines)):
175
+ inner = fence(lines[j])
176
+ if inner and inner.group(1):
177
+ break # the next tagged block starts here
178
+ if inner:
179
+ bare.append(j)
180
+ closing = next((j for j in bare if before_heading(j)), bare[0] if bare else None)
181
+ if closing is None: # unterminated block: leave the text for the check to see
182
+ kept.append(lines[i])
183
+ i += 1
184
+ continue
185
+ kept.append(f'[{match.group(1)} source code removed for the path check]')
186
+ i = closing + 1
187
+ return '\n'.join(kept)
188
+
189
+
190
+ def without_urls(text):
191
+ # Mask whole tokens before upstream extracts filename-like suffixes.
192
+ text = re.sub(r'\b(?![Ff][Ii][Ll][Ee]://)[A-Za-z][A-Za-z0-9+.-]*://[^\s`\"\'<>]+', '[URL]', text)
193
+ # Bare host/path form, e.g. mirrors.ubuntu.com/mirrors.txt.
194
+ return re.sub(r'\b(?:[A-Za-z0-9-]+\.)+(?:com|org|net|edu|gov|io)/[^\s`\"\'<>]+', '[URL]', text)
195
+
196
+
197
+ def without_fenced_blocks(text):
198
+ """Skip Markdown fences of any language, including untagged and shell blocks."""
199
+ kept, opening = [], None
200
+ for line in text.splitlines(keepends=True):
201
+ match = re.match(r'^ {0,3}(`{3,}|~{3,})(.*)$', line.rstrip('\n'))
202
+ if opening is None:
203
+ if match:
204
+ opening = match[1]
205
+ kept.append('[fenced block omitted from path check]\n')
206
+ else:
207
+ kept.append(line)
208
+ elif (match and match[1][0] == opening[0]
209
+ and len(match[1]) >= len(opening) and not match[2].strip()):
210
+ opening = None
211
+ return ''.join(kept)
212
+
213
+
214
+ # Specific conventional interfaces, not an exemption for everything under /boot.
215
+ CONVENTIONAL_REFERENCE_PATHS = (
216
+ r'/boot/grub/grub\.cfg',
217
+ r'/boot/initrd\.img-[0-9][A-Za-z0-9_.+-]*',
218
+ )
219
+
220
+
221
+ def reference_check_script(source):
222
+ """Correct lexical extraction on a temporary copy of pinned upstream."""
223
+ old = "grep -E '^/(app|home|tests|tmp|usr|var|etc)/'"
224
+ if source.count(old) != 1 or source.count('/[a-zA-Z0-9_./]+\\.') != 1:
225
+ raise ValueError('upstream file-reference extractor changed')
226
+ source = source.replace(old, "grep -E '^/'")
227
+ # A quoted basename supplies no working directory. Keep it as a basename.
228
+ source = source.replace("sed 's|^|/app/|'", 'cat')
229
+ # Upstream uses optional quote markers (?) with basic sed regex syntax.
230
+ # Extended regex syntax is required to strip the redirection / -o prefix.
231
+ source = source.replace("sed 's/^>\\s*", "sed -E 's/^>\\s*")
232
+ source = source.replace("sed 's/^-o\\s*", "sed -E 's/^-o\\s*")
233
+ # Consume the full basename, including suffixes after .img (kernel versions).
234
+ lines = source.splitlines(keepends=True)
235
+ for i, line in enumerate(lines):
236
+ if '/[a-zA-Z0-9_./]+\\.' in line:
237
+ line = line.replace('/[a-zA-Z0-9_./]+\\.', '/[a-zA-Z0-9_./-]+\\.')
238
+ line = line.replace("grep -oE '/", "grep -oE '(^|[[:space:]=])/")
239
+ lines[i] = line.replace("wad)'", "wad)[a-zA-Z0-9_.+-]*'").rstrip('\n') + " | sed 's|^[^/]||'\n"
240
+ return ''.join(lines)
241
+
242
+
243
+ def reference_check_text(text):
244
+ text = without_urls(text)
245
+ text = re.sub(r'file://(?=/)', '', text)
246
+ text = re.sub(r'<host>[^<\n]+</host>', '<host>[hostname]</host>', text)
247
+ # Upstream deliberately excludes these system roots, but its second regex
248
+ # can truncate a hyphenated path into e.g. /xsettings.xml and flag it again.
249
+ text = re.sub(r'/(?:tests|tmp|usr|var|etc)/[^\s`\"\'<>;]+', '[system path]', text)
250
+ for path in CONVENTIONAL_REFERENCE_PATHS:
251
+ text = re.sub(r'(?<![\w/])' + path + r'(?![\w./+-])', '[conventional boot artifact]', text)
252
+ return text
253
+
254
+
255
+ def numeric_reference_patterns(instruction, sources):
256
+ """Accept an X filename template only with an explicit numeric X range."""
257
+ bounds = re.search(r'\b(?:where\s+)?X\s+is\s+(\d+)\s*[-–]\s*(\d+)\b', instruction)
258
+ if not bounds:
259
+ return {}
260
+ low, high = map(int, bounds.groups())
261
+ result = {}
262
+ for match in re.finditer(r'\b([A-Za-z0-9_.-]*_X(?:_[A-Za-z0-9_.-]+)?\.[A-Za-z0-9]+)\b', instruction):
263
+ template = match.group(1)
264
+ expression = re.escape(template).replace('_X', r'_(\d+)')
265
+ for candidate in re.finditer(r'(?<![\w.-])' + expression + r'(?![\w.-])', sources):
266
+ if low <= int(candidate.group(1)) <= high:
267
+ result[candidate.group(0)] = {'instruction_pattern': template, 'numeric_range': [low, high]}
268
+ return result
269
+
270
+
271
+ def pip_check_line(line):
272
+ """Adapt shell syntax on the check copy, never rewriting the installation."""
273
+ from packaging.requirements import Requirement, InvalidRequirement
274
+ from urllib.parse import urlsplit
275
+ # Keep quotes intact so quoted '>' and spaces inside requirements are not
276
+ # mistaken for shell operators or separate package arguments.
277
+ pattern = r'''(?:\d+)?(?:>>?|<<?)&?|&&|\|\||[;|&]|(?:[^\s'"\\<>;&|]+|\\[^\n]|'[^']*'|"(?:\\.|[^"\\])*")+'''
278
+ tokens = list(re.finditer(pattern, line))
279
+ cursor = 0
280
+ for token in tokens:
281
+ if line[cursor:token.start()].strip():
282
+ return line # Unsupported/malformed shell syntax: keep the finding.
283
+ cursor = token.end()
284
+ if line[cursor:].strip():
285
+ return line
286
+ edits, i = [], 0
287
+ while i < len(tokens):
288
+ token = tokens[i]
289
+ raw = token.group()
290
+ if raw.startswith('#'):
291
+ break
292
+ if re.fullmatch(r'(?:\d+)?(?:>>?|<)&?', raw) and i + 1 < len(tokens):
293
+ destination = tokens[i + 1]
294
+ if destination.group() not in ('&&', '||', ';', '|', '&'):
295
+ edits.append((token.start(), destination.end(), ' '))
296
+ i += 2
297
+ continue
298
+ try:
299
+ value, = shlex.split(raw)
300
+ except ValueError:
301
+ i += 1
302
+ continue
303
+ url = value
304
+ name = 'hash-pinned-artifact'
305
+ try:
306
+ requirement = Requirement(value)
307
+ if requirement.url and not requirement.marker:
308
+ url, name = requirement.url, requirement.name
309
+ except InvalidRequirement:
310
+ pass
311
+ try:
312
+ parsed = urlsplit(url)
313
+ except ValueError:
314
+ i += 1
315
+ continue
316
+ if (parsed.scheme in ('http', 'https') and parsed.netloc
317
+ and not any(c in url for c in '$`\\')
318
+ and re.fullmatch(r'sha256=[0-9a-fA-F]{64}', parsed.fragment)):
319
+ # Upstream understands == pins, but splits direct references at
320
+ # spaces. This placeholder exists only in its scratch input.
321
+ edits.append((token.start(), token.end(), name + '==0'))
322
+ i += 1
323
+ for start, end, replacement in reversed(edits):
324
+ line = line[:start] + replacement + line[end:]
325
+ return line
326
+
327
+
328
+ def pip_check_text(text):
329
+ # Generated offline installers are tools accepting user-specified packages,
330
+ # not an unpinned install into the task environment. Only exempt forwarding
331
+ # inside a quoted heredoc; retain concrete installs inside those heredocs.
332
+ lines, delimiter = [], None
333
+ for line in text.splitlines(keepends=True):
334
+ if delimiter and line.strip() == delimiter:
335
+ delimiter = None
336
+ elif delimiter and re.fullmatch(
337
+ r'\s*pip3? install --no-index --find-links="\$SCRIPT_DIR" "\$@"\s*', line):
338
+ line = '# generated offline installer forwards caller arguments\n'
339
+ if delimiter is None:
340
+ match = re.search(r"<<\s*['\"]([A-Za-z_][A-Za-z0-9_]*)['\"]", line)
341
+ if match:
342
+ delimiter = match.group(1)
343
+ lines.append(pip_check_line(line))
344
+ return ''.join(lines)
345
+
346
+
347
+ # Content-pinned CPU-affinity audit: Helma job 1017578, all five images at 2/4 CPUs.
348
+ CALIBFORGE_REVIEWED_NPROC = {'contrastive_solver-security_20260508_045740_002': {'file': 'environment/Dockerfile',
349
+ 'sha256': {'environment/Dockerfile': '8554c71778e6d80171e69483cafc1c53f016d16607b586eb8d259936c2996ad1'}},
350
+ 'contrastive_solver-software-engineering_20260510_053611_008': {'file': 'environment/Dockerfile',
351
+ 'sha256': {'environment/Dockerfile': 'fe371f2e4d5ccf5ac295269324bf2d7dbfb6d3e10377e84910f457f384f365cb'}},
352
+ 'contrastive_solver-software-engineering_20260611_210349_008': {'file': 'tests/test.sh',
353
+ 'sha256': {'environment/Dockerfile': '4f6194d3d652fd8cb9d9de5681211adf5ba57146718f2fc0db9d977d11f8d8b7',
354
+ 'tests/test.sh': 'b7f4a23eaffed3576d649078f6bb09f89b84e2a5573063b53552799af644560a'}},
355
+ 'contrastive_solver-system-administration_20260604_004411_008': {'file': 'environment/Dockerfile',
356
+ 'sha256': {'environment/Dockerfile': '47c7d9e917e98d3965d48a380c1d82a2fd774505857ccfdcc6bfdaacba388db9'}},
357
+ 'contrastive_solver-system-administration_20260604_004411_009': {'file': 'environment/Dockerfile',
358
+ 'sha256': {'environment/Dockerfile': 'bbe5c1425ac6323702e29c0faae4d27efa23de0c6202797491ed5343887a2373'}}}
359
+
360
+
361
+ def dockerfile_without_comments(text):
362
+ """Ignore full-line Dockerfile comments, retaining inline arguments/data."""
363
+ kept, heredocs = [], []
364
+ for line in text.splitlines(keepends=True):
365
+ if heredocs:
366
+ kept.append(line)
367
+ if line.strip() == heredocs[0]:
368
+ heredocs.pop(0)
369
+ continue
370
+ if line.lstrip().startswith('#'):
371
+ continue
372
+ kept.append(line)
373
+ # Heredoc payload is data, not Dockerfile comments.
374
+ heredocs.extend(re.findall(r"<<-?\s*['\"]?([A-Za-z_][A-Za-z0-9_]*)['\"]?", line))
375
+ return ''.join(kept)
376
+
377
+
378
+ def dockerfile_sanity_text(text):
379
+ """Give upstream only apt command arguments, not the next 20 source lines.
380
+
381
+ Shell tokenization preserves quoted pins and joins continued RUN commands.
382
+ Unparseable shell is kept for conservative upstream checking.
383
+ """
384
+ text = dockerfile_without_comments(text)
385
+ logical = re.sub(r'\\\n', ' ', text)
386
+ commands = []
387
+ for line in logical.splitlines():
388
+ if not re.match(r'^\s*RUN\s', line, re.I):
389
+ continue
390
+ if re.search(r'\bapt(?:-get)?\b', line) and ('<<' in line or re.match(r'^\s*RUN\s*\[', line, re.I) or re.search(r'\b(?:sh|bash)\s+-c', line)):
391
+ return text # Preserve conservative checking of unsupported shell forms.
392
+ try:
393
+ lexer = shlex.shlex(line, posix=True, punctuation_chars=';&|()<>' )
394
+ lexer.whitespace_split = True
395
+ tokens = list(lexer)
396
+ except ValueError:
397
+ return text
398
+ for i, token in enumerate(tokens):
399
+ if token.rsplit('/', 1)[-1] not in ('apt', 'apt-get'):
400
+ continue
401
+ if i and tokens[i - 1] not in ('RUN', 'run', '&&', '||', ';', '|', 'sudo', 'env', 'then', 'do'):
402
+ continue
403
+ args = []
404
+ for arg in tokens[i + 1:]:
405
+ if arg and all(c in ';&|()<>' for c in arg):
406
+ break
407
+ args.append(arg)
408
+ # Keep update/cleanup advisory behavior, but expose version pins
409
+ # only in install arguments. Epochs/integer pins count too.
410
+ if 'install' in args:
411
+ packages = args[args.index('install') + 1:]
412
+ pinned = [a for a in packages if re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9+.:_-]*=[^=\s]+', a)]
413
+ commands.append('RUN apt install ' + ('pinned-package=1.0' if pinned else 'packages'))
414
+ elif 'update' in args:
415
+ commands.append('RUN apt update')
416
+ if 'rm -rf /var/lib/apt/lists' in text:
417
+ commands.append('RUN rm -rf /var/lib/apt/lists/*')
418
+ return '\n'.join(commands) + '\n'
419
+
420
+
421
+ def calibforge_nproc_text(text, task, relative):
422
+ """Allow only the exact image/script pairs measured in Helma job 1017578."""
423
+ record = CALIBFORGE_REVIEWED_NPROC.get(task.name)
424
+ if not record or relative != record['file']:
425
+ return text
426
+ for filename, digest in record['sha256'].items():
427
+ path = task / filename
428
+ if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != digest:
429
+ return text
430
+ return text.replace('$(nproc)', 'VERIFIED_CPU_AFFINITY')
431
+
432
+
433
+ def nproc_check_text(text, *, dockerfile=False):
434
+ """Conservatively recognize measurement-only variables; not a shell parser.
435
+
436
+ Also recognize the exact Python 2 build audited under Slurm CPU affinity.
437
+ Other build flags and unknown uses retain the original check.
438
+ """
439
+ if dockerfile and re.search(r'^FROM maven:3\.9-eclipse-temurin-(?:8|11|17)$', text, re.M):
440
+ # Match the build context and complete command, not make/nproc generally.
441
+ # Mask only on the check's scratch copy; the actual task is unchanged.
442
+ reviewed = (
443
+ ' && tar -xzf "$d/python2.tgz" -C "$d" && cd "$d/Python-2.7.18" \\\n'
444
+ ' && ./configure --prefix=/opt/python2 --disable-shared --without-ensurepip >/dev/null '
445
+ '&& make -j"$(nproc)" >/dev/null && make install >/dev/null \\\n'
446
+ ' && cd / && rm -rf "$d" && /opt/python2/bin/python2.7 -c "import zlib"'
447
+ )
448
+ text = text.replace(reviewed, reviewed.replace('$(nproc)', 'VERIFIED_CPU_AFFINITY'))
449
+ lines = text.splitlines(keepends=True)
450
+ for i, line in enumerate(lines):
451
+ assignment = re.fullmatch(r'\s*([A-Za-z_]\w*)="?\$\(nproc\)"?\s*', line)
452
+ if not assignment:
453
+ continue
454
+ var = assignment.group(1)
455
+ refs = re.compile(r'\$(?:' + re.escape(var) + r'\b|\{' + re.escape(var) + r'\})')
456
+ uses = [s.strip() for s in lines if refs.search(s) and not s.lstrip().startswith('#')]
457
+ def measurement(s):
458
+ # JSON fields: no command substitutions, backticks or shell chains.
459
+ if s.startswith(('{"', '"')) and not re.search(r'\$\(|`|[;&|]', s):
460
+ return True
461
+ if re.fullmatch(r'if \(\( \$\(echo "\$\w+ > \$' + re.escape(var) + r'" \| bc -l\) \)\); then', s):
462
+ return True
463
+ return bool(re.fullmatch(r'alerts(?:\+)?=\(?"[^\n]*"\)?', s)) and not re.search(r'\$\(|`|[;&|]', s)
464
+ if uses and all(measurement(s) for s in uses):
465
+ lines[i] = line.replace('$(nproc)', 'CPU_MEASUREMENT')
466
+ return ''.join(lines)
467
+
468
+
469
+ def adapted_check_copy(task, scratch, name, profile):
470
+ transforms = {'check-test-file-references.sh': reference_check_text,
471
+ 'check-pip-pinning.sh': pip_check_text,
472
+ 'check-dockerfile-references.sh': dockerfile_without_comments,
473
+ 'check-dockerfile-sanity.sh': dockerfile_sanity_text}
474
+ if profile == 'training':
475
+ transforms['check-nproc.sh'] = nproc_check_text
476
+ if name not in transforms:
477
+ return task
478
+ copy = Path(scratch) / name / task.name
479
+ # Only files consumed by these checks. Avoid copying potentially large setup
480
+ # archives for each adaptation.
481
+ paths = ['instruction.md', 'task.toml', 'environment/Dockerfile',
482
+ 'tests/Dockerfile', 'tests/test.sh', 'solution/solve.sh']
483
+ paths.extend(str(p.relative_to(task)) for p in (task / 'tests').rglob('test_*.py'))
484
+ for relative in paths:
485
+ source = task / relative
486
+ if source.is_file():
487
+ target = copy / relative
488
+ target.parent.mkdir(parents=True, exist_ok=True)
489
+ text = source.read_text(errors='replace')
490
+ if name == 'check-nproc.sh' and relative not in ('instruction.md', 'task.toml'):
491
+ if profile == 'training' and relative == 'solution/solve.sh':
492
+ from data.seta.patch import reviewed_nproc_text
493
+ dockerfile = task / 'environment/Dockerfile'
494
+ text = reviewed_nproc_text(text, task.name,
495
+ dockerfile.read_bytes() if dockerfile.is_file() else b'')
496
+ text = calibforge_nproc_text(text, task, relative)
497
+ text = nproc_check_text(text, dockerfile=relative == 'environment/Dockerfile')
498
+ elif relative not in ('instruction.md', 'task.toml'):
499
+ text = transforms[name](text)
500
+ target.write_text(text)
501
+ if name == 'check-test-file-references.sh':
502
+ evidence = discoverable_references(task)
503
+ if (copy / 'instruction.md').is_file():
504
+ sources = '\n'.join((copy / p).read_text(errors='replace') for p in paths
505
+ if p not in ('instruction.md', 'task.toml') and (copy / p).is_file())
506
+ evidence.update(numeric_reference_patterns((copy / 'instruction.md').read_text(), sources))
507
+ (copy / 'discovered-references.json').write_text(json.dumps(evidence, indent=2))
508
+ if (copy / 'instruction.md').is_file():
509
+ with (copy / 'instruction.md').open('a') as stream:
510
+ stream.write('\nSupplied entry points reveal these references:\n' + '\n'.join(evidence) + '\n')
511
+ return copy
512
+
513
+
514
+ def named_path_examples(text):
515
+ """Recognize explicit location clauses and reuse unique executable locations."""
516
+ locations = {}
517
+ def remember(path):
518
+ if not any(c in path for c in '$*?[]{}'):
519
+ locations.setdefault(path.rsplit('/', 1)[-1], set()).add(path)
520
+ for match in re.finditer(r'''(?<![\w./])/(?!/)[A-Za-z0-9_.+@/-]+(?=$|[\s`"'<>|;,:!?)])''', text):
521
+ remember(match[0].rstrip('.,:'))
522
+
523
+ # Join only this explicit grammatical construction, never nearby paths.
524
+ clause = re.compile(
525
+ r'''\b(?:file|script|executable|utility|tool)\s+(?:named|called)\s+'''
526
+ r'''(?P<quote>[`"']?)(?P<name>[A-Za-z0-9_-][A-Za-z0-9_.+-]*)(?P=quote)'''
527
+ r'''\s+in\s+(?P<dirquote>[`"']?)(?P<directory>/[A-Za-z0-9_.+@/-]+)(?P=dirquote)(?=$|[\s.,:;!?])''', re.I)
528
+ def specified(match):
529
+ directory = match['directory'].rstrip('.,:')
530
+ remember(directory.rstrip('/') + '/' + match['name'])
531
+ start, end = match.span('name')
532
+ start, end = start - match.start(), end - match.start()
533
+ return match[0][:start] + '[explicitly located filename]' + match[0][end:]
534
+ text = clause.sub(specified, text)
535
+
536
+ def invocation(match):
537
+ value = match[1]
538
+ # Mask only ./NAME at command position. Arguments remain checked.
539
+ token = re.match(r'\./(?P<name>[A-Za-z0-9_-][A-Za-z0-9_.+-]*)(?=\s|$)', value)
540
+ if token and len(locations.get(token['name'], set())) == 1:
541
+ return '`[explicitly located executable]' + value[token.end():] + '`'
542
+ return match[0]
543
+ return re.sub(r'`([^`\n]+)`', invocation, text)
544
+
545
+
546
+ def explicit_path_examples(text):
547
+ """Mask locally specified command/link examples, without inferring global cwd."""
548
+ def literal(value):
549
+ return bool(value) and not any(c in value for c in '$`*?[]{}<>\n')
550
+
551
+ def inline(match):
552
+ value = match.group(1)
553
+ try:
554
+ tokens = list(shlex.shlex(value, posix=True, punctuation_chars=';&|<>'))
555
+ except ValueError:
556
+ return match.group(0)
557
+ if re.fullmatch(r'cd\s+(?:--\s+)?\.\.(?:/\.\.)*/?', value.strip()):
558
+ return '[parent navigation]'
559
+ # Only a single command after &&. Extra shell operators, dynamic
560
+ # expressions and another directory change remain review findings.
561
+ args = tokens[1:] if tokens[:1] == ['cd'] else []
562
+ if args[:1] == ['--']:
563
+ args = args[1:]
564
+ if (len(args) >= 3 and args[0].startswith('/') and args[1] == '&&'
565
+ and args[2] not in ('cd', 'pushd', 'popd', 'eval')
566
+ and '-c' not in args[2:]
567
+ and all(literal(t) and not any(c in t for c in ';&|()') for t in [args[0], *args[2:]])):
568
+ return '[command with explicit directory]'
569
+ # ln -s TARGET /absolute/LINK defines the relative target's base.
570
+ if (len(tokens) == 4 and tokens[:2] == ['ln', '-s']
571
+ and tokens[2].startswith(('./', '../')) and tokens[3].startswith('/')
572
+ and all(literal(t) for t in tokens[2:])):
573
+ return '[symlink with explicit location]'
574
+ return match.group(0)
575
+
576
+ # Two adjacent command lines can establish the same local base as &&.
577
+ # Do not carry that directory across paragraphs or unrelated prose.
578
+ def adjacent(match):
579
+ commands = [line.strip().strip('`') for line in match[0].splitlines()]
580
+ combined = '`' + commands[0] + ' && ' + commands[1] + '`'
581
+ result = inline(re.fullmatch(r'`([^`\n]+)`', combined))
582
+ return result if result != combined else match[0]
583
+ text = re.sub(r'(?m)^ {0,3}`?cd [^\n`]+`?\n {0,3}(?:`[^`\n]+`|[^`\n]+)$', adjacent, text)
584
+ text = re.sub(r'`([^`\n]+)`', inline, text)
585
+ absolute = r'''(?:`/[^`\n]+`|"/[^"\n]+"|'/[^'\n]+'|/[^\s`"'<>|;]+)'''
586
+ relative = r'''(?:`\.{1,2}/[^`\n]+`|"\.{1,2}/[^"\n]+"|'\.{1,2}/[^'\n]+'|\.{1,2}/[^\s`"'<>|;]+)'''
587
+ mapping = re.compile(r'(?P<link>' + absolute + r')\s*->\s*(?P<target>' + relative + r')')
588
+ paragraphs = re.split(r'(\n\s*\n)', text)
589
+ for i, paragraph in enumerate(paragraphs):
590
+ if not re.search(r'\b(?:symlink|symbolic\s+link)s?\b', paragraph, re.I):
591
+ continue
592
+ established = set()
593
+ def link(match):
594
+ location = match['link'].strip('`"\'')
595
+ target = match['target'].strip('`"\'')
596
+ if literal(location) and literal(target):
597
+ established.update((target, target.rsplit('/', 1)[0] + '/'))
598
+ return match['link'] + ' -> [relative symlink target]'
599
+ return match.group(0)
600
+ paragraph = mapping.sub(link, paragraph)
601
+ # The same paragraph may reiterate the literal target or its directory.
602
+ # Only these exact inline strings inherit the established link location.
603
+ paragraphs[i] = re.sub(r'`([^`\n]+)`',
604
+ lambda m: '[specified symlink reference]' if m[1] in established else m[0],
605
+ paragraph)
606
+ return ''.join(paragraphs)
607
+
608
+
609
+ def path_check_text(instruction):
610
+ """Adapt known lexical false positives without changing pinned upstream code."""
611
+ text = without_fenced_blocks(without_source_code(instruction))
612
+ text = without_urls(text)
613
+ text = named_path_examples(text)
614
+ text = explicit_path_examples(text)
615
+ # HOME is case-sensitive in shells. Unknown variables remain unresolved.
616
+ text = re.sub(r'''(?<![\w$])(?:\$HOME|\$\{HOME\}|~)/[^\s`"'<>|;]+''',
617
+ '[home-anchored path]', text)
618
+ # A relative command with an explicit working directory on the same line
619
+ # is unambiguous. Do not infer a global cwd from unrelated absolute paths.
620
+ text = re.sub(r'`(\./[^`\n]+)`(?= from `/[^`\n]+`)', '[rooted command]', text)
621
+ # Quoted absolute paths can contain spaces; consume before bare tokens.
622
+ text = re.sub(r'`/[^`\n]+`', '`[absolute path]`', text)
623
+ # Consume the WHOLE absolute token, including @ and hyphens in systemd units.
624
+ # Replacing tokens individually also prevents upstream's global substring
625
+ # filter from excusing a relative path merely because an absolute one exists.
626
+ text = re.sub(r'''(?<![\w./])/(?!/)[^\s`"'<>|;]+''', '[absolute path]', text)
627
+ lines = []
628
+ method = r'console\.(?:log|warn|error|info|debug|trace|table)'
629
+ for line in text.splitlines(keepends=True):
630
+ code_context = re.search(r'\b(?:JavaScript|regex|calls?|references?|strings?|literals?|statements?)\b', line, re.I)
631
+ def inline(match):
632
+ value = match.group(1)
633
+ # A sed substitution is an expression, not a directory reference.
634
+ if re.fullmatch(r's/[^\n]*/[^\n]*/[gip0-9]*', value):
635
+ return '`[sed expression]`'
636
+ if re.search(method + r'\s*\(', value) or (code_context and re.fullmatch(method, value)):
637
+ return '`' + re.sub(method, '[JavaScript method]', value) + '`'
638
+ return match.group(0)
639
+ line = re.sub(r'`([^`\n]+)`', inline, line)
640
+ if code_context:
641
+ line = re.sub(r'(["\'])(' + method + r')\1', '[JavaScript method]', line)
642
+ lines.append(line)
643
+ return ''.join(lines)
644
+
645
+
646
+ def path_check_copy(task, scratch):
647
+ copy = Path(scratch) / 'path-check' / task.name
648
+ (copy / 'environment').mkdir(parents=True, exist_ok=True)
649
+ (copy / 'instruction.md').write_text(path_check_text((task / 'instruction.md').read_text(errors='replace')))
650
+ for name in ('task.toml', 'environment/Dockerfile'):
651
+ if (task / name).is_file():
652
+ shutil.copyfile(task / name, copy / name)
653
+ return copy
654
+
655
+
656
+ def rebuild_summary(out):
657
+ """Reconstruct completed outcomes; ignore only an unfinished final journal line."""
658
+ out = Path(out)
659
+ summary = out / 'summary.json'
660
+ report = json.loads(summary.read_text())
661
+ expected = [Path(path).name for path in report['selected_tasks']]
662
+ expected_names = set(expected)
663
+ entries = {}
664
+ incomplete_tail = False
665
+ with (out / 'outcomes.jsonl').open() as stream:
666
+ for line in stream:
667
+ if not line.endswith('\n'):
668
+ incomplete_tail = True
669
+ break
670
+ entry = json.loads(line)
671
+ name = entry['task']
672
+ if name not in expected_names or name in entries:
673
+ raise ValueError(f'unknown or duplicate journal task: {name}')
674
+ entries[name] = entry
675
+ report['tasks'] = [entries[name] for name in expected if name in entries]
676
+ report['complete'] = len(entries) == len(expected) and not incomplete_tail
677
+ report['passed'] = report['complete'] and all(t['status'] == 'passed' for t in report['tasks'])
678
+ report['incomplete_journal_tail'] = incomplete_tail
679
+ pending = summary.with_suffix('.json.tmp')
680
+ pending.write_text(json.dumps(report, indent=2) + '\n')
681
+ pending.replace(summary)
682
+ return report
683
+
684
+
685
+ def run_checks(tasks, out, profile='training', timeout=300, upstream=None, exclude=(), concurrency=1,
686
+ resume=None, resume_record=None, accept_previous_path_check=False):
687
+ if concurrency < 1:
688
+ raise ValueError('concurrency must be positive')
689
+ if sys.version_info < (3, 11):
690
+ raise ValueError('Terminal-Bench checks require Python 3.11+; activate your prep environment')
691
+ manifest, checks, excluded = load_checks(profile, upstream, exclude)
692
+ if not checks:
693
+ raise ValueError('no static checks selected')
694
+ for command in ('bash', 'grep', 'sed', 'awk', 'find', 'sort', 'uniq', 'mktemp', 'dirname', 'basename', 'cat', 'tr', 'rm'):
695
+ if not shutil.which(command):
696
+ raise ValueError(f'missing required executable: {command}')
697
+ out.mkdir(parents=True, exist_ok=True)
698
+ if (out / 'outcomes.jsonl').exists():
699
+ raise ValueError('output already has task outcomes; use a new output directory or --rebuild-summary')
700
+ report = {'upstream': manifest['repository'], 'commit': manifest['commit'],
701
+ 'concurrency': concurrency, 'profile': profile, 'selected_tasks': [str(t) for t in tasks],
702
+ 'checks': checks, 'excluded_checks': excluded, 'tasks': [],
703
+ 'adaptations': {name: text for name, text in ADAPTATIONS.items() if name in checks or name == 'file names'},
704
+ 'checker_unit_tests_not_run': list(CHECKER_UNIT_TESTS),
705
+ 'conditional_checks': {AI_CHECK: 'runs only when GPTZERO_API_KEY is configured; missing key is a non-failing skip'},
706
+ 'complete': False, 'passed': False}
707
+ imported = {}
708
+ if resume:
709
+ from validation.checkpoints.static_resume import load
710
+ imported, report['resumed_from'] = load(resume, tasks, manifest, checks, profile, resume_record,
711
+ accept_previous_path_check)
712
+ print(f"Static checkpoint: importing {report['resumed_from']['imported_checks']} checks; "
713
+ f"rerunning changed checks {report['resumed_from']['rerun_changed_checks']}", flush=True)
714
+ for name, reason in excluded.items():
715
+ print(f'SKIP {name}: {reason}', flush=True)
716
+ if AI_CHECK in checks and not os.environ.get('GPTZERO_API_KEY', '').strip():
717
+ print('SKIP check_ai_detection.py: no GPTZERO_API_KEY configured (not a failure)', flush=True)
718
+ summary = out / 'summary.json'
719
+ summary.write_text(json.dumps(report, indent=2) + '\n')
720
+ log = out / 'checks.log'
721
+ log_lock = threading.Lock()
722
+ static_root = os.environ.get('ZIH_STATIC_TMPDIR')
723
+ with tempfile.TemporaryDirectory(prefix='tb-checks-', dir=static_root or '/tmp') as scratch, \
724
+ log.open('w') as combined_log, (out / 'outcomes.jsonl').open('x') as journal:
725
+ # Upstream invokes python3. Use this interpreter, not an unrelated
726
+ # system Python that may lack tomllib. No dependency installation needed.
727
+ bindir = Path(scratch) / 'bin'
728
+ bindir.mkdir()
729
+ check_python = os.environ.get('ZIH_STATIC_PYTHON', sys.executable)
730
+ (bindir / 'python3').symlink_to(check_python)
731
+ scripts = (upstream or TERMINAL_BENCH) / 'scripts/checks'
732
+ reference_script = Path(scratch) / 'adapted-scripts/check-test-file-references.sh'
733
+ if reference_script.name in checks:
734
+ reference_script.parent.mkdir()
735
+ reference_script.write_text(reference_check_script((scripts / reference_script.name).read_text()))
736
+ if static_root:
737
+ local_scripts = Path(scratch) / 'scripts'
738
+ shutil.copytree(scripts, local_scripts)
739
+ scripts = local_scripts
740
+ env = {**os.environ, 'PATH': str(bindir) + os.pathsep + os.environ.get('PATH', '')}
741
+ for key in ('FIX_DIRS', 'BASE_DIR', 'BASH_ENV', 'ENV'):
742
+ env.pop(key, None)
743
+ def check_task_body(task, scratch):
744
+ entry = {'task': task.name, 'path': str(task), 'checks': []}
745
+ try:
746
+ validate_input(task)
747
+ except (ValueError, OSError) as exc:
748
+ entry.update(status='error', error=str(exc))
749
+ else:
750
+ pending_checks = set(checks) - set(imported.get(task.name, {}))
751
+ if not pending_checks or (pending_checks <= {AI_CHECK} and not os.environ.get('GPTZERO_API_KEY', '').strip()):
752
+ # Complete checkpointed tasks need no staging copy or subprocesses.
753
+ # The optional AI check is still handled below using current credentials.
754
+ renamed = []
755
+ else:
756
+ if static_root:
757
+ staged = Path(scratch) / 'input' / task.name
758
+ shutil.copytree(task, staged)
759
+ task = staged
760
+ task, renamed = safe_copy(task, scratch)
761
+ if renamed:
762
+ entry['renamed_for_checks'] = renamed
763
+ for name in checks:
764
+ if name in imported.get(task.name, {}):
765
+ entry['checks'].append(imported[task.name][name])
766
+ continue
767
+ if name == AI_CHECK and not os.environ.get('GPTZERO_API_KEY', '').strip():
768
+ entry['checks'].append({'check': name, 'status': 'skipped', 'optional': True,
769
+ 'reason': 'no GPTZERO_API_KEY configured', 'exit_code': None, 'log': None})
770
+ continue
771
+ started = time.monotonic()
772
+ target = path_check_copy(task, scratch) if name == PATH_CHECK else adapted_check_copy(task, scratch, name, profile)
773
+ if name == 'check-test-file-references.sh':
774
+ evidence = json.loads((target / 'discovered-references.json').read_text())
775
+ if evidence:
776
+ entry['discoverable_reference_evidence'] = evidence
777
+ # Buffer each check separately so parallel outputs never interleave.
778
+ with tempfile.TemporaryFile(mode='w+', encoding='utf-8', errors='replace', dir=scratch) as stream:
779
+ # The scripts take under a second; a timeout means the node or the
780
+ # file system stalled (job 916252), so one more attempt is made.
781
+ for attempt in (1, 2):
782
+ try:
783
+ script = LOCAL_CHECKS.get(name) or (reference_script if name == reference_script.name else scripts / name)
784
+ interpreter = sys.executable if name in LOCAL_CHECKS else check_python if name.endswith('.py') else 'bash'
785
+ result = subprocess.run([interpreter, str(script), str(target)],
786
+ cwd=scratch, env=env, stdout=stream, stderr=subprocess.STDOUT, timeout=timeout)
787
+ status = 'passed' if result.returncode == 0 else 'failed'
788
+ rc = result.returncode
789
+ break
790
+ except subprocess.TimeoutExpired:
791
+ status, rc = 'error', None
792
+ stream.write(f'\nTimed out after {timeout} seconds (attempt {attempt})\n')
793
+ stream.flush()
794
+ stream.seek(0)
795
+ if name == PATH_CHECK and rc == 1:
796
+ if re.search(r'relative paths used \(should be absolute under /[^)]*\): ', stream.read()):
797
+ status = 'warning'
798
+ stream.seek(0)
799
+ if name == AI_CHECK and rc == 0:
800
+ text = stream.read()
801
+ if 'skipped' in text.lower() or 'No files to check' in text:
802
+ status = 'skipped'
803
+ stream.seek(0)
804
+ with log_lock:
805
+ combined_log.write(f'\n=== {entry["task"]} / {name} ===\n')
806
+ shutil.copyfileobj(stream, combined_log)
807
+ combined_log.write(f'\n=== result: {status}, exit_code: {rc} ===\n')
808
+ combined_log.flush()
809
+ entry['checks'].append({'check': name, 'status': status, 'optional': name == AI_CHECK, 'exit_code': rc,
810
+ 'log': str(log.resolve()), 'duration_seconds': round(time.monotonic() - started, 3)})
811
+ if status != 'passed':
812
+ print(f'{task.name}: {name}: {status} (see {log})', flush=True)
813
+ entry['warnings'] = [{'tag': 'relative-instruction-path', 'check': c['check'], 'log': c.get('log')} for c in entry['checks'] if c['status'] == 'warning']
814
+ entry['status'] = 'passed' if all(c['status'] in ('passed', 'warning') or (c['status'] == 'skipped' and c.get('optional')) for c in entry['checks']) else 'failed'
815
+ return entry
816
+ def check_task(task):
817
+ if not static_root:
818
+ return check_task_body(task, scratch)
819
+ # Bound live task copies in RAM; oversized tasks use durable scratch.
820
+ # Allow for staging plus renamed/path-check copies per concurrent task.
821
+ parent = scratch
822
+ try:
823
+ validate_input(task)
824
+ size = sum(p.stat().st_size for p in task.rglob('*') if p.is_file())
825
+ limit = int(os.environ.get('ZIH_STATIC_MAX_BYTES', '1073741824')) // (3 * concurrency)
826
+ if size > limit:
827
+ parent = os.environ['TMPDIR']
828
+ except (ValueError, OSError) as exc:
829
+ return {'task': task.name, 'path': str(task), 'checks': [], 'status': 'error', 'error': str(exc)}
830
+ # Delete only this task's temporary copies immediately after its checks.
831
+ with tempfile.TemporaryDirectory(prefix='static-task-', dir=parent) as task_scratch:
832
+ return check_task_body(task, task_scratch)
833
+ with ThreadPoolExecutor(max_workers=concurrency) as pool:
834
+ futures = [pool.submit(check_task, task) for task in tasks]
835
+ for future in as_completed(futures):
836
+ entry = future.result()
837
+ journal.write(json.dumps(entry) + '\n')
838
+ journal.flush()
839
+ print(f"{entry['task']}: {entry['status']}", flush=True)
840
+ report = rebuild_summary(out)
841
+ print(f'{len(checks)} upstream checks per task; {len(excluded)} explicitly excluded. Report: {summary}')
842
+ return 0 if report['passed'] else 1
843
+
844
+
845
+ def main():
846
+ ap = argparse.ArgumentParser(description=__doc__)
847
+ ap.add_argument('root', nargs='?', type=Path)
848
+ ap.add_argument('--profile', choices=('training', 'portable', 'terminal-bench'), default='training')
849
+ ap.add_argument('--out', type=Path, default=Path('verify-out/terminal-bench'))
850
+ ap.add_argument('--limit', type=int)
851
+ ap.add_argument('--concurrency', type=int, default=1, help='parallel static tasks')
852
+ ap.add_argument('--timeout', type=int, default=120, help='seconds per static script per task')
853
+ ap.add_argument('--list', action='store_true', help='list included and excluded checks')
854
+ ap.add_argument('--exclude', action='append', default=[], help='check ID or filename, optionally NAME=reason; repeat or comma-separate')
855
+ ap.add_argument('--dry-run', action='store_true')
856
+ ap.add_argument('--rebuild-summary', action='store_true', help='reconstruct --out/summary.json from saved task outcomes without rerunning checks')
857
+ a = ap.parse_args()
858
+ try:
859
+ if a.rebuild_summary:
860
+ report = rebuild_summary(a.out)
861
+ print(f"Recovered {len(report['tasks'])} task outcomes; complete={report['complete']}")
862
+ return 0 if report['passed'] else 1
863
+ if a.timeout <= 0 or (a.limit is not None and a.limit <= 0):
864
+ raise ValueError('--limit and --timeout must be positive')
865
+ manifest, checks, excluded = load_checks(a.profile, exclude=a.exclude)
866
+ if a.list or a.dry_run:
867
+ print(f"Terminal-Bench {manifest['commit']} ({a.profile})")
868
+ for name in checks:
869
+ print(('SKIP ' + name + ': no GPTZERO_API_KEY configured (not a failure)')
870
+ if name == AI_CHECK and not os.environ.get('GPTZERO_API_KEY', '').strip()
871
+ else f"{'CONDITIONAL' if name == AI_CHECK else 'RUN '} {name}")
872
+ for name, reason in excluded.items():
873
+ print(f'SKIP {name}: {reason}')
874
+ if a.list:
875
+ return 0
876
+ if a.root is None:
877
+ raise ValueError('provide a task or task directory')
878
+ tasks = discover_tasks(a.root)[:a.limit]
879
+ if a.dry_run:
880
+ for task in tasks:
881
+ print(f'Would check {task}')
882
+ return 0
883
+ return run_checks(tasks, a.out, a.profile, a.timeout, exclude=a.exclude, concurrency=a.concurrency)
884
+ except (ValueError, OSError) as exc:
885
+ ap.exit(1, f'{exc}\n')
886
+
887
+
888
+ if __name__ == '__main__':
889
+ raise SystemExit(main())
calibforge/ablations/evidence/stage1-corrected-report.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c00b60d9c12ec156d65de48bd07ad61d6bed85ceea9950d00348e504ae6b4dd4
3
+ size 27612947
calibforge/ablations/evidence/stage1-exclusions.json ADDED
The diff for this file is too large to render. See raw diff
 
calibforge/ablations/evidence/stage1-final-sanity-verification.json ADDED
The diff for this file is too large to render. See raw diff
 
calibforge/ablations/evidence/stage1-initial-outcome.json ADDED
The diff for this file is too large to render. See raw diff
 
calibforge/ablations/evidence/stage1-outcome.json CHANGED
The diff for this file is too large to render. See raw diff
 
calibforge/ablations/evidence/stage1-summary.json CHANGED
@@ -1,29 +1,20 @@
1
  {
2
- "task_count": 5372,
3
- "stage_counts": {
4
- "1": {
5
- "failed": 3383,
6
- "passed": 1989
7
- },
8
- "3": {
9
- "not_evaluated": 5372
10
- },
11
- "4": {
12
- "not_evaluated": 5372
13
- },
14
- "5": {
15
- "not_evaluated": 5372
16
- }
17
  },
18
- "check_counts": {
19
- "1:check-dockerfile-references.sh:failed": 2968,
20
- "1:check-dockerfile-sanity.sh:failed": 4,
21
- "1:check-nproc.sh:failed": 5,
22
- "1:check-pip-pinning.sh:failed": 871,
23
- "1:check-task-absolute-path.sh:warning": 310,
24
- "1:check-task-toml-schema.py:failed": 2
25
- },
26
- "contract_sha256": "fb8eb298e4341021b969d61a28c3ccd389bfb01e6d2dfb73d5a205a80529f46d",
27
- "source": "/hnvme/workspace/y500bb12-optiagent/calibforge-manual-20261014/missing-python-archives/source/tasks.parquet",
28
- "reporting_correction": "175 non-failing instruction-path warnings were incorrectly labeled missing_or_skipped_check in the loop summary. Raw checker report unchanged; corrected summary accepts warnings consistently with the validation pipeline."
29
  }
 
1
  {
2
+ "tasks_checked": 5372,
3
+ "stage1_passed": 4498,
4
+ "stage1_excluded": 874,
5
+ "failed_checks": {
6
+ "check-pip-pinning.sh": 871,
7
+ "check-task-toml-schema.py": 2,
8
+ "check-dockerfile-sanity.sh": 1
 
 
 
 
 
 
 
 
9
  },
10
+ "source": "/hnvme/workspace/y500bb12-optiagent/calibforge-manual-20261014/stage1-current/contract.stage1-tasks/0000.parquet",
11
+ "parquet_sha256": "0682a10c5a0c932d406749490f4d7c2761904e14c97046f9ec5fba25066644aa",
12
+ "policy": "User requested exclusion of all 871 unresolved pip-pinning tasks. Pip pinning remains a required check. Other genuine static failures are also held out. Earlier stage3 and stage3_stage5 ablations are unchanged.",
13
+ "provenance": {
14
+ "original_report": "/hnvme/workspace/y500bb12-optiagent/calibforge-manual-20261014/stage1-current/array/report/stage-1-merged.json",
15
+ "targeted_rerun": "/hnvme/workspace/y500bb12-optiagent/calibforge-manual-20261014/stage1-checker-corrections/rerun/summary.json",
16
+ "reused_checks": "All other checks retain their original results on the identical frozen task snapshot.",
17
+ "original_contract_sha256": "fb8eb298e4341021b969d61a28c3ccd389bfb01e6d2dfb73d5a205a80529f46d",
18
+ "checker_sha256": "bb094bb42b436caac10efa274a03bd37680c245e5163b193fb58453c77a9455e"
19
+ }
 
20
  }
calibforge/ablations/evidence/stage1-targeted-rerun.json ADDED
The diff for this file is too large to render. See raw diff
 
calibforge/ablations/variants.json CHANGED
@@ -85,7 +85,7 @@
85
  "contrastive_solver-system-administration_20260610_111702_004"
86
  ],
87
  "stage1_repaired_variant": {
88
- "status": "Stage-1 checking complete on 5372 tasks: 1989 passed, 3383 failed; repaired variant still pending.",
89
  "plan": "Preserve matched task IDs for the repair-effect ablation; record exclusions separately instead of silently conflating repair and filtering."
90
  },
91
  "stage2_variant": {
 
85
  "contrastive_solver-system-administration_20260610_111702_004"
86
  ],
87
  "stage1_repaired_variant": {
88
+ "status": "Corrected stage-1 selection complete: 4498 passed, 874 excluded (871 pip pins, 1 apt pins, 2 schema failures). Combined stage1/3/5 Parquet pending.",
89
  "plan": "Preserve matched task IDs for the repair-effect ablation; record exclusions separately instead of silently conflating repair and filtering."
90
  },
91
  "stage2_variant": {