From 565fe758ed37e6b3d7ccb480da0f0d988b574821 Mon Sep 17 00:00:00 2001 From: Ioannis Lamprou Date: Wed, 2 Dec 2026 16:41:34 +0100 Subject: [PATCH] feat(runs): add fix-flawed-tasks, rename flag-tasks to find-flawed-tasks --- .../SKILL.md | 8 +- .../references/tau3-banking.md | 0 .../references/where.md | 0 .../scripts/flags.py | 2 +- .agents/skills/fix-flawed-tasks/SKILL.md | 145 ++++++++++ .../fix-flawed-tasks/references/patch.md | 26 ++ .../references/tau3-banking.md | 31 +++ .../skills/fix-flawed-tasks/scripts/fix.py | 260 ++++++++++++++++++ AGENTS.md | 3 +- ...ill.py => test_find_flawed_tasks_skill.py} | 26 +- app/tests/test_fix_flawed_tasks_skill.py | 190 +++++++++++++ 11 files changed, 672 insertions(+), 19 deletions(-) rename .agents/skills/{flag-tasks => find-flawed-tasks}/SKILL.md (96%) rename .agents/skills/{flag-tasks => find-flawed-tasks}/references/tau3-banking.md (100%) rename .agents/skills/{flag-tasks => find-flawed-tasks}/references/where.md (100%) rename .agents/skills/{flag-tasks => find-flawed-tasks}/scripts/flags.py (99%) create mode 100644 .agents/skills/fix-flawed-tasks/SKILL.md create mode 100644 .agents/skills/fix-flawed-tasks/references/patch.md create mode 100644 .agents/skills/fix-flawed-tasks/references/tau3-banking.md create mode 100644 .agents/skills/fix-flawed-tasks/scripts/fix.py rename app/tests/{test_flag_tasks_skill.py => test_find_flawed_tasks_skill.py} (90%) create mode 100644 app/tests/test_fix_flawed_tasks_skill.py diff --git a/.agents/skills/flag-tasks/SKILL.md b/.agents/skills/find-flawed-tasks/SKILL.md similarity index 96% rename from .agents/skills/flag-tasks/SKILL.md rename to .agents/skills/find-flawed-tasks/SKILL.md index 111d44370..9da10ba29 100644 --- a/.agents/skills/flag-tasks/SKILL.md +++ b/.agents/skills/find-flawed-tasks/SKILL.md @@ -1,5 +1,5 @@ --- -name: flag-tasks +name: find-flawed-tasks description: Find the flawed and ambiguous tasks of a benchmark from finished Nullius runs and propose them as pending task flags for a person to accept. Use it when the user asks which tasks of a benchmark are broken, unfair, flawed or ambiguous, why no agent passes some tasks, whether the expected answers can be trusted, or wants task flags proposed for the filtered score. --- @@ -23,7 +23,7 @@ Two rules hold throughout: - **A flag never carries the expected outcome.** Its evidence is one short sentence that points to the problem. Below, `REPO` is the absolute path of the checkout this skill is in, `S` is -`REPO/.agents/skills/flag-tasks/scripts/flags.py` and `WORK` is a new folder outside the checkout and the runs, agreed +`REPO/.agents/skills/find-flawed-tasks/scripts/flags.py` and `WORK` is a new folder outside the checkout and the runs, agreed with the user. Run `S` with the Python that runs Nullius. ## 1. Agree on the runs @@ -105,7 +105,7 @@ readers gave it. The others are: - `unread`: fewer than two readers voted on it. Read `WORK/report.md`. Open each flagged case and its quotes yourself, and check that no line of evidence in -`WORK/flag-tasks.json` gives an expected outcome away. +`WORK/find-flawed-tasks.json` gives an expected outcome away. ## 6. Hand over @@ -115,7 +115,7 @@ write to a run. Then, for each job, look at what it holds and import: ```bash PYTHONPATH=REPO/app python3 -m nullius flags list -PYTHONPATH=REPO/app python3 -m nullius flags import --from WORK/flag-tasks.json --by flag-tasks +PYTHONPATH=REPO/app python3 -m nullius flags import --from WORK/find-flawed-tasks.json --by find-flawed-tasks ``` The flags arrive **pending**, filled in on the trial page's User judge tab, and change no score until a person accepts diff --git a/.agents/skills/flag-tasks/references/tau3-banking.md b/.agents/skills/find-flawed-tasks/references/tau3-banking.md similarity index 100% rename from .agents/skills/flag-tasks/references/tau3-banking.md rename to .agents/skills/find-flawed-tasks/references/tau3-banking.md diff --git a/.agents/skills/flag-tasks/references/where.md b/.agents/skills/find-flawed-tasks/references/where.md similarity index 100% rename from .agents/skills/flag-tasks/references/where.md rename to .agents/skills/find-flawed-tasks/references/where.md diff --git a/.agents/skills/flag-tasks/scripts/flags.py b/.agents/skills/find-flawed-tasks/scripts/flags.py similarity index 99% rename from .agents/skills/flag-tasks/scripts/flags.py rename to .agents/skills/find-flawed-tasks/scripts/flags.py index 4c01e2732..e5cf6373e 100644 --- a/.agents/skills/flag-tasks/scripts/flags.py +++ b/.agents/skills/find-flawed-tasks/scripts/flags.py @@ -222,7 +222,7 @@ def merge(args): lines += [f" - {flat(q['file'])}: \"{flat(q['text'])}\"" for q in v["quotes"]] if notes: lines += ["", "## Not counted", ""] + [f"- {n}" for n in notes] - write(args.out, "flag-tasks.json", {"flags": flags}) + write(args.out, "find-flawed-tasks.json", {"flags": flags}) write(args.out, "third.json", for_readers(third)) write(args.out, "report.md", "\n".join(lines) + "\n") print(summary + (f"; {len(notes)} votes or flags not counted, see report.md" if notes else "")) diff --git a/.agents/skills/fix-flawed-tasks/SKILL.md b/.agents/skills/fix-flawed-tasks/SKILL.md new file mode 100644 index 000000000..38aa9ad53 --- /dev/null +++ b/.agents/skills/fix-flawed-tasks/SKILL.md @@ -0,0 +1,145 @@ +--- +name: fix-flawed-tasks +description: Repair the flawed and ambiguous tasks of a benchmark into a new, versioned copy of the dataset, then measure the effect with a fixed-versus-original rerun. Use it after /find-flawed-tasks, when the user wants accepted task flags turned into fixes, a corrected benchmark version, or to know how much of an agent's score was lost to broken tasks. +--- + +# Fix tasks + +Accepted task flags come in; a **fixed copy** of the dataset goes out, with every change justified by the benchmark's +own material and agreed by two independent readers. Then a rerun compares the fixed copy with the original, side by +side, with the same agent and grader. The original dataset is never touched. + +Rules that hold throughout: + +- **Documents decide.** A fix makes the task match what the benchmark's material requires. A point the material does + not settle gets no fix: report it as `no-fix` instead of inventing a rule. +- **Blind to results.** A fixer and a reviewer see the task and the material, never runs, scores or conversations. If a + round is chosen from an agent's failures, label it `evidence-informed` and report it on its own line. +- **Two readers agree.** A fix is applied only when a second, independent reader agrees; changes the reviewer asks for + go back to the first reader. Unsure stays unchanged. +- **The answers stay here.** Nothing this skill reads or writes reaches an agent that is scored on the same benchmark. +- **The fixed copy is an experiment.** It never replaces the benchmark's official dataset. +- **Frozen before any run.** Fixes, labels and checks are hashed before anything is measured; afterwards a fix is only + reverted by the rule in step 8, and both numbers are reported. +- **Code benchmarks are experimental.** A blind test on SWE-bench did not meet its marks. There the step 5 run check is + required, read per test. + +Below, `REPO` is the absolute path of the checkout this skill is in, `S` is +`REPO/.agents/skills/fix-flawed-tasks/scripts/fix.py` and `WORK` a new folder outside the checkout and the runs, agreed with +the user. Run `S` with the Python that runs Nullius. + +## 1. Agree on the input + +The input is the **accepted** flags only (the status column of `nullius flags list `; leave pending +ones out) or a list of tasks the user names. Find the dataset the runs used and read `references/.md` if it +exists: it says where the task, the expected outcome, the grader and the material live. Optional: mix in a few +unflagged tasks and a few known-flawed ones, unlabelled, to count how often the fixer changes a sound task and how +often it misses a broken one. + +You build `WORK/material/`: the benchmark's documents a fixer may quote, such as its rules, policies and the task +texts. Copy, do not link. Every quote names its file by a path relative to this folder, as in /find-flawed-tasks step 4. It +is a different path from the file an edit changes, which is relative to the task folder. + +## 2. Fix (first reader) + +Give each task to a fixer: the strongest model you have, a separate subagent with its own folder. It gets this file, +`references/patch.md`, the task folder, `WORK/material/` and the brief below, and writes `WORK/proposals/.json` +in the format of `references/patch.md`. A `sound` verdict gets no patch; list the task by name in the report. + +1. From the material alone, decide `sound`, `flawed` (the expected outcome is wrong or cannot be reached) or + `ambiguous` (the material supports more than one outcome, or the outcome depends on something the task leaves open). +2. If not sound, propose the smallest change, preferring the most local one: the expected outcome; a missing fact in + the instructions of another party (a simulated user); stored data the task uses; accepting several outcomes (only + when each one is supported by the material and the grader can accept several); or `no-fix`. +3. Quote the sentence that justifies the change, copied exactly, with its file. +4. A fix makes the task correct, not easier. A new line for a simulated party states a fact, never what the agent + should do; it avoids words that name a tool option or argument; and the expected outcome must stay right if that + party never says the line. +5. Label it: `strict` (outcome or data corrected), `clarifying` (missing fact stated), `lenient` (several outcomes + accepted), `easier` (the fix also removes a hurdle or changes what is tested), `no-fix`. + +## 3. Review (second reader) + +A different strong model, same material, never the fixer's reasoning first: it forms its own verdict, then reads the +proposal and answers `agree`, `partly` (with the exact change) or `disagree`. Write `WORK/reviews/.md`. +`partly` goes back to the fixer, who accepts or rejects each point in `decisions`; the revised patch goes back to the +reviewer once. If the answer is still `partly`, treat it as `disagree`. Only a patch the reviewer finally agrees with +gets `"review": "agree"` and goes to `WORK/patches/`. On `disagree` there is no patch, the task stays unchanged and it +is reported by name. A `no-fix` the reviewer disputes is reported the same way. `apply` refuses a patch without an +agreed review, a quote under 15 characters, and with `--material WORK/material` a quote that is not in the file it +names. + +## 4. Apply + +```bash +python3 S apply WORK/fixed --patches WORK/patches --material WORK/material +``` + +The dataset is copied to `WORK/fixed`, then every edit is applied. An edit names a file inside the task folder and an +`old` text that must occur exactly once; if any edit fails, nothing is written. `WORK/fixed/APPLIED.json` lists every +task, its label, its round and its edits. A task can be fixed in several rounds, each in a new copy: every round is +kept, with the number of the copy it was applied in. + +## 5. Check + +Run the benchmark's own runner on `WORK/fixed` twice: once with its reference-solution agent and once with a +do-nothing agent (for Harbor, the agents `oracle` and `nop`). `references/.md` gives the command. Prepare +the commands; the user launches them. + +- `oracle` must pass every task. +- `nop` must pass none, except tasks whose correct outcome is to change nothing (for example a request the rules + refuse). These are the nop exceptions: list them by name. +- A fixed task is `SAFE` if it passes `oracle` and fails `nop` (or is a nop exception), else `UNSAFE`. Where there is + no reference solution, the task is unchecked. + +Write the results into the copy as `WORK/fixed/CHECKS.json`, before freezing, so the manifest covers them: + +```json +{"results": {"": "SAFE"}, "nop_exceptions": [""], "unchecked": [""]} +``` + +All three keys are required; the lists may be empty. A task is either in `results` or in `unchecked`, not both. +`freeze` needs a result or an unchecked entry for every fixed task, and refuses a copy with an `UNSAFE` task: that +fix is blocked. It goes back to step 2, and the next `apply` writes to a new folder (`WORK/fixed2`): a copy is never +edited in place. + +This check is required for every benchmark. Passing it is necessary, not sufficient: it cannot show that a fix is +right, that a flaw was missed, or that a change to text the control agents never read (a task description, a customer +script) is needed. For code benchmarks it is the only check that runs an edited test: read the result per test, not +per task, confirm from the test log that the edited test ran, and that it fails on the unchanged code. + +## 6. Freeze + +```bash +python3 S freeze WORK/fixed +``` + +Writes `WORK/fixed/MANIFEST.json`: a hash per file, one hash for the whole copy, every round of each task (label, +round, copy) and the checks. Quote the hash in every report and run recipe. Refuses to overwrite an existing manifest: +a new round is a new copy (`apply` from the frozen copy keeps the earlier records and needs new checks). Before any run +and after it, check nothing moved: + +```bash +python3 S verify WORK/fixed +``` + +## 7. Measure + +One run, two arms, same window: the agent on the fixed copy and the same agent on the original dataset, same agent +build and settings, same grader in both, the same number of tries per task. A try is one attempt of an agent at a +task; pass^k is the share of tasks where k tries all pass. Prepare the recipe; the user launches it. +Re-run attempts that failed for infrastructure reasons in both arms alike and report the counts. + +## 8. Report + +- The primary number, fixed in advance: the paired difference of pass^1 over all tasks, with its standard error over + per-task differences. Also pass^k. +- Split by label, so that lenient and easier fixes do not inflate the headline: `strict` + `clarifying` is the + headline split; unchanged tasks are the control and should show no difference. +- Any task that moves by half its tries or more, in either direction, gets a cause check. A fix is reverted only if + its own change caused a drop. A revert is a new patch, applied from the frozen copy into a new folder, checked + (step 5) and frozen again; the as-run number is always reported beside the new one. +- How often each new line for a simulated party was actually said. + +Hand over: the manifest hash, the counts per label, by name the sound, no-fix, disagreed and disputed tasks, the nop +exceptions and the unchecked tasks, the models used, and that the fixed copy is an experiment. diff --git a/.agents/skills/fix-flawed-tasks/references/patch.md b/.agents/skills/fix-flawed-tasks/references/patch.md new file mode 100644 index 000000000..24ad4b5b6 --- /dev/null +++ b/.agents/skills/fix-flawed-tasks/references/patch.md @@ -0,0 +1,26 @@ +# Patch format + +One file per task in `WORK/patches/`, named anything ending in `.json`: + +```json +{"task": "", + "label": "strict | clarifying | lenient | easier | no-fix", + "round": "blind | evidence-informed", + "review": "agree", + "quotes": [{"file": "", "text": "a sentence copied exactly"}], + "decisions": ["one line per reviewer point: accepted or rejected, and why"], + "edits": [{"file": "", "old": "exact text, once", "new": "replacement"}]} +``` + +- `review` is set to `agree` only after the second reader agreed; `apply` refuses anything else. +- `task` is the task's folder name, one level, no path. +- `round` is optional; the default is `blind`. +- `quotes` are required for every label except `no-fix`. Each `text` is at least 15 characters (the same minimum as + /find-flawed-tasks). It is matched with whitespace ignored, so line breaks may differ. `quotes[].file` is relative to + `WORK/material/`; `edits[].file` is relative to the task folder. +- A fix needs at least one edit; a `no-fix` patch has none and records that the material does not settle the task. +- Every edit has `file`, `old` and `new`. `new` is always text. `old` is required: text that occurs exactly once in + the file, or `null` to create a file that does not exist yet. +- Edits are plain text, so they work for any task format. When one fact lives in several files of a task (for example + a copy of the task for the grader and one for another service), edit every copy; `references/.md` says + where they are. diff --git a/.agents/skills/fix-flawed-tasks/references/tau3-banking.md b/.agents/skills/fix-flawed-tasks/references/tau3-banking.md new file mode 100644 index 000000000..ca7fadcf9 --- /dev/null +++ b/.agents/skills/fix-flawed-tasks/references/tau3-banking.md @@ -0,0 +1,31 @@ +# Fixing τ³-bench banking (banking_knowledge) tasks + +- **How the dataset is built.** Each task folder is a copy made by the Harbor adapter from tau2-bench. The task is + copied into `tests/config.json`, `environment/runtime-server/task_config.json` and `solution/`; the stored data + (`db.json`) is not copied, it comes from the image. +- **The task is stored three times** in each task folder: `tests/config.json` (`task`, used by the grader), + `environment/runtime-server/task_config.json` (`task`, used by the simulated customer and the tools) and + `solution/solve.sh` (the actions the `oracle` agent replays). A fix to the expected actions or the customer's + instructions edits all three; `expected_actions` and `reward_basis` in both JSON files follow + `task.evaluation_criteria`. +- **The customer's script** is `task.user_scenario.instructions`. A new line states a fact the customer knows; the + simulated customer may still not say it. +- **Stored data** (`db.json`) is inside the image, built from tau2-bench. A data fix adds the corrected file to + `environment/` and `environment/runtime-server/` and a `COPY` line to both Dockerfiles, replacing + `/opt/tau2-bench/data/tau2/domains/banking_knowledge/db.json`. Other tasks that use the same records must be + checked and listed. +- **Grading:** with `DB` in `reward_basis` the expected actions are replayed and the final databases compared, so an + argument the tool stores (amounts, names, free text) must match exactly. With `ACTION`, each expected action only has + to appear once; order, count and success are not checked. `COMMUNICATE` checks that given texts were said to the + customer. `NL_ASSERTION` is graded by an LLM judge in `tests/evaluate.py`; its model comes from + `TAU2_NL_ASSERTIONS_MODEL`, so keep that the same in both arms. +- **Several accepted outcomes** (`lenient`): the grader above accepts one set of expected actions. A lenient fix is + expressed as alternative accepted actions, for example a second action list that is also a pass. It needs a grader + that supports it: a change to `tests/evaluate.py` in every task that uses it, written as an edit like any other and + checked in step 5. Without such a grader, a point with several right outcomes is `no-fix`. +- **Run check (step 5)** with Harbor, on the fixed copy: + + ```bash + harbor run -p WORK/fixed -a oracle + harbor run -p WORK/fixed -a nop + ``` diff --git a/.agents/skills/fix-flawed-tasks/scripts/fix.py b/.agents/skills/fix-flawed-tasks/scripts/fix.py new file mode 100644 index 000000000..86c2b7541 --- /dev/null +++ b/.agents/skills/fix-flawed-tasks/scripts/fix.py @@ -0,0 +1,260 @@ +"""The /fix-flawed-tasks skill's script: apply agreed task patches to a copy of a dataset, freeze the copy, verify it later. + + fix.py apply DATASET OUT --patches DIR [--material DIR] copy DATASET to OUT, apply every patch (all or nothing) + fix.py freeze OUT write OUT/MANIFEST.json: file hashes, total hash, labels + fix.py verify OUT check OUT still matches its manifest + +A patch is applied only if its review agreed ("review": "agree"). Every quote is checked for its shape and length; +with --material it must also be found in the file it names. Freeze needs OUT/CHECKS.json, the step 5 results, and +refuses a copy with an UNSAFE task. Standard library only; the dataset given to apply is never written to. +""" + +import argparse +import hashlib +import json +import shutil +import sys +from pathlib import Path + +LABELS = ("strict", "clarifying", "lenient", "easier", "no-fix") +ROUNDS = ("blind", "evidence-informed") +RECORDS = ("APPLIED.json", "CHECKS.json", "MANIFEST.json") +CHECK_RESULTS = ("SAFE", "UNSAFE") +# The same minimum as /find-flawed-tasks (SHORTEST_QUOTE in flags.py), so a quote that counted there is long enough here. +# fix.py asks it of every quote, not only of the longest one: each quote must justify the change on its own. +SHORTEST_QUOTE = 15 + + +def _fail(msg): + raise SystemExit(f"fix-flawed-tasks: {msg}") + + +def _read(path): + with open(path, encoding="utf-8", newline="") as f: # keep line endings as they are + return f.read() + + +def _write(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "w", encoding="utf-8", newline="") as f: + f.write(text) + + +def _norm(text): + return " ".join(str(text).split()) + + +def load_patches(folder, material=None): + """Read and validate every *.json patch in `folder`; one task per patch.""" + folder = Path(folder) + if not folder.is_dir(): + _fail(f"no patch folder {folder}") + if material is not None and not Path(material).is_dir(): + _fail(f"no material folder {material}") + patches, seen = [], set() + for f in sorted(folder.glob("*.json")): + try: + p = json.loads(_read(f)) + except ValueError as e: # bad JSON, or not UTF-8 + _fail(f"{f.name}: not JSON ({e})") + task = p.get("task") if isinstance(p, dict) else None + if not isinstance(task, str) or task in ("", ".", "..") or "/" in task or "\\" in task: + _fail(f"{f.name}: needs a task folder name (one level, no path)") + if p.get("label") not in LABELS: + _fail(f"{f.name}: label must be one of {', '.join(LABELS)}") + if p.get("round", "blind") not in ROUNDS: + _fail(f"{f.name}: round must be one of {', '.join(ROUNDS)}") + if p.get("review") != "agree": + _fail(f"{f.name}: no agreed review (\"review\": \"agree\")") + edits = p.get("edits", []) + if not isinstance(edits, list) or any( + not isinstance(e, dict) or not isinstance(e.get("file"), str) or not isinstance(e.get("new"), str) + or not (e.get("old") is None or isinstance(e.get("old"), str)) for e in edits): + _fail(f"{f.name}: edits must be a list of {{file, old (text or null), new (text)}}") + if any("old" not in e for e in edits): + _fail(f"{f.name}: every edit needs \"old\": the text to replace, or null for a new file") + if (p["label"] == "no-fix") != (not edits): + _fail(f"{f.name}: a no-fix patch has no edits, any other patch has edits") + quotes = p.get("quotes", []) + if not isinstance(quotes, list) or (p["label"] != "no-fix" and not quotes): + _fail(f"{f.name}: a fix needs quotes from the material") + for q in quotes: + if not isinstance(q, dict) or not isinstance(q.get("file"), str) or not isinstance(q.get("text"), str): + _fail(f"{f.name}: quotes must be a list of {{file (text), text (text)}}") + if len(_norm(q["text"])) < SHORTEST_QUOTE: + _fail(f"{f.name}: quote from {q['file']} is too short (under {SHORTEST_QUOTE} characters)") + if material is not None: + src = _inside(Path(material), q["file"], f.name) + if not src.is_file() or _norm(q["text"]) not in _norm(_read(src)): + _fail(f"{f.name}: quote not found in {q['file']}") + if task in seen: + _fail(f"{f.name}: a second patch for {task}") + seen.add(task) + patches.append(p) + if not patches: + _fail(f"no patches in {folder}") + return patches + + +def _inside(base, rel, who): + base = base.resolve() + target = (base / rel).resolve() + if target == base or base not in target.parents: + _fail(f"{who}: {rel} is outside {base.name}") + return target + + +def plan(dataset, patches): + """Work out every file's new text in memory, keyed by resolved path; fail before anything is written.""" + dataset = Path(dataset).resolve() + out = {} + for p in patches: + task = _inside(dataset, p["task"], p["task"]) + if not task.is_dir() or task.parent != dataset: + _fail(f"{p['task']}: no such task folder in the dataset") + for e in p.get("edits", []): + path = _inside(task, e["file"], p["task"]) + rel = path.relative_to(dataset) + if e["old"] is None: + if path.exists() or rel in out: + _fail(f"{p['task']}/{e['file']}: a new file that already exists") + out[rel] = e["new"] + continue + if not path.is_file(): + _fail(f"{p['task']}/{e['file']}: no such file") + text = out[rel] if rel in out else _read(path) + n = text.count(e["old"]) if e["old"] else 0 + if n != 1: + _fail(f"{p['task']}/{e['file']}: the old text occurs {n} times, not once") + out[rel] = text.replace(e["old"], e["new"]) + return out + + +def apply(dataset, out, patch_dir, material=None): + dataset, out = Path(dataset).resolve(), Path(out).resolve() + if out.exists(): + _fail(f"{out} exists; a new round is a new copy") + if not dataset.is_dir(): + _fail(f"no dataset folder {dataset}") + if out == dataset or dataset in out.parents or out in dataset.parents: + _fail("the copy must be outside the dataset, and the dataset outside the copy") + patches = load_patches(patch_dir, material) + new_text = plan(dataset, patches) + previous = _records(dataset / "APPLIED.json") if (dataset / "APPLIED.json").is_file() else [] + copy = max((r.get("copy", 1) for r in previous), default=0) + 1 + # Only the copy's own records at the top are left behind; a task's files of the same name are kept. + def top(d, names): # skip record files at the dataset top level only + return [n for n in names if n in RECORDS] if Path(d).resolve() == dataset else [] + shutil.copytree(dataset, out, ignore=top) + for rel, text in new_text.items(): + _write(out / rel, text) + # Every round is kept: a task fixed again in a later copy gets a second record, with the next copy number. + record = previous + [{"task": p["task"], "label": p["label"], "round": p.get("round", "blind"), "copy": copy, + "edits": [e["file"] for e in p.get("edits", [])]} for p in patches] + _write(out / "APPLIED.json", json.dumps(record, indent=1) + "\n") + print(f"applied {len(new_text)} file changes to {sum(1 for p in patches if p.get('edits'))} tasks; " + f"{sum(1 for p in patches if not p.get('edits'))} no-fix; copy at {out}") + + +def _hashes(out): + files = {} + manifest = Path(out) / "MANIFEST.json" + for f in sorted(p for p in Path(out).rglob("*") if p.is_file() and p != manifest): + files[f.relative_to(out).as_posix()] = hashlib.sha256(f.read_bytes()).hexdigest() + total = hashlib.sha256("".join(f"{k}\t{v}\n" for k, v in files.items()).encode()).hexdigest() + return files, total + + +def _records(path): + try: + records = json.loads(_read(path)) + except ValueError as e: + _fail(f"{path}: not JSON ({e})") + if not isinstance(records, list) or any(not isinstance(r, dict) or not {"task", "label", "round"} <= set(r) + for r in records): + _fail(f"{path}: not a list of task records") + return records + + +def _checks(out, fixed): + """Read OUT/CHECKS.json, the step 5 results: every fixed task SAFE or unchecked, none UNSAFE.""" + path = out / "CHECKS.json" + if not path.is_file(): + _fail(f"{out} has no CHECKS.json; write the step 5 results first") + try: + checks = json.loads(_read(path)) + except ValueError as e: + _fail(f"{path.name}: not JSON ({e})") + lists = ("nop_exceptions", "unchecked") + if (not isinstance(checks, dict) or not isinstance(checks.get("results"), dict) + or any(v not in CHECK_RESULTS for v in checks["results"].values()) + or any(not isinstance(checks.get(k), list) or not all(isinstance(t, str) for t in checks[k]) + for k in lists)): + _fail(f"{path.name}: needs results {{task: SAFE or UNSAFE}}, nop_exceptions [tasks] and unchecked [tasks]") + both = sorted(set(checks["results"]) & set(checks["unchecked"])) + if both: + _fail(f"{path.name}: {', '.join(both)} listed both with a result and as unchecked; pick one") + unsafe = sorted(t for t, v in checks["results"].items() if v == "UNSAFE") + if unsafe: + _fail(f"blocked, not frozen: UNSAFE {', '.join(unsafe)}") + missing = sorted(set(fixed) - set(checks["results"]) - set(checks["unchecked"])) + if missing: + _fail(f"{path.name}: no result for fixed task {', '.join(missing)}; list it as SAFE or unchecked") + return checks + + +def freeze(out): + out = Path(out) + if not (out / "APPLIED.json").is_file(): + _fail(f"{out} has no APPLIED.json; run apply first") + if (out / "MANIFEST.json").exists(): + _fail(f"{out / 'MANIFEST.json'} exists; a new round is a new copy") + tasks = {} + for r in _records(out / "APPLIED.json"): + tasks.setdefault(r["task"], []).append({"label": r["label"], "round": r["round"], "copy": r.get("copy", 1)}) + fixed = [t for t, rounds in tasks.items() if any(x["label"] != "no-fix" for x in rounds)] + checks = _checks(out, fixed) + files, total = _hashes(out) + manifest = {"hash": total, "tasks": tasks, "checks": checks, "files": files} + _write(out / "MANIFEST.json", json.dumps(manifest, indent=1) + "\n") + print(f"frozen: {total}") + + +def verify(out): + out = Path(out) + if not (out / "MANIFEST.json").is_file(): + _fail(f"{out} has no MANIFEST.json; run freeze first") + try: + manifest = json.loads(_read(out / "MANIFEST.json")) + manifest["files"].items() + except (ValueError, KeyError, TypeError, AttributeError) as e: + _fail(f"{out / 'MANIFEST.json'}: not a manifest ({e})") + files, total = _hashes(out) + changed = sorted(set(files) ^ set(manifest["files"]) | {k for k in files if manifest["files"].get(k) != files[k]}) + if changed: + _fail(f"changed since freeze: {', '.join(changed[:10])}" + (" ..." if len(changed) > 10 else "")) + print(f"unchanged: {total}") + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="fix.py") + sub = ap.add_subparsers(dest="cmd", required=True) + a = sub.add_parser("apply") + a.add_argument("dataset") + a.add_argument("out") + a.add_argument("--patches", required=True) + a.add_argument("--material") + for name in ("freeze", "verify"): + sub.add_parser(name).add_argument("out") + args = ap.parse_args(argv) + try: + if args.cmd == "apply": + apply(args.dataset, args.out, args.patches, args.material) + else: + {"freeze": freeze, "verify": verify}[args.cmd](args.out) + except (OSError, ValueError) as e: # unreadable files and the like: a message, not a trace + _fail(f"{args.cmd} stopped: {e}") + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/AGENTS.md b/AGENTS.md index 1f25d8b86..1b2957a35 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,7 +173,8 @@ Short and plain: issues, pull requests, their comments, docs. | Settings and storage | `docs/settings/README.md`; `app/nullius/settings.py` | | Judgement; the PR judge | `docs/judgement.md`; docstring of `.github/scripts/judge_pr.py` | | A run that looks wrong, comparing runs | `/run-analysis` | -| Tasks that may be flawed or ambiguous | `/flag-tasks` | +| Tasks that may be flawed or ambiguous | `/find-flawed-tasks` | +| Fixing flagged tasks into a new dataset version | `/fix-flawed-tasks` | | A benchmark's Leaderboard labels | `/label-benchmark` | | Stale docs | `/docs-drift` | | The website; a release | `app/site/README.md`; `app/packaging/README.md` | diff --git a/app/tests/test_flag_tasks_skill.py b/app/tests/test_find_flawed_tasks_skill.py similarity index 90% rename from app/tests/test_flag_tasks_skill.py rename to app/tests/test_find_flawed_tasks_skill.py index 7d10abc75..b7fe4efb1 100644 --- a/app/tests/test_flag_tasks_skill.py +++ b/app/tests/test_find_flawed_tasks_skill.py @@ -1,4 +1,4 @@ -"""The /flag-tasks skill's script: which tasks it lists, which votes it counts, and flags that import as pending.""" +"""The /find-flawed-tasks skill's script: which tasks it lists, which votes it counts, and flags that import as pending.""" import contextlib import importlib.util @@ -11,8 +11,8 @@ from nullius.runs import failure_analysis as fa, flags_cli from tests.test_flags_cli import job -SCRIPT = Path(__file__).resolve().parents[2] / ".agents/skills/flag-tasks/scripts/flags.py" -spec = importlib.util.spec_from_file_location("flag_tasks_script", SCRIPT) +SCRIPT = Path(__file__).resolve().parents[2] / ".agents/skills/find-flawed-tasks/scripts/flags.py" +spec = importlib.util.spec_from_file_location("find_flawed_tasks_script", SCRIPT) script = importlib.util.module_from_spec(spec) spec.loader.exec_module(script) @@ -26,7 +26,7 @@ def vote(task, verdict, text=SENTENCE, file="fees.md", **more): class FlagTasks(unittest.TestCase): def setUp(self): - tmp = tempfile.TemporaryDirectory(prefix="nullius-flag-tasks-") + tmp = tempfile.TemporaryDirectory(prefix="nullius-find-flawed-tasks-") self.addCleanup(tmp.cleanup) self.root = Path(tmp.name) self.work, self.votes, self.material = (self.root / n for n in ("work", "votes", "material")) @@ -48,7 +48,7 @@ def merge(self, **readers): (self.votes / f"{name}.json").write_text(json.dumps(votes)) self.run_script("merge", self.work / "cases.json", "--votes", self.votes, "--material", self.material, "--out", self.work) - return {f["task"]: f for f in json.loads((self.work / "flag-tasks.json").read_text())["flags"]} + return {f["task"]: f for f in json.loads((self.work / "find-flawed-tasks.json").read_text())["flags"]} def spot(self): return self.run_script("spot", *self.runs, "--out", self.work) @@ -77,11 +77,11 @@ def test_a_proposal_for_a_unit_imports_onto_that_unit_never_one_of_its_name(self (self.votes / "a.json").write_text(json.dumps([vote("group-1", "flawed")])) (self.votes / "b.json").write_text(json.dumps([vote("group-1", "flawed")])) self.run_script("merge", self.work / "cases.json", "--votes", self.votes, "--material", self.material, "--out", self.work) - proposed = json.loads((self.work / "flag-tasks.json").read_text())["flags"] + proposed = json.loads((self.work / "find-flawed-tasks.json").read_text())["flags"] self.assertEqual([(f["task"], f["identity"]) for f in proposed], [("group-1", ["b", "1", "set", "group-1"])]) for name in ("alias", "both"): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - flags_cli.main(["import", str(self.root / "std"), name, "--from", str(self.work / "flag-tasks.json")]) + flags_cli.main(["import", str(self.root / "std"), name, "--from", str(self.work / "find-flawed-tasks.json")]) self.assertEqual(fa.load(str(alias)).flags, {}) # group/1 is shown as group-1: not it self.assertEqual({k: f.unit for k, f in fa.load(str(both)).flags.items()}, {"group-1": True}) @@ -99,12 +99,12 @@ def test_a_proposal_keeps_its_attempts_checksum_and_none_is_made_for_an_unresolv for reader in "ab": (self.votes / f"{reader}.json").write_text(json.dumps([vote("x", "flawed"), vote("group-1", "flawed")])) out = self.run_script("merge", self.work / "cases.json", "--votes", self.votes, "--material", self.material, "--out", self.work) - proposed = json.loads((self.work / "flag-tasks.json").read_text())["flags"] + proposed = json.loads((self.work / "find-flawed-tasks.json").read_text())["flags"] self.assertEqual([(f["task"], f["task_version"]) for f in proposed], [("x", "A")]) self.assertIn("1 votes or flags not counted", out) self.assertIn("group-1: flawed not proposed", (self.work / "report.md").read_text()) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: - flags_cli.main(["import", std.tmp, "later", "--from", str(self.work / "flag-tasks.json")]) + flags_cli.main(["import", std.tmp, "later", "--from", str(self.work / "find-flawed-tasks.json")]) self.assertEqual((fa.load(later).flags, err.getvalue()), ({}, "not in the job: x\n")) # later ran x at B def test_spot_leaves_out_infrastructure_errors_and_refuses_a_control_run(self): @@ -158,16 +158,16 @@ def test_the_flags_import_as_pending(self): self.merge(a=[vote("t1", "flawed")], b=[vote("t1", "flawed")]) with contextlib.redirect_stdout(io.StringIO()): code = flags_cli.main(["import", str(self.root / "jobs"), "run-a", - "--from", str(self.work / "flag-tasks.json"), "--by", "flag-tasks"]) + "--from", str(self.work / "find-flawed-tasks.json"), "--by", "find-flawed-tasks"]) flag = fa.load(str(self.runs[0])).flags["t1"] self.assertEqual((code, flag.kind, flag.status, flag.task_version, flag.by), - (0, "flawed", "pending", "c1", "flag-tasks")) + (0, "flawed", "pending", "c1", "find-flawed-tasks")) # the proposal keeps the checksum its attempts recorded: not one for a run where the task changed - proposed = json.loads((self.work / "flag-tasks.json").read_text())["flags"] + proposed = json.loads((self.work / "find-flawed-tasks.json").read_text())["flags"] self.assertEqual([(f["task"], f["task_version"], "identity" in f) for f in proposed], [("t1", "c1", False)]) later = job(self.root / "jobs", "run-later", {"t1": (1, "new")}) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: - flags_cli.main(["import", str(self.root / "jobs"), "run-later", "--from", str(self.work / "flag-tasks.json")]) + flags_cli.main(["import", str(self.root / "jobs"), "run-later", "--from", str(self.work / "find-flawed-tasks.json")]) self.assertEqual((fa.load(str(later)).flags, err.getvalue()), ({}, "not in the job: t1\n")) diff --git a/app/tests/test_fix_flawed_tasks_skill.py b/app/tests/test_fix_flawed_tasks_skill.py new file mode 100644 index 000000000..716e38e16 --- /dev/null +++ b/app/tests/test_fix_flawed_tasks_skill.py @@ -0,0 +1,190 @@ +"""The /fix-flawed-tasks skill's script: agreed patches apply all or nothing to a copy, and a frozen copy is checked.""" + +import contextlib +import importlib.util +import io +import json +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[2] / ".agents/skills/fix-flawed-tasks/scripts/fix.py" +spec = importlib.util.spec_from_file_location("fix_flawed_tasks_script", SCRIPT) +script = importlib.util.module_from_spec(spec) +spec.loader.exec_module(script) + +QUOTE = {"file": "fees.md", "text": "Fees are waived for gold customers only."} + + +def patch(task, label="strict", edits=None, **more): + if edits is None: + edits = [{"file": "tests/config.json", "old": '"amount": 50', "new": '"amount": 49'}] + quotes = [] if label == "no-fix" else [QUOTE] + return dict({"task": task, "label": label, "review": "agree", "quotes": quotes, "decisions": [], + "edits": edits}, **more) + + +class FixTasks(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory(prefix="nullius-fix-flawed-tasks-") + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.dataset, self.out = self.root / "ds", self.root / "fixed" + for t in ("t1", "t2"): + (self.dataset / t / "tests").mkdir(parents=True) + (self.dataset / t / "tests" / "config.json").write_text('{"amount": 50}') + (self.root / "material").mkdir() + (self.root / "material" / "fees.md").write_text("Fees are waived\n for gold customers only.\n") + self.n = 0 + + def patches(self, *ps): + self.n += 1 + d = self.root / f"patches{self.n}" + d.mkdir() + for i, p in enumerate(ps): + (d / f"p{i}.json").write_text(json.dumps(p)) + return d + + def run_script(self, *argv): + out = io.StringIO() + with contextlib.redirect_stdout(out): + script.main([str(a) for a in argv]) + return out.getvalue() + + def checks(self, out, results=None, unchecked=(), nop_exceptions=()): + results = {"t1": "SAFE"} if results is None else results + (Path(out) / "CHECKS.json").write_text(json.dumps( + {"results": results, "unchecked": list(unchecked), "nop_exceptions": list(nop_exceptions)})) + + def apply(self, *ps, dataset=None, out=None, material=False): + argv = ["apply", dataset or self.dataset, out or self.out, "--patches", self.patches(*ps)] + return self.run_script(*argv, *(["--material", self.root / "material"] if material else [])) + + def test_edits_go_to_the_copy_and_the_original_is_untouched(self): + before = script._hashes(self.dataset) + self.apply(patch("t1"), patch("t2", label="no-fix", edits=[]), material=True) + self.assertEqual(script._hashes(self.dataset), before) + self.assertEqual((self.out / "t1/tests/config.json").read_text(), '{"amount": 49}') + self.assertEqual((self.dataset / "t1/tests/config.json").read_text(), '{"amount": 50}') + applied = {r["task"]: r for r in json.loads((self.out / "APPLIED.json").read_text())} + self.assertEqual((applied["t1"]["label"], applied["t2"]["edits"]), ("strict", [])) + + def test_one_bad_edit_writes_nothing(self): + with self.assertRaisesRegex(SystemExit, "occurs 0 times"): + self.apply(patch("t1"), patch("t2", edits=[{"file": "tests/config.json", "old": "absent", "new": "x"}])) + self.assertFalse(self.out.exists()) + + def test_patches_that_are_wrong_are_named(self): + escape = [{"file": "x.txt", "old": None, "new": "x"}] + for bad, msg in ((patch("t1", label="maybe"), "label"), (patch("t9"), "no such task"), + (patch("t1", edits=[]), "no-fix"), (patch("t1", round="peeked"), "round"), + (patch("t1", review="partly"), "agreed review"), (patch("t1", quotes=[]), "quotes"), + (patch("t1", edits=[{"file": "../../x", "old": None, "new": "x"}]), "outside"), + (patch("../outside", edits=escape), "task folder name"), (patch("t1/", edits=escape), "task"), + (patch("t1", edits=[{"file": "tests/config.json", "old": 5, "new": "x"}]), "old"), + (patch("t1", edits=[{"file": "tests/config.json", "new": "x"}]), 'needs "old"'), + (patch("t1", quotes=[{"file": 3, "text": QUOTE["text"]}]), "quotes must be a list"), + (patch("t1", quotes=[QUOTE["text"]]), "quotes must be a list"), + (patch("t1", quotes=[{"file": "fees.md"}]), "quotes must be a list"), + (patch("t1", quotes=[dict(QUOTE, text="Fees waived.")]), "too short")): + with self.assertRaisesRegex(SystemExit, msg): + self.apply(bad) + self.assertFalse(self.out.exists()) + self.assertFalse((self.root / "outside").exists()) + + def test_a_quote_must_be_in_the_material(self): + with self.assertRaisesRegex(SystemExit, "quote not found"): + self.apply(patch("t1", quotes=[dict(QUOTE, text="Fees are waived for silver customers only.")]), + material=True) + + def test_a_short_quote_is_too_short_even_when_found(self): + with self.assertRaisesRegex(SystemExit, "too short") as caught: + self.apply(patch("t1", quotes=[dict(QUOTE, text="gold customers")]), material=True) + self.assertNotIn("not found", str(caught.exception)) + self.assertEqual(script.SHORTEST_QUOTE, 15) + + def test_the_same_file_under_two_spellings_keeps_both_edits(self): + (self.dataset / "t1/tests/config.json").write_text('{"amount": 50, "fee": 5}') + self.apply(patch("t1", edits=[{"file": "tests/config.json", "old": '"amount": 50', "new": '"amount": 49'}, + {"file": "./tests/config.json", "old": '"fee": 5', "new": '"fee": 0'}, + {"file": "environment/data.json", "old": None, "new": "{}"}])) + self.assertEqual((self.out / "t1/tests/config.json").read_text(), '{"amount": 49, "fee": 0}') + self.assertEqual((self.out / "t1/environment/data.json").read_text(), "{}") + + def test_a_tasks_own_record_named_files_are_kept_and_hashed(self): + (self.dataset / "t1/CHECKS.json").write_text("task file") + (self.dataset / "t1/sub").mkdir() + (self.dataset / "t1/sub/MANIFEST.json").write_text("task file") + self.apply(patch("t1")) + self.assertEqual((self.out / "t1/CHECKS.json").read_text(), "task file") + self.assertEqual((self.out / "t1/sub/MANIFEST.json").read_text(), "task file") + self.checks(self.out) + self.run_script("freeze", self.out) + files = json.loads((self.out / "MANIFEST.json").read_text())["files"] + self.assertIn("t1/CHECKS.json", files) + self.assertIn("t1/sub/MANIFEST.json", files) + self.assertNotIn("MANIFEST.json", files) + + def test_line_endings_are_kept(self): + (self.dataset / "t1/tests/config.json").write_bytes(b'{\r\n"amount": 50\r\n}') + self.apply(patch("t1")) + self.assertEqual((self.out / "t1/tests/config.json").read_bytes(), b'{\r\n"amount": 49\r\n}') + + def test_the_copy_must_be_outside_the_dataset(self): + with self.assertRaisesRegex(SystemExit, "outside the dataset"): + self.apply(patch("t1"), out=self.dataset / "fixed") + + def test_freeze_verify_and_a_second_round(self): + self.apply(patch("t1", round="evidence-informed")) + with self.assertRaisesRegex(SystemExit, "no CHECKS.json"): + self.run_script("freeze", self.out) + self.checks(self.out, results={}) + with self.assertRaisesRegex(SystemExit, "no result for fixed task t1"): + self.run_script("freeze", self.out) + self.checks(self.out, unchecked=["t1"]) + with self.assertRaisesRegex(SystemExit, "t1 listed both with a result and as unchecked"): + self.run_script("freeze", self.out) + self.checks(self.out, results={"t1": "UNSAFE"}) + with self.assertRaisesRegex(SystemExit, "blocked, not frozen: UNSAFE t1"): + self.run_script("freeze", self.out) + self.checks(self.out, nop_exceptions=["t2"]) + out = self.run_script("freeze", self.out) + manifest = json.loads((self.out / "MANIFEST.json").read_text()) + self.assertIn(manifest["hash"], out) + self.assertEqual(manifest["tasks"], {"t1": [{"label": "strict", "round": "evidence-informed", "copy": 1}]}) + self.assertEqual(manifest["checks"]["nop_exceptions"], ["t2"]) + self.assertIn("CHECKS.json", manifest["files"]) + self.assertIn("unchanged", self.run_script("verify", self.out)) + with self.assertRaisesRegex(SystemExit, "exists"): + self.run_script("freeze", self.out) + second = self.root / "fixed2" + self.apply(patch("t2"), patch("t1", label="clarifying", edits=[ + {"file": "tests/config.json", "old": "49", "new": "48"}]), dataset=self.out, out=second) + self.assertEqual([r["task"] for r in json.loads((second / "APPLIED.json").read_text())], ["t1", "t2", "t1"]) + self.assertFalse((second / "MANIFEST.json").exists()) + self.assertFalse((second / "CHECKS.json").exists()) + self.checks(second, results={"t1": "SAFE"}, unchecked=["t2"]) + self.run_script("freeze", second) + rounds = json.loads((second / "MANIFEST.json").read_text())["tasks"]["t1"] + self.assertEqual([(r["label"], r["copy"]) for r in rounds], [("strict", 1), ("clarifying", 2)]) + (self.out / "t1/tests/config.json").write_text("changed") + with self.assertRaisesRegex(SystemExit, "changed since freeze"): + self.run_script("verify", self.out) + + def test_verify_sees_an_added_or_a_removed_file(self): + self.apply(patch("t1")) + self.checks(self.out, results={"t1": "SAFE"}) + self.run_script("freeze", self.out) + extra = self.out / "t1/extra.txt" + extra.write_text("new") + with self.assertRaisesRegex(SystemExit, "changed since freeze"): + self.run_script("verify", self.out) + extra.rename(self.root / "extra-moved-aside.txt") + self.assertIn("unchanged", self.run_script("verify", self.out)) + (self.out / "t1/tests/config.json").rename(self.root / "config-moved-aside.json") + with self.assertRaisesRegex(SystemExit, "changed since freeze"): + self.run_script("verify", self.out) + + +if __name__ == "__main__": + unittest.main()