diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md index 9112225..38bb7a7 100644 --- a/docs/architecture/05-building-block-view.md +++ b/docs/architecture/05-building-block-view.md @@ -16,7 +16,7 @@ dependency with its keyword. | Block | Responsibility | Reads | Writes | | ----- | -------------- | ----- | ------ | | `generate_arm.py` | Builds one arm's file by script, with no model call: fixed text, the templates' emitter, its skills apart or inlined, or a map of the chain's topics. Scans the output for leaks and named tools; its self-test rebuilds every committed arm and fails on any difference | `brief.txt`, the templates source | `arms//CLAUDE.md`, `generation.json` | -| `harness.py` | Prepares each workspace, runs the agent in isolation, catches reach, freezes the result, keeps the run record current | The specs, the arm files, the change prompt | The run root | +| `harness.py` | Prepares each workspace, runs the agent in isolation, catches reach, freezes the result, keeps the run record current. Holds a run naming a round to that round's registration, and starts its change tasks from one fixture per block | The specs, the arm files, the change prompt, the fixture manifest and its tarballs | The run root | | `reuse.py` | Copies an earlier round's trials and readings into a new root, with their tool lock | An earlier root | The run root, the scoring area | | `progress.py` | Watches a run: one bar per arm, its voided tries, its cost and the trial running; then its scoring: one bar per arm, the security readings and the trial being scored; then its judging: one bar per arm of judgings out of those owed, the failures still owed and the blind label in hand. Redrawn every 30 s. Read-only | The run records, the scoring area | The console | | `score.py` | Installs each frozen trial cleanly, runs the hidden suite, the static tools and the adherence checklist, counts scope and cost | The run root, the hidden suite, `scoring-requirements.txt`, `toolconfig/` | `scores/`, `scores-change/` | @@ -36,6 +36,7 @@ dependency with its keyword. | `SPEC-thin.md` | The same contract without the practices, for `--spec thin` | harness | | `brief.txt` | What an adopter would type: domain, stack, personal data, boundaries | `generate_arm.py` | | `change-prompt.txt` | The change task's prompt, naming everything its grader drives | harness | +| `change-fixtures.json` | The builds a named round's change task starts from, one per block, each with its tarball's sha256 and the baseline readings that qualified it | harness | | `arms//CLAUDE.md` | Each arm's context file. `arms//skills/` holds a skills arm's skills | harness | | `arms//generation.json` | How each generated file was made | `report.py` | | `scoring-requirements.txt` | The scoring tools, resolved once into the tool lock | `score.py` | diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index c8e0f64..812e547 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -149,7 +149,7 @@ The layers: | Web tools disallowed | Fetching a page | `curl` or `git clone` in the shell | | Git credential helpers cleared | An authenticated clone of the hidden suite | | | Process-stop commands denied | Stopping the harness by name | Stopping by PID or port | -| Transcript scan | Any tool call naming a forbidden path or repository | A call the transcript does not record | +| Transcript scan | Any tool call naming a forbidden path or repository | A call the transcript does not record; a path the shell builds indirectly, through a variable, a wildcard or a climb past a name the scan knows | **Rules** @@ -159,6 +159,7 @@ The layers: | 2 | The tools are fenced | File tools denied outside the workspace, web tools disallowed, no Git credentials, no stop by name | FR-05-03 to FR-05-06 | | 3 | The transcript is the backstop | A hit voids the trial and re-runs it once; the report scans again under the current rule | FR-05-07, FR-05-08 | | 4 | Nothing outlives the trial | Every process started from its directories is stopped before it is frozen | FR-05-09 | +| 5 | A change task's fixtures are fenced | Their directory is in the deny rules, and the scan flags a path naming it or one of its archives; a tripwire for named access, since no static scan of a shell command is complete | FR-13-16 | The decision is ADR-020. diff --git a/docs/coverage.md b/docs/coverage.md index ed2abc2..00d6acd 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -31,9 +31,9 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-01-01 | Self-test | `report.py` "one landed after the first trial is refused"
`report.py` "one merged after the first trial is read at the merge"
`report.py` "a registration landed before the first trial passes, across zones" | +| FR-01-01 | Self-test | `report.py` "one landed after the first trial is refused"
`report.py` "one merged after the first trial is read at the merge"
`report.py` "a registration landed before the first trial passes, across zones"
`report.py` "the main branch is read locally, else as origin's, and a clone with neither is refused, not crashed" | | FR-01-02 | Self-test | `report.py` "one changed and not committed is refused"
`report.py` "an amendment on a branch of its own is refused" | -| FR-01-03 | Self-test | `report.py` "a trial on another spec is refused"
`report.py` "a trial on another prompt is refused"
`report.py` "every trial on the registered spec passes"
`report.py` "every trial on the one prompt passes" | +| FR-01-03 | Self-test | `report.py` "a trial on another spec is refused"
`report.py` "a trial on another prompt is refused"
`report.py` "every trial on the registered spec passes"
`report.py` "every trial on the one prompt passes"
`report.py` "a named round's trial on a spec or prompt its entry does not pin is refused, each task held to its own" | | FR-01-04 | Self-test | `report.py` "a scorable trial recording no spec is refused"
`report.py` "a scorable trial recording no prompt is refused" | | FR-01-05 | Self-test | `harness.py` "a spec edited mid-run refuses the next trial unbuilt"
`harness.py` "a spec changed as it is copied refuses the trial and frees its slot"
`harness.py` "a round-5 run on other content is refused"
`harness.py` "round 6's registered digest is SPEC.md's content, and round 5's is another" | | FR-01-06 | Self-test | `report.py` "a trial start with no UTC offset is refused" | @@ -199,6 +199,16 @@ when: | FR-13-08 | Self-test | `generate_arm.py` "a built file naming a tool is refused" | | FR-13-09 | Self-test | `report.py` "with no --out-dir it lands in this repository's docs/reports/, needing the stamp but no templates source" | | FR-13-10 | Self-test | `generate_arm.py` "every committed arm is what the script builds at its recorded ref, byte for byte, the same twice" | +| FR-13-11 | Self-test | `harness.py` "C1 pins SPEC.md, both prompts and its fixtures by content"
`harness.py` "an unknown round is refused"
`harness.py` "an arm the round does not register is refused"
`harness.py` "a K past the round's registered K is refused"
`harness.py` "a C1 run reads its spec from its entry, not its arms' names"
`harness.py` "a build or change prompt the round does not pin is refused" | +| FR-13-12 | Self-test | `harness.py` "every trial record of a named round names its round, task, arm and block"
`harness.py` "a named round's run record names its round, registration and fixtures"
`harness.py` "a root holding another round's or registration's runs is refused"
`harness.py` "a named round and records naming none never share a root"
`harness.py` "a named round's trial record missing its identity is refused"
`harness.py` "a named round's run refuses a root whose records name none"
`harness.py` "recovery keeps a named round's identity in its run record"
`harness.py` "a run whose trials name a round under a header naming none is refused" | +| FR-13-13 | Self-test | `report.py` "a run its records name C1 does not read as a pilot round"
`report.py` "a root mixing a named round's records with others is refused"
`report.py` "a named round's record missing its identity is refused, not read as the pilot's"
`report.py` "a run whose trials name a round under a header naming none is refused, not read as the pilot's" | +| FR-13-14 | Self-test | `harness.py` "a round of two tasks is complete only with both at K for every arm"
`harness.py` "a change task counts though its arm's build trial failed"
`report.py` "a C1 round owes a block until both tasks are in for every arm"
`report.py` "a C1 block whose builds stand only as change tasks is still owed" | +| FR-13-15 | Self-test | `harness.py` "an empty fixture manifest refuses a named round's change task"
`harness.py` "a fixture listed without its baseline readings is refused"
`harness.py` "a fixture whose tarball differs from its listed hash is refused, at the start and at each trial"
`harness.py` "block b starts from the b-th qualifying build, ascending, cycling"
`harness.py` "a named round's change run records how many distinct fixtures its blocks take"
`harness.py` "a named round's change task needs no build trial of its arm"
`harness.py` "a change run whose manifest or block mapping differs from the root's earlier change runs is refused" | +| FR-13-16 | Self-test | `harness.py` "a change workspace keeps its fixture's code and tests"
`harness.py` "a change workspace drops the fixture's instructions, settings, databases, caches, environments and history"
`harness.py` "a change workspace carries the round's spec and only its arm's context"
`harness.py` "a change workspace starts from one commit, with nothing uncommitted"
`harness.py` "every arm's change workspace of a block holds the same code"
`harness.py` "a change trial may neither read nor name its fixtures' directory"
`harness.py` "a fixture's links stay where what they name stays"
`harness.py` "a fixture linking outside what its change tasks keep is unusable, at the start and at a trial"
`report.py` "a call into the fixtures' directory its record fences off is flagged on the re-scan" | +| FR-13-17 | Self-test | `report.py` "a named round's change task with no build score is read on its own"
`report.py` "a reached build of a named round keeps its change reading, and a reached change task goes alone"
`report.py` "a change task standing alone counts on its ISO axes, not as a broken build"
`report.py` "a change task standing alone reads no build Python"
`report.py` "a named round's change result reads the same whether its build is unscored, working or broken" | +| FR-13-18 | Self-test | `reuse.py` "a named round's trials copied on keep its round in the run record's header"
`reuse.py` "a reuse never mixes a named round's trials with others"
`reuse.py` "a trial copied within a named round names that round in its origin"
`report.py` "trials reused within one named round pair with those run there" | +| FR-13-19 | Self-test | `report.py` "a named round is refused until its registration document is on main before its first trial"
`report.py` "a trial reused within its named round counts toward when the round began" | +| FR-13-20 | Self-test | `archive.py` "a C1 change task's score changed in the archive fails the verify" | | FR-13-21 | Self-test | `reuse.py` "the readings are filed under the word and name their origin"
`reuse.py` "a quality reading comes along with its trial"
`reuse.py` "the judgings keep their labels and the map is theirs alone" | ## 14 One run at a time diff --git a/docs/journeys/run/run-a-round.md b/docs/journeys/run/run-a-round.md index 44135bc..9ccdd70 100644 --- a/docs/journeys/run/run-a-round.md +++ b/docs/journeys/run/run-a-round.md @@ -34,6 +34,15 @@ round running overnight. A trial that was blocked is handled in runs it after the build trials with `--task change`, and scores it with `score.py --task change`. +From round 6 a run names its round, as `--round C1`, and the harness holds it +to that round's registration: its arms, its K, its spec and both prompts. Its +change task starts from the fixtures in `change-fixtures.json`, not from the +arm's own build, so it runs with `--fixtures ` and needs no build trial first. The run prints what each task +still owes; the round is complete with both tasks at K for every arm. +Its registration, `docs/rounds/round-c1.md` for C1, lands on `main` before +the first trial, or the report refuses the round. + ## Commands ```bash @@ -41,6 +50,8 @@ py tests/efficacy/harness.py --self-test --templates py tests/efficacy/harness.py --root --arms none,inline,hybrid,reference,skills --k 15 --model claude-sonnet-5 --dry-run py tests/efficacy/harness.py --root --arms none,inline,hybrid,reference,skills --k 15 --model claude-sonnet-5 py tests/efficacy/score.py --root +py tests/efficacy/harness.py --root --round C1 --k 15 --model claude-sonnet-5 +py tests/efficacy/harness.py --root --round C1 --task change --fixtures --k 15 --model claude-sonnet-5 ``` ## Findings diff --git a/docs/requirements.md b/docs/requirements.md index 0f92f91..3fce73d 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -31,15 +31,17 @@ - **Arm generator:** `generate_arm.py`, which writes a generated arm's file. - **Control builder:** `control/control.py`, which builds the judge's control trees. + - **Reuse:** `reuse.py`, which brings an earlier round's trials into a + run root. - **Owner:** a working practice no script carries out. ### 01 Registration | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-01-01 | The benchmark shall refuse, from round 5, a round whose registration landed on `main` after its first trial started, a merge counting at the merge. | Report | +| FR-01-01 | The benchmark shall refuse, from round 5, a round whose registration landed on `main` after its first trial started, a merge counting at the merge; `main` read as the local branch, else as `origin/main`, and a clone holding neither refused with its reason. | Report | | FR-01-02 | The benchmark shall refuse a registration that differs from `main`'s copy or has changes not committed. | Report | -| FR-01-03 | The benchmark shall refuse a trial built from a spec or prompt other than the ones its round registers, compared by content. | Report | +| FR-01-03 | The benchmark shall refuse a trial built from a spec or prompt other than the ones its round registers, compared by content; a named round's trials each against its entry's spec and the prompt pinned for their task. | Report | | FR-01-04 | The benchmark shall refuse a trial with something to score that records no spec or no prompt. | Report | | FR-01-05 | The benchmark shall check the spec before every trial, and refuse unbuilt the trials after an edit made mid-run. | Harness | | FR-01-06 | The benchmark shall record each trial's start with its UTC offset, and refuse a start with none. | Harness, Report | @@ -210,6 +212,16 @@ | FR-13-08 | The benchmark shall refuse a built arm file that names a tool. | Arm generator | | FR-13-09 | The benchmark shall write a round's report, by default, to its own `docs/reports/`, with no templates source named. | Report | | FR-13-10 | The benchmark shall build every arm a round runs by script, with no model call, and fail its self-test where a committed arm differs from what the script builds at the arm's recorded ref. | Arm generator | +| FR-13-11 | From round 6 the benchmark shall run a round only as `--round` names it, under its registration: refusing a round not registered, an arm it does not register, a K past its K, and a spec, build prompt or change prompt other than the ones it pins by digest. | Harness | +| FR-13-12 | The benchmark shall write a named round and its registration's digest in the run record, and the round, task, arm and block in every trial record, keeping them when a recovery rewrites the record; and refuse a run in a root whose records name another round or digest, or where a named round and records naming none would meet, a header naming no round over trials that name one counting as a named round's record. | Harness | +| FR-13-13 | The benchmark shall read a round from its run records where they name one, refuse records of a named round missing its identity, in a trial or in the header, and infer the round from the arms only for records naming none. | Report | +| FR-13-14 | The benchmark shall call a round of two tasks complete only with both at K for every arm, a change task counting whatever its arm's build trial did. | Harness, Report | +| FR-13-15 | The benchmark shall start every arm's change task of block b of a named round from one fixture, the b-th qualifying build in ascending trial order, cycling when fewer qualify; record the manifest's sha256, each block's fixture and how many distinct fixtures the blocks take; refuse a change run whose manifest or block mapping differs from the root's earlier change runs; and refuse to run while the fixture manifest lists none, lists one without its baseline readings, or names a tarball whose sha256 differs, at the start and at each trial. | Harness | +| FR-13-16 | The benchmark shall derive each change workspace from its fixture's code and tests alone, without its instructions, settings, databases, caches, environments or history, with the round's spec and only the arm's context, in one commit; and fence the fixtures' directory off from the trial, in its deny rules and every scan of its transcripts, the report's re-scan included, a path into it named absolutely, by a fixture archive's name or by a climb to its own name, and refuse a run root inside it, paths compared resolved and, on Windows, in either case; the scan catches a named access only, not a path the shell builds indirectly. Each kept link shall name something the workspace keeps, a fixture holding any other read as unusable, before the run and at a trial. | Harness, Report | +| FR-13-17 | The benchmark shall read a named round's change task whether or not its build trial was scored or left out for a reach, as a trial of its own whose build rows read not measured; count its change targets on their ISO axes whether its build is unscored, working or broken, a broken build gating only the build's own targets; and keep a pilot round's change task with its build. | Report | +| FR-13-18 | The benchmark shall reuse a named round's trials under a run record naming that round and its registration's digest, and never reuse trials into a root of another round, a named round's into a root of none, or another round's into a named round's; name the round and its digest in each reused trial's origin, and pair a trial reused within one named round, under one digest, with the trials run there. | Reuse, Report | +| FR-13-19 | The benchmark shall refuse a named round's report unless the document its registration entry names exists and landed on `main` before the round's first trial, unchanged since, a trial reused within the round counting toward its start. | Report | +| FR-13-20 | The benchmark shall verify an archive by the report's own reading of its round, through one entry point, a named round's change tasks and its reach rule included. | Archive, Report | | FR-13-21 | The benchmark shall bring a reused trial's score, security and quality readings and judgings into the later round, each naming the trial it came from. | Reuse | ### 14 One run at a time diff --git a/tests/efficacy/archive.py b/tests/efficacy/archive.py index fb454de..cbb1713 100644 --- a/tests/efficacy/archive.py +++ b/tests/efficacy/archive.py @@ -25,10 +25,11 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import lib # noqa: E402 -from harness import (TrialError, assert_outside_repository, # noqa: E402 - claim_path, claim_refusal_check, project_folder, - read_claim, remove_tree, running_as, scoring_area, - write_run) +from harness import (REGISTRATIONS, TrialError, # noqa: E402 + assert_outside_repository, claim_path, + claim_refusal_check, project_folder, read_claim, + registration_digest, remove_tree, running_as, + scoring_area, write_run) MANIFEST = "ARCHIVE.json" STAMP = "archived.json" @@ -292,8 +293,12 @@ def figures(root, seed): """What the report computes from a root, with paths left out.""" import report - trials = report.load(root) - report.exclude_reached(trials, report.reaches(root)) + # Read as the report reads it, by one entry point, so a reading the + # report counts can never change unseen by the verify. + trials, problem = report.round_trials(root) + if problem: + raise TrialError(problem) + report.leave_out_reached(root, trials) table = report.collect(trials) results = report.round_contrasts(trials, table, seed) withdrawn = report.withdrawals(trials) @@ -530,6 +535,32 @@ def self_test(): checks.append(("a reading changed in the archive fails the verify", landed and verify(root, into, seed) != [])) + # A C1 root whose one change task has no build score: the report reads + # it, so the verify has to, and a change to it in the archive shows. + named = os.path.join(scratch, "c1") + tarball = os.path.join(named, "change-none-1.tar") + os.makedirs(named) + plant_tarball(tarball, "change-none-1") + write_run(os.path.join(named, "run-c1.json"), + datetime.datetime(2026, 11, 15, 12, 0, 0).astimezone(), + [{"arm": "none", "trial": 1, "outcome": "completed", + "frozen": {"head": "h", "tarball": tarball}}], "change", + identity={"round": "C1", "registration": + registration_digest(REGISTRATIONS["C1"])}) + dump_json(os.path.join(scoring_area(named), "scores-change", + "none-1.json"), + {"name": "none-1", "change_suite": {"value": 0.9}}) + named_into = os.path.join(scratch, "runs", "c1") + archive(named, named_into) + clean = verify(named, named_into, seed) == [] + archived = os.path.join(scoring_area(named_into), "scores-change", + "none-1.json") + dump_json(archived, dict(load_json(archived), + change_suite={"value": 0.4})) + checks.append(("a C1 change task's score changed in the archive fails " + "the verify", + clean and "table" in verify(named, named_into, seed))) + # A round-5d root is verified by round 5d's rules, so reliability's # interval is Newcombe's there as it is in the report. later = os.path.join(scratch, "round-5d") diff --git a/tests/efficacy/change-fixtures.json b/tests/efficacy/change-fixtures.json new file mode 100644 index 0000000..832190e --- /dev/null +++ b/tests/efficacy/change-fixtures.json @@ -0,0 +1,15 @@ +{ + "round": "C1", + "source": { + "round": "5e", + "arm": "none", + "tarballs": "the frozen none-.tar of round 5e's run root, also in its archive" + }, + "qualification": null, + "fixture_fields": { + "trial": "the source build's trial name, as none-3", + "sha256": "the sha256 of that build's frozen tarball", + "baseline": "the source build's frozen readings the qualification took, an object" + }, + "fixtures": [] +} diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index 5949730..29d0758 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -17,6 +17,7 @@ import io import json import os +import posixpath import re import shutil import signal @@ -164,6 +165,43 @@ "skills": "lazyskills/skills"}, } +# The rounds from 6 on, each as registered: its spec, its arms, and per task +# its K and the digest of the prompt every arm is given. A run names its round +# with `--round` and is held to this entry rather than to what its arm names +# suggest, since a round may reuse a pilot arm's name. The pilot rounds have no +# entry and keep the checks they ran under. Each names the document that +# registers it, which has to be on the main branch before its first trial. +REGISTRATIONS = { + "C1": { + "document": "docs/rounds/round-c1.md", + "spec": {"name": "normal", "file": "SPEC.md", + "sha256": ROUND6_SPEC[1]}, + "arms": ["none", "reference", "inline", "skills", "lazyref", + "lazyskills"], + "tasks": { + "build": { + "k": 15, + "prompt_sha256": "e6ca96707fb227d9053eeffcca344963803a2b34" + "2ca8dddab5951e26b914724b"}, + + # Every arm's change task of a block starts from the same build, + # one arm `none` made in round 5e, so the change measures the + # file and not the build the arm happened to leave. The manifest, + # beside this module, lists the builds that qualified, each with + # its tarball's hash, so a fixture swapped later no longer matches. + "change": { + "k": 15, + "prompt_sha256": "52f053c49e0103535e3e966bbcf8f27915be5a7c" + "412283e61b7799cabbdaf829", + "fixtures": { + "manifest": "change-fixtures.json", + "from": {"round": "5e", "arm": "none"}, + "order": "ascending trial number, block b takes the b-th " + "qualifying build, cycling when fewer qualify"}}, + }, + }, +} + def trial_name(arm, block): """A trial's name: the arm's word, a hyphen, the block it runs in.""" return "%s-%d" % (arm, int(block)) @@ -245,10 +283,11 @@ def rule_path(path): return "/" + full -def reach_denials(root, workspace): +def reach_denials(root, workspace, protected=()): """Read and Edit deny rules for what a trial may not reach that a path - names: this repository, the scoring area, and every entry of the run root - but the trial's own workspace and temporary directory. + names: this repository, the scoring area, every entry of the run root + but the trial's own workspace and temporary directory, and each + `protected` directory, such as the one its change task's fixture is in. The shell is not covered, since a deny rule matches a command's prefix and not the paths in it; the transcript scan reads what the shell sent. @@ -268,6 +307,7 @@ def reach_denials(root, workspace): targets.append(source) targets += [os.path.join(root, name) for name in sorted(names) if name != own] + targets += fenced_paths(protected) patterns = ["%s/**" % rule_path(target) for target in targets] patterns += ["%s/%s" % (rule_path(root), entry) for entry in ("*.tar", "run-*.json")] @@ -306,14 +346,16 @@ def kill_denials(): for pattern in patterns for tool in SHELL_TOOLS] -def trial_settings(home, root, workspace): +def trial_settings(home, root, workspace, protected=()): """Write a trial's own settings file into the scratch home, which its - deny rules cover, and return its path.""" + deny rules cover, and return its path; `protected` names directories + outside the run root it may not read either.""" os.makedirs(home, exist_ok=True) path = os.path.join(home, "settings-%s.json" % os.path.basename(os.path.abspath(workspace))) settings = dict(ISOLATED_SETTINGS, - permissions={"deny": reach_denials(root, workspace) + permissions={"deny": reach_denials(root, workspace, + protected) + kill_denials()}) with io.open(path, "w", encoding="utf-8") as handle: json.dump(settings, handle, indent=2) @@ -581,6 +623,15 @@ def prepare_workspace(arm, trial, root, spec=SPEC): os.makedirs(workspace) shutil.copyfile(spec, os.path.join(workspace, "SPEC.md")) + vendored = install_arm(workspace, arm) + commit_start(workspace, "start: %s arm %s" % (ARMS[arm]["label"], arm)) + return workspace, vendored + + +def install_arm(workspace, arm): + """Give a workspace, not yet a repository, its arm's context: the file, + the vendored templates, the skills; `git init` it; return what was + vendored, None for an arm that vendors nothing.""" context = ARMS[arm]["context"] if context: source = os.path.join(ARMS_DIR, context) @@ -601,11 +652,15 @@ def prepare_workspace(arm, trial, root, spec=SPEC): raise TrialError("arm %s needs its skills at %s, which do not " "exist" % (arm, source)) place_skills(workspace, source) + return vendored + + +def commit_start(workspace, message): + """Commit everything in the workspace as its starting state.""" git(workspace, "add", "-A") git(workspace, "-c", "user.name=efficacy", "-c", "user.email=efficacy@example.invalid", - "commit", "-q", "-m", "start: %s arm %s" % (ARMS[arm]["label"], arm)) - return workspace, vendored + "commit", "-q", "-m", message) # The one thing the scratch home must inherit. Credentials live under the @@ -1179,10 +1234,12 @@ def read_transcripts(home, workspace, since=None): return files, tool_calls(files) -def reach(files, calls, workspace=None, temp=None, vendored=None): +def reach(files, calls, workspace=None, temp=None, vendored=None, + protected=(), names=()): """The tool calls naming this repository or the hidden suite and, given the trial's workspace, the scoring area or any part of the run root other - than the trial's own workspace and temporary directory. + than the trial's own workspace and temporary directory, or any path + into a `protected` directory, or any of `names` as a path's component. Only what the agent sent is read, never what came back: a generated file names this repository, and reading it is not reaching for it. A trial @@ -1202,12 +1259,16 @@ def reach(files, calls, workspace=None, temp=None, vendored=None): root = os.path.dirname(pen_of(workspace)) terms.append(os.path.basename(scoring_area(root)).lower()) outside = outside_pattern(workspace, temp) + + # A change task's fixture holds the build whole, its history and its + # databases among it, which its workspace was cleaned of. + fenced = fence_pattern(protected, names) hits = [] for tool, text in calls: lowered = text.lower() hits.extend({"tool": tool, "term": term, "call": text[:300]} for term in terms if term in lowered) - if outside is None: + if outside is None and fenced is None: continue # A call's input arrives as JSON, which doubles a Windows path's @@ -1215,7 +1276,8 @@ def reach(files, calls, workspace=None, temp=None, vendored=None): normal = lowered.replace("\\\\", "/").replace("\\", "/") hits.extend({"tool": tool, "term": match.group(0), "call": text[:300]} - for match in outside.finditer(normal)) + for pattern in (outside, fenced) if pattern is not None + for match in pattern.finditer(normal)) return {"transcripts": files, "hits": hits} @@ -1246,6 +1308,42 @@ def path_pattern(paths): "|".join(re.escape(form) for form in path_forms(paths)), PATH_END)) +def fenced_paths(paths): + """Each of `paths` as given and as resolved, and on Windows in lower + case too, for deny rules a case-sensitive match would otherwise miss.""" + forms = set() + for path in paths: + for form in (os.path.abspath(path), os.path.realpath(path)): + forms.add(form) + if os.name == "nt": + forms.add(form.lower()) + return sorted(forms) + + +def fence_pattern(paths, names): + """A pattern matching a path into any of `paths`, or naming any of + `names` as a whole path component however it is reached, as normalised + by `reach`; None where there is nothing to fence.""" + + # A relative path climbs out of the workspace however many levels the + # shell happens to be deep, so an archive's own name is matched wherever + # it stands as a component, and the directory's after a climb: a folder + # of that name inside the workspace, as `tests/fixtures`, is the trial's. + alternatives = [] + if paths: + alternatives.append("(?:%s)%s" % ("|".join( + re.escape(form) for form in path_forms(fenced_paths(paths))), + PATH_END)) + alternatives.append("\\.\\./(?:%s)%s" % ("|".join( + re.escape(os.path.basename(os.path.abspath(path)).lower()) + for path in sorted(set(paths))), PATH_END)) + if names: + alternatives.append("(? registered["k"]: + return ("--k %d is past round %s's registered K = %d for its %s task" + % (k, round_name, registered["k"], task)) + return None -def spec_problem(arms, spec_name, digest): +def prompt_problem(round_name, task, prompt): + """Why a task's prompt is not the one the named round registers, or + None.""" + registered = REGISTRATIONS[round_name]["tasks"][task]["prompt_sha256"] + digest = text_digest(prompt) + if digest != registered: + return ("the %s prompt is not the one round %s registers: sha256 %s, " + "registered %s" % (task, round_name, digest, registered)) + return None + + +def spec_problem(arms, spec_name, digest, round_name=None): """Why a run of these arms may not build from this spec, or None. - A run holding a round-5, round-5d or round-5e arm builds from the spec - round 5 registers, at the content it registers; any other run is not - checked here. + A run naming a round builds from the spec that round's entry registers. + A run naming none, holding a round-5, round-5d or round-5e arm, builds + from the spec round 5 registers; any other run is not checked here. """ + if round_name is not None: + spec = REGISTRATIONS[round_name]["spec"] + if spec_name != spec["name"]: + return ("round %s registers the %s spec, and this run names %s" + % (round_name, spec["name"], spec_name)) + if digest != spec["sha256"]: + return ("the %s spec is not the content round %s registers: " + "sha256 %s, registered %s" + % (spec_name, round_name, digest, spec["sha256"])) + return None if not set(arms) & set(ROUND5_ARMS + ROUND5D_ARMS + ROUND5E_ARMS): return None name, registered = ROUND5_SPEC @@ -1576,19 +1734,411 @@ def spec_problem(arms, spec_name, digest): % (name, spec_name)) if digest != registered: return ("the %s spec is not the content round 5 registers: sha256 %s, " - "registered %s" % (name, digest, registered)) + "registered %s; a round from 6 on is named with --round" + % (name, digest, registered)) + return None + + +def run_files(root): + """Every run record in a root, by path, in time order.""" + if not os.path.isdir(root): + return [] + return sorted(os.path.join(root, entry) for entry in os.listdir(root) + if entry.startswith("run-") and entry.endswith(".json")) + + +# What every trial record of a named round carries, so a record read on its +# own, copied or reused, still says which round, task, arm and block it was. +IDENTITY = ("round", "task", "arm", "block") + +# What a named round's run record says of the round as a whole, which any +# rewrite of the record keeps. +RUN_IDENTITY = ("round", "registration", "fixtures") + + +def identity_problem(root, round_name=None, digest=None): + """Why the run records in `root` do not fit a run of `round_name` under + the registration at `digest`, or None. With no round named, no record + may name one.""" + for file in run_files(root): + with io.open(file, encoding="utf-8") as handle: + run = json.load(handle) + named, base = run.get("round"), os.path.basename(file) + + # A header naming no round over trials that name one is a named + # round's record that lost its identity, as a copy written without + # it would be; read as the pilot's, it would let any run join it. + if named is None: + marked = [record for record in run.get("trials", []) + if record.get("round") is not None] + if marked: + return ("%s names no round, yet its trial %s names round %s" + % (base, name_of(marked[0]), marked[0]["round"])) + + # A root holds one round. A run naming none in a named round's root + # would be read under the pilot's rules, and the reverse would put a + # named round's trials beside records no registration covers. + if named is None and round_name is not None: + return ("%s names no round, so this root is not round %s's" + % (base, round_name)) + if named is not None and round_name is None: + return ("%s is round %s's, so a run in this root names it with " + "--round %s" % (base, named, named)) + if named is None: + continue + if named != round_name: + return ("%s is round %s's, and this run names round %s" + % (base, named, round_name)) + if run.get("registration") != digest: + return ("%s ran under round %s's registration at sha256 %s, and " + "the registration now reads %s" + % (base, named, run.get("registration"), digest)) + for record in run.get("trials", []): + missing = [key for key in IDENTITY if record.get(key) is None] + if missing or record["round"] != named: + return ("%s holds trial %s with %s, so it cannot be shown to " + "be round %s's" + % (base, name_of(record), + "no %s" % ", ".join(missing) if missing + else "round %s" % record["round"], named)) return None +def recorded_round(root): + """The round a root's run records name, and why they do not hold it + whole: (None, None) for records from before rounds were named.""" + named = None + for file in run_files(root): + with io.open(file, encoding="utf-8") as handle: + named = json.load(handle).get("round") + if named is not None: + break + if named is None: + return None, identity_problem(root) + if named not in REGISTRATIONS: + return named, ("the run records name round %s, which is not " + "registered" % named) + return named, identity_problem(root, named, + registration_digest(REGISTRATIONS[named])) + + +def owed_by_task(entry, records): + """The blocks each task of a registered round still owes, by task. + + A block is owed until every registered arm has a scorable trial of that + task in it. A change task counts whatever its arm's build trial did, + since it starts from a fixture and not from that build. + """ + owed = {} + for task, registered in sorted(entry["tasks"].items()): + done = {(record.get("arm"), record.get("trial")) for record in records + if record.get("task", "build") == task + and record.get("outcome") in SCORABLE} + owed[task] = [block for block in range(1, registered["k"] + 1) + if any((arm, block) not in done + for arm in entry["arms"])] + return owed + + +def manifest_path(entry): + """Where a round's fixture manifest is, beside this module.""" + return os.path.join(HERE, entry["tasks"]["change"]["fixtures"]["manifest"]) + + +def read_fixtures(entry, directory): + """The fixtures a round's change task starts from, each checked against + its tarball in `directory`, in the order the blocks take them.""" + path = manifest_path(entry) + try: + with io.open(path, encoding="utf-8") as handle: + listed = json.load(handle).get("fixtures") or [] + except (OSError, ValueError) as error: + raise TrialError("cannot read the fixture manifest %s: %s" + % (path, error)) + + # No fixture means no change task can start the same for every arm, and + # falling back to each arm's own build would mix the build into the change. + if not listed: + raise TrialError("the fixture manifest %s lists no fixture, so no " + "change task can start; a build is listed once it " + "qualifies" % path) + source = entry["tasks"]["change"]["fixtures"]["from"]["arm"] + fixtures = [] + for fixture in listed: + trial = fixture.get("trial") or "" + if split_name(trial)[0] != source: + raise TrialError("fixture %s is not a build of arm %s" + % (trial, source)) + + # The readings that qualified a build are what its change tasks are + # read against, so one listed without them has not qualified. + if not isinstance(fixture.get("baseline"), dict) \ + or not fixture["baseline"]: + raise TrialError("fixture %s carries no baseline readings, so it " + "has not qualified" % trial) + tarball = os.path.join(directory, "%s.tar" % trial) + if not os.path.isfile(tarball): + raise TrialError("fixture %s has no tarball at %s" + % (trial, tarball)) + digest = spec_digest(tarball) + if digest != fixture.get("sha256"): + raise TrialError("fixture %s's tarball %s has sha256 %s, and the " + "manifest lists %s" + % (trial, tarball, digest, fixture.get("sha256"))) + + # Read whole before any trial, so a fixture no change task could + # start from refuses the run rather than its trials one by one. + try: + with tarfile.open(tarball) as archive: + fixture_members(archive, tarball) + except (OSError, tarfile.TarError) as error: + raise TrialError("fixture %s's tarball %s cannot be read: %s" + % (trial, tarball, error)) + fixtures.append(dict(fixture, tarball=tarball)) + return sorted(fixtures, key=lambda fixture: split_name(fixture["trial"])[1]) + + +def fixture_for(fixtures, block): + """The fixture a block's change tasks start from: the block-th in + order, cycling when fewer qualified than the round has blocks.""" + return fixtures[(block - 1) % len(fixtures)] + + +def run_fixtures(options): + """A named round's change run's fixtures, checked, and what its run + record says of them: the manifest's hash, how many qualified, how many + distinct ones its blocks start from, and which each block takes.""" + entry = REGISTRATIONS[options.round] + if not getattr(options, "fixtures", None): + raise TrialError("round %s's change task starts from its fixtures; " + "name the directory holding their tarballs with " + "--fixtures" % options.round) + + # The fixtures' directory is fenced off from every change trial, so a + # run root inside it would read every trial as reaching past its own. + # Compared resolved and, on Windows, in either case, as the file system + # reads them. + fenced = os.path.normcase(os.path.realpath(options.fixtures)) + root = os.path.normcase(os.path.realpath( + getattr(options, "root", None) or os.sep)) + if root == fenced or root.startswith(fenced.rstrip(os.sep) + os.sep): + raise TrialError("the run root %s is inside the fixtures' directory " + "%s, which no trial may read" + % (options.root, options.fixtures)) + fixtures = read_fixtures(entry, options.fixtures) + blocks = {block: fixture_for(fixtures, block)["trial"] + for block in range(1, options.k + 1)} + return fixtures, {"manifest_sha256": spec_digest(manifest_path(entry)), + "qualified": len(fixtures), + "distinct": len(set(blocks.values())), + "blocks": {str(block): trial + for block, trial in blocks.items()}} + + +def fixtures_problem(root, summary): + """Why a named round's change run, taking its fixtures as `summary` + says, may not join the change runs already in `root`, or None.""" + + # The registration names the manifest only by its file, so a manifest + # edited between two runs of one round would start a block's arms from + # different builds; its content and each block's build must hold. + for file in run_files(root): + with io.open(file, encoding="utf-8") as handle: + run = json.load(handle) + if run.get("task") != "change": + continue + earlier, base = run.get("fixtures") or {}, os.path.basename(file) + if earlier.get("manifest_sha256") != summary["manifest_sha256"]: + return ("%s took its fixtures from a manifest at sha256 %s, and " + "the manifest now reads %s" + % (base, earlier.get("manifest_sha256"), + summary["manifest_sha256"])) + for block, trial in sorted(summary["blocks"].items()): + started = (earlier.get("blocks") or {}).get(block, trial) + if started != trial: + return ("%s started block %s from %s, and this run would " + "start it from %s" % (base, block, started, trial)) + return None + + +def round_records(root): + """Every trial record in a root's run records, in time order.""" + records = [] + for file in run_files(root): + with io.open(file, encoding="utf-8") as handle: + records.extend(json.load(handle).get("trials", [])) + return records + + +def registered_run(options, arms): + """Hold a run to the round it names and its root to that round; return + the identity its run record carries, None for a run naming no round.""" + round_name = getattr(options, "round", None) + if round_name is None: + problem = identity_problem(options.root) + if problem: + raise TrialError(problem) + return None + problem = round_problem(round_name, arms, options.k, options.task) + if problem: + raise TrialError(problem) + prompt = PROMPT if options.task == "build" else read_change_prompt() + digest = registration_digest(REGISTRATIONS[round_name]) + problem = (prompt_problem(round_name, options.task, prompt) + or spec_problem(arms, options.spec, + spec_digest(SPECS[options.spec]), round_name) + or identity_problem(options.root, round_name, digest)) + if problem: + raise TrialError(problem) + return {"round": round_name, "registration": digest} + + +# What a fixture's tree loses before an arm's change task starts from it: +# what its builder was told or read, its settings, its databases, its caches +# and environments, and its history. Each would hand every arm the build +# trial's context or state, and the arm's own context is installed after. +FIXTURE_DROPPED_DIRS = (".git", ".claude", "__pycache__", ".pytest_cache", + ".mypy_cache", ".ruff_cache", ".hypothesis", ".tox", + ".nox", ".cache", "node_modules", "htmlcov", ".vscode", + ".idea") +FIXTURE_DROPPED_FILES = ("claude.md", "claude.local.md", "agents.md", + ".coverage") +FIXTURE_DROPPED_SUFFIXES = (".sqlite", ".sqlite3", ".db", ".pyc", ".pyo", + ".jsonl") + + +def kept_from_fixture(relative, environments): + """Whether a path in a fixture's tree, relative to its top, is code or a + test the change task starts from; `environments` names the virtualenvs + in the tree.""" + parts = relative.split("/") + lowered = [part.lower() for part in parts] + if any(part in FIXTURE_DROPPED_DIRS or part.endswith(".egg-info") + for part in lowered): + return False + if lowered[:2] == VENDORED["into"].lower().split("/"): + return False + if any("/".join(parts[:index]) in environments + for index in range(1, len(parts) + 1)): + return False + + # The round's spec replaces the one the build was given. + if lowered == ["spec.md"]: + return False + return not (lowered[-1] in FIXTURE_DROPPED_FILES + or lowered[-1].endswith(FIXTURE_DROPPED_SUFFIXES)) + + +def link_target(member): + """Where a link member points, as a path relative to the tree's top, or + None where it points out of the tree or at an absolute path.""" + if member.islnk(): + target = posixpath.normpath(member.linkname) + elif member.linkname.startswith("/") or member.linkname[1:2] == ":": + return None + else: + target = posixpath.normpath(posixpath.join( + posixpath.dirname(member.name), member.linkname)) + return None if target == ".." or target.startswith("../") else target + + +def fixture_members(archive, tarball): + """The members of a fixture's tree its change tasks keep, renamed to + the tree's top; raises where the tree cannot be kept whole.""" + members = archive.getmembers() + tops = {member.name.split("/")[0] for member in members} + if len(tops) != 1: + raise TrialError("%s does not hold one directory: %s" + % (tarball, ", ".join(sorted(tops)))) + prefix = tops.pop() + "/" + inside = [member for member in members + if member.name.startswith(prefix) + and (member.isfile() or member.isdir() or member.issym() + or member.islnk())] + for member in inside: + member.name = member.name[len(prefix):] + if member.islnk() and member.linkname.startswith(prefix): + member.linkname = member.linkname[len(prefix):] + + # A virtualenv is known by the file every one carries at its root. + environments = {member.name.rpartition("/")[0] for member in inside + if member.isfile() + and member.name.rpartition("/")[2] == "pyvenv.cfg"} + environments.discard("") + kept = [member for member in inside + if kept_from_fixture(member.name, environments)] + + # A link the build froze stays where what it names stays too. Dropped, + # it would leave code or tests reached through it missing; kept while + # naming something outside what stays, it would dangle, or hand the + # trial what its workspace was cleaned of. Either makes the fixture + # unusable, which is said rather than mended. + names = {member.name for member in kept} + for member in kept: + if (member.issym() or member.islnk()) \ + and link_target(member) not in names: + raise TrialError("fixture %s is unusable: %s links to %s, " + "outside the code and tests its change tasks " + "keep" % (tarball, member.name, member.linkname)) + return kept + + +def unpack_fixture(tarball, target): + """Unpack the code and tests of a fixture's tree into `target`.""" + with tarfile.open(tarball) as archive: + kept = fixture_members(archive, tarball) + archive.extractall(target, members=kept, filter="data") + + +def prepare_fixture_workspace(arm, block, root, fixture, spec): + """Lay out an arm's change task of a block on its fixture: the build's + code and tests, the round's spec, the arm's context, one commit. + + Returns the workspace, its starting commit and what was vendored. + """ + if arm not in ARMS: + raise TrialError("unknown arm %r; the arms are %s" + % (arm, ", ".join(sorted(ARMS)))) + workspace = trial_workspace(root, "change-%s" % trial_name(arm, block)) + if os.path.exists(pen_of(workspace)): + raise TrialError("workspace %s already exists; a trial never reuses " + "one" % workspace) + + # Checked again here, as the tarball is the one unpacked, so a fixture + # replaced after the run started refuses the trials after it. + digest = spec_digest(fixture["tarball"]) + if digest != fixture["sha256"]: + raise TrialError("fixture %s's tarball %s has sha256 %s, and the " + "manifest lists %s" % (fixture["trial"], + fixture["tarball"], digest, + fixture["sha256"])) + os.makedirs(workspace) + try: + unpack_fixture(fixture["tarball"], workspace) + except TrialError: + remove_tree(pen_of(workspace)) + raise + except (OSError, tarfile.TarError) as error: + remove_tree(pen_of(workspace)) + raise TrialError("could not unpack %s: %s" + % (fixture["tarball"], error)) + shutil.copyfile(spec, os.path.join(workspace, "SPEC.md")) + vendored = install_arm(workspace, arm) + commit_start(workspace, "start: change task on %s, %s arm %s" + % (fixture["trial"], ARMS[arm]["label"], arm)) + return workspace, git(workspace, "rev-parse", "HEAD"), vendored + + def run_trial(arm, trial, root, home, options): """Run one build trial and return its record.""" spec_name = getattr(options, "spec", "normal") spec = SPECS[spec_name] + round_name = getattr(options, "round", None) # Read again for every trial, so an edit made after the run started # refuses the trials after it rather than building them from a new spec. arms = getattr(options, "arm_list", ()) - problem = spec_problem(arms, spec_name, spec_digest(spec)) + problem = spec_problem(arms, spec_name, spec_digest(spec), round_name) if problem: raise TrialError(problem) workspace, vendored = prepare_workspace(arm, trial, root, spec) @@ -1597,13 +2147,15 @@ def run_trial(arm, trial, root, home, options): # check above and the copy, so the copy is what is checked and recorded. # A refused workspace is removed, so the trial's slot stays free. digest = spec_digest(os.path.join(workspace, "SPEC.md")) - problem = spec_problem(arms, spec_name, digest) + problem = spec_problem(arms, spec_name, digest, round_name) if problem: remove_tree(pen_of(workspace)) raise TrialError(problem) record = {"arm": arm, "label": ARMS[arm]["label"], "trial": trial, "task": "build", "vendored": vendored, "spec": {"file": os.path.basename(spec), "sha256": digest}} + if round_name is not None: + record.update(round=round_name, block=trial) return run_agent(workspace, trial_name(arm, trial), PROMPT, record, root, home, options) @@ -1619,6 +2171,46 @@ def run_change_trial(arm, trial, root, home, options, build): read_change_prompt(), record, root, home, options) +def run_fixture_change_trial(arm, block, root, home, options, fixture): + """Run one registered round's change task on its block's fixture; return + its record.""" + round_name = options.round + spec_name = REGISTRATIONS[round_name]["spec"]["name"] + spec = SPECS[spec_name] + prompt = read_change_prompt() + + # Both read again for every trial, as a build trial's spec is. + problem = (prompt_problem(round_name, "change", prompt) + or spec_problem(options.arm_list, spec_name, spec_digest(spec), + round_name)) + if problem: + raise TrialError(problem) + workspace, base, vendored = prepare_fixture_workspace(arm, block, root, + fixture, spec) + digest = spec_digest(os.path.join(workspace, "SPEC.md")) + problem = spec_problem(options.arm_list, spec_name, digest, round_name) + if problem: + remove_tree(pen_of(workspace)) + raise TrialError(problem) + record = {"arm": arm, "label": ARMS[arm]["label"], "trial": block, + "block": block, "round": round_name, "task": "change", + "base": base, "vendored": vendored, + "fixture": {key: fixture[key] + for key in ("trial", "sha256", "tarball")}, + + # The fixtures' directory, which the trial's deny rules and + # every scan of its transcript fence off, and its archives' + # names, which a relative path into it would carry. + "protected": fenced_paths([os.path.dirname( + fixture["tarball"])]), + "protected_names": list(getattr(options, "fixture_names", ()) + or [os.path.basename( + fixture["tarball"])]), + "spec": {"file": os.path.basename(spec), "sha256": digest}} + return run_agent(workspace, "change-%s" % trial_name(arm, block), prompt, + record, root, home, options) + + # The endings a trial is scored on. A blocked trial was voided and its re-run # carries the score; a refused one never started. SCORABLE = ("completed", "budget", "timeout") @@ -1759,7 +2351,8 @@ def run_agent(workspace, name, prompt, record, root, home, options): """ assert_no_ambient_context(workspace, home) argv = agent_command(home, options.model, options.effort, options.budget, - trial_settings(home, root, workspace)) + trial_settings(home, root, workspace, + record.get("protected", ()))) record.update({ "workspace": workspace, "prompt": prompt, @@ -1812,7 +2405,9 @@ def run_agent(workspace, name, prompt, record, root, home, options): record["elapsed_s"] = round(time.monotonic() - started, 1) record.update(contain(workspace, temp, home, shared, since, - record.get("vendored"))) + record.get("vendored"), + record.get("protected", ()), + record.get("protected_names", ()))) record.update(reached(record)) record["frozen"] = freeze(workspace, root, name) if record["outcome"] in VOIDING: @@ -1867,10 +2462,11 @@ def pending_trials(arms, k, start=None): def write_run(run_file, started_at, records, task="build", prompt=PROMPT, - arms=(), k=None): + arms=(), k=None, identity=None): """Rewrite the run record with every trial so far. The run's arms and its K are written from the start, so a reader knows the whole run - before its first trial of each arm is in.""" + before its first trial of each arm is in. `identity` names the round + and its registration's digest, for a run that names a round.""" # Written to a sibling and swapped in, so a run killed mid-write leaves # the previous record whole rather than half of a new one. @@ -1881,6 +2477,15 @@ def write_run(run_file, started_at, records, task="build", prompt=PROMPT, header["arms"] = list(arms) if k is not None: header["k"] = k + + # Every trial record of a named round carries its identity, the running + # and refused ones too, so none reads as a record of no round. + if identity: + header.update(identity) + for record in records: + record.setdefault("round", identity["round"]) + record.setdefault("task", task) + record.setdefault("block", record.get("trial")) with io.open(partial, "w", encoding="utf-8") as handle: json.dump(dict(header, trials=records), handle, indent=2) os.replace(partial, run_file) @@ -2061,10 +2666,11 @@ def recover(root, home, table=None): records[index] = dict(record, **ending) changed = True if changed: + identity = {key: run[key] for key in RUN_IDENTITY if key in run} write_run(run_file, datetime.datetime.fromisoformat( run["started_at"]), records, run.get("task", "build"), run.get("prompt", PROMPT), run.get("arms") or (), - run.get("k")) + run.get("k"), identity or None) return voided @@ -3697,6 +4303,506 @@ def edited_in_flight(*args, **kwargs): return checks +def registration_checks(): + """A run naming a round is held to its entry: its arms, K, spec and + prompts; its root holds that round alone, every record naming it.""" + entry = REGISTRATIONS["C1"] + change = read_change_prompt() + checks = [ + ("C1 pins SPEC.md, both prompts and its fixtures by content", + entry["spec"]["sha256"] == spec_digest(SPEC) == ROUND6_SPEC[1] + and entry["tasks"]["build"]["prompt_sha256"] == text_digest(PROMPT) + and entry["tasks"]["change"]["prompt_sha256"] == text_digest(change) + and os.path.isfile(manifest_path(entry))), + ("an unknown round is refused", + round_problem("C9", ["none"], 3, "build") is not None + and round_problem("C1", ["none"], 3, "build") is None), + ("an arm the round does not register is refused", + round_problem("C1", ["none", "hand"], 3, "build") is not None + and round_problem("C1", ["none", "lazyskills"], 3, "change") + is None), + ("a K past the round's registered K is refused", + round_problem("C1", ["none"], 16, "change") is not None + and round_problem("C1", ["none"], 15, "change") is None), + + # C1 runs pilot arms' names on round 6's spec, which the pilot's + # check, going by those names, would refuse. + ("a C1 run reads its spec from its entry, not its arms' names", + spec_problem(["inline", "lazyref"], "normal", ROUND6_SPEC[1], "C1") + is None + and spec_problem(["inline"], "normal", ROUND5_SPEC[1], "C1") + is not None + and spec_problem(["inline"], "thin", ROUND6_SPEC[1], "C1") + is not None), + ("a build or change prompt the round does not pin is refused", + prompt_problem("C1", "build", PROMPT) is None + and prompt_problem("C1", "build", PROMPT + " ") is not None + and prompt_problem("C1", "change", change) is None + and prompt_problem("C1", "change", change + " ") is not None), + ] + + scratch = tempfile.mkdtemp(prefix="efficacy-registration-") + digest = registration_digest(entry) + stamp = datetime.datetime.now().astimezone() + + def planted(name, header, trials): + root = os.path.join(scratch, name) + os.makedirs(root, exist_ok=True) + with io.open(os.path.join(root, "run-%d.json" % len(os.listdir(root))), + "w", encoding="utf-8") as handle: + json.dump(dict(header, trials=trials), handle) + return root + + whole = {"round": "C1", "task": "build", "arm": "none", "block": 1, + "trial": 1, "outcome": "completed"} + legacy = planted("legacy", {}, [{"arm": "none", "trial": 1}]) + other = planted("other", {"round": "C2", "registration": digest}, + [dict(whole, round="C2")]) + stale = planted("stale", {"round": "C1", "registration": "0" * 64}, + [whole]) + bare = planted("bare", {"round": "C1", "registration": digest}, + [dict(whole, block=None)]) + good = planted("good", {"round": "C1", "registration": digest}, [whole]) + unheaded = planted("unheaded", {}, [whole]) + checks += [ + ("a root holding another round's or registration's runs is refused", + identity_problem(other, "C1", digest) is not None + and identity_problem(stale, "C1", digest) is not None + and identity_problem(good, "C1", digest) is None), + ("a named round and records naming none never share a root", + identity_problem(legacy, "C1", digest) is not None + and "--round C1" in (identity_problem(good) or "") + and identity_problem(legacy) is None), + ("a named round's trial record missing its identity is refused", + identity_problem(bare, "C1", digest) is not None + and recorded_round(bare)[1] is not None + and recorded_round(good) == ("C1", None) + and recorded_round(legacy) == (None, None)), + ("a run whose trials name a round under a header naming none is " + "refused", + identity_problem(unheaded) is not None + and identity_problem(unheaded, "C1", digest) is not None + and recorded_round(unheaded)[1] is not None), + ] + written = os.path.join(scratch, "written", "run-1.json") + os.makedirs(os.path.dirname(written)) + write_run(written, stamp, [{"arm": "none", "trial": 2, + "outcome": "refused"}], + "change", change, ["none"], 2, + {"round": "C1", "registration": digest}) + with io.open(written, encoding="utf-8") as handle: + run = json.load(handle) + checks.append(("every trial record of a named round names its round, " + "task, arm and block", + run["round"] == "C1" and run["registration"] == digest + and {key: run["trials"][0].get(key) for key in IDENTITY} + == {"round": "C1", "task": "change", "arm": "none", + "block": 2} + and identity_problem(os.path.dirname(written), "C1", + digest) is None)) + + # A harness that died mid-trial leaves its run record for the next run + # to rewrite, which keeps the round it names. + recovered = os.path.join(scratch, "recovered") + os.makedirs(recovered) + summary = {"manifest_sha256": "1" * 64, "blocks": {"1": "none-2"}} + write_run(os.path.join(recovered, "run-1.json"), stamp, + [dict(in_flight("none", 1), harness_pid=4242)], "change", + change, ["none"], 1, + {"round": "C1", "registration": digest, "fixtures": summary}) + recover(recovered, os.path.join(scratch, "home"), []) + with io.open(os.path.join(recovered, "run-1.json"), + encoding="utf-8") as handle: + run = json.load(handle) + checks.append(("recovery keeps a named round's identity in its run " + "record", + run["trials"][0]["outcome"] == "interrupted" + and run.get("fixtures") == summary + and identity_problem(recovered, "C1", digest) is None)) + + # A round of two tasks, two arms and two blocks: the change tasks come + # after the builds, and one build lost leaves its change task counted. + small = {"arms": ["none", "inline"], + "tasks": {"build": {"k": 2}, "change": {"k": 2}}} + builds = [{"arm": arm, "trial": block, "task": "build", + "outcome": "completed"} for arm in small["arms"] + for block in (1, 2)] + changes = [dict(record, task="change") for record in builds] + failed = [dict(record, outcome="blocked") + if (record["arm"], record["trial"]) == ("inline", 2) else record + for record in builds] + checks += [ + ("a round of two tasks is complete only with both at K for every arm", + owed_by_task(small, builds) == {"build": [], "change": [1, 2]} + and owed_by_task(small, builds + changes[:3]) + == {"build": [], "change": [2]} + and owed_by_task(small, builds + changes) + == {"build": [], "change": []}), + ("a change task counts though its arm's build trial failed", + owed_by_task(small, failed + changes) + == {"build": [2], "change": []}), + ] + try: + checks += fixture_checks(scratch) + finally: + REGISTRATIONS.pop("T1", None) + PINNED_CLI["path"] = None + remove_tree(scratch) + return checks + + +def fixture_checks(scratch): + """A named round's change task starts every arm of a block from one + fixture whose hash matches, cleaned of what its builder was given.""" + entry = json.loads(json.dumps(REGISTRATIONS["C1"])) + manifest = os.path.join(scratch, "change-fixtures.json") + entry["tasks"]["change"]["fixtures"]["manifest"] = manifest + REGISTRATIONS["T1"] = entry + + # One build, as a `none` trial leaves it: its code and tests, and beside + # them all a change task must not inherit. + build = os.path.join(scratch, "build") + planted = { + "tariff/app.py": "built = True\n", + "tests/test_app.py": "def test_built():\n assert True\n", + "pyproject.toml": "[project]\nname = 'tariff'\n", + ".gitignore": "*.db\n", + "CLAUDE.md": "inherited\n", "AGENTS.md": "inherited\n", + "tariff/CLAUDE.md": "inherited\n", + ".claude/settings.json": "{}\n", + ".claude/skills/inherited/SKILL.md": "---\nname: inherited\n---\n", + "docs/solid-ai-templates/templates/base.md": "vendored\n", + ".venv312/pyvenv.cfg": "home = x\n", + ".venv312/Lib/site-packages/thing.py": "x = 1\n", + "tariff/__pycache__/app.cpython-312.pyc": "", + ".pytest_cache/README.md": "cache\n", + "tariff.egg-info/PKG-INFO": "Name: tariff\n", + "data.sqlite": "", "tariff/app.db": "", "session.jsonl": "{}\n", + "SPEC.md": "the build's own spec\n", + } + for relative, text in planted.items(): + path = os.path.join(build, *relative.split("/")) + os.makedirs(os.path.dirname(path), exist_ok=True) + with io.open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + git(build, "init", "-q") + commit_start(build, "build") + tarballs = os.path.join(scratch, "fixtures") + os.makedirs(tarballs) + hashes = {} + for name in ("none-7", "none-2", "none-11"): + hashes[name] = spec_digest(freeze(build, tarballs, name)["tarball"]) + + def listing_as(fixtures): + with io.open(manifest, "w", encoding="utf-8") as handle: + json.dump({"fixtures": fixtures}, handle) + + def refused(*args): + try: + read_fixtures(*args) + return False + except TrialError: + return True + + listed = [{"trial": name, "sha256": hashes[name], + "baseline": {"build_suite": 1.0}} for name in hashes] + listing_as([]) + checks = [("an empty fixture manifest refuses a named round's change " + "task", refused(entry, tarballs))] + listing_as([dict(listed[0], sha256="0" * 64)] + listed[1:]) + mismatched = refused(entry, tarballs) + listing_as([dict(listed[0], baseline={})] + listed[1:]) + checks.append(("a fixture listed without its baseline readings is " + "refused", refused(entry, tarballs))) + listing_as(listed) + fixtures = read_fixtures(entry, tarballs) + order = [fixture_for(fixtures, block)["trial"] for block in range(1, 5)] + checks.append(("block b starts from the b-th qualifying build, ascending, " + "cycling", order == ["none-2", "none-7", "none-11", + "none-2"])) + import argparse as _argparse + two = run_fixtures(_argparse.Namespace(round="T1", fixtures=tarballs, k=2)) + five = run_fixtures(_argparse.Namespace(round="T1", fixtures=tarballs, + k=5)) + checks.append(("a named round's change run records how many distinct " + "fixtures its blocks take", + two[1]["distinct"] == 2 and two[1]["qualified"] == 3 + and five[1]["distinct"] == 3 + and five[1]["blocks"]["4"] == "none-2")) + + root = os.path.join(scratch, "root") + os.makedirs(root) + first = fixtures[0] + prepared = {arm: prepare_fixture_workspace(arm, 1, root, first, SPEC) + for arm in ("none", "inline", "skills")} + files = {arm: git(workspace, "ls-files").splitlines() + for arm, (workspace, _, _) in prepared.items()} + inline = prepared["inline"][0] + skills = os.path.join(prepared["skills"][0], *SKILLS_INTO.split("/")) + + def read(path): + try: + with io.open(path, "rb") as handle: + return handle.read() + except OSError: + return None + + kept = ("tariff/app.py", "tests/test_app.py", "pyproject.toml", + ".gitignore") + dropped = [relative for relative in planted + if relative not in kept + ("CLAUDE.md", "SPEC.md")] + checks.append(("a change workspace keeps its fixture's code and tests", + all(os.path.isfile(os.path.join(inline, *path.split("/"))) + for path in kept))) + checks.append(("a change workspace drops the fixture's instructions, " + "settings, databases, caches, environments and history", + not any(os.path.exists(os.path.join(workspace, + *path.split("/"))) + for workspace, _, _ in prepared.values() + for path in dropped + [".venv312", "__pycache__"]) + and not os.path.exists(os.path.join( + prepared["none"][0], "CLAUDE.md")) + and all(git(workspace, "rev-list", "--count", "HEAD") + == "1" for workspace, _, _ in prepared.values()))) + checks.append(("a change workspace carries the round's spec and only its " + "arm's context", + read(os.path.join(inline, "SPEC.md")) == read(SPEC) + and read(os.path.join(inline, "CLAUDE.md")) + == read(os.path.join(ARMS_DIR, ARMS["inline"]["context"])) + and sorted(os.listdir(skills)) == sorted(os.listdir( + os.path.join(ARMS_DIR, ARMS["skills"]["skills"]))))) + checks.append(("a change workspace starts from one commit, with nothing " + "uncommitted", + all(git(workspace, "status", "--porcelain") == "" + and git(workspace, "rev-parse", "HEAD") == base + for workspace, base, _ in prepared.values()))) + checks.append(("every arm's change workspace of a block holds the same " + "code", + files["none"] == [path for path in files["inline"] + if path != "CLAUDE.md"] + == [path for path in files["skills"] + if path != "CLAUDE.md"])) + + # Replaced after the run checked it, the tarball refuses its trial. + replaced = os.path.join(scratch, "replaced.tar") + shutil.copyfile(first["tarball"], replaced) + with io.open(replaced, "ab") as handle: + handle.write(b"\0" * 1024) + try: + prepare_fixture_workspace("none", 2, root, + dict(first, tarball=replaced), SPEC) + swapped = False + except TrialError: + swapped = not os.path.exists(os.path.join(root, "change-none-2")) + checks.append(("a fixture whose tarball differs from its listed hash is " + "refused, at the start and at each trial", + mismatched and swapped)) + checks += link_checks(scratch, root, entry, listing_as, refused) + listing_as(listed) + return checks + fixture_run_checks(scratch, tarballs) + + +def link_checks(scratch, root, entry, listing_as, refused): + """A fixture's links stay where what they name stays, and one naming + anything else makes the fixture unusable, at the start and at a trial.""" + linked = os.path.join(scratch, "linked") + os.makedirs(linked) + + def plant(name, links): + path = os.path.join(linked, name + ".tar") + with tarfile.open(path, "w") as archive: + for relative, data in (("tariff/app.py", b"built = True\n"), + ("tests/test_app.py", b"x = 1\n"), + (".venv/pyvenv.cfg", b"home = x\n")): + info = tarfile.TarInfo("%s/%s" % (name, relative)) + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + for relative, kind, target in links: + info = tarfile.TarInfo("%s/%s" % (name, relative)) + info.type, info.linkname = kind, target + archive.addfile(info) + return {"trial": name, "sha256": spec_digest(path), "tarball": path, + "baseline": {"build_suite": 1.0}} + + # A symbolic link and a hard link to code and tests that stay. + whole = plant("none-4", [("tariff/alias.py", tarfile.SYMTYPE, "app.py"), + ("tests/again.py", tarfile.LNKTYPE, + "none-4/tests/test_app.py")]) + try: + workspace, _, _ = prepare_fixture_workspace("none", 4, root, whole, + SPEC) + with io.open(os.path.join(workspace, "tariff", "alias.py"), + encoding="utf-8") as handle: + alias = handle.read() + with io.open(os.path.join(workspace, "tests", "again.py"), + encoding="utf-8") as handle: + again = handle.read() + kept = alias == "built = True\n" and again == "x = 1\n" + except (TrialError, OSError): + kept = False + + # A link out of the tree, an absolute one, and one into what the + # cleaning drops: each fixture is unusable, before a trial and at one. + refusals = [] + for block, target in ((5, "../../outside.py"), (6, "/etc/passwd"), + (7, "../.venv/pyvenv.cfg")): + bad = plant("none-%d" % block, + [("tariff/out.py", tarfile.SYMTYPE, target)]) + listing_as([{key: bad[key] + for key in ("trial", "sha256", "baseline")}]) + try: + prepare_fixture_workspace("none", block, root, bad, SPEC) + at_trial = False + except TrialError as error: + at_trial = ("unusable" in str(error) and not os.path.exists( + os.path.join(root, "change-none-%d" % block))) + refusals.append(at_trial and refused(entry, linked)) + return [("a fixture's links stay where what they name stays", + kept), + ("a fixture linking outside what its change tasks keep is " + "unusable, at the start and at a trial", refusals == [True] * 3)] + + +def fenced_off(scratch, tarballs, trials, denied): + """Whether a named round's change trials fence off their fixtures' + directory: in the record, the deny rules and the transcript scan, and + with no run root inside it.""" + import argparse as _argparse + + fenced = os.path.abspath(tarballs) + workspace = trial_workspace(os.path.join(scratch, "fenced-root"), + "change-none-1") + tarball = os.path.join(fenced, "none-2.tar") + names = trials[0].get("protected_names") if trials else [] + + # Named absolutely, in Git Bash's form, and climbed to relatively from + # wherever the shell stands; a name that only contains an archive's, or + # a workspace's own fixtures folder, is not the fixtures' directory. + calls = [("Bash", "tar xf %s" % tarball), + ("Bash", "ls %s" % "/".join(path_forms([fenced])[:1])), + ("Bash", "tar xf ../../../somewhere/none-2.tar"), + ("Bash", 'cat "./none-7.tar"'), + ("Bash", "ls ../../%s/" % os.path.basename(fenced))] + clean = [("Bash", "cat none-2.tar.bak xnone-2.tar"), + ("Bash", "cat tests/fixtures/seed.json")] + protected = trials[0].get("protected", ()) if trials else () + flagged = [bool(reach(["planted.jsonl"], [call], workspace, None, None, + protected, names)["hits"]) + for call in calls + clean] + bare = reach(["planted.jsonl"], calls, workspace, None)["hits"] + nested = [] + roots = [os.path.join(tarballs, "root")] + if os.name == "nt": + roots.append(os.path.join(tarballs.upper(), "root")) + for root in roots: + try: + run_fixtures(_argparse.Namespace(round="T1", fixtures=tarballs, + k=1, root=root)) + nested.append(False) + except TrialError: + nested.append(True) + lower = ([] if os.name != "nt" + else ["Read(%s/**)" % rule_path(fenced.lower())]) + return (all(fenced in trial.get("protected", ()) + and {"none-2.tar", "none-7.tar", "none-11.tar"} + == set(trial.get("protected_names", ())) + for trial in trials) + and all(rule in denied + for rule in ["Read(%s/**)" % rule_path(fenced)] + lower) + and flagged == [True] * len(calls) + [False] * len(clean) + and bare == [] and all(nested)) + + +def fixture_run_checks(scratch, tarballs): + """A named round's change run needs no build trial, and its root takes + no run naming another round or none; the CLI is a stand-in.""" + stand_in = os.path.join(scratch, "bin", + "claude.cmd" if os.name == "nt" else "claude") + os.makedirs(os.path.dirname(stand_in)) + with io.open(stand_in, "w", encoding="utf-8") as handle: + handle.write("@echo off\r\necho 0.0.1 (stand-in)\r\n" + if os.name == "nt" + else '#!/bin/sh\necho "0.0.1 (stand-in)"\n') + os.chmod(stand_in, 0o755) + root = os.path.join(scratch, "change-root") + argv = ["--root", root, "--round", "T1", "--task", "change", "--arms", + "none,inline", "--k", "1", "--fixtures", tarballs, "--cli", + stand_in, "--dry-run"] + saved = {key: os.environ.get(key) for key in ("HOME", "USERPROFILE")} + os.environ["HOME"] = os.environ["USERPROFILE"] = os.path.join(scratch, + "me") + try: + with contextlib.redirect_stdout(io.StringIO()): + code = main(argv) + dry = dry_run_area(root) + runs = run_files(dry) + run = {} + if runs: + with io.open(runs[0], encoding="utf-8") as handle: + run = json.load(handle) + trials = run.get("trials", []) + prepared = os.path.isdir(os.path.join(dry, "change-inline-1")) + settings = os.path.join(dry, "home", "settings-change-inline-1.json") + with io.open(settings, encoding="utf-8") as handle: + denied = json.load(handle)["permissions"]["deny"] + + # The same round's earlier change run, planted beside this one with + # its manifest edited, and with its block 1 started from another + # build: each refuses the run. + drifted = [] + for name, change in ( + ("manifest", {"manifest_sha256": "0" * 64}), + ("block", {"blocks": {"1": "none-7"}})): + earlier = os.path.join(scratch, "drift-" + name) + os.makedirs(earlier) + with io.open(os.path.join(earlier, "run-1.json"), "w", + encoding="utf-8") as handle: + json.dump(dict(run, fixtures=dict(run.get("fixtures") or {}, + **change)), handle) + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + drifted.append((main(["--root", earlier] + argv[2:]), + printed.getvalue())) + os.makedirs(root, exist_ok=True) + planted = os.path.join(root, "run-planted.json") + write_run(planted, datetime.datetime.now().astimezone(), []) + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + mixed = main(argv) + finally: + for key, value in saved.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + return [ + ("a named round's change task needs no build trial of its arm", + code == 0 and prepared + and [trial.get("outcome") for trial in trials] + == ["dry-run", "dry-run"]), + ("a named round's run record names its round, registration and " + "fixtures", + run.get("round") == "T1" + and run.get("registration") + == registration_digest(REGISTRATIONS["T1"]) + and (run.get("fixtures") or {}).get("distinct") == 1 + and all(trial.get("fixture", {}).get("trial") == "none-2" + and trial.get("block") == 1 for trial in trials)), + ("a named round's run refuses a root whose records name none", + mixed == 2 and "names no round" in printed.getvalue()), + ("a change trial may neither read nor name its fixtures' directory", + fenced_off(scratch, tarballs, trials, denied)), + ("a change run whose manifest or block mapping differs from the " + "root's earlier change runs is refused", + [code for code, _ in drifted] == [2, 2] + and "the manifest now reads" in drifted[0][1] + and "started block 1 from none-7" in drifted[1][1] + and fixtures_problem(dry, dict(run.get("fixtures") or {}, + blocks={"1": "none-2", + "2": "none-7"})) is None), + ] + + def self_test(): """Prove the naming, isolation, outcome, resume, change and vendoring rules before a trial.""" @@ -3710,7 +4816,7 @@ def self_test(): + claim_checks() + leftover_checks() + reach_checks() + outside_checks() + vendor_checks() + denial_checks() + kill_checks() + recover_checks() + round5_checks() + spec_checks() - + pen_checks()) + + registration_checks() + pen_checks()) for label, ok in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED")) passed = sum(1 for _, ok in checks if ok) @@ -3735,13 +4841,22 @@ def parse_args(argv): % TEMPLATES_ENV) parser.add_argument("--task", choices=("build", "change"), default="build", - help="run the build trials, or the change task on " - "each scorable build trial") + help="run the build trials, or the change task: on " + "each scorable build trial, or for a named " + "round on its block's fixture") + parser.add_argument("--round", + help="the registered round the run belongs to, as " + "C1, from %s; the run is held to its entry" + % ", ".join(sorted(REGISTRATIONS))) + parser.add_argument("--fixtures", + help="the directory holding the fixtures' tarballs, " + "for a named round's change task") parser.add_argument("--arms", help="which arms to run, as words separated by " "commas, from %s; their order is block 1's. " "Required for a run, so a run names the arms " - "it holds" % ",".join(ARMS)) + "it holds, unless it names a round, whose arms " + "it then runs" % ",".join(ARMS)) parser.add_argument("--k", type=int, default=K_DEFAULT, help="trials per arm (default %d; at most %d, the K a " "round registers)" % (K_DEFAULT, ROUND5_K)) @@ -3820,6 +4935,8 @@ def main(argv): arms = [arm.strip() for arm in (options.arms or "").split(",") if arm.strip()] + if not arms and options.round in REGISTRATIONS: + arms = list(REGISTRATIONS[options.round]["arms"]) unknown = [arm for arm in arms if arm not in ARMS] if not arms or unknown: print("--arms names %s; the arms are %s" @@ -3828,11 +4945,12 @@ def main(argv): return 2 try: pending = pending_trials(arms, options.k, options.start) + identity = registered_run(options, arms) except TrialError as error: print("refused: %s" % error) return 2 options.arm_list = arms - if options.task == "build": + if options.task == "build" and identity is None: problem = spec_problem(arms, options.spec, spec_digest(SPECS[options.spec])) if problem: @@ -3852,11 +4970,22 @@ def main(argv): # The change task needs its prompt and its build trials before anything # runs, so a design or a run root that cannot supply them refuses here. - builds, prompt = {}, PROMPT + # A named round's change task needs its fixtures instead, every one + # matching its hash, and none of its arm's build trials. + builds, fixtures, prompt = {}, [], PROMPT if options.task == "change": try: prompt = read_change_prompt() - builds = scorable_trials(options.root, task="build") + if identity is None: + builds = scorable_trials(options.root, task="build") + else: + fixtures, identity["fixtures"] = run_fixtures(options) + options.fixture_names = sorted( + os.path.basename(fixture["tarball"]) + for fixture in fixtures) + problem = fixtures_problem(options.root, identity["fixtures"]) + if problem: + raise TrialError(problem) except TrialError as error: print("refused: %s" % error) return 2 @@ -3906,6 +5035,11 @@ def runner(arm, trial): if options.task == "build": with credential_watch(home): return run_trial(arm, trial, work, home, options) + if identity is not None: + with credential_watch(home): + return run_fixture_change_trial(arm, trial, work, home, + options, + fixture_for(fixtures, trial)) name = trial_name(arm, trial) if name not in builds: raise TrialError("build trial %s has no scorable outcome, so it " @@ -3916,7 +5050,7 @@ def runner(arm, trial): def write(): write_run(run_file, started_at, records, options.task, prompt, - arms, options.k) + arms, options.k, identity) def probe(): refresh_credentials(home) @@ -3935,6 +5069,15 @@ def wait(): write() print("\nRun record: %s" % run_file) + # A round of two tasks is complete only with both at K for every arm. + if identity is not None: + owed = owed_by_task(REGISTRATIONS[options.round], + round_records(work)) + print("round %s: %s" % (options.round, "; ".join( + "%s owes %s" % (task, "nothing" if not blocks else + "blocks %s" % ", ".join(map(str, blocks))) + for task, blocks in owed.items()))) + refused = sum(1 for r in records if r["outcome"] == "refused") blocked = sum(1 for r in records if r["outcome"] == "blocked") lost = sum(1 for r in records if r["outcome"] == "reached") diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 15e05c5..9e2acb1 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -39,12 +39,13 @@ import archive # noqa: E402 import lib # noqa: E402 from generate_arm import RECORDED, record_path # noqa: E402 -from harness import (ARMS, ARMS_DIR, PROMPT, ROUND5_ARMS, # noqa: E402 - ROUND5_K, ROUND5_SPEC, ROUND5D_ARMS, ROUND5E_ARMS, - SCORABLE, TEMPLATES_ENV, VENDORED, VOIDING, TrialError, - canonical, git, reach, read_transcripts, scoring_area, - split_name, transcript_files, - trial_name) +from harness import (ARMS, ARMS_DIR, PROMPT, REGISTRATIONS, # noqa: E402 + ROUND5_ARMS, ROUND5_K, ROUND5_SPEC, ROUND5D_ARMS, + ROUND5E_ARMS, SCORABLE, TEMPLATES_ENV, VENDORED, VOIDING, + TrialError, canonical, git, reach, read_transcripts, + read_change_prompt, recorded_round, + registration_digest, scoring_area, split_name, + text_digest, transcript_files, trial_name) from harness import name_of as trial_of # noqa: E402 HERE = os.path.dirname(os.path.abspath(__file__)) @@ -593,11 +594,13 @@ def non_inferior(key, interval, direction, baseline_mean=None, margins=None): return {"margin": label, "within": degradation <= margin} -def load(root): +def load(root, named=None): """Every scored trial, with its judging attached where one exists. Keyed by canonical name, so a trial's score, judging and reading meet - however each spelled it. + however each spelled it. For a round `named` by its run records, a change + task whose build trial has no score stands as a trial of its own, its + build readings empty and marked `change_only`. """ area = scoring_area(root) trials = {} @@ -625,8 +628,9 @@ def load(root): elif trials[name]["judge"] is None: trials[name]["judge"] = judging - # A change task sits beside its own build trial, so one whose build trial - # was never scored has nothing to pair with and is left out. + # A pilot round's change task ran on its own build trial, so one whose + # build trial was never scored has nothing to pair with and is left out. + # A named round's starts from a fixture, so it stands without its build. for file in sorted(glob.glob(os.path.join(area, "scores-change", "*.json"))): with io.open(file, encoding="utf-8") as handle: @@ -634,20 +638,54 @@ def load(root): name = canonical(change.get("name") or "") if name in trials: trials[name]["change"] = change + elif named is not None: + trials[name] = change_only({"change": change}) # The security and quality readings each sit beside their trial's score, - # one file a trial, named for it. + # one file a trial, named for it; a change task standing alone takes none. for kind, key in (("security-scores", "security"), ("quality-scores", "quality")): for file in sorted(glob.glob(os.path.join(area, kind, "*.json"))): with io.open(file, encoding="utf-8") as handle: reading = json.load(handle) name = canonical(reading.get("name") or "") - if name in trials: + if name in trials and not trials[name].get("change_only"): trials[name][key] = reading return trials +def round_trials(root): + """A root's trials as its report and its archive's verify read them, and + why they cannot be read: (trials, problem).""" + + # A round its run records name is read as that round, never under the + # pilot's rules its arms' names would suggest, and records missing its + # identity are refused rather than read as the pilot's. + named, problem = recorded_round(root) + if problem: + return {}, problem + trials = load(root, named) + if named is not None: + for trial in trials.values(): + trial["round"] = named + return trials, None + + +def leave_out_reached(root, trials): + """Leave out of `trials`, in place, every trial whose scan finds a reach, + by the rule of the round they are; return the names left out.""" + return exclude_reached(trials, reaches(root), + per_task=named_round(trials) is not None) + + +def change_only(trial): + """A trial, in place, as its change task alone: its build readings + emptied, so every build row reads it as not measured.""" + trial.update({"scores": {}, "judge": None, "judgings": [], + "security": None, "quality": None, "change_only": True}) + return trial + + def arm_of(name): return split_name(name)[0] @@ -664,23 +702,35 @@ def ordered(names): else len(position), index_of(name))) +def named_round(trials): + """The round the run records name for these trials, or None for a run + from before rounds were named.""" + return next((trial.get("round") for trial in trials.values() + if trial.get("round")), None) + + +# A round from 6 on may reuse a pilot arm's name, so the pilot's rounds are +# inferred from the arms only for a run whose records name no round. def is_round5(trials): """Whether the run holds a round-5 arm, so that round's registration, its K and its margins, governs it.""" - return (any(arm_of(name) in ROUND5_ARMS for name in trials) - or is_round5d(trials) or is_round5e(trials)) + return (named_round(trials) is None + and (any(arm_of(name) in ROUND5_ARMS for name in trials) + or is_round5d(trials) or is_round5e(trials))) def is_round5d(trials): """Whether the run holds a round-5d arm, so that round's registration and its verdict rules govern it.""" - return any(arm_of(name) in ROUND5D_ARMS for name in trials) + return (named_round(trials) is None + and any(arm_of(name) in ROUND5D_ARMS for name in trials)) def is_round5e(trials): """Whether the run holds a round-5e arm, so that round's registration governs it, under round 5d's verdict rules.""" - return any(arm_of(name) in ROUND5E_ARMS for name in trials) + return (named_round(trials) is None + and any(arm_of(name) in ROUND5E_ARMS for name in trials)) def later_rules_of(trials): @@ -696,17 +746,30 @@ def later_rules_of(trials): def round_arms(trials): """The arms the run's round registers as fresh trials.""" + if named_round(trials) is not None: + return tuple(REGISTRATIONS[named_round(trials)]["arms"]) if is_round5e(trials): return ROUND5E_ARMS return ROUND5D_ARMS if is_round5d(trials) else ROUND5_RUN def owed_blocks(trials): - """The blocks of round 5's K that still miss a registered arm's trial, - in order.""" + """The blocks of the round's K that still miss a registered arm's trial, + of any task the round registers, in order.""" run = round_arms(trials) - return [block for block in range(1, ROUND5_K + 1) - if any(trial_name(arm, block) not in trials for arm in run)] + if named_round(trials) is None: + return [block for block in range(1, ROUND5_K + 1) + if any(trial_name(arm, block) not in trials for arm in run)] + + # A round of two tasks is complete only with both at K for every arm. + tasks = REGISTRATIONS[named_round(trials)]["tasks"] + k = max(task["k"] for task in tasks.values()) + return [block for block in range(1, k + 1) + if any(trial_name(arm, block) not in trials + or trials[trial_name(arm, block)].get("change_only") + or ("change" in tasks + and not trials[trial_name(arm, block)].get("change")) + for arm in run)] def blocks_named(blocks): @@ -759,6 +822,14 @@ def arm_origins(trials): origins = {} for name in ordered(trials): source = (trials[name].get("scores") or {}).get("reused_from") or {} + + # A trial reused from another root of the same named round, under the + # same registration, ran in this round: its origin is provenance. + named = named_round(trials) + if (named is not None and source.get("round") == named + and source.get("registration") + == registration_digest(REGISTRATIONS[named])): + source = {} origins.setdefault(arm_of(name), source.get("root") or source.get("name") or None) return origins @@ -1470,6 +1541,34 @@ def prompt_problem(root): return None +def registered_inputs_problem(root, named): + """Why one of a named round's trials did not build or change from the + spec and the prompt its round's entry pins for its task, or None.""" + entry = REGISTRATIONS[named] + for record in run_records(root): + + # A refused or unfinished trial put nothing in front of the scorer, + # so it has nothing to show; one with something to score has to. + if record.get("outcome") not in SCORABLE: + continue + task = record.get("task", "build") + registered = entry["tasks"].get(task) + if registered is None: + return ("trial %s ran the %s task, which round %s does not " + "register" % (trial_of(record), task, named)) + spec, prompt = record.get("spec") or {}, record.get("prompt") + if spec.get("sha256") != entry["spec"]["sha256"]: + return ("trial %s's %s task built from %s at sha256 %s, and round " + "%s registers sha256 %s" + % (trial_of(record), task, spec.get("file"), + spec.get("sha256"), named, entry["spec"]["sha256"])) + if (prompt is None + or text_digest(prompt) != registered["prompt_sha256"]): + return ("trial %s was given another %s prompt than the one round " + "%s registers" % (trial_of(record), task, named)) + return None + + def python_problem(trials): """Why the trials' scores were not all installed on one Python, or None. @@ -1479,7 +1578,8 @@ def python_problem(trials): for name, trial in trials.items(): for part in ("scores", "change"): scores = trial.get(part) - if scores is None: + if scores is None or (part == "scores" + and trial.get("change_only")): continue version = scores.get("python") minor = ".".join(version.split(".")[:2]) if version else "unrecorded" @@ -1503,12 +1603,18 @@ def registration_problem(root, registration, repository=REPOSITORY): """Why the round's registration does not predate its first trial, or None when it landed on the main branch before that trial and is unchanged since.""" + if not os.path.isfile(os.path.join(repository, registration)): + return ("%s does not exist, so no trial can be shown to have run " + "after its round registered" % registration) moments = [] for record in run_records(root): # A trial reused from an earlier round ran under that round's - # registration, so only this round's own trials have to follow its. - if record.get("reused_from"): + # registration, so only this round's own trials have to follow its; + # one reused within its own named round ran under this one. + origin = record.get("reused_from") + if origin and not (record.get("round") + and origin.get("round") == record["round"]): continue try: moment = datetime.datetime.fromisoformat(record["started_at"]) @@ -1527,25 +1633,42 @@ def registration_problem(root, registration, repository=REPOSITORY): first = min(moments) if git(repository, "status", "--porcelain", "--", registration): return "%s has changes that are not committed" % registration - if git(repository, "diff", "--name-only", REGISTRATION_BRANCH, "--", - registration): + base = registration_base(repository) + if base is None: + return ("neither %s nor origin/%s is in %s, so %s cannot be shown to " + "have landed; fetch %s" + % (REGISTRATION_BRANCH, REGISTRATION_BRANCH, repository, + registration, REGISTRATION_BRANCH)) + if git(repository, "diff", "--name-only", base, "--", registration): return ("%s differs from %s's copy, so it has not landed; merge it " - "or pull %s" % (registration, REGISTRATION_BRANCH, - REGISTRATION_BRANCH)) + "or pull %s" % (registration, base, REGISTRATION_BRANCH)) # The first-parent line is the main branch's own history, so a merge that # brought the registration in is read at the merge, not at the branch # commit beneath it. GitHub's squash and rebase merges stamp the commit # with the merge time; a fast-forward pushed from a clone keeps the # branch commit's date, which this cannot see past. - landed = git(repository, "log", REGISTRATION_BRANCH, "--first-parent", - "-1", "--format=%cI", "--", registration) + landed = git(repository, "log", base, "--first-parent", "-1", + "--format=%cI", "--", registration) if not landed: - return "%s is not on %s" % (registration, REGISTRATION_BRANCH) + return "%s is not on %s" % (registration, base) if datetime.datetime.fromisoformat(landed) > first: return ("%s landed on %s at %s, after the first trial started at %s" - % (registration, REGISTRATION_BRANCH, landed, - first.isoformat())) + % (registration, base, landed, first.isoformat())) + return None + + +def registration_base(repository): + """The ref the main branch is read at: its local branch, else the + remote's copy of it, or None where the clone holds neither.""" + + # A clone of one branch, as a CI checkout is, holds no local main. + for ref in (REGISTRATION_BRANCH, "origin/" + REGISTRATION_BRANCH): + try: + git(repository, "rev-parse", "--verify", "-q", ref + "^{commit}") + except TrialError: + continue + return ref return None @@ -1565,19 +1688,22 @@ def reaches(root): files, calls = read_transcripts(home, workspace, started(record)) if files: scan = reach(files, calls, workspace, record.get("temp"), - record.get("vendored")) + record.get("vendored"), record.get("protected", ()), + record.get("protected_names", ())) else: scan = record.get("reach") or reach(files, calls) scans.append({"name": name_of(record), "hits": scan["hits"]}) return scans -def exclude_reached(trials, scans): +def exclude_reached(trials, scans, per_task=False): """Leave out of `trials` every trial whose scan finds a reach, in place; return the names left out. - A reached build trial goes whole. A reached change task takes only its - change reading with it, because its build trial was measured clean. + A reached build trial goes whole, or `per_task`, for a round whose change + task starts from a fixture, only its build readings. A reached change + task takes only its change reading with it, because its build trial was + measured clean. """ left_out = [] for scan in scans: @@ -1587,8 +1713,13 @@ def exclude_reached(trials, scans): build = name.replace(CHANGE_TASK, "") if build not in trials: continue - if name == build: + if name == build and per_task and trials[name]["change"] is not None: + change_only(trials[name]) + elif name == build: del trials[name] + elif trials[build]["change"] is not None and per_task \ + and trials[build].get("change_only"): + del trials[build] elif trials[build]["change"] is not None: trials[build]["change"] = None else: @@ -5270,6 +5401,341 @@ def quietly(argv): return checks +def round_identity_checks(): + """A run whose records name a round is read as that round, both tasks + counted; records missing its identity are refused, not read as the + pilot's; records naming none are read by their arms, as before.""" + arms = REGISTRATIONS["C1"]["arms"] + blocks = range(1, REGISTRATIONS["C1"]["tasks"]["build"]["k"] + 1) + + def run(change): + return {trial_name(arm, block): { + "scores": {}, "round": "C1", + "change": {"name": trial_name(arm, block)} if change else None} + for arm in arms for block in blocks} + named, legacy = run(False), run(False) + for trial in legacy.values(): + trial.pop("round") + whole = run(True) + gap = run(True) + gap[trial_name("lazyref", 4)]["change"] = None + checks = [ + ("a run its records name C1 does not read as a pilot round", + not is_round5(named) and not is_round5d(named) + and not is_round5e(named) and iso_rules(named) + and is_round5(legacy) and is_round5e(legacy)), + ("a C1 round owes a block until both tasks are in for every arm", + owed_blocks(named) == list(blocks) and owed_blocks(whole) == [] + and owed_blocks(gap) == [4]), + ] + + scratch = tempfile.mkdtemp(prefix="efficacy-report-identity-") + digest = registration_digest(REGISTRATIONS["C1"]) + trial = {"round": "C1", "task": "build", "arm": "none", "block": 1, + "trial": 1, "outcome": "completed"} + + def refused(name, runs, why="round", documents=()): + root = os.path.join(scratch, name) + scores = os.path.join(scoring_area(root), "scores") + os.makedirs(scores) + os.makedirs(root) + with io.open(os.path.join(scores, "none-1.json"), "w", + encoding="utf-8") as handle: + json.dump({"name": "none-1"}, handle) + for index, header in enumerate(runs): + with io.open(os.path.join(root, "run-%d.json" % index), "w", + encoding="utf-8") as handle: + json.dump(header, handle) + saved, sys.stdout = sys.stdout, io.StringIO() + try: + with planted_repository(os.path.join(scratch, name + "-repo"), + documents): + code = main(["--root", root, "--out-dir", + os.path.join(scratch, "out")]) + printed = sys.stdout.getvalue() + finally: + sys.stdout = saved + return code == 2 and "refused" in printed and why in printed + + good = {"round": "C1", "registration": digest, "trials": [trial]} + + # One build and one change task, each on what C1 pins for its task; + # then each input swapped, or a task given the other's prompt. + spec = {"file": "SPEC.md", "sha256": REGISTRATIONS["C1"]["spec"]["sha256"]} + pinned = dict(trial, spec=spec, prompt=PROMPT) + change = dict(pinned, task="change", prompt=read_change_prompt()) + + def inputs_refused(): + def problem(*records): + root = os.path.join(scratch, "inputs-%d" % len(os.listdir( + scratch))) + os.makedirs(root) + with io.open(os.path.join(root, "run-1.json"), "w", + encoding="utf-8") as handle: + json.dump(dict(good, trials=list(records)), handle) + return registered_inputs_problem(root, "C1") + swapped = [ + problem(dict(pinned, spec=dict(pinned["spec"], sha256="0" * 64)), + change), + problem(pinned, dict(change, prompt=PROMPT)), + problem(dict(pinned, prompt=read_change_prompt()), change), + problem(dict(pinned, spec=None), change), + problem(pinned, dict(change, prompt=None))] + return (problem(pinned, change) is None + and problem(dict(pinned, outcome="refused", spec=None)) + is None + and all(swapped) + and refused("inputs", [dict(good, trials=[dict( + pinned, prompt="Build it.")])], "another build prompt")) + checks += [ + ("a root mixing a named round's records with others is refused", + refused("mixed", [good, {"trials": [{"arm": "none", "trial": 1}]}]) + and refused("other", [good, dict(good, registration="0" * 64)])), + ("a named round's record missing its identity is refused, not read " + "as the pilot's", + refused("bare", [dict(good, trials=[dict(trial, block=None)])])), + ("a run whose trials name a round under a header naming none is " + "refused, not read as the pilot's", + refused("unheaded", [{"trials": [trial]}], "yet its trial")), + ("a named round's trial on a spec or prompt its entry does not pin " + "is refused, each task held to its own", + inputs_refused()), + ("a named round is refused until its registration document is on " + "main before its first trial", + refused("unregistered", [dict(good, trials=[pinned])], + "%s does not exist" % REGISTRATIONS["C1"]["document"]) + and not refused("registered", [dict(good, trials=[dict( + pinned, started_at="2026-11-15T12:00:00+00:00")])], + REGISTRATIONS["C1"]["document"], + [REGISTRATIONS["C1"]["document"]])), + ] + shutil.rmtree(scratch, ignore_errors=True) + return checks + + +@contextlib.contextmanager +def planted_repository(path, documents=()): + """While inside, the report reads registrations from a git repository + planted at `path` holding only `documents`, never this checkout's.""" + saved = globals()["REPOSITORY"] + globals()["REPOSITORY"] = planted_registry( + path, documents=tuple(documents) or (PLANTED_REGISTRATION,)) + try: + yield + finally: + globals()["REPOSITORY"] = saved + shutil.rmtree(path, ignore_errors=True) + + +# The registration a planted repository holds, landed before any planted +# trial starts. +PLANTED_REGISTRATION = "docs/rounds/round.md" + + +def planted_registry(repository, branch=REGISTRATION_BRANCH, + documents=(PLANTED_REGISTRATION,)): + """A git repository holding `documents`, registrations committed on + `branch` at 2026-10-01, for a self-test that must read no branch, and + no document, of this one.""" + for document in documents: + path = os.path.join(repository, *document.split("/")) + os.makedirs(os.path.dirname(path), exist_ok=True) + with io.open(path, "w", encoding="utf-8") as handle: + handle.write("# Round\n") + when = "2026-10-01T10:00:00+00:00" + env = dict(os.environ, GIT_AUTHOR_DATE=when, GIT_COMMITTER_DATE=when) + git(repository, "init", "-q", "-b", branch) + git(repository, "add", "-A") + git(repository, "-c", "user.name=self-test", + "-c", "user.email=self-test@example.invalid", "commit", "-q", "-m", + "register", env=env) + return repository + + +def change_only_checks(): + """A named round's change task is read whether or not its build trial + was scored or reached, on rows of its own; a pilot round's keeps + needing its build.""" + scratch = tempfile.mkdtemp(prefix="efficacy-report-change-only-") + root = os.path.join(scratch, "run") + area = scoring_area(root) + for part in ("scores-change", "security-scores"): + os.makedirs(os.path.join(area, part)) + os.makedirs(root) + records = [] + for arm in ("none", "inline"): + for block in (1, 2): + name = trial_name(arm, block) + with io.open(os.path.join(area, "scores-change", name + ".json"), + "w", encoding="utf-8") as handle: + json.dump({"name": name, "task": "change", + "change_suite": {"value": 0.5 + block / 10.0, + "missing": None}}, handle) + records.append({"round": "C1", "task": "change", "arm": arm, + "block": block, "trial": block, + "outcome": "completed", + "prompt": read_change_prompt(), + "spec": dict(REGISTRATIONS["C1"]["spec"])}) + with io.open(os.path.join(area, "security-scores", "none-1.json"), "w", + encoding="utf-8") as handle: + json.dump({"name": "none-1"}, handle) + with io.open(os.path.join(root, "run-1.json"), "w", + encoding="utf-8") as handle: + json.dump({"round": "C1", "task": "change", "trials": records, + "registration": registration_digest(REGISTRATIONS["C1"])}, + handle) + saved, sys.stdout = sys.stdout, io.StringIO() + try: + with planted_repository(os.path.join(scratch, "repository")): + code = main(["--root", root, "--out-dir", + os.path.join(scratch, "out")]) + printed = sys.stdout.getvalue() + finally: + sys.stdout = saved + alone = load(root, "C1") + for trial in alone.values(): + trial["round"] = "C1" + table = collect(alone) + checks = [ + ("a named round's change task with no build score is read on its own", + code == 2 and "no scores" not in printed + and REGISTRATIONS["C1"]["document"] in printed and load(root) == {} + and sorted(alone) == ["inline-1", "inline-2", "none-1", "none-2"] + and all(trial.get("change_only") and trial["security"] is None + for trial in alone.values()) + and table["change_success"]["values"]["none"][2] == 0.7 + and table["task_success"]["values"]["none"][2] is None), + ] + + # Every arm's change task in, and no build: the round still owes every + # block, its build observations missing. + changes = {trial_name(arm, block): change_only( + {"round": "C1", "change": {"name": trial_name(arm, block)}}) + for arm in REGISTRATIONS["C1"]["arms"] for block in range(1, 16)} + checks.append(("a C1 block whose builds stand only as change tasks is " + "still owed", owed_blocks(changes) == list(range(1, 16)))) + shutil.rmtree(scratch, ignore_errors=True) + + def both(name, python="3.12.1"): + return {"scores": {"name": name, "python": python}, "judge": None, + "judgings": [], "security": {"name": name}, + "change": {"name": name, "python": python, + "change_suite": {"value": 1.0, "missing": None}}} + reach_build = [{"name": "none-1", "hits": [{"term": "x"}]}] + reach_change = [{"name": "none-1" + CHANGE_TASK, "hits": [{"term": "x"}]}] + named = {"none-1": both("none-1"), "none-2": both("none-2")} + legacy = {"none-1": both("none-1"), "none-2": both("none-2")} + left = exclude_reached(named, reach_build, per_task=True) + kept = dict(named.get("none-1") or {}) + exclude_reached(legacy, reach_build) + exclude_reached(named, reach_change, per_task=True) + checks.append(("a reached build of a named round keeps its change " + "reading, and a reached change task goes alone", + left == ["none-1"] and kept.get("change_only") + and kept["change"] is not None + and kept["scores"] == {} and kept["security"] is None + and "none-1" not in legacy and "none-1" not in named + and named["none-2"]["change"] is not None)) + standing = change_only(both("none-3")) + checks.append(("a change task standing alone counts on its ISO axes, not " + "as a broken build", + iso_trial_scores(standing)["Maintainability"] + ["Modifiability"] == 1.0 + and iso_trial_scores(dict(both("none-4"), scores={})) + ["Maintainability"]["Modifiability"] is None)) + + # One change result beside its build unscored, scored and working, and + # scored and broken: a named round reads it the same each time, and a + # pilot round's broken build still takes its change targets with it. + change = {"name": "none-5", "change_suite": {"value": 1.0, + "missing": None}} + working = {"name": "none-5", + "install": {"value": True, "missing": None}, + "boot": {"value": {"factory": True, "index_status": 200}, + "missing": None}} + + # The broken build's own Modifiability target missed, which is read with + # the build and so never reaches the change's sub-score. + broken = dict(working, install={"value": False, "missing": None}, + structure={"value": {"kind_ladders": [1, 2, 3]}, + "missing": None}) + + def modifiability(scores, named="C1"): + trial = {"scores": scores, "change": change, "round": named} + if scores is None: + trial = change_only(dict(trial)) + return iso_trial_scores(trial)["Maintainability"]["Modifiability"] + readings = [modifiability(scores) for scores in (None, working, broken)] + checks.append(("a named round's change result reads the same whether its " + "build is unscored, working or broken", + readings == [1.0, 1.0, 1.0] + and modifiability(broken, None) is None + and modifiability(working, None) == 1.0)) + + # Inline copied in from another root of C1, none run here: one round, + # so the pair is read paired; copied from a round of none, it crosses. + digest = registration_digest(REGISTRATIONS["C1"]) + + def mixed(origin): + trials = {} + for block in (1, 2, 3): + trials[trial_name("none", block)] = {"scores": {}, + "round": "C1"} + reused = dict(origin, root="elsewhere", + name=trial_name("inline", block)) + trials[trial_name("inline", block)] = { + "scores": {"reused_from": reused}, "round": "C1"} + return crossed_labels(trials) + checks.append(("trials reused within one named round pair with those run " + "there", + "inline-none" not in mixed({"round": "C1", + "registration": digest}) + and "inline-none" in mixed({}) + and "inline-none" in mixed({"round": "C1", + "registration": "0" * 64}))) + + # A trial copied within C1, which started after its registration + # landed, is when the round began; the pilot's skip of reused trials + # would leave the round with no first trial. The registration lands in + # a repository planted here, so no branch of this one is read. + began = tempfile.mkdtemp(prefix="efficacy-report-began-") + with io.open(os.path.join(began, "run-1.json"), "w", + encoding="utf-8") as handle: + json.dump({"trials": [{"arm": "none", "trial": 1, "round": "C1", + "reused_from": {"round": "C1"}, + "started_at": "2026-11-15T12:00:00+00:00"}]}, + handle) + registry = planted_registry(os.path.join(began, "repository")) + counted = registration_problem(began, PLANTED_REGISTRATION, registry) + checks.append(("a trial reused within its named round counts toward when " + "the round began", counted is None)) + + # The main branch read as origin's where the clone has no local one, as + # in a CI checkout, and a clone with neither refused with its reason. + remote = planted_registry(os.path.join(began, "remote"), "work") + git(remote, "update-ref", "refs/remotes/origin/" + REGISTRATION_BRANCH, + "HEAD") + bare = planted_registry(os.path.join(began, "bare"), "work") + try: + missing = registration_problem(began, PLANTED_REGISTRATION, bare) + except Exception as error: + missing = "crashed: %s" % error + checks.append(("the main branch is read locally, else as origin's, and a " + "clone with neither is refused, not crashed", + registration_base(registry) == REGISTRATION_BRANCH + and registration_base(remote) + == "origin/" + REGISTRATION_BRANCH + and registration_problem(began, PLANTED_REGISTRATION, + remote) is None + and registration_base(bare) is None + and "neither" in (missing or ""))) + shutil.rmtree(began, ignore_errors=True) + checks.append(("a change task standing alone reads no build Python", + python_problem({"none-1": both("none-1"), + "none-3": standing}) is None)) + return checks + + def context_lines(arm): """The line count of the context file an arm's trials received, None where the arm receives none.""" @@ -6141,24 +6607,32 @@ def iso_trial_scores(trial, withdrawn=(), axes=ISO_AXES): A sub-score is the share of its targets met, over the targets measured, and None where none was. A broken build is scored on Reliability alone, - where the install target fails, and reads None on every other axis. A - target reading a metric in `withdrawn` is not measured. `axes` is the + where the install target fails, and reads None on every other axis; for + a named round, whose change task starts from a fixture, only the build's + own targets are, and the change targets are read whatever the build did. + A target reading a metric in `withdrawn` is not measured. `axes` is the table of targets read. """ broken = works(trial) != 1.0 + + # A named round's change task never ran on this trial's build, so a + # build broken, or not scored at all, says nothing of the change. + apart = trial.get("round") is not None or trial.get("change_only") scores = {} for axis, subs in axes: per_sub = {} for sub, targets in subs: - if broken and axis != BROKEN_AXIS: + if broken and axis != BROKEN_AXIS and not apart: per_sub[sub] = None continue + gated = broken and axis != BROKEN_AXIS # A withdrawn metric's number is no result, on the radar as in # the tables, so its target drops out rather than reads as met. met = [target_met(trial, source, condition, threshold) for _, source, condition, threshold in targets - if source not in withdrawn] + if source not in withdrawn + and not (gated and source not in CHANGE)] measured = [outcome for outcome in met if outcome is not None] per_sub[sub] = (sum(measured) / len(measured) if measured else None) @@ -7281,10 +7755,33 @@ def rescan_checks(): workspace)[1]) == 1 terms = [hit["term"] for scan in reaches(scratch) for hit in scan["hits"] or []] + + # A change trial of a named round whose call unpacked a fixture from + # the fixtures' directory, which its record names as fenced off. + fixtures = os.path.join(tempfile.gettempdir(), + "efficacy-report-rescan-fixtures") + entry["message"]["content"][0]["input"]["command"] = ( + "tar xf %s && tar xf ../../../elsewhere/none-11.tar" + % os.path.join(fixtures, "none-2.tar")) + with io.open(os.path.join(projects, "planted.jsonl"), "w", + encoding="utf-8") as handle: + handle.write(json.dumps(entry) + "\n") + planted[0]["protected"] = [fixtures] + planted[0]["protected_names"] = ["none-2.tar", "none-11.tar"] + with io.open(os.path.join(scratch, "run-planted.json"), "w", + encoding="utf-8") as handle: + json.dump({"trials": planted}, handle) + fenced = [hit["term"] for scan in reaches(scratch) + for hit in scan["hits"] or []] shutil.rmtree(scratch, ignore_errors=True) return [("the planted transcript carries one call", landed), ("its record's clean scan is read again and flagged", - terms == ["../inline-1"])] + terms == ["../inline-1"]), + ("a call into the fixtures' directory its record fences off is " + "flagged on the re-scan", + len(fenced) == 3 and fenced[0].endswith( + "efficacy-report-rescan-fixtures") + and "none-11.tar" in fenced)] def planted_change_run(revision): @@ -8721,6 +9218,8 @@ def self_test(seed): checks.extend((label, ok, ok) for label, ok in spec_checks()) checks.extend((label, ok, ok) for label, ok in prompt_checks()) checks.extend((label, ok, ok) for label, ok in python_checks()) + checks.extend((label, ok, ok) for label, ok in round_identity_checks()) + checks.extend((label, ok, ok) for label, ok in change_only_checks()) for label, ok, got in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED, got %r" % (got,))) @@ -8786,11 +9285,15 @@ def main(argv): print("--root is required unless --self-test is given") return 2 - trials = load(options.root) + trials, problem = round_trials(options.root) + if problem: + print("refused: %s" % problem) + return 2 if not trials: print("no scores under %s; score.py writes them" % scoring_area(options.root)) return 2 + named = named_round(trials) out_dir = options.out_dir if out_dir is None: @@ -8821,6 +9324,25 @@ def main(argv): # A hypothesis registered or changed after the round's first trial could # have been written to fit what that trial showed, so the round is refused # rather than read against it. + # A named round's trials are held to the spec and prompts its entry pins, + # each task to its own, as a pilot round's are to round 5's. + if named is not None: + problem = registered_inputs_problem(options.root, named) + if problem: + print("refused: %s" % problem) + return 2 + + # A named round's registration is its entry's document, held to the + # same rule. + if named is not None: + try: + problem = registration_problem( + options.root, REGISTRATIONS[named]["document"], REPOSITORY) + except TrialError as error: + problem = str(error) + if problem: + print("refused: %s" % problem) + return 2 if is_round5(trials): try: problem = registration_problem( @@ -8855,7 +9377,7 @@ def main(argv): # A trial that read past its workspace measures what it read, not its # arm; the harness voids one its own scan catches, and this re-scan, under # the current rule, leaves out any it missed. - for name in exclude_reached(trials, reaches(options.root)): + for name in leave_out_reached(options.root, trials): print("left out, having reached past its workspace: %s" % name) if not trials: print("no trial is left to report once the reached ones are out") diff --git a/tests/efficacy/reuse.py b/tests/efficacy/reuse.py index 3e59f2b..a1a1c34 100644 --- a/tests/efficacy/reuse.py +++ b/tests/efficacy/reuse.py @@ -23,9 +23,10 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import lib # noqa: E402 -from harness import (ARMS, PROMPT, TrialError, # noqa: E402 - assert_outside_repository, canonical, now, - project_folder, remove_tree, scorable_trials, +from harness import (ARMS, PROMPT, REGISTRATIONS, TrialError, # noqa: E402 + assert_outside_repository, canonical, identity_problem, + now, project_folder, recorded_round, + registration_digest, remove_tree, scorable_trials, scoring_area, write_run) # The scoring area's per-trial readings, each a JSON file named for the @@ -83,8 +84,9 @@ def judgings_of(area, name): return found -def reuse_trial(name, record, source, target): - """Copy one trial's artifacts into the target root and scoring area. +def reuse_trial(name, record, source, target, identity=None): + """Copy one trial's artifacts into the target root and scoring area; + `identity` names the round and registration it ran under, if named. Returns the run record to write for it and the blind label its judging carries, None where it was never judged. @@ -99,6 +101,12 @@ def reuse_trial(name, record, source, target): "name": os.path.splitext(os.path.basename(tarball))[0], "tarball": tarball} + # The origin names its round, so a reader can tell a trial copied within + # one named round, which pairs with the trials run here, from one carried + # over from another. + if identity: + origin = dict(origin, **identity) + copied = dict(record) copied["reused_from"] = origin copied["frozen"] = dict(record["frozen"], @@ -159,6 +167,20 @@ def reuse(source, target, arms): assert_outside_repository(target) chosen = select(source, arms) + # A named round's trials go on as that round's: their copy's run record + # names it, and they join no root of another round or of none, which + # would read them under rules their round never registered. + named, problem = recorded_round(source) + identity = None + if named is not None and not problem: + identity = {"round": named, + "registration": registration_digest(REGISTRATIONS[named])} + problem = identity_problem(target, named, identity["registration"]) + elif not problem: + problem = identity_problem(target) + if problem: + raise TrialError(problem) + # A trial the target already offers would then be offered twice, which # the scorer refuses; better refused here, before anything is copied. try: @@ -192,7 +214,8 @@ def reuse(source, target, arms): taken = {label: name for name, label in mapping["blind"].items()} records, labels = [], {} for name in sorted(chosen): - copied, label = reuse_trial(name, chosen[name], source, target) + copied, label = reuse_trial(name, chosen[name], source, target, + identity) records.append(copied) if label: if label in taken and taken[label] != name: @@ -207,14 +230,16 @@ def reuse(source, target, arms): os.makedirs(target, exist_ok=True) run_file = os.path.join(target, "run-%s-reused.json" % started_at.strftime("%Y-%m-%dT%H-%M-%S")) - write_run(run_file, started_at, records, "build", PROMPT) + write_run(run_file, started_at, records, "build", PROMPT, + identity=identity) return sorted(chosen), run_file -def plant_source(scratch): +def plant_source(scratch, name="earlier", identity=None): """A source root of an earlier round: one trial per arm, each scored, - judged and read for security, with a transcript and a lock.""" - source = os.path.join(scratch, "earlier") + judged and read for security, with a transcript and a lock; a named + round's where `identity` names one.""" + source = os.path.join(scratch, name) area = scoring_area(source) records = [] for arm, index in (("none", 1), ("inline", 1), ("hand", 1)): @@ -240,7 +265,8 @@ def plant_source(scratch): json.dump({"name": old, "arm": arm, "trial": index, "suite_revision": "planted"}, handle) write_run(os.path.join(source, "run-planted.json"), - datetime.datetime(2026, 9, 15, 12, 0, 0), records) + datetime.datetime(2026, 9, 15, 12, 0, 0), records, + identity=identity) os.makedirs(os.path.join(area, "judge")) blind = {"hand-1": "T1", "inline-1": "T2", "none-1": "T3"} for old, label in blind.items(): @@ -335,6 +361,36 @@ def loaded(*parts): carried["reused_from"]["root"] == os.path.abspath(source) and carried["reused_from"]["name"] == "inline-1")) + # A named round's trials keep their round in the copy's header, and go + # into no root of none. + digest = registration_digest(REGISTRATIONS["C1"]) + named = plant_source(scratch, "named", + {"round": "C1", "registration": digest}) + _, kept = reuse(named, os.path.join(scratch, "named-later"), ["inline"]) + header = loaded(kept) + checks.append(("a named round's trials copied on keep its round in the " + "run record's header", + header.get("round") == "C1" + and header.get("registration") == digest + and recorded_round(os.path.dirname(kept)) == ("C1", None))) + origin = loaded(scoring_area(os.path.dirname(kept)), "scores", + "inline-1.json")["reused_from"] + checks.append(("a trial copied within a named round names that round in " + "its origin", + origin.get("round") == "C1" + and origin.get("registration") == digest + and origin.get("root") == os.path.abspath(named))) + joined = [] + for origin, into in ((named, target), + (source, os.path.dirname(kept))): + try: + reuse(origin, into, ["none"]) + joined.append(True) + except TrialError: + joined.append(os.path.exists(os.path.join(into, "none-1.tar"))) + checks.append(("a reuse never mixes a named round's trials with others", + joined == [False, False])) + for label, ok in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED")) remove_tree(scratch)