Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
156 lines
6.4 KiB
Python
156 lines
6.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Task files of the Codex lossy-delta study: parse task.md, hash trees, manifest (test tooling, stdlib only, Python 3.9+).
|
|
|
|
taskfile.py prompt TASKS_ROOT ID print the exact prompt text (no trailing newline)
|
|
taskfile.py check TASKS_ROOT [ID ...] verify MANIFEST.sha256 against the files; exit 1 on any difference
|
|
|
|
Manifest lines: `<sha256> <task>/<relpath>` for every file under tasks/<id>/ (sorted), `EXTERNAL <id> <relpath> <sha256> <bytes>`,
|
|
`PROMPT <id> <sha256 of the extracted prompt>`, `SEEDTREE <id> <digest>` (digest of the workspace the runner builds: seed/ plus external files)
|
|
and `TASK <id> <digest of the task's file lines>`.
|
|
"""
|
|
import hashlib
|
|
import os
|
|
import re
|
|
import sys
|
|
|
|
BEGIN = "<!-- PROMPT BEGIN -->"
|
|
END = "<!-- PROMPT END -->"
|
|
SKIP_DIRS = {"__pycache__", "node_modules", ".angular", "dist"} # node_modules: hard-linked in by the runner (--link-tree), never part of a seed or a workspace digest
|
|
|
|
|
|
def sha256_file(path):
|
|
h = hashlib.sha256()
|
|
with open(path, "rb") as f:
|
|
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
|
|
def sha256_text(text):
|
|
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def read_task(tasks_root, task_id):
|
|
"""-> dict(front matter fields, prompt, externals=[(relpath, sha256, bytes)])"""
|
|
with open(os.path.join(tasks_root, task_id, "task.md"), encoding="utf-8", newline="") as f:
|
|
text = f.read()
|
|
if "\r" in text:
|
|
raise ValueError("%s/task.md contains CR characters" % task_id)
|
|
m = re.match(r"---\n(.*?)\n---\n", text, re.S)
|
|
if not m:
|
|
raise ValueError("%s/task.md has no front matter" % task_id)
|
|
meta = {}
|
|
for line in m.group(1).splitlines():
|
|
if ":" in line:
|
|
k, v = line.split(":", 1)
|
|
meta[k.strip()] = v.strip()
|
|
if text.count(BEGIN) != 1 or text.count(END) != 1:
|
|
raise ValueError("%s/task.md needs exactly one prompt block" % task_id)
|
|
body = text.split(BEGIN, 1)[1].split(END, 1)[0]
|
|
meta["prompt"] = body.strip("\n")
|
|
ext = []
|
|
if "## External seed files" in text:
|
|
for line in text.split("## External seed files", 1)[1].splitlines():
|
|
parts = line.split()
|
|
if len(parts) == 3 and re.fullmatch(r"[0-9a-f]{64}", parts[1]):
|
|
ext.append((parts[0], parts[1], int(parts[2])))
|
|
meta["externals"] = ext
|
|
if meta.get("id") != task_id:
|
|
raise ValueError("%s/task.md has id %r" % (task_id, meta.get("id")))
|
|
return meta
|
|
|
|
|
|
def task_ids(tasks_root):
|
|
return sorted(d for d in os.listdir(tasks_root) if os.path.isfile(os.path.join(tasks_root, d, "task.md")))
|
|
|
|
|
|
def task_files(tasks_root, task_id, reference=False):
|
|
"""Files of a task directory. The reference solution (reference/) is not installed on the server (the agent could find it), so it is not part of
|
|
the checked file list; `reference=True` lists only it."""
|
|
base = os.path.join(tasks_root, task_id)
|
|
out = []
|
|
for root, dirs, files in os.walk(base):
|
|
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
|
|
in_ref = os.path.relpath(root, base).replace(os.sep, "/").split("/")[0] == "reference"
|
|
if in_ref != reference:
|
|
continue
|
|
for n in sorted(files):
|
|
if n.endswith(".pyc"):
|
|
continue
|
|
p = os.path.join(root, n)
|
|
out.append((os.path.relpath(p, tasks_root).replace(os.sep, "/"), p))
|
|
return sorted(out)
|
|
|
|
|
|
def tree_digest(lines):
|
|
return hashlib.sha256(("\n".join(lines) + "\n").encode()).hexdigest()
|
|
|
|
|
|
def seed_tree_lines(seed_dir, externals):
|
|
"""Lines `relpath sha256` of a workspace: the files of seed_dir plus the external files (sha256 from the task)."""
|
|
lines = []
|
|
if os.path.isdir(seed_dir):
|
|
for root, dirs, files in os.walk(seed_dir):
|
|
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
|
|
for n in sorted(files):
|
|
p = os.path.join(root, n)
|
|
lines.append("%s %s" % (os.path.relpath(p, seed_dir).replace(os.sep, "/"), sha256_file(p)))
|
|
for rel, sha, _n in externals:
|
|
lines.append("%s %s" % (rel, sha))
|
|
return sorted(lines)
|
|
|
|
|
|
def workspace_lines(ws):
|
|
return seed_tree_lines(ws, [])
|
|
|
|
|
|
def manifest_lines(tasks_root, ids=None):
|
|
out = []
|
|
for tid in ids or task_ids(tasks_root):
|
|
meta = read_task(tasks_root, tid)
|
|
file_lines = []
|
|
for rel, p in task_files(tasks_root, tid):
|
|
file_lines.append("%s %s" % (sha256_file(p), rel))
|
|
out.extend(file_lines)
|
|
for rel, sha, n in meta["externals"]:
|
|
out.append("EXTERNAL %s %s %s %d" % (tid, rel, sha, n))
|
|
out.append("PROMPT %s %s" % (tid, sha256_text(meta["prompt"])))
|
|
out.append("SEEDTREE %s %s" % (tid, tree_digest(seed_tree_lines(os.path.join(tasks_root, tid, "seed"), meta["externals"]))))
|
|
out.append("TASK %s %s" % (tid, tree_digest(file_lines)))
|
|
ref = ["%s %s" % (sha256_file(p), rel) for rel, p in task_files(tasks_root, tid, reference=True)]
|
|
out.append("REFERENCE %s %s" % (tid, tree_digest(ref)))
|
|
return out
|
|
|
|
|
|
def _task_of(line):
|
|
parts = line.split()
|
|
if parts and parts[0] in ("EXTERNAL", "PROMPT", "SEEDTREE", "TASK", "REFERENCE"):
|
|
return parts[1]
|
|
return parts[-1].split("/", 1)[0] if parts else ""
|
|
|
|
|
|
def check(tasks_root, ids=None):
|
|
"""-> list of problems (empty = the files match MANIFEST.sha256)."""
|
|
mpath = os.path.join(tasks_root, "MANIFEST.sha256")
|
|
if not os.path.isfile(mpath):
|
|
return ["MANIFEST.sha256 missing"]
|
|
recorded = [l for l in open(mpath, encoding="utf-8").read().splitlines() if l]
|
|
ids = ids or task_ids(tasks_root)
|
|
want = set(l for l in manifest_lines(tasks_root, ids) if not l.startswith("REFERENCE "))
|
|
have = set(l for l in recorded if _task_of(l) in ids and not l.startswith("REFERENCE ") and "/reference/" not in l)
|
|
return ["differs: " + l for l in sorted(want - have)] + ["recorded but not on disk: " + l for l in sorted(have - want)]
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) >= 4 and sys.argv[1] == "prompt":
|
|
sys.stdout.write(read_task(sys.argv[2], sys.argv[3])["prompt"])
|
|
elif len(sys.argv) >= 3 and sys.argv[1] == "check":
|
|
probs = check(sys.argv[2], sys.argv[3:] or None)
|
|
for p in probs:
|
|
print(p)
|
|
print("manifest OK" if not probs else "manifest MISMATCH (%d)" % len(probs))
|
|
sys.exit(1 if probs else 0)
|
|
else:
|
|
print(__doc__)
|
|
sys.exit(2)
|