From 14c06473fc84211c53060e15e9230dfab6a8f2fd Mon Sep 17 00:00:00 2001 From: Ioannis Lamprou Date: Wed, 25 Nov 2026 10:04:50 +0100 Subject: [PATCH] feat(runs): add the flag-tasks skill, propose flawed or ambiguous tasks as pending flags The skill checks a benchmark's tasks against its own material and proposes pending flags; a person accepts every flag. flags import gets --by, so a pending flag names the skill. --- .agents/skills/flag-tasks/SKILL.md | 124 +++++++++ .../flag-tasks/references/tau3-banking.md | 20 ++ .agents/skills/flag-tasks/references/where.md | 16 ++ .agents/skills/flag-tasks/scripts/flags.py | 239 ++++++++++++++++++ AGENTS.md | 1 + app/nullius/runs/flags_cli.py | 5 +- app/tests/test_flag_tasks_skill.py | 120 +++++++++ docs/cli/flags.md | 4 +- 8 files changed, 525 insertions(+), 4 deletions(-) create mode 100644 .agents/skills/flag-tasks/SKILL.md create mode 100644 .agents/skills/flag-tasks/references/tau3-banking.md create mode 100644 .agents/skills/flag-tasks/references/where.md create mode 100644 .agents/skills/flag-tasks/scripts/flags.py create mode 100644 app/tests/test_flag_tasks_skill.py diff --git a/.agents/skills/flag-tasks/SKILL.md b/.agents/skills/flag-tasks/SKILL.md new file mode 100644 index 00000000..111d4437 --- /dev/null +++ b/.agents/skills/flag-tasks/SKILL.md @@ -0,0 +1,124 @@ +--- +name: flag-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. +--- + +# Flag tasks + +**Spot** suspicious tasks by counting, have independent readers **check** each against the benchmark's own material, +**merge** their votes, then **a person decides** on the User judge tab. You never accept a flag. + +- `flawed`: the expected outcome is wrong, or the task gives no way to reach it. +- `ambiguous`: more than one reading is defensible and the grader accepts one. + +The two kinds are the same for every benchmark. The category, a short reason, is the benchmark's own. + +A hard task is not a flawed task. A rule that is stated somewhere the agent could read makes the task fair, however +many agents miss it. + +Two rules hold throughout: + +- **The answers stay here.** What this skill reads must never reach an agent that will be scored on the same benchmark: + not its prompt, its tools, its memory or its tuning. Say so when you hand over. +- **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 +with the user. Run `S` with the Python that runs Nullius. + +## 1. Agree on the runs + +One run is enough; two or more agents on the same dataset say more. Leave out control runs (`nop`, `oracle`). If +`/run-analysis` health says a run is broken, stop: its failures say nothing about the tasks. + +## 2. Find the material + +Read `references/.md` if it exists, else fill in a copy of `references/where.md` as `WORK/where.md`. Open +every place it names. The task folder a trial records may be on another machine: ask the user where the dataset is, and +for anything else you cannot find. Without the expected outcomes, stop. + +## 3. Spot + +```bash +python3 S spot [ ...] --out WORK +``` + +An attempt passes with a full reward. One with no reward or an infrastructure error is left out (an agent that ran out +of time counts if it has a reward), and so is a task whose version differs between the runs. Each task is `nobody` (no +attempt passed), `split` (one run passed every attempt, another none), `sometimes` or `always`. The cases are the +first three by default; `--only nobody,split` is cheaper and misses more; `--only nobody,split,sometimes,always` reads +every task. Tell the user how many cases that is and what reading them will cost, and wait for a yes. + +## 4. Check + +Make two folders with the cases' material: `WORK/material/` with what a reader may see first (instructions, documents, +code, tools, other parties' scripts, the grader), and `WORK/outcome/` with the expected outcomes and every note that +gives one away. Copy, do not link. In both, name each task's files as `WORK/for-readers.json` names the task, and +split a file that holds both. The grader goes to `outcome/` when it shows the answer. + +Give every case in `WORK/for-readers.json` to two readers: the strongest models you have, different ones if you can. +Each is a separate subagent, or a session of another assistant, with its own temporary folder. A reader gets the brief +below, `where.md` and the two folders. It never gets `cases.json`, the runs, or another reader's work. It writes +`WORK/votes/.json`, one vote per task: + +```json +[{"task": "…", "verdict": "flawed", "category": "contradicts_document", + "evidence": "Two documents disagree on the fee waiver.", + "quotes": [{"file": "fees_012.md", "text": "a sentence copied exactly"}], + "why": "one or two sentences"}] +``` + +The brief: + +1. From `material/` alone, work out which outcome you would expect and write it down. Only then open the task's file in + `outcome/`. +2. Take the expected outcome apart into every act, value, name and text the grader checks. For each, find the sentence + or existing behaviour that requires or allows it, look for one that forbids it, and ask where the agent would learn + it. +3. Write down one or two other outcomes that a careful agent could reach from the instruction and the rules, and check + whether the grader accepts them. Where another party is played by a model, do the same for what its script leaves + open. +4. Decide. `flawed`: a rule forbids what is expected, a checked fact cannot be known, or nothing settles a choice that + the grader fixes. `ambiguous`: the text supports two readings and the grader accepts one, or it is too vague to tell + a careful person what to do. `fair`: everything that is checked follows from the material. An outcome that no + careful agent would choose is not a reason to flag. +5. Every `flawed` or `ambiguous` needs a sentence copied exactly from `material/`, with its path there: the rule, or the + sentence that leaves the point open. No quote, no flag. +6. `evidence` is one short sentence of at most 60 characters: what is wrong, and where. It gives no value, name or act + of the expected outcome. Explain in `why`. +7. Unsure is `cannot_tell`. Read nothing else, and use nothing you know about these tasks from elsewhere. + +## 5. Merge + +```bash +python3 S merge WORK/cases.json --votes WORK/votes --material WORK/material --out WORK +``` + +A `flawed` or `ambiguous` vote counts only if its quotes are in the files they name; otherwise it becomes `cannot_tell`. +That shows the sentence is real, not that the argument is right. A verdict stands when more than half of the case's +readers gave it. The others are: + +- `third`: two readers disagree. Give `WORK/third.json` to a third reader, same brief, and merge again with its votes + beside the others. Repeat once only. +- `contested`: more than half say something is wrong, but not which kind. +- `undecided`: no majority, or it cannot be told. +- `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. + +## 6. Hand over + +Report in a few lines: tasks read and not read, flags of each kind, the contested and undecided ones by name, which +models voted (one model voting twice is weaker: say so), and that a person decides. Show the flags and ask before you +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 +``` + +The flags arrive **pending**, filled in on the trial page's User judge tab, and change no score until a person accepts +them there or with `nullius flags accept`. A person can also correct one and save it as their own, or remove it. An +accepted flag is kept; a pending flag on the same task is replaced, and one from an earlier round that is not in the +file stays. Never run `accept` or `remove` yourself. diff --git a/.agents/skills/flag-tasks/references/tau3-banking.md b/.agents/skills/flag-tasks/references/tau3-banking.md new file mode 100644 index 00000000..a281c73a --- /dev/null +++ b/.agents/skills/flag-tasks/references/tau3-banking.md @@ -0,0 +1,20 @@ +# Where to look: τ³-bench banking (banking_knowledge) + +- **Instruction:** `/instruction.md`: the policy the agent gets. +- **Expected outcome:** in `/tests/config.json`: `task.evaluation_criteria` (actions, the arguments compared, + `reward_basis`), `expected_actions`, `expected_communicate_info` and `task.description` (its notes can state the + answer). The actions are one way to the expected database state, not the only accepted order. +- **Grader:** `/tests/evaluate.py` runs tau2's own evaluator. With `DB` in `reward_basis` it replays the expected + actions and compares the final databases, so only what changes the database counts. +- **What the agent may read:** the knowledge documents, through its search tools, and the database, through its tools: + tau2-bench `data/tau2/domains/banking_knowledge/` (`documents/`, `db.json`). +- **Tools:** tau2-bench `src/tau2/domains/banking_knowledge/tools.py`; some are unlocked by name from a document. +- **Other parties:** a simulated customer who follows `task.user_scenario` in `/tests/config.json` and may have + tools of their own. It is a model: it can word things differently each time. +- **Conventions:** stated in the documents, which can be several for one topic: read every document on the topic. +- **Categories:** flawed: `contradicts_document` (a document or tool says otherwise), `several_valid_answers` (another + outcome is as good), `unreachable` (no way to the expected state), `unseen_fact` (a checked fact is shown nowhere). + Ambiguous: `two_readings` (of a document or of the request), `depends_on_simulator` (the outcome needs an act of the + simulated customer that its script does not ensure), `exact_name` (an exact name is compared that the documents give + in more than one form). +- **Not available:** nothing known. diff --git a/.agents/skills/flag-tasks/references/where.md b/.agents/skills/flag-tasks/references/where.md new file mode 100644 index 00000000..20e17446 --- /dev/null +++ b/.agents/skills/flag-tasks/references/where.md @@ -0,0 +1,16 @@ +# Where to look: + +Fill in every line with a path that you opened. `` is the task folder; in a Harbor dataset the defaults are the +ones given. + +- **Instruction:** `/instruction.md` +- **Expected outcome:** every place that gives it away, notes included: `/solution/`, `/tests/` +- **Grader:** what it compares, and what it ignores: `/tests/` +- **What the agent may read:** documents, code, data: +- **Tools:** names, arguments and what they return: +- **Other parties:** a simulated user's script, hidden state, what only they know: +- **Conventions:** rounding, time zone, default names, tie breaks, and where each is written: +- **Categories:** the reasons to choose from, each with one line. Start from these, drop what cannot happen here and add + what only this benchmark has: `contradicts_document`, `several_valid_answers`, `unreachable`, `unseen_fact` (flawed), + `two_readings` (ambiguous). +- **Not available:** what you could not find, so what cannot be judged: diff --git a/.agents/skills/flag-tasks/scripts/flags.py b/.agents/skills/flag-tasks/scripts/flags.py new file mode 100644 index 00000000..8db993b1 --- /dev/null +++ b/.agents/skills/flag-tasks/scripts/flags.py @@ -0,0 +1,239 @@ +"""Count the attempts of a benchmark's tasks, and merge readers' votes into proposed task flags. + + python3 flags.py spot JOB [JOB ...] --out DIR [--only nobody,split,sometimes,always] + python3 flags.py merge DIR/cases.json --votes DIR --material DIR [--material DIR ...] --out DIR + +Calls no model and writes only into --out. The flags it writes are for ``nullius flags import``. +""" +import argparse +import json +import os +import re +import sys +from collections import Counter + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), *[".."] * 4, "app"))) + +KINDS = ("flawed", "ambiguous") +VERDICTS = KINDS + ("fair", "cannot_tell") +GROUPS = ("nobody", "split", "sometimes", "always") +SHORTEST_QUOTE = 15 +LONGEST_EVIDENCE = 60 + + +def write(folder, name, data): + os.makedirs(folder, exist_ok=True) + with open(os.path.join(folder, name), "w", encoding="utf-8") as fh: + fh.write(data if isinstance(data, str) else json.dumps(data, indent=1, ensure_ascii=False) + "\n") + + +def for_readers(cases): + """The cases without the pass counts and the trials, which a reader must not see.""" + return [{"task": c["task"], "task_folder": c["task_folder"]} for c in cases] + + +def group(runs): + """The group of a task, from each run's (passed, attempts).""" + passed, total = sum(p for p, _ in runs), sum(n for _, n in runs) + if passed == 0: + return "nobody" + if passed == total: + return "always" + return "split" if any(p == n for p, n in runs) and any(p == 0 for p, _ in runs) else "sometimes" + + +def spot(args): + from nullius.runs import failure_analysis, parse + only = [g for g in args.only.split(",") if g] + if not only or set(only) - set(GROUPS): + sys.exit("--only takes " + ", ".join(GROUPS)) + seen, where, datasets, versions, left_out = {}, {}, set(), {}, 0 + for path in dict.fromkeys(os.path.realpath(p) for p in args.jobs): + job = next((j for j in parse.load_all([path]) if os.path.realpath(j.dir) == path), None) + if job is None: + sys.exit(f"no job in {path}") + if job.agent_name in ("nop", "oracle"): + sys.exit(f"{path} is a control run ({job.agent_name})") + datasets.add(job.dataset) + for task, version in failure_analysis.task_versions(job).items(): + versions.setdefault(task, set()).add(version) + for t in job.trials: + if t.reward is None or t.is_infra: + left_out += 1 + continue + run = seen.setdefault(t.task_base, {}).setdefault(path, [0, 0]) + run[0] += float(t.reward) >= 1 + run[1] += 1 + where.setdefault(t.task_base, t.dir) + if not seen: + sys.exit("no attempt with a reward: nothing to count") + if len(datasets) > 1: + sys.exit("the jobs ran different datasets: " + ", ".join(sorted(map(str, datasets)))) + changed = sorted(t for t in seen if len(versions.get(t, ())) > 1) + groups = {t: group(list(runs.values())) for t, runs in seen.items() if t not in changed} + cases = [] + for task in sorted(t for t in groups if groups[t] in only): + with open(os.path.join(where[task], "result.json"), encoding="utf-8") as fh: + task_id = json.load(fh).get("task_id") or {} + cases.append({"task": task, "group": groups[task], "runs": list(seen[task].values()), + "task_folder": task_id.get("path")}) + write(args.out, "cases.json", cases) + write(args.out, "for-readers.json", for_readers(cases)) + count = Counter(groups.values()) + print(", ".join(f"{g} {count[g]}" for g in GROUPS) + f"; {len(cases)} cases of {len(groups)} tasks") + if left_out: + print(f"left out: {left_out} attempts with no reward or an infrastructure error") + if changed: + print("left out, the runs had different versions: " + ", ".join(changed)) + + +def flat(text): + return re.sub(r"\s+", " ", str(text)).strip() + + +def cell(text): + return flat(text).replace("|", "/") + + +def quoted(quote, roots): + """True when the quote's words are in the file it names, under one of the roots.""" + if not isinstance(quote, dict): + return False + text = flat(quote.get("text", "")) + for root in map(os.path.realpath, roots): + path = os.path.realpath(os.path.join(root, str(quote.get("file", "")))) + if text and path.startswith(root + os.sep) and os.path.isfile(path): + with open(path, encoding="utf-8", errors="replace") as fh: + if text in flat(fh.read()): + return True + return False + + +def decide(verdicts): + """The verdict more than half of the readers gave. Without one: ``unread`` (fewer than two readers), ``third`` (two + that disagree), ``contested`` (more than half say flawed or ambiguous), or ``undecided``.""" + if len(verdicts) < 2: + return "unread" + top, n = Counter(verdicts).most_common(1)[0] + if n * 2 > len(verdicts): + return "undecided" if top == "cannot_tell" else top + if len(verdicts) == 2: + return "third" + return "contested" if sum(v in KINDS for v in verdicts) * 2 > len(verdicts) else "undecided" + + +def read_votes(folder, known): + """Each reader's votes by task, or an exit that names the vote to correct.""" + readers = {} + for name in sorted(f for f in os.listdir(folder) if f.endswith(".json")): + try: + with open(os.path.join(folder, name), encoding="utf-8") as fh: + votes = json.load(fh) + except ValueError as e: + sys.exit(f"{name} is not JSON: {e}") + if not isinstance(votes, list): + sys.exit(f"{name} holds no list of votes") + mine = readers[name[:-5]] = {} + for v in votes: + task = v.get("task") if isinstance(v, dict) else None + if task not in known: + sys.exit(f"{name}: " + (f"{task!r} is not one of the cases" if task else "a vote without a task")) + if task in mine: + sys.exit(f"{name}: two votes on {task}") + if v.get("verdict") not in VERDICTS: + sys.exit(f"{name}, {task}: verdict {v.get('verdict')!r} is not one of {', '.join(VERDICTS)}") + if len(flat(v.get("evidence") or "")) > LONGEST_EVIDENCE: + sys.exit(f"{name}, {task}: evidence over {LONGEST_EVIDENCE} characters, shorten it to one sentence") + mine[task] = v + if len(readers) < 2: + sys.exit(f"{len(readers)} readers in {folder}: at least two are needed") + return readers + + +def why_not(vote, roots): + """Why a flawed or ambiguous vote does not count, or None.""" + quotes = vote.get("quotes") + if not isinstance(quotes, list) or not quotes: + return "no quote" + if not all(quoted(q, roots) for q in quotes): + return "a quote is not in the file it names" + if max(len(flat(q["text"])) for q in quotes) < SHORTEST_QUOTE: + return f"no quote of {SHORTEST_QUOTE} characters or more" + if not all(isinstance(vote.get(k), str) and vote[k].strip() for k in ("category", "evidence")): + return "no category or no evidence" + return None + + +def merge(args): + for root in args.material: + if not os.path.isdir(root): + sys.exit(f"no such directory: {root}") + with open(args.cases, encoding="utf-8") as fh: + cases = json.load(fh) + readers = read_votes(args.votes, {c["task"] for c in cases}) + flags, rows, third, notes, total = [], [], [], [], Counter() + for case in cases: + task, votes = case["task"], [] + for name, given in readers.items(): + if task in given: + v = dict(given[task], reader=name) + reason = why_not(v, args.material) if v["verdict"] in KINDS else None + if reason: + notes.append(f"{name}, {task}: {v['verdict']} not counted, {reason}") + v["verdict"] = "cannot_tell" + votes.append(v) + result = decide([v["verdict"] for v in votes]) + total[result] += 1 + if result == "third": + third.append(case) + agree = [v for v in votes if v["verdict"] == result] if result in KINDS else [] + categories = [c for c, _ in Counter(flat(v["category"]) for v in agree).most_common()] + if agree: + lead = next(v for v in agree if flat(v["category"]) == categories[0]) + flags.append({"task": task, "kind": result, "category": categories[0], + "evidence": f"{flat(lead['evidence'])} ({len(agree)} of {len(votes)})"}) + said = "; ".join(f"{v['reader']}: {v['verdict']}" for v in votes) + rows.append((task, case["group"], result, ", ".join(categories), said, votes)) + order = {k: i for i, k in enumerate(("third", "contested", "flawed", "ambiguous", "undecided", "unread", "fair"))} + rows.sort(key=lambda r: (order[r[2]], r[0])) + summary = ", ".join(f"{k} {total[k]}" for k in order) + voted = ", ".join(f"{name} {len(given)}" for name, given in readers.items()) + lines = ["# Proposed task flags", "", f"{len(cases)} cases: {summary}. Votes: {voted}.", "", + "| Task | Attempts | Result | Category | Votes |", "|---|---|---|---|---|"] + lines += ["| " + " | ".join(cell(c) for c in r[:5]) + " |" for r in rows] + for task, _, result, _, _, votes in rows: + if result not in ("fair", "unread"): + lines += ["", f"## {task}: {result}", ""] + for v in votes: + lines.append(f"- {v['reader']}, {v['verdict']}: {flat(v.get('why', ''))}") + if v["verdict"] in KINDS: + lines.append(f" - category: {flat(v['category'])}; evidence: {flat(v['evidence'])}") + lines += [f" - {flat(q['file'])}: \"{flat(q['text'])}\"" for q in v["quotes"]] + if notes: + lines += ["", "## Votes not counted", ""] + [f"- {n}" for n in notes] + write(args.out, "flag-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 not counted, see report.md" if notes else "")) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = p.add_subparsers(dest="action", required=True) + s = sub.add_parser("spot") + s.add_argument("jobs", nargs="+") + s.add_argument("--out", required=True) + s.add_argument("--only", default="nobody,split,sometimes") + s.set_defaults(run=spot) + m = sub.add_parser("merge") + m.add_argument("cases") + m.add_argument("--votes", required=True) + m.add_argument("--material", required=True, action="append") + m.add_argument("--out", required=True) + m.set_defaults(run=merge) + args = p.parse_args(argv) + args.run(args) + + +if __name__ == "__main__": + main() diff --git a/AGENTS.md b/AGENTS.md index 5451f493..ad99e5e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -171,6 +171,7 @@ 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` | | Stale docs | `/docs-drift` | | The website; a release | `app/site/README.md`; `app/packaging/README.md` | | This machine | `.claude/environment.local.md`, if present | diff --git a/app/nullius/runs/flags_cli.py b/app/nullius/runs/flags_cli.py index 407fd159..dac350b9 100644 --- a/app/nullius/runs/flags_cli.py +++ b/app/nullius/runs/flags_cli.py @@ -6,7 +6,7 @@ nullius flags accept ( | --all-pending) nullius flags remove nullius flags copy - nullius flags import --from FILE [--prefix P] + nullius flags import --from FILE [--prefix P] [--by NAME] nullius flags feasibility ```` is anything ``nullius runs`` reads. A task is named as the job names it (its ``task_base``, the name @@ -175,7 +175,7 @@ def accept(a): versions = fa.task_versions(job, {args.prefix + str(r.get("task", "")) for r in records if isinstance(r, dict)}) source = "import:" + os.path.basename(args.from_file) added, unknown, skipped = fa.update(job.dir, lambda a: fa.import_flags( - a, records, tasks, source=source, by=by, prefix=args.prefix, versions=versions)) + a, records, tasks, source=source, by=args.by or by, prefix=args.prefix, versions=versions)) _report("imported, pending:", added, unknown, skipped) elif args.action == "feasibility": report = feasibility.report(job, jobs) @@ -225,6 +225,7 @@ def parser() -> argparse.ArgumentParser: if name == "import": s.add_argument("--from", dest="from_file", required=True) s.add_argument("--prefix", default="") + s.add_argument("--by", help="who proposes the flags, e.g. the skill's name") return p diff --git a/app/tests/test_flag_tasks_skill.py b/app/tests/test_flag_tasks_skill.py new file mode 100644 index 00000000..a2bcb37e --- /dev/null +++ b/app/tests/test_flag_tasks_skill.py @@ -0,0 +1,120 @@ +"""The /flag-tasks skill's script: which tasks it lists, which votes it counts, and flags that import as pending.""" + +import contextlib +import importlib.util +import io +import json +import tempfile +import unittest +from pathlib import Path + +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 = importlib.util.module_from_spec(spec) +spec.loader.exec_module(script) + +SENTENCE = "Fees are waived for gold customers only." + + +def vote(task, verdict, text=SENTENCE, file="fees.md", **more): + return dict({"task": task, "verdict": verdict, "category": "contradicts_document", "evidence": "fees.md", + "quotes": [{"file": file, "text": text}], "why": "w"}, **more) + + +class FlagTasks(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory(prefix="nullius-flag-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")) + for d in (self.votes, self.material): + d.mkdir() + (self.material / "fees.md").write_text("Fees are waived\n for gold customers only.\n") + (self.root / "secret.md").write_text(SENTENCE) + self.runs = [job(self.root / "jobs", name, {"t1": (0, "c1"), "t2": (t2, "c2"), "t3": (1, "c3"), "t4": (0, v)}) + for name, t2, v in (("run-a", 0, "c4"), ("run-b", 1, "new"))] + + 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 merge(self, **readers): + for name, votes in readers.items(): + (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"]} + + def spot(self): + return self.run_script("spot", *self.runs, "--out", self.work) + + def test_spot_groups_the_tasks_and_leaves_out_a_changed_version(self): + out = self.spot() + groups = {c["task"]: c["group"] for c in json.loads((self.work / "cases.json").read_text())} + self.assertEqual(groups, {"t1": "nobody", "t2": "split"}) + self.assertIn("different versions: t4", out) + + def test_spot_leaves_out_infrastructure_errors_and_refuses_a_control_run(self): + f = self.runs[0] / "t2__1" / "result.json" + f.write_text(json.dumps(dict(json.loads(f.read_text()), exception_info={ + "exception_type": "EnvironmentStartTimeoutError", "exception_message": "", "exception_traceback": ""}))) + out = self.spot() + self.assertIn("left out: 1 attempts", out) + self.assertNotIn("t2", [c["task"] for c in json.loads((self.work / "cases.json").read_text())]) + f = self.runs[0] / "config.json" + f.write_text(json.dumps(dict(json.loads(f.read_text()), agents=[{"name": "nop"}]))) + with self.assertRaisesRegex(SystemExit, "control run"): + self.spot() + + def test_readers_never_get_the_counts(self): + self.spot() + self.merge(a=[vote("t1", "flawed")], b=[vote("t1", "fair")]) + for name in ("for-readers.json", "third.json"): + for case in json.loads((self.work / name).read_text()): + self.assertEqual(set(case), {"task", "task_folder"}) + + def test_two_readers_flag_and_a_third_breaks_a_tie(self): + self.spot() + self.assertEqual(set(self.merge(a=[vote("t1", "flawed"), vote("t2", "flawed")], + b=[vote("t1", "flawed"), vote("t2", "fair")])), {"t1"}) + self.assertEqual([c["task"] for c in json.loads((self.work / "third.json").read_text())], ["t2"]) + self.assertEqual(set(self.merge(c=[vote("t2", "flawed")])), {"t1", "t2"}) + + def test_a_vote_without_a_real_quote_does_not_count(self): + self.spot() + for bad in (vote("t1", "flawed", text="Fees are waived for silver customers."), + vote("t1", "flawed", file="../secret.md"), vote("t1", "flawed", text="Fees"), + vote("t1", "flawed", quotes="none"), vote("t1", "flawed", evidence="")): + self.assertEqual(self.merge(a=[bad], b=[bad]), {}) + + def test_votes_to_correct_are_named(self): + self.spot() + for bad in ([vote("t1", "fair"), vote("t1", "flawed")], [vote("t9", "fair")], [{"verdict": "fair"}], + [vote("t1", "maybe")], {"t1": "fair"}, [vote("t1", "flawed", evidence="x" * 61)]): + with self.assertRaisesRegex(SystemExit, "a.json"): + self.merge(a=bad, b=[vote("t1", "fair")]) + + def test_decide(self): + for verdicts, want in ((["flawed"], "unread"), (["flawed", "fair"], "third"), (["fair", "fair"], "fair"), + (["flawed", "ambiguous", "fair"], "contested"), (["cannot_tell"] * 2, "undecided"), + (["flawed", "flawed", "fair", "fair"], "undecided")): + self.assertEqual(script.decide(verdicts), want) + + def test_the_flags_import_as_pending(self): + self.spot() + 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"]) + 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")) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/cli/flags.md b/docs/cli/flags.md index c73be35f..6769d687 100644 --- a/docs/cli/flags.md +++ b/docs/cli/flags.md @@ -8,8 +8,8 @@ nullius flags set --kind flawed|ambiguous --categ nullius flags accept ( | --all-pending) nullius flags remove nullius flags copy -nullius flags import --from FILE [--prefix P] +nullius flags import --from FILE [--prefix P] [--by NAME] nullius flags feasibility ``` -A flag from `set` counts at once. One from `set --pending`, `copy`, `import` or `feasibility` waits for `accept`, and never replaces an accepted flag. Exit codes: `0` done, `2` usage, `3` not found, `4` invalid input. +A flag from `set` counts at once. One from `set --pending`, `copy`, `import` or `feasibility` waits for `accept`, and never replaces an accepted flag. `import --by` names who proposes the flags; without it, the person running the import. Exit codes: `0` done, `2` usage, `3` not found, `4` invalid input.