Skip to content
workspaceguardrails
  • Home
  • Open Source[4]
  • System Policies[0]
  • Git Hooks[32]
  • Anti-Patterns[303]
  • Hook Configs[22]
  • Sandbox Configs[27]
  • Tools & Scripts[11]
  • AI Governance[20]
  • LLM Gateway
  • Static Analysis
  • Playground
  • Integration Guide
  1. Home
  2. Tools & Scripts
    The Digital and AI Workspace Guardrails Platform2026 ◆ Independent AI Labs
    Skip to content
    workspaceguardrails
    • Home
    • Open Source[4]
    • System Policies[0]
    • Git Hooks[32]
    • Anti-Patterns[303]
    • Hook Configs[22]
    • Sandbox Configs[27]
    • Tools & Scripts[11]
    • AI Governance[20]
    • LLM Gateway
    • Static Analysis
    • Playground
    • Integration Guide
    1. Home
    2. Tools & Scripts
      The Digital and AI Workspace Guardrails Platform2026 ◆ Independent AI Labs
      Skip to content
      workspaceguardrails
      • Home
      • Open Source[4]
      • System Policies[0]
      • Git Hooks[32]
      • Anti-Patterns[303]
      • Hook Configs[22]
      • Sandbox Configs[27]
      • Tools & Scripts[11]
      • AI Governance[20]
      • LLM Gateway
      • Static Analysis
      • Playground
      • Integration Guide
      1. Home
      2. Tools & Scripts

        Tooling

        Scripts available in the workspace-ci repository for bootstrapping, auditing, and managing CI infrastructure across the workspace.

        11 of 11 scripts

        generate-hooks

        Generate native git hooks from .pre-commit-config.yaml.

        Hook Lifecycle
        Make target
        install-hooks

        generate-hooks

        scripts/generate-hooks

        generate-hooks: Generate native git hooks from .pre-commit-config.yaml.

        generate-hooks [--config PATH] [--output-dir PATH] [--dry-run]
        --config
        Path to .pre-commit-config.yaml (default: ./.pre-commit-config.yaml)
        --output-dir
        Directory to write hooks into (default: .git/hooks)
        --dry-run
        Print generated hooks to stdout without writing files

        Output: Writes executable bash scripts to .git/hooks/{pre-commit,commit-msg,pre-push}.

        #!/usr/bin/env bash
        # generate-hooks: Generate native git hooks from .pre-commit-config.yaml.
        set -euo pipefail
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _SCRIPT_DIR="$(cd "$(dirname "$_SELF")" && pwd)"
        _CI_ROOT="$(cd "$_SCRIPT_DIR/.." && pwd)"
        if ! source "$_CI_ROOT/lib/ci.sh"; then
            printf 'generate-hooks: failed to load lib/ci.sh\n' >&2
            exit 1
        fi
        if ! source "$_CI_ROOT/lib/checks_quality.sh"; then
            printf 'generate-hooks: failed to load lib/checks_quality.sh\n' >&2
            exit 1
        fi
        
        _config=".pre-commit-config.yaml"
        _output_dir=""
        _dry_run=0
        while [[ $# -gt 0 ]]; do
            case "$1" in
                --config) _config="$2"; shift 2 ;;
                --output-dir) _output_dir="$2"; shift 2 ;;
                --dry-run) _dry_run=1; shift ;;
                *) ci_fail "Unknown option: $1"; exit 1 ;;
            esac
        done
        [[ -f "$_config" ]] || { ci_fail "Config not found: $_config"; exit 1; }
        [[ -n "$_output_dir" ]] || _output_dir="$(git rev-parse --git-dir)/hooks"
        mkdir -p "$_output_dir"
        ci_info "generate-hooks: $_config -> $_output_dir"
        
        _hooks="$(awk -f "$_CI_ROOT/lib/parse_precommit_config.awk" "$_config")"
        if [[ -z "$_hooks" ]]; then
            ci_pass "no hooks configured; nothing to generate"
            exit 0
        fi
        _total_entries="$(printf '%s\n' "$_hooks" | awk 'END {print NR}')"
        ci_pass "parsed $_total_entries hook entries from $_config"
        
        # === registry function reconciliation (renames never break consumers) ===
        # .pre-commit-config.yaml duplicates each checker's shell function name in
        # every consumer entry. A rename in config/required_hooks.yaml then breaks
        # every consumer until it is re-scaffolded, and a broken hook deadlocks the
        # fix commit. Resolve each registered hook's function by id: a token the lib
        # no longer defines is replaced with the registry's function for that id.
        # Entries whose functions resolve are untouched, so overrides survive.
        _lib_defines() {
            local _fn="$1" _lib
            for _lib in "$_CI_ROOT"/lib/*.sh; do
                if grep -qE "^[[:space:]]*(function[[:space:]]+)?${_fn}[[:space:]]*\(\)" "$_lib"; then
                    return 0
                fi
            done
            return 1
        }
        
        _registry_file="$(ci_config_path required_hooks)"
        if [[ -f "$_registry_file" ]]; then
            declare -A _reg_fn_for_id=()
            _reg_stream="$(awk -v mode=registry -f "$_CI_ROOT/lib/parse_hook_yaml.awk" "$_registry_file")" || _reg_stream=""
            while IFS=$'\034' read -r _ri _rk _re _rr; do
                [[ -n "$_ri" ]] || continue
                case "$_rk" in
                    shell|shell_with_arg) [[ "$_re" == ci_* ]] && _reg_fn_for_id["$_ri"]="$_re" ;;
                esac
            done <<< "$_reg_stream"
            _reconciled_hooks=""
            while IFS=$'\034' read -r _h_id _h_name _h_entry _h_stage _h_pass _h_always _h_files _h_exclude _h_args _h_types _h_advisory; do
                [[ -n "$_h_id" ]] || continue
                _reg_fn="${_reg_fn_for_id[$_h_id]:-}"
                if [[ -n "$_reg_fn" ]] && _lib_defines "$_reg_fn"; then
                    _tokens="$(printf '%s\n' "$_h_entry" | grep -oE 'ci_[a-z_][a-z0-9_]*' | sort -u)" || _tokens=""
                    for _tok in $_tokens; do
                        if ! _lib_defines "$_tok"; then
                            _h_entry="${_h_entry//$_tok/$_reg_fn}"
                            ci_info "reconcile: hook '$_h_id' '$_tok' -> '$_reg_fn' (registry)"
                        fi
                    done
                fi
                _reconciled_hooks+="${_h_id}"$'\034'"${_h_name}"$'\034'"${_h_entry}"$'\034'"${_h_stage}"$'\034'"${_h_pass}"$'\034'"${_h_always}"$'\034'"${_h_files}"$'\034'"${_h_exclude}"$'\034'"${_h_args}"$'\034'"${_h_types}"$'\034'"${_h_advisory}"$'\n'
            done <<< "$_hooks"
            _hooks="$_reconciled_hooks"
        fi
        
        # === entry-resolution integrity (2026-08-24 portable_shell incident) ===
        # A rendered hook whose entry does not resolve fails only at commit time,
        # in the deployed artifact, where fixing it deadlocks (the broken gate
        # blocks the fix commit). Refuse at generation instead: every shell
        # function entry must be defined in the sourced lib, and every python-module
        # entry must exist as a file. This mirrors what the hook itself
        # will do: source lib/checks.sh, then invoke the entry.
        _entry_unresolved=0
        _written_stages=()
        while IFS=$'\034' read -r _e_id _e_name _e_entry _e_rest; do
            [[ -n "$_e_id" ]] || continue
            # Filename-passing entries are prohibited: a check must discover the
            # full tracked+untracked tree itself, never receive a file list (which
            # pre-commit would narrow to the changed subset).
            if [[ "$_e_entry" == *'"$@'* ]]; then
                ci_fail "Hook '$_e_id' entry passes filenames (\"\$@\"), which is prohibited; the check must discover the full tree."
                _entry_unresolved=1
            fi
            # grep exits 1 when an entry has no shell-function token (make
            # targets, python-modules, bare commands); that is expected.
            _e_fns=""
            _e_fns_rc=0
            _e_fns="$(printf '%s\n' "$_e_entry" | grep -oE 'ci_[a-z_][a-z0-9_]*' | sort -u)" || _e_fns_rc=$?
            for _e_fn in $_e_fns; do
                _e_found=""
                for _e_lib in "$_CI_ROOT"/lib/*.sh; do
                    if grep -qE "^[[:space:]]*(function[[:space:]]+)?${_e_fn}[[:space:]]*\(\)" "$_e_lib"; then
                        _e_found="$_e_lib"
                        break
                    fi
                done
                if [[ -z "$_e_found" ]]; then
                    ci_fail "Hook '$_e_id' entry references '${_e_fn}' but no lib module defines it."
                    echo "  Checked: $_CI_ROOT/lib/*.sh" >&2
                    _entry_unresolved=1
                fi
            done
            _e_mod=""
            _e_mod_rc=0
            _e_mod="$(printf '%s\n' "$_e_entry" | grep -oE 'python -m ci\.[a-z_][a-z0-9_.]*' | sed 's/^python -m //')" || _e_mod_rc=$?
            _e_mod="${_e_mod%%$'\n'*}"
            _e_mod_path="${_e_mod//./\/}"
            if [[ -n "$_e_mod" && ! -f "$_CI_ROOT/$_e_mod_path.py" && ! -d "$_CI_ROOT/$_e_mod_path" ]]; then
                ci_fail "Hook '$_e_id' entry references python-module '$_e_mod' but it does not exist."
                _entry_unresolved=1
            fi
        done <<< "$_hooks"
        [[ $_entry_unresolved -eq 0 ]] || exit 1
        ci_pass "entry integrity: all shell functions and python-modules resolve in lib"
        
        for _stage in pre-commit commit-msg pre-push; do
            _stage_hooks="$(printf '%s\n' "$_hooks" | awk -F'\034' -v s="$_stage" '$4 == s')"
            [[ -n "$_stage_hooks" ]] || continue
            # grep -c exits 1 on zero matches and awk can legitimately emit
            # nothing (stage with no advisory hooks); both are fatal under
            # set -e inside $( ). Count with awk's END block instead: always
            # prints, always exits 0.
            _stage_count="$(printf '%s\n' "$_stage_hooks" | awk 'END {print NR}')"
            _stage_advisory="$(printf '%s\n' "$_hooks" | awk -F'\034' -v s="$_stage" '$4 == s && $11 == "true"' | awk 'END {print NR}')"
            _tmp="$(mktemp)"
            {
                printf '%s\n' '#!/usr/bin/env bash' 'set -euo pipefail'
                printf '%s\n' '# AUTO-GENERATED by /opt/workspace-ci/scripts/generate-hooks'
                printf '_ROOT="$(git rev-parse --show-toplevel)"\ncd "$_ROOT"\n'
                printf '%s\n' '[[ -f /opt/workspace-ci/lib/ci.sh ]] || { printf "WORKSPACE-CI deployment unavailable\\n" >&2; exit 1; }'
                printf '%s\n' ''
                printf '%s\n' '# === trust boundary: caller input never selects code, policy, or scan root ==='
                printf '%s\n' '# REQ-HOOK-TRUST-BOUNDARY sections 3 and 4.'
                printf '%s\n' 'for _tb_var in ${!CI_CONFIG_PATH_@} ${!CI_CONFIG_OVERRIDES@} ${!CI_GUARD_CONFIG_OVERRIDES@} \'
                printf '%s\n' '    CI_GUARD_CONFIG_DIR WORKSPACE_CI_CONFIG_ROOT WORKSPACE_GUARD_CONFIG_ROOT \'
                printf '%s\n' '    WORKSPACE_GUARD_CONFIG_OVERRIDES PYTHONPATH CI_CONFIG_DIR CI_PROJECT_ROOT \'
                printf '%s\n' '    CI_LIB_DIR CI_BOOT_DIR CI_SCAN_ROOT \'
                printf '%s\n' '    GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_INDEX_FILE GIT_PREFIX \'
                printf '%s\n' '    GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_NAMESPACE \'
                printf '%s\n' '    GIT_CEILING_DIRECTORIES GIT_DISCOVERY_ACROSS_FILESYSTEM; do'
                printf '%s\n' '    unset "$_tb_var"'
                printf '%s\n' 'done'
                printf '%s\n' 'unset _tb_var'
                printf '%s\n' 'source /opt/workspace-ci/lib/ci.sh'
                printf '%s\n' 'export CI_PROJECT_ROOT=/opt/workspace-ci'
                printf '%s\n' 'export CI_LIB_DIR=/opt/workspace-ci/lib'
                printf '%s\n' 'export CI_CONFIG_DIR=/opt/workspace-ci/config'
                printf '%s\n' 'export CI_BOOT_DIR=/opt/workspace-ci/.boot-linux'
                printf '%s\n' 'export CI_SCAN_ROOT="$_ROOT"'
                printf '%s\n' ''
                printf '%s\n' '# A hook must never execute writable-checkout code with root authority.'
                printf '%s\n' '# Re-exec as the repository owner so any source-development command'
                printf '%s\n' '# (make lint/type-check/check-push) runs unprivileged.'
                printf '%s\n' 'if [[ $EUID -eq 0 ]]; then'
                printf '%s\n' '    _hook_owner="$(stat -c %U "$_ROOT")"'
                printf '%s\n' '    [[ "$_hook_owner" != root ]] || { printf "hook: repository owner is root\\n" >&2; exit 1; }'
                printf '%s\n' '    _hook_home="$(getent passwd "$_hook_owner" | cut -d: -f6)"'
                printf '%s\n' '    exec /usr/sbin/runuser -u "$_hook_owner" -- env HOME="$_hook_home" "$BASH" "$0" "$@"'
                printf '%s\n' 'fi'
                printf '%s\n' ''
                printf '%s\n' '# === quality_exceptions.yaml preflight (mandatory) ==='
                printf '%s\n' 'if [[ ! -f "$_ROOT/quality_exceptions.yaml" ]]; then'
                printf '%s\n' '    ci_fail "quality_exceptions.yaml missing at $_ROOT"'
                printf '%s\n' '    echo "  Fix: copy /opt/workspace-ci/templates/quality_exceptions.template.yaml"'
                printf '%s\n' '    echo "       to $_ROOT/quality_exceptions.yaml and replace __PROJECT_NAME__."'
                printf '%s\n' '    exit 1'
                printf '%s\n' 'fi'
                printf '%s\n' ''
                printf '%s\n' '# === exemption-file compliance (mandatory) ==='
                printf '%s\n' '# CI-BUILTIN-EXEMPTION-COMPLIANCE'
                printf '%s\n' '_exemptions_lib="/opt/workspace-ci/lib/ci_exemptions.sh"'
                printf '%s\n' '_exemptions_manifest="/opt/workspace-ci/config/exemption_files.yaml"'
                printf '%s\n' 'if [[ ! -f "$_exemptions_lib" || ! -f "$_exemptions_manifest" ]]; then'
                printf '%s\n' '    ci_fail "CI exemption infrastructure missing (lib/ci_exemptions.sh or config/exemption_files.yaml)"'
                printf '%s\n' '    exit 1'
                printf '%s\n' 'fi'
                printf '%s\n' 'if ! source "$_exemptions_lib"; then'
                printf '%s\n' '    ci_fail "failed to source $_exemptions_lib"'
                printf '%s\n' '    exit 1'
                printf '%s\n' 'fi'
                printf '%s\n' '_exemption_fail=0'
                printf '%s\n' '_exemption_paths="$(sed -n "s/^  - path: //p" "$_exemptions_manifest")"'
                printf '%s\n' 'for _rel in $_exemption_paths; do'
                printf '%s\n' '    _exemption_state="$(ci_exemption_file_state "$_ROOT/$_rel")"'
                printf '%s\n' '    if [[ "$_exemption_state" != "ok" ]]; then'
                printf '%s\n' '        ci_fail "exemption file not compliant: $_rel (state: $_exemption_state)"'
                printf '%s\n' '        _exemption_fail=1'
                printf '%s\n' '    fi'
                printf '%s\n' 'done'
                printf '%s\n' 'if [[ "$_exemption_fail" -eq 1 ]]; then'
                printf '%s\n' '    echo "  Fix: files must be root-owned regular files; edit via the root-gated yaml editor"'
                printf '%s\n' '    exit 1'
                printf '%s\n' 'fi'
                printf '%s\n' ''
                printf '%s\n' '# === CI catalog provenance (CI repo only, mandatory) ==='
                printf '%s\n' '# CI-BUILTIN-CATALOG-PROVENANCE'
                printf '%s\n' 'if [[ -f "$_ROOT/scripts/generate-hooks" && -d "$_ROOT/config" ]]; then'
                printf '%s\n' '    _catalog_fail=0'
                printf '%s\n' '    for _catalog in "$_ROOT"/config/*.yaml; do'
                printf '%s\n' '        [[ -e "$_catalog" ]] || continue'
                printf '%s\n' '        _catalog_state="$(ci_exemption_file_state "$_catalog")"'
                printf '%s\n' '        if [[ "$_catalog_state" != "ok" ]]; then'
                printf '%s\n' '            ci_fail "CI catalog not compliant: ${_catalog#$_ROOT/} (state: $_catalog_state)"'
                printf '%s\n' '            _catalog_fail=1'
                printf '%s\n' '        fi'
                printf '%s\n' '    done'
                printf '%s\n' '    if [[ "$_catalog_fail" -eq 1 ]]; then'
                printf '%s\n' '        echo "  Fix: config/*.yaml must be root-owned regular files; edit via the root-gated yaml editor"'
                printf '%s\n' '        exit 1'
                printf '%s\n' '    fi'
                printf '%s\n' 'fi'
                while IFS=$'\034' read -r h_id h_name h_entry h_stage h_pass h_always h_files h_exclude h_args h_types h_advisory; do
                    [[ -n "$h_id" ]] || continue
                    [[ -n "$h_entry" ]] || { ci_fail "Hook '$h_id' has empty entry"; exit 1; }
                    h_cmd="${h_entry//bash -c/\"\$BASH\" -c}"
                    h_cmd="${h_cmd//uv run python -m ci./\/opt\/workspace-ci\/.boot-linux\/bin\/uv run --project \/opt\/workspace-ci --no-sync python -P -m ci.}"
                    [[ -n "$h_args" ]] && h_cmd="$h_cmd $h_args"
                    printf '# === Hook: %s ===\n' "$h_id"
                    printf 'ci_info "Running: %s..."\n' "$h_name"
                    if [[ "$h_advisory" == "true" ]]; then
                        # Advisory hooks report findings but never fail the gate:
                        # the exit status is captured explicitly (sanctioned
                        # pattern) and surfaced with ci_info, never enforced.
                        printf '_advisory_rc=0\n'
                        printf '%s || _advisory_rc=$?\n' "$h_cmd"
                        printf 'if [[ "$_advisory_rc" -ne 0 ]]; then ci_info "ADVISORY (non-blocking): %s exited $_advisory_rc; reported, not enforced"; fi\n' "$h_name"
                    elif [[ "$_stage" == commit-msg ]]; then
                        printf '%s "$1" || { ci_fail "%s"; exit 1; }\n' "$h_cmd" "$h_name"
                    else
                        printf '%s || { ci_fail "%s"; exit 1; }\n' "$h_cmd" "$h_name"
                    fi
                done <<< "$_stage_hooks"
            } > "$_tmp"
            if [[ "$_dry_run" -eq 1 ]]; then
                cat "$_tmp"
                rm -f "$_tmp"
                ci_info "DRY-RUN: $_stage would write $_stage_count hooks ($_stage_advisory advisory)"
            else
                mv "$_tmp" "$_output_dir/$_stage"
                chmod 0755 "$_output_dir/$_stage"
                ci_pass "$_stage: $_stage_count hooks written ($_stage_advisory advisory)"
                _written_stages+=("$_stage")
            fi
        done
        if [[ "$_dry_run" -eq 1 ]]; then
            ci_pass "dry run complete; no files written"
        elif [[ "${#_written_stages[@]}" -gt 0 ]]; then
            ci_pass "SUCCESS: ${#_written_stages[@]} hook files written to $_output_dir"
            ci_info "activate with: make install-hooks"
        else
            ci_fail "no stages rendered from $_config"
            exit 1
        fi
        

        Share feedback

        You voted thumbs down

        bootstrap-gitleaks

        Fetch the gitleaks binary and place it on PATH (idempotent, validated by SHA256).

        Bootstrap
        Make target
        install-gitleaks

        bootstrap-gitleaks

        scripts/bootstrap-gitleaks

        bootstrap-gitleaks: fetch the gitleaks binary and place it on PATH. This project depends on `gitleaks` for the pre-commit secret-content scanner. This script is idempotent: if a compatible binary is already present at the target path, it exits 0 without redownloading. Default install location: $CI_PROJECT_ROOT/$CI_BOOT_NAME/bin/gitleaks where $CI_BOOT_NAME is platform-aware (.boot-linux on Linux, .boot-macos on macOS), set at source-time by lib/ci.sh. Override with $GITLEAKS_BIN to drop somewhere else. Override the version with $GITLEAKS_VERSION (default below). CI_PROJECT_ROOT (this repo's own root) is delegated to lib/ci.sh. Per the boot contract, this script installs to CI's own boot dir: NOT the workspace root. Sibling repos reach this binary via the boot-path resolver (lib/ci.sh::ci_resolve_boot_path) which reads moon.yml::project.inherited_boot_dirs. See: docs/specifications/SPEC-BOOT-LAYOUT.md

        bootstrap-gitleaks

        Output: Installs gitleaks to $CI_PROJECT_ROOT/${boot_dir}/bin (boot_dir read from config/boot_layout.yaml; default .boot-linux) if absent/upgrade-needed; no-op otherwise.

        #!/usr/bin/env bash
        # bootstrap-gitleaks: fetch the gitleaks binary and place it on PATH.
        #
        # This project depends on `gitleaks` for the pre-commit secret-content scanner.
        # This script is idempotent: if a compatible binary is already present at the
        # target path, it exits 0 without redownloading.
        #
        # Default install location:
        #   $CI_PROJECT_ROOT/$CI_BOOT_NAME/bin/gitleaks
        # where $CI_BOOT_NAME is platform-aware (.boot-linux on Linux, .boot-macos
        # on macOS), set at source-time by lib/ci.sh.
        # Override with $GITLEAKS_BIN to drop somewhere else.
        #
        # Override the version with $GITLEAKS_VERSION (default below).
        #
        # CI_PROJECT_ROOT (this repo's own root) is delegated to lib/ci.sh. Per the
        # boot contract, this script installs to CI's own boot dir: NOT the
        # workspace root. Sibling repos reach this binary via the
        # boot-path resolver (lib/ci.sh::ci_resolve_boot_path) which reads
        # moon.yml::project.inherited_boot_dirs. See:
        #   docs/specifications/SPEC-BOOT-LAYOUT.md
        
        set -euo pipefail
        
        #
        # Supply-chain pinning: SHA256 verification is MANDATORY and always on.
        # The checksum is fetched at runtime from the checksums.txt sidecar file
        # published alongside the tarballs on the GitHub release page. No hardcoded
        # hashes are used: the sidecar is the trusted source of truth, fetched
        # from the same release origin as the tarball.
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _ci_lib="$(cd "$(dirname "$_SELF")/../lib" && pwd)"
        # shellcheck source=lib/ci.sh
        if ! source "$_ci_lib/ci.sh"; then
            echo "ERROR: failed to source $_ci_lib/ci.sh" >&2
            exit 2
        fi
        if [[ -z "${CI_PROJECT_ROOT:-}" ]]; then
            echo "ERROR: CI_PROJECT_ROOT not set after sourcing ci.sh" >&2
            exit 2
        fi
        GITLEAKS_VERSION="$(ci_tool_version gitleaks)" || { echo "ERROR: missing gitleaks tool pin" >&2; exit 2; }
        GITLEAKS_SHA256="$(ci_tool_artifact gitleaks sha256)" || { echo "ERROR: missing gitleaks checksum" >&2; exit 2; }
        
        _log() { printf '[bootstrap-gitleaks] %s\n' "$*" >&2; }
        
        main() {
            local target_dir target arch tarball url
            target_dir="${CI_PROJECT_ROOT}/${CI_BOOT_NAME}/bin"
            target="${GITLEAKS_BIN:-${target_dir}/gitleaks}"
        
            if ! mkdir -p "$(dirname "$target")"; then
                _log "mkdir failed for $(dirname "$target")"
                return 1
            fi
        
            if [[ -x "$target" ]]; then
                local v_out v_err v_rc=0
                v_out="$(mktemp)"
                v_err="$(mktemp)"
                "$target" version >"$v_out" 2>"$v_err" || v_rc=$?
                if [[ "$v_rc" -eq 0 ]]; then
                    local cur
                    cur="$(head -1 "$v_out")"
                    rm -f "$v_out" "$v_err"
                    if [[ "$cur" == *"$GITLEAKS_VERSION"* ]]; then
                        _log "gitleaks ${GITLEAKS_VERSION} already at $target"
                        return 0
                    fi
                    _log "found existing gitleaks ($cur), upgrading to ${GITLEAKS_VERSION}"
                else
                    local err_msg
                    err_msg="$(head -1 "$v_err")"
                    rm -f "$v_out" "$v_err"
                    _log "existing binary at $target did not respond to 'version' (status=$v_rc): $err_msg"
                    _log "re-downloading fresh copy"
                fi
            fi
        
            case "$(uname -m)" in
                x86_64|amd64)  arch="x64" ;;
                aarch64|arm64) arch="arm64" ;;
                *) _log "unsupported arch: $(uname -m)"; return 1 ;;
            esac
        
            case "$(uname -s)" in
                Linux) goos="linux" ;;
                Darwin) goos="darwin" ;;
                *) _log "unsupported platform: $(uname -s)"; return 1 ;;
            esac
        
            tarball="gitleaks_${GITLEAKS_VERSION}_${goos}_${arch}.tar.gz"
            url="https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/${tarball}"
        
            local tmp
            tmp="$(mktemp -d)"
            # Use ${tmp:-} so the trap is safe under `set -u` once `tmp` (a local)
            # goes out of scope after main() returns.
            # shellcheck disable=SC2064
            trap "rm -rf \"\${tmp:-$tmp}\"" EXIT
        
            _log "fetching ${url}"
            if ! curl -fsSL --retry 3 --retry-delay 2 -o "${tmp}/${tarball}" "$url"; then
                _log "curl failed for $url"
                return 1
            fi
        
            # Mandatory SHA256 verification: fetch the checksums.txt sidecar from
            # the same GitHub release URL as the tarball. The sidecar contains
            # lines of "<hash>  <filename>": we extract the line matching our
            # tarball name and compare the hash against sha256sum of the download.
            # No hardcoded hashes.
            local checksums_url="https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_checksums.txt"
            _log "fetching checksum sidecar: ${checksums_url}"
            local sha_rc=0
            curl -fsSL --retry 3 --retry-delay 2 -o "${tmp}/checksums.txt" "$checksums_url" || sha_rc=$?
            if [[ "$sha_rc" -ne 0 ]]; then
                _log "failed to fetch checksums sidecar (status=$sha_rc): $checksums_url"
                _log "cannot verify tarball integrity without sidecar; refusing to install"
                return 1
            fi
        
            local expected_sha
            expected_sha="$(awk -v tb="$tarball" '$2 == tb {print $1}' "${tmp}/checksums.txt")"
            if [[ -z "$expected_sha" ]]; then
                _log "no checksum entry for $tarball in sidecar; refusing to install"
                return 1
            fi
        
            local actual_sha
            actual_sha="$(ci_sha256 "${tmp}/${tarball}")"
            if [[ "$actual_sha" != "$GITLEAKS_SHA256" ]]; then
                _log "checksum mismatch: expected $GITLEAKS_SHA256, got $actual_sha"
                return 1
            fi
            _log "checksum OK ($GITLEAKS_SHA256)"
        
            _log "extracting ${tarball} to ${tmp}"
            if ! tar -xzf "${tmp}/${tarball}" -C "$tmp" gitleaks; then
                _log "tar extraction failed"
                return 1
            fi
            _log "installing gitleaks to ${target}"
            if ! install -m 0755 "${tmp}/gitleaks" "$target"; then
                _log "install (copy) failed to $target"
                return 1
            fi
        
            local v_out2 v_rc2=0
            v_out2="$(mktemp)"
            "$target" version >"$v_out2" 2>&1 || v_rc2=$?
            if [[ "$v_rc2" -ne 0 ]]; then
                _log "post-install verification failed: '$target version' returned status=$v_rc2"
                rm -f "$v_out2"
                return 1
            fi
            _log "installed: $(head -1 "$v_out2") => $target"
            rm -f "$v_out2"
        }
        
        main "$@"
        

        Share feedback

        You voted thumbs down

        bootstrap-cloc

        Fetch the cloc single-file Perl script and place it on PATH (idempotent, SHA256-verified against a pinned hash).

        Bootstrap
        Make target
        install-cloc

        bootstrap-cloc

        scripts/bootstrap-cloc

        bootstrap-cloc: fetch the cloc single-file Perl script and place it on PATH. This project depends on `cloc` (Count Lines of Code) for the code-stats script. cloc is distributed as a single self-contained Perl script, so bootstrapping it is a download + checksum verify + drop into the boot bin dir. This script is idempotent: if a compatible binary is already present at the target path, it exits 0 without redownloading. Default install location: $CI_PROJECT_ROOT/$CI_BOOT_NAME/bin/cloc where $CI_BOOT_NAME is platform-aware (.boot-linux on Linux, .boot-macos on macOS), set at source-time by lib/ci.sh. Override with $CLOC_BIN to drop somewhere else. Override the version with $CLOC_VERSION (default below). Supply-chain pinning: SHA256 verification is MANDATORY and always on. The selected artifact and its checksum come from res/dependency-pins.yaml. Bumping the version requires recomputing the hash of the selected .pl asset. cloc is a Perl script; a working `perl` is a runtime dependency and is declared in config/system-deps.yaml. This script verifies perl presence before installing so the failure mode is obvious at bootstrap time. CI_PROJECT_ROOT (this repo's own root) is delegated to lib/ci.sh. Per the boot contract, this script installs to CI's OWN boot dir: NOT the workspace root. Sibling repos reach this binary via the boot-path resolver (lib/ci.sh::ci_resolve_boot_path) which reads moon.yml::project.inherited_boot_dirs. See: docs/specifications/SPEC-BOOT-LAYOUT.md

        bootstrap-cloc

        Output: Installs cloc to $CI_PROJECT_ROOT/${boot_dir}/bin/cloc (boot_dir read from config/boot_layout.yaml; default .boot-linux) if absent/upgrade-needed; no-op otherwise. cloc ships no checksum sidecar, so the hash is pinned in-script; perl presence is checked before install.

        #!/usr/bin/env bash
        # bootstrap-cloc: fetch the cloc single-file Perl script and place it on PATH.
        #
        # This project depends on `cloc` (Count Lines of Code) for the code-stats
        # script. cloc is distributed as a single self-contained Perl script, so
        # bootstrapping it is a download + checksum verify + drop into the boot bin
        # dir. This script is idempotent: if a compatible binary is already present
        # at the target path, it exits 0 without redownloading.
        #
        # Default install location:
        #   $CI_PROJECT_ROOT/$CI_BOOT_NAME/bin/cloc
        # where $CI_BOOT_NAME is platform-aware (.boot-linux on Linux, .boot-macos
        # on macOS), set at source-time by lib/ci.sh.
        # Override with $CLOC_BIN to drop somewhere else.
        #
        # Override the version with $CLOC_VERSION (default below).
        #
        # Supply-chain pinning: SHA256 verification is MANDATORY and always on. The
        # selected artifact and its checksum come from res/dependency-pins.yaml.
        # Bumping the version requires recomputing the hash of the selected .pl asset.
        #
        # cloc is a Perl script; a working `perl` is a runtime dependency and is
        # declared in config/system-deps.yaml. This script verifies perl presence
        # before installing so the failure mode is obvious at bootstrap time.
        #
        # CI_PROJECT_ROOT (this repo's own root) is delegated to lib/ci.sh. Per the
        # boot contract, this script installs to CI's OWN boot dir: NOT the
        # workspace root. Sibling repos reach this binary via the boot-path
        # resolver (lib/ci.sh::ci_resolve_boot_path) which reads
        # moon.yml::project.inherited_boot_dirs. See:
        #   docs/specifications/SPEC-BOOT-LAYOUT.md
        
        set -euo pipefail
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _ci_lib="$(cd "$(dirname "$_SELF")/../lib" && pwd)"
        # shellcheck source=lib/ci.sh
        if ! source "$_ci_lib/ci.sh"; then
            echo "ERROR: failed to source $_ci_lib/ci.sh" >&2
            exit 2
        fi
        if [[ -z "${CI_PROJECT_ROOT:-}" ]]; then
            echo "ERROR: CI_PROJECT_ROOT not set after sourcing ci.sh" >&2
            exit 2
        fi
        CLOC_VERSION="$(ci_tool_version cloc)" || { echo "ERROR: missing cloc tool pin" >&2; exit 2; }
        CLOC_ASSET="$(ci_cloc_artifact asset)" || { echo "ERROR: missing cloc artifact" >&2; exit 2; }
        CLOC_SHA256="$(ci_cloc_artifact sha256)" || { echo "ERROR: missing cloc checksum" >&2; exit 2; }
        
        _log() { printf '[bootstrap-cloc] %s\n' "$*" >&2; }
        
        main() {
            local target_dir target
            target_dir="${CI_PROJECT_ROOT}/${CI_BOOT_NAME}/bin"
            target="${CLOC_BIN:-${target_dir}/cloc}"
        
            if ! mkdir -p "$(dirname "$target")"; then
                _log "mkdir failed for $(dirname "$target")"
                return 1
            fi
        
            # cloc is a Perl script: refuse to install without a working perl.
            if [[ -z "$(command -v perl)" ]]; then
                _log "perl not found on PATH; cloc is a Perl script and requires it"
                _log "install perl (declared in config/system-deps.yaml) then re-run"
                return 1
            fi
        
            if [[ -x "$target" ]]; then
                local v_out v_rc=0
                v_out="$(mktemp)"
                "$target" --version >"$v_out" 2>&1 || v_rc=$?
                if [[ "$v_rc" -eq 0 ]]; then
                    local cur
                    cur="$(head -1 "$v_out")"
                    rm -f "$v_out"
                    if [[ "$cur" == *"$CLOC_VERSION"* ]]; then
                        _log "cloc ${CLOC_VERSION} already at $target"
                        return 0
                    fi
                    _log "found existing cloc ($cur), upgrading to ${CLOC_VERSION}"
                else
                    rm -f "$v_out"
                    _log "existing binary at $target did not respond to '--version' (status=$v_rc)"
                    _log "re-downloading fresh copy"
                fi
            fi
        
            local url="https://github.com/AlDanial/cloc/releases/download/v${CLOC_VERSION}/${CLOC_ASSET}"
        
            local tmp
            tmp="$(mktemp -d)"
            # shellcheck disable=SC2064
            trap "rm -rf \"\${tmp:-$tmp}\"" EXIT
        
            _log "fetching ${url}"
            if ! curl -fsSL --retry 3 --retry-delay 2 -o "${tmp}/${CLOC_ASSET}" "$url"; then
                _log "curl failed for $url"
                return 1
            fi
        
            # Mandatory SHA256 verification against the pinned hash.
            local actual_sha
            actual_sha="$(ci_sha256 "${tmp}/${CLOC_ASSET}")"
            if [[ "$actual_sha" != "$CLOC_SHA256" ]]; then
                _log "checksum mismatch: expected $CLOC_SHA256, got $actual_sha"
                _log "if you bumped CLOC_VERSION, recompute the hash (see script header)"
                return 1
            fi
            _log "checksum OK ($CLOC_SHA256)"
        
            _log "installing cloc to ${target}"
            if ! install -m 0755 "${tmp}/${CLOC_ASSET}" "$target"; then
                _log "install (copy) failed to $target"
                return 1
            fi
        
            local v_out2 v_rc2=0
            v_out2="$(mktemp)"
            "$target" --version >"$v_out2" 2>&1 || v_rc2=$?
            if [[ "$v_rc2" -ne 0 ]]; then
                _log "post-install verification failed: '$target --version' returned status=$v_rc2"
                rm -f "$v_out2"
                return 1
            fi
            _log "installed: $(head -1 "$v_out2") => $target"
            rm -f "$v_out2"
        }
        
        main "$@"
        

        Share feedback

        You voted thumbs down

        bootstrap-uv

        Fetch the uv binary and place it on PATH (idempotent; SHA256 opt-in via UV_VERIFY_SHA256=1).

        Bootstrap

        bootstrap-uv

        scripts/bootstrap-uv

        bootstrap-uv: fetch the uv binary and place it on PATH. This project uses `uv` for dependency management (uv sync -> per-repo .venv/) and for cross-project Python invocation (uv run --project). This script is idempotent: if a compatible binary is already present at the target path, it exits 0 without redownloading. Default install location: $CI_PROJECT_ROOT/$CI_BOOT_NAME/bin/uv where $CI_BOOT_NAME is platform-aware (.boot-linux on Linux, .boot-macos on macOS), set at source-time by lib/ci.sh. Override with $UV_BIN to drop somewhere else. Override the version with $UV_VERSION (default below). The per-repo private venv (`.venv/`) is created by `uv sync` (run from the repo root AFTER this script installs the uv binary): NOT by this script. This script installs ONLY the uv BINARY (and uvx if the release ships it). See: docs/specifications/SPEC-BOOT-LAYOUT.md Overrideable env vars: $UV_VERSION : release tag to fetch (default: 0.11.23, the version confirmed in AGENTS.md §2). $UV_BIN : override install target path. Supply-chain pinning: SHA256 verification is MANDATORY and always on. The checksum is fetched at runtime from the .sha256 sidecar file published alongside the tarball on the GitHub release page. No hardcoded hashes are used: the sidecar is the trusted source of truth, fetched from the same release origin as the tarball.

        bootstrap-uv

        Output: Installs uv (and uvx if shipped) to $CI_PROJECT_ROOT/${boot_dir}/bin (boot_dir read from config/boot_layout.yaml; default .boot-linux) if absent/upgrade-needed; no-op otherwise. The per-repo .venv/ is created later by `uv sync`, NOT by this script.

        #!/usr/bin/env bash
        # bootstrap-uv: fetch the uv binary and place it on PATH.
        #
        # This project uses `uv` for dependency management (uv sync -> per-repo
        # .venv/) and for cross-project Python invocation (uv run --project).
        # This script is idempotent: if a compatible binary is already present at
        # the target path, it exits 0 without redownloading.
        #
        # Default install location:
        #   $CI_PROJECT_ROOT/$CI_BOOT_NAME/bin/uv
        # where $CI_BOOT_NAME is platform-aware (.boot-linux on Linux, .boot-macos
        # on macOS), set at source-time by lib/ci.sh.
        # Override with $UV_BIN to drop somewhere else.
        #
        # Override the version with $UV_VERSION (default below).
        #
        # The per-repo private venv (`.venv/`) is created by `uv sync` (run from the
        # repo root AFTER this script installs the uv binary): NOT by this script.
        # This script installs ONLY the uv BINARY (and uvx if the release ships it).
        # See: docs/specifications/SPEC-BOOT-LAYOUT.md
        #
        # Overrideable env vars:
        #   $UV_VERSION        : release tag to fetch (default: 0.11.23, the
        #                         version confirmed in AGENTS.md §2).
        #   $UV_BIN            : override install target path.
        #
        # Supply-chain pinning: SHA256 verification is MANDATORY and always on.
        # The checksum is fetched at runtime from the .sha256 sidecar file
        # published alongside the tarball on the GitHub release page. No hardcoded
        # hashes are used: the sidecar is the trusted source of truth, fetched
        # from the same release origin as the tarball.
        
        set -euo pipefail
        
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _ci_lib="$(cd "$(dirname "$_SELF")/../lib" && pwd)"
        # shellcheck source=lib/ci.sh
        if ! source "$_ci_lib/ci.sh"; then
            echo "ERROR: failed to source $_ci_lib/ci.sh" >&2
            exit 2
        fi
        if [[ -z "${CI_PROJECT_ROOT:-}" ]]; then
            echo "ERROR: CI_PROJECT_ROOT not set after sourcing ci.sh" >&2
            exit 2
        fi
        UV_VERSION="$(ci_tool_version uv)" || { echo "ERROR: missing uv tool pin" >&2; exit 2; }
        UV_SHA256="$(ci_tool_artifact uv sha256)" || { echo "ERROR: missing uv checksum" >&2; exit 2; }
        
        _log() { printf '[bootstrap-uv] %s\n' "$*" >&2; }
        
        main() {
            local target_dir target arch platform tarball url subdir
            target_dir="${CI_PROJECT_ROOT}/${CI_BOOT_NAME}/bin"
            target="${UV_BIN:-${target_dir}/uv}"
        
            if ! mkdir -p "$(dirname "$target")"; then
                _log "mkdir failed for $(dirname "$target")"
                return 1
            fi
        
            if [[ -x "$target" ]]; then
                local v_out v_err v_rc=0
                v_out="$(mktemp)"
                v_err="$(mktemp)"
                "$target" --version >"$v_out" 2>"$v_err" || v_rc=$?
                if [[ "$v_rc" -eq 0 ]]; then
                    local cur
                    cur="$(head -1 "$v_out")"
                    rm -f "$v_out" "$v_err"
                    if [[ "$cur" == *"${UV_VERSION}"* ]]; then
                        _log "uv ${UV_VERSION} already at $target"
                        return 0
                    fi
                    _log "found existing uv ($cur), upgrading to ${UV_VERSION}"
                else
                    local err_msg
                    err_msg="$(head -1 "$v_err")"
                    rm -f "$v_out" "$v_err"
                    _log "existing binary at $target did not respond to '--version'"
                    _log "status=$v_rc: $err_msg: re-downloading fresh copy"
                fi
            fi
        
            case "$(uname -m)" in
                x86_64|amd64)  arch="x86_64" ;;
                aarch64|arm64) arch="aarch64" ;;
                *) _log "unsupported arch: $(uname -m)"; return 1 ;;
            esac
        
            case "$(uname -s)" in
                Linux)  platform="unknown-linux-gnu" ;;
                Darwin) platform="apple-darwin" ;;
                *) _log "unsupported platform: $(uname -s)"; return 1 ;;
            esac
        
            tarball="uv-${arch}-${platform}.tar.gz"
            url="https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${tarball}"
            # uv release tarballs extract into a subdir named uv-<arch>-<platform>.
            subdir="uv-${arch}-${platform}"
        
            local tmp
            tmp="$(mktemp -d)"
            # Use ${tmp:-} so the trap is safe under `set -u` once `tmp` (a local)
            # goes out of scope after main() returns.
            # shellcheck disable=SC2064
            trap "rm -rf \"\${tmp:-$tmp}\"" EXIT
        
            _log "fetching ${url}"
            local dl_rc=0
            curl -fsSL --retry 3 --retry-delay 2 -o "${tmp}/${tarball}" "$url" || dl_rc=$?
            if [[ "$dl_rc" -ne 0 ]]; then
                _log "curl failed for $url (status=$dl_rc)"
                return 1
            fi
        
            local actual_sha
            actual_sha="$(ci_sha256 "${tmp}/${tarball}")"
            if [[ "$actual_sha" != "$UV_SHA256" ]]; then
                _log "checksum mismatch: expected $UV_SHA256, got $actual_sha"
                return 1
            fi
            _log "checksum OK ($UV_SHA256)"
        
            _log "extracting ${tarball} to ${tmp}"
            if ! tar -xzf "${tmp}/${tarball}" -C "$tmp"; then
                _log "tar extraction failed"
                return 1
            fi
        
            # Locate the uv binary: versioned subdir first, archive root for
            # flattened layouts; hard error below when neither exists.
            local uv_src="${tmp}/${subdir}/uv"
            if [[ ! -f "$uv_src" ]]; then
                uv_src="${tmp}/uv"
            fi
            if [[ ! -f "$uv_src" ]]; then
                _log "uv binary not found after extraction"
                _log "looked in ${subdir}/uv and at archive root of ${tmp}"
                return 1
            fi
        
            _log "installing uv to ${target}"
            if ! install -m 0755 "$uv_src" "$target"; then
                _log "install (copy) failed: $uv_src -> $target"
                return 1
            fi
        
            # Copy uvx if the release ships it (same subdir, then archive root).
            local uvx_src="${tmp}/${subdir}/uvx"
            if [[ ! -f "$uvx_src" ]]; then
                uvx_src="${tmp}/uvx"
            fi
            if [[ -f "$uvx_src" ]]; then
                local uvx_target
                uvx_target="$(dirname "$target")/uvx"
                if ! install -m 0755 "$uvx_src" "$uvx_target"; then
                    _log "install (copy) of uvx failed: $uvx_src -> $uvx_target"
                    return 1
                fi
                _log "uvx also installed to $uvx_target"
            fi
        
            local v_out2 v_err2 v_rc2=0
            v_out2="$(mktemp)"
            v_err2="$(mktemp)"
            "$target" --version >"$v_out2" 2>"$v_err2" || v_rc2=$?
            if [[ "$v_rc2" -ne 0 ]]; then
                _log "post-install verification failed: '$target --version' status=$v_rc2"
                _log "stderr: $(head -1 "$v_err2")"
                rm -f "$v_out2" "$v_err2"
                return 1
            fi
            _log "installed: $(head -1 "$v_out2") => $target"
            rm -f "$v_out2" "$v_err2"
        }
        
        main "$@"
        

        Share feedback

        You voted thumbs down

        bootstrap-rust

        Bootstrap a $RUST_TOOLCHAIN Rust toolchain into CI's own .boot-linux/rust and symlink binaries into .boot-linux/bin (idempotent, isolated via RUSTUP_HOME/CARGO_HOME).

        Bootstrap

        bootstrap-rust

        scripts/bootstrap-rust

        Install the pinned Rust toolchain into CI's private boot directory.

        bootstrap-rust

        Output: Installs rustc/cargo/rustup into $CI_PROJECT_ROOT/${boot_dir}/rust and symlinks toolchain + llvm-tools-preview binaries into ${boot_dir}/bin (boot_dir read from config/boot_layout.yaml; default .boot-linux). Refreshes symlinks + components and exits 0 if a working toolchain is already present; reinstalls if rustc is present but fails --version. Repo-private: does NOT touch $HOME/.rustup or $HOME/.cargo.

        #!/usr/bin/env bash
        # Install the pinned Rust toolchain into CI's private boot directory.
        set -euo pipefail
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _ci_lib="$(cd "$(dirname "$_SELF")/../lib" && pwd)"
        # shellcheck source=lib/ci.sh
        if ! source "$_ci_lib/ci.sh"; then
            printf 'bootstrap-rust: failed to source %s\n' "$_ci_lib/ci.sh" >&2
            exit 2
        fi
        
        log() { printf '[bootstrap-rust] %s\n' "$*" >&2; }
        
        main() {
            if [[ $EUID -eq 0 ]]; then
                log "refusing to install a downloaded toolchain as root"
                return 1
            fi
        
            local toolchain rustup_version rustup_sha rust_home target_dir tmp output errors status=0
            toolchain="$(ci_tool_version rust channel)" || return 2
            rustup_version="$(ci_tool_version rustup)" || return 2
            rustup_sha="$(ci_tool_artifact rustup sha256)" || return 2
            rust_home="${CI_PROJECT_ROOT}/${CI_BOOT_NAME}/rust"
            target_dir="${CI_PROJECT_ROOT}/${CI_BOOT_NAME}/bin"
            export RUSTUP_HOME="$rust_home" CARGO_HOME="$rust_home"
            mkdir -p "$rust_home" "$target_dir"
        
            if [[ ! -x "$rust_home/bin/rustup" ]]; then
                [[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || {
                    log "unsupported rustup platform: $(uname -s)/$(uname -m)"
                    return 2
                }
                tmp="$(mktemp -d)"
                trap 'rm -rf "${tmp:-}"' EXIT
                curl -fsSL --retry 3 --retry-delay 2 -o "$tmp/rustup-init" \
                    "https://static.rust-lang.org/rustup/archive/$rustup_version/x86_64-unknown-linux-gnu/rustup-init"
                printf '%s  %s\n' "$rustup_sha" "$tmp/rustup-init" | sha256sum -c -
                chmod 0700 "$tmp/rustup-init"
                "$tmp/rustup-init" -y --no-modify-path --default-toolchain none
            fi
        
            output="$(mktemp)"
            errors="$(mktemp)"
            "$rust_home/bin/rustup" toolchain install "$toolchain" --profile minimal \
                --component clippy,rustfmt,llvm-tools-preview,rust-src >"$output" 2>"$errors" || status=$?
            if [[ $status -ne 0 ]]; then
                log "rustup toolchain install failed (status=$status):"
                cat "$errors" >&2
                rm -f "$output" "$errors"
                return "$status"
            fi
            "$rust_home/bin/rustup" default "$toolchain"
            rm -f "$output" "$errors"
        
            local binary
            for binary in rustup cargo rustc rustfmt cargo-clippy cargo-fmt clippy-driver rustdoc; do
                if [[ -x "$rust_home/bin/$binary" ]]; then
                    ln -sfn "../rust/bin/$binary" "$target_dir/$binary"
                fi
            done
            "$target_dir/rustc" --version
            "$target_dir/cargo" --version
        }
        
        main "$@"
        

        Share feedback

        You voted thumbs down

        bootstrap-workspace-guard

        Build and install the capability-based git guard binary from the sibling WORKSPACE-GUARD repo.

        Bootstrap
        Make target
        build-guard

        Share feedback

        You voted thumbs down

        audit-workspace

        Discover all git repos under a root and report working-tree, sync, and CI integration status.

        Workspace
        Make target
        audit

        audit-workspace

        scripts/audit-workspace

        audit-workspace: Discover all git repos under a root and report status. Reports: working tree state, remote sync, CI integration level. Usage: audit-workspace [ROOT]

        audit-workspace [ROOT]
        ROOT
        Workspace root to scan (default: auto-detected)

        Output: One row per discovered repo with state/sync/CI columns.

        #!/usr/bin/env bash
        # audit-workspace: Discover all git repos under a root and report status.
        # Reports: working tree state, remote sync, CI integration level.
        #
        # Usage: audit-workspace [ROOT]
        set -euo pipefail
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _SCRIPT_DIR="$(cd "$(dirname "$_SELF")" && pwd)"
        _CI_ROOT="$(cd "$_SCRIPT_DIR/.." && pwd)"
        if ! source "$_CI_ROOT/lib/ci.sh"; then
            echo "ERROR: failed to source $_CI_ROOT/lib/ci.sh" >&2
            exit 2
        fi
        
        # Capture stdout of <cmd...>; print the <default> string on failure.
        # stderr is captured to a temp file and printed only on failure (real signal,
        # no swallow). Use for UI display strings where a command failure should
        # surface static text rather than abort the audit.
        _capture_or_default() {
            local default="$1"; shift
            local out err status=0
            out="$(mktemp)"; err="$(mktemp)"
            "$@" >"$out" 2>"$err" || status=$?
            if [[ $status -ne 0 ]]; then
                if [[ -s "$err" ]]; then
                    printf '[audit-workspace] %s (status=%d): %s\n' "$*" "$status" \
                        "$(head -1 "$err")" >&2
                fi
                printf '%s' "$default"
            else
                cat "$out"
            fi
            rm -f "$out" "$err"
        }
        
        _ROOT="${1:-$(git rev-parse --show-toplevel || pwd)}"
        _ROOT="$(cd "$_ROOT" && pwd)"
        
        # Skip patterns for repo discovery
        _SKIP_DIRS="tmp|node_modules|\.venv|__pycache__|research|python-ta-reference|\.boot-linux|\.boot-macos|dist|build"
        
        # Load blocked patterns for L4 check
        _blocked_combined=""
        _blocked_config="$CI_CONFIG_DIR/blocked_commit_patterns.yaml"
        if [[ -f "$_blocked_config" ]]; then
            while IFS= read -r _line; do
                if [[ "$_line" =~ pattern:[[:space:]]*[\"\']?(.+)[\"\']?$ ]]; then
                    _pat="${BASH_REMATCH[1]}"
                    _pat="${_pat%\"}" ; _pat="${_pat%\'}"
                    _pat="${_pat#\"}" ; _pat="${_pat#\'}"
                    [[ -n "$_blocked_combined" ]] && _blocked_combined="${_blocked_combined}|"
                    _blocked_combined="${_blocked_combined}${_pat}"
                fi
            done < "$_blocked_config"
        fi
        
        # Discover repos
        _repos=()
        _gitdirs=()
        ci_capture_pipe _gitdirs 'find "$1" -name ".git" -type d | sort' "$_ROOT"
        for _gitdir in "${_gitdirs[@]}"; do
            _repo="$(dirname "$_gitdir")"
            # Skip matches
            if echo "$_repo" | grep -qE "$_SKIP_DIRS"; then
                continue
            fi
            _repos+=("$_repo")
        done
        
        
        if [[ ${#_repos[@]} -eq 0 ]]; then
            ci_warn "No git repos found under $_ROOT"
            exit 0
        fi
        
        _total_repos=${#_repos[@]}
        _fully_integrated=0
        _total_score=0
        _max_possible=0
        
        # Helper: relative time
        _age() {
            local ts="$1"
            local now
            now="$(date +%s)"
            local diff=$(( now - ts ))
            if [[ $diff -lt 3600 ]]; then
                echo "$((diff / 60))m ago"
            elif [[ $diff -lt 86400 ]]; then
                echo "$((diff / 3600))h ago"
            else
                echo "$((diff / 86400))d ago"
            fi
        }
        
        # Audit each repo
        for _repo in "${_repos[@]}"; do
            _rel="${_repo#"$_ROOT"/}"
            [[ "$_repo" == "$_ROOT" ]] && _rel="(root)"
        
            echo ""
            ci_info "=== $_rel ==="
        
            # 1. Identity
            _branch="$(_capture_or_default "detached" git -C "$_repo" rev-parse --abbrev-ref HEAD)"
            _last_hash="$(_capture_or_default "none" git -C "$_repo" log -1 --format=%h)"
            _last_subj="$(_capture_or_default "" git -C "$_repo" log -1 --format=%s)"
            _last_ts="$(_capture_or_default "0" git -C "$_repo" log -1 --format=%at)"
            _last_age="$(_age "$_last_ts")"
            echo "Branch: $_branch | Last: $_last_hash ${_last_subj:0:60} ($_last_age)"
        
            # 2. Working tree
            _unstaged="$(git -C "$_repo" diff --name-only | wc -l | tr -d ' ')"
            _staged="$(git -C "$_repo" diff --cached --name-only | wc -l | tr -d ' ')"
            _untracked="$(git -C "$_repo" ls-files --others --exclude-standard | wc -l | tr -d ' ')"
            _stash="$(git -C "$_repo" stash list | wc -l | tr -d ' ')"
            if [[ $_unstaged -eq 0 && $_staged -eq 0 && $_untracked -eq 0 ]]; then
                echo "Tree:   clean"
            else
                echo "Tree:   dirty (unstaged:$_unstaged staged:$_staged untracked:$_untracked stash:$_stash)"
            fi
        
            # 3. Remote sync
            _rc_remotes=0
            _remotes="$(git -C "$_repo" remote)" || _rc_remotes=$?
            if [[ -z "$_remotes" ]]; then
                echo "Remotes: none"
            else
                echo "Remotes:"
                while IFS= read -r _remote; do
                    _url="$(_capture_or_default "?" git -C "$_repo" remote get-url "$_remote")"
                    _tracking="$(_capture_or_default "" git -C "$_repo" rev-parse --abbrev-ref "$_branch@{upstream}")"
                    if [[ -z "$_tracking" || "$_tracking" == *"@{upstream}"* ]]; then
                        printf "  %-8s (%s) : no tracking branch\n" "$_remote" "$_url"
                        continue
                    fi
                    _ahead="$(_capture_or_default "?" git -C "$_repo" rev-list --count "$_tracking..HEAD")"
                    _behind="$(_capture_or_default "?" git -C "$_repo" rev-list --count "HEAD..$_tracking")"
                    if [[ "$_ahead" == "0" && "$_behind" == "0" ]]; then
                        _sync="up-to-date"
                    elif [[ "$_ahead" != "0" && "$_behind" != "0" ]]; then
                        _sync="DIVERGED (ahead $_ahead, behind $_behind)"
                    elif [[ "$_ahead" != "0" ]]; then
                        _sync="ahead $_ahead"
                    else
                        _sync="behind $_behind"
                    fi
                    printf "  %-8s (%s) : %s\n" "$_remote" "$_url" "$_sync"
                done <<< "$_remotes"
            fi
        
            # 4. CI Integration
            _score=0
            _max=7
            _max_possible=$((_max_possible + _max))
            _checks=()
        
            # L0: Config
            if [[ -f "$_repo/.pre-commit-config.yaml" ]]; then
                _checks+=("[x] L0: .pre-commit-config.yaml")
                _score=$((_score + 1))
            else
                _checks+=("[ ] L0: .pre-commit-config.yaml (missing)")
            fi
        
            # L1: Native hooks
            if [[ -f "$_repo/.git/hooks/pre-commit" ]] && grep -q 'generate-hooks\|ci\.sh' "$_repo/.git/hooks/pre-commit"; then
                _checks+=("[x] L1: Native hooks installed")
                _score=$((_score + 1))
            elif [[ -f "$_repo/.git/hooks/pre-commit" ]]; then
                _checks+=("[ ] L1: Native hooks (pre-commit exists but not CI-generated)")
            else
                _checks+=("[ ] L1: Native hooks (not installed)")
            fi
        
            # L2: Makefile migrated
            if [[ -f "$_repo/Makefile" ]] && grep -q 'generate-hooks' "$_repo/Makefile"; then
                _checks+=("[x] L2: Makefile migrated")
                _score=$((_score + 1))
            elif [[ -f "$_repo/Makefile" ]] && grep -q 'pre-commit install' "$_repo/Makefile"; then
                _checks+=("[ ] L2: Makefile (still uses pre-commit install)")
            elif [[ -f "$_repo/Makefile" ]]; then
                _checks+=("[ ] L2: Makefile (no hooks target)")
            else
                _checks+=("[ ] L2: Makefile (no Makefile)")
            fi
        
            # L3: Commit msg enforced
            if [[ -f "$_repo/.pre-commit-config.yaml" ]] && grep -q 'check-commit-message\|ci_check_commit_message' "$_repo/.pre-commit-config.yaml"; then
                _checks+=("[x] L3: Commit message format enforced")
                _score=$((_score + 1))
            else
                _checks+=("[ ] L3: Commit message format (not configured)")
            fi
        
            # L4: History clean
            if [[ -n "$_blocked_combined" ]]; then
                _rc_blocked=0
                _violations="$(git -C "$_repo" log --format=%B HEAD | grep -ciE "$_blocked_combined")" || _rc_blocked=$?
                if [[ "$_violations" -eq 0 ]]; then
                    _checks+=("[x] L4: History clean")
                    _score=$((_score + 1))
                else
                    _checks+=("[ ] L4: History clean ($_violations blocked pattern(s) found)")
                fi
            else
                _checks+=("[ ] L4: History clean (no blocked patterns config)")
            fi
        
            # L5: Pre-push hooks
            if [[ -f "$_repo/.git/hooks/pre-push" ]] && grep -q 'generate-hooks\|ci\.sh' "$_repo/.git/hooks/pre-push"; then
                _checks+=("[x] L5: Pre-push hooks")
                _score=$((_score + 1))
            else
                _checks+=("[ ] L5: Pre-push hooks (not installed)")
            fi
        
            # L6: Test suite on push
            if [[ -f "$_repo/.pre-commit-config.yaml" ]] && grep -q 'run-tests\|ci-check-push\|verify-coverage' "$_repo/.pre-commit-config.yaml"; then
                _checks+=("[x] L6: Test suite on push")
                _score=$((_score + 1))
            else
                _checks+=("[ ] L6: Test suite on push (not configured)")
            fi
        
            echo ""
            echo "CI Integration: $_score/$_max"
            for _c in "${_checks[@]}"; do
                echo "  $_c"
            done
        
            _total_score=$((_total_score + _score))
            [[ $_score -eq $_max ]] && _fully_integrated=$((_fully_integrated + 1))
        done
        
        # Summary
        echo ""
        echo "==========================================="
        ci_info "Workspace: $_ROOT"
        echo "Repos: $_total_repos | Fully integrated: $_fully_integrated/$_total_repos | Score: $_total_score/$_max_possible"
        echo "==========================================="
        
        if [[ $_fully_integrated -lt $_total_repos ]]; then
            exit 1
        fi
        exit 0
        

        Share feedback

        You voted thumbs down

        walk-projects

        Emit one nested .git repo path per line, relative to the workspace root.

        Workspace

        walk-projects

        scripts/walk-projects

        walk-projects: emit one nested .git repo path per line, relative to the workspace root. Used by every workspace-level *-recursive Makefile target so the find-and-iterate logic exists in one place. Usage: bash scripts/walk-projects [WORKSPACE_ROOT] Output (one path per line, relative to workspace root): projects/my-project projects/other-project/packages/sub # nested repos handled ... The output excludes the workspace-root repo itself (the umbrella), which is iterated separately by callers when needed.

        walk-projects

        Output: Repo paths on stdout, one per line. Used by recursive Makefile targets.

        #!/usr/bin/env bash
        # walk-projects: emit one nested .git repo path per line, relative to the
        # workspace root.
        #
        # Used by every workspace-level *-recursive Makefile target so the
        # find-and-iterate logic exists in one place.
        #
        # Usage:
        #   bash scripts/walk-projects [WORKSPACE_ROOT]
        #
        # Output (one path per line, relative to workspace root):
        #   projects/my-project
        #   projects/other-project/packages/sub      # nested repos handled
        #   ...
        #
        # The output excludes the workspace-root repo itself (the umbrella), which
        # is iterated separately by callers when needed.
        
        set -euo pipefail
        
        _workspace_root="${1:-}"
        if [[ -z "$_workspace_root" ]]; then
            # Walk up from CWD looking for the three workspace markers
            _cur="$(pwd)"
            while [[ "$_cur" != "/" ]]; do
                if [[ (-d "$_cur/.boot-linux" || -d "$_cur/.boot-macos") \
                      && -d "$_cur/projects" ]]; then
                    _workspace_root="$_cur"
                    break
                fi
                _cur="$(dirname "$_cur")"
            done
        fi
        
        if [[ -z "$_workspace_root" || ! -d "$_workspace_root/projects" ]]; then
            echo "walk-projects: cannot locate workspace root" >&2
            exit 1
        fi
        
        # Find every .git directory under projects/, emit the parent path
        # relative to the workspace root. Includes nested repos at any depth.
        
        cd "$_workspace_root"
        find projects -type d -name .git | while IFS= read -r _gitdir; do
            _repo="$(dirname "$_gitdir")"
            # Skip staging dirs that merely carry a copied .git/config: the wiki
            # prod build (web/scripts/stage-umbrella-repo.mjs) materializes
            # projects/WORKSPACE-VM with only .git/config inside, which is not a
            # repository. A real repository always has .git/HEAD.
            [[ -f "$_gitdir/HEAD" ]] || continue
            echo "$_repo"
        done
        

        Share feedback

        You voted thumbs down

        code-stats

        Codebase statistics across the workspace via cloc (lines, files, per-repo and per-language breakdown).

        Workspace
        Make target
        code-stats

        code-stats

        scripts/code-stats

        code-stats: Codebase statistics across the workspace. Walks every nested .git repo under the workspace root and runs cloc to produce: total lines (code/comment/blank/files), per-repo breakdown, and per-language breakdown. Respects .gitignore by default. Usage: code-stats # workspace-wide (default) code-stats --repo PATH # single repo code-stats --root PATH # workspace rooted at PATH code-stats --by-language # only show language table code-stats --by-repo # only show repo table code-stats --all-files # ignore .gitignore (count vendored too) code-stats --top N # show top N rows in tables (default: 25) code-stats --json # emit machine-readable JSON code-stats --no-umbrella # skip WORKSPACE-VM (workspace-root repo) Exit codes: 0 ok 1 cloc not found / invalid args 2 no repos found

        code-stats [--repo PATH] [--root PATH] [--by-language] [--by-repo] [--all-files] [--top N] [--json] [--no-umbrella]
        --repo
        Restrict to a single repo PATH (default: workspace-wide)
        --root
        Workspace root PATH (default: auto-detected)
        --by-language
        Show only the per-language table
        --by-repo
        Show only the per-repo table
        --all-files
        Ignore .gitignore (count vendored files too)
        --top
        Show top N rows in tables (default: 25)
        --json
        Emit machine-readable JSON instead of tables
        --no-umbrella
        Skip the workspace-root repo itself

        Output: cloc report on stdout (total + per-repo + per-language). Exits 0 on success, 1 if cloc missing, 2 if no repos found.

        #!/usr/bin/env bash
        # code-stats: Codebase statistics across the workspace.
        #
        # Walks every nested .git repo under the workspace root and runs cloc to
        # produce: total lines (code/comment/blank/files), per-repo breakdown, and
        # per-language breakdown. Respects .gitignore by default.
        #
        # Usage:
        #   code-stats                      # workspace-wide (default)
        #   code-stats --repo PATH          # single repo
        #   code-stats --root PATH          # workspace rooted at PATH
        #   code-stats --by-language        # only show language table
        #   code-stats --by-repo            # only show repo table
        #   code-stats --all-files          # ignore .gitignore (count vendored too)
        #   code-stats --top N              # show top N rows in tables (default: 25)
        #   code-stats --json               # emit machine-readable JSON
        #   code-stats --no-umbrella        # skip WORKSPACE-VM (workspace-root repo)
        #
        # Exit codes:
        #   0  ok
        #   1  cloc not found / invalid args
        #   2  no repos found
        set -euo pipefail
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _SCRIPT_DIR="$(cd "$(dirname "$_SELF")" && pwd)"
        # shellcheck source=../lib/ci.sh
        _ci_lib="$_SCRIPT_DIR/../lib/ci.sh"
        if ! source "$_ci_lib"; then
            echo "ERROR: failed to source $_ci_lib" >&2
            exit 2
        fi
        
        # ---------------------------------------------------------------------------
        # cloc lives in CI's own boot dir: scripts/bootstrap-cloc is the single
        # owning installer. Missing binary is a hard error with the remediation.
        # ---------------------------------------------------------------------------
        CLOC="${CI_PROJECT_ROOT}/$(ci_boot_name)/bin/cloc"
        if [[ ! -x "$CLOC" ]]; then
            ci_fail "cloc not found at $CLOC. Install via: bash scripts/bootstrap-cloc  (or: make install-cloc)"
            exit 1
        fi
        
        # uv by absolute boot path: the shell guard resets PATH in recipe shells,
        # so a bare `uv` is never resolvable here (same contract as Makefile UV).
        UV_BIN="${CI_PROJECT_ROOT}/$(ci_boot_name)/bin/uv"
        if [[ ! -x "$UV_BIN" ]]; then
            ci_fail "uv not found at $UV_BIN. Install via: make install-uv"
            exit 1
        fi
        
        # ---------------------------------------------------------------------------
        # Arg parsing
        # ---------------------------------------------------------------------------
        _mode="all"          # all | by-language | by-repo
        _root="$CI_WORKSPACE_ROOT"
        _single_repo=""
        _respect_gitignore=1
        _top_n=25
        _json=0
        _skip_umbrella=0
        
        while [[ $# -gt 0 ]]; do
            case "$1" in
                --repo)         _single_repo="$2"; shift 2 ;;
                --root)         _root="$2"; shift 2 ;;
                --by-language)  _mode="by-language"; shift ;;
                --by-repo)      _mode="by-repo"; shift ;;
                --all-files)    _respect_gitignore=0; shift ;;
                --top)          _top_n="$2"; shift 2 ;;
                --json)         _json=1; shift ;;
                --no-umbrella)  _skip_umbrella=1; shift ;;
                -h|--help)      sed -n '2,20p' "$0" | sed 's/^# \?//'; exit 0 ;;
                *)              ci_fail "unknown arg: $1"; exit 1 ;;
            esac
        done
        
        _root="$(cd "$_root" && pwd)"
        _tmpdir="$(mktemp -d)"
        trap 'rm -rf "$_tmpdir"' EXIT
        
        # Skip patterns for nested repo discovery (mirrors audit-workspace).
        _SKIP_DIRS="tmp|node_modules|\.venv|__pycache__|research|python-ta-reference|\.boot-linux|\.boot-macos|dist|build|target|\.cache|\.local"
        
        # ---------------------------------------------------------------------------
        # Repo discovery
        # ---------------------------------------------------------------------------
        _repos=()
        if [[ -n "$_single_repo" ]]; then
            _single_repo="$(cd "$_single_repo" && pwd)"
            _repos+=("$_single_repo")
        else
            if [[ "$_skip_umbrella" -eq 0 && -d "$_root/.git" ]]; then
                _repos+=("$_root")
            fi
            _gitdirs=()
            ci_capture_pipe _gitdirs 'find "$1" -type d ! -readable -prune -o -name ".git" -type d -print | sort' "$_root"
            for _gitdir in "${_gitdirs[@]}"; do
                _repo="$(dirname "$_gitdir")"
                [[ "$_repo" == "$_root" ]] && continue
                # Prod wiki stages README/Makefile under projects/WORKSPACE-VM; not a real repo.
                [[ "$_repo" == "$_root/projects/WORKSPACE-VM" ]] && continue
                echo "$_repo" | grep -qE "$_SKIP_DIRS" && continue
                _repos+=("$_repo")
            done
        fi
        
        if [[ ${#_repos[@]} -eq 0 ]]; then
            ci_warn "No git repos found under $_root"
            exit 2
        fi
        
        # ---------------------------------------------------------------------------
        # Run cloc per repo, collect results
        # ---------------------------------------------------------------------------
        # Per-repo aggregate file: tab-separated columns
        #   rel_path  files  blank  comment  code
        _per_repo="$_tmpdir/per_repo.tsv"
        # Per-(repo, language) detail file: tab-separated columns
        #   rel_path  language  files  blank  comment  code
        _per_repo_lang="$_tmpdir/per_repo_lang.tsv"
        
        # Track failures to distinguish "0 lines" from "skipped".
        _failed_repos=()
        
        if [[ $_json -eq 1 ]]; then
            printf '[code-stats] scanning %s repo(s) under %s...\n' \
                "${#_repos[@]}" "${_root#$HOME/~}" >&2
        else
            ci_info "Scanning ${#_repos[@]} repo(s) under ${_root#$HOME/~}..."
        fi
        
        for _repo in "${_repos[@]}"; do
            _is_umbrella=0
            if [[ "$_repo" == "$_root" ]]; then
                _is_umbrella=1
                _rel="WORKSPACE-VM"
            else
                _rel="${_repo#"$_root"/}"
                [[ "$_rel" == projects/* ]] && _rel="${_rel#projects/}"
            fi
        
            if [[ $_json -eq 1 ]]; then
                printf '[code-stats] cloc: %s (running; large repos may take several minutes)...\n' \
                    "$_rel" >&2
            fi
        
            # No --quiet: cloc progress goes to stderr (visible during long repos).
            _cloc_args=(--json --not-match-f='package-lock\.json')
            # Always use --exclude-dir instead of --vcs=git because the workspace
            # guard blocks ``git -c safe.directory=* ls-files`` (the command cloc
            # invokes internally under --vcs=git).  The expanded exclude list covers
            # the same heavy/vendored directories that .gitignore would filter.
            if [[ $_respect_gitignore -eq 1 ]]; then
                _cloc_args+=(
                    --exclude-dir=node_modules,.venv,__pycache__,target,dist,build,.cache,.local,.boot-linux,.boot-macos,.git,.next,.turbo,coverage,res
                )
            else
                _cloc_args+=(
                    --exclude-dir=node_modules,.venv,__pycache__,target,dist,build,.cache,.local,.boot-linux,.boot-macos,.git,.next,.turbo,coverage
                )
            fi
        
            _out="$_tmpdir/$(echo "$_rel" | tr '/' '_').json"
            _co_rc=0
            _co_out="$(mktemp)"; _co_err="$(mktemp)"
            if [[ $_is_umbrella -eq 1 ]]; then
                # Umbrella tracks only root-level files; nested projects/ repos are separate .git trees.
                _filelist="$_tmpdir/umbrella_files.txt"
                git -C "$_repo" ls-files >"$_filelist" 2>"$_co_err" || _co_rc=$?
                if [[ $_co_rc -eq 0 && -s "$_filelist" ]]; then
                    ( cd "$_repo" && "$CLOC" "${_cloc_args[@]}" --list-file="$_filelist" --report-file="$_out" . ) \
                        >"$_co_out" 2>"$_co_err" || _co_rc=$?
                elif [[ $_co_rc -eq 0 ]]; then
                    _co_rc=1
                    printf 'no tracked files\n' >"$_co_err"
                fi
            else
                ( cd "$_repo" && "$CLOC" "${_cloc_args[@]}" --report-file="$_out" . ) \
                    >"$_co_out" 2>"$_co_err" || _co_rc=$?
            fi
            if [[ $_co_rc -ne 0 ]]; then
                if [[ -s "$_co_err" ]]; then
                    printf '[code-stats] cloc failed on %s (status=%d): %s\n' \
                        "$_rel" "$_co_rc" "$(head -1 "$_co_err")" >&2
                else
                    printf '[code-stats] cloc failed on %s (status=%d, no stderr)\n' \
                        "$_rel" "$_co_rc" >&2
                fi
                rm -f "$_co_out" "$_co_err"
                _failed_repos+=("$_rel")
                continue
            fi
            rm -f "$_co_out" "$_co_err"
            [[ ! -s "$_out" ]] && continue
        
            # Parse JSON output. cloc's JSON shape:
            # { "header": {...}, "<Lang>": {nFiles, blank, comment, code}, ..., "SUM": {...} }
            # Use a small Python helper for robustness (jq isn't always present).
            _py_rc=0
            "$UV_BIN" run python - "$_out" "$_rel" "$_per_repo" "$_per_repo_lang" <<'PY' || _py_rc=$?
        import json, sys, os
        src, rel, per_repo, per_lang = sys.argv[1:]
        with open(src) as f:
            data = json.load(f)
        total = data.pop("SUM", None)
        data.pop("header", None)
        if total:
            with open(per_repo, "a") as fh:
                fh.write(f"{rel}\t{total['nFiles']}\t{total['blank']}\t{total['comment']}\t{total['code']}\n")
        with open(per_lang, "a") as fh:
            for lang, vals in data.items():
                if not isinstance(vals, dict) or "code" not in vals:
                    continue
                fh.write(f"{rel}\t{lang}\t{vals['nFiles']}\t{vals['blank']}\t{vals['comment']}\t{vals['code']}\n")
        PY
        done
        
        if [[ ${#_failed_repos[@]} -gt 0 && $_json -eq 0 ]]; then
            ci_warn "cloc failed on ${#_failed_repos[@]} repo(s): ${_failed_repos[*]}"
        fi
        
        # ---------------------------------------------------------------------------
        # Render
        # ---------------------------------------------------------------------------
        # Use Python for table formatting: awk's number formatting + sort across
        # multiple keys gets ugly fast and we already depend on Python above.
        "$UV_BIN" run python - "$_per_repo" "$_per_repo_lang" "$_mode" "$_top_n" "$_json" "$_root" <<'PY'
        import sys, json, os
        per_repo_path, per_lang_path, mode, top_n, as_json, root = sys.argv[1:]
        top_n = int(top_n)
        as_json = as_json == "1"
        
        def read_tsv(path, cols):
            rows = []
            if not os.path.exists(path):
                return rows
            with open(path) as f:
                for line in f:
                    line = line.rstrip("\n")
                    if not line:
                        continue
                    parts = line.split("\t")
                    if len(parts) != len(cols):
                        continue
                    row = {}
                    for c, v in zip(cols, parts):
                        row[c] = int(v) if c in {"files","blank","comment","code"} else v
                    rows.append(row)
            return rows
        
        repos = read_tsv(per_repo_path, ["repo","files","blank","comment","code"])
        langs_raw = read_tsv(per_lang_path, ["repo","language","files","blank","comment","code"])
        
        # Aggregate languages across all repos.
        agg = {}
        for r in langs_raw:
            a = agg.setdefault(r["language"], {"files":0,"blank":0,"comment":0,"code":0,"repos":set()})
            a["files"] += r["files"]; a["blank"] += r["blank"]
            a["comment"] += r["comment"]; a["code"] += r["code"]
            a["repos"].add(r["repo"])
        
        totals = {
            "repos": len(repos),
            "files": sum(r["files"] for r in repos),
            "blank": sum(r["blank"] for r in repos),
            "comment": sum(r["comment"] for r in repos),
            "code": sum(r["code"] for r in repos),
        }
        totals["lines"] = totals["blank"] + totals["comment"] + totals["code"]
        
        if as_json:
            # Per-repo language breakdown for wiki card badges.
            repo_langs = []
            for r in langs_raw:
                repo_langs.append({
                    "repo": r["repo"],
                    "language": r["language"],
                    "files": r["files"],
                    "blank": r["blank"],
                    "comment": r["comment"],
                    "code": r["code"],
                })
            out = {
                "root": root,
                "totals": totals,
                "repos": sorted(repos, key=lambda x: -x["code"]),
                "languages": sorted(
                    [{"language":k, **{kk:vv for kk,vv in v.items() if kk!="repos"},
                      "repos": len(v["repos"])} for k,v in agg.items()],
                    key=lambda x: -x["code"],
                ),
                "repo_languages": repo_langs,
            }
            print(json.dumps(out, indent=2))
            sys.exit(0)
        
        def fmt(n): return f"{n:,}"
        
        BOLD = "\033[1m"; CYAN = "\033[0;36m"; GREEN = "\033[0;32m"
        DIM = "\033[2m"; NC = "\033[0m"
        if not sys.stdout.isatty():
            BOLD = CYAN = GREEN = DIM = NC = ""
        
        def hr(ch="="): print(ch * 78)
        
        # Summary
        hr("=")
        print(f"{BOLD}CODE STATISTICS{NC}  root: {root}")
        hr("=")
        print(f"  Repositories scanned : {fmt(totals['repos'])}")
        print(f"  Files                : {fmt(totals['files'])}")
        print(f"  Code lines           : {GREEN}{fmt(totals['code'])}{NC}")
        print(f"  Comment lines        : {fmt(totals['comment'])}")
        print(f"  Blank lines          : {fmt(totals['blank'])}")
        print(f"  Total lines          : {BOLD}{fmt(totals['lines'])}{NC}")
        print()
        
        def print_repo_table():
            if not repos: return
            print(f"{BOLD}Per-repository (top {top_n} by code lines){NC}")
            rows = sorted(repos, key=lambda x: -x["code"])[:top_n]
            name_w = max(len(r["repo"]) for r in rows)
            name_w = min(max(name_w, 24), 60)
            print(f"  {'REPO':<{name_w}}  {'FILES':>7}  {'CODE':>12}  {'COMMENT':>10}  {'BLANK':>10}")
            print(f"  {'-'*name_w}  {'-'*7}  {'-'*12}  {'-'*10}  {'-'*10}")
            for r in rows:
                nm = r["repo"]
                if len(nm) > name_w: nm = "..." + nm[-(name_w-3):]
                print(f"  {nm:<{name_w}}  {fmt(r['files']):>7}  {fmt(r['code']):>12}  {fmt(r['comment']):>10}  {fmt(r['blank']):>10}")
            if len(repos) > top_n:
                print(f"  {DIM}... {len(repos)-top_n} more repo(s) omitted (use --top to show more){NC}")
            print()
        
        def print_lang_table():
            if not agg: return
            print(f"{BOLD}Per-language (top {top_n} by code lines){NC}")
            rows = sorted(agg.items(), key=lambda kv: -kv[1]["code"])[:top_n]
            name_w = max(len(k) for k,_ in rows)
            name_w = max(name_w, 16)
            print(f"  {'LANGUAGE':<{name_w}}  {'REPOS':>5}  {'FILES':>7}  {'CODE':>12}  {'COMMENT':>10}  {'BLANK':>10}")
            print(f"  {'-'*name_w}  {'-'*5}  {'-'*7}  {'-'*12}  {'-'*10}  {'-'*10}")
            for lang, v in rows:
                print(f"  {lang:<{name_w}}  {len(v['repos']):>5}  {fmt(v['files']):>7}  {fmt(v['code']):>12}  {fmt(v['comment']):>10}  {fmt(v['blank']):>10}")
            if len(agg) > top_n:
                print(f"  {DIM}... {len(agg)-top_n} more language(s) omitted{NC}")
            print()
        
        if mode in ("all","by-repo"):
            print_repo_table()
        if mode in ("all","by-language"):
            print_lang_table()
        PY
        

        Share feedback

        You voted thumbs down

        compliance-report

        Run a deep compliance audit of a project (or recursively across the workspace).

        Compliance
        Make target
        compliance

        compliance-report

        scripts/compliance-report

        compliance-report: Run deep compliance audit. Usage: compliance-report [PROJECT_DIR] Audit a single project compliance-report --recursive [ROOT] Discover all .git roots under ROOT and audit each ROOT: the workspace root (auto-detected) when unset.

        compliance-report [PROJECT_DIR]              Audit a single project
        compliance-report --recursive [ROOT]         Discover all .git roots under ROOT and audit each
        
        PROJECT_DIR
        Project to audit (default: current directory)
        --recursive
        Audit every nested .git repo under ROOT

        Output: Compliance score + violations on stdout. Exits non-zero on violations.

        #!/usr/bin/env bash
        # compliance-report: Run deep compliance audit.
        #
        # Usage:
        #   compliance-report [PROJECT_DIR]     Audit a single project
        #   compliance-report --recursive [ROOT] Discover all .git roots under ROOT and audit each
        #
        # ROOT: the workspace root (auto-detected) when unset.
        set -euo pipefail
        
        _SELF="${BASH_SOURCE[0]:-$0}"
        case "$_SELF" in /proc/self/fd/*) _SELF="${SHG_SCRIPT_PATH:-$_SELF}" ;; esac
        _SCRIPT_DIR="$(cd "$(dirname "$_SELF")" && pwd)"
        # shellcheck source=../lib/checks.sh
        if ! source "$_SCRIPT_DIR/../lib/checks.sh"; then
            echo "ERROR: failed to source $_SCRIPT_DIR/../lib/checks.sh" >&2
            exit 2
        fi
        
        # Skip patterns for recursive discovery (mirrors audit-workspace)
        _SKIP_DIRS="tmp|node_modules|\.venv|__pycache__|research|python-ta-reference|\.boot-linux|\.boot-macos|dist|build|target|\.cache|\.local"
        
        if [[ "${1:-}" == "--recursive" ]]; then
            shift
            _root="${1:-$CI_WORKSPACE_ROOT}"
            _root="$(cd "$_root" && pwd)"
        
            # Discover all .git roots
            _repos=()
            _gitdirs=()
            ci_capture_pipe _gitdirs 'find "$1" -name ".git" -type d | sort' "$_root"
            for _gitdir in "${_gitdirs[@]}"; do
                _repo="$(dirname "$_gitdir")"
                echo "$_repo" | grep -qE "$_SKIP_DIRS" && continue
                _repos+=("$_repo")
            done
        
            if [[ ${#_repos[@]} -eq 0 ]]; then
                ci_warn "No git repos found under $_root"
                exit 0
            fi
        
            _total_repos=${#_repos[@]}
            _total_passed=0
            _total_checks=0
            _total_violations=0
            _full_compliance=0
            _results=()
        
            for _repo in "${_repos[@]}"; do
                _rel="${_repo#"$_root"/}"
                [[ "$_repo" == "$_root" ]] && _rel="(root)"
        
                # Run compliance, capture output and exit code
                local _rc=0
                _output="$(ci_compliance_score "$_repo" 2>&1)" || _rc=$?
                echo "$_output"
        
                # Parse score from output: "COMPLIANCE: XX% (P/T)"
                if [[ "$_output" =~ COMPLIANCE:\ ([0-9]+)%\ \(([0-9]+)/([0-9]+)\) ]]; then
                    _pct="${BASH_REMATCH[1]}"
                    _p="${BASH_REMATCH[2]}"
                    _t="${BASH_REMATCH[3]}"
                    _v=$((_t - _p))
                    _total_passed=$((_total_passed + _p))
                    _total_checks=$((_total_checks + _t))
                    _total_violations=$((_total_violations + _v))
                    [[ $_v -eq 0 ]] && _full_compliance=$((_full_compliance + 1))
                    _results+=("$(printf '%3d%%  %-40s (%d/%d)' "$_pct" "$_rel" "$_p" "$_t")")
                fi
            done
        
            # Summary
            _agg_pct=0
            [[ $_total_checks -gt 0 ]] && _agg_pct=$(( (_total_passed * 100) / _total_checks ))
        
            _tier="Tier F"
            [[ $_agg_pct -ge 40 ]] && _tier="Tier D"
            [[ $_agg_pct -ge 60 ]] && _tier="Tier C"
            [[ $_agg_pct -ge 80 ]] && _tier="Tier B"
            [[ $_agg_pct -eq 100 ]] && _tier="Tier A"
        
            echo ""
            echo ""
            ci_info "=============================================="
            ci_info "  WORKSPACE COMPLIANCE SUMMARY"
            ci_info "=============================================="
            echo ""
            for _r in "${_results[@]}"; do
                echo "  $_r"
            done
            echo ""
            echo "  -------------------------------------------"
            printf "  Repos: %d | Full compliance: %d/%d\n" "$_total_repos" "$_full_compliance" "$_total_repos"
            printf "  Checks: %d/%d | Violations: %d\n" "$_total_passed" "$_total_checks" "$_total_violations"
            echo ""
        
            if [[ $_total_violations -eq 0 ]]; then
                ci_pass "WORKSPACE: ${_agg_pct}% | $_tier"
            else
                ci_fail "WORKSPACE: ${_agg_pct}% | $_tier | $_total_violations total violation(s)"
            fi
            echo "=============================================="
        
            [[ $_total_violations -eq 0 ]] && exit 0 || exit 1
        else
            ci_compliance_score "${1:-.}"
        fi
        

        Share feedback

        You voted thumbs down

        check-boot-venv-layout

        Non-blocking audit of boot_layout.yaml + moon.yml + .pre-commit-config.yaml --project refs.

        Compliance

        check-boot-venv-layout

        ci/check_boot_venv_layout.py

        Non-blocking audit of the platform-aware boot-layout contract.

        uv run python -m ci.check_boot_venv_layout [PROJECT_DIR]
        PROJECT_DIR
        Project to audit (default: current directory)

        Output: Score + findings on stdout. Always exits 0 (non-blocking, per FR-BL-7.7).

        #!/usr/bin/env python3
        """Non-blocking audit of the platform-aware boot-layout contract.
        
        Validates that moon.yml::project.inherited_boot_dirs entries resolve to
        existing project roots with accessible boot directories, and that
        .pre-commit-config.yaml --project refs resolve to valid venvs.
        Always exits 0 as an advisory check, with infrastructure errors
        returning 2.
        
        Checks performed:
        1. moon.yml exists (INFO + early-exit if absent).
        2. Parse + validate moon.yml::project.inherited_boot_dirs.
        3. Each inherited_boot_dirs entry resolves to a project root (OK/INFO/WARN).
        4. Existing inherited boot dirs checked for containment, ownership, and mode.
        5. moon.yml::dependsOn contains the moon project id for each
           inherited_boot_dirs entry (WARN).
        6. .pre-commit-config.yaml entry refs resolve to pyproject.toml + venv.
        7. Print summary line with ok/warn/info counts. Exit 0.
        """
        
        from __future__ import annotations
        
        import argparse
        import sys
        from pathlib import Path
        
        import yaml
        from pydantic import ValidationError
        
        from ci._boot_layout_helpers import (
            EXIT_OK,
            MoonYml,
        )
        from ci._boot_layout_helpers import (
            boot_composition_issue as _boot_composition_issue,
        )
        from ci._boot_layout_helpers import (
            derive_moon_id_from_inherited as _derive_moon_id_from_inherited,
        )
        from ci._boot_layout_helpers import (
            emit as _emit,
        )
        from ci._boot_layout_helpers import (
            emit_summary as _emit_summary,
        )
        from ci._boot_layout_helpers import (
            load_yaml as _load_yaml,
        )
        from ci._boot_layout_helpers import (
            resolve_rel as _resolve_rel,
        )
        from ci._boot_layout_helpers import (
            scan_precommit_project_refs as _scan_precommit_project_refs,
        )
        from ci._boot_layout_helpers import (
            scan_precommit_venv_python_refs as _scan_precommit_venv_python_refs,
        )
        
        # ---------------------------------------------------------------------------
        # Check functions
        # ---------------------------------------------------------------------------
        
        
        def _check_moon_exists(
            project_dir: Path,
        ) -> tuple[Path | None, MoonYml | None, list[tuple[str, str]]]:
            """Check 1+2: moon.yml exists and parses validly."""
            moon_path = project_dir / "moon.yml"
            if not moon_path.is_file():
                return (
                    None,
                    None,
                    [("INFO", "moon.yml not found: repo has no boot-layout declaration")],
                )
            try:
                raw = _load_yaml(moon_path)
            except yaml.YAMLError as e:
                return None, None, [("WARN", f"moon.yml malformed YAML: {e}")]
            if raw is None or not isinstance(raw, dict):
                return None, None, [("WARN", "moon.yml is empty or not a mapping")]
            try:
                moon = MoonYml.model_validate(raw)
            except ValidationError as e:
                return None, None, [("WARN", f"moon.yml schema violation: {e}")]
            return moon_path, moon, []
        
        
        def _check_inherited_boot_dirs(
            moon: MoonYml, project_dir: Path
        ) -> list[tuple[str, str]]:
            """Checks 3+4: inherited_boot_dirs resolution + world-writable."""
            findings: list[tuple[str, str]] = []
            proj = moon.project
            if proj is None:
                return [("INFO", "moon.yml has no project: block")]
            entries = proj.inherited_boot_dirs
            if not entries:
                return [
                    ("INFO", "inherited_boot_dirs is empty: repo has no inherited boot dirs")
                ]
            for entry in entries:
                e = entry.strip().rstrip("/")
                if not e:
                    findings.append(("WARN", "inherited_boot_dirs contains an empty entry"))
                    continue
                resolved_project = _resolve_rel(project_dir, e)
                if not resolved_project.exists():
                    findings.append(
                        (
                            "INFO",
                            f"inherited_boot_dirs entry {entry!r} does not exist"
                            " on disk (soft-optional)",
                        )
                    )
                    continue
                if not resolved_project.is_dir():
                    findings.append(
                        (
                            "WARN",
                            f"inherited_boot_dirs entry {entry!r} exists as a"
                            " file (not a directory)",
                        )
                    )
                    continue
                boot_bin = resolved_project / ".boot-linux" / "bin"
                # Accept both .boot-linux and .boot-macos as valid boot dir names
                if not boot_bin.is_dir():
                    boot_bin = resolved_project / ".boot-macos" / "bin"
                if not boot_bin.is_dir():
                    findings.append(
                        (
                            "INFO",
                            f"inherited_boot_dirs entry {entry!r}:"
                            " no .boot-*/bin at project root",
                        )
                    )
                    continue
                composition_issue = _boot_composition_issue(resolved_project, boot_bin)
                if composition_issue is not None:
                    findings.append(
                        (
                            "WARN",
                            f"inherited_boot_dirs entry {entry!r}: {composition_issue}",
                        )
                    )
                    continue
                findings.append(
                    ("OK", f"inherited_boot_dirs entry {entry!r} resolves to {boot_bin}")
                )
            return findings
        
        
        def _check_dependson_alignment(
            moon: MoonYml | None,
        ) -> list[tuple[str, str]]:
            """Check 5: dependsOn has the moon id from each inherited_boot_dirs entry."""
            findings: list[tuple[str, str]] = []
            if moon is None:
                return findings
            proj = moon.project
            if proj is None:
                return findings
            depends = moon.dependsOn
            for entry in proj.inherited_boot_dirs:
                moon_id = _derive_moon_id_from_inherited(entry)
                if moon_id is None:
                    continue
                if moon_id in depends:
                    findings.append(
                        (
                            "OK",
                            f"inherited_boot_dirs entry {entry!r}: dependsOn"
                            f" includes {moon_id!r}",
                        )
                    )
                else:
                    findings.append(
                        (
                            "WARN",
                            f"inherited_boot_dirs entry {entry!r}: dependsOn"
                            f" MISSING {moon_id!r} (add {moon_id!r} to dependsOn"
                            " or remove the entry; per §8.2)",
                        )
                    )
            return findings
        
        
        def _check_precommit_venv_python_refs(project_dir: Path) -> list[tuple[str, str]]:
            """Check 6b: warn on deprecated .venv/bin/python -m ci.* hook entries."""
            findings: list[tuple[str, str]] = []
            pcc_path = project_dir / ".pre-commit-config.yaml"
            if not pcc_path.is_file():
                return findings
            findings.extend(
                (
                    "WARN",
                    f".pre-commit-config.yaml line {line_no}:"
                    " use uv run python or uv run --project <path>"
                    " --no-sync python -m ci.<check> (not .venv/bin/python)",
                )
                for line_no in _scan_precommit_venv_python_refs(pcc_path)
            )
            return findings
        
        
        def _check_precommit_project_refs(project_dir: Path) -> list[tuple[str, str]]:
            """Check 6: .pre-commit-config.yaml --project refs resolve."""
            findings: list[tuple[str, str]] = []
            pcc_path = project_dir / ".pre-commit-config.yaml"
            if not pcc_path.is_file():
                return findings
            refs = _scan_precommit_project_refs(pcc_path)
            seen: set[tuple[str, bool, bool]] = set()
            for line_no, ref in refs:
                target = _resolve_rel(project_dir, ref)
                ok_pyproject = (target / "pyproject.toml").is_file()
                ok_venv = (target / ".venv" / "bin" / "python").is_file()
                key = (str(target), ok_pyproject, ok_venv)
                if key in seen:
                    continue
                seen.add(key)
                if ok_pyproject and ok_venv:
                    findings.append(
                        (
                            "OK",
                            f".pre-commit-config.yaml --project {ref!r} →"
                            f" pyproject.toml + .venv/bin/python at {target}",
                        )
                    )
                elif not ok_pyproject:
                    findings.append(
                        (
                            "WARN",
                            f".pre-commit-config.yaml --project {ref!r}"
                            f" (line {line_no}) → {target} missing pyproject.toml",
                        )
                    )
                else:
                    findings.append(
                        (
                            "WARN",
                            f".pre-commit-config.yaml --project {ref!r}"
                            f" (line {line_no}) → {target} has pyproject.toml"
                            " but no .venv/bin/python (run `uv sync` there)",
                        )
                    )
            return findings
        
        
        # ---------------------------------------------------------------------------
        # Main
        # ---------------------------------------------------------------------------
        
        
        def main() -> int:
            parser = argparse.ArgumentParser(
                prog="check-boot-venv-layout",
                description=(
                    "Non-blocking audit of the boot-layout contract (SPEC-BOOT-LAYOUT)."
                ),
            )
            parser.add_argument(
                "project_dir",
                nargs="?",
                default=".",
                help="Project dir to audit (default: current dir).",
            )
            args = parser.parse_args()
            project_dir = Path(args.project_dir).resolve(strict=False)
        
            findings: list[tuple[str, str]] = []
        
            # Checks 1+2: moon.yml existence + parse
            moon_path, moon, found = _check_moon_exists(project_dir)
            findings.extend(found)
            if moon_path is None or moon is None:
                _emit_and_exit(findings)
                return EXIT_OK
        
            # Checks 3+4: inherited_boot_dirs resolution + world-writable
            findings.extend(_check_inherited_boot_dirs(moon, project_dir))
        
            # Check 5: dependsOn alignment
            findings.extend(_check_dependson_alignment(moon))
        
            # Check 6: .pre-commit-config.yaml --project refs
            findings.extend(_check_precommit_venv_python_refs(project_dir))
            findings.extend(_check_precommit_project_refs(project_dir))
        
            # Check 7: summary
            _emit_and_exit(findings)
            return EXIT_OK  # unreachable
        
        
        def _emit_and_exit(findings: list[tuple[str, str]]) -> None:
            """Print all findings + summary line, then exit 0."""
            n_ok = n_warn = n_info = 0
            for level, msg in findings:
                if level == "OK":
                    n_ok += 1
                elif level == "WARN":
                    n_warn += 1
                else:
                    n_info += 1
                _emit(level, msg)
            _emit_summary(n_ok, n_warn, n_info)
            sys.exit(EXIT_OK)
        
        
        if __name__ == "__main__":
            sys.exit(main())
        

        Share feedback

        You voted thumbs down

        The Digital and AI Workspace Guardrails Platform2026 ◆ Independent AI Labs