matrix.py

acceptance/matrix.py

Provision, generate and grade every target of a grid from ONE invocation.

_prepare

tuple[Rubric, Path, object] | TargetOutcome acceptance.matrix._prepare(Path rubric_path, Path out)

Provision one target and return its rubric and root.

acceptance/matrix.py:106

Source · 18 lines
def _prepare(rubric_path: Path, out: Path) -> tuple[Rubric, Path, object] | TargetOutcome:
    """@brief Load and provision one target.
    @return Prepared triple, or the outcome that stopped it.
    @version 1
    """
    name = rubric_path.parent.name
    try:
        rubric = load(rubric_path)
    except RubricError as exc:
        return TargetOutcome(name, False, "rubric", str(exc))
    root = out / name
    try:
        prepared = provision(rubric, root)
    except ProvisionError as exc:
        return TargetOutcome(name, False, "provision", str(exc))
    return rubric, root, prepared

Activity · 11 steps
lines 111–111name = rubric_path.parent.namelines 112–112trylines 113–113rubric = load(rubric_path)lines 114–114except RubricError as exclines 115–115return TargetOutcome(name, False, "rubric", str(exc))lines 116–116root = out / namelines 117–117trylines 118–118prepared = provision(rubric, root)lines 119–119except ProvisionError as exclines 120–120return TargetOutcome(name, False, "provision", str(exc))lines 121–121return rubric, root, prepared

Flows

drive

int acceptance.matrix.drive(args)

Run every phase for every target.

acceptance/matrix.py:216

Source · 65 lines
def drive(args) -> int:
    """PHASE-MAJOR, NOT TARGET-MAJOR, for generation and grading: every target generates before
    any target grades. A stop midway then leaves whole targets ungenerated rather than every
    target half-graded, and an ungenerated target is a gap a reader can see.

    @brief Drive the grid.
    @return Number of failed targets.
    @version 1
    """
    try:
        rubrics = discover(args.targets, getattr(args, "only", None))
    except ValueError as exc:
        print(f"REFUSED — {exc}", file=sys.stderr)
        return 1
    if not rubrics:
        print(f"REFUSED — no rubrics under {args.targets}", file=sys.stderr)
        return 1
    print(f"{len(rubrics)} target(s): {', '.join(p.parent.name for p in rubrics)}")

    outcomes: list[TargetOutcome] = []
    ready: list[tuple[Path, Path]] = []
    for rubric_path in rubrics:
        name = rubric_path.parent.name
        print(f"\n=== provision {name}")
        prepared = _prepare(rubric_path, args.out)
        if isinstance(prepared, TargetOutcome):
            print(f"REFUSED — {prepared.detail}", file=sys.stderr)
            outcomes.append(prepared)
            continue
        _, root, _ = prepared
        ready.append((rubric_path, root))

    ## STOP HERE ON REQUEST. Provisioning is where a grid fails CHEAPLY — a pin that moved, a
    ## declaration the build did not record, an MCP config whose tools never register — and each
    ## of those is worth finding before a weekend of agent calls rather than on cell 40 of 120.
    ## `check_index_tools_reachable` already runs inside provision(), so this is a real
    ## end-to-end pre-flight and not merely a clone.
    if getattr(args, "provision_only", False):
        failed = [o for o in outcomes if not o.ok]
        print(f"\nprovisioned {len(ready)}/{len(rubrics)} target(s); no phases run")
        for o in failed:
            print(f"  FAILED {o.name} at {o.phase}: {o.detail[:200]}")
        return len(failed)

    for phase in ("generate", "grade", "report"):
        for rubric_path, root in list(ready):
            name = rubric_path.parent.name
            print(f"\n=== {phase} {name}")
            started = time.perf_counter()
            ok = run_phase(phase, phase_argv(phase, rubric_path, root, args))
            print(
                f"--- {phase} {name} {'ok' if ok else 'FAILED'} "
                f"in {time.perf_counter() - started:.0f}s"
            )
            if not ok:
                outcomes.append(TargetOutcome(name, False, phase))
                ready = [r for r in ready if r[0] != rubric_path]

    failed = [o for o in outcomes if not o.ok]
    print(f"\n{len(rubrics) - len(failed)}/{len(rubrics)} target(s) completed every phase")
    for o in failed:
        print(f"  FAILED {o.name} at {o.phase}: {o.detail[:200]}")
    return len(failed)

Activity · 42 steps
lines 225–225trylines 226–226rubrics = discover(args.targets, getattr(args, "only", None))lines 227–227except ValueError as exclines 228–228print(f"REFUSED — {exc}", file=sys.stderr)lines 229–229return 1lines 230–230◇ if not rubricslines 231–231print(f"REFUSED — no rubrics under {args.targets}", file=sys.stderr)lines 232–232return 1lines 233–233print(f"{len(rubrics)} target(s): {', '.join(p.parent.name for p in rubrics)}")lines 235–235outcomes: list[TargetOutcome] = []lines 236–236ready: list[tuple[Path, Path]] = []lines 237–237◇ for rubric_path in rubricslines 238–238name = rubric_path.parent.namelines 239–239print(f"\n=== provision {name}")lines 240–240prepared = _prepare(rubric_path, args.out)lines 241–241◇ if isinstance(prepared, TargetOutcome)lines 242–242print(f"REFUSED — {prepared.detail}", file=sys.stderr)lines 243–243outcomes.append(prepared)lines 244–244continuelines 245–245_, root, _ = preparedlines 246–246ready.append((rubric_path, root))lines 253–253◇ if getattr(args, "provision_only", False)lines 254–254failed = [o for o in outcomes if not o.ok]lines 255–255print(f"\nprovisioned {len(ready)}/{len(rubrics)} target(s); no phases run")lines 256–256◇ for o in failedlines 257–257print(f" FAILED {o.name} at {o.phase}: {o.detail[:200]}")lines 258–258return len(failed)lines 260–260◇ for phase in ("generate", "grade", "report")lines 261–261◇ for rubric_path, root in list(ready)lines 262–262name = rubric_path.parent.namelines 263–263print(f"\n=== {phase} {name}")lines 264–264started = time.perf_counter()lines 265–265ok = run_phase(phase, phase_argv(phase, rubric_path, root, args))lines 266–269print( f"--- {phase} {name} {'ok' if ok else 'FAILED'} " f"in {time.perf_counter() - started:.0f}s" )lines 270–270◇ if not oklines 271–271outcomes.append(TargetOutcome(name, False, phase))lines 272–272ready = [r for r in ready if r[0] != rubric_path]lines 274–274failed = [o for o in outcomes if not o.ok]lines 275–275print(f"\n{len(rubrics) - len(failed)}/{len(rubrics)} target(s) completed every phase")lines 276–276◇ for o in failedlines 277–277print(f" FAILED {o.name} at {o.phase}: {o.detail[:200]}")lines 278–278return len(failed)

Flows

main

int acceptance.matrix.main()

CLI entry point.

acceptance/matrix.py:287

Show on the map →

Called by none

Calls drive

Source · 49 lines
def main() -> int:
    """@brief Drive a grid from one invocation.
    @return Exit code.
    @version 2
    """
    here = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser(prog="acceptance.matrix", description=__doc__)
    parser.add_argument("--out", type=Path, required=True, help="grid output root")
    parser.add_argument("--targets", type=Path, default=here / "targets")
    parser.add_argument(
        "--only",
        nargs="+",
        default=None,
        metavar="NAME",
        help="run only these targets by directory name; an unknown name refuses the grid",
    )
    parser.add_argument("--models", nargs="+", required=True)
    parser.add_argument("--replicates", type=int, default=1)
    parser.add_argument("--seed", type=int, default=7)
    parser.add_argument("--timeout", type=int, default=1800)
    parser.add_argument(
        "--resume",
        action="store_true",
        help="skip cells whose answer is already frozen, so a stalled grid resumes",
    )
    parser.add_argument(
        "--jobs", type=int, default=1, help="grade this many answers at once (grading only)"
    )
    parser.add_argument(
        "--skills",
        type=Path,
        default=None,
        help="usage document appended to the agent's system prompt (generation only)",
    )
    parser.add_argument(
        "--skip-graded",
        type=int,
        default=0,
        metavar="N",
        help="skip cells already holding N grade passes, so a resumed grid moves forward only",
    )
    parser.add_argument(
        "--provision-only",
        action="store_true",
        help="fetch, build and verify every target, then stop before spending any agent calls",
    )
    return drive(parser.parse_args())

Activity · 15 steps
lines 292–292here = Path(__file__).resolve().parentlines 293–293parser = argparse.ArgumentParser(prog="acceptance.matrix", description=__doc__)lines 294–294parser.add_argument("--out", type=Path, required=True, help="grid output root")lines 295–295parser.add_argument("--targets", type=Path, default=here / "targets")lines 296–302parser.add_argument( "--only", nargs="+", default=None, metavar="NAME", help="run only these targets by directory name; an unknown name refuses the grid", )lines 303–303parser.add_argument("--models", nargs="+", required=True)lines 304–304parser.add_argument("--replicates", type=int, default=1)lines 305–305parser.add_argument("--seed", type=int, default=7)lines 306–306parser.add_argument("--timeout", type=int, default=1800)lines 307–311parser.add_argument( "--resume", action="store_true", help="skip cells whose answer is already frozen, so a stalled grid resumes", )lines 312–314parser.add_argument( "--jobs", type=int, default=1, help="grade this many answers at once (grading only)" )lines 315–320parser.add_argument( "--skills", type=Path, default=None, help="usage document appended to the agent's system prompt (generation only)", )lines 321–327parser.add_argument( "--skip-graded", type=int, default=0, metavar="N", help="skip cells already holding N grade passes, so a resumed grid moves forward only", )lines 328–332parser.add_argument( "--provision-only", action="store_true", help="fetch, build and verify every target, then stop before spending any agent calls", )lines 333–333return drive(parser.parse_args())

Flows

phase_argv

list[str] acceptance.matrix.phase_argv(str phase, Path rubric_path, Path root, args)

Build the argv a phase would have been invoked with by hand.

acceptance/matrix.py:131

Show on the map →

Called by drive, test_generate_carries_the_grid_parameters, test_grading_phases_take_no_generation_flags, test_phase_paths_are_derived_and_absolute, test_resume_and_jobs_reach_only_the_phase_that_takes_them, test_skip_graded_reaches_grade_and_nothing_else

Calls none

Source · 51 lines
def phase_argv(phase: str, rubric_path: Path, root: Path, args) -> list[str]:
    """THE PATHS ARE DERIVED, NEVER RETYPED, and they are ABSOLUTE. A relative `--mcp-config`
    resolved against the agent's working directory rather than the operator's and produced an
    index arm with no index and no error — the exact failure `check_index_tools_reachable`
    exists to catch, reached by a path that never got that far.

    @brief One phase's argument list.
    @return Argv.
    @version 2
    """
    answers = (root / "answers").resolve()
    common = ["--rubric", str(rubric_path.resolve())]
    if phase == "generate":
        argv = common + [
            "--models",
            *args.models,
            "--replicates",
            str(args.replicates),
            "--seed",
            str(args.seed),
            "--repo",
            str((root / "repo").resolve()),
            "--out",
            str(answers),
            "--mcp-config",
            str((root / "mcp.json").resolve()),
            "--timeout",
            str(args.timeout),
        ]
        ## FORWARDED, NOT RE-DERIVED. Resuming is the driver's business as much as the phase's:
        ## the grid is what spans the capacity window, and a target part-generated by an earlier
        ## invocation is reached through this same driver or through none at all.
        if getattr(args, "resume", False):
            argv.append("--resume")
        ## FORWARDED LIKE `--resume`: the grid is the unit an experiment runs on, so a flag the
        ## driver cannot pass is a flag that does not exist in practice.
        if getattr(args, "skills", None):
            argv += ["--skills", str(Path(args.skills).resolve())]
        return argv
    argv = common + ["--answers", str(answers)]
    ## GRADE ONLY. `report` has no such flag and passing it would make the driver's argv differ
    ## from the documented invocation, which is the drift `run_phase` exists to prevent.
    if phase == "grade" and getattr(args, "jobs", 1) > 1:
        argv += ["--jobs", str(args.jobs)]
    ## FORWARDED FOR THE SAME REASON `--resume` IS: the grid is what spans a capacity window,
    ## so a flag the driver cannot pass is a flag that does not exist in practice.
    if phase == "grade" and getattr(args, "skip_graded", 0) > 0:
        argv += ["--skip-graded", str(args.skip_graded)]
    return argv

Activity · 15 steps
lines 141–141answers = (root / "answers").resolve()lines 142–142common = ["--rubric", str(rubric_path.resolve())]lines 143–143◇ if phase == "generate"lines 144–159argv = common + [ "--models", *args.models, "--replicates", str(args.replicates), "--seed", str(args.seed), "--repo", str((root / "repo").resolve()), "--out", str(answers), "--mcp-config", str((root / "mcp.json").resolve()), "--timeout", str(args.timeout), ]lines 163–163◇ if getattr(args, "resume", False)lines 164–164argv.append("--resume")lines 167–167◇ if getattr(args, "skills", None)lines 168–168argv += ["--skills", str(Path(args.skills).resolve())]lines 169–169return argvlines 170–170argv = common + ["--answers", str(answers)]lines 173–173◇ if phase == "grade" and getattr(args, "jobs", 1) > 1lines 174–174argv += ["--jobs", str(args.jobs)]lines 177–177◇ if phase == "grade" and getattr(args, "skip_graded", 0) > 0lines 178–178argv += ["--skip-graded", str(args.skip_graded)]lines 179–179return argv

Flows

run_phase

bool acceptance.matrix.run_phase(str phase, list[str] argv)

Run one phase for one target through the CLI's own entry point.

acceptance/matrix.py:187

Show on the map →

Called by drive

Calls main

Source · 21 lines
def run_phase(phase: str, argv: list[str]) -> bool:
    """THROUGH THE SAME ENTRY POINT AN OPERATOR WOULD USE, deliberately. Calling the cmd_*
    functions directly would let this driver drift from the documented invocation, and the
    documented invocation is what every runbook and every past measurement used.

    @brief Execute one phase.
    @return Success.
    @version 1
    """
    from . import __main__ as cli

    saved = sys.argv
    sys.argv = ["acceptance", phase, *argv]
    try:
        return cli.main() == 0
    except SystemExit as exc:
        return exc.code in (0, None)
    finally:
        sys.argv = saved

Activity · 7 steps
lines 196–196from . import __main__ as clilines 198–198saved = sys.argvlines 199–199sys.argv = ["acceptance", phase, *argv]lines 200–200trylines 201–201return cli.main() == 0lines 202–202except SystemExit as exclines 203–203return exc.code in (0, None)

Flows