#!/usr/bin/env bash
# Build and authenticate the hosted Clojure projection used by Core lowering.

set -euo pipefail

root="$(cd "$(dirname "$0")/.." && pwd)"
supervisor="$root/native-core/bin/run-bounded"
BEAGLE_DIR="$root"
source "$root/bin/_beagle-rust-supervisor"
module_helper="$root/bin/_beagle-core-compiler-module-cache.clj"
kill_grace="${BEAGLE_CORE_KILL_GRACE_SECONDS:-5}"
overall_timeout="${BEAGLE_CORE_OVERALL_TIMEOUT_SECONDS:-600}"
module_jobs="${BEAGLE_CORE_MODULE_JOBS:-}"
# The projection key names emitted bytes, not this script's scheduling and
# cache machinery. The canonical projection is source-location-free: diagnostic
# locations remain checker evidence and are not executable artifact identity.
projection_recipe_sha256="eec9758bd1e41a13a613bfd59088bbf40013db6e956519f23810fe1582a56b92"

sources=(
    native-core/src/native/core.bclj
    native-core/src/native/stages.bclj
    native-core/src/native/simd.bclj
    native-core/src/native/lower.bclj
    native-core/src/native/obligations.bclj
    native-core/src/native/c11.bclj
    native-core/src/native/slice.bclj
    native-core/src/native/unit_reuse.bclj
    native-core/src/native/unit_compile.bclj
    native-core/src/native/fold_c17.bclj
    native-core/src/native/body_c17.bclj
    native-core/src/native/body_slice.bclj
    native-core/src/native/qbe.bclj
)

if [[ "${1:-}" == "--list-sources" && $# -eq 1 ]]; then
    printf '%s\n' "${sources[@]}"
    exit 0
fi

out=""
log=""
cache_requested=0
print_key=0
cache_root="${BEAGLE_CORE_COMPILER_CACHE:-${XDG_CACHE_HOME:-${HOME:?HOME is required}/.cache}/beagle/core-compiler-projections}"
while [[ $# -gt 0 ]]; do
    case "$1" in
        --print-key)
            print_key=1
            shift
            ;;
        --out)
            [[ $# -ge 2 ]] || { echo "beagle core compiler projection: --out needs a directory" >&2; exit 2; }
            out="$2"
            shift 2
            ;;
        --out=*)
            out="${1#*=}"
            shift
            ;;
        --log)
            [[ $# -ge 2 ]] || { echo "beagle core compiler projection: --log needs a file" >&2; exit 2; }
            log="$2"
            shift 2
            ;;
        --log=*)
            log="${1#*=}"
            shift
            ;;
        --cache)
            cache_requested=1
            shift
            ;;
        --cache-root)
            [[ $# -ge 2 ]] || { echo "beagle core compiler projection: --cache-root needs a directory" >&2; exit 2; }
            cache_requested=1
            cache_root="$2"
            shift 2
            ;;
        --cache-root=*)
            cache_requested=1
            cache_root="${1#*=}"
            shift
            ;;
        *)
            echo "beagle core compiler projection: unknown option: $1" >&2
            exit 2
            ;;
    esac
done

[[ "$overall_timeout" =~ ^[1-9][0-9]*$ ]] || {
    echo "beagle core compiler projection: invalid overall build deadline" >&2
    exit 2
}
[[ "$kill_grace" =~ ^[1-9][0-9]*$ ]] || {
    echo "beagle core compiler projection: invalid kill grace" >&2
    exit 2
}
[[ -z "$module_jobs" || "$module_jobs" =~ ^[1-9][0-9]*$ ]] || {
    echo "beagle core compiler projection: invalid module job count" >&2
    exit 2
}
[[ "$cache_root" == /* ]] || {
    echo "beagle core compiler projection: cache root must be absolute" >&2
    exit 2
}
[[ -x "$supervisor" ]] || {
    echo "beagle core compiler projection: build supervisor is unavailable" >&2
    exit 2
}
[[ -f "$module_helper" ]] || {
    echo "beagle core compiler projection: module compiler helper is unavailable" >&2
    exit 2
}
command -v bb >/dev/null 2>&1 || {
    echo "beagle core compiler projection: bb is unavailable" >&2
    exit 2
}
if [[ "$print_key" == 1 ]]; then
    [[ -z "$out" && "$cache_requested" == 0 ]] || {
        echo "beagle core compiler projection: --print-key takes no other mode" >&2
        exit 2
    }
elif [[ "$cache_requested" == 1 ]]; then
    [[ -z "$out" ]] || { echo "beagle core compiler projection: --cache and --out are mutually exclusive" >&2; exit 2; }
    [[ "$cache_root" == /* ]] || { echo "beagle core compiler projection: cache root must be absolute" >&2; exit 2; }
else
    [[ -n "$out" ]] || { echo "beagle core compiler projection: --out is required" >&2; exit 2; }
    [[ "$out" == /* ]] || { echo "beagle core compiler projection: --out must be absolute" >&2; exit 2; }
    [[ ! -e "$out" ]] || { echo "beagle core compiler projection: --out already exists: $out" >&2; exit 2; }
fi

# Reporting the key spawns nothing and must stay cheap: every build asks for it
# before deciding whether the multi-minute construction is needed at all.
if [[ "$print_key" != 1 &&
      "${BEAGLE_CORE_COMPILER_PROJECTION_SUPERVISED:-0}" != 1 ]]; then
    rust_supervisor="$(beagle_resolve_rust_supervisor \
        'beagle core compiler projection' || true)"
    [[ -z "$rust_supervisor" ]] || supervisor="$rust_supervisor"
    supervised_args=()
    if [[ "$cache_requested" == 1 ]]; then
        supervised_args+=(--cache-root "$cache_root")
    else
        supervised_args+=(--out "$out")
        [[ -z "$log" ]] || supervised_args+=(--log "$log")
    fi
    exec "$supervisor" "$overall_timeout" "$kill_grace" -- \
        env BEAGLE_CORE_COMPILER_PROJECTION_SUPERVISED=1 "$0" \
        "${supervised_args[@]}"
fi

# The closure of a compiled projection: compiler-module sources, the checked-in
# self-host seed that parses/checks/emits them, and the deterministic assembly
# recipe. The hosted Racket compiler is deliberately not on this path.
write_input_manifest() {
    local destination="$1" relative digest_index input_index
    local -a inputs present_inputs present_flags digests
    inputs=("${sources[@]}"
            bin/beagle-core-compiler-projection
            bin/_beagle-core-compiler-module-cache.clj
            native-core/bin/run-bounded
            flake.nix flake.lock)
    # Presence is decided once and the hash list is built from that same
    # decision, so a file appearing or vanishing mid-scan cannot slide the
    # digests out of step with the names they label. Every build asks for this
    # key before deciding whether the multi-minute construction is needed, and
    # hashing a file at a time cost three processes each.
    present_inputs=()
    present_flags=()
    for relative in "${inputs[@]}"; do
        if [[ "$relative" == bin/beagle-core-compiler-projection ]]; then
            present_flags+=(2)
        elif [[ -f "$root/$relative" ]]; then
            present_flags+=(1)
            present_inputs+=("$root/$relative")
        else
            present_flags+=(0)
        fi
    done
    digests=()
    if ((${#present_inputs[@]} > 0)); then
        mapfile -t digests < <(sha256sum "${present_inputs[@]}" | awk '{print $1}')
        ((${#digests[@]} == ${#present_inputs[@]})) || {
            echo "beagle core compiler projection: hashed ${#digests[@]} of ${#present_inputs[@]} key inputs" >&2
            exit 2
        }
    fi
    {
        printf 'beagle-core-compiler-projection-input/v3\n'
        digest_index=0
        for input_index in "${!inputs[@]}"; do
            # An absent input is its own key value: dropping a file must move
            # the key rather than silently reproduce the key it had when
            # present.
            if [[ "${present_flags[$input_index]}" == 1 ]]; then
                printf '%s %s\n' "${inputs[$input_index]}" "${digests[$digest_index]}"
                digest_index=$((digest_index + 1))
            elif [[ "${present_flags[$input_index]}" == 2 ]]; then
                printf '%s %s\n' "${inputs[$input_index]}" "$projection_recipe_sha256"
            else
                printf '%s absent\n' "${inputs[$input_index]}"
            fi
        done
        find "$root/self-host/seed" -type f -name '*.clj' -print0 |
            LC_ALL=C sort -z | xargs -0 sha256sum |
            awk -v prefix="${#root}" \
                '{ print substr($0, 67 + prefix + 1), substr($0, 1, 64) }'
        printf 'bb %s\n' "$(realpath "$(command -v bb)")"
        printf 'bb-sha256 %s\n' \
            "$(sha256sum "$(realpath "$(command -v bb)")" | awk '{print $1}')"
    } >"$destination"
}

if [[ "$print_key" == 1 ]]; then
    key_work="$(mktemp -d "${TMPDIR:-/tmp}/beagle-core-projection-key.XXXXXX")"
    write_input_manifest "$key_work/input.manifest"
    sha256sum "$key_work/input.manifest" | awk '{print $1}'
    rm -rf "${key_work:?}"
    exit 0
fi

expected_modules() {
    for source in "${sources[@]}"; do
        basename "$source" .bclj
    done | sed 's/$/.clj/' | LC_ALL=C sort
}

validate_compiled_tree() {
    local compiled="$1" expected actual
    [[ -d "$compiled/native" && ! -L "$compiled" ]] || return 1
    expected="$(expected_modules)"
    actual="$(find "$compiled/native" -mindepth 1 -maxdepth 1 -type f \
        -printf '%f\n' | LC_ALL=C sort)"
    [[ "$actual" == "$expected" ]] || return 1
    ! find "$compiled" -mindepth 1 \( -type l -o ! -type d ! -type f \) \
        -print -quit | grep -q .
}

cache_entry_valid() {
    local entry="$1" key="$2" manifest_digest expected_names actual_names
    [[ -d "$entry" && ! -L "$entry" &&
       -f "$entry/input.manifest" && ! -L "$entry/input.manifest" &&
       -f "$entry/artifacts.sha256" && ! -L "$entry/artifacts.sha256" &&
       -f "$entry/READY" && ! -L "$entry/READY" ]] || return 1
    validate_compiled_tree "$entry/compiled" || return 1
    [[ "$(sha256sum "$entry/input.manifest" | awk '{print $1}')" == "$key" ]] || return 1
    manifest_digest="$(sha256sum "$entry/artifacts.sha256" | awk '{print $1}')"
    [[ "$(<"$entry/READY")" == \
       "beagle-core-compiler-projection/v1 $key $manifest_digest" ]] || return 1
    expected_names="$(awk '{ print $2 }' "$entry/artifacts.sha256" | LC_ALL=C sort)"
    actual_names="$(cd "$entry/compiled" && find . -type f -printf '%p\n' | LC_ALL=C sort)"
    [[ -n "$expected_names" && "$expected_names" == "$actual_names" ]] || return 1
    (cd "$entry/compiled" && sha256sum --check --strict ../artifacts.sha256 >/dev/null 2>&1)
}

module_build_order=(
    core stages obligations simd lower c11 slice unit_reuse unit_compile
    fold_c17 body_c17 qbe body_slice
)
declare -A module_dependencies=(
    [core]=""
    [stages]="core"
    [obligations]="core"
    [simd]="core stages"
    [lower]="core stages obligations"
    [c11]="core stages simd"
    [slice]="core stages obligations simd lower c11"
    [unit_reuse]="core stages obligations lower"
    [unit_compile]="core stages obligations lower unit_reuse"
    [fold_c17]="core"
    [body_c17]="core stages obligations simd fold_c17"
    [qbe]="core stages simd"
    [body_slice]="core stages obligations simd lower c11 slice fold_c17 body_c17 qbe"
)
declare -A module_sources=()
for source in "${sources[@]}"; do
    module_sources["$(basename "$source" .bclj)"]="$source"
done

write_module_recipe_manifest() {
    local destination="$1" bb_path
    bb_path="$(realpath "$(command -v bb)")"
    {
        printf 'beagle-core-compiler-module-recipe/v1\n'
        printf 'projection-recipe-sha256 %s\n' "$projection_recipe_sha256"
        printf 'helper-sha256 %s\n' "$(sha256sum "$module_helper" | awk '{print $1}')"
        find "$root/self-host/seed" -type f -name '*.clj' -print0 |
            LC_ALL=C sort -z | xargs -0 sha256sum |
            awk -v prefix="${#root}" \
                '{ print substr($0, 67 + prefix + 1), substr($0, 1, 64) }'
        printf 'bb %s\n' "$bb_path"
        printf 'bb-sha256 %s\n' "$(sha256sum "$bb_path" | awk '{print $1}')"
    } >"$destination"
}

write_module_input_manifest() {
    local destination="$1" module="$2" recipe_digest="$3" dependency entry
    {
        printf 'beagle-core-compiler-module-input/v1\n'
        printf 'recipe-sha256 %s\n' "$recipe_digest"
        printf 'module %s\n' "$module"
        printf 'source %s %s\n' "${module_sources[$module]}" \
            "$(sha256sum "$root/${module_sources[$module]}" | awk '{print $1}')"
        for dependency in ${module_dependencies[$module]}; do
            [[ -n "${module_entries[$dependency]:-}" ]] || {
                echo "beagle core compiler projection: provider is unavailable: $module needs $dependency" >&2
                return 1
            }
            entry="${module_entries[$dependency]}"
            printf 'provider-interface %s %s\n' "$dependency" \
                "$(sha256sum "$entry/interface.json" | awk '{print $1}')"
        done
    } >"$destination"
}

module_entry_valid() {
    local entry="$1" key="$2" manifest_digest expected actual
    [[ -d "$entry" && ! -L "$entry" ]] || return 1
    for expected in input.manifest artifact.clj surface.json interface.json \
            artifacts.sha256 READY; do
        [[ -f "$entry/$expected" && ! -L "$entry/$expected" ]] || return 1
    done
    actual="$(find "$entry" -mindepth 1 -maxdepth 1 -type f -printf '%f\n' |
        LC_ALL=C sort)"
    expected="$(printf '%s\n' READY artifact.clj artifacts.sha256 input.manifest \
        interface.json surface.json | LC_ALL=C sort)"
    [[ "$actual" == "$expected" ]] || return 1
    [[ "$(sha256sum "$entry/input.manifest" | awk '{print $1}')" == "$key" ]] ||
        return 1
    manifest_digest="$(sha256sum "$entry/artifacts.sha256" | awk '{print $1}')"
    [[ "$(<"$entry/READY")" == \
       "beagle-core-compiler-module/v1 $key $manifest_digest" ]] || return 1
    (cd "$entry" && sha256sum --check --strict artifacts.sha256 >/dev/null 2>&1)
}

module_ready() {
    local module="$1" dependency
    for dependency in ${module_dependencies[$module]}; do
        [[ "${module_status[$dependency]:-}" == done ]] || return 1
    done
}

build_module() {
    local module="$1" recipe_digest="$2" object_root="$3" fresh="$4"
    local entry="$5" key="$6" module_log="$7"
    local source dependency stage corrupt manifest_digest started ended elapsed
    local module_lock_fd
    local -a source_args surface_args
    source="${module_sources[$module]}"
    exec {module_lock_fd}>"$object_root/.locks/$key.lock"
    flock -x "$module_lock_fd"
    stage="$(mktemp "$object_root/.staging/locked.$module.XXXXXX")"
    write_module_input_manifest "$stage" "$module" "$recipe_digest"
    cmp -s "$fresh" "$stage" || {
        echo "beagle core compiler projection: module input changed before cache admission: $module" >&2
        return 1
    }
    rm -f "$stage"
    stage=""
    if module_entry_valid "$entry" "$key"; then
        rm -f "$fresh"
        printf 'HIT 0\n'
        return 0
    fi
    if [[ -e "$entry" ]]; then
        corrupt="$object_root/.staging/corrupt.$key.$$"
        mv "$entry" "$corrupt"
        rm -rf "${corrupt:?}"
    fi
    stage="$(mktemp -d "$object_root/.staging/module.$module.XXXXXX")"
    mv "$fresh" "$stage/input.manifest"
    source_args=()
    for dependency in "${sources[@]}"; do
        [[ "$dependency" == "$source" ]] ||
            source_args+=(--source "$root/$dependency")
    done
    surface_args=()
    for dependency in ${module_dependencies[$module]}; do
        surface_args+=(--surface \
            "$root/${module_sources[$dependency]}=${module_entries[$dependency]}/surface.json")
    done
    started="$(date +%s%N)"
    if ! bb -cp "$root/self-host/seed" "$module_helper" compile \
            "${source_args[@]}" "${surface_args[@]}" \
            --artifact "$stage/artifact.clj" \
            --surface-out "$stage/surface.json" \
            --interface-out "$stage/interface.json" \
            "$root/$source" >"$module_log" 2>&1; then
        echo "beagle core compiler projection: module compile failed: $module" >&2
        return 1
    fi
    ended="$(date +%s%N)"
    elapsed=$(( (ended - started + 999999999) / 1000000000 ))
    fresh="$(mktemp "$object_root/.staging/recheck.$module.XXXXXX")"
    write_module_input_manifest "$fresh" "$module" "$recipe_digest"
    cmp -s "$fresh" "$stage/input.manifest" || {
        echo "beagle core compiler projection: source closure changed while compiling $module" >&2
        return 1
    }
    rm -f "$fresh"
    (cd "$stage" && sha256sum artifact.clj interface.json surface.json \
        >artifacts.sha256)
    manifest_digest="$(sha256sum "$stage/artifacts.sha256" | awk '{print $1}')"
    printf 'beagle-core-compiler-module/v1 %s %s\n' \
        "$key" "$manifest_digest" >"$stage/READY"
    module_entry_valid "$stage" "$key" || {
        echo "beagle core compiler projection: staged module proof is invalid: $module" >&2
        return 1
    }
    mv "$stage" "$entry"
    printf 'MISS %s\n' "$elapsed"
}

build_projection() {
    local compiled="$1" build_log="$2" object_root="$3"
    local module dependency entry key fresh core_records generated
    local recipe_digest recipe_manifest
    local recipe_recheck projection_manifest projection_recheck
    local running_count done_count finished_pid finished_module job_rc
    local max_jobs module_log module_error module_report report_kind report_elapsed
    local -a running_pids failed_modules
    declare -gA module_entries=()
    declare -gA module_status=()
    declare -A pid_modules=() module_pids=() module_keys=()
    declare -A module_logs=() module_errors=() module_reports=()
    mkdir -p "$compiled/native" "$object_root/.locks" "$object_root/.staging"
    projection_manifest="$(mktemp "$object_root/.staging/projection.XXXXXX")"
    write_input_manifest "$projection_manifest"
    recipe_manifest="$(mktemp "$object_root/.staging/recipe.XXXXXX")"
    write_module_recipe_manifest "$recipe_manifest"
    recipe_digest="$(sha256sum "$recipe_manifest" | awk '{print $1}')"
    max_jobs="${module_jobs:-$(nproc)}"
    ((max_jobs <= ${#module_build_order[@]})) || max_jobs="${#module_build_order[@]}"
    echo "beagle core compiler projection: construction START (per-module, jobs=$max_jobs, overall build deadline=${overall_timeout}s)" >&2
    : >"$build_log"
    for module in "${module_build_order[@]}"; do
        module_status[$module]=pending
    done
    running_count=0
    done_count=0
    failed_modules=()
    while ((done_count < ${#module_build_order[@]})); do
        if ((${#failed_modules[@]} == 0)); then
            for module in "${module_build_order[@]}"; do
                ((running_count < max_jobs)) || break
                [[ "${module_status[$module]}" == pending ]] || continue
                module_ready "$module" || continue
                fresh="$(mktemp "$object_root/.staging/input.$module.XXXXXX")"
                write_module_input_manifest "$fresh" "$module" "$recipe_digest"
                key="$(sha256sum "$fresh" | awk '{print $1}')"
                entry="$object_root/$key"
                module_entries[$module]="$entry"
                module_keys[$module]="$key"
                module_log="$(mktemp "$object_root/.staging/log.$module.XXXXXX")"
                module_error="$(mktemp "$object_root/.staging/error.$module.XXXXXX")"
                module_report="$(mktemp "$object_root/.staging/report.$module.XXXXXX")"
                module_logs[$module]="$module_log"
                module_errors[$module]="$module_error"
                module_reports[$module]="$module_report"
                build_module "$module" "$recipe_digest" "$object_root" \
                    "$fresh" "$entry" "$key" "$module_log" \
                    >"$module_report" 2>"$module_error" &
                module_pids[$module]=$!
                pid_modules[$!]="$module"
                module_status[$module]=running
                running_count=$((running_count + 1))
                echo "beagle core compiler projection: module START $module" >&2
            done
        fi
        if ((running_count == 0)); then
            if ((${#failed_modules[@]} > 0)); then
                break
            fi
            echo "beagle core compiler projection: module dependency graph made no progress" >&2
            return 1
        fi
        running_pids=("${!pid_modules[@]}")
        finished_pid=""
        if wait -n -p finished_pid "${running_pids[@]}"; then
            job_rc=0
        else
            job_rc=$?
        fi
        finished_module="${pid_modules[$finished_pid]}"
        unset 'pid_modules[$finished_pid]'
        unset 'module_pids[$finished_module]'
        running_count=$((running_count - 1))
        if ((job_rc == 0)); then
            read -r report_kind report_elapsed <"${module_reports[$finished_module]}"
            module_status[$finished_module]=done
            done_count=$((done_count + 1))
            if [[ "$report_kind" == HIT ]]; then
                echo "beagle core compiler projection: module HIT $finished_module ${module_keys[$finished_module]}" >&2
            else
                echo "beagle core compiler projection: module MISS $finished_module ${module_keys[$finished_module]} seconds=$report_elapsed" >&2
            fi
        else
            module_status[$finished_module]=failed
            failed_modules+=("$finished_module")
            echo "beagle core compiler projection: module FAIL $finished_module exit=$job_rc" >&2
            sed -n '1,200p' "${module_errors[$finished_module]}" >&2
            sed -n '1,200p' "${module_logs[$finished_module]}" >&2
        fi
    done
    if ((${#failed_modules[@]} > 0)); then
        echo "beagle core compiler projection: failed modules: ${failed_modules[*]}" >&2
        return 1
    fi
    for module in "${module_build_order[@]}"; do
        cat "${module_logs[$module]}" >>"$build_log"
        rm -f "${module_logs[$module]}" "${module_errors[$module]}" \
            "${module_reports[$module]}"
        entry="${module_entries[$module]}"
        cp -- "$entry/artifact.clj" "$compiled/native/$module.clj"
        cmp -s "$entry/artifact.clj" "$compiled/native/$module.clj" || {
            echo "beagle core compiler projection: assembled module differs from authenticated object: $module" >&2
            return 1
        }
    done
    recipe_recheck="$(mktemp "$object_root/.staging/recipe-recheck.XXXXXX")"
    write_module_recipe_manifest "$recipe_recheck"
    cmp -s "$recipe_manifest" "$recipe_recheck" || {
        echo "beagle core compiler projection: module recipe changed during assembly" >&2
        return 1
    }
    projection_recheck="$(mktemp "$object_root/.staging/projection-recheck.XXXXXX")"
    write_input_manifest "$projection_recheck"
    cmp -s "$projection_manifest" "$projection_recheck" || {
        echo "beagle core compiler projection: projection input changed during assembly" >&2
        return 1
    }
    rm -f "$recipe_manifest" "$recipe_recheck" \
        "$projection_manifest" "$projection_recheck"
    core_records="$(sed -nE 's/.*\(defrecord ([^ ]+).*/\1/p' \
        "$compiled/native/core.clj" | tr '\n' ' ')"
    for module in stages simd lower obligations c11 slice fold_c17 body_c17 body_slice qbe; do
        generated="$compiled/native/$module.clj"
        [[ -f "$generated" ]] || continue
        sed -i 's/\[native\.core :as core\]/[native.core :as core :refer :all]/' "$generated"
        awk -v imp="(import '[native.core $core_records])" \
            '!seen && /^$/ { print imp; seen = 1 } { print }' \
            "$generated" >"$generated.tmp"
        mv "$generated.tmp" "$generated"
    done
    validate_compiled_tree "$compiled" || {
        echo "beagle core compiler projection: compiled module set is incomplete" >&2
        return 1
    }
    echo "beagle core compiler projection: construction END modules=${#sources[@]}" >&2
}

work=""
cleanup() {
    local rc=$?
    [[ -z "$work" || ! -d "$work" ]] || rm -rf "${work:?}"
    return "$rc"
}
trap cleanup EXIT

if [[ "$cache_requested" == 1 ]]; then
    mkdir -p "$cache_root/.locks" "$cache_root/.staging"
    work="$(mktemp -d "$cache_root/.staging/identity.XXXXXX")"
    write_input_manifest "$work/input.manifest"
    key="$(sha256sum "$work/input.manifest" | awk '{print $1}')"
    entry="$cache_root/$key"
    exec {lock_fd}>"$cache_root/.locks/$key.lock"
    echo "beagle core compiler projection: cache lock START $key" >&2
    flock -x "$lock_fd"
    echo "beagle core compiler projection: cache lock END $key" >&2
    if cache_entry_valid "$entry" "$key"; then
        echo "beagle core compiler projection: cache HIT $key" >&2
        printf '%s\n' "$entry/compiled"
        exit 0
    fi
    if [[ -e "$entry" ]]; then
        corrupt="$cache_root/.staging/corrupt.$key.$$"
        mv "$entry" "$corrupt"
        rm -rf "${corrupt:?}"
    fi
    rm -rf "${work:?}"
    work="$(mktemp -d "$cache_root/.staging/projection.XXXXXX")"
    write_input_manifest "$work/input.manifest"
    echo "beagle core compiler projection: cache MISS $key" >&2
    build_projection "$work/compiled" "$work/build.log" "$cache_root/modules"
    rm -f "$work/build.log"
    (cd "$work/compiled" && find . -type f -print0 | LC_ALL=C sort -z |
        xargs -0 sha256sum >"$work/artifacts.sha256")
    manifest_digest="$(sha256sum "$work/artifacts.sha256" | awk '{print $1}')"
    printf 'beagle-core-compiler-projection/v1 %s %s\n' \
        "$key" "$manifest_digest" >"$work/READY"
    cache_entry_valid "$work" "$key" || {
        echo "beagle core compiler projection: staged cache proof is invalid" >&2
        exit 1
    }
    mv "$work" "$entry"
    work=""
    echo "beagle core compiler projection: cache PUBLISHED $key" >&2
    printf '%s\n' "$entry/compiled"
    exit 0
fi

out_parent="$(dirname -- "$out")"
mkdir -p "$out_parent"
work="$(mktemp -d "$out_parent/.beagle-core-compiler-projection.XXXXXX")"
mkdir -p "$cache_root"
build_projection "$work/compiled" "${log:-$work/build.log}" "$cache_root/modules"
mv "$work/compiled" "$out"
