Skip to content

abc_mine.stages.build

WARNING

This documentation is almost entirely "vibe coded"; while a helpful resource for humans and agents to understand this codebase, it should not be considered a source of ground truth in the way documentation normally is, and the user is responsible for verifying that all instructions given here are safe.

abc_mine.stages.build

BUILD — turn each shortlisted commit into a complete ABC Runner task.

One construction agent per shortlisted commit, in parallel. Each agent authors three artifacts:

  • prompt.md — the task statement, the solver's only instruction,
  • build_env.sh — environment setup run before the solver,
  • verification/verify_solution.sh — the hidden deterministic check.

The fourth component, workspace/ (the starting state), is not authored by any agent. The pipeline builds it deterministically by git bundle-cutoff at the parent commit (see :func:abc_mine.repo.build_cutoff_workspace). An agent asked to "remove the change" would introduce exactly the kind of subtle, unauditable variation a benchmark cannot tolerate — and could accidentally leave the answer in the tree.

Two independent polarity layers

A verifier that does not actually discriminate between the fixed and unfixed trees is worthless, and worse than worthless if it passes vacuously: it would certify solvers that did nothing. So polarity is enforced twice, by different parties:

Layer 1 (the agent, in its sandbox). The construction agent is required to check its own verifier against the post-change and pre-change trees before finishing, and to iterate until it discriminates.

Layer 2 (this stage, deterministically). After the agent finishes, the pipeline re-checks polarity on the shipped artifact, in an environment that mirrors the real grader: the code tree bind-mounted at the grading path, the verifier staged outside it, and none of the conveniences that existed during authoring. A task reaches ok only when the verifier FAILs on the shipped starting state and PASSes on a clean checkout of the change commit.

Layer 2 is not redundant. It catches the most common way a plausible-looking verifier is actually broken: depending on a path that existed while the agent was working but does not exist at grading time. Layer 1 cannot catch that by construction, because Layer 1 runs in the environment that has those paths.

Build order

Commits are built in rank order. When the rank stage produced a full ranking (rank.output: full) there is no shortlist to exhaust: the stage simply works down the order, skipping commits already built or out of attempts, until either the list runs out or the per-invocation limit (--limit N) is reached. That limit is a property of one job, not of the run — resubmitting continues from where the previous job stopped. Under parallel backends the limit is a count of commits started, taken from the top of the remaining order.

Checkpoint and resume

The durable record is an append-only manifest.jsonl, written the instant each task finishes. On resume, tasks whose latest entry is ok are skipped; any planned-but-incomplete task directory (from a killed job) is removed and rebuilt. Nothing partial is ever left for a later stage to trust.

BuildPlan dataclass

What a build invocation intends to do.

Source code in abc_mine/stages/build.py
@dataclass
class BuildPlan:
    """What a build invocation intends to do."""

    selected: list[dict[str, Any]] = field(default_factory=list)
    pending: list[dict[str, Any]] = field(default_factory=list)
    already_done: int = 0
    stale_removed: list[str] = field(default_factory=list)
    #: True when building down a full ranking rather than a shortlist.
    full_ranking: bool = False
    #: Commits skipped because they have used up ``execution.max_attempts``.
    exhausted: int = 0
    #: Per-invocation cap on commits started (``None`` = no cap).
    limit: int | None = None
    #: Commits eligible to build but beyond ``limit`` (left for a later job).
    deferred: int = 0
    #: Task ids being resumed from a saved ``unfinished`` state.
    resume_unfinished: list[str] = field(default_factory=list)
    #: Task ids being resumed from a saved ``awaiting_check`` state.
    resume_awaiting: list[str] = field(default_factory=list)

    def describe(self) -> str:
        """Render a human-readable plan."""
        head = "Ranked commits:" if self.full_ranking else "Shortlisted commits:"
        lines = [f"{head:<22} {len(self.selected)}"]
        if self.already_done:
            lines.append(f"  already built:       {self.already_done} (skipping)")
        if self.exhausted:
            lines.append(
                f"  out of attempts:     {self.exhausted} (skipping; raise "
                "execution.max_attempts to retry)"
            )
        if self.resume_unfinished:
            lines.append(
                f"  resume unfinished:   {len(self.resume_unfinished)} "
                "(saved agent state; continues with remaining time budget)"
            )
        if self.resume_awaiting:
            lines.append(
                f"  resume awaiting:     {len(self.resume_awaiting)} "
                "(deliverables present; re-run deterministic check only)"
            )
        if self.stale_removed:
            lines.append(
                f"  incomplete removed:  {len(self.stale_removed)} "
                f"({', '.join(sorted(self.stale_removed)[:3])}"
                f"{', ...' if len(self.stale_removed) > 3 else ''})"
            )
        if self.pending and self.full_ranking:
            ranks = [e.get("rank") for e in self.pending]
            span = f" (ranks {ranks[0]}–{ranks[-1]})" if ranks[0] is not None else ""
        else:
            span = ""
        lines.append(f"  to build now:        {len(self.pending)}{span}")
        if self.deferred:
            lines.append(
                f"  left for later jobs: {self.deferred} (--limit {self.limit}; "
                "resubmit to continue down the order)"
            )
        return "\n".join(lines)

describe

describe() -> str

Render a human-readable plan.

Source code in abc_mine/stages/build.py
def describe(self) -> str:
    """Render a human-readable plan."""
    head = "Ranked commits:" if self.full_ranking else "Shortlisted commits:"
    lines = [f"{head:<22} {len(self.selected)}"]
    if self.already_done:
        lines.append(f"  already built:       {self.already_done} (skipping)")
    if self.exhausted:
        lines.append(
            f"  out of attempts:     {self.exhausted} (skipping; raise "
            "execution.max_attempts to retry)"
        )
    if self.resume_unfinished:
        lines.append(
            f"  resume unfinished:   {len(self.resume_unfinished)} "
            "(saved agent state; continues with remaining time budget)"
        )
    if self.resume_awaiting:
        lines.append(
            f"  resume awaiting:     {len(self.resume_awaiting)} "
            "(deliverables present; re-run deterministic check only)"
        )
    if self.stale_removed:
        lines.append(
            f"  incomplete removed:  {len(self.stale_removed)} "
            f"({', '.join(sorted(self.stale_removed)[:3])}"
            f"{', ...' if len(self.stale_removed) > 3 else ''})"
        )
    if self.pending and self.full_ranking:
        ranks = [e.get("rank") for e in self.pending]
        span = f" (ranks {ranks[0]}–{ranks[-1]})" if ranks[0] is not None else ""
    else:
        span = ""
    lines.append(f"  to build now:        {len(self.pending)}{span}")
    if self.deferred:
        lines.append(
            f"  left for later jobs: {self.deferred} (--limit {self.limit}; "
            "resubmit to continue down the order)"
        )
    return "\n".join(lines)

manifest_path

manifest_path(cfg: MineConfig) -> Path

Return the build stage's append-only manifest path.

Source code in abc_mine/stages/build.py
def manifest_path(cfg: MineConfig) -> Path:
    """Return the build stage's append-only manifest path."""
    return cfg.build_dir / MANIFEST_NAME

attempts_path

attempts_path(cfg: MineConfig) -> Path

Return the build stage's attempt log path.

Source code in abc_mine/stages/build.py
def attempts_path(cfg: MineConfig) -> Path:
    """Return the build stage's attempt log path."""
    return cfg.build_dir / ATTEMPTS_NAME

group_dir

group_dir(cfg: MineConfig) -> Path

Return the emitted task-group directory.

Source code in abc_mine/stages/build.py
def group_dir(cfg: MineConfig) -> Path:
    """Return the emitted task-group directory."""
    return cfg.tasks_dir / cfg.group_id

task_id

task_id(one_line: str, sha: str) -> str

Build a stable, filesystem-safe task id from a description and SHA.

The SHA suffix guarantees uniqueness even when two commits carry identical descriptions, which is common in histories with templated commit subjects.

Source code in abc_mine/stages/build.py
def task_id(one_line: str, sha: str) -> str:
    """Build a stable, filesystem-safe task id from a description and SHA.

    The SHA suffix guarantees uniqueness even when two commits carry identical
    descriptions, which is common in histories with templated commit subjects.
    """
    slug = slugify(one_line or "task", max_length=56)
    return f"{slug}-{sha[:8]}" if slug else f"task-{sha[:8]}"

read_manifest

read_manifest(path: Path) -> list[dict[str, Any]]

Read every manifest entry, skipping malformed lines.

Source code in abc_mine/stages/build.py
def read_manifest(path: Path) -> list[dict[str, Any]]:
    """Read every manifest entry, skipping malformed lines."""
    if not path.is_file():
        return []
    entries: list[dict[str, Any]] = []
    with open(path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                entries.append(json.loads(line))
            except json.JSONDecodeError:
                continue
    return entries

append_manifest

append_manifest(path: Path, entry: dict[str, Any]) -> None

Append one entry atomically.

O_APPEND makes a single small write atomic on POSIX, so parallel workers on a shared filesystem never interleave partial lines — which is what allows the manifest to be the source of truth without a lock.

Source code in abc_mine/stages/build.py
def append_manifest(path: Path, entry: dict[str, Any]) -> None:
    """Append one entry atomically.

    ``O_APPEND`` makes a single small write atomic on POSIX, so parallel workers on
    a shared filesystem never interleave partial lines — which is what allows the
    manifest to be the source of truth without a lock.
    """
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "a") as f:
        f.write(json.dumps(entry, sort_keys=True) + "\n")

record_usage_fields

record_usage_fields(build_dir: Path, tid: str, included: Sequence[Segment], discarded: Sequence[Segment], prior_records: Sequence[dict[str, Any]]) -> dict[str, Any]

Return the usage fields of one manifest record for tid.

usage sums the segments this outcome builds on. usage_discarded sums the spend whose work was thrown away: discarded segments plus any telemetry directory for the task that no earlier record accounts for (an agent whose save was abandoned, say). A label counts as accounted for once a finished (ok/failed) record included it or any record discarded it, so each discarded run is charged exactly once.

Source code in abc_mine/stages/build.py
def record_usage_fields(
    build_dir: Path,
    tid: str,
    included: Sequence[save_mod.Segment],
    discarded: Sequence[save_mod.Segment],
    prior_records: Sequence[dict[str, Any]],
) -> dict[str, Any]:
    """Return the usage fields of one manifest record for ``tid``.

    ``usage`` sums the segments this outcome builds on. ``usage_discarded`` sums
    the spend whose work was thrown away: ``discarded`` segments plus any
    telemetry directory for the task that no earlier record accounts for (an
    agent whose save was abandoned, say). A label counts as accounted for once a
    finished (``ok``/``failed``) record included it or any record discarded it,
    so each discarded run is charged exactly once.
    """
    labels = [seg.telemetry for seg in included if seg.telemetry]
    claimed: set[str] = set(labels)
    for rec in prior_records:
        if rec.get("task_id") != tid:
            continue
        claimed.update(rec.get("discarded_labels") or ())
        if rec.get("status") in ("ok", "failed"):
            claimed.update(rec.get("segment_labels") or ())
    dropped = [seg.usage for seg in discarded]
    dropped_labels = [seg.telemetry for seg in discarded if seg.telemetry]
    claimed.update(dropped_labels)
    for run in telemetry_mod.load_runs(build_dir, tid):
        if run["label"] in claimed:
            continue
        dropped.append(run)
        dropped_labels.append(run["label"])
    fields: dict[str, Any] = {
        "usage": telemetry_mod.merge(seg.usage for seg in included),
        "segment_labels": labels,
    }
    if dropped:
        fields["usage_discarded"] = telemetry_mod.merge(dropped)
        fields["discarded_labels"] = dropped_labels
    return fields

latest_status

latest_status(path: Path) -> dict[str, str]

Return each task's latest manifest status (latest-entry-wins).

Source code in abc_mine/stages/build.py
def latest_status(path: Path) -> dict[str, str]:
    """Return each task's latest manifest status (latest-entry-wins)."""
    latest: dict[str, str] = {}
    for entry in read_manifest(path):
        tid = entry.get("task_id")
        if tid:
            latest[str(tid)] = str(entry.get("status", ""))
    return latest

completed_tasks

completed_tasks(path: Path) -> set[str]

Return task ids whose latest manifest entry is ok.

Latest-entry-wins: a task that failed and was later rebuilt successfully counts as done, and one that was ok but failed on a later forced rebuild does not. An unfinished or awaiting_check task is NOT complete: it must be resumed, so it is excluded here exactly as a plain failure would be.

Source code in abc_mine/stages/build.py
def completed_tasks(path: Path) -> set[str]:
    """Return task ids whose **latest** manifest entry is ``ok``.

    Latest-entry-wins: a task that failed and was later rebuilt successfully counts
    as done, and one that was ``ok`` but failed on a later forced rebuild does not.
    An ``unfinished`` or ``awaiting_check`` task is NOT complete: it must be
    resumed, so it is excluded here exactly as a plain failure would be.
    """
    return {tid for tid, status in latest_status(path).items() if status == "ok"}

saved_tasks

saved_tasks(path: Path) -> dict[str, str]

Return task ids whose latest status is a resumable saved state.

Maps task_id -> status where status is unfinished or awaiting_check. These are the tasks a resume must pick up (and which do NOT count as attempts).

The saved state itself must still be on disk: a resume consumes it, so a record whose state is gone (resumed, then killed before a new save) is an unsaved leftover and is rebuilt from scratch.

Source code in abc_mine/stages/build.py
def saved_tasks(path: Path) -> dict[str, str]:
    """Return task ids whose latest status is a resumable saved state.

    Maps ``task_id -> status`` where status is ``unfinished`` or
    ``awaiting_check``. These are the tasks a resume must pick up (and which do
    NOT count as attempts).

    The saved state itself must still be on disk: a resume consumes it, so a
    record whose state is gone (resumed, then killed before a new save) is an
    unsaved leftover and is rebuilt from scratch.
    """
    from .save import RESUMABLE_STATUSES, STATE_JSON, saved_dir

    return {
        tid: status
        for tid, status in latest_status(path).items()
        if status in RESUMABLE_STATUSES
        and (saved_dir(path.parent, tid) / STATE_JSON).is_file()
    }

cumulative_budget_exhausted

cumulative_budget_exhausted(cumulative_seconds: float, hard_limit: int | None) -> bool

Return True iff the cumulative agent time has reached the hard limit.

hard_limit (execution.timeout_seconds) is a cap on agent wall time summed across every interrupted-and-resumed segment — queue, save, and check time never count. A None limit means uncapped. When the accumulated agent time meets or exceeds the limit, the task is a hard failed (and consumes an attempt) rather than being saved for yet another resume: a commit that has already spent its whole budget without finishing will not finish on a retry.

Source code in abc_mine/stages/build.py
def cumulative_budget_exhausted(
    cumulative_seconds: float, hard_limit: int | None
) -> bool:
    """Return True iff the cumulative agent time has reached the hard limit.

    ``hard_limit`` (``execution.timeout_seconds``) is a cap on *agent* wall time
    summed across every interrupted-and-resumed segment — queue, save, and check
    time never count. A ``None`` limit means uncapped. When the accumulated agent
    time meets or exceeds the limit, the task is a hard ``failed`` (and consumes
    an attempt) rather than being saved for yet another resume: a commit that has
    already spent its whole budget without finishing will not finish on a retry.
    """
    return hard_limit is not None and cumulative_seconds >= hard_limit

remaining_agent_budget

remaining_agent_budget(cumulative_seconds: float, hard_limit: int | None) -> int | None

Return the agent time left before the hard limit, or None if uncapped.

Always at least 1 second so a resume is never launched with a zero/negative timeout; the start-of-segment :func:cumulative_budget_exhausted check is what refuses to launch at all once the budget is spent.

Source code in abc_mine/stages/build.py
def remaining_agent_budget(
    cumulative_seconds: float, hard_limit: int | None
) -> int | None:
    """Return the agent time left before the hard limit, or None if uncapped.

    Always at least 1 second so a resume is never launched with a zero/negative
    timeout; the start-of-segment :func:`cumulative_budget_exhausted` check is
    what refuses to launch at all once the budget is spent.
    """
    if hard_limit is None:
        return None
    return max(1, int(hard_limit - cumulative_seconds))

decide_verifier_result

decide_verifier_result(output: str, returncode: int | None) -> str

Decide PASS/FAIL from verifier output, matching abc-runner exactly.

The last line whose stripped content is exactly PASS or FAIL wins, and PASS additionally requires a zero exit status. Both halves matter: a script that prints PASS then dies in cleanup has not passed, and a bare successful exit with no status line is not a pass either.

This mirrors abc-runner's own logic deliberately. If the two disagreed, a task could satisfy this stage's polarity check and then be graded differently in production — the exact failure this check exists to prevent.

Source code in abc_mine/stages/build.py
def decide_verifier_result(output: str, returncode: int | None) -> str:
    """Decide ``PASS``/``FAIL`` from verifier output, matching abc-runner exactly.

    The **last** line whose stripped content is exactly ``PASS`` or ``FAIL`` wins,
    and ``PASS`` additionally requires a zero exit status. Both halves matter: a
    script that prints ``PASS`` then dies in cleanup has not passed, and a bare
    successful exit with no status line is not a pass either.

    This mirrors abc-runner's own logic deliberately. If the two disagreed, a task
    could satisfy this stage's polarity check and then be graded differently in
    production — the exact failure this check exists to prevent.
    """
    statuses = [
        line.strip() for line in output.splitlines() if line.strip() in {"PASS", "FAIL"}
    ]
    final = statuses[-1] if statuses else "FAIL"
    if final == "PASS" and (returncode is None or returncode == 0):
        return "PASS"
    return "FAIL"

validate_task_dir

validate_task_dir(task_dir: Path) -> list[str]

Return the missing components of an emitted task directory.

Source code in abc_mine/stages/build.py
def validate_task_dir(task_dir: Path) -> list[str]:
    """Return the missing components of an emitted task directory."""
    missing: list[str] = []
    for name in (OUT_PROMPT, OUT_BUILD_ENV, "workspace", OUT_VERIFY):
        if not (task_dir / name).exists():
            missing.append(name)
    return missing

run_verifier_against_tree

run_verifier_against_tree(cfg: MineConfig, *, sandbox: Any, verifier: Path, tree: Path, log_file: Path, scratch: Path) -> str

Run verifier against tree the way the real grader will.

Reproduces the grading environment faithfully, which is the entire point:

  • the code tree is bind-mounted at :data:GRADING_WORKSPACE and is $ABC_RUNNER_WORKSPACE;
  • the verifier is staged outside that mount, as the grader does;
  • nothing that existed for the agent's convenience during authoring is present.

A verifier that quietly depends on an authoring-time path therefore fails here, where it is cheap to discover, rather than in production.

The tree is hard-linked rather than copied where the filesystem permits: source trees are large, this runs twice per task, and a verifier that mutates its input still must not disturb the original.

Source code in abc_mine/stages/build.py
def run_verifier_against_tree(
    cfg: MineConfig,
    *,
    sandbox: Any,
    verifier: Path,
    tree: Path,
    log_file: Path,
    scratch: Path,
) -> str:
    """Run ``verifier`` against ``tree`` the way the real grader will.

    Reproduces the grading environment faithfully, which is the entire point:

    - the code tree is bind-mounted at :data:`GRADING_WORKSPACE` and **is**
      ``$ABC_RUNNER_WORKSPACE``;
    - the verifier is staged **outside** that mount, as the grader does;
    - nothing that existed for the agent's convenience during authoring is
      present.

    A verifier that quietly depends on an authoring-time path therefore fails
    *here*, where it is cheap to discover, rather than in production.

    The tree is hard-linked rather than copied where the filesystem permits: source
    trees are large, this runs twice per task, and a verifier that mutates its input
    still must not disturb the original.
    """
    stage = scratch / "verify"
    if stage.exists():
        shutil.rmtree(stage)
    stage.mkdir(parents=True)

    tree_copy = stage / "tree"
    try:
        shutil.copytree(tree, tree_copy, copy_function=os.link)
    except (OSError, shutil.Error):
        if tree_copy.exists():
            shutil.rmtree(tree_copy)
        shutil.copytree(tree, tree_copy)

    verify_dir = stage / "verification"
    verify_dir.mkdir()
    staged_verifier = verify_dir / "verify_solution.sh"
    shutil.copy2(verifier, staged_verifier)
    staged_verifier.chmod(0o755)

    from automaton.sandbox import BindMount

    log_file.parent.mkdir(parents=True, exist_ok=True)
    verifier_in = GRADING_VERIFY_ROOT / "verify_solution.sh"
    try:
        returncode = sandbox.run_command(
            cfg.container.image,
            ["bash", str(verifier_in)],
            cwd=GRADING_WORKSPACE,
            env_vars={
                "ABC_RUNNER_WORKSPACE": str(GRADING_WORKSPACE),
                "ABC_RUNNER_TASK_ENV": str(GRADING_WORKSPACE / "abc-runner-task-env"),
            },
            bind_mounts=[
                BindMount(tree_copy, GRADING_WORKSPACE),
                BindMount(verify_dir, GRADING_VERIFY_ROOT),
            ],
            log_file=log_file,
            network=False,
            check=False,
        )
    finally:
        shutil.rmtree(stage, ignore_errors=True)

    output = log_file.read_text(errors="replace") if log_file.is_file() else ""
    return decide_verifier_result(output, returncode)

write_group_yaml

write_group_yaml(cfg: MineConfig) -> Path

Write the abc-runner group.yaml for the emitted task group.

Source code in abc_mine/stages/build.py
def write_group_yaml(cfg: MineConfig) -> Path:
    """Write the abc-runner ``group.yaml`` for the emitted task group."""
    dest = group_dir(cfg)
    dest.mkdir(parents=True, exist_ok=True)
    path = dest / "group.yaml"
    path.write_text(
        yaml.safe_dump(
            {
                "id": cfg.group_id,
                "name": cfg.codebase.name,
                "description": (
                    cfg.codebase.group_description
                    or f"Benchmarks mined from the {cfg.codebase.name} git history."
                ),
                "container_template": cfg.group_id,
            },
            sort_keys=False,
            default_flow_style=False,
        )
    )
    return path

plan

plan(cfg: MineConfig, *, only: Sequence[str] = (), force: bool = False, sweep: bool = False, limit: int | None = None) -> BuildPlan

Compute the work list, in rank order.

Read-only unless sweep is set, so every MPI rank derives an identical plan. Only rank 0 should pass sweep=True, since removing directories concurrently with workers reading them would be a race.

limit caps how many commits this invocation starts, taken from the top of the order after skipping those already built or out of attempts.

Source code in abc_mine/stages/build.py
def plan(
    cfg: MineConfig,
    *,
    only: Sequence[str] = (),
    force: bool = False,
    sweep: bool = False,
    limit: int | None = None,
) -> BuildPlan:
    """Compute the work list, in rank order.

    Read-only unless ``sweep`` is set, so every MPI rank derives an identical plan.
    Only rank 0 should pass ``sweep=True``, since removing directories concurrently
    with workers reading them would be a race.

    ``limit`` caps how many commits this invocation starts, taken from the top of
    the order after skipping those already built or out of attempts.
    """
    if limit is not None and limit < 1:
        raise rank_stage.RankError(f"--limit must be >= 1, got {limit}")
    shortlist = rank_stage.load_shortlist(cfg)
    full = bool(shortlist.get("complete"))
    selected = sorted(
        (e for e in shortlist.get("selected", []) if e.get("sha")),
        key=lambda e: e.get("rank") or 0,
    )

    if only:
        selected = [
            e for e in selected if any(str(e["sha"]).startswith(w) for w in only)
        ]

    done = set() if force else completed_tasks(manifest_path(cfg))
    spent = set() if force else set(exhausted_items(attempts_path(cfg), cfg.execution.max_attempts))
    saved = {} if force else saved_tasks(manifest_path(cfg))
    planned = {task_id(e.get("one_line", ""), e["sha"]): e for e in selected}

    # A saved task overrides 'spent'/'done' classification: an unfinished or
    # awaiting-check save is neither finished nor an attempt, so it is eligible.
    eligible = [
        (tid, entry)
        for tid, entry in planned.items()
        if tid not in done and (tid in saved or tid not in spent)
    ]
    # Resume first: saved items ahead of fresh work, each group still in rank
    # order (so an allocation drains its backlog before starting new commits).
    eligible.sort(key=lambda pair: (pair[0] not in saved, (planned[pair[0]].get("rank") or 0)))
    chosen = eligible if limit is None else eligible[:limit]
    pending = [entry for _, entry in chosen]
    chosen_ids = {tid for tid, _ in chosen}

    resume_unfinished = [t for t in chosen_ids if saved.get(t) == "unfinished"]
    resume_awaiting = [t for t in chosen_ids if saved.get(t) == "awaiting_check"]

    stale: list[str] = []
    if sweep:
        # Only directories this invocation will rebuild; a commit deferred to a
        # later job keeps whatever is on disk until that job starts it. Saved
        # tasks are preserved (their task dir may hold awaiting-check
        # deliverables). Unsaved leftovers under unfinished/ (interrupted saves)
        # are removed so they are rebuilt from scratch, not trusted.
        stale = _sweep_incomplete(
            group_dir(cfg), chosen_ids, done | set(saved), force=force
        )
        stale += save_mod.sweep_staging(cfg.build_dir)
        for orphan in save_mod.orphaned_saved_dirs(cfg.build_dir, set(saved)):
            save_mod.discard_saved_state(cfg.build_dir, orphan)
            stale.append(f"unfinished/{orphan}")

    return BuildPlan(
        selected=selected,
        pending=pending,
        already_done=sum(1 for tid in planned if tid in done),
        stale_removed=stale,
        full_ranking=full,
        exhausted=sum(1 for tid in planned if tid in spent and tid not in done and tid not in saved),
        limit=limit,
        deferred=len(eligible) - len(pending),
        resume_unfinished=resume_unfinished,
        resume_awaiting=resume_awaiting,
    )

make_worker

make_worker(cfg: MineConfig, pack: PromptPack, model: dict[str, str], *, dry_run: bool = False) -> Callable[[dict[str, Any]], ItemResult]

Build the per-commit construction worker.

Source code in abc_mine/stages/build.py
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
def make_worker(
    cfg: MineConfig,
    pack: PromptPack,
    model: dict[str, str],
    *,
    dry_run: bool = False,
) -> Callable[[dict[str, Any]], parallel.ItemResult]:
    """Build the per-commit construction worker."""
    automaton_cfg = sandbox_mod.build_automaton_config(model)
    agent = sandbox_mod.make_agent(automaton_cfg)
    harness = sandbox_mod.make_harness()
    summaries = {
        s.get("sha"): s for s in screen_stage.load_summaries(cfg) if s.get("sha")
    }
    manifest = manifest_path(cfg)
    attempts = attempts_path(cfg)
    log_root = cfg.build_dir / "logs"

    def worker(entry: dict[str, Any]) -> parallel.ItemResult:
        """Construct one abc-runner task end to end."""
        sha = entry["sha"]
        tid = task_id(entry.get("one_line", ""), sha)
        summary = summaries.get(sha)
        parent = (summary or {}).get("parent") or entry.get("parent") or f"{sha}^"
        started = time.monotonic()
        sandbox = sandbox_mod.make_sandbox(cfg, dry_run=dry_run)

        def _record(status: str, detail: str = "", **extra: Any) -> parallel.ItemResult:
            """Record the outcome durably, then return it.

            Only ``ok``/``failed`` are *finished* outcomes. ``failed`` consumes an
            attempt; the saved states ``unfinished``/``awaiting_check`` and a
            ``dry_run`` do not. A finished outcome also discards any saved state
            for the task so a later resume does not pick it up. The manifest
            record is the LAST durable write, after any two-phase save completed
            (the caller stages state before calling ``_record``).
            """
            record = {
                "task_id": tid,
                "sha": sha,
                "parent_sha": parent,
                "status": status,
                "detail": detail,
                "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                "model_id": model.get("model", ""),
                "seconds": round(time.monotonic() - started, 1),
                **_usage_fields(),
                **extra,
            }
            if status in ("ok", "failed"):
                save_mod.discard_saved_state(cfg.build_dir, tid)
            append_manifest(manifest, record)
            if status in ("ok", "failed"):
                record_attempt(
                    attempts, tid, status,
                    detail=detail, model_id=model.get("model", ""), sha=sha,
                )
            # The parallel-layer status: only 'ok'/'dry_run' are distinct; every
            # other outcome (including the saved states) maps to a non-ok result
            # so the batch summary and MPI success flag stay meaningful.
            parallel_status = (
                "ok" if status == "ok"
                else "dry_run" if status == "dry_run"
                else "failed"
            )
            return parallel.ItemResult(
                item_id=tid, status=parallel_status, detail=detail, data=record,
            )

        # Resume bookkeeping: a saved state carries the running total of agent
        # wall-clock already spent (only agent time counts toward the hard
        # cumulative limit — never queue, save, or check time).
        prior = save_mod.load_saved_state(cfg.build_dir, tid)
        resuming = prior is not None and prior.state == "unfinished"
        awaiting = prior is not None and prior.state == "awaiting_check"
        cumulative_prior = prior.cumulative_seconds if prior else 0.0
        prior_segments = list(prior.segments) if prior else []
        hard_limit = cfg.execution.timeout_seconds

        # Usage bookkeeping. ``included`` are the segments whose work this
        # attempt builds on; ``discarded`` are segments whose work was thrown
        # away (an unrestorable saved state). Rebound below as they change.
        included: list[save_mod.Segment] = list(prior_segments)
        discarded: list[save_mod.Segment] = []
        timing: dict[str, float] = {}

        def _usage_fields() -> dict[str, Any]:
            if dry_run:
                return {}
            fields = record_usage_fields(
                cfg.build_dir, tid, included, discarded, read_manifest(manifest),
            )
            phases = {k: round(v, 3) for k, v in timing.items()}
            phases["agent_seconds"] = round(sum(seg.seconds for seg in included), 3)
            fields["timing"] = phases
            return fields

        def _remaining_budget() -> int | None:
            return remaining_agent_budget(cumulative_prior, hard_limit)

        def _budget_exceeded() -> bool:
            return cumulative_budget_exhausted(cumulative_prior, hard_limit)

        def _run_polarity(
            sandbox: Any, scratch: Path, task_dir: Path, tree: Path,
            cutoff: Any, run_dir_for_logs: Path | None,
        ) -> parallel.ItemResult:
            """Layer-2 polarity re-check (deterministic; no agent)."""
            verifier = task_dir / OUT_VERIFY
            verify_logs = log_root / tid
            verify_logs.mkdir(parents=True, exist_ok=True)
            workspace = task_dir / "workspace"

            t0 = time.monotonic()
            fail_side = run_verifier_against_tree(
                cfg, sandbox=sandbox, verifier=verifier, tree=workspace,
                log_file=verify_logs / "verify_prechange.log",
                scratch=scratch / "polarity-pre",
            )
            timing["prechange_verify_seconds"] = time.monotonic() - t0
            repo_mod.checkout_detached(tree, sha)
            t0 = time.monotonic()
            pass_side = run_verifier_against_tree(
                cfg, sandbox=sandbox, verifier=verifier, tree=tree,
                log_file=verify_logs / "verify_postchange.log",
                scratch=scratch / "polarity-post",
            )
            timing["postchange_verify_seconds"] = time.monotonic() - t0
            polarity = {
                "prechange_result": fail_side,
                "postchange_result": pass_side,
                "workspace_object_count": getattr(cutoff, "object_count", None),
                "workspace_cutoff_sha": getattr(cutoff, "cutoff_sha", None),
            }
            if run_dir_for_logs is not None:
                sandbox_mod.preserve_logs(
                    run_dir_for_logs, log_root / tid / "agent",
                    keep_logs=cfg.execution.keep_logs,
                    failed=not (fail_side == "FAIL" and pass_side == "PASS"),
                )
            if fail_side != "FAIL":
                return _record(
                    "failed",
                    "verifier polarity is wrong: it should FAIL on the "
                    f"pre-change starting state but returned {fail_side}. "
                    "A verifier that passes without the change would certify "
                    "solvers that did nothing.",
                    **polarity,
                )
            if pass_side != "PASS":
                return _record(
                    "failed",
                    "verifier polarity is wrong: it should PASS on the "
                    f"post-change tree but returned {pass_side}. This usually "
                    "means the verifier depends on something available while "
                    "authoring but absent at grading time.",
                    **polarity,
                )
            return _record("ok", **polarity)

        with sandbox_mod.scratch_dir(cfg, f"lbm-build-{sha[:8]}-") as scratch:
            work = scratch / "work"
            run_dir = scratch / "run"
            work.mkdir(parents=True, exist_ok=True)
            source_name = Path(cfg.codebase.source_mount).name
            task_dir = group_dir(cfg) / tid

            # A full-history worktree: the agent must be able to move between the
            # change and its parent to validate polarity (Layer 1).
            with repo_mod.worktree(cfg.codebase.repo, sha, work / source_name) as tree:
                # -- awaiting-check resume: no agent, just re-run the check -----
                if awaiting:
                    t0 = time.monotonic()
                    try:
                        cutoff = repo_mod.build_cutoff_workspace(
                            cfg.codebase.repo, parent, task_dir / "workspace",
                            forbidden_sha=sha,
                        )
                    except repo_mod.CutoffError as exc:
                        return _record("failed", f"starting-state construction failed: {exc}")
                    finally:
                        timing["workspace_seconds"] = time.monotonic() - t0
                    incomplete = validate_task_dir(task_dir)
                    if incomplete:
                        return _record(
                            "failed",
                            f"task directory is incomplete: {', '.join(incomplete)}",
                        )
                    return _run_polarity(sandbox, scratch, task_dir, tree, cutoff, None)

                diff, _ = repo_mod.commit_diff(cfg.codebase.repo, sha)
                (work / "reference.diff").write_text(diff)
                (work / "commit_message.txt").write_text(
                    repo_mod.commit_message(cfg.codebase.repo, sha) + "\n"
                )

                # -- unfinished resume: restore the agent's tree and session ----
                # A fresh run lets OpenCode assign the session id (it refuses
                # `--session` for one that does not exist); a resume pins the
                # saved id, so a missing session fails instead of silently
                # starting over under a "you were interrupted" notice.
                oc_runtime = run_dir / "opencode-runtime"
                session_id = ""
                if signals_mod.stop_requested(cfg.build_dir):
                    # Stopping already: launch nothing and leave any saved state
                    # exactly as it is (nothing recorded, no attempt used).
                    return parallel.ItemResult(
                        item_id=tid, status="failed",
                        detail="not started: run is stopping",
                    )
                if resuming:
                    try:
                        save_mod.restore_agent_tree(
                            cfg.codebase.repo, parent, sha, cfg.build_dir, tid,
                            work / source_name,
                        )
                        session_id = save_mod.restore_session(
                            cfg.build_dir, tid, oc_runtime, work / sandbox_mod.OUT_DIRNAME,
                        )
                    except (save_mod.RestoreError, OSError) as exc:
                        # Unrestorable = unsaved: start from scratch, full budget.
                        print(f"  [resume] {tid}: cannot restore saved state ({exc}); "
                              "starting fresh", flush=True)
                        save_mod.discard_saved_state(cfg.build_dir, tid)
                        _reset_source_tree(work / source_name, sha)
                        shutil.rmtree(oc_runtime, ignore_errors=True)
                        resuming = False
                        cumulative_prior = 0.0
                        discarded = list(prior_segments)
                        prior_segments = []
                        included = []
                    else:
                        # The snapshot is consumed: from here only a new,
                        # completed save makes this task resumable again.
                        save_mod.discard_saved_state(cfg.build_dir, tid)
                        print(f"  [resume] {tid}: continuing session {session_id} "
                              f"({cumulative_prior:.0f}s used)", flush=True)

                # If we already exhausted the cumulative agent budget on prior
                # segments, this is a hard failure (counts as an attempt).
                if _budget_exceeded():
                    return _record(
                        "failed",
                        f"cumulative agent time limit ({hard_limit}s) reached "
                        f"across {len(prior_segments)} segment(s) without finishing.",
                    )

                prompt = _compose_prompt(cfg, pack, entry, summary)
                timing["setup_seconds"] = time.monotonic() - started
                seg_start_wall = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
                seg_since_ms = int(time.time() * 1000)
                seg_start = time.monotonic()
                run_result = sandbox_mod.run_agent(
                    cfg,
                    sandbox=sandbox,
                    harness=harness,
                    agent=agent,
                    work_dir=work,
                    run_dir=run_dir,
                    prompt_text=prompt,
                    opencode_runtime_dir=oc_runtime,
                    session_id=session_id,
                    resume=resuming,
                    timeout_seconds=_remaining_budget(),
                    budget_exhausted_callback=signals_mod.budget_callback(cfg.build_dir),
                    # Without this a stop is only noticed once the agent ends on
                    # its own, which is too late to save it.
                    stop_check=lambda: signals_mod.stop_requested(cfg.build_dir),
                )
                seg_seconds = time.monotonic() - seg_start

                if run_result.dry_run:
                    return _record("dry_run")

                # Kept for every segment, finished or not: spend is spend.
                seg_index = len(prior_segments) + 1
                seg_usage, seg_label = telemetry_mod.record_run(
                    cfg.build_dir, tid, run_result.run_dir,
                    keep=cfg.execution.keep_telemetry,
                    pricing=model.get("pricing"),
                    agent_seconds=seg_seconds,
                    label_prefix=f"seg{seg_index:02d}",
                    meta={"stage": "build", "item": tid, "sha": sha,
                          "segment": seg_index, "resumed": resuming,
                          "ok": run_result.ok, "model_id": model.get("model", "")},
                    opencode_db=oc_runtime / "opencode" / "data" / "opencode" / "opencode.db",
                    since_ms=seg_since_ms,
                )
                this_segment = save_mod.Segment(
                    model_id=model.get("model", ""),
                    base_url=model.get("base_url", ""),
                    opencode_version=save_mod._opencode_version(run_result.run_dir / "harness_output"),
                    started_at=seg_start_wall,
                    ended_at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                    seconds=seg_seconds,
                    usage=seg_usage,
                    telemetry=seg_label or "",
                )
                all_segments = prior_segments + [this_segment]
                included = all_segments
                cumulative = cumulative_prior + seg_seconds

                budget_stop = bool(getattr(run_result.execution, "budget_exhausted", False))
                stop = signals_mod.stop_requested(cfg.build_dir) or budget_stop

                # -- interrupted mid-turn: two-phase save as 'unfinished' -------
                # The agent did not finish cleanly (signal killed it or a stop was
                # requested). Save its state durably, THEN record. Unless we are
                # already over the hard limit, in which case it is a failure.
                if stop and not run_result.ok:
                    if cumulative_budget_exhausted(cumulative, hard_limit):
                        return _record(
                            "failed",
                            f"cumulative agent time limit ({hard_limit}s) reached; "
                            "interrupted and not finished.",
                        )
                    print(f"  [save] {tid}: saving unfinished agent state", flush=True)
                    draft = {
                        name: run_result.out_path(*name.split("/"))
                        for name in (OUT_PROMPT, OUT_BUILD_ENV, OUT_VERIFY)
                    }
                    try:
                        saved_meta = save_mod.save_agent_state(
                            cfg.build_dir, task_id=tid, sha=sha, parent_sha=parent,
                            state="unfinished",
                            tree=work / source_name,
                            session_store=oc_runtime / "opencode",
                            session_id=session_id,
                            draft_deliverables=draft,
                            cumulative_seconds=cumulative,
                            segments=all_segments,
                        )
                    except Exception as exc:  # noqa: BLE001
                        # No record: unsaved, rebuilt from scratch on resume.
                        print(f"  [save] {tid}: save abandoned ({exc}); task is unsaved",
                              flush=True)
                        return parallel.ItemResult(
                            item_id=tid, status="failed",
                            detail=f"interrupted; save abandoned: {exc}",
                        )
                    session_id = saved_meta.session_id
                    print(f"  [save] {tid}: saved unfinished ({cumulative:.0f}s cumulative)", flush=True)
                    return _record(
                        "unfinished",
                        "agent interrupted; state saved for resume",
                        cumulative_seconds=round(cumulative, 1),
                        session_id=session_id,
                    )

                if not run_result.ok:
                    # Genuine agent failure (not a stop). If the per-agent timeout
                    # fired because the cumulative budget ran out, it is a failure
                    # and consumes an attempt, as before.
                    sandbox_mod.preserve_logs(
                        run_result.run_dir, log_root / tid,
                        keep_logs=cfg.execution.keep_logs, failed=True,
                    )
                    return _record(
                        "failed", run_result.detail or "agent execution failed"
                    )

                # Agent ended its own turn: collect the three deliverables.
                if task_dir.exists():
                    shutil.rmtree(task_dir)
                (task_dir / "verification").mkdir(parents=True, exist_ok=True)

                authored = {
                    OUT_PROMPT: task_dir / OUT_PROMPT,
                    OUT_BUILD_ENV: task_dir / OUT_BUILD_ENV,
                    OUT_VERIFY: task_dir / OUT_VERIFY,
                }
                for name, dest in authored.items():
                    src = run_result.out_path(*name.split("/"))
                    if src.is_file():
                        shutil.copy2(src, dest)
                        if name.endswith(".sh"):
                            dest.chmod(0o755)

                missing = [n for n, d in authored.items() if not d.is_file()]
                if missing:
                    sandbox_mod.preserve_logs(
                        run_result.run_dir, log_root / tid,
                        keep_logs=cfg.execution.keep_logs, failed=True,
                    )
                    return _record(
                        "failed",
                        f"agent did not write: {', '.join(missing)}",
                    )

                # Build the starting state deterministically (no agent).
                workspace = task_dir / "workspace"
                t0 = time.monotonic()
                try:
                    cutoff = repo_mod.build_cutoff_workspace(
                        cfg.codebase.repo, parent, workspace, forbidden_sha=sha
                    )
                except repo_mod.CutoffError as exc:
                    timing["workspace_seconds"] = time.monotonic() - t0
                    sandbox_mod.preserve_logs(
                        run_result.run_dir, log_root / tid,
                        keep_logs=cfg.execution.keep_logs, failed=True,
                    )
                    return _record("failed", f"starting-state construction failed: {exc}")
                timing["workspace_seconds"] = time.monotonic() - t0

                incomplete = validate_task_dir(task_dir)
                if incomplete:
                    return _record(
                        "failed", f"task directory is incomplete: {', '.join(incomplete)}"
                    )

                # The agent finished its turn and deliverables are present. If a
                # stop was requested, the deterministic check is what remains, so
                # save as 'awaiting_check' and re-run only the check on resume —
                # never the agent again.
                if stop:
                    print(f"  [save] {tid}: deliverables present; saving awaiting-check", flush=True)
                    save_mod.save_agent_state(
                        cfg.build_dir, task_id=tid, sha=sha, parent_sha=parent,
                        state="awaiting_check",
                        tree=work / source_name,
                        session_store=None,
                        session_id=session_id,
                        draft_deliverables={},
                        cumulative_seconds=cumulative,
                        segments=all_segments,
                    )
                    return _record(
                        "awaiting_check",
                        "agent finished; verification deferred to resume",
                        cumulative_seconds=round(cumulative, 1),
                    )

                # -- Layer 2: independent polarity re-check ---------------------
                return _run_polarity(sandbox, scratch, task_dir, tree, cutoff, run_result.run_dir)

    return worker

run

run(cfg: MineConfig, pack: PromptPack, model: dict[str, str], *, dry_run: bool = False, only: Sequence[str] = (), force: bool = False, progress: bool = True, limit: int | None = None) -> BatchOutcome

Execute the build stage, building commits in rank order.

limit caps how many commits this invocation starts (see :func:plan).

Source code in abc_mine/stages/build.py
def run(
    cfg: MineConfig,
    pack: PromptPack,
    model: dict[str, str],
    *,
    dry_run: bool = False,
    only: Sequence[str] = (),
    force: bool = False,
    progress: bool = True,
    limit: int | None = None,
) -> parallel.BatchOutcome:
    """Execute the build stage, building commits in rank order.

    ``limit`` caps how many commits this invocation starts (see :func:`plan`).
    """
    rank_, size = parallel.mpi_rank_size()
    is_rank_zero = rank_ == 0

    # Destructive setup on one rank only, then a barrier so no worker reads a
    # directory another rank is deleting.
    work_plan = plan(cfg, only=only, force=force, sweep=is_rank_zero, limit=limit)
    if is_rank_zero:
        cfg.build_dir.mkdir(parents=True, exist_ok=True)
        # A fresh invocation must not inherit a stop flag left behind by a
        # previous (interrupted) run, or it would re-save everything without
        # working. Clear it on the owning rank, before the barrier below so no
        # other rank observes the stale flag.
        save_mod.clear_stop(cfg.build_dir)
        write_group_yaml(cfg)
        if progress:
            print(work_plan.describe())
            print()

    if cfg.execution.parallel == "mpi" and size > 1:
        usable, _ = parallel.mpi_available()
        if usable:
            from mpi4py import MPI

            MPI.COMM_WORLD.Barrier()

    # Install stop handlers on every rank's main thread so SIGUSR1 (Slurm's
    # early warning) and SIGTERM both request a cooperative run-wide stop. This
    # must run after the barrier so the flag was already cleared.
    signals_mod.install(cfg.build_dir)

    if not work_plan.pending:
        return parallel.BatchOutcome(results=[], is_primary=is_rank_zero)

    worker = make_worker(cfg, pack, model, dry_run=dry_run)

    def on_result(result: parallel.ItemResult, index: int, total: int) -> None:
        """Report one completed task."""
        if not progress:
            return
        if result.status == "ok":
            tail = "ok"
        elif result.status == "dry_run":
            tail = "dry run"
        else:
            tail = f"FAILED: {result.detail.splitlines()[0][:70] if result.detail else ''}"
        print(f"  [{index:>3}/{total}] {result.item_id}  {tail}", flush=True)

    return parallel.run_batch(
        work_plan.pending,
        worker,
        backend=cfg.execution.parallel,
        workers=cfg.execution.workers,
        scratch_dir=cfg.execution.scratch_dir,
        run_id=cfg.run_id,
        on_result=on_result,
        # Opt-in cooperative stop: once a run-wide stop is requested (signal or
        # budget exhaustion), the scheduler stops handing out fresh commits.
        # In-flight agents still finish/save via the worker's own stop handling.
        stop_check=lambda: signals_mod.stop_requested(cfg.build_dir),
    )

summarize

summarize(cfg: MineConfig) -> dict[str, Any]

Return aggregate statistics over emitted tasks, from the manifest.

Source code in abc_mine/stages/build.py
def summarize(cfg: MineConfig) -> dict[str, Any]:
    """Return aggregate statistics over emitted tasks, from the manifest."""
    entries = read_manifest(manifest_path(cfg))
    latest: dict[str, dict[str, Any]] = {}
    for entry in entries:
        tid = entry.get("task_id")
        if tid:
            latest[str(tid)] = entry

    counts: dict[str, int] = {}
    for entry in latest.values():
        status = str(entry.get("status", "unknown"))
        counts[status] = counts.get(status, 0) + 1

    # Records of a task are cumulative-per-attempt, so the fallback (for tasks
    # without persisted telemetry) sums each finished attempt plus the latest.
    fallback: dict[str, dict[str, Any]] = {}
    for entry in entries:
        tid = str(entry.get("task_id") or "")
        if not tid or not (entry.get("usage") or entry.get("usage_discarded")):
            continue
        if entry.get("status") in ("ok", "failed") or entry is latest.get(tid):
            fallback.setdefault(tid, {"_parts": []})["_parts"].extend(
                [entry.get("usage"), entry.get("usage_discarded")]
            )
    spend = telemetry_mod.stage_usage(
        cfg.build_dir,
        {tid: telemetry_mod.merge(v["_parts"]) for tid, v in fallback.items()},
    )

    return {
        "tasks": len(latest),
        "usage": spend["usage"],
        "usage_source": spend["source"],
        "usage_items": spend["items"],
        "usage_runs": spend["runs"],
        "by_status": dict(sorted(counts.items())),
        "ok": counts.get("ok", 0),
        "failed": counts.get("failed", 0),
        # Saved, resumable states: an interrupted agent whose work was captured
        # (``unfinished``) or that finished its turn with only the deterministic
        # check left (``awaiting_check``). Neither is done nor a failure.
        "unfinished": counts.get("unfinished", 0),
        "awaiting_check": counts.get("awaiting_check", 0),
        "saved": counts.get("unfinished", 0) + counts.get("awaiting_check", 0),
        "group_dir": str(group_dir(cfg)),
        "failures": [
            {"task_id": tid, "detail": entry.get("detail", "")}
            for tid, entry in sorted(latest.items())
            if entry.get("status") == "failed"
        ],
    }